Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/filesystem_snapshot.py

raw symbols SCIP
1 #!/usr/bin/python
2 # Copyright: (c) 2020-2025, Dell Technologies
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 """ Ansible module for managing Filesystem Snapshots on Unity"""
6
7 from __future__ import (absolute_import, division, print_function)
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: filesystem_snapshot
14 short_description: Manage filesystem snapshot on the Unity storage system
15 description:
16 - Managing Filesystem Snapshot on the Unity storage system includes
17 create filesystem snapshot, get filesystem snapshot, modify filesystem
18 snapshot and delete filesystem snapshot.
19 version_added: '1.1.0'
20 extends_documentation_fragment:
21 - dellemc.unity.unity
22 author:
23 - Rajshree Khare (@kharer5) <[email protected]>
24 options:
25 snapshot_name:
26 description:
27 - The name of the filesystem snapshot.
28 - Mandatory parameter for creating a filesystem snapshot.
29 - For all other operations either I(snapshot_name) or I(snapshot_id)
30 is required.
31 type: str
32 snapshot_id:
33 description:
34 - During creation snapshot_id is auto generated.
35 - For all other operations either I(snapshot_id) or I(snapshot_name)
36 is required.
37 type: str
38 filesystem_name:
39 description:
40 - The name of the Filesystem for which snapshot is created.
41 - For creation of filesystem snapshot either I(filesystem_name) or
42 I(filesystem_id) is required.
43 - Not required for other operations.
44 type: str
45 filesystem_id:
46 description:
47 - The ID of the Filesystem for which snapshot is created.
48 - For creation of filesystem snapshot either I(filesystem_id) or
49 I(filesystem_name) is required.
50 - Not required for other operations.
51 type: str
52 nas_server_name:
53 description:
54 - The name of the NAS server in which the Filesystem is created.
55 - For creation of filesystem snapshot either I(nas_server_name) or
56 I(nas_server_id) is required.
57 - Not required for other operations.
58 type: str
59 nas_server_id:
60 description:
61 - The ID of the NAS server in which the Filesystem is created.
62 - For creation of filesystem snapshot either I(filesystem_id) or
63 I(filesystem_name) is required.
64 - Not required for other operations.
65 type: str
66 auto_delete:
67 description:
68 - This option specifies whether or not the filesystem snapshot will be
69 automatically deleted.
70 - If set to C(true), the filesystem snapshot will expire based on the pool
71 auto deletion policy.
72 - If set to C(false), the filesystem snapshot will not be auto deleted
73 based on the pool auto deletion policy.
74 - Option I(auto_delete) can not be set to C(true), if I(expiry_time) is specified.
75 - If during creation neither I(auto_delete) nor I(expiry_time) is mentioned
76 then the filesystem snapshot will be created keeping I(auto_delete) as
77 C(true).
78 - Once the I(expiry_time) is set, then the filesystem snapshot cannot be
79 assigned to the auto delete policy.
80 type: bool
81 expiry_time:
82 description:
83 - This option is for specifying the date and time after which the
84 filesystem snapshot will expire.
85 - The time is to be mentioned in UTC timezone.
86 - The format is "MM/DD/YYYY HH:MM". Year must be in 4 digits.
87 type: str
88 description:
89 description:
90 - The additional information about the filesystem snapshot can be
91 provided using this option.
92 - The description can be removed by passing an empty string.
93 type: str
94 fs_access_type:
95 description:
96 - Access type of the filesystem snapshot.
97 - Required only during creation of filesystem snapshot.
98 - If not given, snapshot's access type will be C(Checkpoint).
99 type: str
100 choices: ['Checkpoint' , 'Protocol']
101 state:
102 description:
103 - The state option is used to mention the existence of the filesystem
104 snapshot.
105 type: str
106 required: true
107 choices: ['absent', 'present']
108 notes:
109 - Filesystem snapshot cannot be deleted, if it has nfs or smb share.
110 - The I(check_mode) is not supported.
111 '''
112
113 EXAMPLES = r'''
114 - name: Create Filesystem Snapshot
115 filesystem_snapshot:
116 unispherehost: "{{unispherehost}}"
117 username: "{{username}}"
118 password: "{{password}}"
119 validate_certs: "{{validate_certs}}"
120 snapshot_name: "ansible_test_FS_snap"
121 filesystem_name: "ansible_test_FS"
122 nas_server_name: "lglad069"
123 description: "Created using playbook"
124 auto_delete: true
125 fs_access_type: "Protocol"
126 state: "present"
127
128 - name: Create Filesystem Snapshot with expiry time
129 filesystem_snapshot:
130 unispherehost: "{{unispherehost}}"
131 username: "{{username}}"
132 password: "{{password}}"
133 validate_certs: "{{validate_certs}}"
134 snapshot_name: "ansible_test_FS_snap_1"
135 filesystem_name: "ansible_test_FS_1"
136 nas_server_name: "lglad069"
137 description: "Created using playbook"
138 expiry_time: "04/15/2021 2:30"
139 fs_access_type: "Protocol"
140 state: "present"
141
142 - name: Get Filesystem Snapshot Details using Name
143 filesystem_snapshot:
144 unispherehost: "{{unispherehost}}"
145 username: "{{username}}"
146 password: "{{password}}"
147 validate_certs: "{{validate_certs}}"
148 snapshot_name: "ansible_test_FS_snap"
149 state: "present"
150
151 - name: Get Filesystem Snapshot Details using ID
152 filesystem_snapshot:
153 unispherehost: "{{unispherehost}}"
154 username: "{{username}}"
155 password: "{{password}}"
156 validate_certs: "{{validate_certs}}"
157 snapshot_id: "10008000403"
158 state: "present"
159
160 - name: Update Filesystem Snapshot attributes
161 filesystem_snapshot:
162 unispherehost: "{{unispherehost}}"
163 username: "{{username}}"
164 password: "{{password}}"
165 validate_certs: "{{validate_certs}}"
166 snapshot_name: "ansible_test_FS_snap"
167 description: "Description updated"
168 auto_delete: false
169 expiry_time: "04/15/2021 5:30"
170 state: "present"
171
172 - name: Update Filesystem Snapshot attributes using ID
173 filesystem_snapshot:
174 unispherehost: "{{unispherehost}}"
175 username: "{{username}}"
176 password: "{{password}}"
177 validate_certs: "{{validate_certs}}"
178 snapshot_id: "10008000403"
179 expiry_time: "04/18/2021 8:30"
180 state: "present"
181
182 - name: Delete Filesystem Snapshot using Name
183 filesystem_snapshot:
184 unispherehost: "{{unispherehost}}"
185 username: "{{username}}"
186 password: "{{password}}"
187 validate_certs: "{{validate_certs}}"
188 snapshot_name: "ansible_test_FS_snap"
189 state: "absent"
190
191 - name: Delete Filesystem Snapshot using ID
192 filesystem_snapshot:
193 unispherehost: "{{unispherehost}}"
194 username: "{{username}}"
195 password: "{{password}}"
196 validate_certs: "{{validate_certs}}"
197 snapshot_id: "10008000403"
198 state: "absent"
199 '''
200
201 RETURN = r'''
202 changed:
203 description: Whether or not the resource has changed.
204 returned: always
205 type: bool
206 sample: true
207
208 filesystem_snapshot_details:
209 description: Details of the filesystem snapshot.
210 returned: When filesystem snapshot exists
211 type: dict
212 contains:
213 access_type:
214 description: Access type of filesystem snapshot.
215 type: str
216 attached_wwn:
217 description: Attached WWN details.
218 type: str
219 creation_time:
220 description: Creation time of filesystem snapshot.
221 type: str
222 creator_schedule:
223 description: Creator schedule of filesystem snapshot.
224 type: str
225 creator_type:
226 description: Creator type for filesystem snapshot.
227 type: str
228 creator_user:
229 description: Creator user for filesystem snapshot.
230 type: str
231 description:
232 description: Description of the filesystem snapshot.
233 type: str
234 expiration_time:
235 description: Date and time after which the filesystem snapshot
236 will expire.
237 type: str
238 is_auto_delete:
239 description: Is the filesystem snapshot is auto deleted or not.
240 type: bool
241 id:
242 description: Unique identifier of the filesystem snapshot
243 instance.
244 type: str
245 name:
246 description: The name of the filesystem snapshot.
247 type: str
248 size:
249 description: Size of the filesystem snapshot.
250 type: int
251 filesystem_name:
252 description: Name of the filesystem for which the snapshot exists.
253 type: str
254 filesystem_id:
255 description: Id of the filesystem for which the snapshot exists.
256 type: str
257 nas_server_name:
258 description: Name of the NAS server on which filesystem exists.
259 type: str
260 nas_server_id:
261 description: Id of the NAS server on which filesystem exists.
262 type: str
263 sample: {
264 "access_type": "FilesystemSnapAccessTypeEnum.CHECKPOINT",
265 "attached_wwn": null,
266 "creation_time": "2022-10-21 04:42:53.951000+00:00",
267 "creator_schedule": null,
268 "creator_type": "SnapCreatorTypeEnum.USER_CUSTOM",
269 "creator_user": {
270 "id": "user_admin"
271 },
272 "description": "Created using playbook",
273 "existed": true,
274 "expiration_time": null,
275 "filesystem_id": "fs_137",
276 "filesystem_name": "test",
277 "hash": 8739894572587,
278 "host_access": null,
279 "id": "171798721695",
280 "io_limit_policy": null,
281 "is_auto_delete": true,
282 "is_modifiable": false,
283 "is_modified": false,
284 "is_read_only": true,
285 "is_system_snap": false,
286 "last_writable_time": null,
287 "lun": null,
288 "name": "test_FS_snap_1",
289 "nas_server_id": "nas_1",
290 "nas_server_name": "lglad072",
291 "parent_snap": null,
292 "size": 107374182400,
293 "snap_group": null,
294 "state": "SnapStateEnum.READY"
295 }
296
297 '''
298
299 from ansible.module_utils.basic import AnsibleModule
300 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
301 import utils
302 from datetime import datetime
303
304 LOG = utils.get_logger('filesystem_snapshot')
305
306 application_type = "Ansible/1.7.1"
307
308
309 class FilesystemSnapshot(object):
310 """Class with Filesystem Snapshot operations"""
311
312 def __init__(self):
313 """ Define all parameters required by this module"""
314
315 self.module_params = utils.get_unity_management_host_parameters()
316 self.module_params.update(get_snapshot_parameters())
317
318 mutually_exclusive = [['snapshot_name', 'snapshot_id'],
319 ['filesystem_name', 'filesystem_id'],
320 ['nas_server_name', 'nas_server_id']]
321
322 required_one_of = [['snapshot_name', 'snapshot_id']]
323 # initialize the ansible module
324 self.module = AnsibleModule(argument_spec=self.module_params,
325 supports_check_mode=False,
326 mutually_exclusive=mutually_exclusive,
327 required_one_of=required_one_of)
328 utils.ensure_required_libs(self.module)
329
330 # result is a dictionary that contains changed status and
331 # filesystem snapshot details
332 self.result = {"changed": False,
333 'filesystem_snapshot_details': {}}
334
335 self.unity_conn = utils.get_unity_unisphere_connection(
336 self.module.params, application_type)
337 self.snap_obj = utils.snap.UnitySnap(self.unity_conn)
338 LOG.info('Connection established with the Unity Array')
339
340 def validate_expiry_time(self, expiry_time):
341 """Validates the specified expiry_time"""
342 try:
343 datetime.strptime(expiry_time, '%m/%d/%Y %H:%M')
344 except ValueError:
345 error_msg = ("expiry_time: %s, not in MM/DD/YYYY HH:MM format." %
346 expiry_time)
347 LOG.error(error_msg)
348 self.module.fail_json(msg=error_msg)
349
350 def to_update(self, fs_snapshot, description=None, auto_del=None,
351 expiry_time=None, fs_access_type=None):
352 """Determines whether to update the snapshot or not"""
353 snap_modify_dict = dict()
354
355 if fs_access_type and fs_access_type != fs_snapshot.access_type:
356 error_message = "Modification of access type is not allowed."
357 LOG.error(error_message)
358 self.module.fail_json(msg=error_message)
359
360 # If the snapshot has is_auto_delete True,
361 # Check if auto_delete in the input is either None or True
362 if expiry_time and fs_snapshot.is_auto_delete \
363 and (auto_del is None or auto_del):
364 self.module.fail_json(msg="expiry_time can be assigned when"
365 " auto delete is False.")
366 if auto_del is not None:
367 if fs_snapshot.expiration_time:
368 error_msg = "expiry_time for filesystem snapshot is set." \
369 " Once it is set then snapshot cannot" \
370 " be assigned to auto_delete policy."
371 self.module.fail_json(msg=error_msg)
372 if auto_del != fs_snapshot.is_auto_delete:
373 snap_modify_dict['is_auto_delete'] = auto_del
374
375 if description is not None and description != fs_snapshot.description:
376 snap_modify_dict['description'] = description
377
378 if to_update_expiry_time(fs_snapshot, expiry_time):
379 snap_modify_dict['expiry_time'] = expiry_time
380 LOG.info("Snapshot modification details: %s", snap_modify_dict)
381 return snap_modify_dict
382
383 def update_filesystem_snapshot(self, fs_snapshot, snap_modify_dict):
384 try:
385 duration = None
386 if 'expiry_time' in snap_modify_dict \
387 and snap_modify_dict['expiry_time']:
388 duration = convert_timestamp_to_sec(
389 snap_modify_dict['expiry_time'],
390 self.unity_conn.system_time)
391 if duration and duration <= 0:
392 self.module.fail_json(msg="expiry_time should be after"
393 " the current system time.")
394 if 'is_auto_delete' in snap_modify_dict \
395 and snap_modify_dict['is_auto_delete'] is not None:
396 auto_delete = snap_modify_dict['is_auto_delete']
397 else:
398 auto_delete = None
399 if 'description' in snap_modify_dict \
400 and (snap_modify_dict['description']
401 or len(snap_modify_dict['description']) == 0):
402 description = snap_modify_dict['description']
403 else:
404 description = None
405
406 fs_snapshot.modify(retentionDuration=duration,
407 isAutoDelete=auto_delete,
408 description=description)
409 fs_snapshot.update()
410 except Exception as e:
411 error_msg = "Failed to modify filesystem snapshot" \
412 " [name: %s , id: %s] with error %s."\
413 % (fs_snapshot.name, fs_snapshot.id, str(e))
414 LOG.error(error_msg)
415 self.module.fail_json(msg=error_msg)
416
417 def create_filesystem_snapshot(self, snap_name, storage_id,
418 description=None, auto_del=None,
419 expiry_time=None, fs_access_type=None):
420 try:
421 duration = None
422 if expiry_time:
423 duration = convert_timestamp_to_sec(
424 expiry_time, self.unity_conn.system_time)
425 if duration <= 0:
426 self.module.fail_json(msg="expiry_time should be after"
427 " the current system time.")
428
429 fs_snapshot = self.snap_obj.create(
430 cli=self.unity_conn._cli, storage_resource=storage_id,
431 name=snap_name, description=description,
432 is_auto_delete=auto_del, retention_duration=duration,
433 fs_access_type=fs_access_type)
434 return fs_snapshot
435 except Exception as e:
436 error_msg = "Failed to create filesystem snapshot" \
437 " %s with error %s" % (snap_name, str(e))
438 LOG.error(error_msg)
439 self.module.fail_json(msg=error_msg)
440
441 def is_snap_has_share(self, fs_snap):
442 try:
443 obj = self.unity_conn.get_nfs_share(snap=fs_snap) or \
444 self.unity_conn.get_cifs_share(snap=fs_snap)
445 if len(obj) > 0:
446 LOG.info("Snapshot has %s nfs/smb share/s", len(obj))
447 return True
448 except Exception as e:
449 msg = "Failed to get nfs/smb share from filesystem snapshot. " \
450 "error: %s" % str(e)
451 LOG.error(msg)
452 self.module.fail_json(msg=msg)
453 return False
454
455 def delete_fs_snapshot(self, fs_snapshot):
456 try:
457 # Checking whether nfs/smb share created from fs_snapshot
458 if self.is_snap_has_share(fs_snapshot):
459 msg = "Filesystem snapshot cannot be deleted because it has " \
460 "nfs/smb share"
461 LOG.error(msg)
462 self.module.fail_json(msg=msg)
463 fs_snapshot.delete()
464 return None
465
466 except Exception as e:
467 error_msg = "Failed to delete filesystem snapshot" \
468 " [name: %s, id: %s] with error %s." \
469 % (fs_snapshot.name, fs_snapshot.id, str(e))
470 LOG.error(error_msg)
471 self.module.fail_json(msg=error_msg)
472
473 def get_fs_snapshot_obj(self, name=None, id=None):
474 fs_snapshot = id if id else name
475 msg = "Failed to get details of filesystem snapshot %s with error %s."
476 try:
477 fs_snap_obj = self.unity_conn.get_snap(name=name, _id=id)
478 if fs_snap_obj and fs_snap_obj.existed:
479 LOG.info("Successfully got the filesystem snapshot object "
480 "%s.", fs_snap_obj)
481 else:
482 fs_snap_obj = None
483 return fs_snap_obj
484
485 except utils.HttpError as e:
486 if e.http_status == 401:
487 cred_err = ("Incorrect username or password , %s" % e.message)
488 self.module.fail_json(msg=cred_err)
489 else:
490 err_msg = msg % (fs_snapshot, str(e))
491 LOG.error(err_msg)
492 self.module.fail_json(msg=err_msg)
493
494 except utils.UnityResourceNotFoundError as e:
495 err_msg = msg % (fs_snapshot, str(e))
496 LOG.error(err_msg)
497 return None
498
499 except Exception as e:
500 err_msg = msg % (fs_snapshot, str(e))
501 LOG.error(err_msg)
502 self.module.fail_json(msg=err_msg)
503
504 def get_filesystem_obj(self, nas_server=None, name=None, id=None):
505 filesystem = id if id else name
506 try:
507 obj_fs = None
508 if name:
509 if not nas_server:
510 err_msg = "NAS Server is required to get the FileSystem."
511 LOG.error(err_msg)
512 self.module.fail_json(msg=err_msg)
513 obj_fs = self.unity_conn.get_filesystem(name=name,
514 nas_server=nas_server)
515 if obj_fs and obj_fs.existed:
516 LOG.info("Successfully got the filesystem object %s.",
517 obj_fs)
518 return obj_fs
519 if id:
520 if nas_server:
521 obj_fs = self.unity_conn\
522 .get_filesystem(id=id, nas_server=nas_server)
523 else:
524 obj_fs = self.unity_conn.get_filesystem(id=id)
525 if obj_fs and obj_fs.existed:
526 LOG.info("Successfully got the filesystem object %s.",
527 obj_fs)
528 return obj_fs
529 except Exception as e:
530 error_msg = "Failed to get filesystem %s with error %s."\
531 % (filesystem, str(e))
532 LOG.error(error_msg)
533 self.module.fail_json(msg=error_msg)
534
535 def get_nas_server_obj(self, name=None, id=None):
536 nas_server = id if id else name
537 error_msg = ("Failed to get NAS server %s." % nas_server)
538 try:
539 obj_nas = self.unity_conn.get_nas_server(_id=id, name=name)
540 if (name and obj_nas.existed) or (id and obj_nas.existed):
541 LOG.info("Successfully got the NAS server object %s.",
542 obj_nas)
543 return obj_nas
544 else:
545 LOG.error(error_msg)
546 self.module.fail_json(msg=error_msg)
547 except Exception as e:
548 error_msg = "Failed to get NAS server %s with error %s."\
549 % (nas_server, str(e))
550 LOG.error(error_msg)
551 self.module.fail_json(msg=error_msg)
552
553 def create_fs_snapshot_details_dict(self, fs_snapshot):
554 """ Add name and id of storage resource to filesystem snapshot
555 details """
556
557 snapshot_dict = fs_snapshot._get_properties()
558 del snapshot_dict['storage_resource']
559
560 snapshot_dict['filesystem_name'] = fs_snapshot.storage_resource.name
561 snapshot_dict['filesystem_id'] = fs_snapshot.storage_resource.filesystem.id
562
563 obj_fs = self.unity_conn.\
564 get_filesystem(id=fs_snapshot.storage_resource.filesystem.id)
565 if obj_fs and obj_fs.existed:
566 snapshot_dict['nas_server_name'] = obj_fs.nas_server[0].name
567 snapshot_dict['nas_server_id'] = obj_fs.nas_server[0].id
568
569 return snapshot_dict
570
571 def perform_module_operation(self):
572 """
573 Perform different actions on snapshot module based on parameters
574 chosen in playbook
575 """
576 snapshot_name = self.module.params['snapshot_name']
577 snapshot_id = self.module.params['snapshot_id']
578 filesystem_name = self.module.params['filesystem_name']
579 filesystem_id = self.module.params['filesystem_id']
580 nas_server_name = self.module.params['nas_server_name']
581 nas_server_id = self.module.params['nas_server_id']
582 auto_delete = self.module.params['auto_delete']
583 expiry_time = self.module.params['expiry_time']
584 description = self.module.params['description']
585 fs_access_type = self.module.params['fs_access_type']
586 state = self.module.params['state']
587 nas_server_resource = None
588 filesystem_resource = None
589 changed = False
590
591 LOG.info("Getting Filesystem Snapshot details.")
592 fs_snapshot = self.get_fs_snapshot_obj(name=snapshot_name,
593 id=snapshot_id)
594
595 msg = "Filesystem Snapshot details: %s." % str(fs_snapshot)
596 LOG.info(msg)
597
598 # Get NAS server Object
599 if nas_server_name is not None:
600 if nas_server_name == "" or nas_server_name.isspace():
601 self.module.fail_json(msg="Invalid nas_server_name given,"
602 " Please provide a valid name.")
603 nas_server_resource = self\
604 .get_nas_server_obj(name=nas_server_name)
605 elif nas_server_id is not None:
606 if nas_server_id == "" or nas_server_id.isspace():
607 self.module.fail_json(msg="Invalid nas_server_id given,"
608 " Please provide a valid ID.")
609 nas_server_resource = self.get_nas_server_obj(id=nas_server_id)
610
611 # Get Filesystem Object
612 if filesystem_name is not None:
613 if filesystem_name == "" or filesystem_name.isspace():
614 self.module.fail_json(msg="Invalid filesystem_name given,"
615 " Please provide a valid name.")
616 filesystem_resource = self\
617 .get_filesystem_obj(nas_server=nas_server_resource,
618 name=filesystem_name)
619 fs_res_id = filesystem_resource.storage_resource.id
620 elif filesystem_id is not None:
621 if filesystem_id == "" or filesystem_id.isspace():
622 self.module.fail_json(msg="Invalid filesystem_id given,"
623 " Please provide a valid ID.")
624 filesystem_resource = self\
625 .get_filesystem_obj(id=filesystem_id)
626 fs_res_id = filesystem_resource[0].storage_resource.id
627
628 # Check for error, if user tries to create a filesystem snapshot
629 # with the same name.
630 if fs_snapshot and filesystem_resource and \
631 (fs_snapshot.storage_resource.id
632 != fs_res_id):
633 self.module.fail_json(
634 msg="Snapshot %s is of %s storage resource. Cannot create new"
635 " snapshot with same name for %s storage resource."
636 % (fs_snapshot.name, fs_snapshot.storage_resource.name,
637 filesystem_resource.storage_resource.name))
638
639 # check for valid expiry_time
640 if expiry_time is not None and \
641 (expiry_time == "" or expiry_time.isspace()):
642 self.module.fail_json(msg="Please provide valid expiry_time,"
643 " empty expiry_time given.")
644 if expiry_time:
645 self.validate_expiry_time(expiry_time)
646
647 # Check if in input auto_delete is True and expiry_time is not None
648 if expiry_time and auto_delete:
649 error_msg = "Cannot set expiry_time if auto_delete given as True."
650 LOG.info(error_msg)
651 self.module.fail_json(msg=error_msg)
652
653 # check for fs_access_type
654 if fs_access_type is not None:
655 if (fs_access_type == "" or fs_access_type.isspace()):
656 self.module.fail_json(msg="Please provide valid "
657 "fs_access_type, empty "
658 "fs_access_type given.")
659 if fs_access_type == "Checkpoint":
660 fs_access_type = utils.FilesystemSnapAccessTypeEnum.CHECKPOINT
661 elif fs_access_type == "Protocol":
662 fs_access_type = utils.FilesystemSnapAccessTypeEnum.PROTOCOL
663
664 # Check whether to modify the filesystem snapshot or not
665 fs_snap_modify_dict = dict()
666 if state == 'present' and fs_snapshot:
667 fs_snap_modify_dict = self\
668 .to_update(fs_snapshot, description=description,
669 auto_del=auto_delete, expiry_time=expiry_time,
670 fs_access_type=fs_access_type)
671
672 # Create Filesystem Snapshot
673 if not fs_snapshot and state == "present":
674 LOG.info("Creating the filesystem snapshot.")
675
676 if snapshot_id:
677 self.module.fail_json(msg="Creation of Filesystem Snapshot is"
678 " allowed using snapshot_name only,"
679 " snapshot_id given.")
680 if snapshot_name == "" or snapshot_name.isspace():
681 self.module.fail_json(msg="snapshot_name is required for"
682 " creation of the filesystem"
683 " snapshot, empty snapshot_name"
684 " given.")
685 if not filesystem_resource:
686 self.module.fail_json(msg="filesystem_name or filesystem_id"
687 " required to create a snapshot.")
688
689 fs_snapshot = self.create_filesystem_snapshot(
690 snapshot_name,
691 fs_res_id,
692 description,
693 auto_delete,
694 expiry_time,
695 fs_access_type)
696 changed = True
697
698 # Update the Snapshot
699 if fs_snapshot and state == "present" and fs_snap_modify_dict:
700 LOG.info("Updating the Filesystem Snapshot.")
701 self.update_filesystem_snapshot(fs_snapshot, fs_snap_modify_dict)
702 changed = True
703
704 # Delete the Filesystem Snapshot
705 if state == "absent" and fs_snapshot:
706 fs_snapshot = self.delete_fs_snapshot(fs_snapshot)
707 changed = True
708
709 # Add filesystem snapshot details to the result.
710 if fs_snapshot:
711 fs_snapshot.update()
712 self.result["filesystem_snapshot_details"] = \
713 self.create_fs_snapshot_details_dict(fs_snapshot)
714 else:
715 self.result["filesystem_snapshot_details"] = {}
716
717 self.result["changed"] = changed
718 self.module.exit_json(**self.result)
719
720
721 def to_update_expiry_time(fs_snapshot, expiry_time=None):
722 """ Check whether to update expiry_time or not"""
723 if not expiry_time:
724 return False
725 if fs_snapshot.expiration_time is None:
726 return True
727 if convert_timestamp_to_sec(expiry_time, fs_snapshot.expiration_time)\
728 != 0:
729 return True
730 return False
731
732
733 def convert_timestamp_to_sec(expiry_time, snap_time):
734 """Converts the time difference to seconds"""
735 snap_time_str = snap_time.strftime('%m/%d/%Y %H:%M')
736 snap_timestamp = datetime.strptime(snap_time_str, '%m/%d/%Y %H:%M')
737 expiry_timestamp = datetime.strptime(expiry_time, "%m/%d/%Y %H:%M")
738 return int((expiry_timestamp - snap_timestamp).total_seconds())
739
740
741 def get_snapshot_parameters():
742 """This method provide parameter required for the ansible filesystem
743 snapshot module on Unity"""
744 return dict(
745 snapshot_name=dict(required=False, type='str'),
746 snapshot_id=dict(required=False, type='str'),
747 filesystem_name=dict(required=False, type='str'),
748 filesystem_id=dict(required=False, type='str'),
749 nas_server_name=dict(required=False, type='str'),
750 nas_server_id=dict(required=False, type='str'),
751 auto_delete=dict(required=False, type='bool'),
752 expiry_time=dict(required=False, type='str'),
753 description=dict(required=False, type='str'),
754 fs_access_type=dict(required=False, type='str',
755 choices=['Checkpoint', 'Protocol']),
756 state=dict(required=True, type='str', choices=['present', 'absent'])
757 )
758
759
760 def main():
761 """ Create Unity Filesystem Snapshot object and perform actions on it
762 based on user input from playbook"""
763 obj = FilesystemSnapshot()
764 obj.perform_module_operation()
765
766
767 if __name__ == '__main__':
768 main()