Debian Codegraph @

ansible_collections/purestorage/flashblade/plugins/modules/purefb_snap.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2017, 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: purefb_snap
20 version_added: '1.0.0'
21 short_description: Manage filesystem snapshots on Pure Storage FlashBlades
22 description:
23 - Create or delete volumes and filesystem snapshots on Pure Storage FlashBlades.
24 - Restoring a filesystem from a snapshot is only supported using
25 the latest snapshot.
26 author:
27 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
28 options:
29 name:
30 description:
31 - The name of the source filesystem.
32 required: true
33 type: str
34 suffix:
35 description:
36 - Suffix of snapshot name.
37 type: str
38 state:
39 description:
40 - Define whether the filesystem snapshot should exist or not.
41 choices: [ absent, present, restore ]
42 default: present
43 type: str
44 target:
45 aliases: [ targets ]
46 description:
47 - Name of target to replicate snapshot to.
48 - This is only applicable when I(now) is B(true)
49 type: str
50 version_added: "1.7.0"
51 now:
52 description:
53 - Whether to initiate a snapshot replication immeadiately
54 type: bool
55 default: false
56 version_added: "1.7.0"
57 eradicate:
58 description:
59 - Define whether to eradicate the snapshot on delete or leave in trash.
60 type: bool
61 default: false
62 latest_replica:
63 description:
64 - Used when destroying a snapshot.
65 - If false, and the snapshot is the
66 latest replicated snapshot, then destroy will fail.
67 - If true or the snapshot is not the latest replicated snapshot,
68 then destroy will be successful.
69 type: bool
70 default: false
71 version_added: "1.21.0"
72 context:
73 description:
74 - Name of fleet member on which to perform the operation.
75 - This requires the array receiving the request is a member of a fleet
76 and the context name to be a member of the same fleet.
77 type: str
78 default: ""
79 version_added: "1.22.0"
80 extends_documentation_fragment:
81 - purestorage.flashblade.purestorage.fb
82 """
83
84 EXAMPLES = r"""
85 - name: Create snapshot foo.ansible
86 purestorage.flashblade.purefb_snap:
87 name: foo
88 suffix: ansible
89 fb_url: 10.10.10.2
90 api_token: e31060a7-21fc-e277-6240-25983c6c4592
91 state: present
92
93 - name: Create immeadiate snapshot foo.ansible to connected FB bar
94 purestorage.flashblade.purefb_snap:
95 name: foo
96 suffix: ansible
97 now: true
98 target: bar
99 fb_url: 10.10.10.2
100 api_token: e31060a7-21fc-e277-6240-25983c6c4592
101 state: present
102
103 - name: Delete snapshot named foo.snap
104 purestorage.flashblade.purefb_snap:
105 name: foo
106 suffix: snap
107 fb_url: 10.10.10.2
108 api_token: e31060a7-21fc-e277-6240-25983c6c4592
109 state: absent
110
111 - name: Recover deleted snapshot foo.ansible
112 purestorage.flashblade.purefb_snap:
113 name: foo
114 suffix: ansible
115 fb_url: 10.10.10.2
116 api_token: e31060a7-21fc-e277-6240-25983c6c4592
117 state: present
118
119 - name: Restore filesystem foo (uses latest snapshot)
120 purestorage.flashblade.purefb_snap:
121 name: foo
122 fb_url: 10.10.10.2
123 api_token: e31060a7-21fc-e277-6240-25983c6c4592
124 state: restore
125
126 - name: Eradicate snapshot named foo.snap
127 purestorage.flashblade.purefb_snap:
128 name: foo
129 suffix: snap
130 eradicate: true
131 fb_url: 10.10.10.2
132 api_token: e31060a7-21fc-e277-6240-25983c6c4592
133 state: absent
134 """
135
136 RETURN = r"""
137 """
138
139 from ansible.module_utils.basic import AnsibleModule
140 from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
141 get_system,
142 purefb_argument_spec,
143 )
144
145 from datetime import datetime
146
147 HAS_PYPURECLIENT = True
148 try:
149 from pypureclient.flashblade import (
150 FileSystemSnapshotPost,
151 FileSystemSnapshot,
152 FileSystemPost,
153 Reference,
154 )
155 except ImportError:
156 HAS_PYPURECLIENT = False
157
158 SNAP_NOW_API = "2.10"
159 CONTEXT_API_VERSION = "2.17"
160
161
162 def get_fs(module, blade):
163 """Return Filesystem or None"""
164 api_version = list(blade.get_versions().items)
165 if CONTEXT_API_VERSION in api_version:
166 res = blade.get_file_systems(
167 names=[module.params["name"]], context_names=[module.params["context"]]
168 )
169 else:
170 res = blade.get_file_systems(names=[module.params["name"]])
171 if res.status_code == 200:
172 return list(res.items)[0]
173 return None
174
175
176 def get_latest_fssnapshot(module, blade):
177 """Get the name of the latest snpshot or None"""
178 api_version = list(blade.get_versions().items)
179 if CONTEXT_API_VERSION in api_version:
180 res = blade.get_file_system_snapshots(
181 names_or_owner_names=[module.params["name"]],
182 context_names=[module.params["context"]],
183 )
184 else:
185 res = blade.get_file_system_snapshots(
186 names_or_owner_names=[module.params["name"]]
187 )
188 if res.status_code != 200:
189 module.fail_json(
190 msg="Failed to get filesystem snapshots. Error: {0}".format(
191 res.errors[0].message
192 )
193 )
194 all_snaps = list(res.items)
195 last_snap = sorted(all_snaps, key=lambda x: x["created"])[-1]
196 if not last_snap.destroyed:
197 return last_snap.name
198 module.fail_json(
199 msg="Latest snapshot {0} is destroyed."
200 " Eradicate or recover this first.".format(all_snaps[0].name)
201 )
202 return None
203
204
205 def get_fssnapshot(module, blade):
206 """Return Snapshot or None"""
207 api_version = list(blade.get_versions().items)
208 if CONTEXT_API_VERSION in api_version:
209 res = blade.get_file_system_snapshots(
210 names_or_owner_names=[
211 module.params["name"] + "." + module.params["suffix"]
212 ],
213 context_names=[module.params["context"]],
214 )
215 else:
216 res = blade.get_file_system_snapshots(
217 names_or_owner_names=[
218 module.params["name"] + "." + module.params["suffix"]
219 ],
220 )
221 if res.status_code == 200:
222 return list(res.items)[0]
223 return None
224
225
226 def create_snapshot(module, blade):
227 """Create Snapshot"""
228 api_version = list(blade.get_versions().items)
229 changed = False
230 # Special case as we have changed 'target' to be a string not a list of one string
231 # so this provides backwards compatability
232 # target = module.params["target"].replace("[", "").replace("'", "").replace("]", "")
233 blade_exists = False
234 if CONTEXT_API_VERSION in api_version:
235 connected_blades = list(
236 blade.get_array_connections(context_names=[module.params["context"]]).items
237 )
238 else:
239 connected_blades = list(blade.get_array_connections().items)
240 for rem_blade in range(len(connected_blades)):
241 if (
242 module.params["target"]
243 and module.params["target"] == connected_blades[rem_blade].remote.name
244 and connected_blades[rem_blade].status == "connected"
245 ):
246 blade_exists = True
247 break
248 if not module.params["target"] and blade_exists:
249 module.fail_json(msg="Selected target is not a correctly connected system")
250 changed = True
251 if not module.check_mode:
252 if module.params["target"]:
253 if CONTEXT_API_VERSION in api_version:
254 res = blade.post_file_system_snapshots(
255 source_names=[module.params["name"]],
256 send=module.params["now"],
257 targets=[module.params["target"]],
258 file_system_snapshot=FileSystemSnapshotPost(
259 suffix=module.params["suffix"]
260 ),
261 context_names=[module.params["context"]],
262 )
263 else:
264 res = blade.post_file_system_snapshots(
265 source_names=[module.params["name"]],
266 send=module.params["now"],
267 targets=[module.params["target"]],
268 file_system_snapshot=FileSystemSnapshotPost(
269 suffix=module.params["suffix"]
270 ),
271 )
272 else:
273 if CONTEXT_API_VERSION in api_version:
274 res = blade.post_file_system_snapshots(
275 source_names=[module.params["name"]],
276 file_system_snapshot=FileSystemSnapshotPost(
277 suffix=module.params["suffix"]
278 ),
279 context_names=[module.params["context"]],
280 )
281 else:
282 res = blade.post_file_system_snapshots(
283 source_names=[module.params["name"]],
284 file_system_snapshot=FileSystemSnapshotPost(
285 suffix=module.params["suffix"]
286 ),
287 )
288 if res.status_code != 200:
289 module.fail_json(
290 msg="Failed to create remote snapshot. Error: {0}".format(
291 res.errors[0].message
292 )
293 )
294 module.exit_json(changed=changed)
295
296
297 def restore_snapshot(module, blade):
298 """Restore a filesystem back from the latest snapshot"""
299 changed = True
300 api_version = list(blade.get_versions().items)
301 snapname = get_latest_fssnapshot(module, blade)
302 if snapname is not None:
303 if not module.check_mode:
304 if CONTEXT_API_VERSION in api_version:
305 res = blade.post_file_systems(
306 names=[module.params["name"]],
307 overwrite=True,
308 discard_non_snapshotted_data=True,
309 file_system=FileSystemPost(source=Reference(name=snapname)),
310 context_names=[module.params["context"]],
311 )
312 else:
313 res = blade.post_file_systems(
314 names=[module.params["name"]],
315 overwrite=True,
316 discard_non_snapshotted_data=True,
317 file_system=FileSystemPost(source=Reference(name=snapname)),
318 )
319 if res.status_code != 200:
320 module.fail_json(
321 msg="Failed to restore snapshot {0} to filesystem {1}. Error: {2}".format(
322 snapname, module.params["name"], res.errors[0].message
323 )
324 )
325 else:
326 module.fail_json(
327 msg="Filesystem {0} has no snapshots to restore from.".format(
328 module.params["name"]
329 )
330 )
331 module.exit_json(changed=changed)
332
333
334 def recover_snapshot(module, blade):
335 """Recover deleted Snapshot"""
336 changed = True
337 api_version = list(blade.get_versions().items)
338 if not module.check_mode:
339 snapname = module.params["name"] + "." + module.params["suffix"]
340 if CONTEXT_API_VERSION in api_version:
341 res = blade.patch_file_system_snapshots(
342 names=[snapname],
343 file_system_snapshot=FileSystemSnapshot(destroyed=False),
344 context_names=[module.params["context"]],
345 )
346 else:
347 res = blade.patch_file_system_snapshots(
348 names=[snapname],
349 file_system_snapshot=FileSystemSnapshot(destroyed=False),
350 )
351 if res.status_code != 200:
352 module.fail_json(
353 msg="Failed to recover snapshot {0} for filesystem {1}. Error: {2}".format(
354 snapname, module.params["name"], res.errors[0].message
355 )
356 )
357 module.exit_json(changed=changed)
358
359
360 def update_snapshot(module, blade):
361 """Update Snapshot"""
362 changed = False
363 module.exit_json(changed=changed)
364
365
366 def delete_snapshot(module, blade):
367 """Delete Snapshot"""
368 changed = True
369 api_version = list(blade.get_versions().items)
370 if not module.check_mode:
371 snapname = module.params["name"] + "." + module.params["suffix"]
372 if CONTEXT_API_VERSION in api_version:
373 res = blade.patch_file_system_snapshots(
374 names=[snapname],
375 latest_replica=module.params["latest_replica"],
376 file_system_snapshot=FileSystemSnapshot(destroyed=True),
377 context_names=[module.params["context"]],
378 )
379 else:
380 res = blade.patch_file_system_snapshots(
381 names=[snapname],
382 latest_replica=module.params["latest_replica"],
383 file_system_snapshot=FileSystemSnapshot(destroyed=True),
384 )
385 if res.status_code != 200:
386 module.fail_json(
387 msg="Failed to delete snapshot {0}. Error: {1}".format(
388 snapname, res.errors[0].message
389 )
390 )
391 if module.params["eradicate"]:
392 if CONTEXT_API_VERSION in api_version:
393 res = blade.delete_file_system_snapshots(
394 names=[snapname], context_names=[module.params["context"]]
395 )
396 else:
397 res = blade.delete_file_system_snapshots(names=[snapname])
398 if res.status_code != 200:
399 module.fail_json(
400 msg="Failed to eradicate snapshot {0}. Error: {1}".format(
401 snapname, res.errors[0].message
402 )
403 )
404 module.exit_json(changed=changed)
405
406
407 def eradicate_snapshot(module, blade):
408 """Eradicate Snapshot"""
409 changed = True
410 api_version = list(blade.get_versions().items)
411 if not module.check_mode:
412 snapname = module.params["name"] + "." + module.params["suffix"]
413 if CONTEXT_API_VERSION in api_version:
414 res = blade.delete_file_system_snapshots(
415 names=[snapname], context_names=[module.params["context"]]
416 )
417 else:
418 res = blade.delete_file_system_snapshots(names=[snapname])
419 if res.status_code != 200:
420 module.fail_json(
421 msg="Failed to eradicate snapshot {0}. Error: {1}".format(
422 snapname, res.errors[0].message
423 )
424 )
425 module.exit_json(changed=changed)
426
427
428 def main():
429 argument_spec = purefb_argument_spec()
430 argument_spec.update(
431 dict(
432 name=dict(required=True),
433 suffix=dict(type="str"),
434 now=dict(type="bool", default=False),
435 target=dict(type="str", aliases=["targets"]),
436 eradicate=dict(default="false", type="bool"),
437 state=dict(default="present", choices=["present", "absent", "restore"]),
438 latest_replica=dict(default="false", type="bool"),
439 context=dict(type="str", default=""),
440 )
441 )
442
443 required_if = [["now", True, ["target"]]]
444 module = AnsibleModule(
445 argument_spec, required_if=required_if, supports_check_mode=True
446 )
447
448 if not HAS_PYPURECLIENT:
449 module.fail_json(msg="py-pure-client sdk is required for this module")
450
451 if module.params["suffix"] is None:
452 suffix = "snap-" + str(
453 (datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
454 )
455 module.params["suffix"] = suffix.replace(".", "")
456
457 state = module.params["state"]
458 blade = get_system(module)
459 api_version = list(blade.get_versions().items)
460
461 if SNAP_NOW_API not in api_version and module.params["now"]:
462 module.fail_json(
463 msg="Minimum FlashBlade REST version for immeadiate remote snapshots: {0}".format(
464 SNAP_NOW_API
465 )
466 )
467 filesystem = get_fs(module, blade)
468 snap = get_fssnapshot(module, blade)
469 if state == "present" and filesystem and not filesystem.destroyed and not snap:
470 create_snapshot(module, blade)
471 elif (
472 state == "present"
473 and filesystem
474 and not filesystem.destroyed
475 and snap
476 and not snap.destroyed
477 ):
478 update_snapshot(module, blade)
479 elif (
480 state == "present"
481 and filesystem
482 and not filesystem.destroyed
483 and snap
484 and snap.destroyed
485 ):
486 recover_snapshot(module, blade)
487 elif state == "present" and filesystem and filesystem.destroyed:
488 update_snapshot(module, blade)
489 elif state == "present" and not filesystem:
490 update_snapshot(module, blade)
491 elif state == "restore" and filesystem:
492 restore_snapshot(module, blade)
493 elif state == "absent" and snap and not snap.destroyed:
494 delete_snapshot(module, blade)
495 elif state == "absent" and snap and snap.destroyed:
496 eradicate_snapshot(module, blade)
497 elif state == "absent" and not snap:
498 module.exit_json(changed=False)
499 else:
500 module.exit_json(changed=False)
501
502
503 if __name__ == "__main__":
504 main()