-
Notifications
You must be signed in to change notification settings - Fork 15
/
org_inventory_deploy.py
1383 lines (1245 loc) · 50.8 KB
/
org_inventory_deploy.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
"""
-------------------------------------------------------------------------------
Written by Thomas Munzer ([email protected])
Github repository: https://github.com/tmunzer/Mist_library/
This script is licensed under the MIT License.
-------------------------------------------------------------------------------
Python script to deploy organization inventory backup file. By default, this
script can run in "Dry Run" mode to validate the destination org configuration
and raise warning if any object from the source org is missing in the
destination org.
It will not do any changes in the source/destination organizations unless you
pass the "-p"/"--proceed" parameter.
You can use the script "org_inventory_backup.py" to generate the backup file
from an existing organization.
This script is trying to maintain objects integrity as much as possible. To do
so, when an object is referencing another object by its ID, the script will
replace be ID from the original organization by the corresponding ID from the
destination org.
-------
Requirements:
mistapi: https://pypi.org/project/mistapi/
-------
Usage:
This script can be run as is (without parameters), or with the options below.
If no options are defined, or if options are missing, the missing options will
be asked by the script or the default values will be used.
It is recommended to use an environment file to store the required information
to request the Mist Cloud (see https://pypi.org/project/mistapi/ for more
information about the available parameters).
-------
Script Parameters:
-h, --help display this help
-o, --org_id= org_id where to deploy the inventory
-n, --org_name= org name where to deploy the inventory. This parameter
requires "org_id" to be defined
-f, --backup_folder= Path to the folder where to save the org backup (a
subfolder will be created with the org name)
default is "./org_backup"
-b, --source_backup= Name of the backup/template to deploy. This is the name
of the folder where all the backup files are stored.
-s, --sites= If only selected must be process, list a site names to
process, comma separated (e.g. -s "site 1","site 2")
-p, --proceed By default this script is executed in Dry Run mode. It
will validate to destination org configuration, and
check if the required configuration is present, but
it will not change anything in the source/destination
organization.
Use this option to proceed to the changes.
WARNING: Proceed to the deployment. This mode will
unclaim the APs from the source org (if -u is set) and
deploy them on the destination org.
-u, --unclaim if set the script will unclaim the devices from the
source org (only for devices claimed in the source org,
not for adopted devices). Unclaim process will only be
simulated if in Dry Run mode.
WARNING: this option will only unclaim Mist APs, use
the -a option to also unclaim switches and gateways
-a, --unclaim_all To be used with the -u option. Allows the script to
also migrate switches and gateways from the source
org to the destination org (works only for claimed
devices, not adopted ones).
WARNING: This process may reset and reboot the boxes.
Please make sure this will not impact users on site!
-l, --log_file= define the filepath/filename where to write the logs
default is "./script.log"
-e, --env= define the env file to use (see mistapi env file
documentation here: https://pypi.org/project/mistapi/)
default is "~/.mist_env"
--source_env= when using -u/--unclaim option, allows to define a
different env file to access the Source Organization.
default is to use the env file from -e/--env
-------
Examples:
python3 ./org_inventory_deploy.py
python3 ./org_inventory_deploy.py \
--org_id=203d3d02-xxxx-xxxx-xxxx-76896a3330f4 \
--org_name="TEST ORG" \
-p
"""
#####################################################################
#### IMPORTS ####
import json
import os
import sys
import re
import logging
import getopt
from typing import Callable
MISTAPI_MIN_VERSION = "0.44.1"
try:
import mistapi
from mistapi.__logger import console
except:
print(
"""
Critical:
\"mistapi\" package is missing. Please use the pip command to install it.
# Linux/macOS
python3 -m pip install mistapi
# Windows
py -m pip install mistapi
"""
)
sys.exit(2)
#####################################################################
#### PARAMETERS #####
BACKUP_FOLDER = "./org_backup/"
BACKUP_FILE = "./org_inventory_file.json"
FILE_PREFIX = ".".join(BACKUP_FILE.split(".")[:-1])
LOG_FILE = "./script.log"
SOURCE_ENV_FILE = "~/.mist_env"
DEST_ENV_FILE = None
#####################################################################
#### LOGS ####
LOGGER = logging.getLogger(__name__)
#####################################################################
#### GLOBAL VARS ####
ORG_OBJECT_TO_MATCH = {
"sites": {
"mistapi_function": mistapi.api.v1.orgs.sites.listOrgSites,
"text": "Site IDs",
"old_ids_dict": "old_sites_id",
},
"deviceprofiles": {
"mistapi_function": mistapi.api.v1.orgs.deviceprofiles.listOrgDeviceProfiles,
"text": "Device Profile IDs",
"old_ids_dict": "old_deviceprofiles_id",
},
"evpn_topologies": {
"mistapi_function": mistapi.api.v1.orgs.evpn_topologies.listOrgEvpnTopologies,
"text": "EVPN Topology IDs",
"old_ids_dict": "old_evpntopo_id",
},
}
SITE_OBJECT_TO_MATCH = {
"maps": {
"mistapi_function": mistapi.api.v1.sites.maps.listSiteMaps,
"text": "Map IDs",
"old_ids_dict": "old_maps_ids",
},
}
##########################################################################################
# CLASS TO MANAGE UUIDS UPDATES (replace UUIDs from source org to the newly created ones)
class UUIDM:
"""
CLASS TO MANAGE UUIDS UPDATES (replace UUIDs from source org to the newly created ones)
"""
def __init__(self):
self.uuids = {}
self.old_uuid_names = {}
self.missing_ids = {}
self.requests_to_replay = []
def add_uuid(self, new: str, old: str, name: str):
if new and old:
self.uuids[old] = new
self.old_uuid_names[old] = name
def get_new_uuid(self, old: str):
return self.uuids.get(old)
def add_missing_uuid(self, object_type: str, old_uuid: str, name: str):
if not object_type in self.missing_ids:
self.missing_ids[object_type] = {}
if not old_uuid in self.missing_ids[object_type]:
self.missing_ids[object_type][old_uuid] = name
def get_missing_uuids(self):
data = {}
for object_type, old_uuids in self.missing_ids.items():
data[object_type] = []
for old_uuid in old_uuids:
data[object_type].append(
{
"old_uuid": old_uuid,
"name": old_uuids[old_uuid],
}
)
return data
def add_replay(
self, mistapi_function: Callable, scope_id: str, object_type: str, data: dict
):
self.requests_to_replay.append(
{
"mistapi_function": mistapi_function,
"scope_id": scope_id,
"data": data,
"object_type": object_type,
"retry": 0,
}
)
def get_replay(self):
return self.requests_to_replay
def _uuid_string(self, obj_str: str, missing_uuids: list):
uuid_re = '"[a-zA_Z_-]*": "[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}"'
uuids_to_replace = re.findall(uuid_re, obj_str)
if uuids_to_replace:
for uuid in uuids_to_replace:
uuid_key = uuid.replace('"', "").split(":")[0].strip()
uuid_val = uuid.replace('"', "").split(":")[1].strip()
if self.get_new_uuid(uuid_val):
obj_str = obj_str.replace(uuid_val, self.get_new_uuid(uuid_val))
elif uuid_key not in [
"issuer",
"idp_sso_url",
"custom_logout_url",
"sso_issuer",
"sso_idp_sso_url",
"ibeacon_uuid",
]:
missing_uuids.append({uuid_key: uuid_val})
return obj_str, missing_uuids
def _uuid_list(self, obj_str: str, missing_uuids: list):
uuid_list_re = r"(\"[a-zA_Z_-]*\": \[\"[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}\"[^\]]*)]"
uuid_lists_to_replace = re.findall(uuid_list_re, obj_str)
if uuid_lists_to_replace:
for uuid_list in uuid_lists_to_replace:
uuid_key = uuid_list.replace('"', "").split(":")[0].strip()
uuids = (
uuid_list.replace('"', "")
.replace("[", "")
.replace("]", "")
.split(":")[1]
.split(",")
)
for uuid in uuids:
uuid_val = uuid.strip()
if self.get_new_uuid(uuid_val):
obj_str = obj_str.replace(uuid_val, self.get_new_uuid(uuid_val))
else:
missing_uuids.append({uuid_key: uuid_val})
return obj_str, missing_uuids
def find_and_replace(self, obj: dict, object_type: str):
# REMOVE READONLY FIELDS
ids_to_remove = []
for id_name in ids_to_remove:
if id_name in obj:
del obj[id_name]
# REPLACE REMAINING IDS
obj_str = json.dumps(obj)
obj_str, missing_uuids = self._uuid_string(obj_str, [])
obj_str, missing_uuids = self._uuid_list(obj_str, missing_uuids)
obj = json.loads(obj_str)
return obj, missing_uuids
uuid_matching = UUIDM()
##########################################################################################
# PROGRESS BAR AND DISPLAY
class ProgressBar:
"""
PROGRESS BAR AND DISPLAY
"""
def __init__(self):
self.steps_total = 0
self.steps_count = 0
def _pb_update(self, size: int = 80):
if self.steps_count > self.steps_total:
self.steps_count = self.steps_total
percent = self.steps_count / self.steps_total
delta = 17
x = int((size - delta) * percent)
print(f"Progress: ", end="")
print(f"[{'█'*x}{'.'*(size-delta-x)}]", end="")
print(f"{int(percent*100)}%".rjust(5), end="")
def _pb_new_step(
self,
message: str,
result: str,
inc: bool = False,
size: int = 80,
display_pbar: bool = True,
):
if inc:
self.steps_count += 1
text = f"\033[A\033[F{message}"
print(f"{text} ".ljust(size + 4, "."), result)
print("".ljust(80))
if display_pbar:
self._pb_update(size)
def _pb_title(
self, text: str, size: int = 80, end: bool = False, display_pbar: bool = True
):
print("\033[A")
print(f" {text} ".center(size, "-"), "\n")
if not end and display_pbar:
print("".ljust(80))
self._pb_update(size)
def set_steps_total(self, steps_total: int):
self.steps_total = steps_total
def log_message(self, message, display_pbar: bool = True):
self._pb_new_step(message, " ", display_pbar=display_pbar)
def log_success(self, message, inc: bool = False, display_pbar: bool = True):
LOGGER.info(f"{message}: Success")
self._pb_new_step(
message, "\033[92m\u2714\033[0m\n", inc=inc, display_pbar=display_pbar
)
def log_warning(self, message, inc: bool = False, display_pbar: bool = True):
LOGGER.warning(f"{message}")
self._pb_new_step(
message, "\033[93m\u2B58\033[0m\n", inc=inc, display_pbar=display_pbar
)
def log_failure(self, message, inc: bool = False, display_pbar: bool = True):
LOGGER.error(f"{message}: Failure")
self._pb_new_step(
message, "\033[31m\u2716\033[0m\n", inc=inc, display_pbar=display_pbar
)
def log_title(self, message, end: bool = False, display_pbar: bool = True):
LOGGER.info(message)
self._pb_title(message, end=end, display_pbar=display_pbar)
PB = ProgressBar()
##########################################################################################
##########################################################################################
# DEPLOY FUNCTIONS
##########################################################################################
## UNCLAIM/CLAIM FUNCTIONS
def _unclaim_devices(
src_apisession: mistapi.APISession,
src_org_id: str,
devices: list,
magics: dict,
failed_devices: dict,
proceed: bool = False,
unclaim_all: bool = False,
):
LOGGER.debug("inventory_deploy:_unclaim_devices")
serials = []
macs = []
serial_to_mac = {}
for device in devices:
if device.get("mac") in magics:
if device.get("type") == "ap" or unclaim_all:
serials.append(device["serial"])
macs.append(device["mac"])
serial_to_mac[device["serial"]] = device["mac"]
if serials:
try:
message = f"Unclaiming {len(serials)} devices from source Org"
PB.log_message(message)
if not proceed:
PB.log_success(message, inc=True)
else:
response = mistapi.api.v1.orgs.inventory.updateOrgInventoryAssignment(
src_apisession, src_org_id, {"op": "delete", "serials": serials}
)
if response.data.get("error"):
PB.log_warning(message, inc=True)
i = 0
for failed_serial in response.data["error"]:
mac = serial_to_mac[failed_serial]
message = f"Unable to claim device {mac}: {response.data['reason'][i]}"
failed_devices[
mac
] = f"Unable to unclaim device {mac}: {response.data['reason'][i]}"
i += 1
elif response.status_code == 200:
PB.log_success(message, inc=True)
else:
PB.log_failure(message, inc=True)
for device in devices:
if (
device.get("mac") in magics
and device.get("serial") not in failed_devices
):
failed_devices[device["mac"]] = "Unable to claim the device"
except:
PB.log_failure(message, inc=True)
LOGGER.error("Exception occurred", exc_info=True)
def _claim_devices(
dst_apisession: mistapi.APISession,
dst_org_id: str,
devices: list,
magics: dict,
failed_devices: dict,
proceed: bool = False,
unclaim_all: bool = False,
):
LOGGER.debug("inventory_deploy:_claim_devices")
magics_to_claim = []
magic_to_mac = {}
for device in devices:
if device.get("mac") in magics and device.get("mac") not in failed_devices:
if device.get("type") == "ap" or unclaim_all:
magics_to_claim.append(magics[device["mac"]])
magic_to_mac[magics[device["mac"]]] = device["mac"]
if not magics_to_claim:
PB.log_success("No device to claim", inc=True)
return
else:
try:
message = f"Claiming {len(magics_to_claim)} devices"
PB.log_message(message)
if not proceed:
PB.log_success(message, inc=True)
else:
response = mistapi.api.v1.orgs.inventory.addOrgInventory(
dst_apisession, dst_org_id, magics_to_claim
)
if response.data.get("error"):
PB.log_warning(message, inc=True)
i = 0
for failed_magic in response.data["error"]:
mac = magic_to_mac[failed_magic]
message = f"Unable to claim device {mac}: {response.data['reason'][i]}"
failed_devices[mac] = f"Unable to claim device {mac}: {response.data['reason'][i]}"
i += 1
elif response.status_code == 200:
PB.log_success(message, inc=True)
else:
PB.log_failure(message, inc=True)
for device in devices:
if (
device.get("mac") in magics
and device.get("serial") not in failed_devices
):
failed_devices[device["mac"]] = "Unable to claim the device"
except:
PB.log_failure(message, inc=True)
LOGGER.error("Exception occurred", exc_info=True)
def _assign_device_to_site(
dst_apisession: mistapi.APISession,
dst_org_id: str,
dst_site_id: str,
site_name: str,
devices: list,
failed_devices: dict,
proceed: bool = False,
unclaim_all: bool = False,
):
LOGGER.debug("inventory_deploy:_assign_device_to_site")
macs_to_assign = []
for device in devices:
if device.get("mac") and device["mac"] not in failed_devices:
if device.get("type") == "ap" or unclaim_all:
macs_to_assign.append(device["mac"])
if not macs_to_assign:
PB.log_success("No device to assign", inc=True)
return
else:
if len(macs_to_assign) == 1:
message = f"Assigning {len(macs_to_assign)} device to the Site"
else:
message = f"Assigning {len(macs_to_assign)} devices to the Site"
try:
PB.log_message(message)
if not proceed:
PB.log_success(message, inc=True)
else:
response = mistapi.api.v1.orgs.inventory.updateOrgInventoryAssignment(
dst_apisession,
dst_org_id,
{"macs": macs_to_assign, "site_id": dst_site_id, "op": "assign"},
)
if response.data.get("error"):
PB.log_warning(message, inc=True)
i = 0
for failed_mac in response.data["error"]:
message = f"Unable to assign device {failed_mac} to site {site_name}: {response.data['reason'][i]}"
failed_devices[failed_mac] = f"Unable to assign device {failed_mac} to site {site_name}: {response.data['reason'][i]}"
i += 1
elif response.status_code == 200:
PB.log_success(message, inc=True)
else:
PB.log_failure(message, inc=True)
for mac in macs_to_assign:
if mac and mac not in failed_devices:
failed_devices[mac] = f"Unable to assign the device to site {site_name}"
except:
PB.log_failure(message, inc=True)
LOGGER.error("Exception occurred", exc_info=True)
##########################################################################################
## DEVICE RESTORE
def _update_device_configuration(
dst_apisession: mistapi.APISession,
dst_site_id: str,
device: dict,
devices_type: str = "device",
proceed: bool = False,
):
LOGGER.debug("inventory_deploy:_update_device_configuration")
issue_config = False
try:
message = f"{device.get('type', devices_type).title()} {device.get('mac')} (S/N: {device.get('serial')}): Restoring Configuration"
PB.log_message(message)
data, missing_uuids = uuid_matching.find_and_replace(device, "device")
if proceed:
response = mistapi.api.v1.sites.devices.updateSiteDevice(
dst_apisession, dst_site_id, device["id"], data
)
if response.status_code != 200:
raise Exception
PB.log_success(message, inc=True)
except Exception as e:
PB.log_failure(message, True)
LOGGER.error("Exception occurred", exc_info=True)
issue_config = True
return issue_config
def _restore_device_images(
dst_apisession: mistapi.APISession,
src_org_id: str,
dst_site_id: str,
device: dict,
devices_type: str = "device",
proceed: bool = False,
):
LOGGER.debug("inventory_deploy:_restore_device_images")
i = 1
image_exists = True
issue_image = False
while image_exists:
image_name = (
f"{FILE_PREFIX}_org_{src_org_id}_device_{device['serial']}_image_{i}.png"
)
if os.path.isfile(image_name):
try:
message = f"{device.get('type', devices_type).title()} {device.get('mac')} (S/N: {device.get('serial')}): Restoring Image #{i}"
PB.log_message(message)
if proceed:
response = mistapi.api.v1.sites.devices.addSiteDeviceImageFile(
dst_apisession, dst_site_id, device["id"], i, image_name
)
if response.status_code != 200:
raise Exception
PB.log_success(message, inc=False)
except:
issue_image = True
PB.log_failure(message, inc=False)
LOGGER.error("Exception occurred", exc_info=True)
i += 1
else:
image_exists = False
return issue_image
def _restore_devices(
src_apisession: mistapi.APISession,
dst_apisession: mistapi.APISession,
src_org_id: str,
dst_org_id: str,
dst_site_id: str,
site_name: str,
devices: dict,
magics: list,
processed_macs: list,
failed_devices: dict,
proceed: bool = False,
unclaim: bool = False,
unclaim_all: bool = False,
):
LOGGER.debug("inventory_deploy:_restore_devices")
if unclaim:
_unclaim_devices(src_apisession, src_org_id, devices, magics, failed_devices, proceed, unclaim_all)
_claim_devices(dst_apisession, dst_org_id, devices, magics, failed_devices, proceed, unclaim_all)
_assign_device_to_site(dst_apisession, dst_org_id, dst_site_id, site_name, devices, failed_devices, proceed, unclaim_all)
for device in devices:
processed_macs.append(device["mac"])
if device["mac"] not in failed_devices:
if device.get("type") == "ap" or unclaim_all:
issue_config = _update_device_configuration(dst_apisession, dst_site_id, device, device.get("type"), proceed)
issue_image = _restore_device_images(dst_apisession, src_org_id, dst_site_id, device, device.get("type"), proceed)
if issue_config:
failed_devices[device["mac"]] = f"Error when uploading device configuration (site {site_name})"
if issue_image:
failed_devices[device["mac"]] = f"Error when uploading device image (site {site_name})"
def _restore_unassigned_devices(
src_apisession: mistapi.APISession,
dst_apisession: mistapi.APISession,
src_org_id: str,
dst_org_id: str,
processed_macs: dict,
magics: list,
devices: dict,
failed_devices: dict,
proceed: bool = False,
unclaim: bool = False,
unclaim_all: bool = False,
):
LOGGER.debug("inventory_deploy:_restore_unassigned_devices")
devices_not_assigned = []
for device in devices:
if not device["mac"] in processed_macs:
LOGGER.debug(f"inventory_deploy:_restore_unassigned_devices:new unassigned device found {device['mac']}")
devices_not_assigned.append(device)
LOGGER.debug(f"inventory_deploy:_restore_unassigned_devices:list of unassigned device found {devices_not_assigned}")
if unclaim:
_unclaim_devices(src_apisession, src_org_id, devices_not_assigned, magics, failed_devices, proceed, unclaim_all)
_claim_devices(dst_apisession, dst_org_id, devices_not_assigned, magics, failed_devices, proceed, unclaim_all)
##########################################################################################
### IDs Matching
def _process_ids(
dst_apisession: mistapi.APISession,
step: dict,
scope_id: str,
old_ids: dict,
message: str,
):
LOGGER.debug("inventory_deploy:_process_ids")
message = f"Loading {step['text']}"
try:
PB.log_message(message)
response = step["mistapi_function"](dst_apisession, scope_id)
data = mistapi.get_all(dst_apisession, response)
for entry in data:
if entry.get("name") in old_ids:
uuid_matching.add_uuid(
entry.get("id"), old_ids[entry.get("name")], entry.get("name")
)
match_all = True
for old_id_name in old_ids:
if not uuid_matching.get_new_uuid(old_ids[old_id_name]):
uuid_matching.add_missing_uuid(
step["text"], old_ids[old_id_name], old_id_name
)
match_all = False
if match_all:
PB.log_success(message, True)
else:
PB.log_warning(message, True)
except:
PB.log_failure(message, True)
LOGGER.error("Exception occurred", exc_info=True)
def _process_org_ids(
dst_apisession: mistapi.APISession, dst_org_id: str, org_backup: dict
):
LOGGER.debug("inventory_deploy:_process_org_ids")
for org_step_name, org_step_data in ORG_OBJECT_TO_MATCH.items():
old_ids_dict = org_backup[org_step_data["old_ids_dict"]]
_process_ids(
dst_apisession,
org_step_data,
dst_org_id,
old_ids_dict,
"Checking Org Ids",
)
def _process_site_ids(
dst_apisession: mistapi.APISession,
new_site_id: str,
site_name: str,
site_data: dict,
):
LOGGER.debug("inventory_deploy:_process_site_ids")
for site_step_name, site_step_data in SITE_OBJECT_TO_MATCH.items():
old_ids_dict = site_data[site_step_data["old_ids_dict"]]
_process_ids(
dst_apisession,
site_step_data,
new_site_id,
old_ids_dict,
f"Checking Site {site_name} IDs",
)
##########################################################################################
#### CORE FUNCTIONS ####
def _result(failed_devices: dict, proceed: bool) -> bool:
LOGGER.debug("inventory_deploy:_result")
PB.log_title("Result", end=True)
missing_ids = uuid_matching.get_missing_uuids()
if not proceed:
console.warning("This script has been executed in Dry Run mode.")
console.warning(
"No modification have been done on the Source/Destination orgs."
)
console.warning('Use the "-p" / "--proceed" option to execute the changes.')
print()
if missing_ids:
for object_type, ids in missing_ids.items():
console.warning(
f"Unable to find the following {object_type} in the Destination Org:"
)
print()
mistapi.cli.display_list_of_json_as_table(
ids, ["name", "old_uuid"]
)
print("")
if failed_devices:
console.warning(
f"There was {len(failed_devices)} device error(s) during the process:"
)
for serial in failed_devices:
print(f"{serial}: {failed_devices[serial]}")
if not missing_ids and not failed_devices:
console.info("Pre check validation succed!")
console.info("No object missing, you can restore the devices")
print("")
return True
return False
def _deploy(
src_apisession: mistapi.APISession,
dst_apisession: mistapi.APISession,
src_org_id: str,
dst_org_id: str,
org_backup: dict,
filter_site_names: list = [],
proceed: bool = False,
unclaim: bool = False,
unclaim_all: bool = False,
) -> bool:
LOGGER.debug("inventory_deploy:_deploy")
print()
PB.log_title("Processing Org")
uuid_matching.add_uuid(dst_org_id, src_org_id, "Source Org ID")
_process_org_ids(dst_apisession, dst_org_id, org_backup)
failed_devices = {}
processed_macs = []
for restore_site_name in org_backup["sites"]:
if not filter_site_names or restore_site_name in filter_site_names:
PB.log_title(f"Processing Site {restore_site_name}")
site = org_backup["sites"][restore_site_name]
dst_site_id = uuid_matching.get_new_uuid(site["id"])
if not dst_site_id:
uuid_matching.add_missing_uuid("site", site["id"], restore_site_name)
else:
_process_site_ids(dst_apisession, dst_site_id, restore_site_name, site)
_restore_devices(
src_apisession,
dst_apisession,
src_org_id,
dst_org_id,
dst_site_id,
restore_site_name,
site["devices"],
org_backup["magics"],
processed_macs,
failed_devices,
proceed,
unclaim,
unclaim_all,
)
if not filter_site_names:
_restore_unassigned_devices(
src_apisession,
dst_apisession,
src_org_id,
dst_org_id,
processed_macs,
org_backup["magics"],
org_backup["devices"],
failed_devices,
proceed,
unclaim,
unclaim_all,
)
return _result(failed_devices, proceed)
def _check_access(apisession: mistapi.APISession, org_id: str, message: str) -> bool:
LOGGER.debug("inventory_deploy:_check_access")
PB.log_message(message, display_pbar=False)
try:
response = mistapi.api.v1.self.self.getSelf(apisession)
if response.status_code == 200:
privileges = response.data.get("privileges", [])
for p in privileges:
if p.get("scope") == "org" and p.get("org_id") == org_id:
if p.get("role") == "admin":
PB.log_success(message, display_pbar=False)
return True
else:
PB.log_failure(message, display_pbar=False)
console.error(
"You don't have full access to this org. Please use another account"
)
return False
except:
PB.log_failure(message, display_pbar=False)
console.critical("Unable to retrieve privileges from Mist Cloud")
LOGGER.error("Exception occurred", exc_info=True)
PB.log_failure(message, display_pbar=False)
console.error("You don't have access to this org. Please use another account")
return False
def _start_deploy(
src_apisession: mistapi.APISession,
dst_apisession: mistapi.APISession,
dst_org_id: str,
backup_folder_param: str,
source_backup: str = None,
src_org_name: str = None,
filter_site_names: list = [],
proceed: bool = False,
unclaim: bool = False,
unclaim_all: bool = False,
) -> bool:
LOGGER.debug("inventory_deploy:_start_deploy")
_go_to_backup_folder(backup_folder_param, src_org_name, source_backup)
print()
try:
message = f"Loading inventory file {BACKUP_FILE} "
PB.log_message(message, display_pbar=False)
with open(BACKUP_FILE) as f:
backup = json.load(f)
PB.log_success(message, display_pbar=False)
except:
PB.log_failure(message, display_pbar=False)
console.critical("Unable to load the inventory file")
LOGGER.error("Exception occurred", exc_info=True)
sys.exit(1)
try:
message = f"Analyzing template/backup file {BACKUP_FILE} "
PB.log_message(message, display_pbar=False)
src_org_id = backup["org"]["id"]
steps_total = 2
sites_len = len(backup["org"]["sites"])
devices_len = 0
for site_name in backup["org"]["sites"]:
devices_len += len(backup["org"]["sites"][site_name])
steps_total += sites_len * 2 + devices_len * 2
PB.set_steps_total(steps_total)
PB.log_success(message, display_pbar=False)
console.info(f"The process will test the deployment of {steps_total} devices")
except:
PB.log_failure(message, display_pbar=False)
console.critical("Unable to parse the template/backup file")
LOGGER.error("Exception occurred", exc_info=True)
sys.exit(1)
if backup:
if _check_access(
dst_apisession, dst_org_id, "Validating access to the Destination Org"
):
if (
unclaim
and _check_access(
src_apisession, src_org_id, "Validating access to the Source Org"
)
) or not unclaim:
return _deploy(
src_apisession,
dst_apisession,
src_org_id,
dst_org_id,
backup["org"],
filter_site_names,
proceed,
unclaim,
unclaim_all,
)
#####################################################################
#### FOLDER MGMT ####
def _chdir(path: str):
try:
os.chdir(path)
return True
except FileNotFoundError:
console.error(f"Folder path {path} does not exists")
return False
except NotADirectoryError:
console.error(f"Folder path {path} is not a directory")
return False
except PermissionError:
console.error(f"You don't have the rights to access the directory {path}")
return False
except Exception as e:
console.error(f"An error occured : {e}")
LOGGER.error("Exception occurred", exc_info=True)
return False
def _select_backup_folder(folders):
i = 0
print("Available Templates/Backups:")
while i < len(folders):
print(f"{i}) {folders[i]}")
i += 1
folder = None
while folder is None:
resp = input(
f"Which template/backup do you want to deploy (0-{i - 1}, or q to quit)? "
)
if resp.lower() == "q":
console.error("Interruption... Exiting...")
LOGGER.error("Interruption... Exiting...")
sys.exit(0)
try:
respi = int(resp)
if respi >= 0 and respi <= i:
folder = folders[respi]
else:
print(f'The entry value "{respi}" is not valid. Please try again...')
except:
print("Only numbers are allowed. Please try again...")
_chdir(folder)
def _go_to_backup_folder(
backup_folder_param: str, src_org_name: str = None, source_backup: str = None
):
print()
print(" Source Backup/Template ".center(80, "-"))
print()
_chdir(backup_folder_param)
folders = []
for entry in os.listdir("./"):
if os.path.isdir(os.path.join("./", entry)):
folders.append(entry)
folders = sorted(folders, key=str.casefold)
if source_backup in folders and _chdir(source_backup):
print(f"Template/Backup {source_backup} found. It will be automatically used.")
elif src_org_name in folders:
print(f"Template/Backup found for organization {src_org_name}.")
loop = True
while loop:
resp = input("Do you want to use this template/backup (y/N)? ")
if resp.lower() in ["y", "n", " "]:
loop = False
if resp.lower() == "y" and _chdir(src_org_name):
pass
else:
_select_backup_folder(folders)
else:
print(
f"No Template/Backup found for organization {src_org_name}. Please select a folder in the following list."
)
_select_backup_folder(folders)