Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2
3 # Copyright: (c) 2023-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 snapshot policies 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: snapshot_policy
14 version_added: '1.7.0'
15 short_description: Manage snapshot policies on Dell PowerFlex
16 description:
17 - Managing snapshot policies on PowerFlex storage system includes
18 creating, getting details, modifying attributes, adding a source volume,
19 removing a source volume and deleting a snapshot policy.
20 author:
21 - Trisha Datta (@trisha-dell) <[email protected]>
22 extends_documentation_fragment:
23 - dellemc.powerflex.powerflex
24 options:
25 snapshot_policy_name:
26 description:
27 - The name of the snapshot policy.
28 - It is unique across the PowerFlex array.
29 - Mutually exclusive with I(snapshot_policy_id).
30 type: str
31 snapshot_policy_id:
32 description:
33 - The unique identifier of the snapshot policy.
34 - Except create operation, all other operations can be performed
35 using I(snapshot_policy_id).
36 - Mutually exclusive with I(snapshot_policy_name).
37 type: str
38 auto_snapshot_creation_cadence:
39 description:
40 - The auto snapshot creation cadence of the snapshot policy.
41 type: dict
42 suboptions:
43 time:
44 description:
45 - The time between creation of two snapshots.
46 type: int
47 unit:
48 description:
49 - The unit of the auto snapshot creation cadence.
50 type: str
51 choices: ["Minute", "Hour", "Day", "Week"]
52 default: "Minute"
53 num_of_retained_snapshots_per_level:
54 description:
55 - Number of retained snapshots per level.
56 type: list
57 elements: int
58 new_name:
59 description:
60 - New name of the snapshot policy.
61 type: str
62 access_mode:
63 description:
64 - Access mode of the snapshot policy.
65 - READ_ONLY access_mode is allowed only since PowerFlex 5.0.
66 choices: ['READ_WRITE', 'READ_ONLY']
67 type: str
68 secure_snapshots:
69 description:
70 - Whether to secure snapshots or not.
71 - Used only in the create operation.
72 type: bool
73 source_volume:
74 description:
75 - The source volume details to be added or removed.
76 type: list
77 elements: dict
78 suboptions:
79 id:
80 description:
81 - The unique identifier of the source volume
82 to be added or removed.
83 - Mutually exclusive with I(name).
84 type: str
85 name:
86 description:
87 - The name of the source volume to be added or removed.
88 - Mutually exclusive with I(id).
89 type: str
90 auto_snap_removal_action:
91 description:
92 - Ways to handle the snapshots created by the policy (auto snapshots).
93 - Must be provided when I(state) is set to C('absent').
94 choices: ['Remove', 'Detach']
95 type: str
96 detach_locked_auto_snapshots:
97 description:
98 - Whether to detach the locked auto snapshots during removal of source volume.
99 type: bool
100 state:
101 description:
102 - The state of the source volume.
103 - When C(present), source volume will be added to the snapshot policy.
104 - When C(absent), source volume will be removed from the snapshot policy.
105 type: str
106 choices: ['present', 'absent']
107 default: 'present'
108 pause:
109 description:
110 - Whether to pause or resume the snapshot policy.
111 type: bool
112 state:
113 description:
114 - State of the snapshot policy.
115 choices: ['present', 'absent']
116 default: 'present'
117 type: str
118 attributes:
119 check_mode:
120 description: Runs task to validate without performing action on the target machine.
121 support: full
122 diff_mode:
123 description: Runs the task to report the changes made or to be made.
124 support: full
125 notes:
126 - Deprecate statistics since PowerFlex 5.0.
127 - Only READ_ONLY access_mode is allowed since PowerFlex 5.0.
128 '''
129
130 EXAMPLES = r'''
131 - name: Create a snapshot policy
132 dellemc.powerflex.snapshot_policy:
133 hostname: "{{hostname}}"
134 username: "{{username}}"
135 password: "{{password}}"
136 validate_certs: "{{validate_certs}}"
137 snapshot_policy_name: "snapshot_policy_name_1"
138 access_mode: "READ_WRITE"
139 secure_snapshots: false
140 auto_snapshot_creation_cadence:
141 time: 1
142 unit: "Hour"
143 num_of_retained_snapshots_per_level:
144 - 20
145 state: "present"
146
147 - name: Get snapshot policy details using name
148 dellemc.powerflex.snapshot_policy:
149 hostname: "{{hostname}}"
150 username: "{{username}}"
151 password: "{{password}}"
152 validate_certs: "{{validate_certs}}"
153 snapshot_policy_name: "snapshot_policy_name_1"
154
155 - name: Get snapshot policy details using id
156 dellemc.powerflex.snapshot_policy:
157 hostname: "{{hostname}}"
158 username: "{{username}}"
159 password: "{{password}}"
160 validate_certs: "{{validate_certs}}"
161 snapshot_policy_id: "snapshot_policy_id_1"
162
163 - name: Modify a snapshot policy
164 dellemc.powerflex.snapshot_policy:
165 hostname: "{{hostname}}"
166 username: "{{username}}"
167 password: "{{password}}"
168 validate_certs: "{{validate_certs}}"
169 snapshot_policy_name: "snapshot_policy_name_1"
170 auto_snapshot_creation_cadence:
171 time: 2
172 unit: "Hour"
173 num_of_retained_snapshots_per_level:
174 - 40
175
176 - name: Rename a snapshot policy
177 dellemc.powerflex.snapshot_policy:
178 hostname: "{{hostname}}"
179 username: "{{username}}"
180 password: "{{password}}"
181 validate_certs: "{{validate_certs}}"
182 snapshot_policy_name: "snapshot_policy_name_1"
183 new_name: "snapshot_policy_name_1_new"
184
185 - name: Add source volume
186 dellemc.powerflex.snapshot_policy:
187 hostname: "{{hostname}}"
188 username: "{{username}}"
189 password: "{{password}}"
190 validate_certs: "{{validate_certs}}"
191 snapshot_policy_name: "snapshot_policy_name_1"
192 source_volume:
193 - name: "source_volume_name_1"
194 - id: "source_volume_id_2"
195 state: "present"
196
197 - name: Remove source volume
198 dellemc.powerflex.snapshot_policy:
199 hostname: "{{hostname}}"
200 username: "{{username}}"
201 password: "{{password}}"
202 validate_certs: "{{validate_certs}}"
203 snapshot_policy_name: "{{snapshot_policy_name}}"
204 source_volume:
205 - name: "source_volume_name_1"
206 auto_snap_removal_action: 'Remove'
207 state: "absent"
208 - id: "source_volume_id_2"
209 auto_snap_removal_action: 'Remove'
210 detach_locked_auto_snapshots: true
211 state: "absent"
212
213 - name: Pause a snapshot policy
214 dellemc.powerflex.snapshot_policy:
215 hostname: "{{hostname}}"
216 username: "{{username}}"
217 password: "{{password}}"
218 validate_certs: "{{validate_certs}}"
219 snapshot_policy_name: "{{snapshot_policy_name}}"
220 pause: true
221
222 - name: Resume a snapshot policy
223 dellemc.powerflex.snapshot_policy:
224 hostname: "{{hostname}}"
225 username: "{{username}}"
226 password: "{{password}}"
227 validate_certs: "{{validate_certs}}"
228 snapshot_policy_name: "{{snapshot_policy_name}}"
229 pause: false
230
231 - name: Delete a snapshot policy
232 dellemc.powerflex.snapshot_policy:
233 hostname: "{{hostname}}"
234 username: "{{username}}"
235 password: "{{password}}"
236 validate_certs: "{{validate_certs}}"
237 snapshot_policy_name: "snapshot_policy_name"
238 state: "absent"
239 '''
240
241 RETURN = r'''
242 changed:
243 description: Whether or not the resource has changed.
244 returned: always
245 type: bool
246 sample: 'false'
247 snapshot_policy_details:
248 description: Details of the snapshot policy.
249 returned: When snapshot policy exists
250 type: dict
251 contains:
252 autoSnapshotCreationCadenceInMin:
253 description: The snapshot rule of the snapshot policy.
254 type: int
255 id:
256 description: The ID of the snapshot policy.
257 type: str
258 lastAutoSnapshotCreationFailureReason:
259 description: The reason for the failure of last auto snapshot creation .
260 type: str
261 name:
262 description: Name of the snapshot policy.
263 type: str
264 lastAutoSnapshotFailureInFirstLevel:
265 description: Whether the last auto snapshot in first level failed.
266 type: bool
267 maxVTreeAutoSnapshots:
268 description: Maximum number of VTree auto snapshots.
269 type: int
270 nextAutoSnapshotCreationTime:
271 description: The time of creation of the next auto snapshot.
272 type: int
273 numOfAutoSnapshots:
274 description: Number of auto snapshots.
275 type: int
276 numOfCreationFailures:
277 description: Number of creation failures.
278 type: int
279 numOfExpiredButLockedSnapshots:
280 description: Number of expired but locked snapshots.
281 type: int
282 numOfLockedSnapshots:
283 description: Number of locked snapshots.
284 type: int
285 numOfRetainedSnapshotsPerLevel:
286 description: Number of snapshots retained per level
287 type: list
288 numOfSourceVolumes:
289 description: Number of source volumes.
290 type: int
291 secureSnapshots:
292 description: Whether the snapshots are secured.
293 type: bool
294 snapshotAccessMode:
295 description: Access mode of the snapshots.
296 type: str
297 snapshotPolicyState:
298 description: State of the snapshot policy.
299 type: str
300 systemId:
301 description: Unique identifier of the PowerFlex system.
302 type: str
303 timeOfLastAutoSnapshot:
304 description: Time of the last auto snapshot creation.
305 type: str
306 timeOfLastAutoSnapshotCreationFailure:
307 description: Time of the failure of the last auto snapshot creation.
308 type: str
309 statistics:
310 description: Statistics details of the snapshot policy. Deprecated since PowerFlex 5.0.
311 type: dict
312 contains:
313 autoSnapshotVolIds:
314 description: Volume Ids of all the auto snapshots.
315 type: list
316 expiredButLockedSnapshotsIds:
317 description: Ids of expired but locked snapshots.
318 type: list
319 numOfAutoSnapshots:
320 description: Number of auto snapshots.
321 type: int
322 numOfExpiredButLockedSnapshots:
323 description: Number of expired but locked snapshots.
324 type: int
325 numOfSrcVols:
326 description: Number of source volumes.
327 type: int
328 srcVolIds:
329 description: Ids of the source volumes.
330 type: list
331
332 sample: {
333 "autoSnapshotCreationCadenceInMin": 120,
334 "id": "15ae842800000004",
335 "lastAutoSnapshotCreationFailureReason": "NR",
336 "lastAutoSnapshotFailureInFirstLevel": false,
337 "links": [
338 {
339 "href": "/api/instances/SnapshotPolicy::15ae842800000004",
340 "rel": "self"
341 },
342 {
343 "href": "/api/instances/SnapshotPolicy::15ae842800000004/relationships/Statistics",
344 "rel": "/api/SnapshotPolicy/relationship/Statistics"
345 },
346 {
347 "href": "/api/instances/SnapshotPolicy::15ae842800000004/relationships/SourceVolume",
348 "rel": "/api/SnapshotPolicy/relationship/SourceVolume"
349 },
350 {
351 "href": "/api/instances/SnapshotPolicy::15ae842800000004/relationships/AutoSnapshotVolume",
352 "rel": "/api/SnapshotPolicy/relationship/AutoSnapshotVolume"
353 },
354 {
355 "href": "/api/instances/System::0e7a082862fedf0f",
356 "rel": "/api/parent/relationship/systemId"
357 }
358 ],
359 "maxVTreeAutoSnapshots": 40,
360 "name": "Sample_snapshot_policy_1",
361 "nextAutoSnapshotCreationTime": 1683709201,
362 "numOfAutoSnapshots": 0,
363 "numOfCreationFailures": 0,
364 "numOfExpiredButLockedSnapshots": 0,
365 "numOfLockedSnapshots": 0,
366 "numOfRetainedSnapshotsPerLevel": [
367 40
368 ],
369 "numOfSourceVolumes": 0,
370 "secureSnapshots": false,
371 "snapshotAccessMode": "ReadWrite",
372 "snapshotPolicyState": "Active",
373 "statistics": {
374 "autoSnapshotVolIds": [],
375 "expiredButLockedSnapshotsIds": [],
376 "numOfAutoSnapshots": 0,
377 "numOfExpiredButLockedSnapshots": 0,
378 "numOfSrcVols": 0,
379 "srcVolIds": []
380 },
381 "systemId": "0e7a082862fedf0f",
382 "timeOfLastAutoSnapshot": 0,
383 "timeOfLastAutoSnapshotCreationFailure": 0
384 }
385 '''
386
387 from ansible.module_utils.basic import AnsibleModule
388 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \
389 import PowerFlexBase
390 from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell \
391 import utils
392 import copy
393
394 LOG = utils.get_logger('snapshot_policy')
395
396
397 class PowerFlexSnapshotPolicy(PowerFlexBase):
398 """Class with snapshot policies operations"""
399
400 def __init__(self):
401 """ Define all parameters required by this module"""
402
403 mutually_exclusive = [['snapshot_policy_name', 'snapshot_policy_id']]
404
405 ansible_module_params = {
406 'argument_spec': get_powerflex_snapshot_policy_parameters(),
407 'supports_check_mode': True,
408 'mutually_exclusive': mutually_exclusive
409 }
410 super().__init__(AnsibleModule, ansible_module_params)
411
412 self.result = dict(
413 changed=False,
414 snapshot_policy_details={},
415 diff={}
416 )
417
418 def get_snapshot_policy(self, snap_pol_id=None, snap_pol_name=None):
419 """Get snapshot policy details
420 :param snap_pol_name: Name of the snapshot policy.
421 :param snap_pol_id: ID of the snapshot policy.
422 :return: snapshot policy details
423 """
424 try:
425 snap_pol_details = None
426 if snap_pol_id:
427 snap_pol_details = self.powerflex_conn.snapshot_policy.get(
428 filter_fields={'id': snap_pol_id})
429
430 if snap_pol_name:
431 snap_pol_details = self.powerflex_conn.snapshot_policy.get(
432 filter_fields={'name': snap_pol_name})
433
434 if not snap_pol_details:
435 msg = "Unable to find the snapshot policy."
436 LOG.info(msg)
437 return None
438
439 if self.is_gen1_api_version():
440 # Append statistics
441 statistics = \
442 self.powerflex_conn.snapshot_policy.get_statistics(snap_pol_details[0]['id'])
443 snap_pol_details[0]['statistics'] = statistics if statistics else {}
444
445 return snap_pol_details[0]
446
447 except Exception as e:
448 errormsg = f'Failed to get the snapshot policy with error {str(e)}'
449 LOG.error(errormsg)
450 self.module.fail_json(msg=errormsg)
451
452 def is_gen1_api_version(self):
453 """
454 Get the API version and check if it is less than version 5.0.
455
456 Returns:
457 bool: True if the API version is less than version 5.0, False otherwise.
458 """
459 api_version = self.powerflex_conn.system.api_version(cached=True)
460 version_check = utils.is_version_less(api_version, '5.0')
461 return version_check
462
463 def create_snapshot_policy(self, auto_snapshot_creation_cadence_in_min, num_of_retained_snapshots_per_level,
464 access_mode, secure_snapshots, snapshot_policy_name=None):
465 """Create snapshot_policy
466 :param auto_snapshot_creation_cadence_in_min: The auto snapshot creation cadence of the snapshot policy.
467 :param num_of_retained_snapshots_per_level: Number of retained snapshots per level.
468 :param access_mode: Access mode of the snapshot policy.
469 :param secure_snapshots: Whether to secure snapshots or not.
470 :param snapshot_policy_name: Name of the snapshot policy.
471 :return: Id of the snapshot policy, if created.
472 """
473 try:
474 if not self.module.check_mode:
475 policy_id = self.powerflex_conn.snapshot_policy.create(
476 auto_snap_creation_cadence_in_min=auto_snapshot_creation_cadence_in_min,
477 retained_snaps_per_level=num_of_retained_snapshots_per_level, name=snapshot_policy_name,
478 snapshot_access_mode=access_mode, secure_snapshots=secure_snapshots)
479 return policy_id
480
481 except Exception as e:
482 errormsg = f'Creation of snapshot policy failed with error {str(e)}'
483 LOG.error(errormsg)
484 self.module.fail_json(msg=errormsg)
485
486 def delete_snapshot_policy(self, snap_pol_id):
487 """Delete snapshot policy
488 :param snap_pol_id: The unique identifier of the snapshot policy.
489 :return: Details of the snapshot policy.
490 """
491
492 try:
493 if not self.module.check_mode:
494 self.powerflex_conn.snapshot_policy.delete(snap_pol_id)
495 return self.get_snapshot_policy(snap_pol_id=snap_pol_id)
496
497 except Exception as e:
498 errormsg = (f'Deletion of snapshot policy {snap_pol_id} '
499 f'failed with error {str(e)}')
500 LOG.error(errormsg)
501 self.module.fail_json(msg=errormsg)
502
503 def get_volume(self, vol_name=None, vol_id=None):
504 """Get volume details
505 :param vol_name: Name of the volume
506 :param vol_id: ID of the volume
507 :return: Details of volume if exist.
508 """
509
510 id_or_name = vol_id if vol_id else vol_name
511
512 try:
513 if vol_name:
514 volume_details = self.powerflex_conn.volume.get(
515 filter_fields={'name': vol_name})
516 else:
517 volume_details = self.powerflex_conn.volume.get(
518 filter_fields={'id': vol_id})
519
520 if len(volume_details) == 0:
521 error_msg = f"Volume with identifier {id_or_name} not found"
522 LOG.error(error_msg)
523 self.module.fail_json(msg=error_msg)
524
525 # Append snapshot policy name and id
526 if volume_details[0]['snplIdOfSourceVolume'] is not None:
527 snap_policy_id = volume_details[0]['snplIdOfSourceVolume']
528 volume_details[0]['snapshotPolicyId'] = snap_policy_id
529 volume_details[0]['snapshotPolicyName'] = \
530 self.get_snapshot_policy(snap_policy_id)['name']
531
532 return volume_details[0]
533
534 except Exception as e:
535 error_msg = (f"Failed to get the volume {id_or_name}"
536 f" with error {str(e)}")
537 LOG.error(error_msg)
538 self.module.fail_json(msg=error_msg)
539
540 def manage_source_volume(self, snap_pol_details, vol_details, source_volume_element):
541 """Adding or removing a source volume
542 :param snap_pol_details: Details of the snapshot policy details.
543 :param vol_details: Details of the volume.
544 :param source_volume_element: The index of the source volume in the
545 list of volumes to be added/removed.
546 :return: Boolean indicating whether volume is added/removed.
547 """
548 try:
549 if self.module.params['source_volume'][source_volume_element]['state'] == 'present' and \
550 vol_details['snplIdOfSourceVolume'] != snap_pol_details['id']:
551 if not self.module.check_mode:
552 snap_pol_details = self.powerflex_conn.snapshot_policy.add_source_volume(
553 snapshot_policy_id=snap_pol_details['id'],
554 volume_id=vol_details['id'])
555 LOG.info("Source volume successfully added")
556 return True
557
558 elif self.module.params['source_volume'][source_volume_element]['state'] == 'absent' and \
559 vol_details['snplIdOfSourceVolume'] == snap_pol_details['id']:
560 if not self.module.check_mode:
561 snap_pol_details = self.powerflex_conn.snapshot_policy.remove_source_volume(
562 snapshot_policy_id=snap_pol_details['id'],
563 volume_id=vol_details['id'],
564 auto_snap_removal_action=self.module.params['source_volume'][source_volume_element]['auto_snap_removal_action'],
565 detach_locked_auto_snaps=self.module.params['source_volume'][source_volume_element]['detach_locked_auto_snapshots'])
566 LOG.info("Source volume successfully removed")
567 return True
568 return False
569
570 except Exception as e:
571 error_msg = f"Failed to manage the source volume {vol_details['id']} with error {str(e)}"
572 LOG.error(error_msg)
573 self.module.fail_json(msg=error_msg)
574
575 def pause_snapshot_policy(self, snap_pol_details):
576 """Pausing or resuming a snapshot policy.
577 :param snap_pol_details: Details of the snapshot policy details.
578 :return: Boolean indicating whether snapshot policy is paused/removed or not.
579 """
580 try:
581 if self.module.params['pause'] and \
582 snap_pol_details['snapshotPolicyState'] != "Paused":
583 if not self.module.check_mode:
584 self.powerflex_conn.snapshot_policy.pause(
585 snapshot_policy_id=snap_pol_details['id'])
586 LOG.info("Snapshot policy successfully paused.")
587 return True
588
589 elif not self.module.params['pause'] and \
590 snap_pol_details['snapshotPolicyState'] == "Paused":
591 if not self.module.check_mode:
592 self.powerflex_conn.snapshot_policy.resume(
593 snapshot_policy_id=snap_pol_details['id'])
594 LOG.info("Snapshot policy successfully resumed.")
595 return True
596 return False
597
598 except Exception as e:
599 error_msg = f"Failed to pause/resume {snap_pol_details['id']} with error {str(e)}"
600 LOG.error(error_msg)
601 self.module.fail_json(msg=error_msg)
602
603 def to_modify(self, snap_pol_details, auto_snapshot_creation_cadence_in_min, num_of_retained_snapshots_per_level, new_name):
604 """Whether to modify the snapshot policy or not
605 :param snap_pol_details: Details of the snapshot policy.
606 :param auto_snapshot_creation_cadence_in_min: Snapshot rule of the policy.
607 :param num_of_retained_snapshots_per_level: Retention rule of the policy.
608 :param new_name: The new name of the snapshot policy.
609 :return: Dictionary containing the attributes of
610 snapshot policy which are to be updated
611 """
612 modify_dict = {}
613
614 if auto_snapshot_creation_cadence_in_min is not None and \
615 snap_pol_details['autoSnapshotCreationCadenceInMin'] != auto_snapshot_creation_cadence_in_min:
616 modify_dict['auto_snapshot_creation_cadence_in_min'] = auto_snapshot_creation_cadence_in_min
617
618 if num_of_retained_snapshots_per_level is not None and \
619 snap_pol_details['numOfRetainedSnapshotsPerLevel'] != num_of_retained_snapshots_per_level:
620 modify_dict['num_of_retained_snapshots_per_level'] = num_of_retained_snapshots_per_level
621
622 if new_name is not None:
623 if len(new_name.strip()) == 0:
624 self.module.fail_json(
625 msg="Provide valid volume name.")
626 if new_name != snap_pol_details['name']:
627 modify_dict['new_name'] = new_name
628
629 return modify_dict
630
631 def modify_snapshot_policy(self, snap_pol_details, modify_dict):
632 """
633 Modify the snapshot policy attributes
634 :param snap_pol_details: Details of the snapshot policy
635 :param modify_dict: Dictionary containing the attributes of
636 snapshot policy which are to be updated
637 :return: True, if the operation is successful
638 """
639 try:
640 msg = (f"Dictionary containing attributes which are to be"
641 f" updated is {str(modify_dict)}.")
642 LOG.info(msg)
643 if not self.module.check_mode:
644 if 'new_name' in modify_dict:
645 self.powerflex_conn.snapshot_policy.rename(snap_pol_details['id'],
646 modify_dict['new_name'])
647 msg = (f"The name of the volume is updated"
648 f" to {modify_dict['new_name']} sucessfully.")
649 LOG.info(msg)
650
651 if 'auto_snapshot_creation_cadence_in_min' in modify_dict and \
652 'num_of_retained_snapshots_per_level' not in modify_dict:
653 self.powerflex_conn.snapshot_policy.modify(
654 snapshot_policy_id=snap_pol_details['id'],
655 auto_snap_creation_cadence_in_min=modify_dict['auto_snapshot_creation_cadence_in_min'],
656 retained_snaps_per_level=snap_pol_details['numOfRetainedSnapshotsPerLevel'])
657 msg = f"The snapshot rule is updated to {modify_dict['auto_snapshot_creation_cadence_in_min']}"
658 LOG.info(msg)
659
660 elif 'auto_snapshot_creation_cadence_in_min' not in modify_dict and 'num_of_retained_snapshots_per_level' in modify_dict:
661 self.powerflex_conn.snapshot_policy.modify(
662 snapshot_policy_id=snap_pol_details['id'],
663 auto_snap_creation_cadence_in_min=snap_pol_details['autoSnapshotCreationCadenceInMin'],
664 retained_snaps_per_level=modify_dict['num_of_retained_snapshots_per_level'])
665 msg = f"The retention rule is updated to {modify_dict['num_of_retained_snapshots_per_level']}"
666 LOG.info(msg)
667
668 elif 'auto_snapshot_creation_cadence_in_min' in modify_dict and 'num_of_retained_snapshots_per_level' in modify_dict:
669 self.powerflex_conn.snapshot_policy.modify(
670 snapshot_policy_id=snap_pol_details['id'],
671 auto_snap_creation_cadence_in_min=modify_dict['auto_snapshot_creation_cadence_in_min'],
672 retained_snaps_per_level=modify_dict['num_of_retained_snapshots_per_level'])
673 msg = (f"The snapshot rule is updated to {modify_dict['auto_snapshot_creation_cadence_in_min']}"
674 f" and the retention rule is updated to {modify_dict['num_of_retained_snapshots_per_level']}")
675 LOG.info(msg)
676
677 return True
678
679 except Exception as e:
680 err_msg = (f"Failed to update the snapshot policy {snap_pol_details['id']}"
681 f" with error {str(e)}")
682 LOG.error(err_msg)
683 self.module.fail_json(msg=err_msg)
684
685
686 def get_access_mode(access_mode):
687 """
688 :param access_mode: Access mode of the snapshot policy
689 :return: The enum for the access mode
690 """
691
692 access_mode_dict = {
693 "READ_WRITE": "ReadWrite",
694 "READ_ONLY": "ReadOnly"
695 }
696 return access_mode_dict.get(access_mode)
697
698
699 def get_powerflex_snapshot_policy_parameters():
700 """This method provide parameter required for the snapshot
701 policy module on PowerFlex"""
702 return dict(
703 snapshot_policy_name=dict(), snapshot_policy_id=dict(),
704 new_name=dict(),
705 access_mode=dict(choices=['READ_WRITE', 'READ_ONLY']),
706 secure_snapshots=dict(type='bool'),
707 auto_snapshot_creation_cadence=dict(type='dict', options=dict(
708 time=dict(type='int'),
709 unit=dict(choices=['Minute', 'Hour', 'Day', 'Week'],
710 default='Minute'))),
711 num_of_retained_snapshots_per_level=dict(type='list', elements='int'),
712 source_volume=dict(type='list', elements='dict', options=dict(
713 id=dict(), name=dict(),
714 auto_snap_removal_action=dict(choices=['Remove', 'Detach']),
715 detach_locked_auto_snapshots=dict(type='bool'),
716 state=dict(default='present', choices=['present', 'absent']))),
717 pause=dict(type='bool'),
718 state=dict(default='present', choices=['present', 'absent'])
719 )
720
721
722 class SnapshotPolicyCreateHandler():
723 def handle(self, con_object, con_params, snapshot_policy_details, access_mode, auto_snapshot_creation_cadence_in_min):
724 if con_params['state'] == 'present' and not snapshot_policy_details:
725 if con_params['snapshot_policy_id']:
726 con_object.module.fail_json(msg="Creation of snapshot "
727 "policy is allowed "
728 "using snapshot_policy_name only, "
729 "snapshot_policy_id given.")
730 if con_params['access_mode'] == "READ_WRITE" and not con_object.is_gen1_api_version():
731 con_object.module.fail_json(msg="READ_ONLY access_mode is allowed only since PowerFlex 5.0, "
732 "`READ_WRITE` given.")
733
734 if con_object.module._diff:
735 con_object.result.update(
736 {"diff": {"before": {},
737 "after": {
738 "snapshot_policy_name": con_params['snapshot_policy_name'],
739 "access_mode": access_mode,
740 "secure_snapshots": con_params['secure_snapshots'],
741 "auto_snapshot_creation_cadence": con_params['auto_snapshot_creation_cadence'],
742 "num_of_retained_snapshots_per_level": con_params['num_of_retained_snapshots_per_level']}}})
743 snap_pol_id = con_object.create_snapshot_policy(snapshot_policy_name=con_params['snapshot_policy_name'],
744 access_mode=access_mode,
745 secure_snapshots=con_params['secure_snapshots'],
746 auto_snapshot_creation_cadence_in_min=auto_snapshot_creation_cadence_in_min,
747 num_of_retained_snapshots_per_level=con_params['num_of_retained_snapshots_per_level'])
748 con_object.result['changed'] = True
749 if snap_pol_id:
750 snapshot_policy_details = con_object.get_snapshot_policy(snap_pol_name=con_params['snapshot_policy_name'],
751 snap_pol_id=con_params['snapshot_policy_id'])
752
753 msg = (f"snapshot policy created successfully, fetched "
754 f"snapshot_policy details {str(snapshot_policy_details)}")
755 LOG.info(msg)
756
757 SnapshotPolicyModifyHandler().handle(con_object, con_params, snapshot_policy_details,
758 auto_snapshot_creation_cadence_in_min)
759
760
761 class SnapshotPolicyModifyHandler():
762 def handle(self, con_object, con_params, snapshot_policy_details, auto_snapshot_creation_cadence_in_min):
763 modify_dict = {}
764 if con_params['state'] == 'present' and snapshot_policy_details:
765 modify_dict = con_object.to_modify(
766 snap_pol_details=snapshot_policy_details, new_name=con_params['new_name'],
767 auto_snapshot_creation_cadence_in_min=auto_snapshot_creation_cadence_in_min,
768 num_of_retained_snapshots_per_level=con_params['num_of_retained_snapshots_per_level'])
769 msg = (f"Parameters to be modified are as"
770 f" follows: {str(modify_dict)}")
771 LOG.info(msg)
772 if modify_dict and con_params['state'] == 'present':
773 if con_object.module._diff:
774 if 'num_of_retained_snapshots_per_level' in modify_dict:
775 con_object.result["diff"]["after"]["num_of_retained_snapshots_per_level"] =\
776 con_params['num_of_retained_snapshots_per_level']
777 if 'auto_snapshot_creation_cadence_in_min' in modify_dict:
778 con_object.result["diff"]["after"]["auto_snapshot_creation_cadence"] =\
779 con_params['auto_snapshot_creation_cadence']
780 if 'new_name' in modify_dict:
781 con_object.result["diff"]["after"]["new_name"] = con_params['new_name']
782 changed = con_object.modify_snapshot_policy(snap_pol_details=snapshot_policy_details,
783 modify_dict=modify_dict)
784 con_object.result['changed'] |= changed
785 snapshot_policy_details = con_object.get_snapshot_policy(snap_pol_id=snapshot_policy_details.get("id"))
786 SnapshotPolicySourceVolumeHandler().handle(con_object, con_params, snapshot_policy_details)
787
788
789 class SnapshotPolicySourceVolumeHandler():
790 def handle(self, con_object, con_params, snapshot_policy_details):
791 if snapshot_policy_details and con_params['state'] == 'present' and con_params['source_volume'] is not None:
792 changed = False
793 for source_volume_element in range(len(con_params['source_volume'])):
794 if not (con_params['source_volume'][source_volume_element]['id'] or
795 con_params['source_volume'][source_volume_element]['name']):
796 con_object.module.fail_json(
797 msg="Either id or name of source volume needs to be "
798 "passed with state of source volume")
799
800 elif con_params['source_volume'][source_volume_element]['id'] and \
801 con_params['source_volume'][source_volume_element]['name']:
802 con_object.module.fail_json(
803 msg="id and name of source volume are mutually exclusive")
804
805 elif con_params['source_volume'][source_volume_element]['id'] or \
806 con_params['source_volume'][source_volume_element]['name']:
807 volume_details = con_object.get_volume(vol_id=con_params['source_volume'][source_volume_element]['id'],
808 vol_name=con_params['source_volume'][source_volume_element]['name'])
809 changed |= con_object.manage_source_volume(snap_pol_details=snapshot_policy_details,
810 vol_details=volume_details,
811 source_volume_element=source_volume_element)
812 if con_object.module._diff and changed:
813 con_object.result["diff"]["after"]["source_volume"] = copy.deepcopy(con_params['source_volume'])
814 con_object.result['changed'] |= changed
815 snapshot_policy_details = con_object.get_snapshot_policy(snap_pol_name=con_params['snapshot_policy_name'],
816 snap_pol_id=con_params['snapshot_policy_id'])
817 SnapshotPolicyPauseHandler().handle(con_object, con_params, snapshot_policy_details)
818
819
820 class SnapshotPolicyPauseHandler():
821 def handle(self, con_object, con_params, snapshot_policy_details):
822 if con_params["state"] == "present" and con_params["pause"] is not None:
823 changed = \
824 con_object.pause_snapshot_policy(snap_pol_details=snapshot_policy_details)
825 con_object.result['changed'] |= changed
826 if con_object.module._diff and changed:
827 con_object.result["diff"]["after"]["pause"] =\
828 con_params["pause"] if con_params["pause"] is not None else False
829 snapshot_policy_details = \
830 con_object.get_snapshot_policy(snap_pol_name=con_params['snapshot_policy_name'],
831 snap_pol_id=con_params['snapshot_policy_id'])
832 SnapshotPolicyDeleteHandler().handle(con_object, con_params, snapshot_policy_details)
833
834
835 class SnapshotPolicyDeleteHandler():
836 def handle(self, con_object, con_params, snapshot_policy_details):
837 if con_params['state'] == 'absent' and snapshot_policy_details:
838 snapshot_policy_details = con_object.delete_snapshot_policy(
839 snap_pol_id=snapshot_policy_details.get("id"))
840 con_object.result['changed'] = True
841 SnapshotPolicyExitHandler().handle(con_object, snapshot_policy_details)
842
843
844 class SnapshotPolicyExitHandler():
845 def handle(self, con_object, snapshot_policy_details):
846 if con_object.module._diff:
847 after_dict = copy.deepcopy(snapshot_policy_details) if snapshot_policy_details else {}
848 after_dict.pop("links", None)
849 after_dict.pop("statistics", None)
850 con_object.result["diff"]["after"].update(after_dict)
851 con_object.result['snapshot_policy_details'] = snapshot_policy_details
852 con_object.module.exit_json(**con_object.result)
853
854
855 class SnapshotPolicyHandler():
856 def handle(self, con_object, con_params):
857 access_mode = get_access_mode(con_params['access_mode'])
858 snapshot_policy_details = con_object.get_snapshot_policy(snap_pol_name=con_params['snapshot_policy_name'],
859 snap_pol_id=con_params['snapshot_policy_id'])
860 auto_snapshot_creation_cadence_in_min = None
861 if con_params['auto_snapshot_creation_cadence'] is not None:
862 auto_snapshot_creation_cadence_in_min = utils.get_time_minutes(time=con_params['auto_snapshot_creation_cadence']['time'],
863 time_unit=con_params['auto_snapshot_creation_cadence']['unit'])
864 if con_object.module._diff:
865 before_dict = {}
866 if snapshot_policy_details:
867 before_dict = copy.deepcopy(snapshot_policy_details)
868 before_dict.pop("links", None)
869 before_dict.pop("statistics", None)
870 con_object.result["diff"] = dict(before=before_dict, after={})
871 SnapshotPolicyCreateHandler().handle(con_object, con_params, snapshot_policy_details,
872 access_mode, auto_snapshot_creation_cadence_in_min)
873
874
875 def main():
876 """ Create PowerFlex snapshot policy object and perform action on it
877 based on user input from playbook"""
878 obj = PowerFlexSnapshotPolicy()
879 SnapshotPolicyHandler().handle(obj, obj.module.params)
880
881
882 if __name__ == '__main__':
883 main()