summaryrefslogtreecommitdiffstats
path: root/ansible_collections/dellemc/powerflex/plugins/modules/volume.py
blob: 0fc301831683b2d1a25b67ba7d9443435710e574 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
#!/usr/bin/python

# Copyright: (c) 2021, Dell Technologies
# Apache License version 2.0 (see MODULE-LICENSE or http://www.apache.org/licenses/LICENSE-2.0.txt)

""" Ansible module for managing volumes on Dell Technologies (Dell) PowerFlex"""

from __future__ import (absolute_import, division, print_function)

__metaclass__ = type

DOCUMENTATION = r'''
module: volume
version_added: '1.0.0'
short_description: Manage volumes on Dell PowerFlex
description:
- Managing volumes on PowerFlex storage system includes
  creating, getting details, modifying attributes and deleting volume.
- It also includes adding/removing snapshot policy,
  mapping/unmapping volume to/from SDC and listing
  associated snapshots.
author:
- P Srinivas Rao (@srinivas-rao5) <ansible.team@dell.com>
extends_documentation_fragment:
  - dellemc.powerflex.powerflex
options:
  vol_name:
    description:
    - The name of the volume.
    - Mandatory for create operation.
    - It is unique across the PowerFlex array.
    - Mutually exclusive with I(vol_id).
    type: str
  vol_id:
    description:
    - The ID of the volume.
    - Except create operation, all other operations can be performed
      using I(vol_id).
    - Mutually exclusive with I(vol_name).
    type: str
  storage_pool_name:
    description:
    - The name of the storage pool.
    - Either name or the id of the storage pool is required for creating a
      volume.
    - During creation, if storage pool name is provided then either
      protection domain name or id must be mentioned along with it.
    - Mutually exclusive with I(storage_pool_id).
    type: str
  storage_pool_id:
    description:
    - The ID of the storage pool.
    - Either name or the id of the storage pool is required for creating
      a volume.
    - Mutually exclusive with I(storage_pool_name).
    type: str
  protection_domain_name:
    description:
    - The name of the protection domain.
    - During creation of a volume, if more than one storage pool exists with
      the same name then either protection domain name or id must be
      mentioned along with it.
    - Mutually exclusive with I(protection_domain_id).
    type: str
  protection_domain_id:
    description:
    - The ID of the protection domain.
    - During creation of a volume, if more than one storage pool exists with
      the same name then either protection domain name or id must be
      mentioned along with it.
    - Mutually exclusive with I(protection_domain_name).
    type: str
  vol_type:
    description:
    - Type of volume provisioning.
    choices: ["THICK_PROVISIONED", "THIN_PROVISIONED"]
    type: str
  compression_type:
    description:
    - Type of the compression method.
    choices: ["NORMAL", "NONE"]
    type: str
  use_rmcache:
    description:
    - Whether to use RM Cache or not.
    type: bool
  snapshot_policy_name:
    description:
    - Name of the snapshot policy.
    - To remove/detach snapshot policy, empty
      I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
      I(auto_snap_remove_type).
    type: str
  snapshot_policy_id:
    description:
    - ID of the snapshot policy.
    - To remove/detach snapshot policy, empty
      I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
      I(auto_snap_remove_type).
    type: str
  auto_snap_remove_type:
    description:
    - Whether to remove or detach the snapshot policy.
    - To remove/detach snapshot policy, empty
      I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
      I(auto_snap_remove_type).
    - If the snapshot policy name/id is passed empty then
      I(auto_snap_remove_type) is defaulted to C(detach).
    choices: ['remove', 'detach']
    type: str
  size:
    description:
    - The size of the volume.
    - Size of the volume will be assigned as higher multiple of 8 GB.
    type: int
  cap_unit:
    description:
     - The unit of the volume size. It defaults to 'GB'.
    choices: ['GB' , 'TB']
    type: str
  vol_new_name:
    description:
    - New name of the volume. Used to rename the volume.
    type: str
  allow_multiple_mappings:
    description:
    - Specifies whether to allow or not allow multiple mappings.
    - If the volume is mapped to one SDC then for every new mapping
      I(allow_multiple_mappings) has to be passed as true.
    type: bool
  sdc:
    description:
    - Specifies SDC parameters.
    type: list
    elements: dict
    suboptions:
      sdc_name:
        description:
        - Name of the SDC.
        - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
        - Mutually exclusive with I(sdc_id) and I(sdc_ip).
        type: str
      sdc_id:
        description:
        - ID of the SDC.
        - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
        - Mutually exclusive with I(sdc_name) and I(sdc_ip).
        type: str
      sdc_ip:
        description:
        - IP of the SDC.
        - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
        - Mutually exclusive with I(sdc_id) and I(sdc_ip).
        type: str
      access_mode:
        description:
        - Define the access mode for all mappings of the volume.
        choices: ['READ_WRITE', 'READ_ONLY', 'NO_ACCESS']
        type: str
      bandwidth_limit:
        description:
        - Limit of volume network bandwidth.
        - Need to mention in multiple of 1024 Kbps.
        - To set no limit, 0 is to be passed.
        type: int
      iops_limit:
        description:
        - Limit of volume IOPS.
        - Minimum IOPS limit is 11 and specify 0 for unlimited iops.
        type: int
  sdc_state:
    description:
    - Mapping state of the SDC.
    choices: ['mapped', 'unmapped']
    type: str
  delete_snapshots:
    description:
    - If C(true), the volume and all its dependent snapshots will be deleted.
    - If C(false), only the volume will be deleted.
    - It can be specified only when the I(state) is C(absent).
    - It defaults to C(false), if not specified.
    type: bool
  state:
    description:
    - State of the volume.
    choices: ['present', 'absent']
    required: true
    type: str
notes:
  - The I(check_mode) is not supported.
'''

