-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlonghorny.py
executable file
·2121 lines (2016 loc) · 92.2 KB
/
longhorny.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/env python3
# -*- coding: utf-8 -*-
# sfc.py
###############################################################################
# Synopsis: #
# Longhorny manages SolidFire cluster and volume pairing/unpairing/reporting #
# #
# Author: @scaleoutSean #
# https://github.com/scaleoutsean/longhorny #
# License: the Apache License Version 2.0 #
###############################################################################
# References:
# 1) SolidFire API documentation:
# https://docs.netapp.com/us-en/element-software/api/
# 2) SolidFire Python SDK:
# https://solidfire-sdk-python.readthedocs.io/en/latest/index.html
# 3) NetApp Element Software Remote Replication - Feature Description and
# Deployment Guide (TR-4741):
# https://www.netapp.com/media/10607-tr4741.pdf
import time
import argparse
import ast
import datetime
import logging
import os
import pprint
from getpass import getpass
from solidfire.factory import ElementFactory
from solidfire import common
from solidfire.common import LOG
from solidfire.common import ApiServerError
from solidfire.common import SdkOperationError
common.setLogLevel(logging.ERROR)
def cluster(args):
if args.list:
pairing = report_cluster_pairing(src, dst)
print("\nCLUSTER (MUTUAL) PAIRING REPORT:\n")
pprint.pp(pairing)
elif args.pair:
pair_cluster(src, dst)
elif args.unpair:
unpair_cluster(src, dst)
else:
logging.warning(
"Cluster action not recognized. If this is unhandled, there may be a parsing bug or misconfiguration.")
return
def report_cluster_pairing(src: dict, dst: dict) -> dict:
"""
Print to console cluster pairing information between SRC and DST.
"""
pairing = get_cluster_pairing(src, dst)
if len(pairing[src['clusterName']]) == 0 and len(
pairing[dst['clusterName']]) == 0:
print("Neither cluster has existing cluster pairing relationship(s).")
logging.warning("Neither " +
str(src['clusterName']) +
" nor " +
str(dst['clusterName']) +
" has any cluster pairing relationships.")
elif len(pairing[src['clusterName']]) == 0 or len(pairing[dst['clusterName']]) == 0:
logging.warning("One of the clusters is not paired. Number of relationships (SRC/DST): " +
str(len(pairing[src['clusterName']])) + "/" + str(len(pairing[dst['clusterName']])) + ".")
else:
for site in pairing:
for i in pairing[site]:
if i['clusterPairUUID'] in [j['clusterPairUUID']
for j in pairing[site]]:
logging.info(
"Clusters are paired through clusterPairUUID " + str(i['clusterPairUUID']) + ".")
else:
logging.warning(
"Clusters have pairing relationships but are not mutually paired. Foreign relationship: " +
str(
i['clusterPairUUID']) +
".")
return (pairing)
def get_cluster_pairing(src: dict, dst: dict) -> dict:
"""
Return dict with per-site cluster pairings on both clusters.
May return several or no pairing relationships for each cluster, including with other clusters.
"""
pairing = {}
for site in src, dst:
logging.info("Querying site: " + str(site['mvip']) + ".")
try:
r = site['sfe'].list_cluster_pairs().to_json()['clusterPairs']
logging.info(
"Result for site: " +
site['mvip'] +
" : ",
str(r) +
".")
pairing[site['clusterName']] = r
except common.ApiServerError as e:
logging.error(
"Error listing cluster pairs for cluster: " + str(site['clusterName']) + ".")
logging.error("Error: " + str(e))
exit(100)
return pairing
def get_exclusive_cluster_pairing(src: dict, dst: dict) -> dict:
"""
Return dict with 1-to-1 pairing relationships between SRC and DST clusters if and only if that one cluster paring relationship exists.
"""
pairing = get_cluster_pairing(src, dst)
if not len(pairing[src['clusterName']]) == 1 and not len(
pairing[dst['clusterName']]) == 1:
logging.warning("Number of cluster pair relationships (SRC/DST): " +
str(len(pairing[src['clusterName']])) + "/" + str(len(pairing[dst['clusterName']])) + ".")
return {}
else:
for site in pairing:
for i in pairing[site]:
if i['clusterPairUUID'] in [j['clusterPairUUID']
for j in pairing[site]]:
logging.info(
"Clusters are paired through clusterPairUUID " + str(i['clusterPairUUID']) + ".")
else:
logging.warning(
"Clusters have pairing relationships but are not mutually paired. Foreign relationship: " +
str(
i['clusterPairUUID']) +
".")
return pairing
def pair_cluster(src: dict, dst: dict):
"""
Pair SRC and DST clusters.
Works only if each cluster has no existing cluster pairing relationships.
"""
pairing = get_cluster_pairing(src, dst)
if pairing[src['clusterName']] == [] and pairing[dst['clusterName']] == []:
try:
pairing_key = src['sfe'].start_cluster_pairing().to_json()[
'clusterPairingKey']
resp = dst['sfe'].complete_cluster_pairing(pairing_key).to_json()
if isinstance(resp['clusterPairID'], int):
logging.info("Pairing is now complete. Cluster " +
src['clusterName'] +
"returned cluster pair ID " +
str(resp['clusterPairID']) +
".")
except common.ApiServerError as e:
logging.error("Error: Unable to pair clusters: " + str(e))
exit(100)
exclusive_pairing = get_exclusive_cluster_pairing(src, dst)
print("\nCLUSTER PAIRING STATUS AFTER PAIRING:\n")
pprint.pp(exclusive_pairing)
return
else:
logging.warning(
"Clusters are already paired, paired with more than one cluster or in an incomplete pairing state. Use cluster --list to view current status. Exiting.")
exit(100)
def unpair_cluster(src: dict, dst: dict):
"""
Unpair clusters identified by SRC and DST.
Requires that each cluster is not paired or has no more than one cluster pairing relationship.
"""
pairing = get_exclusive_cluster_pairing(src, dst)
if pairing == {}:
logging.error(
"Clusters are not paired, in an incomplete pairing state or there is some other problem. Use cluster --list to view current status.")
exit(100)
cluster_pair_ids = []
for site in src, dst:
try:
resp = site['sfe'].list_cluster_pairs().to_json()['clusterPairs']
cluster_pair_ids.append(
(site['clusterName'], resp[0]['clusterPairID']))
except common.ApiServerError as e:
logging.error("Error: Unable to list cluster pairs: " + str(e))
logging.error("Error: " + str(e))
exit(100)
volume_relationships_check = list_volume(src, dst, [])
if len(volume_relationships_check) > 0 or volume_relationships_check != []:
logging.error(
"One or both clusters are already have paired volumes. Please unpair all paired volumes first.")
exit(100)
if len(resp) == 0 or len(resp) > 1:
logging.error(
"Zero or more than one cluster pairs found. Cluster unpairing action requires a 1-to-1 mutual and exclusive relationship. Exiting.")
exit(100)
else:
for site_id_tuple in cluster_pair_ids:
if site_id_tuple[0] == src['clusterName']:
site = src
try:
resp = site['sfe'].remove_cluster_pair(
site_id_tuple[1]).to_json()
except common.ApiServerError as e:
logging.error(
"Error: Unable to unpair clusters: " + str(e))
exit(100)
else:
site = dst
try:
resp = site['sfe'].remove_cluster_pair(
site_id_tuple[1]).to_json()
except common.ApiServerError as e:
logging.error(
"Error: Unable to unpair clusters: " + str(e))
exit(100)
exclusive_pairing = get_exclusive_cluster_pairing(src, dst)
print("\nCLUSTER PAIRING STATUS AFTER UNPAIRING:\n")
pprint.pp(exclusive_pairing)
return
def volume(args):
if args.list:
try:
try:
volume_pair = data_type(args.data)
logging.info(
"Data provided for listing volumes. Querying pair: " +
str(volume_pair) +
" for pairing status.")
except BaseException:
volume_pair = []
logging.info(
"Trying to list volumes in list " +
str(volume_pair) +
" for pairing status.")
list_volume(src, dst, volume_pair)
except Exception as e:
logging.error("Error: " + str(e))
exit(200)
elif args.report:
try:
if args.data is None or args.data == '':
logging.error(
"No data provided for volume report customization. Using default value: [].")
report_data = {}
else:
report_data = {}
pass
report_volume_replication_status(src, dst, report_data)
except Exception as e:
logging.error("Error: " + str(e))
exit(200)
elif args.pair:
pair_data = data_type(args.data)
pair_volume(src, dst, pair_data)
elif args.unpair:
try:
data = data_type(args.data)
except BaseException:
logging.error(
"Error: Unpair data missing or not understood. Presently only one pair is supported per unpair action, ex: --data '1,2'. Exiting.")
exit(200)
if data is None or data == []:
logging.error(
"No data found for unpairing. By default, unpair action unpairs nothing rather than everything. Exiting.")
exit(200)
unpair_volume(src, dst, data)
elif args.prime_dst:
av_data = account_volume_data(args.data)
prime_destination_volumes(src, dst, av_data)
elif args.reverse:
reverse_replication(src, dst)
elif args.snapshot:
if args.data is None or args.data == '':
logging.info(
"No data input provided. Using default values: 168,long168h-snap.")
data = '168;long168h-snap'
else:
data = args.data
snap_data = snapshot_data(data)
snapshot_site(src, dst, snap_data)
elif args.mismatched:
list_mismatched_pairs(src, dst)
elif args.set_mode:
if args.data is None:
logging.error(
"Replication takes two inputs; the mode and one or more volume IDs from the replication source (e.g. --data 'Async;100,101)'. Exiting.")
exit(200)
else:
volume_mode = replication_data(args.data)
logging.info("Desired replication type: " +
str(volume_mode[0]) +
" for volume ID(s)" +
str(volume_mode[1]) +
".")
set_volume_replication_mode(src, dst, volume_mode)
elif args.set_status:
if args.data is None:
logging.error(
"Replication state must be specified. Use --data 'pause' or --data 'resume'. Exiting.")
exit(200)
else:
state = replication_state(args.data)
if state == 'pause' or state == 'resume':
logging.info("Desired replication state: " + state)
set_volume_replication_state(src, dst, state)
elif args.resize:
if args.data is None:
logging.error(
"Volume resize action requires volume size and volume ID. Use --data '1073741824;100,200' to grow 100 and 200 by 1Gi. Exiting.")
exit(200)
else:
data = increase_volume_size_data(args.data)
increase_size_of_paired_volumes(src, dst, data)
elif args.upsize_remote:
if args.data is None:
logging.error(
"Remote volume resize action requires volume IDs of a SRC/DST pair. Use --data '100,200' to grow DST/200 to the size of SRC/100. Exiting.")
exit(200)
else:
data = upsize_remote_volume_data(args.data)
upsize_remote_volume(src, dst, data)
else:
logging.warning("Volume action not recognized.")
return
def report_volume_replication_status(
src: dict, dst: dict, report_data: dict) -> dict:
"""
Print out volume replication report in dictionary format.
"""
print(
"TODO: report_volume_replication_status using report_data: " +
str(report_data))
return
def snapshot_site(src: dict, dst: dict, snap_data: list) -> dict:
"""
Create local crash-consistent snapshot for all individual volumes using paired volumes on SRC.
"""
logging.warning("NOTE: If you have applications that span multiple volumes, you may need to create a dedicated group snapshot for those volumes because you may want to restore those as a group.")
logging.warning(
"Taking individual snapshots at SRC using params: " +
str(snap_data))
paired_volumes = list_volume(src, dst, [])
if paired_volumes == []:
logging.error(
"No paired volumes found. Ensure volumes are paired before taking a snapshot.")
exit(200)
snapshot_retention = str(snap_data[0]) + ':00:00' # "HH:MM:SS"
snapshot_name = snap_data[1]
for v in paired_volumes:
try:
r = src['sfe'].create_snapshot(
v['localVolumeID'], retention=snapshot_retention, name=snapshot_name).to_json()['snapshot']
snap_meta = "volume ID: " + str(r['volumeID']) + ", snapshot ID: " + str(
r['snapshotID']) + ", snapshot name: " + str(r['name']) + ", expiration time" + str(r['expirationTime'])
logging.info("Snapshot created for volume ID " +
str(v['localVolumeID']) + ": " + snap_meta)
except common.ApiServerError as e:
logging.error(
"Error creating snapshot for volume ID " +
str(v['localVolumeID']) +
".")
logging.error("Error: " + str(e))
exit(200)
return
def upsize_remote_volume(src: dict, dst: dict, data: list):
"""
Increase size of DST volume to match the size of SRC volume.
The main use case for upsizing just the remote paired volume is Trident CSI generally increases only the size of the source volume, leaving the remote volume smaller.
This function allows the destination volume to be increased to match the source volume and replication to continue.
As the volumes are mismatched to begin with, the function does not check multiple volume pairing details - it simply increases the size of the paired destination volume to match the source volume.
"""
logging.info("Attempting to grow paired DST volume ID " +
str(data[1]) + " to size of SRC volume ID " + str(data[0]) + ".")
src_vol_params = {
'isPaired': True,
'volumeStatus': 'active',
'includeVirtualVolumes': False,
'volumeIDs': [
data[0]]}
dst_vol_params = {
'isPaired': True,
'volumeStatus': 'active',
'includeVirtualVolumes': False,
'volumeIDs': [
data[1]]}
src_vol = src['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=src_vol_params)
dst_vol = dst['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=dst_vol_params)
if src_vol['volumes'] == [] or dst_vol['volumes'] == []:
logging.error("Volume ID " +
str(data[0]) +
" and/or " +
str(data[1]) +
" not found on SRC or DST cluster, respectively. Exiting.")
exit(200)
else:
logging.info("Volumes found: SRC volume ID " +
str(data[0]) + " and DST volume ID " + str(data[1]) + ".")
src_vol_mode = src_vol['volumes'][0]['access']
dst_vol_mode = dst_vol['volumes'][0]['access']
src_vol_total_size = src_vol['volumes'][0]['totalSize']
dst_vol_total_size = dst_vol['volumes'][0]['totalSize']
if not dst_vol_total_size < src_vol_total_size:
logging.error("SRC volume ID " +
str(data[0]) +
" must be larger than DST volume ID " +
str(data[1][1]) +
" for this action to work. Exiting.")
exit(200)
try:
pause_params = {'volumeID': data[0], 'pausedManual': True}
src['sfe'].invoke_sfapi(
method='ModifyVolumePair',
parameters=pause_params)
logging.info("Paused replication for SRC volume ID " +
str(data[0]) + ".")
except BaseException:
logging.error(
"Error pausing replication for SRC volume ID " + str(data[0]) + ".")
exit(200)
try:
r = dst['sfe'].modify_volume(data[1], total_size=src_vol_total_size)
logging.info("Increased size of DST volume ID " +
str(data[1]) + " to " + str(src_vol_total_size) + " bytes.")
except Exception as e:
logging.error(
"Error increasing size of DST volume ID " +
str(
data[1]) +
" to " +
str(src_vol_total_size) +
" bytes. Please manually resize the DST volume. You may use volume --mismatched to view. Exiting.\n" +
str(e))
exit(200)
resume_params = {'volumeID': data[0], 'pausedManual': False}
try:
logging.info(
"Will resume replication for the pair if SRC is readWrite and DST replicationTarget.")
if src_vol_mode == 'readWrite' and dst_vol_mode == 'replicationTarget':
r = src['sfe'].invoke_sfapi(
method='ModifyVolumePair',
parameters=resume_params)
logging.info(
"Resumed replication for volume pair on SRC volume ID " + str(data[0]) + ".")
else:
logging.warning("Volume ID " +
str(data[0]) +
" is in mode " +
str(src_vol_mode) +
" and paired with volume ID " +
str(data[1]) +
" in mode " +
str(dst_vol_mode) +
". Skipping attempt to resume replication.")
except BaseException:
logging.error(
"Error resuming replication for volume ID " +
str(
data[0]) +
". The volumes should be resized but replication is still paused. Try manually resuming. Exiting.")
exit(200)
try:
src_vol_final = src['sfe'].invoke_sfapi(
method='ListVolumes', parameters=src_vol_params)
dst_vol_final = dst['sfe'].invoke_sfapi(
method='ListVolumes', parameters=dst_vol_params)
except Exception as e:
logging.error(
"Error listing volumes after DST volume resizing. Exiting.\n" +
str(e))
exit(200)
src_vol_details = {
'volumeID': src_vol_final['volumes'][0]['volumeID'],
'name': src_vol_final['volumes'][0]['name'],
'totalSize': src_vol_final['volumes'][0]['totalSize'],
'access': src_vol_final['volumes'][0]['access'],
'state': src_vol_final['volumes'][0]['volumePairs'][0]['remoteReplication']['state'],
'volumePairs': src_vol_final['volumes'][0]['volumePairs'][0]['remoteVolumeID']
}
dst_vol_details = {
'volumeID': dst_vol_final['volumes'][0]['volumeID'],
'name': dst_vol_final['volumes'][0]['name'],
'totalSize': dst_vol_final['volumes'][0]['totalSize'],
'access': dst_vol_final['volumes'][0]['access'],
'volumePairs': dst_vol_final['volumes'][0]['volumePairs'][0]['remoteVolumeID']
}
if src_vol_details['totalSize'] == dst_vol_details['totalSize']:
logging.info("Volume ID " +
str(data[0]) +
" and " +
str(data[1]) +
" have been successfully resized to " +
str(src_vol_details['totalSize']) +
" bytes. (" +
str(round(src_vol_details['totalSize'] /
(1024 *
1024 *
1024), 2)) +
" GiB).")
else:
logging.error("Volume ID " +
str(data[0]) +
" and " +
str(data[1]) +
" have not been resized to " +
str(src_vol_details['totalSize']) +
" bytes. Use volumes --mismatch to find what happened. Exiting.")
exit(200)
resize_action_report = [src_vol_details, dst_vol_details]
print("\nUPSIZE REMOTE VOLUME ACTION REPORT:\n")
pprint.pp(resize_action_report)
return
def increase_size_of_paired_volumes(src: dict, dst: dict, data: list):
"""
Increase size of paired volumes on SRC and DST clusters by the byte amount specified in the data field.
volume --grow --data='1073741824;100,200' means grow 100 and 200 by 1Gi.
This function first uses ListVolumes to confirm the source (volume ID) exists in readWrite access mode and is paired with a volume on the destination cluster.
"""
logging.info("Attempting to grow paired volumes SRC volume ID " +
str(data[1][0]) +
" and DST volume ID " +
str(data[1][1]) +
" by " +
str(data[0]) +
" bytes.")
src_vol_params = {
'isPaired': True,
'volumeStatus': 'active',
'includeVirtualVolumes': False,
'volumeIDs': [
data[1][0]]}
dst_vol_params = {
'isPaired': True,
'volumeStatus': 'active',
'includeVirtualVolumes': False,
'volumeIDs': [
data[1][1]]}
src_vol = src['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=src_vol_params)
dst_vol = dst['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=dst_vol_params)
if src_vol['volumes'] == [] or dst_vol['volumes'] == []:
logging.error("Volume ID " +
str(data[1][0]) +
" and/or " +
str(data[1][1]) +
" not found on SRC or DST cluster, respectively. Exiting.")
exit(200)
else:
logging.info("Volumes found: SRC volume ID " +
str(data[1][0]) +
" and DST volume ID " +
str(data[1][1]) +
".")
src_vol_mode = src_vol['volumes'][0]['access']
dst_vol_mode = dst_vol['volumes'][0]['access']
src_vol_total_size = src_vol['volumes'][0]['totalSize']
dst_vol_total_size = dst_vol['volumes'][0]['totalSize']
if src_vol_total_size != dst_vol_total_size:
logging.warning("SRC volume ID " +
str(data[1][0]) +
" and DST volume ID " +
str(data[1][1]) +
" are not the same size. Exiting.")
exit(200)
if data[0] > (src_vol_total_size * 2):
logging.error("SRC volume ID " +
str(data[0]) +
" would be increased by " +
str(data[0]) +
" bytes, which is more than twice its current size of " +
str(src_vol_total_size) +
" bytes. To avoid mistakes, this function cannot increase volume size by either more than 2x or 1 TiB at a time. Exiting.")
exit(200)
new_total_size = data[0] + src_vol_total_size
if new_total_size > 17592186044416:
logging.error("Volumes SRC/" +
str(data[1][0]) +
", and DST/" +
str(data[1][1]) +
" would be increased to " +
str(new_total_size) +
" bytes, which is more than the SolidFire maximum volume size of 16 TiB. Exiting.")
exit(200)
# NOTE: we user src volume's pairing configuration and status to determine
# if replication is paused or not
dst_vol_replication_state = src_vol['volumes'][0]['volumePairs'][0]['remoteReplication']['state']
dst_vol_id = src_vol['volumes'][0]['volumePairs'][0]['remoteVolumeID']
if src_vol_mode != 'readWrite' or dst_vol_id != data[1][1] or dst_vol_mode != 'replicationTarget':
logging.error("Volume ID " +
str(data[1][0]) +
" is in mode " +
str(src_vol_mode) +
" and paired with volume ID " +
str(dst_vol_id) +
" with replication state " +
str(dst_vol_replication_state) +
".")
exit(200)
else:
logging.info("Volume ID " +
str(data[1][0]) +
" is in " +
str(src_vol_mode) +
" mode, paired with " +
str(dst_vol_id) +
" in replication state " +
str(dst_vol_replication_state) +
". Continuing.")
try:
pause_params = {'volumeID': data[1][0], 'pausedManual': True}
src['sfe'].invoke_sfapi(
method='ModifyVolumePair',
parameters=pause_params)
logging.info("Paused replication for SRC volume ID " +
str(data[1][0]) + ".")
except BaseException:
logging.error(
"Error pausing replication for SRC volume ID " + str(data[1][0]) + ".")
exit(200)
try:
r = dst['sfe'].modify_volume(data[1][1], total_size=new_total_size)
logging.info("Increased size of DST volume ID " +
str(data[1][0]) + " to " + str(data[0]) + " bytes.")
except Exception as e:
logging.error("Error increasing size of DST volume ID " +
str(data[1][1]) +
" to " +
str(data[0]) +
" bytes. Please manually resize the DST volume. You may use volume --mismatched to view. Exiting.\n" +
str(e))
exit(200)
try:
logging.info("Size of the destination volume has been increased.")
r = src['sfe'].modify_volume(data[1][0], total_size=new_total_size)
logging.info("Increased size of SRC volume ID " +
str(data[1][0]) + " to " + str(new_total_size) + " bytes.")
except Exception as e:
logging.error(
"Error increasing size of volume " +
str(
data[1][0]) +
" to " +
str(new_total_size) +
" bytes. Please manually resize the SRC volume and set replication to resume. You may use volume --mismatched to view. Exiting.\n" +
str(e))
exit(200)
resume_params = {'volumeID': data[1][0], 'pausedManual': True}
try:
logging.info("Resuming replication for volume pair.")
r = src['sfe'].invoke_sfapi(
method='ModifyVolumePair',
parameters=resume_params)
logging.info(
"Resumed replication for volume pair on SRC volume ID " + str(data[1][0]) + ".")
except BaseException:
logging.error(
"Error resuming replication for volume ID " +
str(
data[1][0]) +
". The volumes should be resized but replication is still paused. Try manually resuming. Exiting.")
exit(200)
try:
src_vol_final = src['sfe'].invoke_sfapi(
method='ListVolumes', parameters=src_vol_params)
dst_vol_final = dst['sfe'].invoke_sfapi(
method='ListVolumes', parameters=dst_vol_params)
except Exception as e:
logging.error(
"Error listing volumes after resizing. Exiting.\n" +
str(e))
exit(200)
src_vol_details = {
'volumeID': src_vol_final['volumes'][0]['volumeID'],
'name': src_vol_final['volumes'][0]['name'],
'totalSize': src_vol_final['volumes'][0]['totalSize'],
'access': src_vol_final['volumes'][0]['access'],
'state': src_vol_final['volumes'][0]['volumePairs'][0]['remoteReplication']['state'],
'volumePairs': src_vol_final['volumes'][0]['volumePairs'][0]['remoteVolumeID']
}
dst_vol_details = {
'volumeID': dst_vol_final['volumes'][0]['volumeID'],
'name': dst_vol_final['volumes'][0]['name'],
'totalSize': dst_vol_final['volumes'][0]['totalSize'],
'access': dst_vol_final['volumes'][0]['access'],
'volumePairs': dst_vol_final['volumes'][0]['volumePairs'][0]['remoteVolumeID']
}
if src_vol_details['totalSize'] == dst_vol_details['totalSize']:
logging.info("Volume ID " +
str(data[1][0]) +
" and " +
str(data[1][1]) +
" have been successfully resized to " +
str(src_vol_details['totalSize']) +
" bytes. (" +
str(round(src_vol_details['totalSize'] /
(1024 *
1024 *
1024), 2)) +
" GiB).")
else:
logging.error("Volume ID " +
str(data[1][0]) +
" and " +
str(data[1][1]) +
" have not been resized to " +
str(src_vol_details['totalSize']) +
" bytes. Use volumes --mismatch to find what happened. Exiting.")
exit(200)
resize_action_report = [src_vol_details, dst_vol_details]
print("\nRESIZE ACTION REPORT:\n")
pprint.pp(resize_action_report)
return
def list_mismatched_pairs(src: dict, dst: dict) -> dict:
"""
List mismatched volume pairs.
Mismatched pairs are those for which there's a unilateral pairing, volume sizes do not match or something else appears wrong.
"""
params = {'isPaired': True}
existing_pairs = {}
src_pairs = src['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=params)['volumes']
dst_pairs = dst['sfe'].invoke_sfapi(
method='ListVolumes',
parameters=params)['volumes']
src_ids = [(i['volumeID'], i['volumePairs'][0]['remoteVolumeID'])
for i in src_pairs]
dst_ids = [(i['volumeID'], i['volumePairs'][0]['remoteVolumeID'])
for i in dst_pairs]
if len(src_ids) != len(dst_ids):
logging.warning("SRC and DST have different number of volume pairings at SRC/DST: " +
str(len(src_ids)) + "/" + str(len(dst_ids)) + ".")
src_account_ids = [(i['volumeID'], i['accountID']) for i in src_pairs]
dst_account_ids = [(i['volumeID'], i['accountID']) for i in dst_pairs]
if len(set([i[1] for i in src_account_ids])) > 1:
logging.warning("Multiple account IDs found on paired volumes at SRC: " +
str(len(set([i[1] for i in src_account_ids]))) + ".")
if len(set([i[1] for i in dst_account_ids])) > 1:
logging.warning("Multiple account IDs found on paired volumes at DST: " +
str(len(set([i[1] for i in dst_account_ids]))) + ".")
mismatch = []
for p in src_ids:
pr = (p[1], p[0])
if pr not in dst_ids:
logging.warning("Volume ID " +
str(p[0]) +
" is paired on SRC but not on DST cluster.")
for p in dst_ids:
pr = (p[1], p[0])
if pr not in src_ids:
logging.warning("Volume ID " +
str(p[0]) +
" is paired on DST but not on SRC cluster.")
if len(src_ids) == 0 and len(dst_ids) == 0:
logging.warning("No volumes found on one or both sides.")
return
elif len(src_ids) == 0 or len(dst_ids) == 0:
logging.warning(
"One or both sides have no paired volumes. Number of paired volumes at SRC/DST:" +
len(src_ids) +
"/" +
len(dst_ids) +
".")
return
else:
site_pairs = {}
s_list = []
for pair in src_pairs:
kvs = {
'accountID': pair['accountID'],
'volumeID': pair['volumeID'],
'name': pair['name'],
'deleteTime': pair['deleteTime'],
'purgeTime': pair['purgeTime'],
'totalSize': pair['totalSize'],
'enable512e': pair['enable512e'],
'volumePairUUID': pair['volumePairs'][0]['volumePairUUID'],
'remoteVolumeID': pair['volumePairs'][0]['remoteVolumeID'],
'remoteVolumeName': pair['volumePairs'][0]['remoteVolumeName']
}
if 'qos' in pair.keys():
qos = pair['qos']
pair['qos'] = qos
else:
qos_policy_id = pair['qosPolicyID']
pair['qosPolicyID'] = qos_policy_id
s_list.append(kvs)
site_pairs[src['clusterName']] = s_list
d_list = []
for pair in dst_pairs:
kvs = {
'accountID': pair['accountID'],
'volumeID': pair['volumeID'],
'name': pair['name'],
'deleteTime': pair['deleteTime'],
'purgeTime': pair['purgeTime'],
'totalSize': pair['totalSize'],
'enable512e': pair['enable512e'],
'volumePairUUID': pair['volumePairs'][0]['volumePairUUID'],
'remoteVolumeID': pair['volumePairs'][0]['remoteVolumeID'],
'remoteVolumeName': pair['volumePairs'][0]['remoteVolumeName']
}
if 'qos' in pair.keys():
pair['qos'] = qos
else:
qos_policy_id = pair['qosPolicyID']
pair['qosPolicyID'] = qos_policy_id
d_list.append(kvs)
site_pairs[dst['clusterName']] = d_list
unique = []
for i in site_pairs[src['clusterName']]:
mismatch = {}
if i['volumePairUUID'] not in (
j['volumePairUUID'] for j in site_pairs[dst['clusterName']]):
mismatch[src['clusterName']] = {
'volumeID': i['volumeID'],
'volumePairUUID': i['volumePairUUID'],
'volumePairUUID': i['volumePairUUID'],
'mismatchSite': dst['clusterName'],
'remoteVolumeID': i['remoteVolumeID']}
logging.warning("Mismatch found at SRC: vol ID " +
str(i['volumeID']) +
" in relationship " +
str(i['volumePairUUID']) +
" found at SRC, but relationship from paired SRC volume ID is missing: " +
str(i['remoteVolumeID']) +
".")
unique.append(mismatch)
else:
pass
for i in site_pairs[dst['clusterName']]:
mismatch = {}
if i['volumePairUUID'] not in (
j['volumePairUUID'] for j in site_pairs[src['clusterName']]):
mismatch[dst['clusterName']] = {
'volumeID': i['volumeID'],
'volumePairUUID': i['volumePairUUID'],
'remoteSite': src['clusterName'],
'remoteVolumeID': i['remoteVolumeID']}
logging.warning("Mismatch found at DST: vol ID " +
str(i['volumeID']) +
" in relationship " +
str(i['volumePairUUID']) +
" found at SRC, but relationship from paired SRC volume ID is missing: " +
str(i['remoteVolumeID']) +
".")
unique.append(mismatch)
else:
pass
print("\nMISMATCHED PAIRED VOLUMES ONLY:\n")
pprint.pp(unique)
return
def prime_destination_volumes(src, dst, data):
"""
Creates volumes on DST cluster for specified account, with volume properties based on list of Volume IDs from SRC but set to replicationTarget mode.
Takes a two inputs, the first of which is a pair of SRC and DST account IDs and the second is a list of volume IDs (VOL1, VOL2) to use as templates at the remote site.
"""
try:
try:
src_account_vols = src['sfe'].list_volumes_for_account(data[0][0]).to_json()[
'volumes']
except BaseException:
logging.error(
"Error getting account volumes for source site account ID: " +
str(
data[0][0]) +
". Make sure the account ID exists. Exiting.")
exit(200)
# list of SRC Volume IDs to be used as templates
src_vid = [i for i in data[1]]
for v in src_account_vols:
if v['volumeID'] in src_vid:
logging.info("Volume ID " + str(v['volumeID']) + " found to belong to account ID " + str(
data[0][0]) + ". Checking the volume for existing replication relationships (must be none).")
if 'volumePairs' in v.keys() and v['volumePairs'] != []:
logging.error("Error: Volume ID " +
str(v['volumeID']) +
" has replication relationships. Volumes used for priming must not be already paired. Exiting.")
exit(200)
except BaseException:
logging.error(
"Error getting account volumes for account ID: " +
str(
data[0][0]) +
". All of the SRC volume IDs must be owned by the specific SRC account ID. Exiting.")
exit(200)
src_volumes = []
for v in src_account_vols:
if v['volumeID'] in src_vid: # skip volumes not in the DATA list of volume IDs
if 'qos' in v.keys():
src_volume = {
'volumeID': v['volumeID'],
'enable512e': v['enable512e'],
'fifoSize': v['fifoSize'],
'minFifoSize': v['minFifoSize'],
'name': v['name'],
'qos': v['qos'],
'totalSize': v['totalSize']}
else:
src_volume = {
'volumeID': v['volumeID'],
'enable512e': v['enable512e'],
'fifoSize': v['fifoSize'],
'minFifoSize': v['minFifoSize'],
'name': v['name'],
'qosPolicyID': v['qosPolicyID'],
'totalSize': v['totalSize']}
src_volumes.append(src_volume)
logging.warning(
"SRC volumes to be used as template for volume creation on DST cluster:")
pprint.pp(src_volumes)
try:
dst_account_id = dst['sfe'].get_account_by_id(data[0][1]).to_json()[
'account']['accountID']
if dst_account_id == data[0][1]:
print("DST account exists (DATA vs API response): " +
str(data[0][1]) + "," + str(dst_account_id) + ".")
logging.info("DST account exists (DATA vs API response): " +
str(data[0][1]) + "," + str(dst_account_id) + ".")
except BaseException:
logging.error("DST account ID " +
str(data[0][1]) +
" does not exist or cannot be queried. Exiting.")
exit(200)
dst_volumes = []
for v in src_volumes:
if 'qos' in v.keys():
params = {
'accountID': dst_account_id,
'name': v['name'],
'totalSize': v['totalSize'],
'enable512e': v['enable512e'],
'qos': v['qos'],
'fifoSize': v['fifoSize'],
'minFifoSize': v['minFifoSize']}
else:
print(
"QoS not found in volume properties. Using qosPolicyID instead:",
v['qosPolicyID'])
params = {
'accountID': dst_account_id,
'name': v['name'],
'totalSize': v['totalSize'],
'enable512e': v['enable512e'],
'qosPolicyID': v['qos'],
'fifoSize': v['fifoSize'],
'minFifoSize': v['minFifoSize']}
try:
logging.info(
"Creating volume on DST cluster using params: " +
str(params) +
".")
dst_volume = dst['sfe'].invoke_sfapi(
method='CreateVolume', parameters=params)
dst_volumes.append(
(v['volumeID'], dst_volume['volume']['volumeID']))
except ApiServerError as e:
logging.error("Error creating volume on DST cluster: " + str(e))
exit(200)
try:
if len(dst_volumes) < 500:
logging.info(
"Less than 500 volumes to be modified. Using the bulk volume modification API.")
r = dst['sfe'].modify_volumes(
[i[1] for i in dst_volumes], access='replicationTarget')
else:
logging.info(
"More than 500 volumes to be modified. Using the individual volume modification API. Inspect DST for correctness before pairing.")
for i in dst_volumes:
try:
r = dst['sfe'].modify_volume(
i[1], access='replicationTarget')