Debian Codegraph @

ansible_collections/dellemc/powerflex/plugins/modules/volume_v2.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # Copyright: (c) 2025, Dell Technologies
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """Ansible module for managing volumes on Dell Technologies (Dell) PowerFlex"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r"""
13 module: volume_v2
14 version_added: '3.0.0'
15 short_description: Manage volumes on Dell PowerFlex
16 description:
17 - Managing volumes on PowerFlex storage system includes
18 creating, getting details, modifying attributes and deleting volume.
19 - It also includes adding/removing snapshot policy,
20 mapping/unmapping volume to/from SDC and listing
21 associated snapshots.
22
23 author:
24 - Yuhao Liu (@RayLiu7) <[email protected]>
25
26 extends_documentation_fragment:
27 - dellemc.powerflex.powerflex_v2
28 options:
29 vol_name:
30 description:
31 - The name of the volume.
32 - Mandatory for create operation.
33 - It is unique across the PowerFlex array.
34 - Mutually exclusive with I(vol_id).
35 type: str
36 vol_id:
37 description:
38 - The ID of the volume.
39 - Except create operation, all other operations can be performed
40 using I(vol_id).
41 - Mutually exclusive with I(vol_name).
42 type: str
43 storage_pool_name:
44 description:
45 - The name of the storage pool.
46 - Either name or the id of the storage pool is required for creating a
47 volume.
48 - During creation, if storage pool name is provided then either
49 protection domain name or id must be mentioned along with it.
50 - Mutually exclusive with I(storage_pool_id).
51 type: str
52 storage_pool_id:
53 description:
54 - The ID of the storage pool.
55 - Either name or the id of the storage pool is required for creating
56 a volume.
57 - Mutually exclusive with I(storage_pool_name).
58 type: str
59 protection_domain_name:
60 description:
61 - The name of the protection domain.
62 - During creation of a volume, if more than one storage pool exists with
63 the same name then either protection domain name or id must be
64 mentioned along with it.
65 - Mutually exclusive with I(protection_domain_id).
66 type: str
67 protection_domain_id:
68 description:
69 - The ID of the protection domain.
70 - During creation of a volume, if more than one storage pool exists with
71 the same name then either protection domain name or id must be
72 mentioned along with it.
73 - Mutually exclusive with I(protection_domain_name).
74 type: str
75 vol_type:
76 description:
77 - Type of volume provisioning.
78 choices: ["THICK_PROVISIONED", "THIN_PROVISIONED"]
79 type: str
80 snapshot_policy_name:
81 description:
82 - Name of the snapshot policy.
83 - To remove/detach snapshot policy, empty
84 I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
85 I(auto_snap_remove_type).
86 type: str
87 snapshot_policy_id:
88 description:
89 - ID of the snapshot policy.
90 - To remove/detach snapshot policy, empty
91 I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
92 I(auto_snap_remove_type).
93 type: str
94 auto_snap_remove_type:
95 description:
96 - Whether to remove or detach the snapshot policy.
97 - To remove/detach snapshot policy, empty
98 I(snapshot_policy_id)/I(snapshot_policy_name) is to be passed along with
99 I(auto_snap_remove_type).
100 - If the snapshot policy name/id is passed empty then
101 I(auto_snap_remove_type) is defaulted to C(detach).
102 choices: ['remove', 'detach']
103 type: str
104 size:
105 description:
106 - The size of the volume.
107 - Size of the volume will be assigned as higher multiple of 8 GB.
108 type: int
109 cap_unit:
110 description:
111 - The unit of the volume size. It defaults to 'GB'.
112 choices: ['GB' , 'TB']
113 type: str
114 vol_new_name:
115 description:
116 - New name of the volume. Used to rename the volume.
117 type: str
118 refresh_src_vol_id:
119 description:
120 - ID of the source volume/snapshot to refresh from.
121 - Either the name or the id of the source volume/snapshot is required
122 - Mutually exclusive with I(refresh_src_vol_name).
123 type: str
124 refresh_src_vol_name:
125 description:
126 - Name of the source volume/snapshot to refresh from.
127 - Either the name or the id of the source volume/snapshot is required
128 - Mutually exclusive with I(refresh_src_vol_id).
129 type: str
130 restore_src_vol_id:
131 description:
132 - ID of the source volume/snapshot to restore from.
133 - Either the name or the id of the source volume/snapshot is required
134 - Mutually exclusive with I(restore_src_vol_name).
135 type: str
136 restore_src_vol_name:
137 description:
138 - Name of the source volume/snapshot to restore from.
139 - Either the name or the id of the source volume/snapshot is required
140 - Mutually exclusive with I(restore_src_vol_id).
141 type: str
142 allow_multiple_mappings:
143 description:
144 - Specifies whether to allow or not allow multiple mappings.
145 - If the volume is mapped to one SDC then for every new mapping
146 I(allow_multiple_mappings) has to be passed as true.
147 type: bool
148 sdc:
149 description:
150 - Specifies SDC parameters.
151 type: list
152 elements: dict
153 suboptions:
154 sdc_name:
155 description:
156 - Name of the SDC.
157 - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
158 - Mutually exclusive with I(sdc_id) and I(sdc_ip).
159 type: str
160 sdc_id:
161 description:
162 - ID of the SDC.
163 - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
164 - Mutually exclusive with I(sdc_name) and I(sdc_ip).
165 type: str
166 sdc_ip:
167 description:
168 - IP of the SDC.
169 - Specify either I(sdc_name), I(sdc_id) or I(sdc_ip).
170 - Mutually exclusive with I(sdc_id) and I(sdc_ip).
171 type: str
172 access_mode:
173 description:
174 - Define the access mode for all mappings of the volume.
175 choices: ['READ_WRITE', 'READ_ONLY', 'NO_ACCESS']
176 type: str
177 bandwidth_limit:
178 description:
179 - Limit of volume network bandwidth.
180 - Need to mention in multiple of 1024 Kbps.
181 - To set no limit, 0 is to be passed.
182 type: int
183 iops_limit:
184 description:
185 - Limit of volume IOPS.
186 - Minimum IOPS limit is 11 and specify 0 for unlimited iops.
187 type: int
188 sdc_state:
189 description:
190 - Mapping state of the SDC.
191 choices: ['mapped', 'unmapped']
192 type: str
193 delete_snapshots:
194 description:
195 - If C(true), the volume and all its dependent snapshots will be deleted.
196 - If C(false), only the volume will be deleted.
197 - It can be specified only when the I(state) is C(absent).
198 - It defaults to C(false), if not specified.
199 type: bool
200 state:
201 description:
202 - State of the volume.
203 choices: ['present', 'absent']
204 required: true
205 type: str
206 attributes:
207 check_mode:
208 description: Runs task to validate without performing action on the target
209 machine.
210 support: full
211 diff_mode:
212 description: Runs the task to report the changes made or to be made.
213 support: full
214 notes:
215 - Compression_type and use_rmcache are not supported since PowerFlex 5.0.0
216 - Refresh and restore cannot be conducted in the same task.
217 """
218
219 EXAMPLES = r"""
220 - name: Create a volume
221 dellemc.powerflex.volume_v2:
222 hostname: "{{hostname}}"
223 username: "{{username}}"
224 password: "{{password}}"
225 validate_certs: "{{validate_certs}}"
226 port: "{{port}}"
227 vol_name: "sample_volume"
228 storage_pool_name: "pool_1"
229 protection_domain_name: "pd_1"
230 vol_type: "THIN_PROVISIONED"
231 size: 16
232 state: "present"
233
234 - name: Map a SDC to volume
235 dellemc.powerflex.volume_v2:
236 hostname: "{{hostname}}"
237 username: "{{username}}"
238 password: "{{password}}"
239 validate_certs: "{{validate_certs}}"
240 port: "{{port}}"
241 vol_name: "sample_volume"
242 allow_multiple_mappings: true
243 sdc:
244 - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
245 access_mode: "READ_WRITE"
246 sdc_state: "mapped"
247 state: "present"
248
249 - name: Unmap a SDC to volume
250 dellemc.powerflex.volume_v2:
251 hostname: "{{hostname}}"
252 username: "{{username}}"
253 password: "{{password}}"
254 validate_certs: "{{validate_certs}}"
255 port: "{{port}}"
256 vol_name: "sample_volume"
257 sdc:
258 - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
259 sdc_state: "unmapped"
260 state: "present"
261
262 - name: Map multiple SDCs to a volume
263 dellemc.powerflex.volume_v2:
264 hostname: "{{hostname}}"
265 username: "{{username}}"
266 password: "{{password}}"
267 validate_certs: "{{validate_certs}}"
268 port: "{{port}}"
269 vol_name: "sample_volume"
270 protection_domain_name: "pd_1"
271 sdc:
272 - sdc_id: "92A304DB-EFD7-44DF-A07E-D78134CC9764"
273 access_mode: "READ_WRITE"
274 bandwidth_limit: 2048
275 iops_limit: 20
276 - sdc_ip: "198.10.xxx.xxx"
277 access_mode: "READ_ONLY"
278 allow_multiple_mappings: true
279 sdc_state: "mapped"
280 state: "present"
281
282 - name: Get the details of the volume
283 dellemc.powerflex.volume_v2:
284 hostname: "{{hostname}}"
285 username: "{{username}}"
286 password: "{{password}}"
287 validate_certs: "{{validate_certs}}"
288 port: "{{port}}"
289 vol_id: "fe6c8b7100000005"
290 state: "present"
291
292 - name: Restore volume
293 dellemc.powerflex.volume_v2:
294 hostname: "{{hostname}}"
295 username: "{{username}}"
296 password: "{{password}}"
297 validate_certs: "{{validate_certs}}"
298 port: "{{port}}"
299 restore_src_vol_id: "fe6c8b7100000006"
300 state: "present"
301
302 - name: Refresh volume
303 dellemc.powerflex.volume_v2:
304 hostname: "{{hostname}}"
305 username: "{{username}}"
306 password: "{{password}}"
307 validate_certs: "{{validate_certs}}"
308 port: "{{port}}"
309 refresh_src_vol_name: "example_snapshot"
310 state: "present"
311
312 - name: Modify the details of the Volume
313 dellemc.powerflex.volume_v2:
314 hostname: "{{hostname}}"
315 username: "{{username}}"
316 password: "{{password}}"
317 validate_certs: "{{validate_certs}}"
318 port: "{{port}}"
319 vol_name: "sample_volume"
320 storage_pool_name: "pool_1"
321 vol_new_name: "new_sample_volume"
322 size: 64
323 state: "present"
324
325 - name: Delete the Volume
326 dellemc.powerflex.volume_v2:
327 hostname: "{{hostname}}"
328 username: "{{username}}"
329 password: "{{password}}"
330 validate_certs: "{{validate_certs}}"
331 port: "{{port}}"
332 vol_name: "sample_volume"
333 delete_snapshots: false
334 state: "absent"
335
336 - name: Delete the Volume and all its dependent snapshots
337 dellemc.powerflex.volume_v2:
338 hostname: "{{hostname}}"
339 username: "{{username}}"
340 password: "{{password}}"
341 validate_certs: "{{validate_certs}}"
342 port: "{{port}}"
343 vol_name: "sample_volume"
344 delete_snapshots: true
345 state: "absent"
346 """
347
348 RETURN = r"""
349 changed:
350 description: Whether or not the resource has changed.
351 returned: always
352 type: bool
353 sample: 'false'
354 volume_details:
355 description: Details of the volume.
356 returned: When volume exists
357 type: dict
358 contains:
359 id:
360 description: The ID of the volume.
361 type: str
362 mappedSdcInfo:
363 description: The details of the mapped SDC.
364 type: dict
365 contains:
366 sdcId:
367 description: ID of the SDC.
368 type: str
369 sdcName:
370 description: Name of the SDC.
371 type: str
372 sdcIp:
373 description: IP of the SDC.
374 type: str
375 accessMode:
376 description: Mapping access mode for the specified volume.
377 type: str
378 limitIops:
379 description: IOPS limit for the SDC.
380 type: int
381 limitBwInMbps:
382 description: Bandwidth limit for the SDC.
383 type: int
384 name:
385 description: Name of the volume.
386 type: str
387 sizeInKb:
388 description: Size of the volume in Kb.
389 type: int
390 sizeInGb:
391 description: Size of the volume in Gb.
392 type: int
393 storagePoolId:
394 description: ID of the storage pool in which volume resides.
395 type: str
396 storagePoolName:
397 description: Name of the storage pool in which volume resides.
398 type: str
399 protectionDomainId:
400 description: ID of the protection domain in which volume resides.
401 type: str
402 protectionDomainName:
403 description: Name of the protection domain in which volume resides.
404 type: str
405 snapshotPolicyId:
406 description: ID of the snapshot policy associated with volume.
407 type: str
408 snapshotPolicyName:
409 description: Name of the snapshot policy associated with volume.
410 type: str
411 snapshotsList:
412 description: List of snapshots associated with the volume.
413 type: str
414 statistics:
415 description: Statistics details of the volume.
416 type: dict
417 contains:
418 "avg_host_read_latency":
419 description: Average host read latency.
420 type: int
421 "avg_host_trim_latency":
422 description: Average host trim latency.
423 type: int
424 "avg_host_write_latency":
425 description: Average host write latency.
426 type: int
427 "host_read_bandwidth":
428 description: Host read bandwidth.
429 type: int
430 "host_read_iops":
431 description: Host read IOPS.
432 type: int
433 "host_trim_bandwidth":
434 description: Host trim bandwidth.
435 type: int
436 "host_trim_iops":
437 description: Host trim IOPS.
438 type: int
439 "host_write_bandwidth":
440 description: Host write bandwidth.
441 type: int
442 "host_write_iops":
443 description: Host write IOPS.
444 type: int
445 "logical_provisioned":
446 description: Logical provisioned size.
447 type: int
448 "logical_used":
449 description: Logical used size.
450 type: int
451 sample: {
452 "accessModeLimit": "ReadWrite",
453 "ancestorVolumeId": null,
454 "autoSnapshotGroupId": null,
455 "compressionMethod": "Invalid",
456 "consistencyGroupId": null,
457 "creationTime": 1631618520,
458 "dataLayout": "MediumGranularity",
459 "genType": "EC",
460 "id": "cdd883cf00000002",
461 "links": [
462 {
463 "href": "/api/instances/Volume::cdd883cf00000002",
464 "rel": "self"
465 },
466 {
467 "href": "/api/instances/Volume::cdd883cf00000002/relationships
468 /Statistics",
469 "rel": "/api/Volume/relationship/Statistics"
470 },
471 {
472 "href": "/api/instances/VTree::6e86255c00000001",
473 "rel": "/api/parent/relationship/vtreeId"
474 },
475 {
476 "href": "/api/instances/StoragePool::e0d8f6c900000000",
477 "rel": "/api/parent/relationship/storagePoolId"
478 }
479 ],
480 "lockedAutoSnapshot": false,
481 "lockedAutoSnapshotMarkedForRemoval": false,
482 "managedBy": "ScaleIO",
483 "mappedSdcInfo": null,
484 "name": "ansible-volume-1",
485 "notGenuineSnapshot": false,
486 "nsid": 23,
487 "originalExpiryTime": 0,
488 "pairIds": null,
489 "protectionDomainId": "9300c1f900000000",
490 "protectionDomainName": "domain1",
491 "replicationJournalVolume": false,
492 "replicationTimeStamp": 0,
493 "retentionLevels": [],
494 "secureSnapshotExpTime": 0,
495 "sizeInGB": 16,
496 "sizeInKb": 16777216,
497 "snapshotPolicyId": null,
498 "snapshotPolicyName": null,
499 "snapshotsList": [
500 {
501 "accessModeLimit": "ReadOnly",
502 "ancestorVolumeId": "cdd883cf00000002",
503 "autoSnapshotGroupId": null,
504 "compressionMethod": "Invalid",
505 "consistencyGroupId": "22f1e80c00000001",
506 "creationTime": 1631619229,
507 "dataLayout": "MediumGranularity",
508 "id": "cdd883d000000004",
509 "links": [
510 {
511 "href": "/api/instances/Volume::cdd883d000000004",
512 "rel": "self"
513 },
514 {
515 "href": "/api/instances/Volume::cdd883d000000004
516 /relationships/Statistics",
517 "rel": "/api/Volume/relationship/Statistics"
518 },
519 {
520 "href": "/api/instances/Volume::cdd883cf00000002",
521 "rel": "/api/parent/relationship/ancestorVolumeId"
522 },
523 {
524 "href": "/api/instances/VTree::6e86255c00000001",
525 "rel": "/api/parent/relationship/vtreeId"
526 },
527 {
528 "href": "/api/instances/StoragePool::e0d8f6c900000000",
529 "rel": "/api/parent/relationship/storagePoolId"
530 }
531 ],
532 "lockedAutoSnapshot": false,
533 "lockedAutoSnapshotMarkedForRemoval": false,
534 "managedBy": "ScaleIO",
535 "mappedSdcInfo": null,
536 "name": "ansible_vol_snap_1",
537 "notGenuineSnapshot": false,
538 "originalExpiryTime": 0,
539 "pairIds": null,
540 "replicationJournalVolume": false,
541 "replicationTimeStamp": 0,
542 "retentionLevels": [],
543 "secureSnapshotExpTime": 0,
544 "sizeInKb": 16777216,
545 "snplIdOfAutoSnapshot": null,
546 "snplIdOfSourceVolume": null,
547 "storagePoolId": "e0d8f6c900000000",
548 "timeStampIsAccurate": false,
549 "useRmcache": false,
550 "volumeReplicationState": "UnmarkedForReplication",
551 "volumeType": "Snapshot",
552 "vtreeId": "6e86255c00000001"
553 }
554 ],
555 "statistics": {
556 'host_trim_bandwidth': 0,
557 'host_trim_iops': 0,
558 'avg_host_write_latency': 0,
559 'logical_provisioned': 3221225472,
560 'avg_host_read_latency': 0,
561 'host_read_bandwidth': 0,
562 'host_read_iops': 0,
563 'logical_used': 0,
564 'host_write_bandwidth': 0,
565 'host_write_iops': 0,
566 'avg_host_trim_latency': 0
567 },
568 "snplIdOfAutoSnapshot": null,
569 "snplIdOfSourceVolume": null,
570 "storagePoolId": "e0d8f6c900000000",
571 "storagePoolName": "pool1",
572 "timeStampIsAccurate": false,
573 "useRmcache": false,
574 "volumeClass": "defaultclass",
575 "volumeReplicationState": "UnmarkedForReplication",
576 "volumeType": "ThinProvisioned",
577 "vtreeId": "6e86255c00000001"
578 }
579 """
580
581 from ansible.module_utils.basic import AnsibleModule
582 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell import (
583 utils,
584 )
585 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base import (
586 powerflex_compatibility,
587 )
588 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base import (
589 PowerFlexBase,
590 )
591 import copy
592
593 LOG = utils.get_logger("volume_v2")
594
595
596 @powerflex_compatibility(min_ver="5.0", predecessor="volume")
597 class PowerFlexVolumeV2(PowerFlexBase):
598 """Class with volume operations"""
599
600 def __init__(self):
601 """Define all parameters required by this module"""
602 argument_spec = get_powerflex_volume_parameters()
603
604 mut_ex_args = [
605 ["vol_name", "vol_id"],
606 ["storage_pool_name", "storage_pool_id"],
607 ["protection_domain_name", "protection_domain_id"],
608 ["snapshot_policy_name", "snapshot_policy_id"],
609 ["refresh_src_vol_id", "refresh_src_vol_name"],
610 ["restore_src_vol_id", "restore_src_vol_name"],
611 ["refresh_src_vol_id", "restore_src_vol_id"],
612 ["refresh_src_vol_name", "restore_src_vol_name"],
613 ["refresh_src_vol_name", "restore_src_vol_id"],
614 ["restore_src_vol_name", "refresh_src_vol_id"],
615 ["vol_id", "storage_pool_name"],
616 ["vol_id", "storage_pool_id"],
617 ["vol_id", "protection_domain_name"],
618 ["vol_id", "protection_domain_id"],
619 ]
620
621 required_together_args = [["sdc", "sdc_state"]]
622
623 required_one_of_args = [["vol_name", "vol_id"]]
624
625 module_params = {
626 "argument_spec": argument_spec,
627 "supports_check_mode": True,
628 "mutually_exclusive": mut_ex_args,
629 "required_together": required_together_args,
630 "required_one_of": required_one_of_args,
631 }
632
633 super().__init__(AnsibleModule, module_params)
634 super().check_module_compatibility()
635
636 def get_protection_domain(
637 self, protection_domain_name=None, protection_domain_id=None
638 ):
639 """Get protection domain details
640 :param protection_domain_name: Name of the protection domain
641 :param protection_domain_id: ID of the protection domain
642 :return: Protection domain details
643 """
644 name_or_id = (
645 protection_domain_id if protection_domain_id else protection_domain_name
646 )
647 try:
648 pd_details = None
649 if protection_domain_id:
650 pd_details = self.powerflex_conn.protection_domain.get(
651 filter_fields={"id": protection_domain_id}
652 )
653
654 if protection_domain_name:
655 pd_details = self.powerflex_conn.protection_domain.get(
656 filter_fields={"name": protection_domain_name}
657 )
658
659 if not pd_details:
660 err_msg = (
661 "Unable to find the protection domain with {0}. "
662 "Please enter a valid protection domain"
663 " name/id.".format(name_or_id)
664 )
665 self.module.fail_json(msg=err_msg)
666
667 return pd_details[0]
668
669 except Exception as e:
670 errormsg = (
671 "Failed to get the protection domain {0} with"
672 " error {1}".format(name_or_id, str(e))
673 )
674 LOG.error(errormsg)
675 self.module.fail_json(msg=errormsg)
676
677 def get_snapshot_policy(self, snap_pol_id=None, snap_pol_name=None):
678 """Get snapshot policy details
679 :param snap_pol_name: Name of the snapshot policy
680 :param snap_pol_id: ID of the snapshot policy
681 :return: snapshot policy details
682 """
683 name_or_id = snap_pol_id if snap_pol_id else snap_pol_name
684 try:
685 snap_pol_details = None
686 if snap_pol_id:
687 snap_pol_details = self.powerflex_conn.snapshot_policy.get(
688 filter_fields={"id": snap_pol_id}
689 )
690
691 if snap_pol_name:
692 snap_pol_details = self.powerflex_conn.snapshot_policy.get(
693 filter_fields={"name": snap_pol_name}
694 )
695
696 if not snap_pol_details:
697 err_msg = (
698 "Unable to find the snapshot policy with {0}. "
699 "Please enter a valid snapshot policy"
700 " name/id.".format(name_or_id)
701 )
702 self.module.fail_json(msg=err_msg)
703
704 return snap_pol_details[0]
705
706 except Exception as e:
707 errormsg = "Failed to get the snapshot policy {0} with" " error {1}".format(
708 name_or_id, str(e)
709 )
710 LOG.error(errormsg)
711 self.module.fail_json(msg=errormsg)
712
713 def get_storage_pool(
714 self, storage_pool_id=None, storage_pool_name=None, protection_domain_id=None
715 ):
716 """Get storage pool details
717 :param protection_domain_id: ID of the protection domain
718 :param storage_pool_name: The name of the storage pool
719 :param storage_pool_id: The storage pool id
720 :return: Storage pool details
721 """
722 name_or_id = storage_pool_id if storage_pool_id else storage_pool_name
723 try:
724 sp_details = None
725 if storage_pool_id:
726 sp_details = self.powerflex_conn.storage_pool.get(
727 filter_fields={"id": storage_pool_id}
728 )
729
730 if storage_pool_name:
731 sp_details = self.powerflex_conn.storage_pool.get(
732 filter_fields={"name": storage_pool_name}
733 )
734
735 if len(sp_details) > 1 and protection_domain_id is None:
736 err_msg = (
737 "More than one storage pool found with {0},"
738 " Please provide protection domain Name/Id"
739 " to fetch the unique"
740 " pool".format(storage_pool_name)
741 )
742 self.module.fail_json(msg=err_msg)
743
744 if len(sp_details) > 1 and protection_domain_id:
745 sp_details = self.powerflex_conn.storage_pool.get(
746 filter_fields={
747 "name": storage_pool_name,
748 "protectionDomainId": protection_domain_id,
749 }
750 )
751 if not sp_details:
752 err_msg = (
753 "Unable to find the storage pool with {0}. "
754 "Please enter a valid pool "
755 "name/id.".format(name_or_id)
756 )
757 self.module.fail_json(msg=err_msg)
758 return sp_details[0]
759
760 except Exception as e:
761 errormsg = "Failed to get the storage pool {0} with error " "{1}".format(
762 name_or_id, str(e)
763 )
764 LOG.error(errormsg)
765 self.module.fail_json(msg=errormsg)
766
767 def get_volume(self, vol_name=None, vol_id=None):
768 """Get volume details
769 :param vol_name: Name of the volume
770 :param vol_id: ID of the volume
771 :return: Details of volume if exist.
772 """
773
774 id_or_name = vol_id if vol_id else vol_name
775
776 try:
777 if vol_id:
778 volume_details = self.powerflex_conn.volume.get(
779 filter_fields={"id": vol_id}
780 )
781 else:
782 volume_details = self.powerflex_conn.volume.get(
783 filter_fields={"name": vol_name}
784 )
785
786 if len(volume_details) == 0:
787 msg = "Volume with identifier {0} not found".format(id_or_name)
788 LOG.info(msg)
789 return None
790
791 # Append size in GB in the volume details
792 if "sizeInKb" in volume_details[0] and volume_details[0]["sizeInKb"]:
793 volume_details[0]["sizeInGB"] = utils.get_size_in_gb(
794 volume_details[0]["sizeInKb"], "KB"
795 )
796
797 # Append storage pool name and id.
798 sp = None
799 pd_id = None
800 if (
801 "storagePoolId" in volume_details[0]
802 and volume_details[0]["storagePoolId"]
803 ):
804 sp = self.get_storage_pool(volume_details[0]["storagePoolId"])
805 if len(sp) > 0:
806 volume_details[0]["storagePoolName"] = sp["name"]
807 pd_id = sp["protectionDomainId"]
808
809 # Append protection domain name and id
810 if sp and "protectionDomainId" in sp and sp["protectionDomainId"]:
811 pd = self.get_protection_domain(protection_domain_id=pd_id)
812 volume_details[0]["protectionDomainId"] = pd_id
813 volume_details[0]["protectionDomainName"] = pd["name"]
814
815 # Append snapshot policy name and id
816 if volume_details[0]["snplIdOfSourceVolume"] is not None:
817 snap_policy_id = volume_details[0]["snplIdOfSourceVolume"]
818 volume_details[0]["snapshotPolicyId"] = snap_policy_id
819 volume_details[0]["snapshotPolicyName"] = self.get_snapshot_policy(
820 snap_policy_id
821 )["name"]
822 else:
823 volume_details[0]["snapshotPolicyId"] = None
824 volume_details[0]["snapshotPolicyName"] = None
825
826 # Append the list of snapshots associated with the volume
827 list_of_snaps = self.powerflex_conn.volume.get(
828 filter_fields={"ancestorVolumeId": volume_details[0]["id"]}
829 )
830 volume_details[0]["snapshotsList"] = list_of_snaps
831
832 # Append statistics
833 if volume_details[0]["id"]:
834 statistics = self.powerflex_conn.volume.get_statistics(
835 volume_id=[volume_details[0]["id"]]
836 )
837 volume_details[0]["statistics"] = (
838 convert_statistics(statistics) if statistics else {}
839 )
840
841 return volume_details[0]
842
843 except Exception as e:
844 error_msg = "Failed to get the volume {0} with error {1}"
845 error_msg = error_msg.format(id_or_name, str(e))
846 LOG.error(error_msg)
847 self.module.fail_json(msg=error_msg)
848
849 def get_sdc_id(self, sdc_name=None, sdc_ip=None, sdc_id=None):
850 """Get the SDC ID
851 :param sdc_name: The name of the SDC
852 :param sdc_ip: The IP of the SDC
853 :param sdc_id: The ID of the SDC
854 :return: The ID of the SDC
855 """
856
857 if sdc_name:
858 id_ip_name = sdc_name
859 elif sdc_ip:
860 id_ip_name = sdc_ip
861 else:
862 id_ip_name = sdc_id
863
864 try:
865 if sdc_name:
866 sdc_details = self.powerflex_conn.sdc.get(
867 filter_fields={"name": sdc_name}
868 )
869 elif sdc_ip:
870 sdc_details = self.powerflex_conn.sdc.get(
871 filter_fields={"sdcIp": sdc_ip}
872 )
873 else:
874 sdc_details = self.powerflex_conn.sdc.get(filter_fields={"id": sdc_id})
875
876 if len(sdc_details) == 0:
877 error_msg = "Unable to find SDC with identifier {0}".format(id_ip_name)
878 self.module.fail_json(msg=error_msg)
879 return sdc_details[0]["id"]
880 except Exception as e:
881 errormsg = "Failed to get the SDC {0} with error " "{1}".format(
882 id_ip_name, str(e)
883 )
884 LOG.error(errormsg)
885 self.module.fail_json(msg=errormsg)
886
887 def create_volume(self, vol_name, pool_id, size, vol_type=None):
888 """Create volume
889 :param vol_type: Type of volume.
890 :param size: Size of the volume.
891 :param pool_id: Id of the storage pool.
892 :param vol_name: The name of the volume.
893 :return: Boolean indicating if create operation is successful
894 """
895 try:
896 if vol_name is None or len(vol_name.strip()) == 0:
897 self.module.fail_json(msg="Please provide valid volume name.")
898
899 if not size:
900 self.module.fail_json(
901 msg="Size is a mandatory parameter "
902 "for creating a volume. Please "
903 "enter a valid size"
904 )
905
906 # Basic volume created.
907 if not self.module.check_mode:
908 self.powerflex_conn.volume.create(
909 storage_pool_id=pool_id,
910 size_in_gb=size,
911 name=vol_name,
912 volume_type=vol_type,
913 )
914 return True
915
916 except Exception as e:
917 errormsg = "Create volume {0} operation failed with " "error {1}".format(
918 vol_name, str(e)
919 )
920 LOG.error(errormsg)
921 self.module.fail_json(msg=errormsg)
922
923 def modify_access_mode(self, vol_id, access_mode_list):
924 """Modify access mode of SDCs mapped to volume
925 :param vol_id: The volume id
926 :param access_mode_list: List containing SDC ID's
927 whose access mode is to modified
928 :return: Boolean indicating if modifying access
929 mode is successful
930 """
931
932 try:
933 changed = False
934 for temp in access_mode_list:
935 if temp["accessMode"]:
936 if not self.module.check_mode:
937 self.powerflex_conn.volume.set_access_mode_for_sdc(
938 volume_id=vol_id,
939 sdc_id=temp["sdc_id"],
940 access_mode=temp["accessMode"],
941 )
942 changed = True
943 return changed
944 except Exception as e:
945 errormsg = (
946 "Modify access mode of SDC operation failed "
947 "with error {0}".format(str(e))
948 )
949 LOG.error(errormsg)
950 self.module.fail_json(msg=errormsg)
951
952 def modify_limits(self, payload):
953 """Modify IOPS and bandwidth limits of SDC's mapped to volume
954 :param payload: Dict containing SDC ID's whose bandwidth and
955 IOPS is to modified
956 :return: Boolean indicating if modifying limits is successful
957 """
958
959 try:
960 changed = False
961 if (
962 payload["bandwidth_limit"] is not None
963 or payload["iops_limit"] is not None
964 ):
965 if not self.module.check_mode:
966 self.powerflex_conn.volume.set_mapped_sdc_limits(**payload)
967 changed = True
968 return changed
969 except Exception as e:
970 errormsg = (
971 "Modify bandwidth/iops limits of SDC %s operation "
972 "failed with error %s" % (payload["sdc_id"], str(e))
973 )
974 LOG.error(errormsg)
975 self.module.fail_json(msg=errormsg)
976
977 def delete_volume(self, vol_id, remove_mode):
978 """Delete volume
979 :param vol_id: The volume id
980 :param remove_mode: Removal mode for the volume
981 :return: Boolean indicating if delete operation is successful
982 """
983
984 try:
985 if not self.module.check_mode:
986 self.powerflex_conn.volume.delete(vol_id, remove_mode)
987 return True
988 except Exception as e:
989 errormsg = "Delete volume {0} operation failed with " "error {1}".format(
990 vol_id, str(e)
991 )
992 LOG.error(errormsg)
993 self.module.fail_json(msg=errormsg)
994
995 def unmap_volume_from_sdc(self, volume, sdc):
996 """Unmap SDC's from volume
997 :param volume: volume details
998 :param sdc: List of SDCs to be unmapped
999 :return: Boolean indicating if unmap operation is successful
1000 """
1001
1002 current_sdcs = volume["mappedSdcInfo"]
1003 current_sdc_ids = []
1004 sdc_id_list = []
1005 sdc_id = None
1006 if current_sdcs:
1007 for temp in current_sdcs:
1008 current_sdc_ids.append(temp["sdcId"])
1009
1010 for temp in sdc:
1011 if "sdc_name" in temp and temp["sdc_name"]:
1012 sdc_id = self.get_sdc_id(sdc_name=temp["sdc_name"])
1013 elif "sdc_ip" in temp and temp["sdc_ip"]:
1014 sdc_id = self.get_sdc_id(sdc_ip=temp["sdc_ip"])
1015 else:
1016 sdc_id = self.get_sdc_id(sdc_id=temp["sdc_id"])
1017 if sdc_id in current_sdc_ids:
1018 sdc_id_list.append(sdc_id)
1019
1020 LOG.info("SDC IDs to remove %s", sdc_id_list)
1021
1022 if len(sdc_id_list) == 0:
1023 return False
1024
1025 try:
1026 if not self.module.check_mode:
1027 for sdc_id in sdc_id_list:
1028 self.powerflex_conn.volume.remove_mapped_host(volume["id"], sdc_id)
1029 return True
1030 except Exception as e:
1031 errormsg = "Unmap SDC {0} from volume {1} failed with error " "{2}".format(
1032 sdc_id, volume["id"], str(e)
1033 )
1034 LOG.error(errormsg)
1035 self.module.fail_json(msg=errormsg)
1036
1037 def map_volume_to_sdc(self, volume, sdc):
1038 """Map SDC's to volume
1039 :param volume: volume details
1040 :param sdc: List of SDCs
1041 :return: Boolean indicating if mapping operation is successful
1042 """
1043
1044 current_sdcs = volume["mappedSdcInfo"]
1045 sdc_id_list = []
1046 sdc_map_list = []
1047 sdc_modify_list1 = []
1048 sdc_modify_list2 = []
1049
1050 current_sdc_ids = self.get_current_sdcs(current_sdcs)
1051
1052 for temp in sdc:
1053 sdc_id = self.get_sdc_id_from_input(temp)
1054 if sdc_id not in current_sdc_ids:
1055 sdc_id_list.append(sdc_id)
1056 self.update_temp_data(temp, sdc_id)
1057 sdc_map_list.append(temp)
1058 else:
1059 access_mode_dict, limits_dict = check_for_sdc_modification(
1060 volume, sdc_id, temp
1061 )
1062 self.update_sdc_lists(
1063 sdc_modify_list1, sdc_modify_list2, access_mode_dict, limits_dict
1064 )
1065
1066 LOG.info("SDC to add: %s", sdc_map_list)
1067
1068 if not sdc_map_list:
1069 return False, sdc_modify_list1, sdc_modify_list2
1070
1071 try:
1072 changed = False
1073 for sdc in sdc_map_list:
1074 payload = {
1075 "volume_id": volume["id"],
1076 "host_id": sdc["sdc_id"],
1077 "access_mode": sdc["access_mode"],
1078 "allow_multiple_mappings": self.module.params[
1079 "allow_multiple_mappings"
1080 ],
1081 }
1082 if not self.module.check_mode:
1083 self.powerflex_conn.volume.add_mapped_host(**payload)
1084
1085 if sdc["bandwidth_limit"] or sdc["iops_limit"]:
1086 payload = {
1087 "volume_id": volume["id"],
1088 "sdc_id": sdc["sdc_id"],
1089 "bandwidth_limit": sdc["bandwidth_limit"],
1090 "iops_limit": sdc["iops_limit"],
1091 }
1092
1093 if not self.module.check_mode:
1094 self.powerflex_conn.volume.set_mapped_sdc_limits(**payload)
1095 changed = True
1096 return changed, sdc_modify_list1, sdc_modify_list2
1097 except Exception as e:
1098 errormsg = "Mapping volume {0} to SDC {1} " "failed with error {2}".format(
1099 volume["name"], sdc["sdc_id"], str(e)
1100 )
1101 LOG.error(errormsg)
1102 self.module.fail_json(msg=errormsg)
1103
1104 def update_sdc_lists(
1105 self, sdc_modify_list1, sdc_modify_list2, access_mode_dict, limits_dict
1106 ):
1107 if access_mode_dict:
1108 sdc_modify_list1.append(access_mode_dict)
1109 if limits_dict:
1110 sdc_modify_list2.append(limits_dict)
1111
1112 def get_sdc_id_from_input(self, temp):
1113 if "sdc_name" in temp and temp["sdc_name"]:
1114 sdc_id = self.get_sdc_id(sdc_name=temp["sdc_name"])
1115 elif "sdc_ip" in temp and temp["sdc_ip"]:
1116 sdc_id = self.get_sdc_id(sdc_ip=temp["sdc_ip"])
1117 else:
1118 sdc_id = self.get_sdc_id(sdc_id=temp["sdc_id"])
1119 return sdc_id
1120
1121 def update_temp_data(self, temp, sdc_id):
1122 temp["sdc_id"] = sdc_id
1123 if "access_mode" in temp:
1124 temp["access_mode"] = get_access_mode(temp["access_mode"])
1125 if "bandwidth_limit" not in temp:
1126 temp["bandwidth_limit"] = None
1127 if "iops_limit" not in temp:
1128 temp["iops_limit"] = None
1129
1130 def get_current_sdcs(self, current_sdcs):
1131 current_sdc_ids = []
1132 if current_sdcs:
1133 for temp in current_sdcs:
1134 current_sdc_ids.append(temp["sdcId"])
1135 return current_sdc_ids
1136
1137 def validate_parameters(
1138 self, auto_snap_remove_type, snap_pol_id, snap_pol_name, delete_snaps, state
1139 ):
1140 """Validate the input parameters"""
1141
1142 sdc = self.module.params["sdc"]
1143 cap_unit = self.module.params["cap_unit"]
1144 size = self.module.params["size"]
1145
1146 if sdc:
1147 for temp in sdc:
1148 if (
1149 all([temp["sdc_id"], temp["sdc_ip"]])
1150 or all([temp["sdc_id"], temp["sdc_name"]])
1151 or all([temp["sdc_ip"], temp["sdc_name"]])
1152 ):
1153 self.module.fail_json(
1154 msg="sdc_id, sdc_ip and sdc_name " "are mutually exclusive"
1155 )
1156
1157 if (cap_unit is not None) and not size:
1158 self.module.fail_json(
1159 msg="cap_unit can be specified along "
1160 "with size only. Please enter a valid"
1161 " value for size"
1162 )
1163
1164 if auto_snap_remove_type and snap_pol_name is None and snap_pol_id is None:
1165 err_msg = (
1166 "To remove/detach snapshot policy, please provide"
1167 " empty snapshot policy name/id along with "
1168 "auto_snap_remove_type parameter"
1169 )
1170 LOG.error(err_msg)
1171 self.module.fail_json(msg=err_msg)
1172
1173 if state == "present" and delete_snaps is not None:
1174 self.module.fail_json(
1175 msg="delete_snapshots can be specified only when the state"
1176 " is passed as absent."
1177 )
1178
1179 def refresh_volume(self, vol_id, refresh_src_vol_id):
1180 """
1181 Refresh the volume
1182 :param vol_id: Id of the volume
1183 :param refresh_src_vol_id: Id of the source volume/snapshot
1184 """
1185 try:
1186 msg = "Refreshing the volume {0} with source volume id " "{1}".format(
1187 vol_id, refresh_src_vol_id
1188 )
1189 LOG.info(msg)
1190 if not self.module.check_mode:
1191 self.powerflex_conn.volume.refresh(vol_id, refresh_src_vol_id)
1192 except Exception as e:
1193 err_msg = "Failed to refresh volume {0} operation with " "error {1}".format(
1194 vol_id, str(e)
1195 )
1196 LOG.error(err_msg)
1197 self.module.fail_json(msg=err_msg)
1198
1199 def restore_volume(self, vol_id, restore_src_vol_id):
1200 """
1201 Restore the volume
1202 :param vol_id: Id of the volume
1203 :param restore_src_vol_id: Id of the source volume/snapshot
1204 """
1205 try:
1206 msg = "Restoring the volume {0} with source volume id " "{1}".format(
1207 vol_id, restore_src_vol_id
1208 )
1209 LOG.info(msg)
1210 if not self.module.check_mode:
1211 self.powerflex_conn.volume.restore(vol_id, restore_src_vol_id)
1212 except Exception as e:
1213 err_msg = "Failed to restore volume {0} operation with " "error {1}".format(
1214 vol_id, str(e)
1215 )
1216 LOG.error(err_msg)
1217 self.module.fail_json(msg=err_msg)
1218
1219 def modify_volume(self, vol_id, modify_dict):
1220 """
1221 Update the volume attributes
1222 :param vol_id: Id of the volume
1223 :param modify_dict: Dictionary containing the attributes of
1224 volume which are to be updated
1225 :return: True, if the operation is successful
1226 """
1227 try:
1228 msg = (
1229 "Dictionary containing attributes which are to be"
1230 " updated is {0}.".format(str(modify_dict))
1231 )
1232 LOG.info(msg)
1233
1234 if "auto_snap_remove_type" in modify_dict:
1235 snap_type = modify_dict["auto_snap_remove_type"]
1236 msg = (
1237 "Removing/detaching the snapshot policy from a "
1238 "volume. auto_snap_remove_type: {0} and snapshot "
1239 "policy id: "
1240 "{1}".format(snap_type, modify_dict["snap_pol_id"])
1241 )
1242 LOG.info(msg)
1243 if not self.module.check_mode:
1244 self.powerflex_conn.snapshot_policy.remove_source_volume(
1245 modify_dict["snap_pol_id"], vol_id, snap_type
1246 )
1247 msg = "The snapshot policy has been {0}ed " "successfully".format(
1248 snap_type
1249 )
1250 LOG.info(msg)
1251
1252 if (
1253 "auto_snap_remove_type" not in modify_dict
1254 and "snap_pol_id" in modify_dict
1255 ):
1256 if not self.module.check_mode:
1257 self.powerflex_conn.snapshot_policy.add_source_volume(
1258 modify_dict["snap_pol_id"], vol_id
1259 )
1260 msg = (
1261 "Attached the snapshot policy {0} to volume"
1262 " successfully.".format(modify_dict["snap_pol_id"])
1263 )
1264 LOG.info(msg)
1265
1266 if "new_name" in modify_dict:
1267 if not self.module.check_mode:
1268 self.powerflex_conn.volume.rename(vol_id, modify_dict["new_name"])
1269 msg = (
1270 "The name of the volume is updated"
1271 " to {0} sucessfully.".format(modify_dict["new_name"])
1272 )
1273 LOG.info(msg)
1274
1275 if "new_size" in modify_dict:
1276 if not self.module.check_mode:
1277 self.powerflex_conn.volume.extend(vol_id, modify_dict["new_size"])
1278 msg = (
1279 "The size of the volume is extended to {0} "
1280 "sucessfully.".format(str(modify_dict["new_size"]))
1281 )
1282 LOG.info(msg)
1283
1284 return True
1285
1286 except Exception as e:
1287 err_msg = "Failed to update the volume {0}" " with error {1}".format(
1288 vol_id, str(e)
1289 )
1290 LOG.error(err_msg)
1291 self.module.fail_json(msg=err_msg)
1292
1293 def to_modify(
1294 self, vol_details, new_size, new_name, snap_pol_id, auto_snap_remove_type
1295 ):
1296 """
1297
1298 :param vol_details: Details of the volume
1299 :param new_size: Size of the volume
1300 :param new_name: The new name of the volume
1301 :param snap_pol_id: Id of the snapshot policy
1302 :param auto_snap_remove_type: Whether to remove or detach the policy
1303 :return: Dictionary containing the attributes of
1304 volume which are to be updated
1305 """
1306 modify_dict = {}
1307
1308 vol_size_in_gb = utils.get_size_in_gb(vol_details["sizeInKb"], "KB")
1309
1310 self.update_new_size(new_size, modify_dict, vol_size_in_gb)
1311
1312 self.update_new_name(vol_details, new_name, modify_dict)
1313
1314 if (
1315 snap_pol_id is not None
1316 and snap_pol_id == ""
1317 and auto_snap_remove_type
1318 and vol_details["snplIdOfSourceVolume"]
1319 ):
1320 modify_dict["auto_snap_remove_type"] = auto_snap_remove_type
1321 modify_dict["snap_pol_id"] = vol_details["snplIdOfSourceVolume"]
1322
1323 if snap_pol_id is not None and snap_pol_id != "":
1324 if auto_snap_remove_type and vol_details["snplIdOfSourceVolume"]:
1325 err_msg = (
1326 "To remove/detach a snapshot policy, provide the"
1327 " snapshot policy name/id as empty string"
1328 )
1329 self.module.fail_json(msg=err_msg)
1330 if (
1331 auto_snap_remove_type is None
1332 and vol_details["snplIdOfSourceVolume"] is None
1333 ):
1334 modify_dict["snap_pol_id"] = snap_pol_id
1335
1336 return modify_dict
1337
1338 def update_new_name(self, vol_details, new_name, modify_dict):
1339 if new_name is not None:
1340 if new_name is None or len(new_name.strip()) == 0:
1341 self.module.fail_json(msg="Please provide valid volume " "name.")
1342 if new_name != vol_details["name"]:
1343 modify_dict["new_name"] = new_name
1344
1345 def update_new_size(self, new_size, modify_dict, vol_size_in_gb):
1346 if new_size is not None and not (
1347 (vol_size_in_gb - 8) < new_size <= vol_size_in_gb
1348 ):
1349 modify_dict["new_size"] = new_size
1350
1351 def verify_params(
1352 self,
1353 vol_details,
1354 snap_pol_name,
1355 snap_pol_id,
1356 pd_name,
1357 pd_id,
1358 pool_name,
1359 pool_id,
1360 ):
1361 """
1362 :param vol_details: Details of the volume
1363 :param snap_pol_name: Name of the snapshot policy
1364 :param snap_pol_id: Id of the snapshot policy
1365 :param pd_name: Name of the protection domain
1366 :param pd_id: Id of the protection domain
1367 :param pool_name: Name of the storage pool
1368 :param pool_id: Id of the storage pool
1369 """
1370
1371 if (
1372 snap_pol_id
1373 and "snapshotPolicyId" in vol_details
1374 and vol_details["snapshotPolicyId"] is not None
1375 and snap_pol_id != vol_details["snapshotPolicyId"]
1376 ):
1377 self.module.fail_json(
1378 msg="Entered snapshot policy id does not"
1379 " match with the snapshot policy's id"
1380 " attached to the volume. Please enter"
1381 " a correct snapshot policy id."
1382 )
1383
1384 if (
1385 snap_pol_name
1386 and "snapshotPolicyName" in vol_details
1387 and vol_details["snapshotPolicyName"] is not None
1388 and snap_pol_name != vol_details["snapshotPolicyName"]
1389 ):
1390 self.module.fail_json(
1391 msg="Entered snapshot policy name does not"
1392 " match with the snapshot policy's "
1393 "name attached to the volume. Please"
1394 " enter a correct snapshot policy"
1395 " name."
1396 )
1397
1398 if pd_id and pd_id != vol_details["protectionDomainId"]:
1399 self.module.fail_json(
1400 msg="Entered protection domain id does not"
1401 " match with the volume's protection"
1402 " domain id. Please enter a correct"
1403 " protection domain id."
1404 )
1405
1406 if pool_id and pool_id != vol_details["storagePoolId"]:
1407 self.module.fail_json(
1408 msg="Entered storage pool id does"
1409 " not match with the volume's "
1410 "storage pool id. Please enter"
1411 " a correct storage pool id."
1412 )
1413
1414 if pd_name and pd_name != vol_details["protectionDomainName"]:
1415 self.module.fail_json(
1416 msg="Entered protection domain name does"
1417 " not match with the volume's "
1418 "protection domain name. Please enter"
1419 " a correct protection domain name."
1420 )
1421
1422 if pool_name and pool_name != vol_details["storagePoolName"]:
1423 self.module.fail_json(
1424 msg="Entered storage pool name does"
1425 " not match with the volume's "
1426 "storage pool name. Please enter"
1427 " a correct storage pool name."
1428 )
1429
1430 def initialize_diff_after(self, volume_params, volume_details):
1431 """Initialize diff between playbook input and volume details
1432 :param volume_params: Dictionary of parameters input from playbook
1433 :param volume_params: Dictionary of volume details
1434 :return: Dictionary of parameters of differences"""
1435
1436 diff_dict = {}
1437 if volume_params["state"] == "absent":
1438 return diff_dict
1439
1440 if volume_details is None:
1441 excluded_keys = {
1442 "hostname",
1443 "username",
1444 "password",
1445 "port",
1446 "timeout",
1447 "validate_certs",
1448 "state",
1449 }
1450 diff_dict = {}
1451
1452 for key, value in volume_params.items():
1453 if key not in excluded_keys and value is not None:
1454 diff_dict[key] = value
1455
1456 else:
1457 diff_dict = copy.deepcopy(volume_details)
1458 return diff_dict
1459
1460 def update_diff_after(self, modify_dict, diff_dict):
1461 """Update diff between playbook input and volume details
1462 :param modify_dict: Dictionary of parameters of differences
1463 :param diff_dict: Dictionary of volume details
1464 :return: Dictionary of parameters of differences"""
1465
1466 diff_dict_new = copy.deepcopy(diff_dict)
1467 if modify_dict:
1468 if "new_size" in modify_dict and modify_dict["new_size"]:
1469 size = self.module.params["size"]
1470 cap_unit = self.module.params["cap_unit"]
1471 diff_dict_new["after"]["size"] = size
1472 diff_dict_new["after"]["size_cap_unit"] = cap_unit
1473 diff_dict_new["after"]["sizeInKb"] = (
1474 self.get_size_data(size, cap_unit) * 1024
1475 )
1476 diff_dict_new["after"]["sizeInGB"] = self.get_size_data(size, cap_unit)
1477 if "new_name" in modify_dict and modify_dict["new_name"]:
1478 diff_dict_new["after"]["name"] = modify_dict["new_name"]
1479 if "snap_pol_id" in modify_dict and modify_dict["snap_pol_id"]:
1480 diff_dict_new["after"]["snplIdOfSourceVolume"] = modify_dict[
1481 "snap_pol_id"
1482 ]
1483 if (
1484 "auto_snap_remove_type" in modify_dict
1485 and modify_dict["auto_snap_remove_type"]
1486 ):
1487 diff_dict_new["after"]["snplIdOfSourceVolume"] = None
1488 return diff_dict_new
1489
1490 def perform_module_operation(self):
1491 """
1492 Perform different actions on volume based on parameters passed in
1493 the playbook
1494 """
1495 vol_name = self.module.params["vol_name"]
1496 vol_id = self.module.params["vol_id"]
1497 vol_type = self.module.params["vol_type"]
1498 sp_name = self.module.params["storage_pool_name"]
1499 sp_id = self.module.params["storage_pool_id"]
1500 pd_name = self.module.params["protection_domain_name"]
1501 pd_id = self.module.params["protection_domain_id"]
1502 snap_pol_name = self.module.params["snapshot_policy_name"]
1503 snap_pol_id = self.module.params["snapshot_policy_id"]
1504 auto_snap_remove_type = self.module.params["auto_snap_remove_type"]
1505 size = self.module.params["size"]
1506 cap_unit = self.module.params["cap_unit"]
1507 vol_new_name = self.module.params["vol_new_name"]
1508 refresh_src_vol_id = self.module.params["refresh_src_vol_id"]
1509 refresh_src_vol_name = self.module.params["refresh_src_vol_name"]
1510 restore_src_vol_id = self.module.params["restore_src_vol_id"]
1511 restore_src_vol_name = self.module.params["restore_src_vol_name"]
1512 sdc = copy.deepcopy(self.module.params["sdc"])
1513 sdc_state = self.module.params["sdc_state"]
1514 delete_snapshots = self.module.params["delete_snapshots"]
1515 state = self.module.params["state"]
1516
1517 vol_type = get_vol_type(vol_type)
1518 auto_snap_remove_type = self.check_null_capitalize(auto_snap_remove_type)
1519
1520 # result is a dictionary to contain end state and volume details
1521 changed = False
1522 result = dict(changed=False, volume_details={})
1523 self.validate_parameters(
1524 auto_snap_remove_type, snap_pol_id, snap_pol_name, delete_snapshots, state
1525 )
1526
1527 auto_snap_remove_type = self.get_auto_snap_rt(
1528 snap_pol_name, snap_pol_id, auto_snap_remove_type
1529 )
1530
1531 size = self.get_size_data(size, cap_unit)
1532
1533 pd_id = self.get_pd_details(pd_name, pd_id)
1534
1535 sp_id = self.get_sp_details(sp_name, pd_id, sp_id)
1536
1537 snap_pol_id = self.get_snap_pol_details(snap_pol_name, snap_pol_id)
1538
1539 # get volume details
1540 volume_details, vol_id = self.get_vol(vol_name, vol_id)
1541
1542 if vol_name and volume_details:
1543 self.verify_params(
1544 volume_details,
1545 snap_pol_name,
1546 snap_pol_id,
1547 pd_name,
1548 pd_id,
1549 sp_name,
1550 sp_id,
1551 )
1552
1553 refresh_src_vol_id, restore_src_vol_id = self.get_refresh_restore_src_id(
1554 refresh_src_vol_id,
1555 refresh_src_vol_name,
1556 restore_src_vol_id,
1557 restore_src_vol_name,
1558 )
1559
1560 before_dict = volume_details if volume_details is not None else {}
1561 diff_dict = {}
1562 diff_dict = self.initialize_diff_after(self.module.params, volume_details)
1563 result["diff"] = dict(before=before_dict, after=diff_dict)
1564
1565 # create operation
1566 create_changed = False
1567 if state == "present" and not volume_details:
1568 vol_id, volume_details, create_changed = self.create_new_volume(
1569 vol_name, vol_id, vol_type, sp_id, size, vol_new_name, volume_details
1570 )
1571
1572 refresh_restore_changed = False
1573 if state == "present" and (restore_src_vol_id or refresh_src_vol_id):
1574 if refresh_src_vol_id:
1575 self.refresh_volume(vol_id, refresh_src_vol_id)
1576 if restore_src_vol_id:
1577 self.restore_volume(vol_id, restore_src_vol_id)
1578 refresh_restore_changed = True
1579
1580 # Mapping the SDCs to a volume
1581 map_changed = False
1582 mode_changed = False
1583 limits_changed = False
1584 if state == "present" and volume_details and sdc and sdc_state == "mapped":
1585 mode_changed, limits_changed, map_changed = self.sdc_state_mapped(
1586 vol_id, sdc, volume_details
1587 )
1588
1589 # Unmap the SDCs to a volume
1590 unmap_changed = False
1591 if state == "present" and volume_details and sdc and sdc_state == "unmapped":
1592 unmap_changed = self.unmap_volume_from_sdc(volume_details, sdc)
1593
1594 if not create_changed and (
1595 map_changed or unmap_changed or mode_changed or limits_changed
1596 ):
1597 result["diff"]["after"]["mappedSdcInfo"] = {
1598 "sdc": sdc,
1599 "sdcState": sdc_state,
1600 }
1601
1602 modify_dict = {}
1603 if volume_details and state == "present":
1604 modify_dict = self.to_modify(
1605 volume_details, size, vol_new_name, snap_pol_id, auto_snap_remove_type
1606 )
1607 msg = "Parameters to be modified are as follows: {0}".format(
1608 str(modify_dict)
1609 )
1610 LOG.info(msg)
1611
1612 # Update the basic volume attributes
1613 modify_changed = False
1614 if modify_dict and state == "present":
1615 modify_changed = self.modify_volume(vol_id, modify_dict)
1616 if not create_changed and modify_dict:
1617 result["diff"] = self.update_diff_after(modify_dict, result["diff"])
1618
1619 # delete operation
1620 del_changed = False
1621 if state == "absent" and volume_details:
1622 del_changed = self.delete_operation(vol_id, delete_snapshots)
1623
1624 changed = (
1625 modify_changed
1626 or unmap_changed
1627 or map_changed
1628 or create_changed
1629 or del_changed
1630 or mode_changed
1631 or limits_changed
1632 or refresh_restore_changed
1633 )
1634
1635 # Returning the updated volume details
1636 self.prepare_output(vol_id, vol_name, result, create_changed)
1637
1638 result["changed"] = changed
1639 self.module.exit_json(**result)
1640
1641 def prepare_output(self, vol_id, vol_name, result, create_changed):
1642 vol_details = self.get_volume(vol_name, vol_id)
1643 result["volume_details"] = vol_details
1644 if not self.module.check_mode and not create_changed:
1645 result["diff"]["after"] = vol_details
1646
1647 def get_vol(self, vol_name, vol_id):
1648 volume_details = self.get_volume(vol_name, vol_id)
1649 if volume_details:
1650 vol_id = volume_details["id"]
1651 msg = "Fetched the volume details {0}".format(str(volume_details))
1652 LOG.info(msg)
1653 return volume_details, vol_id
1654
1655 def get_auto_snap_rt(self, snap_pol_name, snap_pol_id, auto_snap_remove_type):
1656 if not auto_snap_remove_type and (snap_pol_name == "" or snap_pol_id == ""):
1657 auto_snap_remove_type = "Detach"
1658 return auto_snap_remove_type
1659
1660 def get_size_data(self, size, cap_unit):
1661 if size:
1662 if not cap_unit:
1663 cap_unit = "GB"
1664
1665 if cap_unit == "TB":
1666 size = size * 1024
1667 return size
1668
1669 def get_pd_details(self, pd_name, pd_id):
1670 if pd_name:
1671 pd_details = self.get_protection_domain(pd_name)
1672 if pd_details:
1673 pd_id = pd_details["id"]
1674 msg = (
1675 "Fetched the protection domain details with id {0},"
1676 " name {1}".format(pd_id, pd_name)
1677 )
1678 LOG.info(msg)
1679 return pd_id
1680
1681 def get_sp_details(self, sp_name, pd_id, sp_id):
1682 if sp_name:
1683 sp_details = self.get_storage_pool(
1684 storage_pool_name=sp_name, protection_domain_id=pd_id
1685 )
1686 if sp_details:
1687 sp_id = sp_details["id"]
1688 msg = "Fetched the storage pool details id {0}," " name {1}".format(
1689 sp_id, sp_name
1690 )
1691 LOG.info(msg)
1692 return sp_id
1693
1694 def get_snap_pol_details(self, snap_pol_name, snap_pol_id):
1695 if snap_pol_name is not None:
1696 snap_pol_details = None
1697 if snap_pol_name:
1698 snap_pol_details = self.get_snapshot_policy(snap_pol_name=snap_pol_name)
1699 if snap_pol_details:
1700 snap_pol_id = snap_pol_details["id"]
1701
1702 if snap_pol_name == "":
1703 snap_pol_id = ""
1704 msg = "Fetched the snapshot policy details with id {0}," " name {1}".format(
1705 snap_pol_id, snap_pol_name
1706 )
1707 LOG.info(msg)
1708 return snap_pol_id
1709
1710 def get_refresh_restore_src_id(
1711 self,
1712 refresh_src_vol_id,
1713 refresh_src_vol_name,
1714 restore_src_vol_id,
1715 restore_src_vol_name,
1716 ):
1717 refresh_src_vol_id_updated = refresh_src_vol_id
1718 if refresh_src_vol_name:
1719 _, refresh_src_vol_id_updated = self.get_vol( # pylint: disable=disallowed-name
1720 refresh_src_vol_name, None
1721 )
1722 if refresh_src_vol_id_updated is None:
1723 self.module.fail_json(
1724 msg="Invalid refresh src vol name"
1725 )
1726 restore_src_vol_id_updated = restore_src_vol_id
1727 if restore_src_vol_name:
1728 _, restore_src_vol_id_updated = self.get_vol( # pylint: disable=disallowed-name
1729 restore_src_vol_name, None
1730 )
1731 if restore_src_vol_id_updated is None:
1732 self.module.fail_json(
1733 msg="Invalid restore src vol name"
1734 )
1735 return refresh_src_vol_id_updated, restore_src_vol_id_updated
1736
1737 def create_new_volume(
1738 self, vol_name, vol_id, vol_type, sp_id, size, vol_new_name, volume_details
1739 ):
1740 if vol_id:
1741 self.module.fail_json(
1742 msg="Creation of volume is allowed "
1743 "using vol_name only, "
1744 "vol_id given."
1745 )
1746
1747 if vol_new_name:
1748 self.module.fail_json(
1749 msg="vol_new_name parameter is not supported during "
1750 "creation of a volume. Try renaming the volume after"
1751 " the creation."
1752 )
1753 create_changed = self.create_volume(vol_name, sp_id, size, vol_type)
1754 if create_changed and not self.module.check_mode:
1755 volume_details = self.get_volume(vol_name)
1756 vol_id = volume_details["id"]
1757 msg = "Volume created successfully, fetched " "volume details {0}".format(
1758 str(volume_details)
1759 )
1760 LOG.info(msg)
1761 return vol_id, volume_details, create_changed
1762
1763 def sdc_state_mapped(self, vol_id, sdc, volume_details):
1764 mode_changed = False
1765 limits_changed = False
1766 map_changed = False
1767 map_changed, access_mode_list, limits_list = self.map_volume_to_sdc(
1768 volume_details, sdc
1769 )
1770 if len(access_mode_list) > 0:
1771 mode_changed = self.modify_access_mode(vol_id, access_mode_list)
1772 if len(limits_list) > 0:
1773 for temp in limits_list:
1774 payload = {
1775 "volume_id": volume_details["id"],
1776 "sdc_id": temp["sdc_id"],
1777 "bandwidth_limit": temp["bandwidth_limit"],
1778 "iops_limit": temp["iops_limit"],
1779 }
1780 limits_changed = self.modify_limits(payload)
1781 return mode_changed, limits_changed, map_changed
1782
1783 def delete_operation(self, vol_id, delete_snapshots):
1784 if delete_snapshots is True:
1785 delete_snapshots = "INCLUDING_DESCENDANTS"
1786 if delete_snapshots is None or delete_snapshots is False:
1787 delete_snapshots = "ONLY_ME"
1788 del_changed = self.delete_volume(vol_id, delete_snapshots)
1789 return del_changed
1790
1791 def check_null_capitalize(self, input_str):
1792 if input_str:
1793 input_str = input_str.capitalize()
1794 return input_str
1795
1796
1797 def convert_statistics(raw_statistics):
1798 statistics = {}
1799
1800 for metric in raw_statistics.get("resources", [])[0].get("metrics", []):
1801 metric_name = metric.get("name")
1802 # Assumes each metric has at least one value in 'values'
1803 metric_value = metric.get("values", [None])[0]
1804 statistics[metric_name] = metric_value
1805
1806 return statistics
1807
1808
1809 def check_for_sdc_modification(volume, sdc_id, sdc_details):
1810 """
1811 :param volume: The volume details
1812 :param sdc_id: The ID of the SDC
1813 :param sdc_details: The details of SDC
1814 :return: Dictionary with SDC attributes to be modified
1815 """
1816 access_mode_dict = dict()
1817 limits_dict = dict()
1818
1819 for sdc in volume["mappedSdcInfo"]:
1820 if sdc["sdcId"] == sdc_id:
1821 update_access_mode(sdc_id, sdc_details, access_mode_dict, sdc)
1822 if (
1823 sdc["limitIops"] != sdc_details["iops_limit"]
1824 or sdc["limitBwInMbps"] != sdc_details["bandwidth_limit"]
1825 ):
1826 limits_dict["sdc_id"] = sdc_id
1827 limits_dict["iops_limit"] = None
1828 limits_dict["bandwidth_limit"] = None
1829 if sdc["limitIops"] != sdc_details["iops_limit"]:
1830 limits_dict["iops_limit"] = sdc_details["iops_limit"]
1831 if sdc["limitBwInMbps"] != get_limits_in_mb(
1832 sdc_details["bandwidth_limit"]
1833 ):
1834 limits_dict["bandwidth_limit"] = sdc_details["bandwidth_limit"]
1835 break
1836 return access_mode_dict, limits_dict
1837
1838
1839 def update_access_mode(sdc_id, sdc_details, access_mode_dict, sdc):
1840 if sdc["accessMode"] != get_access_mode(sdc_details["access_mode"]):
1841 access_mode_dict["sdc_id"] = sdc_id
1842 access_mode_dict["accessMode"] = get_access_mode(sdc_details["access_mode"])
1843
1844
1845 def get_limits_in_mb(limits):
1846 """
1847 :param limits: Limits in KB
1848 :return: Limits in MB
1849 """
1850
1851 if limits:
1852 return limits / 1024
1853
1854
1855 def get_access_mode(access_mode):
1856 """
1857 :param access_mode: Access mode of the SDC
1858 :return: The enum for the access mode
1859 """
1860
1861 access_mode_dict = {
1862 "READ_WRITE": "ReadWrite",
1863 "READ_ONLY": "ReadOnly",
1864 "NO_ACCESS": "NoAccess",
1865 }
1866 return access_mode_dict.get(access_mode)
1867
1868
1869 def get_vol_type(vol_type):
1870 """
1871 :param vol_type: Type of the volume
1872 :return: Corresponding value for the entered vol_type
1873 """
1874 vol_type_dict = {
1875 "THICK_PROVISIONED": "ThickProvisioned",
1876 "THIN_PROVISIONED": "ThinProvisioned",
1877 }
1878 if vol_type:
1879 vol_type = vol_type_dict.get(vol_type)
1880 return vol_type
1881
1882
1883 def get_powerflex_volume_parameters():
1884 """This method provide parameter required for the volume
1885 module on PowerFlex"""
1886 return dict(
1887 vol_name=dict(),
1888 vol_id=dict(),
1889 storage_pool_name=dict(),
1890 storage_pool_id=dict(),
1891 protection_domain_name=dict(),
1892 protection_domain_id=dict(),
1893 snapshot_policy_name=dict(),
1894 snapshot_policy_id=dict(),
1895 size=dict(type="int"),
1896 cap_unit=dict(choices=["GB", "TB"]),
1897 vol_type=dict(choices=["THICK_PROVISIONED", "THIN_PROVISIONED"]),
1898 auto_snap_remove_type=dict(choices=["detach", "remove"]),
1899 vol_new_name=dict(),
1900 allow_multiple_mappings=dict(type="bool"),
1901 delete_snapshots=dict(type="bool"),
1902 refresh_src_vol_id=dict(),
1903 refresh_src_vol_name=dict(),
1904 restore_src_vol_id=dict(),
1905 restore_src_vol_name=dict(),
1906 sdc=dict(
1907 type="list",
1908 elements="dict",
1909 options=dict(
1910 sdc_id=dict(),
1911 sdc_ip=dict(),
1912 sdc_name=dict(),
1913 access_mode=dict(choices=["READ_WRITE", "READ_ONLY", "NO_ACCESS"]),
1914 bandwidth_limit=dict(type="int"),
1915 iops_limit=dict(type="int"),
1916 ),
1917 ),
1918 sdc_state=dict(choices=["mapped", "unmapped"]),
1919 state=dict(required=True, type="str", choices=["present", "absent"]),
1920 )
1921
1922
1923 def main():
1924 """Create PowerFlex volume object and perform actions on it
1925 based on user input from playbook"""
1926 obj = PowerFlexVolumeV2()
1927 obj.perform_module_operation()
1928
1929
1930 if __name__ == "__main__":
1931 main()