EXAMPLES = r'''
- name: Create a volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    storage_pool_name: "pool_1"
    protection_domain_name: "pd_1"
    vol_type: "THICK_PROVISIONED"
    compression_type: "NORMAL"
    use_rmcache: true
    size: 16
    state: "present"

- name: Map a SDC to volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    allow_multiple_mappings: true
    sdc:
      - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
        access_mode: "READ_WRITE"
    sdc_state: "mapped"
    state: "present"

- name: Unmap a SDC to volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    sdc:
      - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
    sdc_state: "unmapped"
    state: "present"

- name: Map multiple SDCs to a volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    protection_domain_name: "pd_1"
    sdc:
      - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
        access_mode: "READ_WRITE"
        bandwidth_limit: 2048
        iops_limit: 20
      - sdc_ip: "198.10.xxx.xxx"
        access_mode: "READ_ONLY"
    allow_multiple_mappings: true
    sdc_state: "mapped"
    state: "present"

- name: Get the details of the volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_id: "fe6c8b7100000005"
    state: "present"

- name: Modify the details of the Volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    storage_pool_name: "pool_1"
    new_vol_name: "new_sample_volume"
    size: 64
    state: "present"

- name: Delete the Volume
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    delete_snapshots: false
    state: "absent"

- name: Delete the Volume and all its dependent snapshots
  dellemc.powerflex.volume:
    hostname: "{{hostname}}"
    username: "{{username}}"
    password: "{{password}}"
    validate_certs: "{{validate_certs}}"
    port: "{{port}}"
    vol_name: "sample_volume"
    delete_snapshots: true
    state: "absent"
'''

RETURN = r'''
changed:
    description: Whether or not the resource has changed.
    returned: always
    type: bool
    sample: 'false'
volume_details:
    description: Details of the volume.
    returned: When volume exists
    type: dict
    contains:
        id:
            description: The ID of the volume.
            type: str
        mappedSdcInfo:
            description: The details of the mapped SDC.
            type: dict
            contains:
                sdcId:
                    description: ID of the SDC.
                    type: str
                sdcName:
                    description: Name of the SDC.
                    type: str
                sdcIp:
                    description: IP of the SDC.
                    type: str
                accessMode:
                    description: Mapping access mode for the specified volume.
                    type: str
                limitIops:
                    description: IOPS limit for the SDC.
                    type: int
                limitBwInMbps:
                    description: Bandwidth limit for the SDC.
                    type: int
        name:
            description: Name of the volume.
            type: str
        sizeInKb:
            description: Size of the volume in Kb.
            type: int
        sizeInGb:
            description: Size of the volume in Gb.
            type: int
        storagePoolId:
            description: ID of the storage pool in which volume resides.
            type: str
        storagePoolName:
            description: Name of the storage pool in which volume resides.
            type: str
        protectionDomainId:
            description: ID of the protection domain in which volume resides.
            type: str
        protectionDomainName:
            description: Name of the protection domain in which volume resides.
            type: str
        snapshotPolicyId:
            description: ID of the snapshot policy associated with volume.
            type: str
        snapshotPolicyName:
            description: Name of the snapshot policy associated with volume.
            type: str
        snapshotsList:
            description: List of snapshots associated with the volume.
            type: str
        "statistics":
            description: Statistics details of the storage pool.
            type: dict
            contains:
                "numOfChildVolumes":
                    description: Number of child volumes.
                    type: int
                "numOfMappedSdcs":
                    description: Number of mapped Sdcs of the volume.
                    type: int
    sample: {
        "accessModeLimit": "ReadWrite",
        "ancestorVolumeId": null,
        "autoSnapshotGroupId": null,
        "compressionMethod": "Invalid",
        "consistencyGroupId": null,
        "creationTime": 1631618520,
        "dataLayout": "MediumGranularity",
        "id": "cdd883cf00000002",
        "links": [
            {
                "href": "/api/instances/Volume::cdd883cf00000002",
                "rel": "self"
            },
            {
                "href": "/api/instances/Volume::cdd883cf00000002/relationships
                        /Statistics",
                "rel": "/api/Volume/relationship/Statistics"
            },
            {
                "href": "/api/instances/VTree::6e86255c00000001",
                "rel": "/api/parent/relationship/vtreeId"
            },
            {
                "href": "/api/instances/StoragePool::e0d8f6c900000000",
                "rel": "/api/parent/relationship/storagePoolId"
            }
        ],
        "lockedAutoSnapshot": false,
        "lockedAutoSnapshotMarkedForRemoval": false,
        "managedBy": "ScaleIO",
        "mappedSdcInfo": null,
        "name": "ansible-volume-1",
        "notGenuineSnapshot": false,
        "originalExpiryTime": 0,
        "pairIds": null,
        "protectionDomainId": "9300c1f900000000",
        "protectionDomainName": "domain1",
        "replicationJournalVolume": false,
        "replicationTimeStamp": 0,
        "retentionLevels": [],
        "secureSnapshotExpTime": 0,
        "sizeInGB": 16,
        "sizeInKb": 16777216,
        "snapshotPolicyId": null,
        "snapshotPolicyName": null,
        "snapshotsList": [
            {
                "accessModeLimit": "ReadOnly",
                "ancestorVolumeId": "cdd883cf00000002",
                "autoSnapshotGroupId": null,
                "compressionMethod": "Invalid",
                "consistencyGroupId": "22f1e80c00000001",
                "creationTime": 1631619229,
                "dataLayout": "MediumGranularity",
                "id": "cdd883d000000004",
                "links": [
                    {
                        "href": "/api/instances/Volume::cdd883d000000004",
                        "rel": "self"
                    },
                    {
                        "href": "/api/instances/Volume::cdd883d000000004
                                /relationships/Statistics",
                        "rel": "/api/Volume/relationship/Statistics"
                    },
                    {
                        "href": "/api/instances/Volume::cdd883cf00000002",
                        "rel": "/api/parent/relationship/ancestorVolumeId"
                    },
                    {
                        "href": "/api/instances/VTree::6e86255c00000001",
                        "rel": "/api/parent/relationship/vtreeId"
                    },
                    {
                        "href": "/api/instances/StoragePool::e0d8f6c900000000",
                        "rel": "/api/parent/relationship/storagePoolId"
                    }
                ],
                "lockedAutoSnapshot": false,
                "lockedAutoSnapshotMarkedForRemoval": false,
                "managedBy": "ScaleIO",
                "mappedSdcInfo": null,
                "name": "ansible_vol_snap_1",
                "notGenuineSnapshot": false,
                "originalExpiryTime": 0,
                "pairIds": null,
                "replicationJournalVolume": false,
                "replicationTimeStamp": 0,
                "retentionLevels": [],
                "secureSnapshotExpTime": 0,
                "sizeInKb": 16777216,
                "snplIdOfAutoSnapshot": null,
                "snplIdOfSourceVolume": null,
                "storagePoolId": "e0d8f6c900000000",
                "timeStampIsAccurate": false,
                "useRmcache": false,
                "volumeReplicationState": "UnmarkedForReplication",
                "volumeType": "Snapshot",
                "vtreeId": "6e86255c00000001"
            }
        ],
        "statistics": {
            "childVolumeIds": [
            ],
            "descendantVolumeIds": [
            ],
            "initiatorSdcId": null,
            "mappedSdcIds": [
            "c42425XXXXXX"
            ],
            "numOfChildVolumes": 0,
            "numOfDescendantVolumes": 0,
            "numOfMappedSdcs": 1,
            "registrationKey": null,
            "registrationKeys": [
            ],
            "replicationJournalVolume": false,
            "replicationState": "UnmarkedForReplication",
            "reservationType": "NotReserved",
            "rplTotalJournalCap": 0,
            "rplUsedJournalCap": 0,
            "userDataReadBwc": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            },
            "userDataSdcReadLatency": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            },
            "userDataSdcTrimLatency": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            },
            "userDataSdcWriteLatency": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            },
            "userDataTrimBwc": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            },
            "userDataWriteBwc": {
                "numOccured": 0,
                "numSeconds": 0,
                "totalWeightInKb": 0
            }
        },
        "snplIdOfAutoSnapshot": null,
        "snplIdOfSourceVolume": null,
        "storagePoolId": "e0d8f6c900000000",
        "storagePoolName": "pool1",
        "timeStampIsAccurate": false,
        "useRmcache": false,
        "volumeReplicationState": "UnmarkedForReplication",
        "volumeType": "ThinProvisioned",
        "vtreeId": "6e86255c00000001"
    }
'''

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell\
    import utils
