Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/nfs.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 nfs export on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r"""
11 ---
12 module: nfs
13 version_added: '1.1.0'
14 short_description: Manage NFS export on Unity storage system
15 description:
16 - Managing NFS export on Unity storage system includes-
17 Create new NFS export,
18 Modify NFS export attributes,
19 Display NFS export details,
20 Delete NFS export.
21
22 extends_documentation_fragment:
23 - dellemc.unity.unity
24
25 author:
26 - Vivek Soni (@v-soni11) <[email protected]>
27
28 options:
29 nfs_export_name:
30 description:
31 - Name of the nfs export.
32 - Mandatory for create operation.
33 - Specify either I(nfs_export_name) or I(nfs_export_id) (but not both) for any
34 operation.
35 type: str
36 nfs_export_id:
37 description:
38 - ID of the nfs export.
39 - This is a unique ID generated by Unity storage system.
40 type: str
41 filesystem_name:
42 description:
43 - Name of the filesystem for which NFS export will be created.
44 - Either filesystem or snapshot is required for creation of the NFS.
45 - If I(filesystem_name) is specified, then I(nas_server) is required to uniquely
46 identify the filesystem.
47 - If filesystem parameter is provided, then snapshot cannot be specified.
48 type: str
49 filesystem_id:
50 description:
51 - ID of the filesystem.
52 - This is a unique ID generated by Unity storage system.
53 type: str
54 snapshot_name:
55 description:
56 - Name of the snapshot for which NFS export will be created.
57 - Either filesystem or snapshot is required for creation of the NFS
58 export.
59 - If snapshot parameter is provided, then filesystem cannot be specified.
60 type: str
61 snapshot_id:
62 description:
63 - ID of the snapshot.
64 - This is a unique ID generated by Unity storage system.
65 type: str
66 nas_server_name:
67 description:
68 - Name of the NAS server on which filesystem will be hosted.
69 type: str
70 nas_server_id:
71 description:
72 - ID of the NAS server on which filesystem will be hosted.
73 type: str
74 path:
75 description:
76 - Local path to export relative to the NAS server root.
77 - With NFS, each export of a file_system or file_snap must have a unique
78 local path.
79 - Mandatory while creating NFS export.
80 type: str
81 description:
82 description:
83 - Description of the NFS export.
84 - Optional parameter when creating a NFS export.
85 - To modify description, pass the new value in I(description) field.
86 - To remove description, pass the empty value in I(description) field.
87 type: str
88 host_state:
89 description:
90 - Define whether the hosts can access the NFS export.
91 - Required when adding or removing access of hosts from the export.
92 type: str
93 choices: ['present-in-export', 'absent-in-export']
94 anonymous_uid:
95 description:
96 - Specifies the user ID of the anonymous account.
97 - If not specified at the time of creation, it will be set to 4294967294.
98 type: int
99 anonymous_gid:
100 description:
101 - Specifies the group ID of the anonymous account.
102 - If not specified at the time of creation, it will be set to 4294967294.
103 type: int
104 state:
105 description:
106 - State variable to determine whether NFS export will exist or not.
107 required: true
108 type: str
109 choices: ['absent', 'present']
110 default_access:
111 description:
112 - Default access level for all hosts that can access the NFS export.
113 - For hosts that need different access than the default,
114 they can be configured by adding to the list.
115 - If I(default_access) is not mentioned during creation, then NFS export will
116 be created with C(NO_ACCESS).
117 type: str
118 choices: ['NO_ACCESS', 'READ_ONLY', 'READ_WRITE', 'ROOT',
119 'READ_ONLY_ROOT']
120 min_security:
121 description:
122 - NFS enforced security type for users accessing a NFS export.
123 - If not specified at the time of creation, it will be set to C(SYS).
124 type: str
125 choices: ['SYS', 'KERBEROS', 'KERBEROS_WITH_INTEGRITY',
126 'KERBEROS_WITH_ENCRYPTION']
127 adv_host_mgmt_enabled:
128 description:
129 - If C(false), allows you to specify hosts without first having to register them.
130 - Mandatory while adding access hosts.
131 type: bool
132 no_access_hosts:
133 description:
134 - Hosts with no access to the NFS export.
135 - List of dictionaries. Each dictionary will have any of the keys from
136 I(host_name), I(host_id), I(subnet), I(netgroup), I(domain) and I(ip_address).
137 - If I(adv_host_mgmt_enabled) is C(true) then the accepted keys are I(host_name), I(host_id) and I(ip_address).
138 - If I(adv_host_mgmt_enabled) is C(false) then the accepted keys are I(host_name), I(subnet), I(netgroup), I(domain) and I(ip_address).
139 type: list
140 elements: dict
141 suboptions:
142 host_name:
143 description:
144 - Name of the host.
145 type: str
146 host_id:
147 description:
148 - ID of the host.
149 type: str
150 ip_address:
151 description:
152 - IP address of the host.
153 type: str
154 subnet:
155 description:
156 - Subnet can be an 'IP address/netmask' or 'IP address/prefix length'.
157 type: str
158 netgroup:
159 description:
160 - Netgroup that is defined in NIS or the local netgroup file.
161 type: str
162 domain:
163 description:
164 - DNS domain, where all NFS clients in the domain are included in the host list.
165 type: str
166 read_only_hosts:
167 description:
168 - Hosts with read-only access to the NFS export.
169 - List of dictionaries. Each dictionary will have any of the keys from
170 I(host_name), I(host_id), I(subnet), I(netgroup), I(domain) and I(ip_address).
171 - If I(adv_host_mgmt_enabled) is C(true) then the accepted keys are I(host_name), I(host_id) and I(ip_address).
172 - If I(adv_host_mgmt_enabled) is C(false) then the accepted keys are I(host_name), I(subnet), I(netgroup), I(domain) and I(ip_address).
173 type: list
174 elements: dict
175 suboptions:
176 host_name:
177 description:
178 - Name of the host.
179 type: str
180 host_id:
181 description:
182 - ID of the host.
183 type: str
184 ip_address:
185 description:
186 - IP address of the host.
187 type: str
188 subnet:
189 description:
190 - Subnet can be an 'IP address/netmask' or 'IP address/prefix length'.
191 type: str
192 netgroup:
193 description:
194 - Netgroup that is defined in NIS or the local netgroup file.
195 type: str
196 domain:
197 description:
198 - DNS domain, where all NFS clients in the domain are included in the host list.
199 type: str
200 read_only_root_hosts:
201 description:
202 - Hosts with read-only for root user access to the NFS export.
203 - List of dictionaries. Each dictionary will have any of the keys from
204 I(host_name), I(host_id), I(subnet), I(netgroup), I(domain) and I(ip_address).
205 - If I(adv_host_mgmt_enabled) is C(true) then the accepted keys are I(host_name), I(host_id) and I(ip_address).
206 - If I(adv_host_mgmt_enabled) is C(false) then the accepted keys are I(host_name), I(subnet), I(netgroup), I(domain) and I(ip_address).
207 type: list
208 elements: dict
209 suboptions:
210 host_name:
211 description:
212 - Name of the host.
213 type: str
214 host_id:
215 description:
216 - ID of the host.
217 type: str
218 ip_address:
219 description:
220 - IP address of the host.
221 type: str
222 subnet:
223 description:
224 - Subnet can be an 'IP address/netmask' or 'IP address/prefix length'.
225 type: str
226 netgroup:
227 description:
228 - Netgroup that is defined in NIS or the local netgroup file.
229 type: str
230 domain:
231 description:
232 - DNS domain, where all NFS clients in the domain are included in the host list.
233 type: str
234 read_write_hosts:
235 description:
236 - Hosts with read and write access to the NFS export.
237 - List of dictionaries. Each dictionary will have any of the keys from
238 I(host_name), I(host_id), I(subnet), I(netgroup), I(domain) and I(ip_address).
239 - If I(adv_host_mgmt_enabled) is C(true) then the accepted keys are I(host_name), I(host_id) and I(ip_address).
240 - If I(adv_host_mgmt_enabled) is C(false) then the accepted keys are I(host_name), I(subnet), I(netgroup), I(domain) and I(ip_address).
241 type: list
242 elements: dict
243 suboptions:
244 host_name:
245 description:
246 - Name of the host.
247 type: str
248 host_id:
249 description:
250 - ID of the host.
251 type: str
252 ip_address:
253 description:
254 - IP address of the host.
255 type: str
256 subnet:
257 description:
258 - Subnet can be an 'IP address/netmask' or 'IP address/prefix length'.
259 type: str
260 netgroup:
261 description:
262 - Netgroup that is defined in NIS or the local netgroup file.
263 type: str
264 domain:
265 description:
266 - DNS domain, where all NFS clients in the domain are included in the host list.
267 type: str
268 read_write_root_hosts:
269 description:
270 - Hosts with read and write for root user access to the NFS export.
271 - List of dictionaries. Each dictionary will have any of the keys from
272 I(host_name), I(host_id), I(subnet), I(netgroup), I(domain) and I(ip_address).
273 - If I(adv_host_mgmt_enabled) is C(true) then the accepted keys are I(host_name), I(host_id) and I(ip_address).
274 - If I(adv_host_mgmt_enabled) is C(false) then the accepted keys are I(host_name), I(subnet), I(netgroup), I(domain) and I(ip_address).
275 type: list
276 elements: dict
277 suboptions:
278 host_name:
279 description:
280 - Name of the host.
281 type: str
282 host_id:
283 description:
284 - ID of the host.
285 type: str
286 ip_address:
287 description:
288 - IP address of the host.
289 type: str
290 subnet:
291 description:
292 - Subnet can be an 'IP address/netmask' or 'IP address/prefix length'.
293 type: str
294 netgroup:
295 description:
296 - Netgroup that is defined in NIS or the local netgroup file.
297 type: str
298 domain:
299 description:
300 - DNS domain, where all NFS clients in the domain are included in the host list.
301 type: str
302 notes:
303 - The I(check_mode) is not supported.
304 """
305
306 EXAMPLES = r"""
307 - name: Create nfs export from filesystem
308 nfs:
309 unispherehost: "{{unispherehost}}"
310 username: "{{username}}"
311 password: "{{password}}"
312 validate_certs: "{{validate_certs}}"
313 nfs_export_name: "ansible_nfs_from_fs"
314 path: '/'
315 filesystem_id: "fs_377"
316 state: "present"
317
318 - name: Create nfs export from snapshot
319 nfs:
320 unispherehost: "{{unispherehost}}"
321 username: "{{username}}"
322 password: "{{password}}"
323 validate_certs: "{{validate_certs}}"
324 nfs_export_name: "ansible_nfs_from_snap"
325 path: '/'
326 snapshot_name: "ansible_fs_snap"
327 state: "present"
328
329 - name: Modify nfs export
330 nfs:
331 unispherehost: "{{unispherehost}}"
332 username: "{{username}}"
333 password: "{{password}}"
334 validate_certs: "{{validate_certs}}"
335 nfs_export_name: "ansible_nfs_from_fs"
336 nas_server_id: "nas_3"
337 description: ""
338 default_access: "READ_ONLY_ROOT"
339 anonymous_gid: 4294967290
340 anonymous_uid: 4294967290
341 state: "present"
342
343 - name: Add host in nfs export with adv_host_mgmt_enabled as true
344 nfs:
345 unispherehost: "{{unispherehost}}"
346 username: "{{username}}"
347 password: "{{password}}"
348 validate_certs: "{{validate_certs}}"
349 nfs_export_name: "ansible_nfs_from_fs"
350 filesystem_id: "fs_377"
351 adv_host_mgmt_enabled: true
352 no_access_hosts:
353 - host_id: "Host_1"
354 read_only_hosts:
355 - host_id: "Host_2"
356 read_only_root_hosts:
357 - host_name: "host_name1"
358 read_write_hosts:
359 - host_name: "host_name2"
360 read_write_root_hosts:
361 - ip_address: "1.1.1.1"
362 host_state: "present-in-export"
363 state: "present"
364
365 - name: Remove host in nfs export with adv_host_mgmt_enabled as true
366 nfs:
367 unispherehost: "{{unispherehost}}"
368 username: "{{username}}"
369 password: "{{password}}"
370 validate_certs: "{{validate_certs}}"
371 nfs_export_name: "ansible_nfs_from_fs"
372 filesystem_id: "fs_377"
373 adv_host_mgmt_enabled: true
374 no_access_hosts:
375 - host_id: "Host_1"
376 read_only_hosts:
377 - host_id: "Host_2"
378 read_only_root_hosts:
379 - host_name: "host_name1"
380 read_write_hosts:
381 - host_name: "host_name2"
382 read_write_root_hosts:
383 - ip_address: "1.1.1.1"
384 host_state: "absent-in-export"
385 state: "present"
386
387 - name: Add host in nfs export with adv_host_mgmt_enabled as false
388 nfs:
389 unispherehost: "{{unispherehost}}"
390 username: "{{username}}"
391 password: "{{password}}"
392 validate_certs: "{{validate_certs}}"
393 nfs_export_name: "ansible_nfs_from_fs"
394 filesystem_id: "fs_377"
395 adv_host_mgmt_enabled: false
396 no_access_hosts:
397 - domain: "google.com"
398 read_only_hosts:
399 - netgroup: "netgroup_admin"
400 read_only_root_hosts:
401 - host_name: "host5"
402 read_write_hosts:
403 - subnet: "168.159.57.4/255.255.255.0"
404 read_write_root_hosts:
405 - ip_address: "10.255.2.4"
406 host_state: "present-in-export"
407 state: "present"
408
409 - name: Remove host in nfs export with adv_host_mgmt_enabled as false
410 nfs:
411 unispherehost: "{{unispherehost}}"
412 username: "{{username}}"
413 password: "{{password}}"
414 validate_certs: "{{validate_certs}}"
415 nfs_export_name: "ansible_nfs_from_fs"
416 filesystem_id: "fs_377"
417 adv_host_mgmt_enabled: false
418 no_access_hosts:
419 - domain: "google.com"
420 read_only_hosts:
421 - netgroup: "netgroup_admin"
422 read_only_root_hosts:
423 - host_name: "host5"
424 read_write_hosts:
425 - subnet: "168.159.57.4/255.255.255.0"
426 read_write_root_hosts:
427 - ip_address: "10.255.2.4"
428 host_state: "absent-in-export"
429 state: "present"
430
431 - name: Get nfs details
432 nfs:
433 unispherehost: "{{unispherehost}}"
434 username: "{{username}}"
435 password: "{{password}}"
436 validate_certs: "{{validate_certs}}"
437 nfs_export_id: "NFSShare_291"
438 state: "present"
439
440 - name: Delete nfs export by nfs name
441 nfs:
442 unispherehost: "{{unispherehost}}"
443 username: "{{username}}"
444 password: "{{password}}"
445 validate_certs: "{{validate_certs}}"
446 nfs_export_name: "ansible_nfs_name"
447 nas_server_name: "ansible_nas_name"
448 state: "absent"
449 """
450
451 RETURN = r"""
452 changed:
453 description: Whether or not the resource has changed.
454 returned: always
455 type: bool
456 sample: "false"
457
458 nfs_share_details:
459 description: Details of the nfs export.
460 returned: When nfs export exists.
461 type: dict
462 contains:
463 anonymous_uid:
464 description: User ID of the anonymous account
465 type: int
466 anonymous_gid:
467 description: Group ID of the anonymous account
468 type: int
469 default_access:
470 description: Default access level for all hosts that can access export
471 type: str
472 description:
473 description: Description about the nfs export
474 type: str
475 id:
476 description: ID of the nfs export
477 type: str
478 min_security:
479 description: NFS enforced security type for users accessing an export
480 type: str
481 name:
482 description: Name of the nfs export
483 type: str
484 no_access_hosts_string:
485 description: Hosts with no access to the nfs export
486 type: str
487 read_only_hosts_string:
488 description: Hosts with read-only access to the nfs export
489 type: str
490 read_only_root_hosts_string:
491 description: Hosts with read-only for root user access to the nfs export
492 type: str
493 read_write_hosts_string:
494 description: Hosts with read and write access to the nfs export
495 type: str
496 read_write_root_hosts_string:
497 description: Hosts with read and write for root user access to export
498 type: str
499 type:
500 description: NFS export type. i.e. filesystem or snapshot
501 type: str
502 export_paths:
503 description: Export paths that can be used to mount and access export
504 type: list
505 filesystem:
506 description: Details of the filesystem on which nfs export is present
507 type: dict
508 contains:
509 UnityFileSystem:
510 description: filesystem details
511 type: dict
512 contains:
513 id:
514 description: ID of the filesystem
515 type: str
516 name:
517 description: Name of the filesystem
518 type: str
519 nas_server:
520 description: Details of the nas server
521 type: dict
522 contains:
523 UnityNasServer:
524 description: NAS server details
525 type: dict
526 contains:
527 id:
528 description: ID of the nas server
529 type: str
530 name:
531 description: Name of the nas server
532 type: str
533 sample: {
534 'anonymous_gid': 4294967294,
535 'anonymous_uid': 4294967294,
536 'creation_time': '2022-03-09 15:05:34.720000+00:00',
537 'default_access': 'NFSShareDefaultAccessEnum.NO_ACCESS',
538 'description': '',
539 'export_option': 1,
540 'export_paths': [
541 '**.***.**.**:/dummy-share-123'
542 ],
543 'filesystem': {
544 'UnityFileSystem': {
545 'id': 'fs_id_1',
546 'name': 'fs_name_1'
547 }
548 },
549 'host_accesses': None,
550 'id': 'NFSShare_14393',
551 'is_read_only': None,
552 'min_security': 'NFSShareSecurityEnum.SYS',
553 'modification_time': '2022-04-25 08:12:28.179000+00:00',
554 'name': 'dummy-share-123',
555 'nfs_owner_username': None,
556 'no_access_hosts': None,
557 'no_access_hosts_string': 'host1,**.***.*.*',
558 'path': '/',
559 'read_only_hosts': None,
560 'read_only_hosts_string': '',
561 'read_only_root_access_hosts': None,
562 'read_only_root_hosts_string': '',
563 'read_write_hosts': None,
564 'read_write_hosts_string': '',
565 'read_write_root_hosts_string': '',
566 'role': 'NFSShareRoleEnum.PRODUCTION',
567 'root_access_hosts': None,
568 'snap': None,
569 'type': 'NFSTypeEnum.NFS_SHARE',
570 'existed': true,
571 'nas_server': {
572 'UnityNasServer': {
573 'id': 'nas_id_1',
574 'name': 'dummy_nas_server'
575 }
576 }
577 }
578 """
579
580 import re
581 import traceback
582
583 try:
584 from ipaddress import ip_network, IPv4Network, IPv6Network
585 HAS_IPADDRESS, IP_ADDRESS_IMP_ERR = True, None
586 except ImportError:
587 HAS_IPADDRESS, IP_ADDRESS_IMP_ERR = False, traceback.format_exc()
588
589 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
590 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
591 import utils
592
593 LOG = utils.get_logger('nfs')
594
595 DEFAULT_ACCESS_LIST = ['NO_ACCESS', 'READ_ONLY', 'READ_WRITE', 'ROOT',
596 'READ_ONLY_ROOT']
597 MIN_SECURITY_LIST = ['SYS', 'KERBEROS', 'KERBEROS_WITH_INTEGRITY',
598 'KERBEROS_WITH_ENCRYPTION']
599 HOST_DICT = dict(type='list', required=False, elements='dict',
600 options=dict(host_name=dict(),
601 host_id=dict(),
602 ip_address=dict(),
603 subnet=dict(),
604 netgroup=dict(),
605 domain=dict()))
606 HOST_STATE_LIST = ['present-in-export', 'absent-in-export']
607 STATE_LIST = ['present', 'absent']
608
609 application_type = "Ansible/1.7.1"
610
611
612 class NFS(object):
613 """Class with nfs export operations"""
614
615 def __init__(self):
616 """ Define all parameters required by this module"""
617
618 self.module_params = utils.get_unity_management_host_parameters()
619 self.module_params.update(get_nfs_parameters())
620
621 mutually_exclusive = [['nfs_export_id', 'nas_server_id'],
622 ['nfs_export_id', 'nas_server_name'],
623 ['filesystem_id', 'filesystem_name',
624 'snapshot_id', 'snapshot_name'],
625 ['nas_server_id', 'nas_server_name']]
626 required_one_of = [['nfs_export_id', 'nfs_export_name']]
627
628 """ initialize the ansible module """
629 self.module = AnsibleModule(
630 argument_spec=self.module_params, supports_check_mode=False,
631 mutually_exclusive=mutually_exclusive,
632 required_one_of=required_one_of)
633 utils.ensure_required_libs(self.module)
634
635 if not HAS_IPADDRESS:
636 self.module.fail_json(msg=missing_required_lib("ipaddress"),
637 exception=IP_ADDRESS_IMP_ERR)
638
639 self.unity = utils.get_unity_unisphere_connection(self.module.params,
640 application_type)
641 self.cli = self.unity._cli
642
643 self.is_given_nfs_for_fs = None
644 if self.module.params['filesystem_name'] or \
645 self.module.params['filesystem_id']:
646 self.is_given_nfs_for_fs = True
647 elif self.module.params['snapshot_name'] or \
648 self.module.params['snapshot_id']:
649 self.is_given_nfs_for_fs = False
650
651 # Contain hosts input & output parameters
652 self.host_param_mapping = {
653 'no_access_hosts': 'no_access_hosts_string',
654 'read_only_hosts': 'read_only_hosts_string',
655 'read_only_root_hosts': 'read_only_root_hosts_string',
656 'read_write_hosts': 'read_write_hosts_string',
657 'read_write_root_hosts': 'read_write_root_hosts_string'
658 }
659
660 # Default_access mapping. keys are giving by user & values are
661 # accepted by SDK
662 self.default_access = {'READ_ONLY_ROOT': 'RO_ROOT'}
663
664 LOG.info('Got the unity instance for provisioning on Unity')
665
666 def validate_host_access_data(self, host_dict):
667 """
668 Validate host access data
669 :param host_dict: Host access data
670 :return None
671 """
672 fqdn_pat = re.compile(r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{0,62}'
673 r'[a-zA-Z0-9]\.)+[a-zA-Z]{2,63}$)')
674
675 if host_dict.get('host_name'):
676 version = get_ip_version(host_dict.get('host_name'))
677 if version in (4, 6):
678 msg = "IP4/IP6: %s given in host_name instead " \
679 "of name" % host_dict.get('host_name')
680 LOG.error(msg)
681 self.module.fail_json(msg=msg)
682
683 if host_dict.get('ip_address'):
684 ip_or_fqdn = host_dict.get('ip_address')
685 version = get_ip_version(ip_or_fqdn)
686 # validate its FQDN or not
687 if version == 0 and not fqdn_pat.match(ip_or_fqdn):
688 msg = "%s is not a valid FQDN" % ip_or_fqdn
689 LOG.error(msg)
690 self.module.fail_json(msg=msg)
691
692 if host_dict.get('subnet'):
693 subnet = host_dict.get('subnet')
694 subnet_info = subnet.split("/")
695 if len(subnet_info) != 2:
696 msg = "Subnet should be in format 'IP address/netmask' or 'IP address/prefix length'"
697 LOG.error(msg)
698 self.module.fail_json(msg=msg)
699
700 def validate_adv_host_mgmt_enabled_check(self, host_dict):
701 """
702 Validate adv_host_mgmt_enabled check
703 :param host_dict: Host access data
704 :return None
705 """
706 host_dict_keys_set = set(host_dict.keys())
707 adv_host_mgmt_enabled_true_set = {'host_name', 'host_id', 'ip_address'}
708 adv_host_mgmt_enabled_false_set = {'host_name', 'subnet', 'domain', 'netgroup', 'ip_address'}
709 adv_host_mgmt_enabled_true_diff = host_dict_keys_set - adv_host_mgmt_enabled_true_set
710 adv_host_mgmt_enabled_false_diff = host_dict_keys_set - adv_host_mgmt_enabled_false_set
711 if self.module.params['adv_host_mgmt_enabled'] and adv_host_mgmt_enabled_true_diff != set():
712 msg = "If 'adv_host_mgmt_enabled' is true then host access should only have %s" % adv_host_mgmt_enabled_true_set
713 LOG.error(msg)
714 self.module.fail_json(msg=msg)
715 elif not self.module.params['adv_host_mgmt_enabled'] and adv_host_mgmt_enabled_false_diff != set():
716 msg = "If 'adv_host_mgmt_enabled' is false then host access should only have %s" % adv_host_mgmt_enabled_false_set
717 LOG.error(msg)
718 self.module.fail_json(msg=msg)
719
720 def validate_host_access_input_params(self):
721 """
722 Validate host access params
723 :return None
724 """
725 for param in list(self.host_param_mapping.keys()):
726 if self.module.params[param] and (not self.module.params[
727 'host_state'] or self.module.params[
728 'adv_host_mgmt_enabled'] is None):
729 msg = "'host_state' and 'adv_host_mgmt_enabled' is required along with: %s" % param
730 LOG.error(msg)
731 self.module.fail_json(msg=msg)
732 elif self.module.params[param]:
733 for host_dict in self.module.params[param]:
734 host_dict = {k: v for k, v in host_dict.items() if v}
735 self.validate_adv_host_mgmt_enabled_check(host_dict)
736 self.validate_host_access_data(host_dict)
737
738 def validate_module_attributes(self):
739 """
740 Validate module attributes
741 :return None
742 """
743 param_list = ['nfs_export_name', 'nfs_export_id', 'filesystem_name',
744 'filesystem_id', 'nas_server_id',
745 'snapshot_name', 'snapshot_id', 'path']
746
747 for param in param_list:
748 if self.module.params[param] and \
749 len(self.module.params[param].strip()) == 0:
750 msg = "Please provide valid value for: %s" % param
751 LOG.error(msg)
752 self.module.fail_json(msg=msg)
753
754 def validate_input(self):
755 """ Validate input parameters """
756
757 if self.module.params['nfs_export_name'] and \
758 not self.module.params['snapshot_name'] and \
759 not self.module.params['snapshot_id']:
760 if ((self.module.params['filesystem_name']) and
761 (not self.module.params['nas_server_id'] and
762 not self.module.params['nas_server_name'])):
763 msg = "Please provide nas server id or name along with " \
764 "filesystem name and nfs name"
765 LOG.error(msg)
766 self.module.fail_json(msg=msg)
767
768 if ((not self.module.params['nas_server_id']) and
769 (not self.module.params['nas_server_name']) and
770 (not self.module.params['filesystem_id'])):
771 msg = "Please provide either nas server id/name or " \
772 "filesystem id"
773 LOG.error(msg)
774 self.module.fail_json(msg=msg)
775 self.validate_module_attributes()
776 self.validate_host_access_input_params()
777
778 def get_nfs_id_or_name(self):
779 """ Provide nfs_export_id or nfs_export_name user given value
780
781 :return: value provided by user in nfs_export_id/nfs_export_name
782 :rtype: str
783 """
784 if self.module.params['nfs_export_id']:
785 return self.module.params['nfs_export_id']
786 return self.module.params['nfs_export_name']
787
788 def get_nas_from_given_input(self):
789 """ Get nas server object
790
791 :return: nas server object
792 :rtype: UnityNasServer
793 """
794 LOG.info("Getting nas server details")
795 if not self.module.params['nas_server_id'] and not \
796 self.module.params['nas_server_name']:
797 return None
798 id_or_name = self.module.params['nas_server_id'] if \
799 self.module.params['nas_server_id'] else self.module.params[
800 'nas_server_name']
801 try:
802 nas = self.unity.get_nas_server(
803 _id=self.module.params['nas_server_id'],
804 name=self.module.params['nas_server_name'])
805 except utils.UnityResourceNotFoundError as e:
806 # In case of incorrect name
807 msg = "Given nas server not found error: %s" % str(e)
808 LOG.error(msg)
809 self.module.fail_json(msg=msg)
810 except utils.HTTPClientError as e:
811 if e.http_status == 401:
812 msg = "Failed to get nas server: %s due to incorrect " \
813 "username/password error: %s" % (id_or_name, str(e))
814 else:
815 msg = "Failed to get nas server: %s error: %s" % (
816 id_or_name, str(e))
817 LOG.error(msg)
818 self.module.fail_json(msg=msg)
819 except Exception as e:
820 msg = "Failed to get nas server: %s error: %s" % (
821 id_or_name, str(e))
822 LOG.error(msg)
823 self.module.fail_json(msg=msg)
824
825 if nas and not nas.existed:
826 # In case of incorrect id, sdk return nas object whose attribute
827 # existed=false, instead of raising UnityResourceNotFoundError
828 msg = "Please check nas details it does not exists"
829 LOG.error(msg)
830 self.module.fail_json(msg=msg)
831
832 LOG.info("Got nas server details")
833 return nas
834
835 def get_nfs_share(self, id=None, name=None):
836 """ Get the nfs export
837
838 :return: nfs_export object if nfs exists else None
839 :rtype: UnityNfsShare or None
840 """
841 try:
842 if not id and not name:
843 msg = "Please give nfs id/name"
844 LOG.error(msg)
845 self.module.fail_json(msg=msg)
846
847 id_or_name = id if id else name
848 LOG.info("Getting nfs export: %s", id_or_name)
849 if id:
850 # Get nfs details from nfs ID
851 if self.is_given_nfs_for_fs:
852 nfs = self.unity.get_nfs_share(
853 _id=id, filesystem=self.fs_obj)
854 elif self.is_given_nfs_for_fs is False:
855 # nfs from snap
856 nfs = self.unity.get_nfs_share(_id=id, snap=self.snap_obj)
857 else:
858 nfs = self.unity.get_nfs_share(_id=id)
859 else:
860 # Get nfs details from nfs name
861 if self.is_given_nfs_for_fs:
862 nfs = self.unity.get_nfs_share(
863 name=name, filesystem=self.fs_obj)
864 elif self.is_given_nfs_for_fs is False:
865 # nfs from snap
866 nfs = self.unity.get_nfs_share(
867 name=name, snap=self.snap_obj)
868 else:
869 nfs = self.unity.get_nfs_share(name=name)
870
871 if isinstance(nfs, utils.UnityNfsShareList):
872 # This block will be executed, when we are trying to get nfs
873 # details using nfs name & nas server.
874 nfs_list = nfs
875 LOG.info("Multiple nfs export with same name: %s "
876 "found", id_or_name)
877 if self.nas_obj:
878 for n in nfs_list:
879 if n.filesystem.nas_server == self.nas_obj:
880 return n
881 msg = "Multiple nfs share with same name: %s found. " \
882 "Given nas server is not correct. Please check"
883 else:
884 msg = "Multiple nfs share with same name: %s found. " \
885 "Please give nas server"
886 else:
887 # nfs is instance of UnityNfsShare class
888 if nfs and nfs.existed:
889 if self.nas_obj and nfs.filesystem.nas_server != \
890 self.nas_obj:
891 msg = "nfs found but nas details given is incorrect"
892 LOG.error(msg)
893 self.module.fail_json(msg=msg)
894 LOG.info("Successfully got nfs share for: %s", id_or_name)
895 return nfs
896 elif nfs and not nfs.existed:
897 # in case of incorrect id, sdk returns nfs object whose
898 # attribute existed=False
899 msg = "Please check incorrect nfs id is given"
900 else:
901 msg = "Failed to get nfs share: %s" % id_or_name
902 except utils.UnityResourceNotFoundError as e:
903 msg = "NFS share: %(id_or_name)s not found " \
904 "error: %(err)s" % {'id_or_name': id_or_name, 'err': str(e)}
905 LOG.info(str(msg))
906 return None
907 except utils.HTTPClientError as e:
908 if e.http_status == 401:
909 msg = "Failed to get nfs share: %s due to incorrect " \
910 "username/password error: %s" % (id_or_name, str(e))
911 else:
912 msg = "Failed to get nfs share: %s error: %s" % (id_or_name,
913 str(e))
914 except utils.StoropsConnectTimeoutError as e:
915 msg = "Failed to get nfs share: %s check unispherehost IP: %s " \
916 "error: %s" % (id_or_name,
917 self.module.params['nfs_export_id'], str(e))
918 except Exception as e:
919 msg = "Failed to get nfs share: %s error: %s" % (id_or_name,
920 str(e))
921 LOG.error(msg)
922 self.module.fail_json(msg=msg)
923
924 def delete_nfs_share(self, nfs_obj):
925 """ Delete nfs share
926
927 :param nfs: NFS share obj
928 :type nfs: UnityNfsShare
929 :return: None
930 """
931 try:
932 LOG.info("Deleting nfs share: %s", self.get_nfs_id_or_name())
933 nfs_obj.delete()
934 LOG.info("Deleted nfs share")
935 except Exception as e:
936 msg = "Failed to delete nfs share, error: %s" % str(e)
937 LOG.error(msg)
938 self.module.fail_json(msg=msg)
939
940 def get_filesystem(self):
941 """ Get filesystem obj
942
943 :return: filesystem obj
944 :rtype: UnityFileSystem
945 """
946 if self.module.params['filesystem_id']:
947 id_or_name = self.module.params['filesystem_id']
948 elif self.module.params['filesystem_name']:
949 id_or_name = self.module.params['filesystem_name']
950 else:
951 msg = "Please provide filesystem ID/name, to get filesystem"
952 LOG.error(msg)
953 self.module.fail_json(msg=msg)
954
955 try:
956 if self.module.params['filesystem_name']:
957 if not self.nas_obj:
958 err_msg = "NAS Server is required to get the filesystem"
959 LOG.error(err_msg)
960 self.module.fail_json(msg=err_msg)
961 LOG.info("Getting filesystem by name: %s", id_or_name)
962 fs_obj = self.unity.get_filesystem(
963 name=self.module.params['filesystem_name'],
964 nas_server=self.nas_obj)
965 elif self.module.params['filesystem_id']:
966 LOG.info("Getting filesystem by ID: %s", id_or_name)
967 fs_obj = self.unity.get_filesystem(
968 _id=self.module.params['filesystem_id'])
969 except utils.UnityResourceNotFoundError as e:
970 msg = "Filesystem: %s not found error: %s" % (
971 id_or_name, str(e))
972 LOG.error(msg)
973 self.module.fail_json(msg=msg)
974 except utils.HTTPClientError as e:
975 if e.http_status == 401:
976 msg = "Failed to get filesystem due to incorrect " \
977 "username/password error: %s" % str(e)
978 else:
979 msg = "Failed to get filesystem error: %s" % str(e)
980 LOG.error(msg)
981 except Exception as e:
982 msg = "Failed to get filesystem: %s error: %s" % (
983 id_or_name, str(e))
984 LOG.error(msg)
985 self.module.fail_json(msg=msg)
986
987 if fs_obj and fs_obj.existed:
988 LOG.info("Got the filesystem: %s", id_or_name)
989 return fs_obj
990 else:
991 msg = "Filesystem: %s does not exists" % id_or_name
992 LOG.error(msg)
993 self.module.fail_json(msg=msg)
994
995 def get_snapshot(self):
996 """ Get snapshot obj
997
998 :return: Snapshot obj
999 :rtype: UnitySnap
1000 """
1001 if self.module.params['snapshot_id']:
1002 id_or_name = self.module.params['snapshot_id']
1003 elif self.module.params['snapshot_name']:
1004 id_or_name = self.module.params['snapshot_name']
1005 else:
1006 msg = "Please provide snapshot ID/name, to get snapshot"
1007 LOG.error(msg)
1008 self.module.fail_json(msg=msg)
1009
1010 LOG.info("Getting snapshot: %s", id_or_name)
1011 try:
1012 if id_or_name:
1013 snap_obj = self.unity.get_snap(
1014 _id=self.module.params['snapshot_id'],
1015 name=self.module.params['snapshot_name'])
1016 else:
1017 msg = "Failed to get the snapshot. Please provide snapshot " \
1018 "details"
1019 LOG.error(msg)
1020 self.module.fail_json(msg=msg)
1021 except utils.UnityResourceNotFoundError as e:
1022 msg = "Failed to get snapshot: %s error: %s" % (id_or_name,
1023 str(e))
1024 LOG.error(msg)
1025 self.module.fail_json(msg=msg)
1026 except utils.HTTPClientError as e:
1027 if e.http_status == 401:
1028 msg = "Failed to get snapshot due to incorrect " \
1029 "username/password error: %s" % str(e)
1030 else:
1031 msg = "Failed to get snapshot error: %s" % str(e)
1032 LOG.error(msg)
1033 except Exception as e:
1034 msg = "Failed to get snapshot: %s error: %s" % (id_or_name,
1035 str(e))
1036 LOG.error(msg)
1037 self.module.fail_json(msg=msg)
1038
1039 if snap_obj and snap_obj.existed:
1040 LOG.info("Successfully got the snapshot: %s", id_or_name)
1041 return snap_obj
1042 else:
1043 msg = "Snapshot: %s does not exists" % id_or_name
1044 LOG.error(msg)
1045 self.module.fail_json(msg=msg)
1046
1047 def get_host_obj(self, host_id=None, host_name=None, ip_address=None):
1048 """
1049 Get host object
1050 :param host_id: ID of the host
1051 :param host_name: Name of the host
1052 :param ip_address: Network address of the host
1053 :return: Host object
1054 :rtype: object
1055 """
1056 try:
1057 host_obj = None
1058 host = None
1059 if host_id:
1060 host = host_id
1061 host_obj = self.unity.get_host(_id=host_id)
1062 elif host_name:
1063 host = host_name
1064 host_obj = self.unity.get_host(name=host_name)
1065 elif ip_address:
1066 host = ip_address
1067 host_obj = self.unity.get_host(address=ip_address)
1068
1069 if host_obj and host_obj.existed:
1070 LOG.info("Successfully got host: %s", host_obj.name)
1071 return host_obj
1072 else:
1073 msg = f'Host : {host} does not exists'
1074 LOG.error(msg)
1075 self.module.fail_json(msg=msg)
1076
1077 except Exception as e:
1078 msg = f'Failed to get host {host}, error: {e}'
1079 LOG.error(msg)
1080 self.module.fail_json(msg=msg)
1081
1082 def get_host_access_string_value(self, host_dict):
1083 """
1084 Form host access string
1085 :host_dict Host access type info
1086 :return Host access data in string
1087 """
1088 if host_dict.get("host_id"):
1089 return self.get_host_obj(host_id=(host_dict.get("host_id"))).name + ','
1090 elif host_dict.get("host_name"):
1091 return host_dict.get(
1092 "host_name") + ','
1093 elif host_dict.get("ip_address"):
1094 return host_dict.get(
1095 "ip_address") + ','
1096 elif host_dict.get("subnet"):
1097 return host_dict.get(
1098 "subnet") + ','
1099 elif host_dict.get("domain"):
1100 return "*." + host_dict.get(
1101 "domain") + ','
1102 elif host_dict.get("netgroup"):
1103 return "@" + host_dict.get(
1104 "netgroup") + ','
1105
1106 def get_host_obj_value(self, host_dict):
1107 """
1108 Form host access value using host object
1109 :host_dict Host access type info
1110 :return Host object
1111 """
1112 if host_dict.get("host_id"):
1113 return self.get_host_obj(host_id=host_dict.get("host_id"))
1114 elif host_dict.get("host_name"):
1115 return self.get_host_obj(host_name=host_dict.get("host_name"))
1116 elif host_dict.get("ip_address"):
1117 return self.get_host_obj(ip_address=host_dict.get("ip_address"))
1118
1119 def format_host_dict_for_adv_mgmt(self):
1120 """
1121 Form host access for advance management
1122 :return: Formatted Host access type info
1123 :rtype: dict
1124 """
1125 result_host = {}
1126 for param in list(self.host_param_mapping.keys()):
1127 if self.module.params[param]:
1128 result_host[param] = []
1129 for host_dict in self.module.params[param]:
1130 result_host[param].append(self.get_host_obj_value(host_dict))
1131
1132 if 'read_only_root_hosts' in result_host:
1133 result_host['read_only_root_access_hosts'] = result_host.pop('read_only_root_hosts')
1134 if 'read_write_root_hosts' in result_host:
1135 result_host['root_access_hosts'] = result_host.pop('read_write_root_hosts')
1136 return result_host
1137
1138 def format_host_dict_for_non_adv_mgmt(self):
1139 """
1140 Form host access for non advance management option
1141 :return: Formatted Host access type info
1142 :rtype: dict
1143 """
1144 result_host = {}
1145 for param in list(self.host_param_mapping.keys()):
1146 if self.module.params[param]:
1147 result_host[param] = ''
1148 for host_dict in self.module.params[param]:
1149 result_host[param] += self.get_host_access_string_value(host_dict)
1150
1151 if result_host != {}:
1152 # Since we are supporting HOST STRING parameters instead of HOST
1153 # parameters, so lets change given input HOST parameter name to
1154 # HOST STRING parameter name and strip trailing ','
1155 result_host = {self.host_param_mapping[k]: v[:-1] for k, v in result_host.items()}
1156 return result_host
1157
1158 def get_host_dict_from_pb(self):
1159 """ Traverse all given hosts params and provides with host dict,
1160 which has respective host str param name with its value
1161 required by SDK
1162
1163 :return: dict with key named as respective host str param name & value
1164 required by SDK
1165 :rtype: dict
1166 """
1167 LOG.info("Getting host parameters")
1168 result_host = {}
1169 if self.module.params['host_state']:
1170 if not self.module.params['adv_host_mgmt_enabled']:
1171 result_host = self.format_host_dict_for_non_adv_mgmt()
1172 else:
1173 result_host = self.format_host_dict_for_adv_mgmt()
1174 return result_host
1175
1176 def get_adv_param_from_pb(self):
1177 """ Provide all the advance parameters named as required by SDK
1178
1179 :return: all given advanced parameters
1180 :rtype: dict
1181 """
1182 param = {}
1183 LOG.info("Getting all given advance parameter")
1184 host_dict = self.get_host_dict_from_pb()
1185 if host_dict:
1186 param.update(host_dict)
1187
1188 fields = ('description', 'anonymous_uid', 'anonymous_gid')
1189 for field in fields:
1190 if self.module.params[field] is not None:
1191 param[field] = self.module.params[field]
1192
1193 if self.module.params['min_security'] and self.module.params[
1194 'min_security'] in utils.NFSShareSecurityEnum.__members__:
1195 LOG.info("Getting min_security object from NFSShareSecurityEnum")
1196 param['min_security'] = utils.NFSShareSecurityEnum[
1197 self.module.params['min_security']]
1198
1199 if self.module.params['default_access']:
1200 param['default_access'] = self.get_default_access()
1201
1202 LOG.info("Successfully got advance parameter: %s", param)
1203 return param
1204
1205 def get_default_access(self):
1206 LOG.info("Getting default_access object from "
1207 "NFSShareDefaultAccessEnum")
1208 default_access = self.default_access.get(
1209 self.module.params['default_access'],
1210 self.module.params['default_access'])
1211 try:
1212 return utils.NFSShareDefaultAccessEnum[default_access]
1213 except KeyError as e:
1214 msg = "default_access: %s not found error: %s" % (
1215 default_access, str(e))
1216 LOG.error(msg)
1217 self.module.fail_json(msg)
1218
1219 def correct_payload_as_per_sdk(self, payload, nfs_details=None):
1220 """ Correct payload keys as required by SDK
1221
1222 :param payload: Payload used for create/modify operation
1223 :type payload: dict
1224 :param nfs_details: NFS details
1225 :type nfs_details: dict
1226 :return: Payload required by SDK
1227 :rtype: dict
1228 """
1229 ouput_host_param = self.host_param_mapping.values()
1230 if set(payload.keys()) & set(ouput_host_param):
1231 if not nfs_details or (nfs_details and nfs_details['export_option'] != 1):
1232 payload['export_option'] = 1
1233 if 'read_write_root_hosts_string' in payload:
1234 # SDK have param named 'root_access_hosts_string' instead of
1235 # 'read_write_root_hosts_string'
1236 payload['root_access_hosts_string'] = payload.pop(
1237 'read_write_root_hosts_string')
1238
1239 return payload
1240
1241 def create_nfs_share_from_filesystem(self):
1242 """ Create nfs share from given filesystem
1243
1244 :return: nfs_share object
1245 :rtype: UnityNfsShare
1246 """
1247
1248 name = self.module.params['nfs_export_name']
1249 path = self.module.params['path']
1250
1251 if not name or not path:
1252 msg = "Please provide name and path both for create"
1253 LOG.error(msg)
1254 self.module.fail_json(msg=msg)
1255
1256 param = self.get_adv_param_from_pb()
1257 if 'default_access' in param:
1258 # create nfs from FILESYSTEM take 'share_access' as param in SDK
1259 param['share_access'] = param.pop('default_access')
1260 LOG.info("Param name: 'share_access' is used instead of "
1261 "'default_access' in SDK so changed")
1262
1263 param = self.correct_payload_as_per_sdk(param)
1264
1265 LOG.info("Creating nfs share from filesystem with param: %s", param)
1266 try:
1267 nfs_obj = utils.UnityNfsShare.create(
1268 cli=self.cli, name=name, fs=self.fs_obj, path=path, **param)
1269 LOG.info("Successfully created nfs share: %s", nfs_obj)
1270 return nfs_obj
1271 except utils.UnityNfsShareNameExistedError as e:
1272 LOG.error(str(e))
1273 self.module.fail_json(msg=str(e))
1274 except Exception as e:
1275 msg = "Failed to create nfs share: %s error: %s" % (name, str(e))
1276 LOG.error(msg)
1277 self.module.fail_json(msg=msg)
1278
1279 def create_nfs_share_from_snapshot(self):
1280 """ Create nfs share from given snapshot
1281
1282 :return: nfs_share object
1283 :rtype: UnityNfsShare
1284 """
1285
1286 name = self.module.params['nfs_export_name']
1287 path = self.module.params['path']
1288
1289 if not name or not path:
1290 msg = "Please provide name and path both for create"
1291 LOG.error(msg)
1292 self.module.fail_json(msg=msg)
1293
1294 param = self.get_adv_param_from_pb()
1295
1296 param = self.correct_payload_as_per_sdk(param)
1297
1298 LOG.info("Creating nfs share from snap with param: %s", param)
1299 try:
1300 nfs_obj = utils.UnityNfsShare.create_from_snap(
1301 cli=self.cli, name=name, snap=self.snap_obj, path=path, **param)
1302 LOG.info("Successfully created nfs share: %s", nfs_obj)
1303 return nfs_obj
1304 except utils.UnityNfsShareNameExistedError as e:
1305 LOG.error(str(e))
1306 self.module.fail_json(msg=str(e))
1307 except Exception as e:
1308 msg = "Failed to create nfs share: %s error: %s" % (name, str(e))
1309 LOG.error(msg)
1310 self.module.fail_json(msg=msg)
1311
1312 def create_nfs_share(self):
1313 """ Create nfs share from either filesystem/snapshot
1314
1315 :return: nfs_share object
1316 :rtype: UnityNfsShare
1317 """
1318 if self.is_given_nfs_for_fs:
1319 # Share to be created from filesystem
1320 return self.create_nfs_share_from_filesystem()
1321 elif self.is_given_nfs_for_fs is False:
1322 # Share to be created from snapshot
1323 return self.create_nfs_share_from_snapshot()
1324 else:
1325 msg = "Please provide filesystem or filesystem snapshot to create NFS export"
1326 LOG.error(msg)
1327 self.module.fail_json(msg=msg)
1328
1329 def convert_host_str_to_list(self, host_str):
1330 """ Convert host_str which have comma separated hosts to host_list with
1331 ip4/ip6 host obj if IP4/IP6 like string found
1332
1333 :param host_str: hosts str separated by comma
1334 :return: hosts list, which may contains IP4/IP6 object if given in
1335 host_str
1336 :rytpe: list
1337 """
1338 if not host_str:
1339 LOG.debug("Empty host_str given")
1340 return []
1341
1342 host_list = []
1343 try:
1344 for h in host_str.split(","):
1345 version = get_ip_version(h)
1346 if version == 4:
1347 h = u'{0}'.format(h)
1348 h = IPv4Network(h, strict=False)
1349 elif version == 6:
1350 h = u'{0}'.format(h)
1351 h = IPv6Network(h, strict=False)
1352 host_list.append(h)
1353 except Exception as e:
1354 msg = "Error while converting host_str: %s to list error: %s" % (
1355 host_str, str(e))
1356 LOG.error(msg)
1357 self.module.fail_json(msg=msg)
1358 return host_list
1359
1360 def add_host_dict_for_adv(self, existing_host_dict, new_host_dict):
1361 """ Compares & adds up new hosts with the existing ones and provide
1362 the final consolidated hosts for advance host management
1363
1364 :param existing_host_dict: All hosts params details which are
1365 associated with existing nfs which to be modified
1366 :type existing_host_dict: dict
1367 :param new_host_dict: All hosts param details which are to be added
1368 :type new_host_dict: dict
1369 :return: consolidated hosts params details which contains newly added
1370 hosts along with the existing ones
1371 :rtype: dict
1372 """
1373 modify_host_dict = {}
1374 for host_access_key in existing_host_dict:
1375 LOG.debug("Checking for param: %s", host_access_key)
1376 new_host_obj_list = new_host_dict[host_access_key]
1377 if new_host_obj_list and not existing_host_dict[host_access_key]:
1378 # Existing nfs host is empty so lets directly add
1379 # new_host_str as it is
1380 LOG.debug("Existing nfs host key: %s is empty, so lets add new host given value as it is", host_access_key)
1381 modify_host_dict[host_access_key] = new_host_obj_list
1382 continue
1383
1384 existing_host_obj_list = [self.get_host_obj(host_id=existing_host_dict['UnityHost']['id'])
1385 for existing_host_dict in existing_host_dict[host_access_key]['UnityHostList']]
1386
1387 if not new_host_obj_list:
1388 LOG.debug("Nothing to add as no host given")
1389 continue
1390
1391 existing_set = set(host.id for host in existing_host_obj_list)
1392 actual_to_add = [new_host for new_host in new_host_obj_list if new_host.id not in existing_set]
1393
1394 if not actual_to_add:
1395 LOG.debug("All host given to be added is already added")
1396 continue
1397
1398 # Lets extends actual_to_add list, which is new with existing
1399 actual_to_add.extend(existing_host_obj_list)
1400 modify_host_dict[host_access_key] = actual_to_add
1401
1402 return modify_host_dict
1403
1404 def add_host_dict_for_non_adv(self, existing_host_dict, new_host_dict):
1405 """ Compares & adds up new hosts with the existing ones and provide
1406 the final consolidated hosts for non advance host management
1407
1408 :param existing_host_dict: All hosts params details which are
1409 associated with existing nfs which to be modified
1410 :type existing_host_dict: dict
1411 :param new_host_dict: All hosts param details which are to be added
1412 :type new_host_dict: dict
1413 :return: consolidated hosts params details which contains newly added
1414 hosts along with the existing ones
1415 :rtype: dict
1416 """
1417 modify_host_dict = {}
1418 for host_access_key in existing_host_dict:
1419 LOG.debug("Checking add host for param: %s", host_access_key)
1420 existing_host_str = existing_host_dict[host_access_key]
1421 existing_host_list = self.convert_host_str_to_list(
1422 existing_host_str)
1423
1424 new_host_str = new_host_dict[host_access_key]
1425 new_host_list = self.convert_host_str_to_list(
1426 new_host_str)
1427
1428 if not new_host_list:
1429 LOG.debug("Nothing to add as no host given")
1430 continue
1431
1432 if new_host_list and not existing_host_list:
1433 # Existing nfs host is empty so lets directly add
1434 # new_host_str as it is
1435 LOG.debug("Existing nfs host key: %s is empty, so lets add new host given value as it is", host_access_key)
1436 modify_host_dict[host_access_key] = new_host_str
1437 continue
1438
1439 actual_to_add = list(set(new_host_list) - set(existing_host_list))
1440 if not actual_to_add:
1441 LOG.debug("All host given to be added is already added")
1442 continue
1443
1444 # Lets extends actual_to_add list, which is new with existing
1445 actual_to_add.extend(existing_host_list)
1446
1447 # Since SDK takes host_str as ',' separated instead of list, so
1448 # lets convert str to list
1449 # Note: explicity str() needed here to convert IP4/IP6 object
1450 modify_host_dict[host_access_key] = ",".join(str(v) for v in actual_to_add)
1451 return modify_host_dict
1452
1453 def remove_host_dict_for_adv(self, existing_host_dict, new_host_dict):
1454 """ Compares & remove new hosts from the existing ones and provide
1455 the remaining hosts for advance host management
1456
1457 :param existing_host_dict: All hosts params details which are
1458 associated with existing nfs which to be modified
1459 :type existing_host_dict: dict
1460 :param new_host_dict: All hosts param details which are to be removed
1461 :type new_host_dict: dict
1462 :return: existing hosts params details from which given new hosts are
1463 removed
1464 :rtype: dict
1465 """
1466 modify_host_dict = {}
1467 for host_access_key in existing_host_dict:
1468 LOG.debug("Checking host for param: %s", host_access_key)
1469 if not existing_host_dict[host_access_key]:
1470 # existing list is already empty, so nothing to remove
1471 LOG.debug("Existing list is already empty, so nothing to remove")
1472 continue
1473
1474 existing_host_obj_list = [self.get_host_obj(host_id=existing_host_dict['UnityHost']['id'])
1475 for existing_host_dict in existing_host_dict[host_access_key]['UnityHostList']]
1476 new_host_obj_list = new_host_dict[host_access_key]
1477
1478 if new_host_obj_list == []:
1479 LOG.debug("Nothing to remove as no host given")
1480 continue
1481
1482 unique_new_host_list = [new_host.id for new_host in new_host_obj_list]
1483 if len(new_host_obj_list) > len(set(unique_new_host_list)):
1484 msg = f'Duplicate host given: {unique_new_host_list} in host param: {host_access_key}'
1485 LOG.error(msg)
1486 self.module.fail_json(msg=msg)
1487
1488 unique_existing_host_list = [host.id for host in existing_host_obj_list]
1489 actual_to_remove = list(set(unique_new_host_list) & set(
1490 unique_existing_host_list))
1491 if not actual_to_remove:
1492 continue
1493
1494 final_host_list = [existing_host for existing_host in existing_host_obj_list if existing_host.id not in unique_new_host_list]
1495
1496 modify_host_dict[host_access_key] = final_host_list
1497
1498 return modify_host_dict
1499
1500 def remove_host_dict_for_non_adv(self, existing_host_dict, new_host_dict):
1501 """ Compares & remove new hosts from the existing ones and provide
1502 the remaining hosts for non advance host management
1503
1504 :param existing_host_dict: All hosts params details which are
1505 associated with existing nfs which to be modified
1506 :type existing_host_dict: dict
1507 :param new_host_dict: All hosts param details which are to be removed
1508 :type new_host_dict: dict
1509 :return: existing hosts params details from which given new hosts are
1510 removed
1511 :rtype: dict
1512 """
1513 modify_host_dict = {}
1514
1515 for host_access_key in existing_host_dict:
1516 LOG.debug("Checking remove host for param: %s", host_access_key)
1517 existing_host_str = existing_host_dict[host_access_key]
1518 existing_host_list = self.convert_host_str_to_list(
1519 existing_host_str)
1520
1521 new_host_str = new_host_dict[host_access_key]
1522 new_host_list = self.convert_host_str_to_list(
1523 new_host_str)
1524
1525 if not new_host_list:
1526 LOG.debug("Nothing to remove as no host given")
1527 continue
1528
1529 if len(new_host_list) > len(set(new_host_list)):
1530 msg = "Duplicate host given: %s in host param: %s" % (
1531 new_host_list, host_access_key)
1532 LOG.error(msg)
1533 self.module.fail_json(msg=msg)
1534
1535 if new_host_list and not existing_host_list:
1536 # existing list is already empty, so nothing to remove
1537 LOG.debug("Existing list is already empty, so nothing to remove")
1538 continue
1539
1540 actual_to_remove = list(set(new_host_list) & set(
1541 existing_host_list))
1542 if not actual_to_remove:
1543 continue
1544
1545 final_host_list = list(set(existing_host_list) - set(
1546 actual_to_remove))
1547
1548 # Since SDK takes host_str as ',' separated instead of list, so
1549 # lets convert str to list
1550 # Note: explicity str() needed here to convert IP4/IP6 object
1551 modify_host_dict[host_access_key] = ",".join(str(v) for v in final_host_list)
1552
1553 return modify_host_dict
1554
1555 def add_host(self, existing_host_dict, new_host_dict):
1556 """ Compares & adds up new hosts with the existing ones and provide
1557 the final consolidated hosts
1558
1559 :param existing_host_dict: All hosts params details which are
1560 associated with existing nfs which to be modified
1561 :type existing_host_dict: dict
1562 :param new_host_dict: All hosts param details which are to be added
1563 :type new_host_dict: dict
1564 :return: consolidated hosts params details which contains newly added
1565 hosts along with the existing ones
1566 :rtype: dict
1567 """
1568 if self.module.params['adv_host_mgmt_enabled']:
1569 modify_host_dict = self.add_host_dict_for_adv(existing_host_dict, new_host_dict)
1570 else:
1571 modify_host_dict = self.add_host_dict_for_non_adv(existing_host_dict, new_host_dict)
1572
1573 return modify_host_dict
1574
1575 def remove_host(self, existing_host_dict, new_host_dict):
1576 """ Compares & remove new hosts from the existing ones and provide
1577 the remaining hosts
1578
1579 :param existing_host_dict: All hosts params details which are
1580 associated with existing nfs which to be modified
1581 :type existing_host_dict: dict
1582 :param new_host_dict: All hosts param details which are to be removed
1583 :type new_host_dict: dict
1584 :return: existing hosts params details from which given new hosts are
1585 removed
1586 :rtype: dict
1587 """
1588 if self.module.params['adv_host_mgmt_enabled']:
1589 modify_host_dict = self.remove_host_dict_for_adv(existing_host_dict, new_host_dict)
1590 else:
1591 modify_host_dict = self.remove_host_dict_for_non_adv(existing_host_dict, new_host_dict)
1592
1593 return modify_host_dict
1594
1595 def modify_nfs_share(self, nfs_obj):
1596 """ Modify given nfs share
1597
1598 :param nfs_obj: NFS share obj
1599 :type nfs_obj: UnityNfsShare
1600 :return: tuple(bool, nfs_obj)
1601 - bool: indicates whether nfs_obj is modified or not
1602 - nfs_obj: same nfs_obj if not modified else modified nfs_obj
1603 :rtype: tuple
1604 """
1605 modify_param = {}
1606 LOG.info("Modifying nfs share")
1607
1608 nfs_details = nfs_obj._get_properties()
1609 fields = ('description', 'anonymous_uid', 'anonymous_gid')
1610 for field in fields:
1611 if self.module.params[field] is not None and \
1612 self.module.params[field] != nfs_details[field]:
1613 modify_param[field] = self.module.params[field]
1614
1615 if self.module.params['min_security'] and self.module.params[
1616 'min_security'] != nfs_obj.min_security.name:
1617 modify_param['min_security'] = utils.NFSShareSecurityEnum[
1618 self.module.params['min_security']]
1619
1620 if self.module.params['default_access']:
1621 default_access = self.get_default_access()
1622 if default_access != nfs_obj.default_access:
1623 modify_param['default_access'] = default_access
1624
1625 new_host_dict = self.get_host_dict_from_pb()
1626 if new_host_dict:
1627 try:
1628 if is_nfs_have_host_with_host_obj(nfs_details) and not self.module.params['adv_host_mgmt_enabled']:
1629 msg = "Modification of nfs host is restricted using adv_host_mgmt_enabled as false since nfs " \
1630 "already have host added using host obj"
1631 LOG.error(msg)
1632 self.module.fail_json(msg=msg)
1633 elif is_nfs_have_host_with_host_string(nfs_details) and self.module.params['adv_host_mgmt_enabled']:
1634 msg = "Modification of nfs host is restricted using adv_host_mgmt_enabled as true since nfs " \
1635 "already have host added without host obj"
1636 LOG.error(msg)
1637 self.module.fail_json(msg=msg)
1638 LOG.info("Extracting same given param from nfs")
1639 existing_host_dict = {k: nfs_details[k] for k in new_host_dict}
1640 except KeyError as e:
1641 msg = "Failed to extract key-value from current nfs: %s" % \
1642 str(e)
1643 LOG.error(msg)
1644 self.module.fail_json(msg=msg)
1645
1646 if self.module.params['host_state'] == HOST_STATE_LIST[0]:
1647 # present-in-export
1648 LOG.info("Getting host to be added")
1649 modify_host_dict = self.add_host(existing_host_dict, new_host_dict)
1650 else:
1651 # absent-in-export
1652 LOG.info("Getting host to be removed")
1653 modify_host_dict = self.remove_host(existing_host_dict, new_host_dict)
1654
1655 if modify_host_dict:
1656 modify_param.update(modify_host_dict)
1657
1658 if not modify_param:
1659 LOG.info("Existing nfs attribute value is same as given input, "
1660 "so returning same nfs object - idempotency case")
1661 return False, nfs_obj
1662
1663 modify_param = self.correct_payload_as_per_sdk(
1664 modify_param, nfs_details)
1665
1666 try:
1667 resp = nfs_obj.modify(**modify_param)
1668 resp.raise_if_err()
1669 except Exception as e:
1670 msg = "Failed to modify nfs error: %s" % str(e)
1671 LOG.error(msg)
1672 self.module.fail_json(msg=msg)
1673
1674 return True, self.get_nfs_share(id=nfs_obj.id)
1675
1676 def perform_module_operation(self):
1677 """ Perform different actions on nfs based on user parameter
1678 chosen in playbook """
1679
1680 changed = False
1681 nfs_share_details = {}
1682
1683 self.validate_input()
1684
1685 self.nas_obj = None
1686 if self.module.params['nas_server_id'] or self.module.params[
1687 'nas_server_name']:
1688 self.nas_obj = self.get_nas_from_given_input()
1689
1690 self.fs_obj = None
1691 self.snap_obj = None
1692 if self.is_given_nfs_for_fs:
1693 self.fs_obj = self.get_filesystem()
1694 elif self.is_given_nfs_for_fs is False:
1695 self.snap_obj = self.get_snapshot()
1696
1697 # Get nfs Share
1698 nfs_obj = self.get_nfs_share(
1699 id=self.module.params['nfs_export_id'],
1700 name=self.module.params['nfs_export_name']
1701 )
1702
1703 # Delete nfs Share
1704 if self.module.params['state'] == STATE_LIST[1]:
1705 if nfs_obj:
1706 # delete_nfs_share() does not return any value
1707 # In case of successful delete, lets nfs_obj set None
1708 # to avoid fetching and displaying attribute
1709 nfs_obj = self.delete_nfs_share(nfs_obj)
1710 changed = True
1711 elif not nfs_obj:
1712 # create
1713 nfs_obj = self.create_nfs_share()
1714 changed = True
1715 else:
1716 # modify
1717 changed, nfs_obj = self.modify_nfs_share(nfs_obj)
1718
1719 # Get display attributes
1720 if self.module.params['state'] and nfs_obj:
1721 nfs_share_details = get_nfs_share_display_attrs(nfs_obj)
1722
1723 result = {"changed": changed,
1724 "nfs_share_details": nfs_share_details}
1725 self.module.exit_json(**result)
1726
1727
1728 def get_nfs_share_display_attrs(nfs_obj):
1729 """ Provide nfs share attributes for display
1730
1731 :param nfs: NFS share obj
1732 :type nfs: UnityNfsShare
1733 :return: nfs_share_details
1734 :rtype: dict
1735 """
1736 LOG.info("Getting nfs share details from nfs share object")
1737 nfs_share_details = nfs_obj._get_properties()
1738
1739 # Adding filesystem_name to nfs_share_details
1740 LOG.info("Updating filesystem details")
1741 nfs_share_details['filesystem']['UnityFileSystem']['name'] = \
1742 nfs_obj.filesystem.name
1743 if 'id' not in nfs_share_details['filesystem']['UnityFileSystem']:
1744 nfs_share_details['filesystem']['UnityFileSystem']['id'] = \
1745 nfs_obj.filesystem.id
1746
1747 # Adding nas server details
1748 LOG.info("Updating nas server details")
1749 nas_details = nfs_obj.filesystem._get_properties()['nas_server']
1750 nas_details['UnityNasServer']['name'] = \
1751 nfs_obj.filesystem.nas_server.name
1752 nfs_share_details['nas_server'] = nas_details
1753
1754 # Adding snap.id & snap.name if nfs_obj is for snap
1755 if is_nfs_obj_for_snap(nfs_obj):
1756 LOG.info("Updating snap details")
1757 nfs_share_details['snap']['UnitySnap']['id'] = nfs_obj.snap.id
1758 nfs_share_details['snap']['UnitySnap']['name'] = nfs_obj.snap.name
1759
1760 LOG.info("Successfully updated nfs share details")
1761 return nfs_share_details
1762
1763
1764 def is_nfs_have_host_with_host_obj(nfs_details):
1765 """ Check whether nfs host is already added using host obj
1766
1767 :param nfs_details: nfs details
1768 :return: True if nfs have host already added with host obj else False
1769 :rtype: bool
1770 """
1771 host_obj_params = ('no_access_hosts', 'read_only_hosts',
1772 'read_only_root_access_hosts', 'read_write_hosts',
1773 'root_access_hosts')
1774 for host_obj_param in host_obj_params:
1775 if nfs_details.get(host_obj_param):
1776 return True
1777 return False
1778
1779
1780 def is_nfs_have_host_with_host_string(nfs_details):
1781 """ Check whether nfs host is already added using host by string method
1782
1783 :param nfs_details: nfs details
1784 :return: True if nfs have host already added with host string method else False
1785 :rtype: bool
1786 """
1787 host_obj_params = (
1788 'no_access_hosts_string',
1789 'read_only_hosts_string',
1790 'read_only_root_hosts_string',
1791 'read_write_hosts_string',
1792 'read_write_root_hosts_string'
1793 )
1794 for host_obj_param in host_obj_params:
1795 if nfs_details.get(host_obj_param):
1796 return True
1797 return False
1798
1799
1800 def get_ip_version(val):
1801 try:
1802 val = u'{0}'.format(val)
1803 ip = ip_network(val, strict=False)
1804 return ip.version
1805 except ValueError:
1806 return 0
1807
1808
1809 def is_nfs_obj_for_fs(nfs_obj):
1810 """ Check whether the nfs_obj if for filesystem
1811
1812 :param nfs_obj: NFS share object
1813 :return: True if nfs_obj is of filesystem type
1814 :rtype: bool
1815 """
1816 if nfs_obj.type == utils.NFSTypeEnum.NFS_SHARE:
1817 return True
1818 return False
1819
1820
1821 def is_nfs_obj_for_snap(nfs_obj):
1822 """ Check whether the nfs_obj if for snapshot
1823
1824 :param nfs_obj: NFS share object
1825 :return: True if nfs_obj is of snapshot type
1826 :rtype: bool
1827 """
1828 if nfs_obj.type == utils.NFSTypeEnum.NFS_SNAPSHOT:
1829 return True
1830 return False
1831
1832
1833 def get_nfs_parameters():
1834 """ Provides parameters required for the NFS share module on Unity """
1835
1836 return dict(
1837 nfs_export_name=dict(required=False, type='str'),
1838 nfs_export_id=dict(required=False, type='str'),
1839 filesystem_id=dict(required=False, type='str'),
1840 filesystem_name=dict(required=False, type='str'),
1841 snapshot_id=dict(required=False, type='str'),
1842 snapshot_name=dict(required=False, type='str'),
1843 nas_server_id=dict(required=False, type='str'),
1844 nas_server_name=dict(required=False, type='str'),
1845 path=dict(required=False, type='str', no_log=True),
1846 description=dict(required=False, type='str'),
1847 default_access=dict(required=False, type='str',
1848 choices=DEFAULT_ACCESS_LIST),
1849 min_security=dict(required=False, type='str',
1850 choices=MIN_SECURITY_LIST),
1851 adv_host_mgmt_enabled=dict(required=False, type='bool', default=None),
1852 no_access_hosts=HOST_DICT,
1853 read_only_hosts=HOST_DICT,
1854 read_only_root_hosts=HOST_DICT,
1855 read_write_hosts=HOST_DICT,
1856 read_write_root_hosts=HOST_DICT,
1857 host_state=dict(required=False, type='str', choices=HOST_STATE_LIST),
1858 anonymous_uid=dict(required=False, type='int'),
1859 anonymous_gid=dict(required=False, type='int'),
1860 state=dict(required=True, type='str', choices=STATE_LIST)
1861 )
1862
1863
1864 def main():
1865 """ Create UnityNFS object and perform action on it
1866 based on user input from playbook"""
1867 obj = NFS()
1868 obj.perform_module_operation()
1869
1870
1871 if __name__ == '__main__':
1872 main()