-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsite_conf_deploy.py
More file actions
1745 lines (1573 loc) · 60.8 KB
/
site_conf_deploy.py
File metadata and controls
1745 lines (1573 loc) · 60.8 KB
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 (tmunzer@juniper.net)
Github repository: https://github.com/tmunzer/Mist_library/
This script is licensed under the MIT License.
-------------------------------------------------------------------------------
Python script to restore site template/backup file.
You can use the script "site_conf_backup.py" to generate the backup file from an
existing organization.
This script will not overide existing objects. If you already configured objects in the
destination organization, new objects will be reused or created. If you want to "reset" the
destination organization, you can use the script "org_conf_zeroise.py".
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.
You can run the script with the command "python3 site_conf_import.py"
The script has 3 different steps:
1) admin login
2) choose the destination org
3) choose the backup/template to restore
all the objects will be created from the json file.
"""
#### IMPORTS ####
import sys
import logging
import json
import argparse
import re
import signal
import os.path
from typing import Callable
MISTAPI_MIN_VERSION = "0.55.5"
try:
import mistapi
from mistapi.__logger import console
except ImportError:
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 = "./site_backup/"
BACKUP_FILE = "./site_conf_file.json"
FILE_PREFIX = ".".join(BACKUP_FILE.split(".")[:-1])
LOG_FILE = "./script.log"
ENV_FILE = "./.env"
#####################################################################
#### LOGS ####
LOGGER = logging.getLogger(__name__)
#####################################################################
#### GLOBALS #####
SYS_EXIT = False
def sigint_handler(signal, frame):
global SYS_EXIT
SYS_EXIT = True
print("[Ctrl C],KeyboardInterrupt exception occurred.")
signal.signal(signal.SIGINT, sigint_handler)
#####################################################################
# DEPLOY OBJECTS REFS
class Step:
"""
Class to define a step in the backup process.
"""
def __init__(
self,
create_mistapi_function: Callable,
list_mistapi_function: Callable | None = None,
update_mistapi_function: Callable | None = None,
list_type_query_param: str | None = None,
text: str = "",
attr_name: str = "name",
):
self.list_mistapi_function = list_mistapi_function
self.list_type_query_param = list_type_query_param
self.create_mistapi_function = create_mistapi_function
self.update_mistapi_function = update_mistapi_function
self.text = text
self.attr_name = attr_name
self.existing_objects = []
def load_existing_objects(self, apisession, org_id):
"""
Load existing objects from the destination organization.
:param apisession: The Mist API session.
:param org_id: The organization ID.
"""
LOGGER.debug("Loading existing objects for step: %s", self.text)
message = f"Loading existing objects for {self.text}"
PB.log_message(message, display_pbar=False)
try:
if self.list_mistapi_function and self.list_type_query_param:
resp = self.list_mistapi_function(
apisession,
org_id,
type=self.list_type_query_param,
limit=1000,
page=1,
)
self.existing_objects = mistapi.get_all(apisession, resp)
elif self.list_mistapi_function:
resp = self.list_mistapi_function(
apisession, org_id, limit=1000, page=1
)
self.existing_objects = mistapi.get_all(apisession, resp)
else:
self.existing_objects = []
PB.log_success(message, display_pbar=False, inc=False)
except Exception as e:
PB.log_failure(message, display_pbar=False, inc=False)
LOGGER.error("Error loading existing objects for step %s: %s", self.text, e)
self.existing_objects = []
def search_existing_object(self, obj: dict, obj_name: str, action: str):
"""
Search for an existing object by name.
:param obj: The object to search for.
:param obj_name: The name of the object to search for.
:param action: The action to take if the object exists ("skip", "replace", "rename").
:return: A tuple (proceed: bool, obj: dict | None, existing_obj_id: str | None)
"""
LOGGER.debug(
"Searching for existing object %s with name %s", self.text, obj_name
)
LOGGER.debug("merge action: %s", action)
for existing_obj in self.existing_objects:
if existing_obj.get(self.attr_name, "") == obj_name:
if action == "skip":
LOGGER.debug(
"Object %s with name %s already exists, skipping...",
self.text,
obj_name,
)
UUID_MATCHING.add_uuid(existing_obj["id"], obj["id"])
return False, None, existing_obj["id"]
elif action == "replace":
LOGGER.debug(
"Object %s with name %s already exists, replacing...",
self.text,
obj_name,
)
UUID_MATCHING.add_uuid(existing_obj["id"], obj["id"])
obj["id"] = existing_obj["id"]
return False, obj, existing_obj["id"]
elif action == "rename":
new_name = f"{obj_name}_copy"
LOGGER.debug(
"Object %s with name %s already exists, renaming to %s...",
self.text,
obj_name,
new_name,
)
obj[self.attr_name] = new_name
return True, obj, existing_obj["id"]
LOGGER.debug(
"Object %s with name %s does not exist, proceeding...",
self.text,
obj_name,
)
return True, obj, None
ORG_STEPS = {
"sites": Step(
list_mistapi_function=mistapi.api.v1.orgs.sites.listOrgSites,
create_mistapi_function=mistapi.api.v1.orgs.sites.createOrgSite,
update_mistapi_function=mistapi.api.v1.sites.sites.updateSiteInfo,
text="Org Sites",
),
"alarmtemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.alarmtemplates.listOrgAlarmTemplates,
create_mistapi_function=mistapi.api.v1.orgs.alarmtemplates.createOrgAlarmTemplate,
update_mistapi_function=mistapi.api.v1.orgs.alarmtemplates.updateOrgAlarmTemplate,
text="Org alarmtemplate",
),
"aptemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.aptemplates.listOrgAptemplates,
create_mistapi_function=mistapi.api.v1.orgs.aptemplates.createOrgAptemplate,
update_mistapi_function=mistapi.api.v1.orgs.aptemplates.updateOrgAptemplate,
text="Org aptemplate",
),
"rftemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.rftemplates.listOrgRfTemplates,
create_mistapi_function=mistapi.api.v1.orgs.rftemplates.createOrgRfTemplate,
update_mistapi_function=mistapi.api.v1.orgs.rftemplates.updateOrgRfTemplate,
text="Org rftemplate",
),
"networktemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.networktemplates.listOrgNetworkTemplates,
create_mistapi_function=mistapi.api.v1.orgs.networktemplates.createOrgNetworkTemplate,
update_mistapi_function=mistapi.api.v1.orgs.networktemplates.updateOrgNetworkTemplate,
text="Org networktemplate",
),
"gatewaytemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.gatewaytemplates.listOrgGatewayTemplates,
create_mistapi_function=mistapi.api.v1.orgs.gatewaytemplates.createOrgGatewayTemplate,
update_mistapi_function=mistapi.api.v1.orgs.gatewaytemplates.updateOrgGatewayTemplate,
text="Org gatewaytemplate",
),
"secpolicy": Step(
list_mistapi_function=mistapi.api.v1.orgs.secpolicies.listOrgSecPolicies,
create_mistapi_function=mistapi.api.v1.orgs.secpolicies.createOrgSecPolicy,
update_mistapi_function=mistapi.api.v1.orgs.secpolicies.updateOrgSecPolicy,
text="Org secpolicy",
),
"sitetemplate": Step(
list_mistapi_function=mistapi.api.v1.orgs.sitetemplates.listOrgSiteTemplates,
create_mistapi_function=mistapi.api.v1.orgs.sitetemplates.createOrgSiteTemplate,
update_mistapi_function=mistapi.api.v1.orgs.sitetemplates.updateOrgSiteTemplate,
text="Org sitetemplate",
),
"sitegroups": Step(
list_mistapi_function=mistapi.api.v1.orgs.sitegroups.listOrgSiteGroups,
create_mistapi_function=mistapi.api.v1.orgs.sitegroups.createOrgSiteGroup,
text="Org sitegroup",
),
}
SITE_STEPS = {
"maps": Step(
list_mistapi_function=mistapi.api.v1.sites.maps.listSiteMaps,
create_mistapi_function=mistapi.api.v1.sites.maps.createSiteMap,
update_mistapi_function=mistapi.api.v1.sites.maps.updateSiteMap,
text="Site maps",
),
"zones": Step(
list_mistapi_function=mistapi.api.v1.sites.zones.listSiteZones,
create_mistapi_function=mistapi.api.v1.sites.zones.createSiteZone,
update_mistapi_function=mistapi.api.v1.sites.zones.updateSiteZone,
text="Site zones",
),
"rssizones": Step(
list_mistapi_function=mistapi.api.v1.sites.rssizones.listSiteRssiZones,
create_mistapi_function=mistapi.api.v1.sites.rssizones.createSiteRssiZone,
update_mistapi_function=mistapi.api.v1.sites.rssizones.updateSiteRssiZone,
text="Site rssizones",
),
"assets": Step(
list_mistapi_function=mistapi.api.v1.sites.assets.listSiteAssets,
create_mistapi_function=mistapi.api.v1.sites.assets.createSiteAsset,
update_mistapi_function=mistapi.api.v1.sites.assets.updateSiteAsset,
text="Site assets",
),
"assetfilters": Step(
list_mistapi_function=mistapi.api.v1.sites.assetfilters.listSiteAssetFilters,
create_mistapi_function=mistapi.api.v1.sites.assetfilters.createSiteAssetFilter,
update_mistapi_function=mistapi.api.v1.sites.assetfilters.updateSiteAssetFilter,
text="Site assetfilters",
),
"beacons": Step(
list_mistapi_function=mistapi.api.v1.sites.beacons.listSiteBeacons,
create_mistapi_function=mistapi.api.v1.sites.beacons.createSiteBeacon,
update_mistapi_function=mistapi.api.v1.sites.beacons.updateSiteBeacon,
text="Site beacons",
),
"psks": Step(
list_mistapi_function=mistapi.api.v1.sites.psks.listSitePsks,
create_mistapi_function=mistapi.api.v1.sites.psks.importSitePsks,
update_mistapi_function=mistapi.api.v1.sites.psks.updateSitePsk,
text="Site psks",
),
"vbeacons": Step(
list_mistapi_function=mistapi.api.v1.sites.vbeacons.listSiteVBeacons,
create_mistapi_function=mistapi.api.v1.sites.vbeacons.createSiteVBeacon,
update_mistapi_function=mistapi.api.v1.sites.vbeacons.updateSiteVBeacon,
text="Site vbeacons",
),
"evpn_topologies": Step(
list_mistapi_function=mistapi.api.v1.sites.evpn_topologies.listSiteEvpnTopologies,
create_mistapi_function=mistapi.api.v1.sites.evpn_topologies.createSiteEvpnTopology,
update_mistapi_function=mistapi.api.v1.sites.evpn_topologies.updateSiteEvpnTopology,
text="Site EVPN Topologies",
),
"webhooks": Step(
list_mistapi_function=mistapi.api.v1.sites.webhooks.listSiteWebhooks,
create_mistapi_function=mistapi.api.v1.sites.webhooks.createSiteWebhook,
update_mistapi_function=mistapi.api.v1.sites.webhooks.updateSiteWebhook,
text="Site webhooks",
),
"wxtunnels": Step(
list_mistapi_function=mistapi.api.v1.sites.wxtunnels.listSiteWxTunnels,
create_mistapi_function=mistapi.api.v1.sites.wxtunnels.createSiteWxTunnel,
update_mistapi_function=mistapi.api.v1.sites.wxtunnels.updateSiteWxTunnel,
text="Site wxtunnels",
),
"wlans": Step(
list_mistapi_function=mistapi.api.v1.sites.wlans.listSiteWlans,
create_mistapi_function=mistapi.api.v1.sites.wlans.createSiteWlan,
update_mistapi_function=mistapi.api.v1.sites.wlans.updateSiteWlan,
text="Site wlans",
attr_name="ssid",
),
"wxtags": Step(
list_mistapi_function=mistapi.api.v1.sites.wxtags.listSiteWxTags,
create_mistapi_function=mistapi.api.v1.sites.wxtags.createSiteWxTag,
update_mistapi_function=mistapi.api.v1.sites.wxtags.updateSiteWxTag,
text="Site wxtags",
),
"wxrules": Step(
list_mistapi_function=mistapi.api.v1.sites.wxrules.listSiteWxRules,
create_mistapi_function=mistapi.api.v1.sites.wxrules.createSiteWxRule,
update_mistapi_function=mistapi.api.v1.sites.wxrules.updateSiteWxRule,
text="Site wxrules",
attr_name="order",
),
"settings": Step(
create_mistapi_function=mistapi.api.v1.sites.setting.updateSiteSettings,
update_mistapi_function=mistapi.api.v1.sites.setting.updateSiteSettings,
text="Site settings",
),
}
##########################################################################################
# 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.requests_to_replay = []
def add_uuid(self, new: str | None, old: str | None) -> None:
"""
Add a new UUID mapping to the dictionary.
:param new: The new UUID to be added.
:param old: The old UUID that the new UUID replaces.
"""
if new and old:
LOGGER.debug("add_uuid: old_id %s matching new_id %s", old, new)
self.uuids[old] = new
else:
LOGGER.warning("add_uuid: old_id %s matching new_id %s", old, new)
def get_new_uuid(self, old: str) -> str:
"""
Get the new UUID that replaces the old UUID.
:param old: The old UUID to be replaced.
:return: The new UUID if it exists, otherwise None.
"""
return self.uuids.get(old, "")
def add_replay(
self,
mist_step: Step,
scope_id: str,
object_id: str,
object_type: str,
data: dict,
) -> None:
"""
Add a request to the replay list.
:param create_mistapi_function: The function to create the object.
:param update_mistapi_function: The function to update the object.
:param scope_id: The scope ID where the object is located.
:param object_id: The ID of the object to be created or updated.
:param object_type: The type of the object (e.g., "wlans", "sites").
:param data: The data to be used for creating or updating the object.
"""
self.requests_to_replay.append(
{
"mist_step": mist_step,
"scope_id": scope_id,
"object_id": object_id,
"data": data,
"object_type": object_type,
"retry": 0,
}
)
def get_replay(self) -> list:
"""
Get the list of requests to replay.
:return: A list of requests to replay.
"""
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}"'
uuid_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}\""
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 = '("[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_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) -> tuple:
"""
Find and replace UUIDs in the given object.
:param obj: The object to process.
:param object_type: The type of the object (e.g., "wlans", "sites").
:return: A tuple containing the processed object and a list of missing UUIDs.
"""
# REMOVE READONLY FIELDS
ids_to_remove = [
"id",
"msp_id",
"org_id",
"site_id",
"site_ids",
"url",
"bg_image_url",
"portal_template_url",
"portal_sso_url",
"thumbnail_url",
"template_url",
"ui_url",
]
for id_name in ids_to_remove:
if not object_type == "webhooks" or not id_name == "url":
if id_name in obj:
del obj[id_name]
if "service_policies" in obj:
for service_policy in obj.get("service_policies", []):
if "id" in service_policy:
del service_policy["id"]
# 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)
if {'uuid': '00000000-0000-1000-8000-000000000000'} in missing_uuids:
missing_uuids.remove({'uuid': '00000000-0000-1000-8000-000000000000'})
if missing_uuids:
LOGGER.warning("find_and_replace: Object %s has missing UUIDs: %s", object_type, missing_uuids)
LOGGER.warning("find_and_replace: Object data: %s", obj_str)
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("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)
print()
def set_steps_total(self, steps_total: int) -> None:
"""
Set the total number of steps for the progress bar.
:param steps_total: The total number of steps
"""
self.steps_total = steps_total
def log_message(self, message, display_pbar: bool = True) -> None:
"""
Log a message in the progress bar.
:param message: The message to log
:param display_pbar: If True, the progress bar will be displayed after the message
"""
self._pb_new_step(message, " ", display_pbar=display_pbar)
def log_debug(self, message) -> None:
"""
Log a debug message.
:param message: The debug message to log
"""
LOGGER.debug(message)
def log_success(
self, message, inc: bool = False, display_pbar: bool = True
) -> None:
"""
Log a success message in the progress bar.
:param message: The success message to log
:param inc: If True, the step count will be incremented
:param display_pbar: If True, the progress bar will be displayed after the success
"""
LOGGER.info("%s: Success", message)
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
) -> None:
"""
Log a warning message in the progress bar.
:param message: The warning message to log
:param inc: If True, the step count will be incremented
:param display_pbar: If True, the progress bar will be displayed after the warning
"""
LOGGER.warning(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
) -> None:
"""
Log a failure message in the progress bar.
:param message: The failure message to log
:param inc: If True, the step count will be incremented
:param display_pbar: If True, the progress bar will be displayed after the failure
"""
LOGGER.error("%s: Failure", message)
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) -> None:
"""
Log a title message in the progress bar.
:param message: The title message to log
:param end: If True, the progress bar will not be displayed after the title
:param display_pbar: If True, the progress bar will be displayed after the title
"""
LOGGER.info(message)
self._pb_title(message, end=end, display_pbar=display_pbar)
PB = ProgressBar()
##########################################################################################
##########################################################################################
# DEPLOY FUNCTIONS
##########################################################################################
# COMMON FUNCTION
def _common_process(
apisession: mistapi.APISession,
scope_id: str,
data: list,
step: Step,
step_name: str,
merge_action: str,
):
LOGGER.debug(
"conf_deploy:_common_process: step_name %s, merge action: %s",
step_name,
merge_action,
)
step.load_existing_objects(apisession, scope_id)
for step_data in data:
create, object_to_deploy, _ = step.search_existing_object(
step_data, step_data[step.attr_name], merge_action
)
if object_to_deploy and create:
_common_deploy(
apisession,
step,
scope_id,
step_name,
object_to_deploy,
)
elif object_to_deploy:
_common_update(
apisession,
step,
scope_id,
object_to_deploy["id"],
step_name,
object_to_deploy,
)
else:
PB.steps_count += 1
def _common_deploy(
apisession: mistapi.APISession,
mist_step: Step,
scope_id: str,
object_type: str,
data: dict,
retry: bool = False,
) -> str:
LOGGER.debug("conf_deploy:_common_deploy")
if SYS_EXIT:
sys.exit(0)
if not mist_step.create_mistapi_function:
LOGGER.error(
"conf_deploy:_common_deploy: No create function provided for object type %s",
object_type,
)
return ""
old_id = None
new_id = ""
object_name = ""
if "name" in data:
object_name = f'"{data.get("name", "<unknown>")}"'
elif "ssid" in data:
object_name = f'"{data.get("ssid", "<unknown>")}"'
if "id" in data:
old_id = data["id"]
else:
old_id = None
if object_type == "evpn_topologies":
data["overwrite"] = True
message = f"Creating {object_type} {object_name}"
PB.log_message(message, display_pbar=False)
data, missing_uuids = UUID_MATCHING.find_and_replace(data, object_type)
try:
response = mist_step.create_mistapi_function(apisession, scope_id, data)
if response.status_code == 200:
new_id = response.data.get("id")
if not missing_uuids:
PB.log_success(message, display_pbar=False)
elif not retry:
UUID_MATCHING.add_replay(
mist_step,
scope_id,
new_id,
object_type,
data,
)
PB.log_warning(message, display_pbar=False)
else:
PB.log_failure(message, display_pbar=False)
except Exception:
PB.log_failure(message, display_pbar=False)
LOGGER.error("Exception occurred", exc_info=True)
UUID_MATCHING.add_uuid(new_id, old_id)
return new_id
def _common_update(
apisession: mistapi.APISession,
mist_step: Step,
scope_id: str,
object_id: str,
object_type: str,
data: dict,
) -> str | None:
LOGGER.debug("conf_deploy:_common_update")
if SYS_EXIT:
sys.exit(0)
old_id = None
new_id = None
object_name = ""
if "name" in data:
object_name = f'"{data.get("name", "<unknown>")}"'
elif "ssid" in data:
object_name = f'"{data.get("ssid", "<unknown>")}"'
if "id" in data:
old_id = data["id"]
else:
old_id = None
if object_type == "evpn_topologies":
data["overwrite"] = True
message = f"Updating {object_type} {object_name} (id: {object_id})"
PB.log_message(message, display_pbar=False)
data, _ = UUID_MATCHING.find_and_replace(data, object_type)
try:
if mist_step.update_mistapi_function is None:
LOGGER.error(
"conf_deploy:_common_update: No update function provided for object type %s",
object_type,
)
return None
if not object_id:
LOGGER.debug(
"conf_deploy:_common_update: Updating object type %s with scope_id %s and no object_id",
object_type,
scope_id,
)
response = mist_step.update_mistapi_function(
apisession, scope_id, data
)
else:
LOGGER.debug(
"conf_deploy:_common_update: Updating object type %s with scope_id %s and object_id %s",
object_type,
scope_id,
object_id,
)
response = mist_step.update_mistapi_function(
apisession, scope_id, object_id, data
)
if response.status_code == 200:
new_id = response.data.get("id")
PB.log_success(message, display_pbar=False)
else:
PB.log_failure(message, display_pbar=False)
except Exception:
PB.log_failure(message, display_pbar=False)
LOGGER.error("Exception occurred", exc_info=True)
UUID_MATCHING.add_uuid(new_id, old_id)
return new_id
##########################################################################################
# BULK IMPORT
def _bulk_import_process(
apisession: mistapi.APISession,
scope_id: str,
step_name: str,
step_data: dict,
step: Step,
) -> None:
if step_name == "psks" and step_data:
_import_psks(apisession, step.create_mistapi_function, scope_id, step_data)
elif step_name == "usermacs" and step_data:
_import_usermacs(apisession, step.create_mistapi_function, scope_id, step_data)
def _import_psks(
apisession: mistapi.APISession,
mistapi_function: Callable | None,
scope_id: str,
data: dict,
) -> None:
LOGGER.debug("conf_deploy:_import_psks")
if SYS_EXIT:
sys.exit(0)
if not mistapi_function:
LOGGER.error("conf_deploy:_import_psks: No import function provided for PSKs")
return None
message = "Importing PSKs"
PB.log_message(message, display_pbar=False)
try:
response = mistapi_function(apisession, scope_id, data)
if response.status_code == 200:
PB.log_success(message, display_pbar=False)
else:
PB.log_failure(message, display_pbar=False)
except Exception:
PB.log_failure(message, display_pbar=False)
LOGGER.error("Exception occurred", exc_info=True)
return None
def _import_usermacs(
apisession: mistapi.APISession,
mistapi_function: Callable | None,
scope_id: str,
data: dict,
) -> None:
LOGGER.debug("conf_deploy:_import_usermacs")
if SYS_EXIT:
sys.exit(0)
if not mistapi_function:
LOGGER.error(
"conf_deploy:_import_usermacs: No import function provided for User Macs"
)
return None
message = "Importing Usermacs "
PB.log_message(message, display_pbar=False)
try:
response = mistapi_function(apisession, scope_id, data)
if response.status_code == 200:
PB.log_success(message, display_pbar=False)
else:
PB.log_failure(message, display_pbar=False)
except Exception:
PB.log_failure(message, display_pbar=False)
LOGGER.error("Exception occurred", exc_info=True)
##########################################################################################
# WLAN FUNCTIONS
def _wlan_process(
apisession: mistapi.APISession,
scope_id: str,
old_scope_id: str,
data: list,
step: Step,
merge_action: str,
):
step.load_existing_objects(apisession, scope_id)
for step_data in data:
create, object_to_deploy, _ = step.search_existing_object(
step_data, step_data["ssid"], merge_action
)
if object_to_deploy and create:
_deploy_wlan(
apisession,
step,
scope_id,
object_to_deploy,
old_scope_id,
)
elif object_to_deploy:
_update_wlan(
apisession,
step,
scope_id,
object_to_deploy,
old_scope_id,
)
else:
PB.steps_count += 1
def _deploy_wlan(
apisession: mistapi.APISession,
mist_step: Step,
scope_id: str,
data: dict,
old_org_id: str,
old_site_id: str = "",
) -> None:
LOGGER.debug("conf_deploy:_deploy_wlan")
if SYS_EXIT:
sys.exit(0)
if not mist_step.create_mistapi_function:
LOGGER.error("conf_deploy:_deploy_wlan: No create function provided for WLANs")
return None
old_wlan_id = data["id"]
new_wlan_id = _common_deploy(
apisession,
mist_step,
scope_id,
"wlans",
data,
)
UUID_MATCHING.add_uuid(new_wlan_id, old_wlan_id)
_deploy_wlan_portal(
apisession,
old_org_id,
old_site_id,
old_wlan_id,
scope_id,
new_wlan_id,
data.get("ssid", "<unknown>"),
)
def _update_wlan(
apisession: mistapi.APISession,
mist_step: Step,
scope_id: str,
data: dict,
old_org_id: str,
old_site_id: str = "",
) -> None:
LOGGER.debug("conf_deploy:_deploy_wlan")
if SYS_EXIT:
sys.exit(0)
if not mist_step.create_mistapi_function:
LOGGER.error("conf_deploy:_deploy_wlan: No create function provided for WLANs")
return None
old_wlan_id = data["id"]
new_wlan_id = _common_update(
apisession,
mist_step,
scope_id,
old_wlan_id,
"wlans",
data,
)
_deploy_wlan_portal(
apisession,
old_org_id,
old_site_id,
old_wlan_id,
scope_id,
new_wlan_id,
data.get("ssid", "<unknown>"),
)
def _deploy_wlan_portal(
apisession: mistapi.APISession,
old_org_id: str,
old_site_id: str,
old_wlan_id: str,
scope_id: str,
new_wlan_id: str | None,
wlan_name: str,
) -> None:
LOGGER.debug("conf_deploy:_deploy_wlan_portal")
portal_file_name = ""
if SYS_EXIT:
sys.exit(0)
elif not old_site_id:
portal_file_name = f"{FILE_PREFIX}_wlan_{old_wlan_id}.json"
portal_image = f"{FILE_PREFIX}_wlan_{old_wlan_id}.png"
upload_image_function = mistapi.api.v1.orgs.wlans.uploadOrgWlanPortalImageFile
update_template_function = mistapi.api.v1.orgs.wlans.updateOrgWlanPortalTemplate
else:
portal_file_name = (
f"{FILE_PREFIX}_site_{old_site_id}_wlan_{old_wlan_id}.json"
)