import copy

LOG = utils.get_logger('volume')


class PowerFlexVolume(object):
    """Class with volume operations"""

    def __init__(self):
        """ Define all parameters required by this module"""
        self.module_params = utils.get_powerflex_gateway_host_parameters()
        self.module_params.update(get_powerflex_volume_parameters())

        mut_ex_args = [['vol_name', 'vol_id'],
                       ['storage_pool_name', 'storage_pool_id'],
                       ['protection_domain_name', 'protection_domain_id'],
                       ['snapshot_policy_name', 'snapshot_policy_id'],
                       ['vol_id', 'storage_pool_name'],
                       ['vol_id', 'storage_pool_id'],
                       ['vol_id', 'protection_domain_name'],
                       ['vol_id', 'protection_domain_id']]

        required_together_args = [['sdc', 'sdc_state']]

        required_one_of_args = [['vol_name', 'vol_id']]

        # initialize the Ansible module
        self.module = AnsibleModule(
            argument_spec=self.module_params,
            supports_check_mode=False,
            mutually_exclusive=mut_ex_args,
            required_together=required_together_args,
            required_one_of=required_one_of_args)

        utils.ensure_required_libs(self.module)

        try:
            self.powerflex_conn = utils.get_powerflex_gateway_host_connection(
                self.module.params)
            LOG.info("Got the PowerFlex system connection object instance")
        except Exception as e:
            LOG.error(str(e))
            self.module.fail_json(msg=str(e))

    def get_protection_domain(self, protection_domain_name=None,
                              protection_domain_id=None):
        """Get protection domain details
            :param protection_domain_name: Name of the protection domain
            :param protection_domain_id: ID of the protection domain
            :return: Protection domain details
        """
        name_or_id = protection_domain_id if protection_domain_id \
            else protection_domain_name
        try:
            pd_details = None
            if protection_domain_id:
                pd_details = self.powerflex_conn.protection_domain.get(
                    filter_fields={'id': protection_domain_id})

            if protection_domain_name:
                pd_details = self.powerflex_conn.protection_domain.get(
                    filter_fields={'name': protection_domain_name})

            if not pd_details:
                err_msg = "Unable to find the protection domain with {0}. " \
                          "Please enter a valid protection domain" \
                          " name/id.".format(name_or_id)
                self.module.fail_json(msg=err_msg)

            return pd_details[0]

        except Exception as e:
            errormsg = "Failed to get the protection domain {0} with" \
                       " error {1}".format(name_or_id, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def get_snapshot_policy(self, snap_pol_id=None, snap_pol_name=None):
        """Get snapshot policy details
            :param snap_pol_name: Name of the snapshot policy
            :param snap_pol_id: ID of the snapshot policy
            :return: snapshot policy details
        """
        name_or_id = snap_pol_id if snap_pol_id else snap_pol_name
        try:
            snap_pol_details = None
            if snap_pol_id:
                snap_pol_details = self.powerflex_conn.snapshot_policy.get(
                    filter_fields={'id': snap_pol_id})

            if snap_pol_name:
                snap_pol_details = self.powerflex_conn.snapshot_policy.get(
                    filter_fields={'name': snap_pol_name})

            if not snap_pol_details:
                err_msg = "Unable to find the snapshot policy with {0}. " \
                          "Please enter a valid snapshot policy" \
                          " name/id.".format(name_or_id)
                self.module.fail_json(msg=err_msg)

            return snap_pol_details[0]

        except Exception as e:
            errormsg = "Failed to get the snapshot policy {0} with" \
                       " error {1}".format(name_or_id, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def get_storage_pool(self, storage_pool_id=None, storage_pool_name=None,
                         protection_domain_id=None):
        """Get storage pool details
            :param protection_domain_id: ID of the protection domain
            :param storage_pool_name: The name of the storage pool
            :param storage_pool_id: The storage pool id
            :return: Storage pool details
        """
        name_or_id = storage_pool_id if storage_pool_id \
            else storage_pool_name
        try:
            sp_details = None
            if storage_pool_id:
                sp_details = self.powerflex_conn.storage_pool.get(
                    filter_fields={'id': storage_pool_id})

            if storage_pool_name:
                sp_details = self.powerflex_conn.storage_pool.get(
                    filter_fields={'name': storage_pool_name})

            if len(sp_details) > 1 and protection_domain_id is None:
                err_msg = "More than one storage pool found with {0}," \
                          " Please provide protection domain Name/Id" \
                          " to fetch the unique" \
                          " pool".format(storage_pool_name)
                self.module.fail_json(msg=err_msg)

            if len(sp_details) > 1 and protection_domain_id:
                sp_details = self.powerflex_conn.storage_pool.get(
                    filter_fields={'name': storage_pool_name,
                                   'protectionDomainId':
                                       protection_domain_id})
            if not sp_details:
                err_msg = "Unable to find the storage pool with {0}. " \
                          "Please enter a valid pool " \
                          "name/id.".format(name_or_id)
                self.module.fail_json(msg=err_msg)
            return sp_details[0]

        except Exception as e:
            errormsg = "Failed to get the storage pool {0} with error " \
                       "{1}".format(name_or_id, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def get_volume(self, vol_name=None, vol_id=None):
        """Get volume details
            :param vol_name: Name of the volume
            :param vol_id: ID of the volume
            :return: Details of volume if exist.
        """

        id_or_name = vol_id if vol_id else vol_name

        try:
            if vol_name:
                volume_details = self.powerflex_conn.volume.get(
                    filter_fields={'name': vol_name})
            else:
                volume_details = self.powerflex_conn.volume.get(
                    filter_fields={'id': vol_id})

            if len(volume_details) == 0:
                msg = "Volume with identifier {0} not found".format(
                    id_or_name)
                LOG.info(msg)
                return None

            # Append size in GB in the volume details
            if 'sizeInKb' in volume_details[0] and \
                    volume_details[0]['sizeInKb']:
                volume_details[0]['sizeInGB'] = utils.get_size_in_gb(
                    volume_details[0]['sizeInKb'], 'KB')

            # Append storage pool name and id.
            sp = None
            pd_id = None
            if 'storagePoolId' in volume_details[0] and \
                    volume_details[0]['storagePoolId']:
                sp = \
                    self.get_storage_pool(volume_details[0]['storagePoolId'])
                if len(sp) > 0:
                    volume_details[0]['storagePoolName'] = sp['name']
                    pd_id = sp['protectionDomainId']

            # Append protection domain name and id
            if sp and 'protectionDomainId' in sp and \
                    sp['protectionDomainId']:
                pd = self.get_protection_domain(protection_domain_id=pd_id)
                volume_details[0]['protectionDomainId'] = pd_id
                volume_details[0]['protectionDomainName'] = pd['name']

            # Append snapshot policy name and id
            if volume_details[0]['snplIdOfSourceVolume'] is not None:
                snap_policy_id = volume_details[0]['snplIdOfSourceVolume']
                volume_details[0]['snapshotPolicyId'] = snap_policy_id
                volume_details[0]['snapshotPolicyName'] = \
                    self.get_snapshot_policy(snap_policy_id)['name']

            return volume_details[0]

        except Exception as e:
            error_msg = "Failed to get the volume {0} with error {1}"
            error_msg = error_msg.format(id_or_name, str(e))
            LOG.error(error_msg)
            self.module.fail_json(msg=error_msg)

    def get_sdc_id(self, sdc_name=None, sdc_ip=None, sdc_id=None):
        """Get the SDC ID
            :param sdc_name: The name of the SDC
            :param sdc_ip: The IP of the SDC
            :param sdc_id: The ID of the SDC
            :return: The ID of the SDC
        """

        if sdc_name:
            id_ip_name = sdc_name
        elif sdc_ip:
            id_ip_name = sdc_ip
        else:
            id_ip_name = sdc_id

        try:
            if sdc_name:
                sdc_details = self.powerflex_conn.sdc.get(
                    filter_fields={'name': sdc_name})
            elif sdc_ip:
                sdc_details = self.powerflex_conn.sdc.get(
                    filter_fields={'sdcIp': sdc_ip})
            else:
                sdc_details = self.powerflex_conn.sdc.get(
                    filter_fields={'id': sdc_id})

            if len(sdc_details) == 0:
                error_msg = "Unable to find SDC with identifier {0}".format(
                    id_ip_name)
                self.module.fail_json(msg=error_msg)
            return sdc_details[0]['id']
        except Exception as e:
            errormsg = "Failed to get the SDC {0} with error " \
                       "{1}".format(id_ip_name, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def create_volume(self, vol_name, pool_id, size, vol_type=None,
                      use_rmcache=None, comp_type=None):
        """Create volume
            :param use_rmcache: Boolean indicating whether to use RM cache.
            :param comp_type: Type of compression method for the volume.
            :param vol_type: Type of volume.
            :param size: Size of the volume.
            :param pool_id: Id of the storage pool.
            :param vol_name: The name of the volume.
            :return: Boolean indicating if create operation is successful
        """
        try:
            if vol_name is None or len(vol_name.strip()) == 0:
                self.module.fail_json(msg="Please provide valid volume name.")

            if not size:
                self.module.fail_json(msg="Size is a mandatory parameter "
                                          "for creating a volume. Please "
                                          "enter a valid size")
            pool_data_layout = None
            if pool_id:
                pool_details = self.get_storage_pool(storage_pool_id=pool_id)
                pool_data_layout = pool_details['dataLayout']
            if comp_type and pool_data_layout and \
                    pool_data_layout != "FineGranularity":
                err_msg = "compression_type for volume can only be " \
                          "mentioned when storage pools have Fine " \
                          "Granularity layout. Storage Pool found" \
                          " with {0}".format(pool_data_layout)
                self.module.fail_json(msg=err_msg)

            # Basic volume created.
            self.powerflex_conn.volume.create(
                storage_pool_id=pool_id, size_in_gb=size, name=vol_name,
                volume_type=vol_type, use_rmcache=use_rmcache,
                compression_method=comp_type)
            return True

        except Exception as e:
            errormsg = "Create volume {0} operation failed with " \
                       "error {1}".format(vol_name, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def modify_access_mode(self, vol_id, access_mode_list):
        """Modify access mode of SDCs mapped to volume
            :param vol_id: The volume id
            :param access_mode_list: List containing SDC ID's
             whose access mode is to modified
            :return: Boolean indicating if modifying access
             mode is successful
        """

        try:
            changed = False
            for temp in access_mode_list:
                if temp['accessMode']:
                    self.powerflex_conn.volume.set_access_mode_for_sdc(
                        volume_id=vol_id, sdc_id=temp['sdc_id'],
                        access_mode=temp['accessMode'])
                    changed = True
            return changed
        except Exception as e:
            errormsg = "Modify access mode of SDC operation failed " \
                       "with error {0}".format(str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def modify_limits(self, payload):
        """Modify IOPS and bandwidth limits of SDC's mapped to volume
            :param payload: Dict containing SDC ID's whose bandwidth and
                   IOPS is to modified
            :return: Boolean indicating if modifying limits is successful
        """

        try:
            changed = False
            if payload['bandwidth_limit'] is not None or \
                    payload['iops_limit'] is not None:
                self.powerflex_conn.volume.set_mapped_sdc_limits(**payload)
                changed = True
            return changed
        except Exception as e:
            errormsg = "Modify bandwidth/iops limits of SDC %s operation " \
                       "failed with error %s" % (payload['sdc_id'], str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def delete_volume(self, vol_id, remove_mode):
        """Delete volume
            :param vol_id: The volume id
            :param remove_mode: Removal mode for the volume
            :return: Boolean indicating if delete operation is successful
        """

        try:
            self.powerflex_conn.volume.delete(vol_id, remove_mode)
            return True
        except Exception as e:
            errormsg = "Delete volume {0} operation failed with " \
                       "error {1}".format(vol_id, str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def unmap_volume_from_sdc(self, volume, sdc):
        """Unmap SDC's from volume
            :param volume: volume details
            :param sdc: List of SDCs to be unmapped
            :return: Boolean indicating if unmap operation is successful
        """

        current_sdcs = volume['mappedSdcInfo']
        current_sdc_ids = []
        sdc_id_list = []
        sdc_id = None
        if current_sdcs:
            for temp in current_sdcs:
                current_sdc_ids.append(temp['sdcId'])

        for temp in sdc:
            if 'sdc_name' in temp and temp['sdc_name']:
                sdc_id = self.get_sdc_id(sdc_name=temp['sdc_name'])
            elif 'sdc_ip' in temp and temp['sdc_ip']:
                sdc_id = self.get_sdc_id(sdc_ip=temp['sdc_ip'])
            else:
                sdc_id = self.get_sdc_id(sdc_id=temp['sdc_id'])
            if sdc_id in current_sdc_ids:
                sdc_id_list.append(sdc_id)

        LOG.info("SDC IDs to remove %s", sdc_id_list)

        if len(sdc_id_list) == 0:
            return False

        try:
            for sdc_id in sdc_id_list:
                self.powerflex_conn.volume.remove_mapped_sdc(
                    volume['id'], sdc_id)
            return True
        except Exception as e:
            errormsg = "Unmap SDC {0} from volume {1} failed with error " \
                       "{2}".format(sdc_id, volume['id'], str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def map_volume_to_sdc(self, volume, sdc):
        """Map SDC's to volume
            :param volume: volume details
            :param sdc: List of SDCs
            :return: Boolean indicating if mapping operation is successful
        """

        current_sdcs = volume['mappedSdcInfo']
        current_sdc_ids = []
        sdc_id_list = []
        sdc_map_list = []
        sdc_modify_list1 = []
        sdc_modify_list2 = []

        if current_sdcs:
            for temp in current_sdcs:
                current_sdc_ids.append(temp['sdcId'])

        for temp in sdc:
            if 'sdc_name' in temp and temp['sdc_name']:
                sdc_id = self.get_sdc_id(sdc_name=temp['sdc_name'])
            elif 'sdc_ip' in temp and temp['sdc_ip']:
                sdc_id = self.get_sdc_id(sdc_ip=temp['sdc_ip'])
            else:
                sdc_id = self.get_sdc_id(sdc_id=temp['sdc_id'])
            if sdc_id not in current_sdc_ids:
                sdc_id_list.append(sdc_id)
                temp['sdc_id'] = sdc_id
                if 'access_mode' in temp:
                    temp['access_mode'] = \
                        get_access_mode(temp['access_mode'])
                if 'bandwidth_limit' not in temp:
                    temp['bandwidth_limit'] = None
                if 'iops_limit' not in temp:
                    temp['iops_limit'] = None
                sdc_map_list.append(temp)
            else:
                access_mode_dict, limits_dict = check_for_sdc_modification(
                    volume, sdc_id, temp)
                if access_mode_dict:
                    sdc_modify_list1.append(access_mode_dict)
                if limits_dict:
                    sdc_modify_list2.append(limits_dict)

        LOG.info("SDC to add: %s", sdc_map_list)

        if not sdc_map_list:
            return False, sdc_modify_list1, sdc_modify_list2

        try:
            changed = False
            for sdc in sdc_map_list:
                payload = {
                    "volume_id": volume['id'],
                    "sdc_id": sdc['sdc_id'],
                    "access_mode": sdc['access_mode'],
                    "allow_multiple_mappings":
                        self.module.params['allow_multiple_mappings']
                }
                self.powerflex_conn.volume.add_mapped_sdc(**payload)

                if sdc['bandwidth_limit'] or sdc['iops_limit']:
                    payload = {
                        "volume_id": volume['id'],
                        "sdc_id": sdc['sdc_id'],
                        "bandwidth_limit": sdc['bandwidth_limit'],
                        "iops_limit": sdc['iops_limit']
                    }

                    self.powerflex_conn.volume.set_mapped_sdc_limits(**payload)
                changed = True
            return changed, sdc_modify_list1, sdc_modify_list2
        except Exception as e:
            errormsg = "Mapping volume {0} to SDC {1} " \
                       "failed with error {2}".format(volume['name'],
                                                      sdc['sdc_id'], str(e))
            LOG.error(errormsg)
            self.module.fail_json(msg=errormsg)

    def validate_parameters(self, auto_snap_remove_type, snap_pol_id,
                            snap_pol_name, delete_snaps, state):
        """Validate the input parameters"""

        sdc = self.module.params['sdc']
        cap_unit = self.module.params['cap_unit']
        size = self.module.params['size']

        if sdc:
            for temp in sdc:
                if (all([temp['sdc_id'], temp['sdc_ip']]) or
                        all([temp['sdc_id'], temp['sdc_name']]) or
                        all([temp['sdc_ip'], temp['sdc_name']])):
                    self.module.fail_json(msg="sdc_id, sdc_ip and sdc_name "
                                              "are mutually exclusive")

        if (cap_unit is not None) and not size:
            self.module.fail_json(msg="cap_unit can be specified along "
                                      "with size only. Please enter a valid"
                                      " value for size")

        if auto_snap_remove_type and snap_pol_name is None \
                and snap_pol_id is None:
            err_msg = "To remove/detach snapshot policy, please provide" \
                      " empty snapshot policy name/id along with " \
                      "auto_snap_remove_type parameter"
            LOG.error(err_msg)
            self.module.fail_json(msg=err_msg)

        if state == "present" and delete_snaps is not None:
            self.module.fail_json(
                msg="delete_snapshots can be specified only when the state"
                    " is passed as absent.")

    def modify_volume(self, vol_id, modify_dict):
        """
        Update the volume attributes
        :param vol_id: Id of the volume
        :param modify_dict: Dictionary containing the attributes of
         volume which are to be updated
        :return: True, if the operation is successful
        """
        try:
            msg = "Dictionary containing attributes which are to be" \
                  " updated is {0}.".format(str(modify_dict))
            LOG.info(msg)

            if 'auto_snap_remove_type' in modify_dict:
                snap_type = modify_dict['auto_snap_remove_type']
                msg = "Removing/detaching the snapshot policy from a " \
                      "volume. auto_snap_remove_type: {0} and snapshot " \
                      "policy id: " \
                      "{1}".format(snap_type, modify_dict['snap_pol_id'])
                LOG.info(msg)
                self.powerflex_conn.snapshot_policy.remove_source_volume(
                    modify_dict['snap_pol_id'], vol_id, snap_type)
                msg = "The snapshot policy has been {0}ed " \
                      "successfully".format(snap_type)
                LOG.info(msg)

            if 'auto_snap_remove_type' not in modify_dict\
                    and 'snap_pol_id' in modify_dict:
                self.powerflex_conn.snapshot_policy.add_source_volume(
                    modify_dict['snap_pol_id'], vol_id)
                msg = "Attached the snapshot policy {0} to volume" \
                      " successfully.".format(modify_dict['snap_pol_id'])
                LOG.info(msg)

            if 'new_name' in modify_dict:
                self.powerflex_conn.volume.rename(vol_id,
                                                  modify_dict['new_name'])
                msg = "The name of the volume is updated" \
                      " to {0} sucessfully.".format(modify_dict['new_name'])
                LOG.info(msg)

            if 'new_size' in modify_dict:
                self.powerflex_conn.volume.extend(vol_id,
                                                  modify_dict['new_size'])
                msg = "The size of the volume is extended to {0} " \
                      "sucessfully.".format(str(modify_dict['new_size']))
                LOG.info(msg)

            if 'use_rmcache' in modify_dict:
                self.powerflex_conn.volume.set_use_rmcache(
                    vol_id, modify_dict['use_rmcache'])
                msg = "The use RMcache is updated to {0}" \
                      " sucessfully.".format(modify_dict['use_rmcache'])
                LOG.info(msg)

            if 'comp_type' in modify_dict:
                self.powerflex_conn.volume.set_compression_method(
                    vol_id, modify_dict['comp_type'])
                msg = "The compression method is updated to {0}" \
                      " successfully.".format(modify_dict['comp_type'])
                LOG.info(msg)
            return True

        except Exception as e:
            err_msg = "Failed to update the volume {0}" \
                      " with error {1}".format(vol_id, str(e))
            LOG.error(err_msg)
            self.module.fail_json(msg=err_msg)

    def to_modify(self, vol_details, new_size, use_rmcache, comp_type,
                  new_name, snap_pol_id,
                  auto_snap_remove_type):
        """

        :param vol_details: Details of the volume
        :param new_size: Size of the volume
        :param use_rmcache: Bool value of use rm cache
        :param comp_type: Type of compression method
        :param new_name: The new name of the volume
        :param snap_pol_id: Id of the snapshot policy
        :param auto_snap_remove_type: Whether to remove or detach the policy
        :return: Dictionary containing the attributes of
         volume which are to be updated
        """
        modify_dict = {}

        if comp_type:
            pool_id = vol_details['storagePoolId']
            pool_details = self.get_storage_pool(storage_pool_id=pool_id)
            pool_data_layout = pool_details['dataLayout']
            if pool_data_layout != "FineGranularity":
                err_msg = "compression_type for volume can only be " \
                          "mentioned when storage pools have Fine " \
                          "Granularity layout. Storage Pool found" \
                          " with {0}".format(pool_data_layout)
                self.module.fail_json(msg=err_msg)

            if comp_type != vol_details['compressionMethod']:
                modify_dict['comp_type'] = comp_type

        if use_rmcache is not None and \
                vol_details['useRmcache'] != use_rmcache:
            modify_dict['use_rmcache'] = use_rmcache

        vol_size_in_gb = utils.get_size_in_gb(vol_details['sizeInKb'], 'KB')

        if new_size is not None and \
                not ((vol_size_in_gb - 8) < new_size <= vol_size_in_gb):
            modify_dict['new_size'] = new_size

        if new_name is not None:
            if new_name is None or len(new_name.strip()) == 0:
                self.module.fail_json(msg="Please provide valid volume "
                                          "name.")
            if new_name != vol_details['name']:
                modify_dict['new_name'] = new_name

        if snap_pol_id is not None and snap_pol_id == "" and \
                auto_snap_remove_type and vol_details['snplIdOfSourceVolume']:
            modify_dict['auto_snap_remove_type'] = auto_snap_remove_type
            modify_dict['snap_pol_id'] = \
                vol_details['snplIdOfSourceVolume']

        if snap_pol_id is not None and snap_pol_id != "":
            if auto_snap_remove_type and vol_details['snplIdOfSourceVolume']:
                err_msg = "To remove/detach a snapshot policy, provide the" \
                          " snapshot policy name/id as empty string"
                self.module.fail_json(msg=err_msg)
            if auto_snap_remove_type is None and \
                    vol_details['snplIdOfSourceVolume'] is None:
                modify_dict['snap_pol_id'] = snap_pol_id

        return modify_dict

    def verify_params(self, vol_details, snap_pol_name, snap_pol_id, pd_name,
                      pd_id, pool_name, pool_id):
        """
        :param vol_details: Details of the volume
        :param snap_pol_name: Name of the snapshot policy
        :param snap_pol_id: Id of the snapshot policy
        :param pd_name: Name of the protection domain
        :param pd_id: Id of the protection domain
        :param pool_name: Name of the storage pool
        :param pool_id: Id of the storage pool
        """

        if snap_pol_id and 'snapshotPolicyId' in vol_details and \
                snap_pol_id != vol_details['snapshotPolicyId']:
            self.module.fail_json(msg="Entered snapshot policy id does not"
                                      " match with the snapshot policy's id"
                                      " attached to the volume. Please enter"
                                      " a correct snapshot policy id.")

        if snap_pol_name and 'snapshotPolicyId' in vol_details and \
                snap_pol_name != vol_details['snapshotPolicyName']:
            self.module.fail_json(msg="Entered snapshot policy name does not"
                                      " match with the snapshot policy's "
                                      "name attached to the volume. Please"
                                      " enter a correct snapshot policy"
                                      " name.")

        if pd_id and pd_id != vol_details['protectionDomainId']:
            self.module.fail_json(msg="Entered protection domain id does not"
                                      " match with the volume's protection"
                                      " domain id. Please enter a correct"
                                      " protection domain id.")

        if pool_id and pool_id != vol_details['storagePoolId']:
            self.module.fail_json(msg="Entered storage pool id does"
                                      " not match with the volume's "
                                      "storage pool id. Please enter"
                                      " a correct storage pool id.")

        if pd_name and pd_name != vol_details['protectionDomainName']:
            self.module.fail_json(msg="Entered protection domain name does"
                                      " not match with the volume's "
                                      "protection domain name. Please enter"
                                      " a correct protection domain name.")

        if pool_name and pool_name != vol_details['storagePoolName']:
            self.module.fail_json(msg="Entered storage pool name does"
                                      " not match with the volume's "
                                      "storage pool name. Please enter"
                                      " a correct storage pool name.")

    def perform_module_operation(self):
        """
        Perform different actions on volume based on parameters passed in
        the playbook
        """
        vol_name = self.module.params['vol_name']
        vol_id = self.module.params['vol_id']
        vol_type = self.module.params['vol_type']
        compression_type = self.module.params['compression_type']
        sp_name = self.module.params['storage_pool_name']
        sp_id = self.module.params['storage_pool_id']
        pd_name = self.module.params['protection_domain_name']
        pd_id = self.module.params['protection_domain_id']
        snap_pol_name = self.module.params['snapshot_policy_name']
        snap_pol_id = self.module.params['snapshot_policy_id']
        auto_snap_remove_type = self.module.params['auto_snap_remove_type']
        use_rmcache = self.module.params['use_rmcache']
        size = self.module.params['size']
        cap_unit = self.module.params['cap_unit']
        vol_new_name = self.module.params['vol_new_name']
        sdc = copy.deepcopy(self.module.params['sdc'])
        sdc_state = self.module.params['sdc_state']
        delete_snapshots = self.module.params['delete_snapshots']
        state = self.module.params['state']

        if compression_type:
            compression_type = compression_type.capitalize()
        if vol_type:
            vol_type = get_vol_type(vol_type)
        if auto_snap_remove_type:
            auto_snap_remove_type = auto_snap_remove_type.capitalize()

        # result is a dictionary to contain end state and volume details
        changed = False
        result = dict(
            changed=False,
            volume_details={}
        )
        self.validate_parameters(auto_snap_remove_type, snap_pol_id,
                                 snap_pol_name, delete_snapshots, state)

        if not auto_snap_remove_type and\
                (snap_pol_name == "" or snap_pol_id == ""):
            auto_snap_remove_type = "Detach"
        if size:
            if not cap_unit:
                cap_unit = 'GB'

            if cap_unit == 'TB':
                size = size * 1024

        if pd_name:
            pd_details = self.get_protection_domain(pd_name)
            if pd_details:
                pd_id = pd_details['id']
            msg = "Fetched the protection domain details with id {0}," \
                  " name {1}".format(pd_id, pd_name)
            LOG.info(msg)

        if sp_name:
            sp_details = self.get_storage_pool(storage_pool_name=sp_name,
                                               protection_domain_id=pd_id)
            if sp_details:
                sp_id = sp_details['id']
            msg = "Fetched the storage pool details id {0}," \
                  " name {1}".format(sp_id, sp_name)
            LOG.info(msg)

        if snap_pol_name is not None:
            snap_pol_details = None
            if snap_pol_name:
                snap_pol_details = \
                    self.get_snapshot_policy(snap_pol_name=snap_pol_name)
            if snap_pol_details:
                snap_pol_id = snap_pol_details['id']

            if snap_pol_name == "":
                snap_pol_id = ""
            msg = "Fetched the snapshot policy details with id {0}," \
                  " name {1}".format(snap_pol_id, snap_pol_name)
            LOG.info(msg)

        # get volume details
        volume_details = self.get_volume(vol_name, vol_id)
        if volume_details:
            vol_id = volume_details['id']
        msg = "Fetched the volume details {0}".format(str(volume_details))
        LOG.info(msg)

        if vol_name and volume_details:
            self.verify_params(
                volume_details, snap_pol_name, snap_pol_id, pd_name, pd_id,
                sp_name, sp_id)

        # create operation
        create_changed = False
        if state == 'present' and not volume_details:
            if vol_id:
                self.module.fail_json(msg="Creation of volume is allowed "
                                          "using vol_name only, "
                                          "vol_id given.")

            if vol_new_name:
                self.module.fail_json(
                    msg="vol_new_name parameter is not supported during "
                        "creation of a volume. Try renaming the volume after"
                        " the creation.")
            create_changed = self.create_volume(vol_name, sp_id, size,
                                                vol_type, use_rmcache,
                                                compression_type)
            if create_changed:
                volume_details = self.get_volume(vol_name)
                vol_id = volume_details['id']
                msg = "Volume created successfully, fetched " \
                      "volume details {0}".format(str(volume_details))
                LOG.info(msg)

        # checking if basic volume parameters are modified or not.
        modify_dict = {}
        if volume_details and state == 'present':
            modify_dict = self.to_modify(
                volume_details, size, use_rmcache, compression_type,
                vol_new_name, snap_pol_id, auto_snap_remove_type)
            msg = "Parameters to be modified are as" \
                  " follows: {0}".format(str(modify_dict))
            LOG.info(msg)

        # Mapping the SDCs to a volume
        mode_changed = False
        limits_changed = False
        map_changed = False
        if state == 'present' and volume_details and sdc and \
                sdc_state == 'mapped':
            map_changed, access_mode_list, limits_list = \
                self.map_volume_to_sdc(volume_details, sdc)
            if len(access_mode_list) > 0:
                mode_changed = self.modify_access_mode(vol_id,
                                                       access_mode_list)
            if len(limits_list) > 0:
                for temp in limits_list:
                    payload = {
                        "volume_id": volume_details['id'],
                        "sdc_id": temp['sdc_id'],
                        "bandwidth_limit": temp['bandwidth_limit'],
                        "iops_limit": temp['iops_limit']
                    }
                    limits_changed = self.modify_limits(payload)

        # Unmap the SDCs to a volume
        unmap_changed = False
        if state == 'present' and volume_details and sdc and \
                sdc_state == 'unmapped':
            unmap_changed = self.unmap_volume_from_sdc(volume_details, sdc)

        # Update the basic volume attributes
        modify_changed = False
        if modify_dict and state == 'present':
            modify_changed = self.modify_volume(vol_id, modify_dict)

        # delete operation
        del_changed = False
        if state == 'absent' and volume_details:
            if delete_snapshots is True:
                delete_snapshots = 'INCLUDING_DESCENDANTS'
            if delete_snapshots is None or delete_snapshots is False:
                delete_snapshots = 'ONLY_ME'
            del_changed = \
                self.delete_volume(vol_id, delete_snapshots)

        if modify_changed or unmap_changed or map_changed or create_changed\
                or del_changed or mode_changed or limits_changed:
            changed = True

        # Returning the updated volume details
        if state == 'present':
            vol_details = self.show_output(vol_id)
            result['volume_details'] = vol_details
        result['changed'] = changed
        self.module.exit_json(**result)

    def show_output(self, vol_id):
        """Show volume details
            :param vol_id: ID of the volume
            :return: Details of volume if exist.
        """

        try:
            volume_details = self.powerflex_conn.volume.get(
                filter_fields={'id': vol_id})

            if len(volume_details) == 0:
                msg = "Volume with identifier {0} not found".format(
                    vol_id)
                LOG.error(msg)
                return None

            # Append size in GB in the volume details
            if 'sizeInKb' in volume_details[0] and \
                    volume_details[0]['sizeInKb']:
                volume_details[0]['sizeInGB'] = utils.get_size_in_gb(
                    volume_details[0]['sizeInKb'], 'KB')

            # Append storage pool name and id.
            sp = None
            pd_id = None
            if 'storagePoolId' in volume_details[0] and \
                    volume_details[0]['storagePoolId']:
                sp = \
                    self.get_storage_pool(volume_details[0]['storagePoolId'])
                if len(sp) > 0:
                    volume_details[0]['storagePoolName'] = sp['name']
                    pd_id = sp['protectionDomainId']

            # Append protection domain name and id
            if sp and 'protectionDomainId' in sp and \
                    sp['protectionDomainId']:
                pd = self.get_protection_domain(protection_domain_id=pd_id)
                volume_details[0]['protectionDomainId'] = pd_id
                volume_details[0]['protectionDomainName'] = pd['name']

            # Append snapshot policy name and id
            if volume_details[0]['snplIdOfSourceVolume'] is not None:
                snap_policy_id = volume_details[0]['snplIdOfSourceVolume']
                volume_details[0]['snapshotPolicyId'] = snap_policy_id
                volume_details[0]['snapshotPolicyName'] = \
                    self.get_snapshot_policy(snap_policy_id)['name']
            else:
                volume_details[0]['snapshotPolicyId'] = None
                volume_details[0]['snapshotPolicyName'] = None

            # Append the list of snapshots associated with the volume
            list_of_snaps = self.powerflex_conn.volume.get(
                filter_fields={'ancestorVolumeId': volume_details[0]['id']})
            volume_details[0]['snapshotsList'] = list_of_snaps

            # Append statistics
            statistics = self.powerflex_conn.volume.get_statistics(volume_details[0]['id'])
            volume_details[0]['statistics'] = statistics if statistics else {}

            return volume_details[0]

        except Exception as e:
            error_msg = "Failed to get the volume {0} with error {1}"
            error_msg = error_msg.format(vol_id, str(e))
            LOG.error(error_msg)
            self.module.fail_json(msg=error_msg)


def check_for_sdc_modification(volume, sdc_id, sdc_details):
    """
    :param volume: The volume details
    :param sdc_id: The ID of the SDC
    :param sdc_details: The details of SDC
    :return: Dictionary with SDC attributes to be modified
    """
    access_mode_dict = dict()
    limits_dict = dict()

    for sdc in volume['mappedSdcInfo']:
        if sdc['sdcId'] == sdc_id:
            if sdc['accessMode'] != \
                    get_access_mode(sdc_details['access_mode']):
                access_mode_dict['sdc_id'] = sdc_id
                access_mode_dict['accessMode'] = get_access_mode(
                    sdc_details['access_mode'])
            if sdc['limitIops'] != sdc_details['iops_limit'] or \
                    sdc['limitBwInMbps'] != sdc_details['bandwidth_limit']:
                limits_dict['sdc_id'] = sdc_id
                limits_dict['iops_limit'] = None
                limits_dict['bandwidth_limit'] = None
                if sdc['limitIops'] != sdc_details['iops_limit']:
                    limits_dict['iops_limit'] = sdc_details['iops_limit']
                if sdc['limitBwInMbps'] != \
                        get_limits_in_mb(sdc_details['bandwidth_limit']):
                    limits_dict['bandwidth_limit'] = \
                        sdc_details['bandwidth_limit']
            break
    return access_mode_dict, limits_dict


def get_limits_in_mb(limits):
    """
    :param limits: Limits in KB
    :return: Limits in MB
    """

    if limits:
        return limits / 1024


def get_access_mode(access_mode):
    """
    :param access_mode: Access mode of the SDC
    :return: The enum for the access mode
    """

    access_mode_dict = {
        "READ_WRITE": "ReadWrite",
        "READ_ONLY": "ReadOnly",
        "NO_ACCESS": "NoAccess"
    }
    return access_mode_dict.get(access_mode)


def get_vol_type(vol_type):
    """
    :param vol_type: Type of the volume
    :return: Corresponding value for the entered vol_type
    """
    vol_type_dict = {
        "THICK_PROVISIONED": "ThickProvisioned",
        "THIN_PROVISIONED": "ThinProvisioned",
    }
    return vol_type_dict.get(vol_type)


def get_powerflex_volume_parameters():
    """This method provide parameter required for the volume
    module on PowerFlex"""
    return dict(
        vol_name=dict(), vol_id=dict(),
        storage_pool_name=dict(), storage_pool_id=dict(),
        protection_domain_name=dict(), protection_domain_id=dict(),
        use_rmcache=dict(type='bool'), snapshot_policy_name=dict(),
        snapshot_policy_id=dict(),
        size=dict(type='int'),
        cap_unit=dict(choices=['GB', 'TB']),
        vol_type=dict(choices=['THICK_PROVISIONED', 'THIN_PROVISIONED']),
        compression_type=dict(choices=['NORMAL', 'NONE']),
        auto_snap_remove_type=dict(choices=['detach', 'remove']),
        vol_new_name=dict(),
        allow_multiple_mappings=dict(type='bool'),
        delete_snapshots=dict(type='bool'),
        sdc=dict(
            type='list', elements='dict', options=dict(
                sdc_id=dict(), sdc_ip=dict(),
                sdc_name=dict(),
                access_mode=dict(choices=['READ_WRITE', 'READ_ONLY',
                                          'NO_ACCESS']),
                bandwidth_limit=dict(type='int'),
                iops_limit=dict(type='int')
            )
        ),
        sdc_state=dict(choices=['mapped', 'unmapped']),
        state=dict(required=True, type='str', choices=['present', 'absent'])
    )


def main():
    """ Create PowerFlex volume object and perform actions on it
        based on user input from playbook"""
    obj = PowerFlexVolume()
    obj.perform_module_operation()


if __name__ == '__main__':
    main()