Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/filesystem.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 on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12
13 module: filesystem
14 version_added: '1.1.0'
15 short_description: Manage filesystem on Unity storage system
16 description:
17 - Managing filesystem on Unity storage system includes
18 Create new filesystem,
19 Modify snapschedule attribute of filesystem,
20 Modify filesystem attributes,
21 Display filesystem details,
22 Display filesystem snapshots,
23 Display filesystem snapschedule,
24 Delete snapschedule associated with the filesystem,
25 Delete filesystem,
26 Create new filesystem with quota configuration,
27 Enable, modify and disable replication.
28
29 extends_documentation_fragment:
30 - dellemc.unity.unity
31
32 author:
33 - Arindam Datta (@dattaarindam) <[email protected]>
34 - Meenakshi Dembi (@dembim) <[email protected]>
35 - Spandita Panigrahi (@panigs7) <[email protected]>
36
37 options:
38 filesystem_name:
39 description:
40 - The name of the filesystem. Mandatory only for the create operation.
41 All the operations are supported through I(filesystem_name).
42 - It is mutually exclusive with I(filesystem_id).
43 type: str
44 filesystem_id:
45 description:
46 - The id of the filesystem.
47 - It can be used only for get, modify, or delete operations.
48 - It is mutually exclusive with I(filesystem_name).
49 type: str
50 pool_name:
51 description:
52 - This is the name of the pool where the filesystem will be created.
53 - Either the I(pool_name) or I(pool_id) must be provided to create a new
54 filesystem.
55 type: str
56 pool_id:
57 description:
58 - This is the ID of the pool where the filesystem will be created.
59 - Either the I(pool_name) or I(pool_id) must be provided to create a new
60 filesystem.
61 type: str
62 size:
63 description:
64 - The size of the filesystem.
65 type: int
66 cap_unit:
67 description:
68 - The unit of the filesystem size. It defaults to C(GB), if not specified.
69 choices: ['GB' , 'TB']
70 type: str
71 nas_server_name:
72 description:
73 - Name of the NAS server on which filesystem will be hosted.
74 type: str
75 nas_server_id:
76 description:
77 - ID of the NAS server on which filesystem will be hosted.
78 type: str
79 supported_protocols:
80 description:
81 - Protocols supported by the file system.
82 - It will be overridden by NAS server configuration if NAS Server is C(Multiprotocol).
83 type: str
84 choices: ['NFS', 'CIFS', 'MULTIPROTOCOL']
85 description:
86 description:
87 - Description about the filesystem.
88 - Description can be removed by passing empty string ("").
89 type: str
90 smb_properties:
91 description:
92 - Advance settings for SMB. It contains optional candidate variables.
93 type: dict
94 suboptions:
95 is_smb_sync_writes_enabled:
96 description:
97 - Indicates whether the synchronous writes option is enabled on the
98 file system.
99 type: bool
100 is_smb_notify_on_access_enabled:
101 description:
102 - Indicates whether notifications of changes to directory file
103 structure are enabled.
104 type: bool
105 is_smb_op_locks_enabled:
106 description:
107 - Indicates whether opportunistic file locking is enabled on the file
108 system.
109 type: bool
110 is_smb_notify_on_write_enabled:
111 description:
112 - Indicates whether file write notifications are enabled on the file
113 system.
114 type: bool
115 smb_notify_on_change_dir_depth:
116 description:
117 - Integer variable, determines the lowest directory level to which
118 the enabled notifications apply.
119 - Minimum value is C(1).
120 type: int
121 data_reduction:
122 description:
123 - Boolean variable, specifies whether or not to enable compression.
124 Compression is supported only for thin filesystem.
125 type: bool
126 is_thin:
127 description:
128 - Boolean variable, specifies whether or not it is a thin filesystem.
129 type: bool
130 access_policy:
131 description:
132 - Access policy of a filesystem.
133 choices: ['NATIVE', 'UNIX', 'WINDOWS']
134 type: str
135 locking_policy:
136 description:
137 - File system locking policies. These policy choices control whether the
138 NFSv4 range locks must be honored.
139 type: str
140 choices: ['ADVISORY', 'MANDATORY']
141 tiering_policy:
142 description:
143 - Tiering policy choices for how the storage resource data will be
144 distributed among the tiers available in the pool.
145 choices: ['AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']
146 type: str
147 quota_config:
148 description:
149 - Configuration for quota management. It contains optional parameters.
150 type: dict
151 suboptions:
152 grace_period:
153 description:
154 - Grace period set in quota configuration after soft limit is reached.
155 - If I(grace_period) is not set during creation of filesystem,
156 it will be set to C(7 days) by default.
157 type: int
158 grace_period_unit:
159 description:
160 - Unit of grace period.
161 - Default unit is C(days).
162 type: str
163 choices: ['minutes', 'hours', 'days']
164 default_hard_limit:
165 description:
166 - Default hard limit for user quotas and tree quotas.
167 - If I(default_hard_limit) is not set while creation of filesystem,
168 it will be set to C(0B) by default.
169 type: int
170 default_soft_limit:
171 description:
172 - Default soft limit for user quotas and tree quotas.
173 - If I(default_soft_limit) is not set while creation of filesystem,
174 it will be set to C(0B) by default.
175 type: int
176 is_user_quota_enabled:
177 description:
178 - Indicates whether the user quota is enabled.
179 - If I(is_user_quota_enabled) is not set while creation of filesystem,
180 it will be set to C(false) by default.
181 - Parameters I(is_user_quota_enabled) and I(quota_policy) are
182 mutually exclusive.
183 type: bool
184 quota_policy:
185 description:
186 - Quota policy set in quota configuration.
187 - If I(quota_policy) is not set while creation of filesystem, it will
188 be set to C(FILE_SIZE) by default.
189 - Parameters I(is_user_quota_enabled) and I(quota_policy) are
190 mutually exclusive.
191 choices: ['FILE_SIZE','BLOCKS']
192 type: str
193 cap_unit:
194 description:
195 - Unit of I(default_soft_limit) and I(default_hard_limit) size.
196 - Default unit is C(GB).
197 choices: ['MB', 'GB', 'TB']
198 type: str
199 state:
200 description:
201 - State variable to determine whether filesystem will exist or not.
202 choices: ['absent', 'present']
203 required: true
204 type: str
205 snap_schedule_name:
206 description:
207 - This is the name of an existing snapshot schedule which is to be associated with the filesystem.
208 - This is mutually exclusive with I(snapshot_schedule_id).
209 type: str
210 snap_schedule_id:
211 description:
212 - This is the id of an existing snapshot schedule which is to be associated with the filesystem.
213 - This is mutually exclusive with I(snapshot_schedule_name).
214 type: str
215 replication_params:
216 description:
217 - Settings required for enabling or modifying replication.
218 type: dict
219 suboptions:
220 replication_name:
221 description:
222 - Name of the replication session.
223 type: str
224 new_replication_name:
225 description:
226 - Replication name to rename the session to.
227 type: str
228 replication_mode:
229 description:
230 - The replication mode.
231 - This is a mandatory field while creating a replication session.
232 type: str
233 choices: ['synchronous', 'asynchronous', 'manual']
234 rpo:
235 description:
236 - Maximum time to wait before the system syncs the source and destination LUNs.
237 - The I(rpo) option should be specified if the I(replication_mode) is C(asynchronous).
238 - The value should be in range of C(5) to C(1440) for C(asynchronous),
239 C(0) for C(synchronous) and C(-1) for C(manual).
240 type: int
241 replication_type:
242 description:
243 - Type of replication.
244 choices: ['local', 'remote']
245 type: str
246 remote_system:
247 description:
248 - Details of remote system to which the replication is being configured.
249 - The I(remote_system) option should be specified if the I(replication_type) is C(remote).
250 type: dict
251 suboptions:
252 remote_system_host:
253 required: true
254 description:
255 - IP or FQDN for remote Unity unisphere Host.
256 type: str
257 remote_system_username:
258 type: str
259 required: true
260 description:
261 - User name of remote Unity unisphere Host.
262 remote_system_password:
263 type: str
264 required: true
265 description:
266 - Password of remote Unity unisphere Host.
267 remote_system_verifycert:
268 type: bool
269 default: true
270 description:
271 - Boolean variable to specify whether or not to validate SSL
272 certificate of remote Unity unisphere Host.
273 - C(true) - Indicates that the SSL certificate should be verified.
274 - C(false) - Indicates that the SSL certificate should not be
275 verified.
276 remote_system_port:
277 description:
278 - Port at which remote Unity unisphere is hosted.
279 type: int
280 default: 443
281 destination_pool_id:
282 type: str
283 description:
284 - ID of pool to allocate destination filesystem.
285 destination_pool_name:
286 type: str
287 description:
288 - Name of pool to allocate destination filesystem.
289 replication_state:
290 description:
291 - State of the replication.
292 choices: ['enable', 'disable']
293 type: str
294
295 notes:
296 - SMB shares, NFS exports, and snapshots associated with filesystem need
297 to be deleted prior to deleting a filesystem.
298 - The I(quota_config) parameter can be used to update default hard limit
299 and soft limit values to limit the maximum space that can be used.
300 By default they both are set to 0 during filesystem
301 creation which means unlimited.
302 - The I(check_mode) is not supported.
303 """
304
305 EXAMPLES = r"""
306 - name: Create FileSystem
307 filesystem:
308 unispherehost: "{{unispherehost}}"
309 username: "{{username}}"
310 password: "{{password}}"
311 validate_certs: "{{validate_certs}}"
312 filesystem_name: "ansible_test_fs"
313 nas_server_name: "lglap761"
314 pool_name: "pool_1"
315 size: 5
316 state: "present"
317
318 - name: Create FileSystem with quota configuration
319 filesystem:
320 unispherehost: "{{unispherehost}}"
321 username: "{{username}}"
322 password: "{{password}}"
323 validate_certs: "{{validate_certs}}"
324 filesystem_name: "ansible_test_fs"
325 nas_server_name: "lglap761"
326 pool_name: "pool_1"
327 size: 5
328 quota_config:
329 grace_period: 8
330 grace_period_unit: "days"
331 default_soft_limit: 10
332 is_user_quota_enabled: false
333 state: "present"
334
335 - name: Expand FileSystem size
336 filesystem:
337 unispherehost: "{{unispherehost}}"
338 username: "{{username}}"
339 password: "{{password}}"
340 validate_certs: "{{validate_certs}}"
341 filesystem_name: "ansible_test_fs"
342 nas_server_name: "lglap761"
343 size: 10
344 state: "present"
345
346 - name: Expand FileSystem size
347 filesystem:
348 unispherehost: "{{unispherehost}}"
349 username: "{{username}}"
350 password: "{{password}}"
351 validate_certs: "{{validate_certs}}"
352 filesystem_name: "ansible_test_fs"
353 nas_server_name: "lglap761"
354 size: 10
355 state: "present"
356
357 - name: Modify FileSystem smb_properties
358 filesystem:
359 unispherehost: "{{unispherehost}}"
360 username: "{{username}}"
361 password: "{{password}}"
362 validate_certs: "{{validate_certs}}"
363 filesystem_name: "ansible_test_fs"
364 nas_server_name: "lglap761"
365 smb_properties:
366 is_smb_op_locks_enabled: true
367 smb_notify_on_change_dir_depth: 5
368 is_smb_notify_on_access_enabled: true
369 state: "present"
370
371 - name: Modify FileSystem Snap Schedule
372 filesystem:
373 unispherehost: "{{unispherehost}}"
374 username: "{{username}}"
375 password: "{{password}}"
376 validate_certs: "{{validate_certs}}"
377 filesystem_id: "fs_141"
378 snap_schedule_id: "{{snap_schedule_id}}"
379 state: "{{state_present}}"
380
381 - name: Get details of FileSystem using id
382 filesystem:
383 unispherehost: "{{unispherehost}}"
384 username: "{{username}}"
385 password: "{{password}}"
386 validate_certs: "{{validate_certs}}"
387 filesystem_id: "rs_405"
388 state: "present"
389
390 - name: Delete a FileSystem using id
391 filesystem:
392 unispherehost: "{{unispherehost}}"
393 username: "{{username}}"
394 password: "{{password}}"
395 validate_certs: "{{validate_certs}}"
396 filesystem_id: "rs_405"
397 state: "absent"
398
399 - name: Enable replication on the fs
400 filesystem:
401 unispherehost: "{{unispherehost}}"
402 username: "{{username}}"
403 password: "{{password}}"
404 validate_certs: "{{validate_certs}}"
405 filesystem_id: "rs_405"
406 replication_params:
407 replication_name: "test_repl"
408 replication_type: "remote"
409 replication_mode: "asynchronous"
410 rpo: 60
411 remote_system:
412 remote_system_host: '0.1.2.3'
413 remote_system_verifycert: false
414 remote_system_username: 'username'
415 remote_system_password: 'password'
416 destination_pool_name: "pool_test_1"
417 replication_state: "enable"
418 state: "present"
419
420 - name: Modify replication on the fs
421 filesystem:
422 unispherehost: "{{unispherehost}}"
423 username: "{{username}}"
424 password: "{{password}}"
425 validate_certs: "{{validate_certs}}"
426 filesystem_id: "rs_405"
427 replication_params:
428 replication_name: "test_repl"
429 new_replication_name: "test_repl_updated"
430 replication_mode: "asynchronous"
431 rpo: 50
432 replication_state: "enable"
433 state: "present"
434
435 - name: Disable replication on the fs
436 filesystem:
437 unispherehost: "{{unispherehost}}"
438 username: "{{username}}"
439 password: "{{password}}"
440 validate_certs: "{{validate_certs}}"
441 filesystem_id: "rs_405"
442 replication_state: "disable"
443 state: "present"
444
445 - name: Disable replication by specifying replication_name on the fs
446 filesystem:
447 unispherehost: "{{unispherehost}}"
448 username: "{{username}}"
449 password: "{{password}}"
450 validate_certs: "{{validate_certs}}"
451 filesystem_id: "rs_405"
452 replication_params:
453 replication_name: "test_replication"
454 replication_state: "disable"
455 state: "present"
456 """
457
458 RETURN = r'''
459 changed:
460 description: Whether or not the resource has changed.
461 returned: always
462 type: bool
463 sample: true
464
465 filesystem_details:
466 description: Details of the filesystem.
467 returned: When filesystem exists
468 type: dict
469 contains:
470 id:
471 description: The system generated ID given to the filesystem.
472 type: str
473 name:
474 description: Name of the filesystem.
475 type: str
476 description:
477 description: Description about the filesystem.
478 type: str
479 is_data_reduction_enabled:
480 description: Whether or not compression enabled on this
481 filesystem.
482 type: bool
483 size_total_with_unit:
484 description: Size of the filesystem with actual unit.
485 type: str
486 tiering_policy:
487 description: Tiering policy applied to this filesystem.
488 type: str
489 is_cifs_notify_on_access_enabled:
490 description: Indicates whether the system generates a
491 notification when a user accesses the file system.
492 type: bool
493 is_cifs_notify_on_write_enabled:
494 description: Indicates whether the system generates a notification
495 when the file system is written to.
496 type: bool
497 is_cifs_op_locks_enabled:
498 description: Indicates whether opportunistic file locks are enabled
499 for the file system.
500 type: bool
501 is_cifs_sync_writes_enabled:
502 description: Indicates whether the CIFS synchronous writes option
503 is enabled for the file system.
504 type: bool
505 cifs_notify_on_change_dir_depth:
506 description: Indicates the lowest directory level to which the
507 enabled notifications apply, if any.
508 type: int
509 pool:
510 description: The pool in which this filesystem is allocated.
511 type: dict
512 contains:
513 id:
514 description: The system ID given to the pool.
515 type: str
516 name:
517 description: The name of the storage pool.
518 type: str
519 nas_server:
520 description: The NAS Server details on which this filesystem is hosted.
521 type: dict
522 contains:
523 id:
524 description: The system ID given to the NAS Server.
525 type: str
526 name:
527 description: The name of the NAS Server.
528 type: str
529 snapshots:
530 description: The list of snapshots of this filesystem.
531 type: list
532 contains:
533 id:
534 description: The system ID given to the filesystem
535 snapshot.
536 type: str
537 name:
538 description: The name of the filesystem snapshot.
539 type: str
540 is_thin_enabled:
541 description: Indicates whether thin provisioning is enabled for
542 this filesystem.
543 type: bool
544 snap_schedule_id:
545 description: Indicates the id of the snap schedule associated
546 with the filesystem.
547 type: str
548 snap_schedule_name:
549 description: Indicates the name of the snap schedule associated
550 with the filesystem.
551 type: str
552 quota_config:
553 description: Details of quota configuration of the filesystem
554 created.
555 type: dict
556 contains:
557 grace_period:
558 description: Grace period set in quota configuration
559 after soft limit is reached.
560 type: str
561 default_hard_limit:
562 description: Default hard limit for user quotas
563 and tree quotas.
564 type: int
565 default_soft_limit:
566 description: Default soft limit for user quotas
567 and tree quotas.
568 type: int
569 is_user_quota_enabled:
570 description: Indicates whether the user quota is enabled.
571 type: bool
572 quota_policy:
573 description: Quota policy set in quota configuration.
574 type: str
575 replication_sessions:
576 description: List of replication sessions if replication is enabled.
577 type: dict
578 contains:
579 id:
580 description: ID of replication session
581 type: str
582 name:
583 description: Name of replication session
584 type: str
585 remote_system:
586 description: Remote system
587 type: dict
588 contains:
589 id:
590 description: ID of remote system
591 type: str
592 sample: {
593 "access_policy": "AccessPolicyEnum.UNIX",
594 "cifs_notify_on_change_dir_depth": 512,
595 "cifs_share": null,
596 "data_reduction_percent": 0,
597 "data_reduction_ratio": 1.0,
598 "data_reduction_size_saved": 0,
599 "description": "",
600 "existed": true,
601 "folder_rename_policy": "FSRenamePolicyEnum.SMB_RENAME_FORBIDDEN",
602 "format": "FSFormatEnum.UFS64",
603 "hash": 8735427610152,
604 "health": {
605 "UnityHealth": {
606 "hash": 8735427614928
607 }
608 },
609 "host_io_size": "HostIOSizeEnum.GENERAL_8K",
610 "id": "fs_65916",
611 "is_advanced_dedup_enabled": false,
612 "is_cifs_notify_on_access_enabled": false,
613 "is_cifs_notify_on_write_enabled": false,
614 "is_cifs_op_locks_enabled": false,
615 "is_cifs_sync_writes_enabled": false,
616 "is_data_reduction_enabled": false,
617 "is_read_only": false,
618 "is_smbca": false,
619 "is_thin_enabled": true,
620 "locking_policy": "FSLockingPolicyEnum.MANDATORY",
621 "metadata_size": 11274289152,
622 "metadata_size_allocated": 4294967296,
623 "min_size_allocated": 0,
624 "name": "test_fs",
625 "nas_server": {
626 "id": "nas_18",
627 "name": "test_nas1"
628 },
629 "nfs_share": null,
630 "per_tier_size_used": [
631 6979321856,
632 0,
633 0
634 ],
635 "pool": {
636 "id": "pool_7",
637 "name": "pool 7"
638 },
639 "pool_full_policy": "ResourcePoolFullPolicyEnum.FAIL_WRITES",
640 "quota_config": {
641 "default_hard_limit": "0B",
642 "default_soft_limit": "0B",
643 "grace_period": "7.0 days",
644 "id": "quotaconfig_171798760421_0",
645 "is_user_quota_enabled": false,
646 "quota_policy": "QuotaPolicyEnum.FILE_SIZE"
647 },
648 "replication_sessions": {
649 "current_transfer_est_remain_time": 0,
650 "id": "***",
651 "last_sync_time": "2022-05-12 11:20:38+00:00",
652 "local_role": "ReplicationSessionReplicationRoleEnum.SOURCE",
653 "max_time_out_of_sync": 60,
654 "members": null,
655 "name": "local_repl_new",
656 "network_status": "ReplicationSessionNetworkStatusEnum.OK",
657 "remote_system": {
658 "UnityRemoteSystem": {
659 "hash": 8735426929707
660 }
661 },
662 "replication_resource_type": "ReplicationEndpointResourceTypeEnum.FILESYSTEM",
663 "src_resource_id": "res_66444",
664 "src_status": "ReplicationSessionStatusEnum.OK",
665 "status": "ReplicationOpStatusEnum.AUTO_SYNC_CONFIGURED",
666 "sync_progress": 0,
667 "sync_state": "ReplicationSessionSyncStateEnum.IDLE"
668 },
669 "size_allocated": 283148288,
670 "size_allocated_total": 4578148352,
671 "size_preallocated": 2401173504,
672 "size_total": 10737418240,
673 "size_total_with_unit": "10.0 GB",
674 "size_used": 1620312064,
675 "snap_count": 2,
676 "snaps_size": 21474869248,
677 "snaps_size_allocated": 32768,
678 "snapshots": [],
679 "supported_protocols": "FSSupportedProtocolEnum.NFS",
680 "tiering_policy": "TieringPolicyEnum.AUTOTIER_HIGH",
681 "type": "FilesystemTypeEnum.FILESYSTEM"
682 }
683 '''
684
685 from ansible.module_utils.basic import AnsibleModule
686 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
687 import utils
688
689 LOG = utils.get_logger('filesystem')
690
691 application_type = "Ansible/1.7.1"
692
693
694 class Filesystem(object):
695 """Class with FileSystem operations"""
696
697 def __init__(self):
698 """Define all parameters required by this module"""
699 self.module_params = utils.get_unity_management_host_parameters()
700 self.module_params.update(get_filesystem_parameters())
701
702 mutually_exclusive = [['filesystem_name', 'filesystem_id'],
703 ['pool_name', 'pool_id'],
704 ['nas_server_name', 'nas_server_id'],
705 ['snap_schedule_name', 'snap_schedule_id']]
706
707 required_one_of = [['filesystem_name', 'filesystem_id']]
708
709 # initialize the Ansible module
710 self.module = AnsibleModule(
711 argument_spec=self.module_params,
712 supports_check_mode=False,
713 mutually_exclusive=mutually_exclusive,
714 required_one_of=required_one_of)
715 utils.ensure_required_libs(self.module)
716
717 self.unity_conn = utils.get_unity_unisphere_connection(
718 self.module.params, application_type)
719
720 def get_filesystem(self, name=None, id=None, obj_nas_server=None):
721 """Get the details of a FileSystem.
722 :param filesystem_name: The name of the filesystem
723 :param filesystem_id: The id of the filesystem
724 :param obj_nas_server: NAS Server object instance
725 :return: instance of the respective filesystem if exist.
726 """
727
728 id_or_name = id if id else name
729 errormsg = "Failed to get the filesystem {0} with error {1}"
730
731 try:
732 obj_fs = None
733 if id:
734 if obj_nas_server:
735 obj_fs = self.unity_conn.get_filesystem(
736 _id=id,
737 nas_server=obj_nas_server)
738 else:
739 obj_fs = self.unity_conn.get_filesystem(_id=id)
740
741 if obj_fs and obj_fs.existed:
742 LOG.info("Successfully got the filesystem "
743 "object %s ", obj_fs)
744 return obj_fs
745 elif name:
746 if not obj_nas_server:
747 err_msg = "NAS Server is required to get the FileSystem"
748 LOG.error(err_msg)
749 self.module.fail_json(msg=err_msg)
750
751 obj_fs = self.unity_conn.get_filesystem(
752 name=name,
753 nas_server=obj_nas_server)
754 if obj_fs:
755 LOG.info(
756 "Successfully got the filesystem object %s ", obj_fs)
757 return obj_fs
758 else:
759 LOG.info("Failed to get the filesystem %s", id_or_name)
760 return None
761
762 except utils.HttpError as e:
763 if e.http_status == 401:
764 cred_err = "Incorrect username or password , {0}".format(
765 e.message)
766 msg = errormsg.format(id_or_name, cred_err)
767 self.module.fail_json(msg=msg)
768 else:
769 msg = errormsg.format(id_or_name, str(e))
770 self.module.fail_json(msg=msg)
771
772 except utils.UnityResourceNotFoundError as e:
773 msg = errormsg.format(id_or_name, str(e))
774 LOG.error(msg)
775 return None
776
777 except Exception as e:
778 msg = errormsg.format(id_or_name, str(e))
779 LOG.error(msg)
780 self.module.fail_json(msg=msg)
781
782 def get_nas_server(self, name=None, id=None):
783 """Get the instance of a NAS Server.
784 :param name: The NAS Server name
785 :param id: The NAS Server id
786 :return: instance of the respective NAS Server if exists.
787 """
788
789 errormsg = "Failed to get the NAS Server {0} with error {1}"
790 id_or_name = name if name else id
791
792 try:
793 obj_nas = self.unity_conn.get_nas_server(_id=id, name=name)
794 if id and obj_nas.existed:
795 LOG.info("Successfully got the nas server object %s",
796 obj_nas)
797 return obj_nas
798 elif name:
799 LOG.info("Successfully got the nas server object %s ",
800 obj_nas)
801 return obj_nas
802 else:
803 msg = "Failed to get the nas server with {0}".format(
804 id_or_name)
805 LOG.error(msg)
806 self.module.fail_json(msg=msg)
807
808 except Exception as e:
809 msg = errormsg.format(name, str(e))
810 LOG.error(msg)
811 self.module.fail_json(msg=msg)
812
813 def get_pool(self, pool_name=None, pool_id=None):
814 """Get the instance of a pool.
815 :param pool_name: The name of the pool
816 :param pool_id: The id of the pool
817 :return: Dict containing pool details if exists
818 """
819
820 id_or_name = pool_id if pool_id else pool_name
821 errormsg = "Failed to get the pool {0} with error {1}"
822
823 try:
824 obj_pool = self.unity_conn.get_pool(name=pool_name, _id=pool_id)
825
826 if pool_id and obj_pool.existed:
827 LOG.info("Successfully got the pool object %s",
828 obj_pool)
829 return obj_pool
830 if pool_name:
831 LOG.info("Successfully got pool %s", obj_pool)
832 return obj_pool
833 else:
834 msg = "Failed to get the pool with {0}".format(
835 id_or_name)
836 LOG.error(msg)
837 self.module.fail_json(msg=msg)
838
839 except Exception as e:
840 msg = errormsg.format(id_or_name, str(e))
841 LOG.error(msg)
842 self.module.fail_json(msg=msg)
843
844 def get_tiering_policy_enum(self, tiering_policy):
845 """Get the tiering_policy enum.
846 :param tiering_policy: The tiering_policy string
847 :return: tiering_policy enum
848 """
849
850 if tiering_policy in utils.TieringPolicyEnum.__members__:
851 return utils.TieringPolicyEnum[tiering_policy]
852 else:
853 errormsg = "Invalid choice {0} for tiering policy".format(
854 tiering_policy)
855 LOG.error(errormsg)
856 self.module.fail_json(msg=errormsg)
857
858 def get_supported_protocol_enum(self, supported_protocol):
859 """Get the supported_protocol enum.
860 :param supported_protocol: The supported_protocol string
861 :return: supported_protocol enum
862 """
863
864 supported_protocol = "MULTI_PROTOCOL" if \
865 supported_protocol == "MULTIPROTOCOL" else supported_protocol
866 if supported_protocol in utils.FSSupportedProtocolEnum.__members__:
867 return utils.FSSupportedProtocolEnum[supported_protocol]
868 else:
869 errormsg = "Invalid choice {0} for supported_protocol".format(
870 supported_protocol)
871 LOG.error(errormsg)
872 self.module.fail_json(msg=errormsg)
873
874 def get_locking_policy_enum(self, locking_policy):
875 """Get the locking_policy enum.
876 :param locking_policy: The locking_policy string
877 :return: locking_policy enum
878 """
879 if locking_policy in utils.FSLockingPolicyEnum.__members__:
880 return utils.FSLockingPolicyEnum[locking_policy]
881 else:
882 errormsg = "Invalid choice {0} for locking_policy".format(
883 locking_policy)
884 LOG.error(errormsg)
885 self.module.fail_json(msg=errormsg)
886
887 def get_access_policy_enum(self, access_policy):
888 """Get the access_policy enum.
889 :param access_policy: The access_policy string
890 :return: access_policy enum
891 """
892 if access_policy in utils.AccessPolicyEnum.__members__:
893 return utils.AccessPolicyEnum[access_policy]
894 else:
895 errormsg = "Invalid choice {0} for access_policy".format(
896 access_policy)
897 LOG.error(errormsg)
898 self.module.fail_json(msg=errormsg)
899
900 def create_filesystem(self, name, obj_pool, obj_nas_server, size):
901 """Create a FileSystem.
902 :param name: Name of the FileSystem
903 :param obj_pool: Storage Pool obj instance
904 :param obj_nas_server: NAS Server obj instance
905 :param size: Total size of a filesystem in bytes
906 :return: FileSystem object on successful creation
907 """
908 try:
909
910 supported_protocol = self.module.params['supported_protocols']
911 supported_protocol = self.get_supported_protocol_enum(
912 supported_protocol) if supported_protocol else None
913 is_thin = self.module.params['is_thin']
914
915 tiering_policy = self.module.params['tiering_policy']
916 tiering_policy = self.get_tiering_policy_enum(tiering_policy) \
917 if tiering_policy else None
918
919 obj_fs = utils.UnityFileSystem.create(
920 self.unity_conn._cli,
921 pool=obj_pool,
922 nas_server=obj_nas_server,
923 name=name,
924 size=size,
925 proto=supported_protocol,
926 is_thin=is_thin,
927 tiering_policy=tiering_policy)
928
929 LOG.info("Successfully created file system , %s", obj_fs)
930 return obj_fs
931
932 except Exception as e:
933 errormsg = "Create filesystem {0} operation failed" \
934 " with error {1}".format(name, str(e))
935 LOG.error(errormsg)
936 self.module.fail_json(msg=errormsg)
937
938 def delete_filesystem(self, id):
939 """Delete a FileSystem.
940 :param id: The object instance of the filesystem to be deleted
941 """
942
943 try:
944 obj_fs = self.get_filesystem(id=id)
945 obj_fs_dict = obj_fs._get_properties()
946 if obj_fs_dict['cifs_share'] is not None:
947 errormsg = "The Filesystem has SMB Shares. Hence deleting " \
948 "this filesystem is not safe."
949 LOG.error(errormsg)
950 self.module.fail_json(msg=errormsg)
951 if obj_fs_dict['nfs_share'] is not None:
952 errormsg = "The FileSystem has NFS Exports. Hence deleting " \
953 "this filesystem is not safe."
954 LOG.error(errormsg)
955 self.module.fail_json(msg=errormsg)
956 obj_fs.delete()
957 return True
958
959 except Exception as e:
960 errormsg = "Delete operation of FileSystem id:{0} " \
961 "failed with error {1}".format(id,
962 str(e))
963 LOG.error(errormsg)
964 self.module.fail_json(msg=errormsg)
965
966 def is_modify_required(self, obj_fs, cap_unit):
967 """Checks if any modify required for filesystem attributes
968 :param obj_fs: filesystem instance
969 :param cap_unit: capacity unit
970 :return: filesystem to update dict
971 """
972 try:
973 to_update = {}
974 obj_fs = obj_fs.update()
975 description = self.module.params['description']
976
977 if description is not None and description != obj_fs.description:
978 to_update.update({'description': description})
979
980 size = self.module.params['size']
981 if size and cap_unit:
982 size_byte = int(utils.get_size_bytes(size, cap_unit))
983 if size_byte < obj_fs.size_total:
984 self.module.fail_json(msg="Filesystem size can be "
985 "expanded only")
986 elif size_byte > obj_fs.size_total:
987 to_update.update({'size': size_byte})
988
989 tiering_policy = self.module.params['tiering_policy']
990 if tiering_policy and self.get_tiering_policy_enum(
991 tiering_policy) != obj_fs.tiering_policy:
992 to_update.update({'tiering_policy':
993 self.get_tiering_policy_enum(
994 tiering_policy)})
995
996 is_thin = self.module.params['is_thin']
997 if is_thin is not None and is_thin != obj_fs.is_thin_enabled:
998 to_update.update({'is_thin': is_thin})
999
1000 data_reduction = self.module.params['data_reduction']
1001 if data_reduction is not None and \
1002 data_reduction != obj_fs.is_data_reduction_enabled:
1003 to_update.update({'is_compression': data_reduction})
1004
1005 access_policy = self.module.params['access_policy']
1006 if access_policy and self.get_access_policy_enum(
1007 access_policy) != obj_fs.access_policy:
1008 to_update.update({'access_policy':
1009 self.get_access_policy_enum(access_policy)})
1010
1011 locking_policy = self.module.params['locking_policy']
1012 if locking_policy and self.get_locking_policy_enum(
1013 locking_policy) != obj_fs.locking_policy:
1014 to_update.update({'locking_policy':
1015 self.get_locking_policy_enum(
1016 locking_policy)})
1017
1018 snap_sch = obj_fs.storage_resource.snap_schedule
1019
1020 if self.snap_sch_id is not None:
1021 if self.snap_sch_id == "":
1022 if snap_sch and snap_sch.id != self.snap_sch_id:
1023 to_update.update({'is_snap_schedule_paused': False})
1024 elif snap_sch is None or snap_sch.id != self.snap_sch_id:
1025 to_update.update({'snap_sch_id': self.snap_sch_id})
1026
1027 smb_properties = self.module.params['smb_properties']
1028 if smb_properties:
1029 sync_writes_enabled = \
1030 smb_properties['is_smb_sync_writes_enabled']
1031 oplocks_enabled = \
1032 smb_properties['is_smb_op_locks_enabled']
1033 notify_on_write = \
1034 smb_properties['is_smb_notify_on_write_enabled']
1035 notify_on_access = \
1036 smb_properties['is_smb_notify_on_access_enabled']
1037 notify_on_change_dir_depth = \
1038 smb_properties['smb_notify_on_change_dir_depth']
1039
1040 if sync_writes_enabled is not None and \
1041 sync_writes_enabled != obj_fs.is_cifs_sync_writes_enabled:
1042 to_update.update(
1043 {'is_cifs_sync_writes_enabled': sync_writes_enabled})
1044
1045 if oplocks_enabled is not None and \
1046 oplocks_enabled != obj_fs.is_cifs_op_locks_enabled:
1047 to_update.update(
1048 {'is_cifs_op_locks_enabled': oplocks_enabled})
1049
1050 if notify_on_write is not None and \
1051 notify_on_write != \
1052 obj_fs.is_cifs_notify_on_write_enabled:
1053 to_update.update(
1054 {'is_cifs_notify_on_write_enabled': notify_on_write})
1055
1056 if notify_on_access is not None and \
1057 notify_on_access != \
1058 obj_fs.is_cifs_notify_on_access_enabled:
1059 to_update.update(
1060 {'is_cifs_notify_on_access_enabled':
1061 notify_on_access})
1062
1063 if notify_on_change_dir_depth is not None and \
1064 notify_on_change_dir_depth != \
1065 obj_fs.cifs_notify_on_change_dir_depth:
1066 to_update.update(
1067 {'cifs_notify_on_change_dir_depth':
1068 notify_on_change_dir_depth})
1069 if len(to_update) > 0:
1070 return to_update
1071 else:
1072 return None
1073
1074 except Exception as e:
1075 errormsg = "Failed to determine if FileSystem id: {0}" \
1076 " modification required with error {1}".format(obj_fs.id,
1077 str(e))
1078 LOG.error(errormsg)
1079 self.module.fail_json(msg=errormsg)
1080
1081 def modify_filesystem(self, update_dict, obj_fs):
1082 """ modifes attributes for a filesystem instance
1083 :param update_dict: modify dict
1084 :return: True on Success
1085 """
1086 try:
1087 adv_smb_params = [
1088 'is_cifs_sync_writes_enabled',
1089 'is_cifs_op_locks_enabled',
1090 'is_cifs_notify_on_write_enabled',
1091 'is_cifs_notify_on_access_enabled',
1092 'cifs_notify_on_change_dir_depth']
1093
1094 cifs_fs_payload = {}
1095 fs_update_payload = {}
1096
1097 for smb_param in adv_smb_params:
1098 if smb_param in update_dict.keys():
1099 cifs_fs_payload.update({smb_param: update_dict[smb_param]})
1100
1101 LOG.debug("CIFS Modify Payload: %s", cifs_fs_payload)
1102
1103 cifs_fs_parameters = obj_fs.prepare_cifs_fs_parameters(
1104 **cifs_fs_payload)
1105
1106 fs_update_params = [
1107 'size',
1108 'is_thin',
1109 'tiering_policy',
1110 'is_compression',
1111 'access_policy',
1112 'locking_policy',
1113 'description',
1114 'cifs_fs_parameters']
1115
1116 for fs_param in fs_update_params:
1117 if fs_param in update_dict.keys():
1118 fs_update_payload.update({fs_param: update_dict[fs_param]})
1119
1120 if cifs_fs_parameters:
1121 fs_update_payload.update(
1122 {'cifs_fs_parameters': cifs_fs_parameters})
1123
1124 if "snap_sch_id" in update_dict.keys():
1125 fs_update_payload.update(
1126 {'snap_schedule_parameters': {'snapSchedule':
1127 {'id': update_dict.get('snap_sch_id')}
1128 }}
1129 )
1130 elif "is_snap_schedule_paused" in update_dict.keys():
1131 fs_update_payload.update(
1132 {'snap_schedule_parameters': {'isSnapSchedulePaused': False}
1133 })
1134
1135 obj_fs = obj_fs.update()
1136 resp = obj_fs.modify(**fs_update_payload)
1137 LOG.info("Successfully modified the FS with response %s", resp)
1138
1139 except Exception as e:
1140 errormsg = "Failed to modify FileSystem instance id: {0}" \
1141 " with error {1}".format(obj_fs.id, str(e))
1142 LOG.error(errormsg)
1143 self.module.fail_json(msg=errormsg)
1144
1145 def get_filesystem_display_attributes(self, obj_fs):
1146 """get display filesystem attributes
1147 :param obj_fs: filesystem instance
1148 :return: filesystem dict to display
1149 """
1150 try:
1151 obj_fs = obj_fs.update()
1152 filesystem_details = obj_fs._get_properties()
1153 filesystem_details['size_total_with_unit'] = utils. \
1154 convert_size_with_unit(int(filesystem_details['size_total']))
1155 if obj_fs.pool:
1156 filesystem_details.update(
1157 {'pool': {'name': obj_fs.pool.name,
1158 'id': obj_fs.pool.id}})
1159 if obj_fs.nas_server:
1160 filesystem_details.update(
1161 {'nas_server': {'name': obj_fs.nas_server.name,
1162 'id': obj_fs.nas_server.id}})
1163 snap_list = []
1164 if obj_fs.has_snap():
1165 for snap in obj_fs.snapshots:
1166 d = {'name': snap.name, 'id': snap.id}
1167 snap_list.append(d)
1168 filesystem_details['snapshots'] = snap_list
1169
1170 if obj_fs.storage_resource.snap_schedule:
1171 filesystem_details['snap_schedule_id'] = obj_fs.storage_resource.snap_schedule.id
1172 filesystem_details['snap_schedule_name'] = obj_fs.storage_resource.snap_schedule.name
1173
1174 quota_config_obj = self.get_quota_config_details(obj_fs)
1175
1176 if quota_config_obj:
1177
1178 hard_limit = utils.convert_size_with_unit(
1179 quota_config_obj.default_hard_limit)
1180 soft_limit = utils.convert_size_with_unit(
1181 quota_config_obj.default_soft_limit)
1182 grace_period = get_time_with_unit(
1183 quota_config_obj.grace_period)
1184
1185 filesystem_details.update({'quota_config':
1186 {'id': quota_config_obj.id,
1187 'default_hard_limit': hard_limit,
1188 'default_soft_limit': soft_limit,
1189 'is_user_quota_enabled':
1190 quota_config_obj.is_user_quota_enabled,
1191 'quota_policy': quota_config_obj._get_properties()[
1192 'quota_policy'],
1193 'grace_period': grace_period}
1194 })
1195 filesystem_details['replication_sessions'] = []
1196 fs_repl_sessions = self.get_replication_session(obj_fs)
1197 if fs_repl_sessions:
1198 filesystem_details['replication_sessions'] = \
1199 fs_repl_sessions._get_properties()
1200 return filesystem_details
1201
1202 except Exception as e:
1203 errormsg = "Failed to display the filesystem {0} with " \
1204 "error {1}".format(obj_fs.name, str(e))
1205 LOG.error(errormsg)
1206 self.module.fail_json(msg=errormsg)
1207
1208 def validate_input_string(self):
1209 """ validates the input string checks if it is empty string """
1210 invalid_string = ""
1211 try:
1212 for key in self.module.params:
1213 val = self.module.params[key]
1214 if key == "description" or key == "snap_schedule_name" \
1215 or key == "snap_schedule_id":
1216 continue
1217 if isinstance(val, str) \
1218 and val == invalid_string:
1219 errmsg = 'Invalid input parameter "" for {0}'.format(
1220 key)
1221 self.module.fail_json(msg=errmsg)
1222 if self.module.params['replication_params'] and self.module.params['replication_state'] is None:
1223 self.module.fail_json(msg="Please specify replication_state along with replication_params")
1224 except Exception as e:
1225 errormsg = "Failed to validate the module param with " \
1226 "error {0}".format(str(e))
1227 LOG.error(errormsg)
1228 self.module.fail_json(msg=errormsg)
1229
1230 def resolve_to_snapschedule_id(self, params):
1231 """ Get snapshot id for a give snap schedule name
1232 :param params: snap schedule name or id
1233 :return: snap schedule id after validation
1234 """
1235
1236 try:
1237 snap_sch_id = None
1238 snapshot_schedule = {}
1239 if params["name"]:
1240 snapshot_schedule = utils.UnitySnapScheduleList.get(self.unity_conn._cli, name=params["name"])
1241 elif params["id"]:
1242 snapshot_schedule = utils.UnitySnapScheduleList.get(self.unity_conn._cli, id=params["id"])
1243
1244 if snapshot_schedule:
1245 snap_sch_id = snapshot_schedule.id[0]
1246
1247 if not snap_sch_id:
1248 errormsg = "Failed to find the snapshot schedule id against given name " \
1249 "or id: {0}".format(params["name"]), (params["id"])
1250 LOG.error(errormsg)
1251 self.module.fail_json(msg=errormsg)
1252
1253 return snap_sch_id
1254
1255 except Exception as e:
1256 errormsg = "Failed to find the snapshot schedules with " \
1257 "error {0}".format(str(e))
1258
1259 def get_quota_config_details(self, obj_fs):
1260 """
1261 Get the quota config ID mapped to the filesystem
1262 :param obj_fs: Filesystem instance
1263 :return: Quota config object if exists else None
1264 """
1265 try:
1266 all_quota_config = self.unity_conn.get_quota_config(filesystem=obj_fs)
1267 fs_id = obj_fs.id
1268
1269 if len(all_quota_config) == 0:
1270 LOG.error("The quota_config object for new filesystem "
1271 "is not updated yet.")
1272 return None
1273
1274 for quota_config in range(len(all_quota_config)):
1275 if fs_id and all_quota_config[quota_config].filesystem.id == fs_id and \
1276 not all_quota_config[quota_config].tree_quota:
1277 msg = "Quota config id for filesystem %s is %s" \
1278 % (fs_id, all_quota_config[quota_config].id)
1279 LOG.info(msg)
1280 return all_quota_config[quota_config]
1281
1282 except Exception as e:
1283 errormsg = "Failed to fetch quota config for filesystem {0} " \
1284 " with error {1}".format(fs_id, str(e))
1285 LOG.error(errormsg)
1286 self.module.fail_json(msg=errormsg)
1287
1288 def modify_quota_config(self, quota_config_obj, quota_config_params):
1289 """
1290 Modify default quota config settings of newly created filesystem.
1291 The default setting of quota config after filesystem creation is:
1292 default_soft_limit and default_hard_limit are 0,
1293 is_user_quota_enabled is false,
1294 grace_period is 7 days and,
1295 quota_policy is FILE_SIZE.
1296 :param quota_config_obj: Quota config instance
1297 :param quota_config_params: Quota config parameters to be modified
1298 :return: Boolean whether quota config is modified
1299 """
1300
1301 if quota_config_params:
1302 soft_limit = quota_config_params['default_soft_limit']
1303 hard_limit = quota_config_params['default_hard_limit']
1304 is_user_quota_enabled = quota_config_params['is_user_quota_enabled']
1305 quota_policy = quota_config_params['quota_policy']
1306 grace_period = quota_config_params['grace_period']
1307 cap_unit = quota_config_params['cap_unit']
1308 gp_unit = quota_config_params['grace_period_unit']
1309
1310 if soft_limit:
1311 soft_limit_in_bytes = utils.get_size_bytes(soft_limit, cap_unit)
1312 else:
1313 soft_limit_in_bytes = quota_config_obj.default_soft_limit
1314
1315 if hard_limit:
1316 hard_limit_in_bytes = utils.get_size_bytes(hard_limit, cap_unit)
1317 else:
1318 hard_limit_in_bytes = quota_config_obj.default_hard_limit
1319
1320 if grace_period:
1321 grace_period_in_sec = get_time_in_seconds(grace_period, gp_unit)
1322 else:
1323 grace_period_in_sec = quota_config_obj.grace_period
1324
1325 policy_enum = None
1326 policy_enum_val = None
1327 if quota_policy:
1328 if utils.QuotaPolicyEnum[quota_policy]:
1329 policy_enum = utils.QuotaPolicyEnum[quota_policy]
1330 policy_enum_val = \
1331 utils.QuotaPolicyEnum[quota_policy]._get_properties()['value']
1332 else:
1333 errormsg = "Invalid choice {0} for quota policy".format(
1334 quota_policy)
1335 LOG.error(errormsg)
1336 self.module.fail_json(msg=errormsg)
1337
1338 # Verify if modify is required. If not required, return False
1339 if quota_config_obj.default_hard_limit == hard_limit_in_bytes and \
1340 quota_config_obj.default_soft_limit == soft_limit_in_bytes and \
1341 quota_config_obj.grace_period == grace_period_in_sec and \
1342 ((quota_policy is not None and
1343 quota_config_obj.quota_policy == policy_enum) or
1344 quota_policy is None) and \
1345 (is_user_quota_enabled is None or
1346 (is_user_quota_enabled is not None and
1347 is_user_quota_enabled == quota_config_obj.is_user_quota_enabled)):
1348 return False
1349
1350 try:
1351 resp = self.unity_conn.modify_quota_config(
1352 quota_config_id=quota_config_obj.id,
1353 grace_period=grace_period_in_sec,
1354 default_hard_limit=hard_limit_in_bytes,
1355 default_soft_limit=soft_limit_in_bytes,
1356 is_user_quota_enabled=is_user_quota_enabled,
1357 quota_policy=policy_enum_val)
1358 LOG.info("Successfully modified the quota config with response %s", resp)
1359 return True
1360
1361 except Exception as e:
1362 errormsg = "Failed to modify quota config for filesystem {0} " \
1363 " with error {1}".format(quota_config_obj.filesystem.id, str(e))
1364 LOG.error(errormsg)
1365 self.module.fail_json(msg=errormsg)
1366
1367 def update_replication_params(self, replication_params):
1368 ''' Update replication params '''
1369 try:
1370 if replication_params['replication_type'] == 'remote' or \
1371 (replication_params['replication_type'] is None and
1372 replication_params['remote_system']):
1373 connection_params = {
1374 'unispherehost': replication_params['remote_system']['remote_system_host'],
1375 'username': replication_params['remote_system']['remote_system_username'],
1376 'password': replication_params['remote_system']['remote_system_password'],
1377 'validate_certs': replication_params['remote_system']['remote_system_verifycert'],
1378 'port': replication_params['remote_system']['remote_system_port']
1379 }
1380 remote_system_conn = utils.get_unity_unisphere_connection(
1381 connection_params, application_type)
1382 replication_params['remote_system_name'] = remote_system_conn.name
1383 if replication_params['destination_pool_name'] is not None:
1384 pool_object = \
1385 remote_system_conn.get_pool(name=replication_params['destination_pool_name'])
1386 replication_params['destination_pool_id'] = pool_object.id
1387 else:
1388 if replication_params['destination_pool_name'] is not None:
1389 pool_object = \
1390 self.unity_conn.get_pool(name=replication_params['destination_pool_name'])
1391 replication_params['destination_pool_id'] = pool_object.id
1392 except Exception as e:
1393 errormsg = "Updating replication params failed" \
1394 " with error %s" % str(e)
1395 LOG.error(errormsg)
1396 self.module.fail_json(msg=errormsg)
1397
1398 def validate_rpo(self, replication_params):
1399 ''' Validates rpo based on replication mode '''
1400 if replication_params['replication_mode'] == 'asynchronous' and \
1401 replication_params['rpo'] is None:
1402 errormsg = "rpo is required together with 'asynchronous' replication_mode."
1403 LOG.error(errormsg)
1404 self.module.fail_json(msg=errormsg)
1405
1406 rpo, replication_mode = replication_params['rpo'], replication_params[
1407 'replication_mode']
1408
1409 if rpo and replication_mode:
1410
1411 rpo_criteria = {
1412 "asynchronous": lambda n: 5 <= n <= 1440,
1413 "synchronous": lambda n: n == 0,
1414 "manual": lambda n: n == -1
1415 }
1416
1417 if rpo and not rpo_criteria[replication_mode](rpo):
1418 errormsg = f"Invalid rpo value - {rpo} for " \
1419 f"{replication_mode} replication mode."
1420 LOG.error(errormsg)
1421 self.module.fail_json(msg=errormsg)
1422
1423 def validate_replication_params(self, replication_params):
1424 ''' Validate replication params '''
1425 if not replication_params:
1426 errormsg = "Please specify replication_params to enable replication."
1427 LOG.error(errormsg)
1428 self.module.fail_json(msg=errormsg)
1429
1430 if replication_params['destination_pool_id'] is not None and \
1431 replication_params['destination_pool_name'] is not None:
1432 errormsg = "'destination_pool_id' and 'destination_pool_name' is mutually exclusive."
1433 LOG.error(errormsg)
1434 self.module.fail_json(msg=errormsg)
1435
1436 self.validate_rpo(replication_params)
1437 # Validate replication type
1438 if replication_params['replication_type'] == 'remote' and replication_params['remote_system'] is None:
1439 errormsg = "Remote_system is required together with 'remote' replication_type"
1440 LOG.error(errormsg)
1441 self.module.fail_json(msg=errormsg)
1442
1443 def validate_create_replication_params(self, replication_params):
1444 ''' Validate replication params '''
1445
1446 if replication_params['destination_pool_id'] is None and \
1447 replication_params['destination_pool_name'] is None:
1448 errormsg = "Either 'destination_pool_id' or 'destination_pool_name' is required to enable replication."
1449 LOG.error(errormsg)
1450 self.module.fail_json(msg=errormsg)
1451
1452 keys = ['replication_mode', 'replication_type']
1453 for key in keys:
1454 if replication_params[key] is None:
1455 errormsg = "Please specify %s to enable replication." % key
1456 LOG.error(errormsg)
1457 self.module.fail_json(msg=errormsg)
1458
1459 def modify_replication_session(self, obj_fs, repl_session, replication_params):
1460 """ Modify the replication session
1461 :param: obj_fs: Filesystem object
1462 :param: repl_session: Replication session to be modified
1463 :param: replication_params: Module input params
1464 :return: True if modification is successful
1465 """
1466 try:
1467 LOG.info("Modifying replication session of filesystem %s", obj_fs.name)
1468 modify_payload = {}
1469 rpo = 0
1470 if replication_params['replication_mode']:
1471 if replication_params['replication_mode'] == 'manual':
1472 rpo = -1
1473 elif replication_params['replication_mode'] == 'synchronous':
1474 rpo = 0
1475 elif replication_params['replication_mode'] == 'asynchronous':
1476 rpo = replication_params.get('rpo', 0)
1477 elif replication_params['rpo']:
1478 rpo = replication_params['rpo']
1479 name = repl_session.name
1480 if replication_params['new_replication_name'] and \
1481 name != replication_params['new_replication_name']:
1482 name = replication_params['new_replication_name']
1483
1484 if repl_session.name != name:
1485 modify_payload['name'] = name
1486 if ((replication_params['replication_mode'] or replication_params['rpo']) and
1487 repl_session.max_time_out_of_sync != rpo):
1488 modify_payload['max_time_out_of_sync'] = rpo
1489
1490 if modify_payload:
1491 repl_session.modify(**modify_payload)
1492 return True
1493
1494 return False
1495 except Exception as e:
1496 errormsg = "Modifying replication session failed with error %s" % e
1497 LOG.error(errormsg)
1498 self.module.fail_json(msg=errormsg)
1499
1500 def enable_replication(self, obj_fs, replication_params):
1501 """ Enable the replication session
1502 :param: obj_fs: Filesystem object
1503 :param: replication_params: Module input params
1504 :return: True if enabling replication is successful
1505 """
1506 try:
1507 self.validate_replication_params(replication_params)
1508 self.update_replication_params(replication_params)
1509
1510 repl_session = \
1511 self.get_replication_session_on_filter(obj_fs, replication_params, "modify")
1512 if repl_session:
1513 return self.modify_replication_session(obj_fs, repl_session, replication_params)
1514
1515 self.validate_create_replication_params(replication_params)
1516 replication_args_list = get_replication_args_list(replication_params)
1517 if 'remote_system_name' in replication_params:
1518 remote_system_name = replication_params['remote_system_name']
1519 remote_system_list = self.unity_conn.get_remote_system()
1520 for remote_system in remote_system_list:
1521 if remote_system.name == remote_system_name:
1522 replication_args_list['remote_system'] = remote_system
1523 break
1524 if 'remote_system' not in replication_args_list.keys():
1525 errormsg = "Remote system %s is not found" % (remote_system_name)
1526 LOG.error(errormsg)
1527 self.module.fail_json(msg=errormsg)
1528
1529 LOG.info("Enabling replication to the filesystem %s", obj_fs.name)
1530 obj_fs.replicate_with_dst_resource_provisioning(**replication_args_list)
1531 return True
1532 except Exception as e:
1533 errormsg = "Enabling replication to the filesystem %s failed " \
1534 "with error %s" % (obj_fs.name, str(e))
1535 LOG.error(errormsg)
1536 self.module.fail_json(msg=errormsg)
1537
1538 def disable_replication(self, obj_fs, replication_params):
1539 """ Remove replication from the filesystem
1540 :param: replication_params: Module input params
1541 :return: True if disabling replication is successful
1542 """
1543 try:
1544 LOG.info(("Disabling replication on the filesystem %s", obj_fs.name))
1545 if replication_params:
1546 self.update_replication_params(replication_params)
1547 repl_session = \
1548 self.get_replication_session_on_filter(obj_fs, replication_params, "delete")
1549 if repl_session:
1550 repl_session.delete()
1551 return True
1552 return False
1553 except Exception as e:
1554 errormsg = "Disabling replication on the filesystem %s failed " \
1555 "with error %s" % (obj_fs.name, str(e))
1556 LOG.error(errormsg)
1557 self.module.fail_json(msg=errormsg)
1558
1559 def get_replication_session_on_filter(self, obj_fs, replication_params, action):
1560 if replication_params and replication_params['remote_system']:
1561 repl_session = \
1562 self.get_replication_session(obj_fs, filter_key="remote_system_name",
1563 replication_params=replication_params)
1564 elif replication_params and replication_params['replication_name']:
1565 repl_session = \
1566 self.get_replication_session(obj_fs, filter_key="name",
1567 name=replication_params['replication_name'])
1568 else:
1569 repl_session = self.get_replication_session(obj_fs, action=action)
1570 if repl_session and action and replication_params and \
1571 replication_params['replication_type'] == 'local' and \
1572 repl_session.remote_system.name != self.unity_conn.name:
1573 return None
1574
1575 return repl_session
1576
1577 def get_replication_session(self, obj_fs, filter_key=None, replication_params=None, name=None, action=None):
1578 """ Retrieves the replication sessions configured for the filesystem
1579 :param: obj_fs: Filesystem object
1580 :param: filter_key: Key to filter replication sessions
1581 :param: replication_params: Module input params
1582 :param: name: Replication session name
1583 :param: action: Specifies modify or delete action on replication session
1584 :return: Replication session details
1585 """
1586 try:
1587 repl_session = self.unity_conn.get_replication_session(src_resource_id=obj_fs.storage_resource.id)
1588 if not filter_key and repl_session:
1589 if len(repl_session) > 1:
1590 if action:
1591 error_msg = 'There are multiple replication sessions for the filesystem.'\
1592 ' Please specify replication_name in replication_params to %s.' % action
1593 self.module.fail_json(msg=error_msg)
1594 return repl_session
1595 return repl_session[0]
1596 for session in repl_session:
1597 if filter_key == 'remote_system_name' and \
1598 session.remote_system.name == replication_params['remote_system_name']:
1599 return session
1600 if filter_key == 'name' and session.name == name:
1601 return session
1602 return None
1603 except Exception as e:
1604 errormsg = "Retrieving replication session on the filesystem failed " \
1605 "with error %s", str(e)
1606 LOG.error(errormsg)
1607 self.module.fail_json(msg=errormsg)
1608
1609 def perform_module_operation(self):
1610 """
1611 Perform different actions on filesystem module based on parameters
1612 passed in the playbook
1613 """
1614 filesystem_name = self.module.params['filesystem_name']
1615 filesystem_id = self.module.params['filesystem_id']
1616 nas_server_name = self.module.params['nas_server_name']
1617 nas_server_id = self.module.params['nas_server_id']
1618 pool_name = self.module.params['pool_name']
1619 pool_id = self.module.params['pool_id']
1620 size = self.module.params['size']
1621 cap_unit = self.module.params['cap_unit']
1622 quota_config = self.module.params['quota_config']
1623 replication_params = self.module.params['replication_params']
1624 replication_state = self.module.params['replication_state']
1625 state = self.module.params['state']
1626 snap_schedule_name = self.module.params['snap_schedule_name']
1627 snap_schedule_id = self.module.params['snap_schedule_id']
1628
1629 # result is a dictionary to contain end state and FileSystem details
1630 changed = False
1631 result = dict(
1632 changed=False,
1633 filesystem_details={}
1634 )
1635
1636 to_modify_dict = None
1637 filesystem_details = None
1638 quota_config_obj = None
1639
1640 self.validate_input_string()
1641
1642 if size is not None and size == 0:
1643 self.module.fail_json(msg="Size can not be 0 (Zero)")
1644
1645 if size and not cap_unit:
1646 cap_unit = 'GB'
1647
1648 if quota_config:
1649 if (quota_config['default_hard_limit'] is not None
1650 or quota_config['default_soft_limit'] is not None) and \
1651 not quota_config['cap_unit']:
1652 quota_config['cap_unit'] = 'GB'
1653
1654 if quota_config['grace_period'] is not None \
1655 and quota_config['grace_period_unit'] is None:
1656 quota_config['grace_period_unit'] = 'days'
1657
1658 if quota_config['grace_period'] is not None \
1659 and quota_config['grace_period'] <= 0:
1660 self.module.fail_json(msg="Invalid grace_period provided. "
1661 "Must be greater than 0.")
1662
1663 if quota_config['default_soft_limit'] is not None \
1664 and utils.is_size_negative(quota_config['default_soft_limit']):
1665 self.module.fail_json(msg="Invalid default_soft_limit provided. "
1666 "Must be greater than or equal to 0.")
1667
1668 if quota_config['default_hard_limit'] is not None \
1669 and utils.is_size_negative(quota_config['default_hard_limit']):
1670 self.module.fail_json(msg="Invalid default_hard_limit provided. "
1671 "Must be greater than or equal to 0.")
1672
1673 if (cap_unit is not None) and not size:
1674 self.module.fail_json(msg="cap_unit can be specified along "
1675 "with size")
1676
1677 nas_server = None
1678 if nas_server_name or nas_server_id:
1679 nas_server = self.get_nas_server(
1680 name=nas_server_name, id=nas_server_id)
1681
1682 obj_pool = None
1683 if pool_name or pool_id:
1684 obj_pool = self.get_pool(pool_name=pool_name, pool_id=pool_id)
1685
1686 obj_fs = None
1687 obj_fs = self.get_filesystem(name=filesystem_name,
1688 id=filesystem_id,
1689 obj_nas_server=nas_server)
1690
1691 self.snap_sch_id = None
1692 if snap_schedule_name or snap_schedule_id:
1693 snap_schedule_params = {
1694 "name": snap_schedule_name,
1695 "id": snap_schedule_id
1696 }
1697 self.snap_sch_id = self.resolve_to_snapschedule_id(snap_schedule_params)
1698 elif snap_schedule_name == "" or snap_schedule_id == "":
1699 self.snap_sch_id = ""
1700
1701 if obj_fs:
1702 filesystem_details = obj_fs._get_properties()
1703 filesystem_id = obj_fs.get_id()
1704 to_modify_dict = self.is_modify_required(obj_fs, cap_unit)
1705 LOG.info("From Mod Op, to_modify_dict: %s", to_modify_dict)
1706
1707 if state == 'present' and not filesystem_details:
1708 if not filesystem_name:
1709 msg_noname = "FileSystem with id {0} is not found, unable to " \
1710 "create a FileSystem without a valid " \
1711 "filesystem_name".format(filesystem_id)
1712 self.module.fail_json(msg=msg_noname)
1713
1714 if not pool_name and not pool_id:
1715 self.module.fail_json(msg="pool_id or pool_name is required "
1716 "to create new filesystem")
1717 if not size:
1718 self.module.fail_json(msg="Size is required to create"
1719 " a filesystem")
1720 size = utils.get_size_bytes(size, cap_unit)
1721
1722 obj_fs = self.create_filesystem(name=filesystem_name,
1723 obj_pool=obj_pool,
1724 obj_nas_server=nas_server,
1725 size=size)
1726
1727 LOG.debug("Successfully created filesystem , %s", obj_fs)
1728 filesystem_id = obj_fs.id
1729 filesystem_details = obj_fs._get_properties()
1730 to_modify_dict = self.is_modify_required(obj_fs, cap_unit)
1731 LOG.debug("Got filesystem id , %s", filesystem_id)
1732 changed = True
1733
1734 if state == 'present' and filesystem_details and to_modify_dict:
1735 self.modify_filesystem(update_dict=to_modify_dict, obj_fs=obj_fs)
1736 changed = True
1737
1738 """
1739 Set quota configuration
1740 """
1741 if state == "present" and filesystem_details and quota_config:
1742 quota_config_obj = self.get_quota_config_details(obj_fs)
1743
1744 if quota_config_obj is not None:
1745 is_quota_config_modified = self.modify_quota_config(
1746 quota_config_obj=quota_config_obj,
1747 quota_config_params=quota_config)
1748
1749 if is_quota_config_modified:
1750 changed = True
1751 else:
1752 self.module.fail_json(msg="One or more operations related"
1753 " to this task failed because the"
1754 " new object created could not be fetched."
1755 " Please rerun the task for expected result.")
1756
1757 if state == 'present' and filesystem_details and replication_state is not None:
1758 if replication_state == 'enable':
1759 changed = self.enable_replication(obj_fs, replication_params)
1760 else:
1761 changed = self.disable_replication(obj_fs, replication_params)
1762
1763 if state == 'absent' and filesystem_details:
1764 changed = self.delete_filesystem(filesystem_id)
1765 filesystem_details = None
1766
1767 if state == 'present' and filesystem_details:
1768 filesystem_details = self.get_filesystem_display_attributes(
1769 obj_fs=obj_fs)
1770
1771 result['changed'] = changed
1772 result['filesystem_details'] = filesystem_details
1773 self.module.exit_json(**result)
1774
1775
1776 def get_time_in_seconds(time, time_units):
1777 """This method get time is seconds"""
1778 min_in_sec = 60
1779 hour_in_sec = 60 * 60
1780 day_in_sec = 24 * 60 * 60
1781 if time is not None and time > 0:
1782 if time_units in 'minutes':
1783 return time * min_in_sec
1784 elif time_units in 'hours':
1785 return time * hour_in_sec
1786 elif time_units in 'days':
1787 return time * day_in_sec
1788 else:
1789 return time
1790 else:
1791 return 0
1792
1793
1794 def get_time_with_unit(time):
1795 """This method sets seconds in minutes, hours or days."""
1796 sec_in_min = 60
1797 sec_in_hour = 60 * 60
1798 sec_in_day = 24 * 60 * 60
1799
1800 if time % sec_in_day == 0:
1801 time = time / sec_in_day
1802 unit = 'days'
1803
1804 elif time % sec_in_hour == 0:
1805 time = time / sec_in_hour
1806 unit = 'hours'
1807
1808 else:
1809 time = time / sec_in_min
1810 unit = 'minutes'
1811 return "%s %s" % (time, unit)
1812
1813
1814 def get_replication_args_list(replication_params):
1815 """Returns the replication args for payload"""
1816 replication_args_list = {
1817 'dst_pool_id': replication_params['destination_pool_id']
1818 }
1819
1820 if replication_params['replication_name']:
1821 replication_args_list['replication_name'] = replication_params['replication_name']
1822
1823 if 'replication_mode' in replication_params:
1824 if replication_params['replication_mode'] == 'asynchronous':
1825 replication_args_list['max_time_out_of_sync'] = replication_params['rpo']
1826 elif replication_params['replication_mode'] == 'synchronous':
1827 replication_args_list['max_time_out_of_sync'] = 0
1828 else:
1829 replication_args_list['max_time_out_of_sync'] = -1
1830
1831 return replication_args_list
1832
1833
1834 def get_filesystem_parameters():
1835 """This method provide parameters required for the ansible filesystem
1836 module on Unity"""
1837 return dict(
1838 filesystem_name=dict(required=False, type='str'),
1839 filesystem_id=dict(required=False, type='str'),
1840 nas_server_name=dict(required=False, type='str'),
1841 nas_server_id=dict(required=False, type='str'),
1842 description=dict(required=False, type='str'),
1843 pool_name=dict(required=False, type='str'),
1844 pool_id=dict(required=False, type='str'),
1845 size=dict(required=False, type='int'),
1846 cap_unit=dict(required=False, type='str', choices=['GB', 'TB']),
1847 is_thin=dict(required=False, type='bool'),
1848 data_reduction=dict(required=False, type='bool'),
1849 supported_protocols=dict(required=False, type='str',
1850 choices=['NFS', 'CIFS', 'MULTIPROTOCOL']),
1851 smb_properties=dict(type='dict', options=dict(
1852 is_smb_sync_writes_enabled=dict(type='bool'),
1853 is_smb_notify_on_access_enabled=dict(type='bool'),
1854 is_smb_op_locks_enabled=dict(type='bool'),
1855 is_smb_notify_on_write_enabled=dict(type='bool'),
1856 smb_notify_on_change_dir_depth=dict(type='int')
1857 )),
1858 access_policy=dict(required=False, type='str',
1859 choices=['NATIVE', 'UNIX', 'WINDOWS']),
1860 locking_policy=dict(required=False, type='str',
1861 choices=['ADVISORY', 'MANDATORY']),
1862 tiering_policy=dict(required=False, type='str', choices=[
1863 'AUTOTIER_HIGH', 'AUTOTIER', 'HIGHEST', 'LOWEST']),
1864 snap_schedule_name=dict(required=False, type='str'),
1865 snap_schedule_id=dict(required=False, type='str'),
1866 quota_config=dict(required=False, type='dict', options=dict(
1867 grace_period=dict(required=False, type='int'),
1868 grace_period_unit=dict(required=False, type='str', choices=['minutes', 'hours', 'days']),
1869 default_hard_limit=dict(required=False, type='int'),
1870 default_soft_limit=dict(required=False, type='int'),
1871 is_user_quota_enabled=dict(required=False, type='bool'),
1872 quota_policy=dict(required=False, type='str', choices=['FILE_SIZE', 'BLOCKS']),
1873 cap_unit=dict(required=False, type='str', choices=['MB', 'GB', 'TB']),
1874 ), mutually_exclusive=[['is_user_quota_enabled', 'quota_policy']]),
1875 replication_params=dict(type='dict', options=dict(
1876 replication_name=dict(type='str'),
1877 new_replication_name=dict(type='str'),
1878 replication_type=dict(type='str', choices=['local', 'remote']),
1879 replication_mode=dict(type='str',
1880 choices=['synchronous', 'asynchronous',
1881 'manual']),
1882 rpo=dict(type='int'),
1883 remote_system=dict(type='dict',
1884 options=dict(
1885 remote_system_host=dict(type='str', required=True),
1886 remote_system_verifycert=dict(type='bool', required=False,
1887 default=True),
1888 remote_system_username=dict(type='str', required=True),
1889 remote_system_password=dict(type='str', required=True, no_log=True),
1890 remote_system_port=dict(type='int', required=False, default=443)
1891 )),
1892 destination_pool_name=dict(type='str'),
1893 destination_pool_id=dict(type='str')
1894 )),
1895 replication_state=dict(type='str', choices=['enable', 'disable']),
1896 state=dict(required=True, type='str', choices=['present', 'absent'])
1897 )
1898
1899
1900 def main():
1901 """ Create Unity FileSystem object and perform action on it
1902 based on user input from playbook"""
1903 obj = Filesystem()
1904 obj.perform_module_operation()
1905
1906
1907 if __name__ == '__main__':
1908 main()