forked from PackeTsar/freeztp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ztp.py
4164 lines (4086 loc) · 177 KB
/
ztp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
##### FreeZTP Server #####
##### Written by John W Kerns #####
##### http://blog.packetsar.com #####
##### https://github.com/packetsar/freeztp #####
##### Inform FreeZTP version here #####
version = "v1.5.1"
##### Import native modules #####
import os
import re
import sys
import csv
import time
import json
import curses
import socket
import logging
import platform
import commands
import threading
class os_detect:
def __init__(self):
self._dist = self._dist_detect()
self._systemd = self._systemd_detect()
self._pkgmgr = self._pkgmgr_detect()
self._make_names()
def _systemd_detect(self):
checksystemd = commands.getstatusoutput("systemctl")
if len(checksystemd[1]) > 50 and "Operation not permitted" not in checksystemd[1]:
return True
else:
return False
def _pkgmgr_detect(self):
checkpkgmgr = {}
checknames = ["yum", "apt", "apt-get"]
for mgr in checknames:
checkpkgmgr.update({len(commands.getstatusoutput(mgr)[1]): mgr})
pkgmgr = checkpkgmgr[sorted(list(checkpkgmgr), key=int)[len(sorted(list(checkpkgmgr), key=int)) - 1]]
return pkgmgr
def _dist_detect(self):
distlist = platform.linux_distribution()
if "centos" in distlist[0].lower():
return "centos"
elif "red hat" in distlist[0].lower() and float(distlist[1] > 8):
return "rhel8"
elif "red hat" in distlist[0].lower():
return "rhel"
elif "ubuntu" in distlist[0].lower():
return "ubuntu"
elif "debian" in distlist[0].lower():
return "debian"
else:
print("Unsupported OS Type! Please create an issue at https://github.com/PackeTsar/freeztp/issues and include below information.")
print(platform.linux_distribution())
sys.exit()
def _make_names(self):
if self._dist == "centos":
self.DHCPSVC = "dhcpd"
self.DHCPPKG = "dhcp"
self.PIPPKG = "python2-pip"
self.PKGDIR = "/usr/lib/python2.7/site-packages/"
self.DHCPLEASES = "/var/lib/dhcpd/dhcpd.leases"
elif self._dist == "rhel8":
self.DHCPSVC = "dhcpd"
self.DHCPPKG = "dhcp-server"
self.PIPPKG = "python2-pip"
self.PKGDIR = "/usr/lib/python2.7/site-packages/"
self.DHCPLEASES = "/var/lib/dhcpd/dhcpd.leases"
elif self._dist == "rhel":
self.DHCPSVC = "dhcpd"
self.DHCPPKG = "dhcp"
self.PIPPKG = "python2-pip"
self.PKGDIR = "/usr/lib/python2.7/site-packages/"
self.DHCPLEASES = "/var/lib/dhcpd/dhcpd.leases"
elif self._dist == "ubuntu":
self.DHCPSVC = "isc-dhcp-server"
self.DHCPPKG = "isc-dhcp-server"
self.PIPPKG = "python-pip"
self.PKGDIR = "/usr/local/lib/python2.7/dist-packages/"
self.DHCPLEASES = "/var/lib/dhcp/dhcpd.leases"
elif self._dist == "debian":
self.DHCPSVC = "isc-dhcp-server"
self.DHCPPKG = "isc-dhcp-server"
self.PIPPKG = "python-pip"
self.PKGDIR = "/usr/local/lib/python2.7/dist-packages/"
self.DHCPLEASES = "/var/lib/dhcp/dhcpd.leases"
def service_control(self, cmd, service):
if self._systemd:
os.system("sudo systemctl %s %s" % (cmd, service))
else:
os.system("sudo service %s %s" % (service, cmd))
def install_pkg(self, pkg):
cmd = "sudo %s install -y %s" % (self._pkgmgr, pkg)
console("")
os.system("sudo %s install -y %s" % (self._pkgmgr, pkg))
def interceptor(afile, raddress, rport):
log("interceptor: Called. Checking the cache")
cached = cache.get(afile, raddress)
if cached:
return cached
else:
log("interceptor: Cache returned None. Running cfact.lookup procedure")
lookup = cfact.lookup(afile, raddress)
log("interceptor: cfact.lookup returned (%s)" % lookup)
if lookup:
log("interceptor: Returning ztp_dyn_file instantiated object")
zfile = ztp_dyn_file(afile, raddress, rport)
cache.store(afile, raddress, zfile)
return zfile
else:
log("interceptor: Returning None")
return None
##### Class to cache generated file objects to prevent multiple rapid #####
##### hits to the ZTP process: reducing logging #####
class file_cache:
def __init__(self):
self.timeout = config.running["file-cache-timeout"]
self._cache_list = []
self._cache = {}
self.mthread = threading.Thread(target=self._maintenance)
self.mthread.daemon = True
self.mthread.start()
def store(self, filename, ipaddr, fileobj):
if self.timeout == 0:
log("file_cache.store: Caching set to 0. Declining caching.")
else:
data = {time.time(): {"filename": filename, "ipaddr": ipaddr, "file": fileobj}}
log("file_cache.store: Storing %s" % str(data))
self._cache.update(data)
def get(self, filename, ipaddr):
currenttime = time.time()
for entry in self._cache:
if filename == self._cache[entry]["filename"] and ipaddr == self._cache[entry]["ipaddr"]:
log("file_cache.get: File (%s) requested by (%s) found in cache. Checking timeout." % (filename, ipaddr))
if currenttime - entry < self.timeout:
log("file_cache.get: Cached file is still within timeout period. Resetting to 0 and returning")
self._cache[entry]["file"].position = 0
return self._cache[entry]["file"]
else:
log("file_cache.get: Cached file is outside of timeout period. Deleting from cache. Returning None")
del self._cache[entry]
return None
log("file_cache.get: File (%s) requested by (%s) not in cache" % (filename, ipaddr))
return None
def _maintenance(self):
self.sthread = threading.Thread(target=self._maintain_cache)
self.sthread.daemon = True
self.sthread.start()
while True:
time.sleep(1)
if not self.sthread.is_alive():
self.sthread = threading.Thread(target=self._maintain_cache)
self.sthread.daemon = True
self.sthread.start()
def _maintain_cache(self):
while True:
time.sleep(1)
currenttime = time.time()
for entry in list(self._cache):
if currenttime - entry > self.timeout:
log("file_cache._maintain_cache: Timing out and deleting %s:%s" % (entry, self._cache[entry]))
del self._cache[entry]
##### Dynamic file object: instantiated by the tftpy server to generate #####
##### TFTP files #####
class ztp_dyn_file:
closed = False
position = 0
def __init__(self, afile, raddress, rport, data=None, track=True):
self.filename = afile
self.ipaddr = raddress
self.port = rport
self.track = track
if self.track:
tracking.files.append(self)
log("ztp_dyn_file: Instantiated as (%s)" % str(self))
if not data:
self.data = cfact.request(afile, raddress)
else:
self.data = data
self.__len__ = self.len
log("ztp_dyn_file: File size is %s bytes" % len(self.data))
def tell(self):
#log("ztp_dyn_file.tell: Called. Returning (%s)" % str(self.position))
return self.position
def len(self):
if len(self.data)-self.position < 1:
return 0
return len(self.data)-self.position
def read(self, size):
start = self.position
end = self.position + size
#if not self.closed:
# log("ztp_dyn_file.read: Called with size (%s)" % str(size))
result = str(self.data[start:end])
#if not self.closed:
# log("ztp_dyn_file.read: Returning position %s to %s" % (str(start), str(end)))
self.position = end
if self.track:
tracking.report({
"ipaddr": self.ipaddr,
"filename": self.filename,
"port": self.port,
"position": self.position,
"source": "ztp_dyn_file",
"file": self})
return result
def seek(self, arg1, arg2):
log("ztp_dyn_file.seek: Called with args (%s) and (%s)" % (str(arg1), str(arg1)))
def close(self):
if not self.closed:
log("ztp_dyn_file.close: Called. File closing.")
else:
log("ztp_dyn_file.close: Called again from cache.")
self.closed = True
##### Configuration factory: The main program which creates TFTP files #####
##### based on the ZTP configuration #####
class config_factory:
def __init__(self):
global j2
global meta
import jinja2 as j2
from jinja2 import meta
self.state = {}
self.snmprequests = {}
try:
self.basefilename = config.running["initialfilename"]
self.imagediscoveryfile = config.running["imagediscoveryfile"]
self.basesnmpcom = config.running["community"]
self.snmpoid = config.running["snmpoid"]
self.baseconfig = config.running["starttemplate"]["value"]
self.uniquesuffix = config.running["suffix"]
self.templates = config.running["templates"]
self.keyvalstore = config.running["keyvalstore"]
self.associations = config.running["associations"]
except:
console("cfact.__init__: Error pulling settings from config file")
def _check_supression(self, ipaddr):
log("cfact._check_supression: Called. Checking for image download supression for IP (%s)" % ipaddr)
timeout = config.running["image-supression"]
for session in tracking.status:
timestamp = session
filename = tracking.status[session]["filename"]
sesip = tracking.status[session]["ipaddr"]
if filename == config.running["imagediscoveryfile"]:
if sesip == ipaddr:
if time.time()-float(timestamp) < timeout:
log("cfact._check_supression: Previous session detected %s seconds ago (within %s seconds). Supressing upgrade." % (time.time()-float(timestamp), timeout))
return True
log("cfact._check_supression: Previous session not detected within %s seconds." % timeout)
return False
def lookup(self, filename, ipaddr):
log("cfact.lookup: Called. Checking filename (%s) and IP (%s)" % (filename, ipaddr))
tempid = filename.replace(self.uniquesuffix, "")
if (self.uniquesuffix in filename) and (filename != self.basefilename):
log("cfact.lookup: TempID is (%s)" % tempid)
log("cfact.lookup: Current SNMP Requests: %s" % list(self.snmprequests))
if filename == self.basefilename:
log("cfact.lookup: Requested filename matches the initialfilename. Returning True")
return True
elif filename == self.imagediscoveryfile:
log("cfact.lookup: Requested filename matches the imagediscoveryfile")
log("cfact.lookup: #############IOS UPGRADE ABOUT TO BEGIN!!!#############")
return True
elif self.uniquesuffix in filename and tempid in list(self.snmprequests): # If the filname contains the suffix and it has an entry in the snmp request list
log("cfact.lookup: Seeing the suffix in the filename and the TempID in the SNMPRequests")
if self.snmprequests[tempid].complete: # If the snmprequest has completed
log("cfact.lookup: The SNMP request is showing as completed")
for response in self.snmprequests[tempid].responses:
if self.id_configured(self.snmprequests[tempid].responses[response]): # If the snmp id response is a configured IDArray or keystore
log("cfact.lookup: The target ID is in the Keystore or in an IDArray")
return True
if self._default_lookup(): # If there is a default keystore configured
log("cfact.lookup: The target ID is NOT in the Keystore or in an IDArray, but a default is configured")
return True
elif self._default_lookup(): # If there is a default keystore configured
log("cfact.lookup: The target ID is NOT in the Keystore or in an IDArray, but a default is configured")
return True
if "ztp-" in tempid.lower():
log("cfact.lookup: Creating new SNMP request for %s: %s" % (str(tempid), str(ipaddr)))
self.create_snmp_request(tempid, ipaddr)
return False
def _default_lookup(self):
log("cfact._default_lookup: Checking if a default-keystore is configured and ready...")
if config.running["default-keystore"]: # If a default keystore ID is set
kid = config.running["default-keystore"]
log("cfact._default_lookup: A default keystore ID (%s) is configured" % kid)
if self.get_keystore_id({"default-keystore-test": kid}, silent=True):
return kid
else:
log("cfact._default_lookup: Keystore (%s) does not exist. Nothing to return" % kid)
else:
log("cfact._default_lookup: Default-keystore set to none. Returning none")
return False
def id_configured(self, serial):
if serial in list(config.running["keyvalstore"]):
return True
else:
arraykeys = []
for array in config.running["idarrays"]:
for iden in config.running["idarrays"][array]:
arraykeys.append(iden)
if serial in arraykeys:
return True
else:
if serial in list(external_keystores.data["keyvalstore"]):
return True
else:
arraykeys = []
for array in external_keystores.data["idarrays"]:
for iden in external_keystores.data["idarrays"][array]:
arraykeys.append(iden)
if serial in arraykeys:
return True
else:
return False
def request(self, filename, ipaddr, test=False):
log("cfact.request: Called with filename (%s) and IP (%s)" % (filename, ipaddr))
if filename == self.basefilename:
log("cfact.request: Filename (%s) matches the configured initialfilename" % self.basefilename)
tempid = self._generate_name()
log("cfact.request: Generated a TempID with cfact._generate_name: (%s)" % tempid)
if not test:
self.create_snmp_request(tempid, ipaddr)
tracking.provision({
"Temp ID": tempid,
"IP Address": ipaddr,
"Matched Keystore": None,
"Status": "Incomplete",
"Real IDs": None,
"MAC Address": None,
"Timestamp": time.time()
})
log("cfact.request: Generated a SNMP Request with TempID (%s) and IP (%s)" % (tempid, ipaddr))
result = self.merge_base_config(tempid)
log("cfact.request: Returning the below initial config to TFTPy:\n%s\n%s\n%s" % ("#"*25, result, "#"*25))
self.send_tracking_update(ipaddr, filename, len(result))
return result
elif filename == self.imagediscoveryfile:
log("cfact.request: Filename (%s) matches the configured imagediscoveryfile" % filename)
if self._check_supression(ipaddr):
result = "Image_Download_Supressed"
self.send_tracking_update(ipaddr, filename, len(result))
return result
else:
result = config.running["imagefile"]
log("cfact.request: Returning the value of the imagefile setting (%s)" % result)
self.send_tracking_update(ipaddr, filename, len(result))
return result
else:
log("cfact.request: Filename (%s) does NOT match the configured initialfilename" % filename)
tempid = filename.replace(self.uniquesuffix, "")
log("cfact.request: Stripped filename to TempID (%s)" % tempid)
if config.running["delay-keystore"]:
delay = float(config.running["delay-keystore"])
log("cfact.request: Delaying keystore loopup for (%s) milliseconds" % config.running["delay-keystore"])
time.sleep(delay/1000)
if self.uniquesuffix in filename and tempid in list(self.snmprequests):
log("cfact.request: Seeing the suffix in the filename and the TempID in the SNMP Requests")
if self.snmprequests[tempid].complete:
log("cfact.request: SNMP Request says it has completed")
identifiers = self.snmprequests[tempid].responses
log("cfact.request: SNMP request returned target ID (%s)" % identifiers)
if not test:
tracking.provision({
"Temp ID": tempid,
"IP Address": ipaddr,
"Matched Keystore": None,
"Status": "Processing",
"Real IDs": identifiers,
"MAC Address": None,
"Timestamp": time.time()
})
keystoretup = self.get_keystore_id(identifiers)
if keystoretup:
keystoreid, iden = keystoretup
else:
keystoreid = None
iden = None
log("cfact.request: Keystore ID Lookup returned (%s)" % keystoreid)
snmpinfo = dict(identifiers)
snmpinfo.update({"matched": iden})
if keystoreid:
result, kvals = self.merge_final_config(keystoreid, snmpinfo)
if config.running["logging"]["merged-config-to-mainlog"] == "enable":
log("cfact.request: Returning the below config to TFTPy:\n%s\n%s\n%s" % ("#"*25, result, "#"*25))
else:
log("cfact.request: Returning merged config to TFTPy")
self.log_merged_config_file(result, kvals, {
"keystore_id": keystoreid,
"ipaddr": ipaddr,
"epoch_timestamp": time.time(),
"local_timestamp": time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time())),
"local_year": time.strftime('%Y', time.localtime(time.time())),
"local_month": time.strftime('%m', time.localtime(time.time())),
"local_day": time.strftime('%d', time.localtime(time.time())),
"local_hour": time.strftime('%H', time.localtime(time.time())),
"local_minute": time.strftime('%M', time.localtime(time.time())),
"local_second": time.strftime('%S', time.localtime(time.time())),
"temp_id": tempid
})
self.send_tracking_update(ipaddr, filename, len(result))
if not test:
tracking.provision({
"Temp ID": tempid,
"IP Address": ipaddr,
"Matched Keystore": keystoreid,
"Status": "Complete",
"Real IDs": None,
"MAC Address": None,
"Timestamp": time.time()
})
return result
else:
log("cfact.request: SNMP request for (%s) returned an unknown ID, checking for default-keystore" % self.snmprequests[tempid].host)
default = self._default_lookup()
if default:
log("cfact.request: default-keystore is configured. Returning default")
result, kvals = self.merge_final_config(default, snmpinfo)
if config.running["logging"]["merged-config-to-mainlog"] == "enable":
log("cfact.request: Returning the below config to TFTPy:\n%s\n%s\n%s" % ("#"*25, result, "#"*25))
else:
log("cfact.request: Returning merged config to TFTPy")
self.log_merged_config_file(result, kvals, {
"keystore_id": default,
"ipaddr": ipaddr,
"epoch_timestamp": time.time(),
"local_timestamp": time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time())),
"local_year": time.strftime('%Y', time.localtime(time.time())),
"local_month": time.strftime('%m', time.localtime(time.time())),
"local_day": time.strftime('%d', time.localtime(time.time())),
"local_hour": time.strftime('%H', time.localtime(time.time())),
"local_minute": time.strftime('%M', time.localtime(time.time())),
"local_second": time.strftime('%S', time.localtime(time.time())),
"temp_id": tempid
})
self.send_tracking_update(ipaddr, filename, len(result))
if not test:
tracking.provision({
"Temp ID": tempid,
"IP Address": ipaddr,
"Matched Keystore": default,
"Status": "Complete",
"Real IDs": None,
"MAC Address": None,
"Timestamp": time.time()
})
return result
else:
log("cfact.request: SNMP request is not complete on host (%s), checking for default-keystore" % self.snmprequests[tempid].host)
default = self._default_lookup()
if default:
log("cfact.request: default-keystore is configured. Returning default")
result, kvals = self.merge_final_config(default)
if config.running["logging"]["merged-config-to-mainlog"] == "enable":
log("cfact.request: Returning the below config to TFTPy:\n%s\n%s\n%s" % ("#"*25, result, "#"*25))
else:
log("cfact.request: Returning merged config to TFTPy")
self.log_merged_config_file(result, kvals, {
"keystore_id": default,
"ipaddr": ipaddr,
"epoch_timestamp": time.time(),
"local_timestamp": time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time())),
"local_year": time.strftime('%Y', time.localtime(time.time())),
"local_month": time.strftime('%m', time.localtime(time.time())),
"local_day": time.strftime('%d', time.localtime(time.time())),
"local_hour": time.strftime('%H', time.localtime(time.time())),
"local_minute": time.strftime('%M', time.localtime(time.time())),
"local_second": time.strftime('%S', time.localtime(time.time())),
"temp_id": tempid
})
self.send_tracking_update(ipaddr, filename, len(result))
if not test:
tracking.provision({
"Temp ID": tempid,
"IP Address": ipaddr,
"Matched Keystore": default,
"Status": "Complete",
"Real IDs": None,
"MAC Address": None,
"Timestamp": time.time()
})
return result
log("cfact.request: Nothing else caught. Returning None")
return None
def log_merged_config_file(self, filedata, keystore_data, other_args):
if config.running["logging"]["merged-config-to-custom-file"] != "disable":
###########
newdict = dict(keystore_data)
newdict.update(other_args)
log("cfact.log_merged_config_file: Creating custom log file name from variables:\n{}".format(json.dumps(newdict, indent=4)))
env = j2.Environment(loader=j2.FileSystemLoader('/'))
template = env.from_string(config.running["logging"]["merged-config-to-custom-file"])
newfile = template.render(newdict)
log("cfact.log_merged_config_file: Final merge log file is ({})".format(newfile))
###########
dir, filename = os.path.split(newfile)
if not dir or not filename:
log("cfact.log_merged_config_file: ERROR: Directory or Filename not present (dir={}), (filename={})".format(dir, filename))
elif os.path.isfile(newfile):
log("cfact.log_merged_config_file: File ({}) already exists. Appending".format(newfile))
f = open(newfile, "a")
f.write("\n\n{}\n\n".format(filedata))
f.close()
elif not os.path.isdir(dir):
log("cfact.log_merged_config_file: Creating new directory ({})".format(dir))
os.makedirs(dir)
log("cfact.log_merged_config_file: Writing to file ({})".format(newfile))
f = open(newfile, "w")
f.write("\n\n{}\n\n".format(filedata))
f.close()
else:
log("cfact.log_merged_config_file: Directory ({}) already exists".format(dir))
log("cfact.log_merged_config_file: Writing to file ({})".format(newfile))
f = open(newfile, "w")
f.write("\n\n{}\n\n".format(filedata))
f.close()
def send_tracking_update(self, ipaddr, filename, filesize):
tracking.report({
"ipaddr": ipaddr,
"filename": filename,
"filesize": filesize,
"port": None,
"position": None,
"source": "config_factory"})
def create_snmp_request(self, tempid, ipaddr):
newquery = snmp_query(ipaddr, self.basesnmpcom, self.snmpoid)
self.snmprequests.update({tempid: newquery})
def _generate_name(self):
timeint = int(str(time.time()).replace(".", ""))
timehex = hex(timeint)
hname = timehex[2:12].upper()
return("ZTP-"+hname)
def merge_base_config(self, tempid):
env = j2.Environment(loader=j2.FileSystemLoader('/'))
template = env.from_string(self.baseconfig)
return template.render(autohostname=tempid, community=self.basesnmpcom)
def merge_final_config(self, keystoreid, snmpinfo=None):
if keystoreid in config.running["keyvalstore"]:
path = config.running
else:
path = external_keystores.data
templatedata = self.get_template(keystoreid)
env = j2.Environment(loader=j2.FileSystemLoader('/'))
template = env.from_string(templatedata)
vals = self.pull_keystore_values(path, keystoreid)
if snmpinfo:
vals.update({"snmpinfo": snmpinfo})
vals = self._global_keystore_merge(vals)
log("cfact.merge_final_config: Merging with values:\n{}".format(json.dumps(vals, indent=4)))
return (template.render(vals), vals)
def get_keystore_id(self, idens, silent=False):
for identifier in idens:
identifier = idens[identifier]
if not silent:
log("cfact.get_keystore_id: Checking Keystores and IDArrays for (%s)" % identifier)
log("cfact.get_keystore_id: Checking Keystore names for (%s)" % identifier)
if identifier in list(config.running["keyvalstore"]):
if not silent:
log("cfact.get_keystore_id: ID (%s) resolved directly to a keystore" % identifier)
return (identifier, identifier)
else:
if not silent:
log("cfact.get_keystore_id: ID (%s) not found in keystore names, checking local IDArrays" % identifier)
for arrayname in list(config.running["idarrays"]):
if identifier in config.running["idarrays"][arrayname]:
if not silent:
log("cfact.get_keystore_id: ID '%s' resolved to arrayname '%s'" % (identifier, arrayname))
if arrayname in list(config.running["keyvalstore"]):
log("cfact.get_keystore_id: Keystore with name '%s' has been found" % arrayname)
return (arrayname, identifier)
elif arrayname in list(external_keystores.data["keyvalstore"]):
log("cfact.get_keystore_id: Keystore with name '%s' has been found in an external-keystore" % arrayname)
return (arrayname, identifier)
else:
log("cfact.get_keystore_id: A keystore matching arrayname '%s' cannot be found. Discarding IDArray match" % arrayname)
if not silent:
log("cfact.get_keystore_id: ID (%s) not found in local IDArrays, checking external Keystore names" % identifier)
if identifier in list(external_keystores.data["keyvalstore"]):
if not silent:
log("cfact.get_keystore_id: ID (%s) resolved directly to an external-keystore" % identifier)
return (identifier, identifier)
if not silent:
log("cfact.get_keystore_id: ID (%s) not found in external Keystore names, checking external IDArrays" % identifier)
for arrayname in list(external_keystores.data["idarrays"]):
if identifier in external_keystores.data["idarrays"][arrayname]:
if not silent:
log("cfact.get_keystore_id: ID '%s' resolved to arrayname '%s' in an external-keystore" % (identifier, arrayname))
return (arrayname, identifier)
if not silent:
log("cfact.get_keystore_id: ID (%s) not found in external IDArrays. ID Lookup failed!" % identifier)
def get_template(self, identity):
log("cfact.get_template: Looking up association for identity (%s)" % identity)
response = False
for association in self.associations:
if identity == association:
templatename = self.associations[association]
log("cfact.get_template: Found associated template (%s)" % templatename)
if templatename in self.templates:
log("cfact.get_template: Template (%s) exists in local config. Returning" % templatename)
response = self.templates[templatename]["value"]
elif templatename in external_templates.templates:
log("cfact.get_template: Template (%s) exists as an external-template. Returning" % templatename)
response = external_templates.templates[templatename]
else:
log("cfact.get_template: Template (%s) does not exist. Checking for default-template" % templatename)
if not response:
for association in external_keystores.data["associations"]:
if identity == association:
templatename = external_keystores.data["associations"][association]
log("cfact.get_template: Found associated template (%s) in an external keystore" % templatename)
if templatename in self.templates:
log("cfact.get_template: Template (%s) exists in local config. Returning" % templatename)
response = self.templates[templatename]["value"]
elif templatename in external_templates.templates:
log("cfact.get_template: Template (%s) exists as an external-template. Returning" % templatename)
response = external_templates.templates[templatename]
else:
log("cfact.get_template: Template (%s) does not exist. Checking for default-template" % templatename)
if not response:
if config.running["default-template"]:
log("cfact.get_template: Default-template is pointing to (%s)" % config.running["default-template"])
templatename = config.running["default-template"]
if templatename in self.templates:
log("cfact.get_template: Template (%s) exists in local config. Returning" % templatename)
response = self.templates[templatename]["value"]
elif templatename in external_templates.templates:
log("cfact.get_template: Template (%s) exists as an external-template. Returning" % templatename)
response = external_templates.templates[templatename]
else:
log("cfact.get_template: Template (%s) does not exist. Checking for default-template" % templatename)
else:
log("cfact.get_template: Default-template is set to None")
return response
def merge_test(self, iden, template):
idtup = self.get_keystore_id({"Merge Test":iden})
if not idtup:
log("ID '%s' cannot be found!" % iden)
log("To check for usage of a default keystore use: ztp request default-keystore-test")
return None
identity, identifier = idtup
if identity in config.running["keyvalstore"]:
path = config.running
else:
path = external_keystores.data
if not identity:
log("ID '%s' does not exist in keystore!" % iden)
else:
if template == "final":
templatedata = self.get_template(identity)
if not templatedata:
log("No tempate associated with identity %s" % iden)
quit()
else:
env = j2.Environment(loader=j2.FileSystemLoader('/'))
j2template = env.from_string(templatedata)
ast = env.parse(templatedata)
elif template == "initial":
env = j2.Environment(loader=j2.FileSystemLoader('/'))
j2template = env.from_string(self.baseconfig)
ast = j2template.parse(self.baseconfig)
templatevarlist = list(meta.find_undeclared_variables(ast))
varsmissing = False
missingvarlist = []
for var in templatevarlist:
if var not in path["keyvalstore"][identity]:
varsmissing = True
missingvarlist.append(var)
if varsmissing:
console("\nSome variables in jinja template do not exist in keystore:")
for var in missingvarlist:
console("\t-"+var)
console("\n")
kvalues = self.pull_keystore_values(path, identity)
snmpinfo = {"matched": "FAKEMATCHEDSERIAL"}
for oid in config.running["snmpoid"]:
snmpinfo.update({oid: "{}_FAKESERIAL".format(oid)})
kvalues.update({"snmpinfo": snmpinfo})
log("cfact.merge_test: Merging with values:\n{}".format(json.dumps(kvalues, indent=4)))
console("##############################")
console(j2template.render(kvalues))
console("##############################")
def pull_keystore_values(self, path, keystore_id):
if (keystore_id not in path["idarrays"]) and (keystore_id not in list(config.running["idarrays"])):
return self._global_keystore_merge(path["keyvalstore"][keystore_id])
else:
log("cfact.pull_keystore_values: Inserting IDArray keys")
base_vals = dict(path["keyvalstore"][keystore_id])
# Grab values from selected path first
if keystore_id in path["idarrays"]:
ida_vals = path["idarrays"][keystore_id]
else: # Otherwise grab from local config
ida_vals = config.running["idarrays"][keystore_id]
# If it doesn't exist at all, inject it
if "idarray" not in base_vals:
base_vals.update({"idarray": ida_vals})
# It it exists but is empty
elif not base_vals["idarray"]:
# Replace empty data with the local data
base_vals.update({"idarray": ida_vals})
index = 1
for value in ida_vals:
key = "idarray_{}".format(index)
if key not in base_vals:
base_vals.update({key: value})
index += 1
return self._global_keystore_merge(base_vals)
def _global_keystore_merge(self, ksdata):
keystoredata = dict(ksdata)
log("cfact._global_lookup: Checking if a global-keystore is configured and ready...")
if config.running["global-keystore"]: # If a global keystore ID is set
kid = config.running["global-keystore"]
log("cfact._global_lookup: A global-keystore is configured ({}), checking if it exists in local config".format(kid))
if kid in config.running["keyvalstore"]:
log("cfact._global_lookup: Global keystore exists in local config. Adding and returning")
keystoredata[kid] = config.running["keyvalstore"][kid]
return keystoredata
elif kid in external_keystores.data["keyvalstore"]:
log("cfact._global_lookup: Global keystore exists in external keystore. Returning")
keystoredata[kid] = external_keystores.data["keyvalstore"][kid]
return keystoredata
else:
log("cfact._global_lookup: Global keystore doesn't exist. Returning keystore data unchanged")
return keystoredata
else:
log("cfact._global_lookup: Global-keystore configured as none. Discarding")
return keystoredata
##### SNMP Querying object: It is instantiated by the config_factory #####
##### when the initial template is pulled down. A thread is #####
##### spawned which continuously tries to query the ID of the #####
##### switch. Once successfully queried, the querying object #####
##### retains the real ID of the switch which is mapped to a #####
##### keystore ID when the final template is requested #####
class snmp_query:
def __init__(self, host, community, oids, timeout=30):
global pysnmp
import pysnmp.hlapi
self.complete = False
self.status = "starting"
self.responses = {}
self.host = host
self.community = community
self.oids = oids
self.timeout = timeout
self.threads = []
#self._start()
self.thread = threading.Thread(target=self._start)
self.thread.daemon = True
self.thread.start()
def _start(self):
for oid in self.oids:
thread = threading.Thread(target=self._query_worker, args=(oid, self.oids[oid]))
thread.daemon = True
thread.start()
self.threads.append(thread)
def _watch_threads(self):
loop = True
while loop:
alldead = True
for thread in self.threads:
if thread.isAlive():
alldead = False
if alldead:
loop = False
def _query_worker(self, oidname, oid):
starttime = time.time()
self.status = "running"
while not self.complete:
try:
log("snmp_query._query_worker: Attempting SNMP Query")
response = self._get_oid(oid)
self.responses.update({oidname: response})
self.status = "success"
self.complete = True
log("snmp_query._query_worker: SNMP Query Successful (OID: %s). Host (%s) responded with (%s)" % (oidname, self.host, str(response)))
except IndexError:
self.status = "retrying"
log("snmp_query._query_worker: SNMP Query Timed Out")
if (time.time() - starttime) > self.timeout:
self.status = "failed"
log("snmp_query._query_worker: Timeout Expired, Query Thread Terminating")
break
else:
time.sleep(0.1)
def _get_oid(self, oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
pysnmp.hlapi.getCmd(pysnmp.hlapi.SnmpEngine(),
pysnmp.hlapi.CommunityData(self.community, mpModel=0),
pysnmp.hlapi.UdpTransportTarget((self.host, 161)),
pysnmp.hlapi.ContextData(),
pysnmp.hlapi.ObjectType(pysnmp.hlapi.ObjectIdentity(oid)))
)
return str(varBinds[0][1])
##### Configuration Manager: handles publishing of and changes to the ZTP #####
##### configuration input by the administrator #####
class config_manager:
def __init__(self):
self.sections = [
{"name": "dhcpd", "function": self.show_config_dhcpd},
{"name": "template", "function": self.show_config_template},
{"name": "keystore", "function": self.show_config_keystore},
{"name": "idarray", "function": self.show_config_idarray},
{"name": "association", "function": self.show_config_association},
{"name": "integration", "function": self.show_config_integration}
]
self.configfile = self._get_config_file()
self._publish()
def _get_config_file(self):
configfilename = "ztp.cfg"
pathlist = ["/etc/ztp", os.getcwd()]
for path in pathlist:
filepath = path + "/" + configfilename
if os.path.isfile(filepath):
return filepath
return None
def _publish(self):
if self.configfile:
f = open(self.configfile, "r")
self.rawconfig = f.read()
f.close()
self.running = json.loads(self.rawconfig)
self.suffix = self.running["suffix"]
self.templates = self.running["templates"]
self.keyvalstore = self.running["keyvalstore"]
self.initialfilename = self.running["initialfilename"]
self.community = self.running["community"]
self.snmpoid = self.running["snmpoid"]
self.starttemplate = self.running["starttemplate"]
self.associations = self.running["associations"]
else:
console("No Config File Found! Please install app!")
def load_external(self):
if self.configfile:
if "external-keystores" in self.running:
external_keystores.load()
if "external-templates" in self.running:
external_templates.load()
def save(self):
self.rawconfig = self.json = json.dumps(self.running, indent=4, sort_keys=True)
f = open(self.configfile, "w")
self.rawconfig = f.write(self.rawconfig)
f.close()
def set(self, args):
setting = args[2]
value = args[3]
exceptions = ["keyvalstore", "starttemplate"]
if setting in exceptions:
console("Cannot configure this way")
elif setting == "snmpoid":
self.running[setting].update({value: args[4]})
self.save()
elif setting == "integration":
self.set_integration(args[3], args[4], args[5])
elif setting == "external-keystore":
self.set_external_keystore(args[3], args[4], args[5])
elif setting == "template" or setting == "initial-template":
if setting == "initial-template":
console("Enter each line of the template ending with '%s' on a line by itself" % args[3])
newtemplate = self.multilineinput(args[3])
self.running["starttemplate"] = {"delineator":args[3], "value": newtemplate}
elif setting == "template":
console("Enter each line of the template ending with '%s' on a line by itself" % args[4])
newtemplate = self.multilineinput(args[4])
if "templates" not in list(self.running):
self.running.update({"templates": {}})
self.running["templates"].update({value:{}})
self.running["templates"][value]["value"] = newtemplate
self.running["templates"][value]["delineator"] = args[4]
self.save()
elif setting == "external-template":
self.set_external_template(args[3], args[4], args[5])
elif setting == "keystore":
self.set_keystore(args[3], args[4], args[5] )
elif setting == "idarray":
self.set_idarray(value, args[4:])
elif setting == "association":
iden = args[4]
template = args[6]
self.set_association(iden, template)
elif setting == "default-keystore" or setting == "default-template" or setting == "global-keystore":
if value.lower() == "none":
value = None
self.running[setting] = value
self.save()
elif setting == "image-supression" or setting == "file-cache-timeout" or setting == "delay-keystore":
try:
self.running[setting] = int(value)
self.save()
except ValueError:
console("Must be an integer!")
elif setting == "dhcpd-option":
self.set_dhcpd_options(args)
elif setting == "dhcpd":
self.set_dhcpd(args)
elif setting == "logging":
self.set_logging(args[3], args[4])
else:
if setting in list(self.running):
self.running[setting] = value
self.save()
else:
console("Unknown Setting!")
def clear(self, args):
setting = args[2]
iden = args[3]
if setting == "keystore":
key = args[4]
if iden not in list(self.running["keyvalstore"]):
console("ID does not exist in keystore: %s" % iden)
else:
if key == "all":
del self.running["keyvalstore"][iden]
else:
if key not in list(self.running["keyvalstore"][iden]):
console("Key does not exist under ID %s: %s" % (iden, key))
else:
del self.running["keyvalstore"][iden][key]
if self.running["keyvalstore"][iden] == {}: # No keys left
del self.running["keyvalstore"][iden]
elif setting == "integration":
key = args[4]
if iden not in list(self.running["integrations"]):
console("Integration (%s) does not exist!" % iden)
else:
if key == "all":
del self.running["integrations"][iden]
else:
if key not in list(self.running["integrations"][iden]):
console("Key (%s) does not exist under integration (%s)" % (iden, key))
else:
del self.running["integrations"][iden][key]
if self.running["integrations"][iden] == {}: # No keys left
del self.running["integrations"][iden]
elif setting == "external-keystore":
key = args[4]
if iden not in list(self.running["external-keystores"]):
console("External-keystore (%s) does not exist!" % iden)
else:
if key == "all":
del self.running["external-keystores"][iden]
else:
if key not in list(self.running["external-keystores"][iden]):
console("Key (%s) does not exist under external-keystore (%s)" % (iden, key))
else:
del self.running["external-keystores"][iden][key]
if self.running["external-keystores"][iden] == {}: # No keys left
del self.running["external-keystores"][iden]
elif setting == "idarray":
if iden not in list(self.running["idarrays"]):
console("ID does not exist in the idarrays: %s" % iden)
else:
del self.running["idarrays"][iden]
elif setting == "snmpoid":
if self.running["snmpoid"] == {}:
console("No SNMP OID's are currently configured")
elif iden not in list(self.running["snmpoid"]):
console("snmpoid '%s' is not currently configured" % iden)
else:
del self.running["snmpoid"][iden]
elif setting == "template":
if "templates" not in list(self.running):
console("No templates are currently configured")
elif iden not in list(self.running["templates"]):
console("Template '%s' is not currently configured" % iden)
else:
del self.running["templates"][iden]
elif setting == "external-template":
if iden not in self.running["external-templates"]:
console("External-template '%s' is not currently configured" % iden)
else:
del self.running["external-templates"][iden]
elif setting == "association":
if "associations" not in list(self.running):
console("No associations are currently configured")
elif iden not in list(self.running["associations"]):
console("Association '%s' is not currently configured" % iden)
else:
del self.running["associations"][iden]
elif setting == "dhcpd":
if "dhcpd" not in list(self.running):
console("No DHCP scopes are currently configured")
elif iden not in list(self.running["dhcpd"]):