Debian Codegraph @

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

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