Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_pgsched.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefa_pgsched
20 short_description: Manage protection groups replication schedules on Pure Storage FlashArrays
21 version_added: '1.0.0'
22 description:
23 - Modify or delete protection groups replication schedules on Pure Storage FlashArrays.
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 name:
28 description:
29 - The name of the protection group.
30 type: str
31 required: true
32 state:
33 description:
34 - Define whether to set or delete the protection group schedule.
35 type: str
36 default: present
37 choices: [ absent, present ]
38 schedule:
39 description:
40 - Which schedule to change.
41 type: str
42 choices: ['replication', 'snapshot']
43 required: true
44 enabled:
45 description:
46 - Enable the schedule being configured.
47 type: bool
48 default: true
49 replicate_at:
50 description:
51 - Provide a time in 12-hour AM/PM format, eg. 11AM
52 - Only valid if I(replicate_frequency) is an exact multiple of 86400, ie 1 day.
53 type: str
54 blackout_start:
55 description:
56 - Specifies the time at which to suspend replication.
57 - Provide a time in 12-hour AM/PM format, eg. 11AM
58 type: str
59 blackout_end:
60 description:
61 - Specifies the time at which to restart replication.
62 - Provide a time in 12-hour AM/PM format, eg. 5PM
63 type: str
64 replicate_frequency:
65 description:
66 - Specifies the replication frequency in seconds.
67 - Range 900 - 34560000 (FA-405, //M10, //X10 and Cloud Block Store).
68 - Range 300 - 34560000 (all other arrays).
69 type: int
70 snap_at:
71 description:
72 - Provide a time in 12-hour AM/PM format, eg. 11AM
73 - Only valid if I(snap_frequency) is an exact multiple of 86400, ie 1 day.
74 type: str
75 snap_frequency:
76 description:
77 - Specifies the snapshot frequency in seconds.
78 - Range available 300 - 34560000.
79 type: int
80 days:
81 description:
82 - Specifies the number of days to keep the I(per_day) snapshots beyond the
83 I(all_for) period before they are eradicated
84 - Max retention period is 4000 days
85 type: int
86 all_for:
87 description:
88 - Specifies the length of time, in seconds, to keep the snapshots on the
89 source array before they are eradicated.
90 - Range available 1 - 34560000.
91 type: int
92 per_day:
93 description:
94 - Specifies the number of I(per_day) snapshots to keep beyond the I(all_for) period.
95 - Maximum number is 1440
96 type: int
97 target_all_for:
98 description:
99 - Specifies the length of time, in seconds, to keep the replicated snapshots on the targets.
100 - Range is 1 - 34560000 seconds.
101 type: int
102 target_per_day:
103 description:
104 - Specifies the number of I(per_day) replicated snapshots to keep beyond the I(target_all_for) period.
105 - Maximum number is 1440
106 type: int
107 target_days:
108 description:
109 - Specifies the number of days to keep the I(target_per_day) replicated snapshots
110 beyond the I(target_all_for) period before they are eradicated.
111 - Max retention period is 4000 days
112 type: int
113 context:
114 description:
115 - Name of fleet member on which to perform the operation.
116 - This requires the array receiving the request is a member of a fleet
117 and the context name to be a member of the same fleet.
118 type: str
119 default: ""
120 version_added: '1.33.0'
121 extends_documentation_fragment:
122 - purestorage.flasharray.purestorage.fa
123 """
124
125 EXAMPLES = r"""
126 - name: Update protection group snapshot schedule
127 purestorage.flasharray.purefa_pgsched:
128 name: foo
129 schedule: snapshot
130 enabled: true
131 snap_frequency: 86400
132 snap_at: 3PM
133 per_day: 5
134 all_for: 5
135 fa_url: 10.10.10.2
136 api_token: e31060a7-21fc-e277-6240-25983c6c4592
137
138 - name: Update protection group replication schedule
139 purestorage.flasharray.purefa_pgsched:
140 name: foo
141 schedule: replication
142 enabled: true
143 replicate_frequency: 86400
144 replicate_at: 3PM
145 target_per_day: 5
146 target_all_for: 5
147 blackout_start: 2AM
148 blackout_end: 5AM
149 fa_url: 10.10.10.2
150 api_token: e31060a7-21fc-e277-6240-25983c6c4592
151
152 - name: Delete protection group snapshot schedule
153 purestorage.flasharray.purefa_pgsched:
154 name: foo
155 schedule: snapshot
156 state: absent
157 fa_url: 10.10.10.2
158 api_token: e31060a7-21fc-e277-6240-25983c6c4592
159
160 - name: Delete protection group replication schedule
161 purestorage.flasharray.purefa_pgsched:
162 name: foo
163 schedule: replication
164 state: absent
165 fa_url: 10.10.10.2
166 api_token: e31060a7-21fc-e277-6240-25983c6c4592
167 """
168
169 RETURN = r"""
170 """
171
172 from ansible.module_utils.basic import AnsibleModule
173 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
174 get_array,
175 purefa_argument_spec,
176 )
177 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
178 LooseVersion,
179 )
180
181 HAS_PURESTORAGE = True
182 try:
183 from pypureclient.flasharray import (
184 ProtectionGroup,
185 ReplicationSchedule,
186 SnapshotSchedule,
187 RetentionPolicy,
188 TimeWindow,
189 )
190 except ImportError:
191 HAS_PURESTORAGE = False
192
193
194 CONTEXT_API_VERSION = "2.38"
195
196
197 def get_pending_pgroup(module, array):
198 """Get Protection Group"""
199 api_version = array.get_rest_version()
200 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
201 res = array.get_protection_groups(
202 names=[module.params["name"]],
203 destroyed=True,
204 context_names=[module.params["name"]],
205 )
206 else:
207 res = array.get_protection_groups(names=[module.params["name"]], destroyed=True)
208 if res.status_code == 200:
209 return list(res.items)[0]
210 return None
211
212
213 def get_pgroup(module, array):
214 """Get Protection Group"""
215 api_version = array.get_rest_version()
216 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
217 res = array.get_protection_groups(
218 names=[module.params["name"]], context_names=[module.params["context"]]
219 )
220 else:
221 res = array.get_protection_groups(names=[module.params["name"]])
222 if res.status_code == 200:
223 return list(res.items)[0]
224 return None
225
226
227 def _convert_to_minutes(hour):
228 period = hour[-2:].upper()
229 hour_value = int(hour[:-2])
230
231 if period == "AM" and hour_value == 12:
232 return 0
233 if period == "AM":
234 return hour_value * 3600
235 if period == "PM" and hour_value == 12:
236 return 43200
237 return (hour_value + 12) * 3600
238
239
240 def update_schedule(module, array, snap_time, repl_time):
241 """
242 Update Protection Group Schedule for snapshots and replication.
243 Immediately fail if any patch call returns an error.
244 """
245 api_version = array.get_rest_version()
246 changed = False
247
248 # Fetch protection group
249 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
250 groups = list(
251 array.get_protection_groups(
252 names=[module.params["name"]], context_names=[module.params["context"]]
253 ).items
254 )
255 else:
256 groups = list(array.get_protection_groups(names=[module.params["name"]]).items)
257
258 if not groups:
259 module.fail_json(msg=f"Protection group {module.params['name']} not found")
260
261 schedule = groups[0]
262
263 # Ensure blackout exists
264 if not hasattr(schedule.replication_schedule.blackout, "start"):
265 schedule.replication_schedule.blackout = TimeWindow(start=0, end=0)
266
267 # Current snapshot schedule
268 current_snap = {
269 "days": schedule.source_retention.days,
270 "snap_frequency": schedule.snapshot_schedule.frequency,
271 "snap_enabled": schedule.snapshot_schedule.enabled,
272 "snap_at": getattr(schedule.snapshot_schedule, "at", None),
273 "per_day": schedule.source_retention.per_day,
274 "all_for": schedule.source_retention.all_for_sec,
275 }
276
277 # Current replication schedule
278 current_repl = {
279 "replicate_frequency": schedule.replication_schedule.frequency,
280 "replicate_enabled": schedule.replication_schedule.enabled,
281 "replicate_at": getattr(schedule.replication_schedule, "at", None),
282 "target_days": schedule.target_retention.days,
283 "target_per_day": schedule.target_retention.per_day,
284 "target_all_for": schedule.target_retention.all_for_sec,
285 "blackout_start": schedule.replication_schedule.blackout.start,
286 "blackout_end": schedule.replication_schedule.blackout.end,
287 }
288
289 kwargs = {"names": [module.params["name"]]}
290 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
291 kwargs["context_names"] = [module.params["context"]]
292
293 # Snapshot schedule
294 if module.params["schedule"] == "snapshot":
295 snap_enabled = (
296 current_snap["snap_enabled"]
297 if module.params.get("enabled") is None
298 else module.params["enabled"]
299 )
300 snap_frequency = (
301 module.params["snap_frequency"] * 1000
302 if module.params.get("snap_frequency") is not None
303 else current_snap["snap_frequency"]
304 )
305 snap_at = (
306 _convert_to_minutes(module.params["snap_at"].upper())
307 if module.params.get("snap_at")
308 else current_snap["snap_at"]
309 )
310 days = (
311 current_snap["days"]
312 if module.params.get("days") is None
313 else module.params["days"]
314 )
315 per_day = (
316 current_snap["per_day"]
317 if module.params.get("per_day") is None
318 else module.params["per_day"]
319 )
320 all_for = (
321 current_snap["all_for"]
322 if module.params.get("all_for") is None
323 else module.params["all_for"]
324 )
325
326 # Patch snap_enabled separately
327 if snap_enabled != current_snap["snap_enabled"]:
328 changed = True
329 res = array.patch_protection_groups(
330 **kwargs,
331 protection_group=ProtectionGroup(
332 snapshot_schedule=SnapshotSchedule(enabled=snap_enabled)
333 ),
334 )
335 if res.status_code != 200:
336 module.fail_json(
337 msg=f"Failed to update snap_enabled for pgroup {module.params['name']}. Error: {res.errors[0].message}"
338 )
339
340 # Patch frequency and at together
341 if (
342 snap_frequency != current_snap["snap_frequency"]
343 or snap_at != current_snap["snap_at"]
344 ):
345 changed = True
346 res = array.patch_protection_groups(
347 **kwargs,
348 protection_group=ProtectionGroup(
349 snapshot_schedule=SnapshotSchedule(
350 frequency=snap_frequency, at=snap_at
351 )
352 ),
353 )
354 if res.status_code != 200:
355 module.fail_json(
356 msg=f"Failed to update snap_frequency/at for pgroup {module.params['name']}. Error: {res.errors[0].message}"
357 )
358
359 # Patch retention separately
360 if (
361 days != current_snap["days"]
362 or per_day != current_snap["per_day"]
363 or all_for != current_snap["all_for"]
364 ):
365 changed = True
366 res = array.patch_protection_groups(
367 **kwargs,
368 protection_group=ProtectionGroup(
369 source_retention=RetentionPolicy(
370 days=days, per_day=per_day, all_for_sec=all_for
371 )
372 ),
373 )
374 if res.status_code != 200:
375 module.fail_json(
376 msg=f"Failed to update snapshot retention for pgroup {module.params['name']}. Error: {res.errors[0].message}"
377 )
378
379 # Replication schedule
380 else:
381 replicate_enabled = (
382 current_repl["replicate_enabled"]
383 if module.params.get("enabled") is None
384 else module.params["enabled"]
385 )
386 replicate_frequency = (
387 module.params["replicate_frequency"] * 1000
388 if module.params.get("replicate_frequency") is not None
389 else current_repl["replicate_frequency"]
390 )
391 replicate_at = (
392 _convert_to_minutes(module.params["replicate_at"].upper())
393 if module.params.get("replicate_at")
394 else current_repl["replicate_at"]
395 )
396 target_days = (
397 current_repl["target_days"]
398 if module.params.get("target_days") is None
399 else module.params["target_days"]
400 )
401 target_per_day = (
402 current_repl["target_per_day"]
403 if module.params.get("target_per_day") is None
404 else module.params["target_per_day"]
405 )
406 target_all_for = (
407 current_repl["target_all_for"]
408 if module.params.get("target_all_for") is None
409 else module.params["target_all_for"]
410 )
411 blackout_start = (
412 current_repl["blackout_start"]
413 if module.params.get("blackout_start") is None
414 else _convert_to_minutes(module.params["blackout_start"].upper())
415 )
416 blackout_end = (
417 current_repl["blackout_end"]
418 if module.params.get("blackout_end") is None
419 else _convert_to_minutes(module.params["blackout_end"].upper())
420 )
421
422 # Patch replicate_enabled separately
423 if replicate_enabled != current_repl["replicate_enabled"]:
424 changed = True
425 res = array.patch_protection_groups(
426 **kwargs,
427 protection_group=ProtectionGroup(
428 replication_schedule=ReplicationSchedule(enabled=replicate_enabled)
429 ),
430 )
431 if res.status_code != 200:
432 module.fail_json(
433 msg=f"Failed to update replicate_enabled for pgroup {module.params['name']}. Error: {res.errors[0].message}"
434 )
435
436 # Patch frequency and at together
437 if (
438 replicate_frequency != current_repl["replicate_frequency"]
439 or replicate_at != current_repl["replicate_at"]
440 ):
441 changed = True
442 res = array.patch_protection_groups(
443 **kwargs,
444 protection_group=ProtectionGroup(
445 replication_schedule=ReplicationSchedule(
446 frequency=replicate_frequency, at=replicate_at
447 )
448 ),
449 )
450 if res.status_code != 200:
451 module.fail_json(
452 msg=f"Failed to update replicate_frequency/at for pgroup {module.params['name']}. Error: {res.errors[0].message}"
453 )
454
455 # Patch blackout separately
456 if (
457 blackout_start != current_repl["blackout_start"]
458 or blackout_end != current_repl["blackout_end"]
459 ):
460 changed = True
461 res = array.patch_protection_groups(
462 **kwargs,
463 protection_group=ProtectionGroup(
464 replication_schedule=ReplicationSchedule(
465 blackout=TimeWindow(start=blackout_start, end=blackout_end)
466 )
467 ),
468 )
469 if res.status_code != 200:
470 module.fail_json(
471 msg=f"Failed to update blackout window for pgroup {module.params['name']}. Error: {res.errors[0].message}"
472 )
473
474 # Patch target retention separately
475 if (
476 target_days != current_repl["target_days"]
477 or target_per_day != current_repl["target_per_day"]
478 or target_all_for != current_repl["target_all_for"]
479 ):
480 changed = True
481 res = array.patch_protection_groups(
482 **kwargs,
483 protection_group=ProtectionGroup(
484 target_retention=RetentionPolicy(
485 days=target_days,
486 per_day=target_per_day,
487 all_for_sec=target_all_for,
488 )
489 ),
490 )
491 if res.status_code != 200:
492 module.fail_json(
493 msg=f"Failed to update replication retention for pgroup {module.params['name']}. Error: {res.errors[0].message}"
494 )
495
496 module.exit_json(changed=changed)
497
498
499 def delete_schedule(module, array):
500 """Delete, ie. disable, Protection Group Schedules"""
501 api_version = array.get_rest_version()
502 changed = False
503
504 class Res:
505 def __init__(self, status_code):
506 self.status_code = status_code
507
508 res = Res(200)
509 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
510 schedule = list(
511 array.get_protection_groups(
512 names=[module.params["name"]], context_names=[module.params["context"]]
513 ).items
514 )[0]
515 else:
516 schedule = list(
517 array.get_protection_groups(names=[module.params["name"]]).items
518 )[0]
519 if module.params["schedule"] == "replication":
520 if schedule.replication_schedule.enabled:
521 changed = True
522 if not module.check_mode:
523 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
524 res = array.patch_protection_groups(
525 names=[module.params["name"]],
526 context_names=[module.params["context"]],
527 protection_group=ProtectionGroup(
528 replication_schedule=ReplicationSchedule(
529 blackout=TimeWindow(start=0, end=0),
530 frequency=14400,
531 enabled=False,
532 ),
533 ),
534 )
535 if res.status_code != 200:
536 module.fail_json(
537 msg="Resetting pgroup {0} {1} schedule failed. Error: {2}".format(
538 module.params["name"],
539 module.params["schedule"],
540 res.errors[0].message,
541 )
542 )
543 res = array.patch_protection_groups(
544 names=[module.params["name"]],
545 context_names=[module.params["context"]],
546 protection_group=ProtectionGroup(
547 target_retention=RetentionPolicy(
548 all_for_sec=1,
549 per_day=0,
550 days=0,
551 ),
552 ),
553 )
554 else:
555 res = array.patch_protection_groups(
556 names=[module.params["name"]],
557 protection_group=ProtectionGroup(
558 target_retention=RetentionPolicy(
559 all_for_sec=1,
560 per_day=0,
561 days=0,
562 ),
563 ),
564 )
565 if res.status_code != 200:
566 module.fail_json(
567 msg="Resetting pgroup {0} {1} schedule failed. Error: {2}".format(
568 module.params["name"],
569 module.params["schedule"],
570 res.errors[0].message,
571 )
572 )
573 res = array.patch_protection_groups(
574 names=[module.params["name"]],
575 protection_group=ProtectionGroup(
576 replication_schedule=ReplicationSchedule(
577 blackout=TimeWindow(start=0, end=0),
578 frequency=14400,
579 enabled=False,
580 ),
581 ),
582 )
583 else:
584 if schedule.snapshot_schedule.enabled:
585 changed = True
586 if not module.check_mode:
587 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
588 res = array.patch_protection_groups(
589 names=[module.params["name"]],
590 context_names=[module.params["context"]],
591 protection_group=ProtectionGroup(
592 snapshot_schedule=SnapshotSchedule(
593 frequency=300, enabled=False
594 ),
595 ),
596 )
597 if res.status_code != 200:
598 module.fail_json(
599 msg="Resetting pgroup {0} {1} schedule failed. Error: {2}".format(
600 module.params["name"],
601 module.params["schedule"],
602 res.errors[0].message,
603 )
604 )
605 res = array.patch_protection_groups(
606 names=[module.params["name"]],
607 context_names=[module.params["context"]],
608 protection_group=ProtectionGroup(
609 source_retention=RetentionPolicy(
610 all_for_sec=1,
611 per_day=0,
612 days=0,
613 ),
614 ),
615 )
616 else:
617 res = array.patch_protection_groups(
618 names=[module.params["name"]],
619 protection_group=ProtectionGroup(
620 snapshot_schedule=SnapshotSchedule(
621 frequency=300, enabled=False
622 ),
623 ),
624 )
625 if res.status_code != 200:
626 module.fail_json(
627 msg="Resetting pgroup {0} {1} schedule failed. Error: {2}".format(
628 module.params["name"],
629 module.params["schedule"],
630 res.errors[0].message,
631 )
632 )
633 res = array.patch_protection_groups(
634 names=[module.params["name"]],
635 protection_group=ProtectionGroup(
636 source_retention=RetentionPolicy(
637 all_for_sec=1,
638 per_day=0,
639 days=0,
640 ),
641 ),
642 )
643 if res.status_code != 200:
644 module.fail_json(
645 msg="Deleting pgroup {0} {1} schedule failed. Error: {2}".format(
646 module.params["name"], module.params["schedule"], res.errors[0].message
647 )
648 )
649 module.exit_json(changed=changed)
650
651
652 def main():
653 argument_spec = purefa_argument_spec()
654 argument_spec.update(
655 dict(
656 name=dict(type="str", required=True),
657 state=dict(type="str", default="present", choices=["absent", "present"]),
658 schedule=dict(
659 type="str", required=True, choices=["replication", "snapshot"]
660 ),
661 blackout_start=dict(type="str"),
662 blackout_end=dict(type="str"),
663 snap_at=dict(type="str"),
664 replicate_at=dict(type="str"),
665 replicate_frequency=dict(type="int"),
666 snap_frequency=dict(type="int"),
667 all_for=dict(type="int"),
668 days=dict(type="int"),
669 per_day=dict(type="int"),
670 target_all_for=dict(type="int"),
671 target_per_day=dict(type="int"),
672 target_days=dict(type="int"),
673 enabled=dict(type="bool", default=True),
674 context=dict(type="str", default=""),
675 )
676 )
677
678 required_together = [["blackout_start", "blackout_end"]]
679
680 module = AnsibleModule(
681 argument_spec, required_together=required_together, supports_check_mode=True
682 )
683
684 state = module.params["state"]
685 array = get_array(module)
686
687 pgroup = get_pgroup(module, array)
688 repl_time = False
689 if module.params["replicate_at"] and module.params["replicate_frequency"]:
690 if not module.params["replicate_frequency"] % 86400 == 0:
691 module.fail_json(
692 msg="replicate_at not valid unless replicate frequency is measured in days, ie. a multiple of 86400"
693 )
694 repl_time = True
695 snap_time = False
696 if module.params["snap_at"] and module.params["snap_frequency"]:
697 if not module.params["snap_frequency"] % 86400 == 0:
698 module.fail_json(
699 msg="snap_at not valid unless snapshot frequency is measured in days, ie. a multiple of 86400"
700 )
701 snap_time = True
702 if pgroup and state == "present":
703 update_schedule(module, array, snap_time, repl_time)
704 elif pgroup and state == "absent":
705 delete_schedule(module, array)
706 elif pgroup is None:
707 module.fail_json(
708 msg="Specified protection group {0} does not exist.".format(
709 module.params["name"]
710 )
711 )
712
713
714 if __name__ == "__main__":
715 main()