Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_lun.py

raw
1 #!/usr/bin/python
2
3 # (c) 2017-2026, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 module: na_ontap_lun
12
13 short_description: NetApp ONTAP manage LUNs
14 extends_documentation_fragment:
15 - netapp.ontap.netapp.na_ontap
16 version_added: 2.6.0
17 author: NetApp Ansible Team (@carchi8py) <[email protected]>
18
19 description:
20 - Create, destroy, resize LUNs on NetApp ONTAP.
21
22 options:
23
24 state:
25 description:
26 - Whether the specified LUN should exist or not.
27 choices: ['present', 'absent']
28 type: str
29 default: present
30
31 name:
32 description:
33 - The name of the LUN to manage.
34 - Or LUN group name (volume name) when san_application_template is used.
35 required: true
36 type: str
37
38 from_name:
39 description:
40 - The name of the LUN to be renamed.
41 type: str
42 version_added: 20.12.0
43
44 flexvol_name:
45 description:
46 - The name of the FlexVol the LUN should exist on.
47 - Required if san_application_template is not present.
48 - Not allowed if san_application_template is present.
49 - Not supported for ASA r2 system.
50 type: str
51 aliases: ['volume_name']
52
53 qtree_name:
54 description:
55 - Specifies the name of the Qtree that contains the new LUN.
56 - Not allowed if san_application_template is present.
57 - Only supported with REST.
58 - Qtrees are not supported with ASA r2 system.
59 version_added: 22.8.0
60 type: str
61
62 size:
63 description:
64 - The size of the LUN in C(size_unit).
65 - Required when creating a single LUN if application template is not used.
66 type: int
67
68 size_unit:
69 description:
70 - The unit used to interpret the size parameter.
71 choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
72 default: 'gb'
73 type: str
74
75 comment:
76 description:
77 - Optional descriptive comment for the LUN.
78 type: str
79 version_added: 21.2.0
80
81 force_resize:
82 description:
83 - Forcibly reduce the size. This is required for reducing the size of the LUN to avoid accidentally
84 reducing the LUN size.
85 - Not supported with REST.
86 type: bool
87
88 force_remove:
89 description:
90 - If "true", override checks that prevent a LUN from being destroyed if it is online and mapped.
91 - If "false", destroying an online and mapped LUN will fail.
92 type: bool
93 default: false
94
95 force_remove_fenced:
96 description:
97 - If "true", override checks that prevent a LUN from being destroyed while it is fenced.
98 - If "false", attempting to destroy a fenced LUN will fail.
99 - The default if not specified is "false". This field is available in Data ONTAP 8.2 and later.
100 - Not supported with REST.
101 type: bool
102
103 vserver:
104 required: true
105 description:
106 - The name of the vserver to use.
107 type: str
108
109 os_type:
110 description:
111 - The os type for the LUN.
112 type: str
113 aliases: ['ostype']
114
115 qos_policy_group:
116 description:
117 - The QoS policy group to be set on the LUN.
118 - With REST, qos_policy_group and qos_adaptive_policy_group are handled as QOS policy.
119 type: str
120 version_added: 20.12.0
121
122 qos_adaptive_policy_group:
123 description:
124 - The adaptive QoS policy group to be set on the LUN.
125 - Defines measurable service level objectives (SLOs) and service level agreements (SLAs) that adjust based on the LUN's allocated space or used space.
126 - Requires ONTAP 9.4 or later.
127 - With REST, qos_policy_group and qos_adaptive_policy_group are handled as QOS policy.
128 type: str
129 version_added: 21.2.0
130
131 space_reserve:
132 description:
133 - This can be set to "false" which will create a LUN without any space being reserved.
134 - Not supported for ASA r2 system. All LUNs are provisioned without a space reservation.
135 type: bool
136 default: true
137
138 space_allocation:
139 description:
140 - This enables support for the SCSI Thin Provisioning features. If the Host and file system do
141 not support this do not enable it.
142 - Not supported for ASA r2 system. All LUNs are provisioned with SCSI thin provisioning enabled.
143 type: bool
144 version_added: 2.7.0
145
146 use_exact_size:
147 description:
148 - This can be set to "false" which will round the LUN >= 450g.
149 type: bool
150 default: true
151 version_added: 20.11.0
152
153 san_application_template:
154 description:
155 - additional options when using the application/applications REST API to create LUNs.
156 - the module is using ZAPI by default, and switches to REST if san_application_template is present.
157 - create one or more LUNs (and the associated volume as needed).
158 - operations at the LUN level are supported, they require to know the LUN short name.
159 - this requires ONTAP 9.8 or higher.
160 - The module partially supports ONTAP 9.7 for create and delete operations, but not for modify (API limitations).
161 - Not supported with ASA r2 system.
162 type: dict
163 version_added: 20.12.0
164 suboptions:
165 name:
166 description: name of the SAN application.
167 type: str
168 required: true
169 igroup_name:
170 description: name of the initiator group through which the contents of this application will be accessed.
171 type: str
172 lun_count:
173 description: number of LUNs in the application component (1 to 32).
174 type: int
175 protection_type:
176 description:
177 - The snasphot policy for the volume supporting the LUNs.
178 type: dict
179 suboptions:
180 local_policy:
181 description:
182 - The snapshot copy policy for the volume.
183 type: str
184 storage_service:
185 description:
186 - The performance service level (PSL) for this volume
187 type: str
188 choices: ['value', 'performance', 'extreme']
189 tiering:
190 description:
191 - Cloud tiering policy.
192 type: dict
193 suboptions:
194 control:
195 description: Storage tiering placement rules for the container.
196 choices: ['required', 'best_effort', 'disallowed']
197 type: str
198 policy:
199 description:
200 - Cloud tiering policy.
201 choices: ['all', 'auto', 'none', 'snapshot-only']
202 type: str
203 object_stores:
204 description: list of object store names for tiering.
205 type: list
206 elements: str
207 total_size:
208 description:
209 - The total size of the application component, split across the member LUNs in C(total_size_unit).
210 - Recommended when C(lun_count) is present.
211 - Required when C(lun_count) is present and greater than 1.
212 - Note - if lun_count is equal to 1, and total_size is not present, size is used to maintain backward compatibility.
213 type: int
214 version_added: 21.1.0
215 total_size_unit:
216 description:
217 - The unit used to interpret the total_size parameter.
218 - Defaults to size_unit if not present.
219 choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
220 type: str
221 version_added: 21.1.0
222 use_san_application:
223 description:
224 - Whether to use the application/applications REST/API to create LUNs.
225 - This will default to true if any other suboption is present.
226 type: bool
227 default: true
228 scope:
229 description:
230 - whether the top level name identifies a single LUN or a LUN group (application).
231 - By default, the module will try to make the right choice, but can report extra warnings.
232 - Setting scope to 'application' is required to convert an existing volume to a smart container.
233 - The module reports an error when 'lun' or 'application' is used and the desired action cannot be completed.
234 - The module issues warnings when the default 'auto' is used, and there is ambiguity regarding the desired actions.
235 type: str
236 choices: ['application', 'auto', 'lun']
237 default: auto
238 version_added: 21.2.0
239 exclude_aggregates:
240 description:
241 - The list of aggregate names to exclude when creating a volume.
242 - Requires ONTAP 9.9.1 GA or better.
243 type: list
244 elements: str
245 version_added: 21.7.0
246
247 provisioning_options:
248 description:
249 - Options that are applied to create operation.
250 - Only supported with REST, requires ONTAP 9.16.1 or later.
251 type: dict
252 version_added: 23.2.0
253 suboptions:
254 count:
255 description:
256 - The number of LUNs to provision with these properties.
257 - When provided, the name is considered a prefix, and a suffix of the form _<N> is generated
258 where N is the next available numeric index, starting with 1.
259 type: int
260 auto:
261 description:
262 - If the volume specified in the request does not exist, automatically provision one of appropriate size.
263 - If the volume does exist, resize it to accommodate the new LUN.
264 - Only supported on Unified ONTAP.
265 type: bool
266
267 lambda_config:
268 description:
269 - Configuration parameters for AWS Lambda proxy functionality.
270 - These option and suboptions are only supported with REST.
271 type: dict
272 version_added: 23.3.0
273 suboptions:
274 function_name:
275 description:
276 - The name of the AWS Lambda function to invoke.
277 type: str
278 required: true
279 aws_region:
280 description:
281 - The name of the AWS region.
282 type: str
283 required: true
284 aws_profile:
285 description:
286 - The name of the AWS profile to use for authentication.
287 type: str
288
289 notes:
290 - Compatible with ASA r2 system when using REST for ONTAP releases 9.16.0x onwards.
291 - Module is not idempotent when C(provisioning_options) is set.
292 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
293 '''
294
295 EXAMPLES = """
296 - name: Create LUN
297 netapp.ontap.na_ontap_lun:
298 state: present
299 name: ansibleLUN
300 flexvol_name: ansibleVolume
301 vserver: ansibleVServer
302 size: 5
303 size_unit: mb
304 os_type: linux
305 space_reserve: true
306 hostname: "{{ netapp_hostname }}"
307 username: "{{ netapp_username }}"
308 password: "{{ netapp_password }}"
309
310 - name: Resize LUN
311 netapp.ontap.na_ontap_lun:
312 state: present
313 name: ansibleLUN
314 force_resize: true
315 volume_name: ansibleVolume
316 vserver: ansibleVServer
317 size: 5
318 size_unit: gb
319 hostname: "{{ netapp_hostname }}"
320 username: "{{ netapp_username }}"
321 password: "{{ netapp_password }}"
322
323 - name: Create LUNs using SAN application
324 netapp.ontap.na_ontap_lun:
325 state: present
326 name: ansibleLUN
327 size: 15
328 size_unit: mb
329 os_type: linux
330 space_reserve: false
331 san_application_template:
332 name: san-ansibleLUN
333 igroup_name: testme_igroup
334 lun_count: 3
335 protection_type:
336 local_policy: default
337 exclude_aggregates: aggr0
338 hostname: "{{ netapp_hostname }}"
339 username: "{{ netapp_username }}"
340 password: "{{ netapp_password }}"
341
342 - name: Convert existing volume to SAN application
343 netapp.ontap.na_ontap_lun:
344 state: present
345 name: someVolume
346 size: 22
347 size_unit: mb
348 os_type: linux
349 space_reserve: false
350 san_application_template:
351 name: san-ansibleLUN
352 igroup_name: testme_igroup
353 lun_count: 3
354 protection_type:
355 local_policy: default
356 scope: application
357 hostname: "{{ netapp_hostname }}"
358 username: "{{ netapp_username }}"
359 password: "{{ netapp_password }}"
360
361 - name: Create LUNs
362 netapp.ontap.na_ontap_lun:
363 state: present
364 name: ansibleLUN
365 flexvol_name: ansibleVolume
366 vserver: ansibleVServer
367 size: 5
368 size_unit: mb
369 os_type: linux
370 provisioning_options:
371 count: 2
372 hostname: "{{ netapp_hostname }}"
373 username: "{{ netapp_username }}"
374 password: "{{ netapp_password }}"
375 """
376
377 RETURN = """
378 """
379
380 import copy
381 import traceback
382
383 from ansible.module_utils.basic import AnsibleModule
384 from ansible.module_utils._text import to_native
385 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
386 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
387 from ansible_collections.netapp.ontap.plugins.module_utils.rest_application import RestApplication
388 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
389 from ansible_collections.netapp.ontap.plugins.module_utils import rest_volume
390 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
391 from ansible_collections.netapp.ontap.plugins.module_utils import rest_ontap_personality
392
393 HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
394
395
396 class NetAppOntapLUN:
397 ''' create, modify, delete LUN '''
398
399 def __init__(self):
400
401 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
402 self.argument_spec.update(dict(
403 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
404 name=dict(required=True, type='str'),
405 from_name=dict(required=False, type='str'),
406 size=dict(type='int'),
407 size_unit=dict(default='gb',
408 choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb',
409 'pb', 'eb', 'zb', 'yb'], type='str'),
410 comment=dict(required=False, type='str'),
411 force_resize=dict(type='bool'),
412 force_remove=dict(required=False, type='bool', default=False),
413 force_remove_fenced=dict(type='bool'),
414 flexvol_name=dict(type='str', aliases=['volume_name']),
415 qtree_name=dict(type='str'),
416 vserver=dict(required=True, type='str'),
417 os_type=dict(required=False, type='str', aliases=['ostype']),
418 qos_policy_group=dict(required=False, type='str'),
419 qos_adaptive_policy_group=dict(required=False, type='str'),
420 space_reserve=dict(required=False, type='bool', default=True),
421 space_allocation=dict(required=False, type='bool'),
422 use_exact_size=dict(required=False, type='bool', default=True),
423 san_application_template=dict(type='dict', options=dict(
424 use_san_application=dict(type='bool', default=True),
425 exclude_aggregates=dict(type='list', elements='str'),
426 name=dict(required=True, type='str'),
427 igroup_name=dict(type='str'),
428 lun_count=dict(type='int'),
429 protection_type=dict(type='dict', options=dict(
430 local_policy=dict(type='str'),
431 )),
432 storage_service=dict(type='str', choices=['value', 'performance', 'extreme']),
433 tiering=dict(type='dict', options=dict(
434 control=dict(type='str', choices=['required', 'best_effort', 'disallowed']),
435 policy=dict(type='str', choices=['all', 'auto', 'none', 'snapshot-only']),
436 object_stores=dict(type='list', elements='str') # create only
437 )),
438 total_size=dict(type='int'),
439 total_size_unit=dict(choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb',
440 'pb', 'eb', 'zb', 'yb'], type='str'),
441 scope=dict(type='str', choices=['application', 'auto', 'lun'], default='auto'),
442 )),
443 provisioning_options=dict(type='dict', options=dict(
444 count=dict(required=False, type='int'),
445 auto=dict(required=False, type='bool'),
446 )),
447 ))
448
449 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
450
451 self.module = AnsibleModule(
452 argument_spec=self.argument_spec,
453 required_if=[
454 ['use_lambda', True, ('lambda_config',)]
455 ],
456 supports_check_mode=True,
457 mutually_exclusive=[('qos_policy_group', 'qos_adaptive_policy_group')]
458 )
459
460 # set up state variables
461 self.na_helper = NetAppModule()
462 self.parameters = self.na_helper.set_parameters(self.module.params)
463
464 if self.parameters.get('size') is not None:
465 self.parameters['size'] *= netapp_utils.POW2_BYTE_MAP[self.parameters['size_unit']]
466 if self.na_helper.safe_get(self.parameters, ['san_application_template', 'total_size']) is not None:
467 unit = self.na_helper.safe_get(self.parameters, ['san_application_template', 'total_size_unit'])
468 if unit is None:
469 unit = self.parameters['size_unit']
470 self.parameters['san_application_template']['total_size'] *= netapp_utils.POW2_BYTE_MAP[unit]
471
472 self.debug = {}
473 self.uuid = None
474 # self.debug['got'] = 'empty' # uncomment to enable collecting data
475 self.asa_r2_system = False
476
477 self.rest_api = OntapRestAPI(self.module)
478 # use_exact_size is defaulted to true, but not supported with REST. To get around this we will ignore the variable in rest.
479 unsupported_rest_properties = ['force_resize', 'force_remove_fenced']
480 partially_supported_rest_properties = [['san_application_template', (9, 7)],
481 ['space_allocation', (9, 10)],
482 ['provisioning_options', (9, 16, 1)]]
483 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties,
484 partially_supported_rest_properties)
485 if self.use_rest:
486 if self.rest_api.meets_rest_minimum_version(True, 9, 16, 0):
487 # ASA r2 is only supported from ONTAP releases 9.16.0x onwards
488 self.is_asa_r2_system()
489 if self.asa_r2_system:
490 self.validate_params_asa_r2()
491
492 self.parameters.pop('use_exact_size')
493 if self.parameters.get('qos_adaptive_policy_group') is not None:
494 self.parameters['qos_policy_group'] = self.parameters.pop('qos_adaptive_policy_group')
495 else:
496 if self.parameters.get('use_lambda'):
497 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
498 if not netapp_utils.has_netapp_lib():
499 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
500 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
501 # set default value for ZAPI only supported options.
502 if self.parameters.get('force_resize') is None:
503 self.parameters['force_resize'] = False
504 if self.parameters.get('force_remove_fenced') is None:
505 self.parameters['force_remove_fenced'] = False
506
507 # REST API for application/applications if needed
508 self.rest_app = self.setup_rest_application()
509
510 def is_asa_r2_system(self):
511 ''' checks if the given host is a ASA r2 system or not '''
512 self.asa_r2_system = rest_ontap_personality.is_asa_r2_system(self.rest_api, self.module)
513
514 def validate_params_asa_r2(self):
515 if self.parameters.get('space_reserve') is not None:
516 if not self.parameters['space_reserve']:
517 self.module.warn("Ignoring 'space_reserve' as all LUNs are provisioned without a space reservation for ASA r2 system.")
518 self.parameters.pop('space_reserve')
519 if self.parameters.get('space_allocation') is not None:
520 self.module.warn("Ignoring 'space_allocation' as all LUNs are provisioned with SCSI thin provisioning enabled for ASA r2 system.")
521 self.parameters.pop('space_allocation')
522 if self.parameters.get('flexvol_name') is not None:
523 self.module.warn("Ignoring 'flexvol_name' as volumes are managed internally for ASA r2 system.")
524 self.parameters.pop('flexvol_name')
525 if self.parameters.get('san_application_template') is not None:
526 self.module.warn("Ignoring 'san_application_template' for ASA r2 system.")
527 self.parameters.pop('san_application_template')
528
529 def setup_rest_application(self):
530 use_application_template = self.na_helper.safe_get(self.parameters, ['san_application_template', 'use_san_application'])
531 rest_app = None
532 if self.use_rest:
533 if use_application_template:
534 if self.parameters.get('flexvol_name') is not None:
535 self.module.fail_json(msg="'flexvol_name' option is not supported when san_application_template is present")
536 if self.parameters.get('qtree_name') is not None:
537 self.module.fail_json(msg="'qtree_name' option is not supported when san_application_template is present")
538 name = self.na_helper.safe_get(self.parameters, ['san_application_template', 'name'], allow_sparse_dict=False)
539 rest_app = RestApplication(self.rest_api, self.parameters['vserver'], name)
540 elif self.parameters.get('flexvol_name') is None:
541 if not self.asa_r2_system:
542 self.module.fail_json(msg="flexvol_name option is required when san_application_template is not present")
543 else:
544 if use_application_template:
545 self.module.fail_json(msg="Error: using san_application_template requires ONTAP 9.7 or later and REST must be enabled.")
546 if self.parameters.get('flexvol_name') is None:
547 self.module.fail_json(msg="Error: 'flexvol_name' option is required when using ZAPI.")
548 return rest_app
549
550 def get_luns(self, lun_path=None):
551 """
552 Return list of LUNs matching vserver and volume names.
553
554 :return: list of LUNs in XML format.
555 :rtype: list
556 """
557 if self.use_rest:
558 return self.get_luns_rest(lun_path)
559 luns = []
560 tag = None
561
562 query_details = netapp_utils.zapi.NaElement('lun-info')
563 query_details.add_new_child('vserver', self.parameters['vserver'])
564 if lun_path is not None:
565 query_details.add_new_child('lun_path', lun_path)
566 else:
567 query_details.add_new_child('volume', self.parameters['flexvol_name'])
568 query = netapp_utils.zapi.NaElement('query')
569 query.add_child_elem(query_details)
570
571 while True:
572 lun_info = netapp_utils.zapi.NaElement('lun-get-iter')
573 lun_info.add_child_elem(query)
574 if tag:
575 lun_info.add_new_child('tag', tag, True)
576
577 try:
578 result = self.server.invoke_successfully(lun_info, enable_tunneling=True)
579 except netapp_utils.zapi.NaApiError as exc:
580 self.module.fail_json(msg="Error fetching luns for %s: %s" %
581 (self.parameters['flexvol_name'] if lun_path is None else lun_path, to_native(exc)),
582 exception=traceback.format_exc())
583
584 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
585 attr_list = result.get_child_by_name('attributes-list')
586 luns.extend(attr_list.get_children())
587 tag = result.get_child_content('next-tag')
588 if tag is None:
589 break
590 return luns
591
592 def get_lun_details(self, lun):
593 """
594 Extract LUN details, from XML to python dict
595
596 :return: Details about the lun
597 :rtype: dict
598 """
599 if self.use_rest:
600 return lun
601 return_value = {'size': int(lun.get_child_content('size'))}
602 bool_attr_map = {
603 'is-space-alloc-enabled': 'space_allocation',
604 'is-space-reservation-enabled': 'space_reserve'
605 }
606 for attr in bool_attr_map:
607 value = lun.get_child_content(attr)
608 if value is not None:
609 return_value[bool_attr_map[attr]] = self.na_helper.get_value_for_bool(True, value)
610 str_attr_map = {
611 'comment': 'comment',
612 'multiprotocol-type': 'os_type',
613 'name': 'name',
614 'path': 'path',
615 'qos-policy-group': 'qos_policy_group',
616 'qos-adaptive-policy-group': 'qos_adaptive_policy_group',
617 }
618 for attr in str_attr_map:
619 value = lun.get_child_content(attr)
620 if value is None and attr in ('comment', 'qos-policy-group', 'qos-adaptive-policy-group'):
621 value = ''
622 if value is not None:
623 return_value[str_attr_map[attr]] = value
624
625 return return_value
626
627 def find_lun(self, luns, name, lun_path=None):
628 """
629 Return lun record matching name or path
630
631 :return: lun record
632 :rtype: XML for ZAPI, dict for REST, or None if not found
633 """
634 if luns:
635 for lun in luns:
636 path = lun['path']
637 if lun_path is None:
638 if name == path:
639 return lun
640 _rest, _splitter, found_name = path.rpartition('/')
641 if found_name == name:
642 return lun
643 elif lun_path == path:
644 return lun
645 return None
646
647 def get_lun_by_name(self, name):
648 """
649 Return details about the LUN by name for ASA r2 systems
650
651 :return: Details about the lun
652 :rtype: dict
653 """
654 api = 'storage/luns'
655 query = {
656 'name': name,
657 'svm.name': self.parameters['vserver'],
658 'fields': "comment,lun_maps,name,os_type,qos_policy.name,space,enabled"}
659 record, error = rest_generic.get_one_record(self.rest_api, api, query)
660 if error:
661 self.module.fail_json(msg="Error getting lun %s: %s" % (self.parameters['name'], to_native(error)),
662 exception=traceback.format_exc())
663 if record:
664 return {
665 'uuid': self.na_helper.safe_get(record, ['uuid']),
666 'name': self.na_helper.safe_get(record, ['name']),
667 'path': self.na_helper.safe_get(record, ['name']),
668 'size': self.na_helper.safe_get(record, ['space', 'size']),
669 'comment': self.na_helper.safe_get(record, ['comment']),
670 'os_type': self.na_helper.safe_get(record, ['os_type']),
671 'qos_policy_group': self.na_helper.safe_get(record, ['qos_policy', 'name']),
672 'space_reserve': self.na_helper.safe_get(record, ['space', 'guarantee', 'requested']),
673 'space_allocation': self.na_helper.safe_get(record, ['space', 'scsi_thin_provisioning_support_enabled']),
674 }
675 return None
676
677 def get_lun(self, name, lun_path=None):
678 """
679 Return details about the LUN
680
681 :return: Details about the lun
682 :rtype: dict
683 """
684 if self.asa_r2_system:
685 return self.get_lun_by_name(name)
686 luns = self.get_luns(lun_path)
687 lun = self.find_lun(luns, name, lun_path)
688 if lun is not None:
689 return self.get_lun_details(lun)
690 return None
691
692 def get_luns_from_app(self):
693 app_details, error = self.rest_app.get_application_details()
694 self.fail_on_error(error)
695 if app_details is not None:
696 app_details['paths'] = self.get_lun_paths_from_app()
697 return app_details
698
699 def get_lun_paths_from_app(self):
700 """Get luns path for SAN application"""
701 backing_storage, error = self.rest_app.get_application_component_backing_storage()
702 self.fail_on_error(error)
703 # {'luns': [{'path': '/vol/ansibleLUN/ansibleLUN_1', ...
704 if backing_storage is not None:
705 return [lun['path'] for lun in backing_storage.get('luns', [])]
706 return None
707
708 def get_lun_path_from_backend(self, name):
709 """returns lun path matching name if found in backing_storage
710 retruns None if not found
711 """
712 lun_paths = self.get_lun_paths_from_app()
713 match = "/%s" % name
714 return next((path for path in lun_paths if path.endswith(match)), None)
715
716 def create_san_app_component(self, modify):
717 '''Create SAN application component'''
718 if modify:
719 required_options = ['name']
720 action = 'modify'
721 if 'lun_count' in modify:
722 required_options.append('total_size')
723 else:
724 required_options = ('name', 'total_size')
725 action = 'create'
726 for option in required_options:
727 if self.parameters.get(option) is None:
728 self.module.fail_json(msg="Error: '%s' is required to %s a san application." % (option, action))
729
730 application_component = dict(name=self.parameters['name'])
731 if not modify:
732 application_component['lun_count'] = 1 # default value for create, may be overriden below
733
734 for attr in ('igroup_name', 'lun_count', 'storage_service'):
735 if not modify or attr in modify:
736 value = self.na_helper.safe_get(self.parameters, ['san_application_template', attr])
737 if value is not None:
738 application_component[attr] = value
739 for attr in ('os_type', 'qos_policy_group', 'qos_adaptive_policy_group', 'total_size'):
740 if not self.rest_api.meets_rest_minimum_version(True, 9, 8, 0) and attr in (
741 'os_type',
742 'qos_policy_group',
743 'qos_adaptive_policy_group',
744 ):
745 # os_type and qos are not supported in 9.7 for the SAN application_component
746 continue
747 if not modify or attr in modify:
748 value = self.na_helper.safe_get(self.parameters, [attr])
749 if value is not None:
750 # only one of them can be present at most
751 if attr in ('qos_policy_group', 'qos_adaptive_policy_group'):
752 attr = 'qos'
753 value = dict(policy=dict(name=value))
754 application_component[attr] = value
755 tiering = self.na_helper.safe_get(self.parameters, ['san_application_template', 'tiering'])
756 if tiering is not None and not modify:
757 application_component['tiering'] = {}
758 for attr in ('control', 'policy', 'object_stores'):
759 value = tiering.get(attr)
760 if attr == 'object_stores' and value is not None:
761 value = [dict(name=x) for x in value]
762 if value is not None:
763 application_component['tiering'][attr] = value
764 return application_component
765
766 def create_san_app_body(self, modify=None):
767 '''Create body for san template'''
768 # TODO:
769 # Should we support new_igroups?
770 # It may raise idempotency issues if the REST call fails if the igroup already exists.
771 # And we already have na_ontap_igroups.
772 san = {
773 'application_components': [self.create_san_app_component(modify)],
774 }
775 for attr in ('protection_type',):
776 if not modify or attr in modify:
777 value = self.na_helper.safe_get(self.parameters, ['san_application_template', attr])
778 if value is not None:
779 # we expect value to be a dict, but maybe an empty dict
780 value = self.na_helper.filter_out_none_entries(value)
781 if value:
782 san[attr] = value
783 for attr in ('exclude_aggregates',):
784 if modify is None: # only used for create
785 values = self.na_helper.safe_get(self.parameters, ['san_application_template', attr])
786 if values:
787 san[attr] = [dict(name=name) for name in values]
788 for attr in ('os_type',):
789 if not modify: # not supported for modify operation, but required at application component level for create
790 value = self.na_helper.safe_get(self.parameters, [attr])
791 if value is not None:
792 san[attr] = value
793 body, error = self.rest_app.create_application_body('san', san)
794 return body, error
795
796 def create_san_application(self):
797 '''Use REST application/applications san template to create one or more LUNs'''
798 body, error = self.create_san_app_body()
799 self.fail_on_error(error)
800 dummy, error = self.rest_app.create_application(body)
801 self.fail_on_error(error)
802
803 def modify_san_application(self, modify):
804 '''Use REST application/applications san template to add one or more LUNs'''
805 body, error = self.create_san_app_body(modify)
806 self.fail_on_error(error)
807 # these cannot be present when using PATCH
808 body.pop('name')
809 body.pop('svm')
810 body.pop('smart_container')
811 dummy, error = self.rest_app.patch_application(body)
812 self.fail_on_error(error)
813
814 def convert_to_san_application(self, scope):
815 '''First convert volume to smart container using POST
816 Second modify app to add new luns using PATCH
817 '''
818 # dummy modify, so that we don't fill in the body
819 modify = dict(dummy='dummy')
820 body, error = self.create_san_app_body(modify)
821 self.fail_on_error(error)
822 dummy, error = self.rest_app.create_application(body)
823 self.fail_on_error(error)
824 app_current, error = self.rest_app.get_application_uuid()
825 self.fail_on_error(error)
826 if app_current is None:
827 self.module.fail_json(msg='Error: failed to create smart container for %s' % self.parameters['name'])
828 app_modify, app_modify_warning = self.app_changes(scope)
829 if app_modify_warning is not None:
830 self.module.warn(app_modify_warning)
831 if app_modify:
832 self.modify_san_application(app_modify)
833
834 def delete_san_application(self):
835 '''Use REST application/applications san template to delete one or more LUNs'''
836 dummy, error = self.rest_app.delete_application()
837 self.fail_on_error(error)
838
839 def create_lun(self):
840 """
841 Create LUN with requested name and size
842 """
843 if self.use_rest:
844 return self.create_lun_rest()
845 path = '/vol/%s/%s' % (self.parameters['flexvol_name'], self.parameters['name'])
846 options = {'path': path,
847 'size': str(self.parameters['size']),
848 'space-reservation-enabled': self.na_helper.get_value_for_bool(False, self.parameters['space_reserve']),
849 'use-exact-size': str(self.parameters['use_exact_size'])}
850 if self.parameters.get('space_allocation') is not None:
851 options['space-allocation-enabled'] = self.na_helper.get_value_for_bool(False, self.parameters['space_allocation'])
852 if self.parameters.get('comment') is not None:
853 options['comment'] = self.parameters['comment']
854 if self.parameters.get('os_type') is not None:
855 options['ostype'] = self.parameters['os_type']
856 if self.parameters.get('qos_policy_group') is not None:
857 options['qos-policy-group'] = self.parameters['qos_policy_group']
858 if self.parameters.get('qos_adaptive_policy_group') is not None:
859 options['qos-adaptive-policy-group'] = self.parameters['qos_adaptive_policy_group']
860 lun_create = netapp_utils.zapi.NaElement.create_node_with_children(
861 'lun-create-by-size', **options)
862
863 try:
864 self.server.invoke_successfully(lun_create, enable_tunneling=True)
865 except netapp_utils.zapi.NaApiError as exc:
866 self.module.fail_json(msg="Error provisioning lun %s of size %s: %s"
867 % (self.parameters['name'], self.parameters['size'], to_native(exc)),
868 exception=traceback.format_exc())
869
870 def delete_lun(self, path):
871 """
872 Delete requested LUN
873 """
874 if self.use_rest:
875 return self.delete_lun_rest()
876 lun_delete = netapp_utils.zapi.NaElement.create_node_with_children(
877 'lun-destroy', **{'path': path,
878 'force': str(self.parameters['force_remove']),
879 'destroy-fenced-lun':
880 str(self.parameters['force_remove_fenced'])})
881
882 try:
883 self.server.invoke_successfully(lun_delete, enable_tunneling=True)
884 except netapp_utils.zapi.NaApiError as exc:
885 self.module.fail_json(msg="Error deleting lun %s: %s" % (path, to_native(exc)),
886 exception=traceback.format_exc())
887
888 def resize_lun(self, path):
889 """
890 Resize requested LUN
891
892 :return: True if LUN was actually re-sized, false otherwise.
893 :rtype: bool
894 """
895 if self.use_rest:
896 return self.resize_lun_rest()
897 lun_resize = netapp_utils.zapi.NaElement.create_node_with_children(
898 'lun-resize', **{'path': path,
899 'size': str(self.parameters['size']),
900 'force': str(self.parameters['force_resize'])})
901 try:
902 self.server.invoke_successfully(lun_resize, enable_tunneling=True)
903 except netapp_utils.zapi.NaApiError as exc:
904 if to_native(exc.code) == "9042":
905 # Error 9042 denotes the new LUN size being the same as the
906 # old LUN size. This happens when there's barely any difference
907 # in the two sizes. For example, from 8388608 bytes to
908 # 8194304 bytes. This should go away if/when the default size
909 # requested/reported to/from the controller is changed to a
910 # larger unit (MB/GB/TB).
911 return False
912 else:
913 self.module.fail_json(msg="Error resizing lun %s: %s" % (path, to_native(exc)),
914 exception=traceback.format_exc())
915
916 return True
917
918 def set_lun_value(self, path, key, value):
919 key_to_zapi = dict(
920 comment=('lun-set-comment', 'comment'),
921 # The same ZAPI is used for both QOS attributes
922 qos_policy_group=('lun-set-qos-policy-group', 'qos-policy-group'),
923 qos_adaptive_policy_group=('lun-set-qos-policy-group', 'qos-adaptive-policy-group'),
924 space_allocation=('lun-set-space-alloc', 'enable'),
925 space_reserve=('lun-set-space-reservation-info', 'enable')
926 )
927 if key in key_to_zapi:
928 zapi, option = key_to_zapi[key]
929 else:
930 self.module.fail_json(msg="option %s cannot be modified to %s" % (key, value))
931 options = dict(path=path)
932 if option == 'enable':
933 options[option] = self.na_helper.get_value_for_bool(False, value)
934 else:
935 options[option] = value
936
937 lun_set = netapp_utils.zapi.NaElement.create_node_with_children(zapi, **options)
938 try:
939 self.server.invoke_successfully(lun_set, enable_tunneling=True)
940 except netapp_utils.zapi.NaApiError as exc:
941 self.module.fail_json(msg="Error setting lun option %s: %s" % (key, to_native(exc)),
942 exception=traceback.format_exc())
943 return
944
945 def modify_lun(self, path, modify):
946 """
947 update LUN properties (except size or name)
948 """
949 if self.use_rest:
950 return self.modify_lun_rest(modify)
951 for key in sorted(modify):
952 self.set_lun_value(path, key, modify[key])
953
954 def rename_lun(self, path, new_path):
955 """
956 rename LUN
957 """
958 if self.use_rest:
959 return self.rename_lun_rest(new_path)
960 lun_move = netapp_utils.zapi.NaElement.create_node_with_children(
961 'lun-move', **{'path': path,
962 'new-path': new_path})
963 try:
964 self.server.invoke_successfully(lun_move, enable_tunneling=True)
965 except netapp_utils.zapi.NaApiError as exc:
966 self.module.fail_json(msg="Error moving lun %s: %s" % (path, to_native(exc)),
967 exception=traceback.format_exc())
968
969 def fail_on_error(self, error, stack=False):
970 if error is None:
971 return
972 elements = dict(msg="Error: %s" % error)
973 if stack:
974 elements['stack'] = traceback.format_stack()
975 self.module.fail_json(**elements)
976
977 def set_total_size(self, validate):
978 # fix total_size attribute, report error if total_size is missing (or size is missing)
979 attr = 'total_size'
980 value = self.na_helper.safe_get(self.parameters, ['san_application_template', attr])
981 if value is not None or not validate:
982 self.parameters[attr] = value
983 return
984 lun_count = self.na_helper.safe_get(self.parameters, ['san_application_template', 'lun_count'])
985 value = self.parameters.get('size')
986 if value is not None and (lun_count is None or lun_count == 1):
987 self.parameters[attr] = value
988 return
989 self.module.fail_json(msg="Error: 'total_size' is a required SAN application template attribute when creating a LUN application")
990
991 def validate_app_create(self):
992 # fix total_size attribute
993 self.set_total_size(validate=True)
994
995 def validate_app_changes(self, modify, warning):
996 saved_modify = dict(modify)
997 errors = [
998 "Error: the following application parameter cannot be modified: %s. Received: %s."
999 % (key, str(modify))
1000 for key in modify
1001 if key not in ('igroup_name', 'os_type', 'lun_count', 'total_size')
1002 ]
1003
1004 extra_attrs = tuple()
1005 if 'lun_count' in modify:
1006 extra_attrs = ('total_size', 'os_type', 'igroup_name')
1007 else:
1008 ignored_keys = [key for key in modify if key not in ('total_size',)]
1009 for key in ignored_keys:
1010 self.module.warn(
1011 "Ignoring: %s. This application parameter is only relevant when increasing the LUN count. Received: %s."
1012 % (key, str(saved_modify)))
1013 modify.pop(key)
1014 for attr in extra_attrs:
1015 value = self.parameters.get(attr)
1016 if value is None:
1017 value = self.na_helper.safe_get(self.parameters['san_application_template'], [attr])
1018 if value is None:
1019 errors.append('Error: %s is a required parameter when increasing lun_count.' % attr)
1020 else:
1021 modify[attr] = value
1022 if errors:
1023 self.module.fail_json(msg='\n'.join(errors))
1024 if 'total_size' in modify:
1025 self.set_total_size(validate=False)
1026 if warning and 'lun_count' not in modify:
1027 # can't change total_size, let's ignore it
1028 self.module.warn(warning)
1029 modify.pop('total_size')
1030 saved_modify.pop('total_size')
1031 if modify and not self.rest_api.meets_rest_minimum_version(True, 9, 8):
1032 self.module.fail_json(
1033 msg='Error: modifying %s is not supported on ONTAP 9.7' % ', '.join(saved_modify.keys()))
1034
1035 def fail_on_large_size_reduction(self, app_current, desired, provisioned_size):
1036 """ Error if a reduction of size > 10% is requested.
1037 Warn for smaller reduction and ignore it, to protect against 'rounding' errors.
1038 """
1039 total_size = app_current['total_size']
1040 desired_size = desired.get('total_size')
1041 warning = None
1042 if desired_size is not None:
1043 details = "total_size=%d, provisioned=%d, requested=%d" % (total_size, provisioned_size, desired_size)
1044 if desired_size < total_size:
1045 # * 100 to get a percentage, and .0 to force float conversion
1046 reduction = round((total_size - desired_size) * 100.0 / total_size, 1)
1047 if reduction > 10:
1048 self.module.fail_json(msg="Error: can't reduce size: %s" % details)
1049 else:
1050 warning = "Ignoring small reduction (%.1f %%) in total size: %s" % (reduction, details)
1051 elif desired_size > total_size and desired_size < provisioned_size:
1052 # we can't increase, but we can't say it is a problem, as the size is already bigger!
1053 warning = "Ignoring increase: requested size is too small: %s" % details
1054 return warning
1055
1056 def get_luns_rest(self, lun_path=None):
1057 if lun_path is None and self.parameters.get('flexvol_name') is None:
1058 return []
1059 api = 'storage/luns'
1060 query = {
1061 'svm.name': self.parameters['vserver'],
1062 'fields': "comment,lun_maps,name,os_type,qos_policy.name,space"}
1063 if lun_path is not None:
1064 query['name'] = lun_path
1065 else:
1066 query['location.volume.name'] = self.parameters['flexvol_name']
1067 if self.parameters.get('qtree_name') is not None:
1068 query['location.qtree.name'] = self.parameters['qtree_name']
1069 record, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
1070 if error:
1071 if lun_path is not None:
1072 self.module.fail_json(msg="Error getting lun_path %s: %s" % (lun_path, to_native(error)),
1073 exception=traceback.format_exc())
1074 else:
1075 self.module.fail_json(
1076 msg="Error getting LUN's for flexvol %s: %s" % (self.parameters['flexvol_name'], to_native(error)),
1077 exception=traceback.format_exc())
1078 return self.format_get_luns(record)
1079
1080 def format_get_luns(self, records):
1081 luns = []
1082 if not records:
1083 return None
1084 for record in records:
1085 # TODO: Check that path and name are the same in Rest
1086 lun = {
1087 'uuid': self.na_helper.safe_get(record, ['uuid']),
1088 'name': self.na_helper.safe_get(record, ['name']),
1089 'path': self.na_helper.safe_get(record, ['name']),
1090 'size': self.na_helper.safe_get(record, ['space', 'size']),
1091 'comment': self.na_helper.safe_get(record, ['comment']),
1092 'flexvol_name': self.na_helper.safe_get(record, ['location', 'volume', 'name']),
1093 'os_type': self.na_helper.safe_get(record, ['os_type']),
1094 'qos_policy_group': self.na_helper.safe_get(record, ['qos_policy', 'name']),
1095 'space_reserve': self.na_helper.safe_get(record, ['space', 'guarantee', 'requested']),
1096 'space_allocation': self.na_helper.safe_get(record,
1097 ['space', 'scsi_thin_provisioning_support_enabled']),
1098 }
1099 luns.append(lun)
1100 return luns
1101
1102 def create_lun_rest(self):
1103 name = self.parameters['name'] if self.asa_r2_system else self.create_lun_path_rest()
1104 api = 'storage/luns'
1105 body = {
1106 'svm.name': self.parameters['vserver'],
1107 'name': name,
1108 }
1109 if self.parameters.get('flexvol_name') is not None:
1110 body['location.volume.name'] = self.parameters['flexvol_name']
1111 if self.parameters.get('qtree_name') is not None:
1112 body['location.qtree.name'] = self.parameters['qtree_name']
1113 if self.parameters.get('os_type') is not None:
1114 body['os_type'] = self.parameters['os_type']
1115 if self.parameters.get('size') is not None:
1116 body['space.size'] = self.parameters['size']
1117 if self.parameters.get('space_reserve') is not None:
1118 if not self.asa_r2_system:
1119 body['space.guarantee.requested'] = self.parameters['space_reserve']
1120 if self.parameters.get('space_allocation') is not None:
1121 body['space.scsi_thin_provisioning_support_enabled'] = self.parameters['space_allocation']
1122 if self.parameters.get('comment') is not None:
1123 body['comment'] = self.parameters['comment']
1124 if self.parameters.get('qos_policy_group') is not None:
1125 body['qos_policy.name'] = self.parameters['qos_policy_group']
1126 if self.parameters.get('provisioning_options') is not None:
1127 body['provisioning_options'] = self.na_helper.filter_out_none_entries(self.parameters.get('provisioning_options'))
1128 dummy, error = rest_generic.post_async(self.rest_api, api, body)
1129 if error:
1130 self.module.fail_json(msg="Error creating LUN %s: %s" % (self.parameters['name'], to_native(error)),
1131 exception=traceback.format_exc())
1132
1133 def create_lun_path_rest(self):
1134 """ ZAPI accepts just a name, while REST expects a path. We need to convert a name in to a path for backward compatibility
1135 If the name start with a slash we will assume it a path and use it as the name
1136 """
1137 if not self.parameters['name'].startswith('/') and self.parameters.get('flexvol_name') is not None:
1138 # if it dosn't start with a slash we will use flexvol name and/or qtree name to build the path
1139 if self.parameters.get('qtree_name') is not None:
1140 return '/vol/%s/%s/%s' % (self.parameters['flexvol_name'], self.parameters['qtree_name'], self.parameters['name'])
1141 return '/vol/%s/%s' % (self.parameters['flexvol_name'], self.parameters['name'])
1142 return self.parameters['name']
1143
1144 def delete_lun_rest(self):
1145 if self.uuid is None:
1146 self.module.fail_json(msg="Error deleting LUN %s: UUID not found" % self.parameters['name'])
1147 api = 'storage/luns'
1148 query = {'allow_delete_while_mapped': self.parameters['force_remove']}
1149 dummy, error = rest_generic.delete_async(self.rest_api, api, self.uuid, query)
1150 if error:
1151 self.module.fail_json(msg="Error deleting LUN %s: %s" % (self.parameters['name'], to_native(error)),
1152 exception=traceback.format_exc())
1153
1154 def rename_lun_rest(self, new_path):
1155 if self.uuid is None:
1156 self.module.fail_json(msg="Error renaming LUN %s: UUID not found" % self.parameters['name'])
1157 api = 'storage/luns'
1158 body = {'name': new_path}
1159 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body)
1160 if error:
1161 self.module.fail_json(msg="Error renaming LUN %s: %s" % (self.parameters['name'], to_native(error)),
1162 exception=traceback.format_exc())
1163
1164 def resize_lun_rest(self):
1165 if self.uuid is None:
1166 self.module.fail_json(msg="Error resizing LUN %s: UUID not found" % self.parameters['name'])
1167 api = 'storage/luns'
1168 body = {'space.size': self.parameters['size']}
1169 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body)
1170 if error:
1171 if 'New LUN size is the same as the old LUN size' in error:
1172 return False
1173 self.module.fail_json(msg="Error resizing LUN %s: %s" % (self.parameters['name'], to_native(error)),
1174 exception=traceback.format_exc())
1175 return True
1176
1177 def modify_lun_rest(self, modify):
1178 local_modify = modify.copy()
1179 if self.uuid is None:
1180 self.module.fail_json(msg="Error modifying LUN %s: UUID not found" % self.parameters['name'])
1181 api = 'storage/luns'
1182 body = {}
1183 if local_modify.get('space_reserve') is not None:
1184 body['space.guarantee.requested'] = local_modify.pop('space_reserve')
1185 if local_modify.get('space_allocation') is not None:
1186 body['space.scsi_thin_provisioning_support_enabled'] = local_modify.pop('space_allocation')
1187 if local_modify.get('comment') is not None:
1188 body['comment'] = local_modify.pop('comment')
1189 if local_modify.get('qos_policy_group') is not None:
1190 body['qos_policy.name'] = local_modify.pop('qos_policy_group')
1191 if local_modify != {}:
1192 self.module.fail_json(
1193 msg="Error modifying LUN %s: Unknown parameters: %s" % (self.parameters['name'], local_modify))
1194 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body)
1195 if error:
1196 self.module.fail_json(msg="Error modifying LUN %s: %s" % (self.parameters['name'], to_native(error)),
1197 exception=traceback.format_exc())
1198
1199 def check_for_errors(self, lun_cd_action, current, modify):
1200 errors = []
1201 if lun_cd_action == 'create':
1202 if self.parameters.get('flexvol_name') is None:
1203 if self.use_rest and not self.asa_r2_system:
1204 errors.append("The flexvol_name parameter is required for creating a LUN.")
1205 if self.use_rest and self.parameters.get('os_type') is None:
1206 errors.append("The os_type parameter is required for creating a LUN with REST.")
1207 if self.parameters.get('size') is None:
1208 self.module.fail_json(msg="size is a required parameter for create.")
1209 elif modify and 'os_type' in modify:
1210 self.module.fail_json(msg="os_type cannot be modified: current: %s, desired: %s" % (current['os_type'], modify['os_type']))
1211 if errors:
1212 self.module.fail_json(msg=' '.join(errors))
1213
1214 def set_uuid(self, current):
1215 if self.use_rest and current is not None and current.get('uuid') is not None:
1216 self.uuid = current['uuid']
1217
1218 def app_changes(self, scope):
1219 # find and validate app changes
1220 app_current, error = self.rest_app.get_application_details('san')
1221 self.fail_on_error(error)
1222 # save application name, as it is overriden in the flattening operation
1223 app_name = app_current['name']
1224 # there is an issue with total_size not reflecting the real total_size, and some additional overhead
1225 provisioned_size = self.na_helper.safe_get(app_current, ['statistics', 'space', 'provisioned'])
1226 if provisioned_size is None:
1227 provisioned_size = 0
1228 if self.debug:
1229 self.debug['app_current'] = app_current # will be updated below as it is mutable
1230 self.debug['got'] = copy.deepcopy(app_current) # fixed copy
1231 # flatten
1232 app_current = app_current['san'] # app template
1233 app_current.update(app_current['application_components'][0]) # app component
1234 del app_current['application_components']
1235 # if component name does not match, assume a change at LUN level
1236 comp_name = app_current['name']
1237 if comp_name != self.parameters['name']:
1238 msg = "desired component/volume name: %s does not match existing component name: %s" % (self.parameters['name'], comp_name)
1239 if scope == 'application':
1240 self.module.fail_json(msg='Error: ' + msg + ". scope=%s" % scope)
1241 return None, msg + ". scope=%s, assuming 'lun' scope." % scope
1242 # restore app name
1243 app_current['name'] = app_name
1244
1245 # ready to compare, except for a quirk in size handling
1246 desired = dict(self.parameters['san_application_template'])
1247 warning = self.fail_on_large_size_reduction(app_current, desired, provisioned_size)
1248
1249 # preserve change state before calling modify in case an ignorable total_size change is the only change
1250 changed = self.na_helper.changed
1251 app_modify = self.na_helper.get_modified_attributes(app_current, desired)
1252 self.validate_app_changes(app_modify, warning)
1253 if not app_modify:
1254 self.na_helper.changed = changed
1255 app_modify = None
1256 return app_modify, None
1257
1258 def get_app_apply(self):
1259 scope = self.na_helper.safe_get(self.parameters, ['san_application_template', 'scope'])
1260 app_current, error = self.rest_app.get_application_uuid()
1261 self.fail_on_error(error)
1262 if scope == 'lun' and app_current is None:
1263 self.module.fail_json(msg='Application not found: %s. scope=%s.' %
1264 (self.na_helper.safe_get(self.parameters, ['san_application_template', 'name']),
1265 scope))
1266 return scope, app_current
1267
1268 def app_actions(self, app_current, scope, actions, results):
1269 app_modify, app_modify_warning = None, None
1270 app_cd_action = self.na_helper.get_cd_action(app_current, self.parameters)
1271 if app_cd_action == 'create':
1272 # check if target volume already exists
1273 cp_volume_name = self.parameters['name']
1274 volume, error = rest_volume.get_volume(self.rest_api, self.parameters['vserver'], cp_volume_name)
1275 self.fail_on_error(error)
1276 if volume is not None:
1277 if scope == 'application':
1278 # volume already exists, but not as part of this application
1279 app_cd_action = 'convert'
1280 if not self.rest_api.meets_rest_minimum_version(True, 9, 8, 0):
1281 msg = 'Error: converting a LUN volume to a SAN application container requires ONTAP 9.8 or better.'
1282 self.module.fail_json(msg=msg)
1283 else:
1284 # default name already in use, ask user to clarify intent
1285 msg = "Error: volume '%s' already exists. Please use a different group name, or use 'application' scope. scope=%s"
1286 self.module.fail_json(msg=msg % (cp_volume_name, scope))
1287 if app_cd_action is not None:
1288 actions.append('app_%s' % app_cd_action)
1289 if app_cd_action == 'create':
1290 self.validate_app_create()
1291 if app_cd_action is None and app_current is not None:
1292 app_modify, app_modify_warning = self.app_changes(scope)
1293 if app_modify:
1294 actions.append('app_modify')
1295 results['app_modify'] = dict(app_modify)
1296 return app_cd_action, app_modify, app_modify_warning
1297
1298 def lun_actions(self, app_current, actions, results, scope, app_modify, app_modify_warning):
1299 # actions at LUN level
1300 lun_cd_action, lun_modify, lun_rename = None, None, None
1301 lun_path, from_lun_path = None, None
1302 from_name = self.parameters.get('from_name')
1303 if self.rest_app and app_current:
1304 # For LUNs created using a SAN application, we're getting lun paths from the backing storage
1305 lun_path = self.get_lun_path_from_backend(self.parameters['name'])
1306 if from_name is not None:
1307 from_lun_path = self.get_lun_path_from_backend(from_name)
1308 current = self.get_lun(self.parameters['name'], lun_path)
1309 self.set_uuid(current)
1310 if current is not None and lun_path is None:
1311 lun_path = current['path']
1312 lun_cd_action = self.na_helper.get_cd_action(current, self.parameters)
1313 if lun_cd_action == 'create' and from_name is not None:
1314 # create by renaming existing LUN, if it exists
1315 old_lun = self.get_lun(from_name, from_lun_path)
1316 lun_rename = self.na_helper.is_rename_action(old_lun, current)
1317 if lun_rename is None:
1318 self.module.fail_json(msg="Error renaming lun: %s does not exist" % from_name)
1319 if lun_rename:
1320 current = old_lun
1321 if from_lun_path is None:
1322 from_lun_path = current['path']
1323 head, _sep, tail = from_lun_path.rpartition(from_name)
1324 if tail:
1325 self.module.fail_json(
1326 msg="Error renaming lun: %s does not match lun_path %s" % (from_name, from_lun_path))
1327 self.set_uuid(current)
1328 lun_path = head + self.parameters['name']
1329 lun_cd_action = None
1330 actions.append('lun_rename')
1331 app_modify_warning = None # reset warning as we found a match
1332 if lun_cd_action is not None:
1333 actions.append('lun_%s' % lun_cd_action)
1334 if lun_cd_action is None and self.parameters['state'] == 'present':
1335 # we already handled rename if required
1336 current.pop('name', None)
1337 lun_modify = self.na_helper.get_modified_attributes(current, self.parameters)
1338 if lun_modify:
1339 actions.append('lun_modify')
1340 results['lun_modify'] = dict(lun_modify)
1341 app_modify_warning = None # reset warning as we found a match
1342 if lun_cd_action and self.rest_app and app_current:
1343 msg = 'This module does not support %s a LUN by name %s a SAN application.' % \
1344 ('adding', 'to') if lun_cd_action == 'create' else ('removing', 'from')
1345 if scope == 'auto':
1346 # ignore LUN not found, as name can be a group name
1347 self.module.warn(msg + ". scope=%s, assuming 'application'" % scope)
1348 if not app_modify:
1349 self.na_helper.changed = False
1350 elif scope == 'lun':
1351 self.module.fail_json(msg=msg + ". scope=%s." % scope)
1352 lun_cd_action = None
1353 self.check_for_errors(lun_cd_action, current, lun_modify)
1354 return lun_path, from_lun_path, lun_cd_action, lun_rename, lun_modify, app_modify_warning
1355
1356 def lun_modify_after_app_update(self, lun_path, results):
1357 # modify at LUN level, as app modify does not set some LUN level options (eg space_reserve)
1358 if lun_path is None:
1359 lun_path = self.get_lun_path_from_backend(self.parameters['name'])
1360 current = self.get_lun(self.parameters['name'], lun_path)
1361 self.set_uuid(current)
1362 # we already handled rename if required
1363 current.pop('name', None)
1364 lun_modify = self.na_helper.get_modified_attributes(current, self.parameters)
1365 if lun_modify:
1366 results['lun_modify_after_app_update'] = dict(lun_modify)
1367 self.check_for_errors(None, current, lun_modify)
1368 return lun_modify
1369
1370 def apply(self):
1371 results = {}
1372 app_cd_action, app_modify, lun_cd_action, lun_modify, lun_rename = None, None, None, None, None
1373 app_modify_warning, app_current, lun_path, from_lun_path = None, None, None, None
1374 actions = []
1375 if self.rest_app:
1376 scope, app_current = self.get_app_apply()
1377 else:
1378 # no application template, fall back to LUN only
1379 scope = 'lun'
1380 if self.rest_app and scope != 'lun':
1381 app_cd_action, app_modify, app_modify_warning = self.app_actions(app_current, scope, actions, results)
1382 if app_cd_action is None and scope != 'application':
1383 lun_path, from_lun_path, lun_cd_action, lun_rename, lun_modify, app_modify_warning = \
1384 self.lun_actions(app_current, actions, results, scope, app_modify, app_modify_warning)
1385 if self.na_helper.changed and not self.module.check_mode:
1386 if app_cd_action == 'create':
1387 self.create_san_application()
1388 elif app_cd_action == 'convert':
1389 self.convert_to_san_application(scope)
1390 elif app_cd_action == 'delete':
1391 self.rest_app.delete_application()
1392 elif lun_cd_action == 'create':
1393 self.create_lun()
1394 elif lun_cd_action == 'delete':
1395 self.delete_lun(lun_path)
1396 else:
1397 if app_modify:
1398 self.modify_san_application(app_modify)
1399 if lun_rename:
1400 self.rename_lun(from_lun_path, lun_path)
1401 if app_modify:
1402 # space_reserve will be set to True
1403 # To match input parameters, lun_modify is recomputed.
1404 lun_modify = self.lun_modify_after_app_update(lun_path, results)
1405 size_changed = False
1406 if lun_modify and 'size' in lun_modify:
1407 # Ensure that size was actually changed. Please
1408 # read notes in 'resize_lun' function for details.
1409 size_changed = self.resize_lun(lun_path)
1410 lun_modify.pop('size')
1411 if lun_modify:
1412 self.modify_lun(lun_path, lun_modify)
1413 if not lun_modify and not lun_rename and not app_modify:
1414 # size may not have changed
1415 self.na_helper.changed = size_changed
1416
1417 if app_modify_warning:
1418 self.module.warn(app_modify_warning)
1419 result = netapp_utils.generate_result(self.na_helper.changed, actions,
1420 extra_responses={'debug': self.debug} if self.debug else None)
1421 self.module.exit_json(**result)
1422
1423
1424 def main():
1425 lun = NetAppOntapLUN()
1426 lun.apply()
1427
1428
1429 if __name__ == '__main__':
1430 main()