Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2026, NetApp, Inc
4 # GNU General Public License v3.0+
5 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 '''
10 na_ontap_quotas
11 '''
12
13
14 DOCUMENTATION = '''
15 module: na_ontap_quotas
16 short_description: NetApp ONTAP Quotas
17 extends_documentation_fragment:
18 - netapp.ontap.netapp.na_ontap
19 version_added: 2.8.0
20 author: NetApp Ansible Team (@carchi8py) <[email protected]>
21 description:
22 - Set/Modify/Delete quota on ONTAP
23 options:
24 state:
25 description:
26 - Whether the specified quota should exist or not.
27 choices: ['present', 'absent']
28 default: present
29 type: str
30 vserver:
31 required: true
32 description:
33 - Name of the vserver to use.
34 type: str
35 volume:
36 description:
37 - The name of the volume that the quota resides on.
38 required: true
39 type: str
40 quota_target:
41 description:
42 - The quota target of the type specified.
43 - users and group takes quota_target value in REST.
44 - For default user and group quota rules, the quota_target must be specified as "".
45 type: str
46 qtree:
47 description:
48 - Name of the qtree for the quota.
49 - For user or group rules, it can be the qtree name or "" if no qtree.
50 - For tree type rules, this field must be "".
51 default: ""
52 type: str
53 type:
54 description:
55 - The type of quota rule.
56 choices: ['user', 'group', 'tree']
57 type: str
58 policy:
59 description:
60 - Name of the quota policy from which the quota rule should be obtained.
61 - Only supported with ZAPI.
62 - Multiple alternative quota policies (active and backup) are not supported in REST.
63 - REST manages the quota rules of the active policy.
64 type: str
65 set_quota_status:
66 description:
67 - Whether the specified volume should have quota status on or off.
68 type: bool
69 perform_user_mapping:
70 description:
71 - Whether quota management will perform user mapping for the user specified in quota-target.
72 - User mapping can be specified only for a user quota rule.
73 type: bool
74 aliases: ['user_mapping']
75 version_added: 20.12.0
76 file_limit:
77 description:
78 - The number of files that the target can have.
79 - use '-' to reset file limit.
80 type: str
81 disk_limit:
82 description:
83 - The amount of disk space that is reserved for the target.
84 - Expects a number followed with B (for bytes), KB, MB, GB, TB.
85 - If the unit is not present KB is used by default.
86 - Examples - 10MB, 20GB, 1TB, 20B, 10.
87 - In REST, if limit is less than 1024 bytes, the value is rounded up to 1024 bytes.
88 - use '-' to reset disk limit.
89 type: str
90 soft_file_limit:
91 description:
92 - The number of files the target would have to exceed before a message is logged and an SNMP trap is generated.
93 - use '-' to reset soft file limit.
94 type: str
95 soft_disk_limit:
96 description:
97 - The amount of disk space the target would have to exceed before a message is logged and an SNMP trap is generated.
98 - See C(disk_limit) for format description.
99 - In REST, if limit is less than 1024 bytes, the value is rounded up to 1024 bytes.
100 - use '-' to reset soft disk limit.
101 type: str
102 threshold:
103 description:
104 - The amount of disk space the target would have to exceed before a message is logged.
105 - See C(disk_limit) for format description.
106 - Only supported with ZAPI.
107 type: str
108 activate_quota_on_change:
109 description:
110 - Method to use to activate quota on a change.
111 - Default value is 'resize' in ZAPI.
112 - With REST, Changes to quota rule limits C(file_limit), C(disk_limit), C(soft_file_limit), and C(soft_disk_limit) are applied automatically
113 without requiring a quota resize operation.
114 choices: ['resize', 'reinitialize', 'none']
115 type: str
116 version_added: 20.12.0
117 lambda_config:
118 description:
119 - Configuration parameters for AWS Lambda proxy functionality.
120 - These option and suboptions are only supported with REST.
121 type: dict
122 version_added: 23.5.0
123 suboptions:
124 function_name:
125 description:
126 - The name of the AWS Lambda function to invoke.
127 type: str
128 required: true
129 aws_region:
130 description:
131 - The name of the AWS region.
132 type: str
133 required: true
134 aws_profile:
135 description:
136 - The name of the AWS profile to use for authentication.
137 type: str
138
139 notes:
140 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
141
142 '''
143
144 EXAMPLES = """
145 - name: Create quota rule in ZAPI.
146 netapp.ontap.na_ontap_quotas:
147 state: present
148 vserver: ansible
149 volume: ansible
150 quota_target: user1
151 type: user
152 policy: ansible
153 file_limit: 2
154 disk_limit: 3
155 set_quota_status: true
156 hostname: "{{ netapp_hostname }}"
157 username: "{{ netapp_username }}"
158 password: "{{ netapp_password }}"
159 - name: Resize quota
160 netapp.ontap.na_ontap_quotas:
161 state: present
162 vserver: ansible
163 volume: ansible
164 quota_target: user1
165 type: user
166 policy: ansible
167 file_limit: 2
168 disk_limit: 3
169 set_quota_status: true
170 activate_quota_on_change: resize
171 hostname: "{{ netapp_hostname }}"
172 username: "{{ netapp_username }}"
173 password: "{{ netapp_password }}"
174 - name: Reinitialize quota
175 netapp.ontap.na_ontap_quotas:
176 state: present
177 vserver: ansible
178 volume: ansible
179 quota_target: user1
180 type: user
181 policy: ansible
182 file_limit: 2
183 disk_limit: 3
184 set_quota_status: true
185 activate_quota_on_change: reinitialize
186 hostname: "{{ netapp_hostname }}"
187 username: "{{ netapp_username }}"
188 password: "{{ netapp_password }}"
189 - name: Modify quota
190 netapp.ontap.na_ontap_quotas:
191 state: present
192 vserver: ansible
193 volume: ansible
194 quota_target: user1
195 type: user
196 policy: ansible
197 file_limit: 2
198 disk_limit: 3
199 threshold: 3
200 set_quota_status: false
201 hostname: "{{ netapp_hostname }}"
202 username: "{{ netapp_username }}"
203 password: "{{ netapp_password }}"
204 - name: Delete quota
205 netapp.ontap.na_ontap_quotas:
206 state: absent
207 vserver: ansible
208 volume: ansible
209 quota_target: /vol/ansible
210 type: user
211 policy: ansible
212 hostname: "{{ netapp_hostname }}"
213 username: "{{ netapp_username }}"
214 password: "{{ netapp_password }}"
215 - name: Add/Set quota rule for type user in REST.
216 netapp.ontap.na_ontap_quotas:
217 state: present
218 vserver: ansible
219 volume: ansible
220 quota_target: "user1,user2"
221 qtree: qtree
222 type: user
223 file_limit: 2
224 disk_limit: 3
225 set_quota_status: true
226 hostname: "{{ netapp_hostname }}"
227 username: "{{ netapp_username }}"
228 password: "{{ netapp_password }}"
229 - name: Modify quota reset file limit and modify disk limit.
230 netapp.ontap.na_ontap_quotas:
231 state: present
232 vserver: ansible
233 volume: ansible
234 quota_target: "user1,user2"
235 qtree: qtree
236 type: user
237 file_limit: "-"
238 disk_limit: 100
239 set_quota_status: true
240 hostname: "{{ netapp_hostname }}"
241 username: "{{ netapp_username }}"
242 password: "{{ netapp_password }}"
243 - name: Add/Set quota rule for type group in REST.
244 netapp.ontap.na_ontap_quotas:
245 state: present
246 vserver: ansible
247 volume: ansible
248 quota_target: group1
249 qtree: qtree
250 type: group
251 file_limit: 2
252 disk_limit: 3
253 set_quota_status: true
254 hostname: "{{ netapp_hostname }}"
255 username: "{{ netapp_username }}"
256 password: "{{ netapp_password }}"
257 - name: Add/Set quota rule for type qtree in REST.
258 netapp.ontap.na_ontap_quotas:
259 state: present
260 vserver: ansible
261 volume: ansible
262 quota_target: qtree1
263 type: tree
264 file_limit: 2
265 disk_limit: 3
266 set_quota_status: true
267 hostname: "{{ netapp_hostname }}"
268 username: "{{ netapp_username }}"
269 password: "{{ netapp_password }}"
270 """
271
272 RETURN = """
273
274 """
275
276 import time
277 import traceback
278 import re
279 from ansible.module_utils.basic import AnsibleModule
280 from ansible.module_utils._text import to_native
281 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
282 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
283 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
284 import ansible_collections.netapp.ontap.plugins.module_utils.rest_response_helpers as rrh
285
286
287 class NetAppONTAPQuotas:
288 '''Class with quotas methods'''
289
290 def __init__(self):
291
292 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
293 self.argument_spec.update(dict(
294 state=dict(required=False, choices=['present', 'absent'], default='present'),
295 vserver=dict(required=True, type='str'),
296 volume=dict(required=True, type='str'),
297 quota_target=dict(required=False, type='str'),
298 qtree=dict(required=False, type='str', default=""),
299 type=dict(required=False, type='str', choices=['user', 'group', 'tree']),
300 policy=dict(required=False, type='str'),
301 set_quota_status=dict(required=False, type='bool'),
302 perform_user_mapping=dict(required=False, type='bool', aliases=['user_mapping']),
303 file_limit=dict(required=False, type='str'),
304 disk_limit=dict(required=False, type='str'),
305 soft_file_limit=dict(required=False, type='str'),
306 soft_disk_limit=dict(required=False, type='str'),
307 threshold=dict(required=False, type='str'),
308 activate_quota_on_change=dict(required=False, type='str', choices=['resize', 'reinitialize', 'none'])
309 ))
310
311 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
312
313 self.module = AnsibleModule(
314 argument_spec=self.argument_spec,
315 supports_check_mode=True,
316 required_by={
317 'policy': ['quota_target', 'type'],
318 'perform_user_mapping': ['quota_target', 'type'],
319 'file_limit': ['quota_target', 'type'],
320 'disk_limit': ['quota_target', 'type'],
321 'soft_file_limit': ['quota_target', 'type'],
322 'soft_disk_limit': ['quota_target', 'type'],
323 'threshold': ['quota_target', 'type'],
324 },
325 required_together=[('quota_target', 'type')],
326 required_if=[
327 ('use_lambda', True, ['lambda_config']),
328 ],
329 )
330
331 self.na_helper = NetAppModule()
332 self.parameters = self.na_helper.set_parameters(self.module.params)
333 # Set up Rest API
334 self.rest_api = netapp_utils.OntapRestAPI(self.module)
335 unsupported_rest_properties = ['policy', 'threshold']
336 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties)
337 self.volume_uuid = None # volume UUID after quota rule creation, used for on or off quota status
338 self.quota_uuid = None
339 self.warn_msg = None
340 self.validate_parameters_ZAPI_REST()
341
342 if not self.use_rest:
343 if self.parameters.get('use_lambda'):
344 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
345 if not netapp_utils.has_netapp_lib():
346 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
347 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
348
349 def validate_parameters_ZAPI_REST(self):
350 if self.use_rest:
351 if self.parameters.get('type') == 'tree':
352 if self.parameters['qtree']:
353 self.module.fail_json(msg="Error: Qtree cannot be specified for a tree type rule, it should be ''.")
354 # valid qtree name for ZAPI is /vol/vol_name/qtree_name and REST is qtree_name.
355 if '/' in self.parameters.get('quota_target', ''):
356 self.parameters['quota_target'] = self.parameters['quota_target'].split('/')[-1]
357 for quota_limit in ['file_limit', 'disk_limit', 'soft_file_limit', 'soft_disk_limit']:
358 if self.parameters.get(quota_limit) == '-1':
359 self.parameters[quota_limit] = '-'
360 else:
361 # converted blank parameter to * as shown in vsim
362 if self.parameters.get('quota_target') == "":
363 self.parameters['quota_target'] = '*'
364 if not self.parameters.get('activate_quota_on_change'):
365 self.parameters['activate_quota_on_change'] = 'resize'
366 size_format_error_message = "input string is not a valid size format. A valid size format is constructed as" \
367 "<integer><size unit>. For example, '10MB', '10KB'. Only numeric input is also valid." \
368 "The default unit size is KB."
369 if self.parameters.get('disk_limit') and self.parameters['disk_limit'] != '-' and not self.convert_to_kb_or_bytes('disk_limit'):
370 self.module.fail_json(msg='disk_limit %s' % size_format_error_message)
371 if self.parameters.get('soft_disk_limit') and self.parameters['soft_disk_limit'] != '-' and not self.convert_to_kb_or_bytes('soft_disk_limit'):
372 self.module.fail_json(msg='soft_disk_limit %s' % size_format_error_message)
373 if self.parameters.get('threshold') and self.parameters['threshold'] != '-' and not self.convert_to_kb_or_bytes('threshold'):
374 self.module.fail_json(msg='threshold %s' % size_format_error_message)
375
376 def get_quota_status(self):
377 """
378 Return details about the quota status
379 :param:
380 name : volume name
381 :return: status of the quota. None if not found.
382 :rtype: dict
383 """
384 quota_status_get = netapp_utils.zapi.NaElement('quota-status')
385 quota_status_get.translate_struct({
386 'volume': self.parameters['volume']
387 })
388 try:
389 result = self.server.invoke_successfully(quota_status_get, enable_tunneling=True)
390 except netapp_utils.zapi.NaApiError as error:
391 self.module.fail_json(msg='Error fetching quotas status info: %s' % to_native(error),
392 exception=traceback.format_exc())
393 return result['status']
394
395 def get_quotas_with_retry(self, get_request, policy):
396 return_values = None
397 if policy is not None:
398 get_request['query']['quota-entry'].add_new_child('policy', policy)
399 try:
400 result = self.server.invoke_successfully(get_request, enable_tunneling=True)
401 except netapp_utils.zapi.NaApiError as error:
402 # Bypass a potential issue in ZAPI when policy is not set in the query
403 # https://github.com/ansible-collections/netapp.ontap/issues/4
404 # BURT1076601 Loop detected in next() for table quota_rules_zapi
405 if policy is None and 'Reason - 13001:success' in to_native(error):
406 result = None
407 return_values = self.debug_quota_get_error(error)
408 else:
409 self.module.fail_json(msg='Error fetching quotas info for policy %s: %s'
410 % (policy, to_native(error)),
411 exception=traceback.format_exc())
412 return result, return_values
413
414 def get_quotas(self, policy=None):
415 """
416 Get quota details
417 :return: name of volume if quota exists, None otherwise
418 """
419 if self.parameters.get('type') is None:
420 return None
421 if policy is None:
422 policy = self.parameters.get('policy')
423 quota_get = netapp_utils.zapi.NaElement('quota-list-entries-iter')
424 query = {
425 'query': {
426 'quota-entry': {
427 'volume': self.parameters['volume'],
428 'quota-target': self.parameters['quota_target'],
429 'quota-type': self.parameters['type'],
430 'vserver': self.parameters['vserver'],
431 'qtree': self.parameters['qtree'] or '""'
432 }
433 }
434 }
435 quota_get.translate_struct(query)
436 result, return_values = self.get_quotas_with_retry(quota_get, policy)
437 if result is None:
438 return return_values
439 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
440 # if quota-target is '*', the query treats it as a wildcard. But a blank entry is represented as '*'.
441 # Hence the need to loop through all records to find a match.
442 for quota_entry in result.get_child_by_name('attributes-list').get_children():
443 quota_target = quota_entry.get_child_content('quota-target')
444 if quota_target == self.parameters['quota_target']:
445 return_values = {'volume': quota_entry.get_child_content('volume'),
446 'file_limit': quota_entry.get_child_content('file-limit'),
447 'disk_limit': quota_entry.get_child_content('disk-limit'),
448 'soft_file_limit': quota_entry.get_child_content('soft-file-limit'),
449 'soft_disk_limit': quota_entry.get_child_content('soft-disk-limit'),
450 'threshold': quota_entry.get_child_content('threshold')}
451 value = self.na_helper.safe_get(quota_entry, ['perform-user-mapping'])
452 if value is not None:
453 return_values['perform_user_mapping'] = self.na_helper.get_value_for_bool(True, value)
454 return return_values
455 return None
456
457 def get_quota_policies(self):
458 """
459 Get list of quota policies
460 :return: list of quota policies (empty list if None found)
461 """
462 quota_policy_get = netapp_utils.zapi.NaElement('quota-policy-get-iter')
463 query = {
464 'query': {
465 'quota-policy-info': {
466 'vserver': self.parameters['vserver']
467 }
468 }
469 }
470 quota_policy_get.translate_struct(query)
471 try:
472 result = self.server.invoke_successfully(quota_policy_get, enable_tunneling=True)
473 except netapp_utils.zapi.NaApiError as error:
474 self.module.fail_json(msg='Error fetching quota policies: %s' % to_native(error),
475 exception=traceback.format_exc())
476 return ([policy['policy-name'] for policy in result['attributes-list'].get_children()]
477 if result.get_child_by_name('attributes-list')
478 else [])
479
480 def debug_quota_get_error(self, error):
481 policies = self.get_quota_policies()
482 entries = {}
483 for policy in policies:
484 entries[policy] = self.get_quotas(policy)
485 if len(policies) == 1:
486 self.module.warn('retried with success using policy="%s" on "13001:success" ZAPI error.' % policy)
487 return entries[policies[0]]
488 self.module.fail_json(msg='Error fetching quotas info: %s - current vserver policies: %s, details: %s'
489 % (to_native(error), policies, entries))
490
491 def quota_entry_set(self):
492 """
493 Adds a quota entry
494 """
495 options = {'volume': self.parameters['volume'],
496 'quota-target': self.parameters['quota_target'],
497 'quota-type': self.parameters['type'],
498 'qtree': self.parameters['qtree']}
499
500 self.set_zapi_options(options)
501 if self.parameters.get('policy'):
502 options['policy'] = self.parameters['policy']
503 set_entry = netapp_utils.zapi.NaElement.create_node_with_children(
504 'quota-set-entry', **options)
505 try:
506 self.server.invoke_successfully(set_entry, enable_tunneling=True)
507 except netapp_utils.zapi.NaApiError as error:
508 self.module.fail_json(msg='Error adding/modifying quota entry %s: %s'
509 % (self.parameters['volume'], to_native(error)),
510 exception=traceback.format_exc())
511
512 def quota_entry_delete(self):
513 """
514 Deletes a quota entry
515 """
516 options = {'volume': self.parameters['volume'],
517 'quota-target': self.parameters['quota_target'],
518 'quota-type': self.parameters['type'],
519 'qtree': self.parameters['qtree']}
520 set_entry = netapp_utils.zapi.NaElement.create_node_with_children(
521 'quota-delete-entry', **options)
522 if self.parameters.get('policy'):
523 set_entry.add_new_child('policy', self.parameters['policy'])
524 try:
525 self.server.invoke_successfully(set_entry, enable_tunneling=True)
526 except netapp_utils.zapi.NaApiError as error:
527 self.module.fail_json(msg='Error deleting quota entry %s: %s'
528 % (self.parameters['volume'], to_native(error)),
529 exception=traceback.format_exc())
530
531 def quota_entry_modify(self, modify_attrs):
532 """
533 Modifies a quota entry
534 """
535 for key in list(modify_attrs):
536 modify_attrs[key.replace("_", "-")] = modify_attrs.pop(key)
537 options = {'volume': self.parameters['volume'],
538 'quota-target': self.parameters['quota_target'],
539 'quota-type': self.parameters['type'],
540 'qtree': self.parameters['qtree']}
541 options.update(modify_attrs)
542 self.set_zapi_options(options)
543 if self.parameters.get('policy'):
544 options['policy'] = str(self.parameters['policy'])
545 modify_entry = netapp_utils.zapi.NaElement.create_node_with_children(
546 'quota-modify-entry', **options)
547 try:
548 self.server.invoke_successfully(modify_entry, enable_tunneling=True)
549 except netapp_utils.zapi.NaApiError as error:
550 self.module.fail_json(msg='Error modifying quota entry %s: %s'
551 % (self.parameters['volume'], to_native(error)),
552 exception=traceback.format_exc())
553
554 def set_zapi_options(self, options):
555 if self.parameters.get('file_limit'):
556 options['file-limit'] = self.parameters['file_limit']
557 if self.parameters.get('disk_limit'):
558 options['disk-limit'] = self.parameters['disk_limit']
559 if self.parameters.get('perform_user_mapping') is not None:
560 options['perform-user-mapping'] = str(self.parameters['perform_user_mapping'])
561 if self.parameters.get('soft_file_limit'):
562 options['soft-file-limit'] = self.parameters['soft_file_limit']
563 if self.parameters.get('soft_disk_limit'):
564 options['soft-disk-limit'] = self.parameters['soft_disk_limit']
565 if self.parameters.get('threshold'):
566 options['threshold'] = self.parameters['threshold']
567
568 def on_or_off_quota(self, status, cd_action=None):
569 """
570 on or off quota
571 """
572 quota = netapp_utils.zapi.NaElement.create_node_with_children(
573 status, **{'volume': self.parameters['volume']})
574 try:
575 self.server.invoke_successfully(quota,
576 enable_tunneling=True)
577 except netapp_utils.zapi.NaApiError as error:
578 if cd_action == 'delete' and status == 'quota-on' and '14958:No valid quota rules found' in to_native(error):
579 # ignore error on quota-on, as all rules have been deleted
580 self.module.warn('Last rule deleted, quota is off.')
581 return
582 self.module.fail_json(msg='Error setting %s for %s: %s'
583 % (status, self.parameters['volume'], to_native(error)),
584 exception=traceback.format_exc())
585
586 def resize_quota(self, cd_action=None):
587 """
588 resize quota
589 """
590 quota = netapp_utils.zapi.NaElement.create_node_with_children(
591 'quota-resize', **{'volume': self.parameters['volume']})
592 try:
593 self.server.invoke_successfully(quota,
594 enable_tunneling=True)
595 except netapp_utils.zapi.NaApiError as error:
596 if cd_action == 'delete' and '14958:No valid quota rules found' in to_native(error):
597 # ignore error on quota-on, as all rules have been deleted
598 self.module.warn('Last rule deleted, but quota is on as resize is not allowed.')
599 return
600 self.module.fail_json(msg='Error setting %s for %s: %s'
601 % ('quota-resize', self.parameters['volume'], to_native(error)),
602 exception=traceback.format_exc())
603
604 def get_quotas_rest(self):
605 """
606 Retrieves quotas with rest API.
607 If type is user then it returns all possible combinations of user name records.
608 Report api is used to fetch file and disk limit info
609 """
610 if not self.use_rest:
611 return self.get_quotas()
612 query = {'svm.name': self.parameters.get('vserver'),
613 'volume.name': self.parameters.get('volume'),
614 'type': self.parameters.get('type'),
615 'fields': 'svm.uuid,'
616 'svm.name,'
617 'space.hard_limit,'
618 'files.hard_limit,'
619 'user_mapping,'
620 'qtree.name,'
621 'type,'
622 'space.soft_limit,'
623 'files.soft_limit,'
624 'volume.uuid,'
625 'users.name,'
626 'users.id,'
627 'group.name,'}
628
629 # set qtree name in query for type user and group if not ''.
630 if self.parameters['qtree']:
631 query['qtree.name'] = self.parameters['qtree']
632 users_names, users_ids = [], []
633 if self.parameters.get('quota_target'):
634 type = self.parameters['type']
635 if type == 'user':
636 users_names = [target for target in self.parameters['quota_target'].split(',') if not target.isdigit()]
637 users_ids = [target for target in self.parameters['quota_target'].split(',') if target.isdigit()]
638 if users_names:
639 query['users.name'] = ",".join(users_names)
640 if users_ids:
641 query['users.id'] = ",".join(users_ids)
642 else:
643 field_name = 'group.name' if type == 'group' else 'qtree.name'
644 query[field_name] = self.parameters['quota_target']
645
646 api = 'storage/quota/rules'
647 # If type: user, get quota rules api returns users which has name starts with input target user names.
648 # Example of users list in a record:
649 # users: [{'name': 'quota_user'}], users: [{'name': 'quota_user'}, {'name': 'quota'}]
650 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
651 if error:
652 self.module.fail_json(msg="Error on getting quota rule info: %s" % error)
653 if records:
654 record = None
655 for item in records:
656 # along with user/group, qtree should also match to get current quota.
657 # for type user/group if qtree is not set in create, its not returned in GET, make desired qtree None if ''.
658 desired_qtree = self.parameters['qtree'] if self.parameters.get('qtree') else None
659 current_qtree = self.na_helper.safe_get(item, ['qtree', 'name'])
660 type = self.parameters.get('type')
661 if type in ['user', 'group']:
662 if desired_qtree != current_qtree:
663 continue
664 if type == 'user':
665 current_users = {}
666 current_users['names'] = [user['name'] for user in item['users'] if user.get('name')]
667 current_users['ids'] = [user['id'] for user in item['users'] if user.get('id')]
668 if set(current_users['names']) == set(users_names) and \
669 set(current_users['ids']) == set(users_ids):
670 record = item
671 break
672 elif item['group']['name'] == self.parameters['quota_target']:
673 record = item
674 break
675 # for type tree, desired quota_target should match current tree.
676 elif type == 'tree' and current_qtree == self.parameters['quota_target']:
677 record = item
678 break
679 if record:
680 self.volume_uuid = record['volume']['uuid']
681 self.quota_uuid = record['uuid']
682 current = {
683 'soft_file_limit': self.na_helper.safe_get(record, ['files', 'soft_limit']),
684 'disk_limit': self.na_helper.safe_get(record, ['space', 'hard_limit']),
685 'soft_disk_limit': self.na_helper.safe_get(record, ['space', 'soft_limit']),
686 'file_limit': self.na_helper.safe_get(record, ['files', 'hard_limit']),
687 'perform_user_mapping': self.na_helper.safe_get(record, ['user_mapping']),
688 }
689 # Rest allows reset quota limits using '-', convert None to '-' to avoid idempotent issue.
690 current['soft_file_limit'] = '-' if current['soft_file_limit'] is None else str(current['soft_file_limit'])
691 current['disk_limit'] = '-' if current['disk_limit'] is None else str(current['disk_limit'])
692 current['soft_disk_limit'] = '-' if current['soft_disk_limit'] is None else str(current['soft_disk_limit'])
693 current['file_limit'] = '-' if current['file_limit'] is None else str(current['file_limit'])
694 return current
695 return None
696
697 def quota_entry_set_rest(self):
698 """
699 quota_entry_set with rest API.
700 for type: 'user' and 'group', quota_target is used.
701 value for user, group and qtree should be passed as ''
702 """
703 if not self.use_rest:
704 return self.quota_entry_set()
705 body = {'svm.name': self.parameters.get('vserver'),
706 'volume.name': self.parameters.get('volume'),
707 'type': self.parameters.get('type'),
708 'qtree.name': self.parameters.get('qtree')}
709 quota_target = self.parameters.get('quota_target')
710 if self.parameters.get('type') == 'user':
711 body['users.name'] = quota_target.split(',')
712 elif self.parameters.get('type') == 'group':
713 body['group.name'] = quota_target
714 if self.parameters.get('type') == 'tree':
715 body['qtree.name'] = quota_target
716 if 'file_limit' in self.parameters:
717 body['files.hard_limit'] = self.parameters.get('file_limit')
718 if 'soft_file_limit' in self.parameters:
719 body['files.soft_limit'] = self.parameters.get('soft_file_limit')
720 if 'disk_limit' in self.parameters:
721 body['space.hard_limit'] = self.parameters.get('disk_limit')
722 if 'soft_disk_limit' in self.parameters:
723 body['space.soft_limit'] = self.parameters.get('soft_disk_limit')
724 if 'perform_user_mapping' in self.parameters:
725 body['user_mapping'] = self.parameters.get('perform_user_mapping')
726 query = {'return_records': 'true'} # in order to capture UUID
727 api = 'storage/quota/rules'
728 response, error = rest_generic.post_async(self.rest_api, api, body, query)
729 if error:
730 if "job reported error:" in error and "entry doesn't exist" in error:
731 # ignore RBAC issue with FSx - BURT1525998
732 self.module.warn('Ignoring job status, assuming success.')
733 elif '5308568' in error:
734 # code: 5308568 requires quota to be disabled/enabled to take effect.
735 # code: 5308571 - rule created, but to make it active reinitialize quota.
736 # reinitialize will disable/enable quota.
737 self.form_warn_msg_rest('create', '5308568')
738 elif '5308571' in error:
739 self.form_warn_msg_rest('create', '5308571')
740 else:
741 self.module.fail_json(msg="Error on creating quotas rule: %s" % error)
742 # fetch volume uuid as response will be None if above code error occurs.
743 self.volume_uuid = self.get_quota_status_or_volume_id_rest(get_volume=True)
744 # skip fetching volume uuid from response if volume_uuid already populated.
745 if not self.volume_uuid and response:
746 record, error = rrh.check_for_0_or_1_records(api, response, error, query)
747 if not error and record and not record['volume']['uuid']:
748 error = 'volume uuid key not present in %s:' % record
749 if error:
750 self.module.fail_json(msg='Error on getting volume uuid: %s' % error)
751 if record:
752 self.volume_uuid = record['volume']['uuid']
753
754 def quota_entry_delete_rest(self):
755 """
756 quota_entry_delete with rest API.
757 """
758 if not self.use_rest:
759 return self.quota_entry_delete()
760 api = 'storage/quota/rules'
761 dummy, error = rest_generic.delete_async(self.rest_api, api, self.quota_uuid)
762 if error is not None:
763 # delete operation succeeded, but reinitialize is required.
764 # code: 5308569 requires quota to be disabled/enabled to take effect.
765 # code: 5308572 error occurs when trying to delete last rule.
766 if '5308569' in error:
767 self.form_warn_msg_rest('delete', '5308569')
768 elif '5308572' in error:
769 self.form_warn_msg_rest('delete', '5308572')
770 else:
771 self.module.fail_json(msg="Error on deleting quotas rule: %s" % error)
772
773 def quota_entry_modify_rest(self, modify_quota):
774 """
775 quota_entry_modify with rest API.
776 User mapping cannot be turned on for multiuser quota rules.
777 """
778 if not self.use_rest:
779 return self.quota_entry_modify(modify_quota)
780 body = {}
781 if 'disk_limit' in modify_quota:
782 body['space.hard_limit'] = modify_quota['disk_limit']
783 if 'file_limit' in modify_quota:
784 body['files.hard_limit'] = modify_quota['file_limit']
785 if 'soft_disk_limit' in modify_quota:
786 body['space.soft_limit'] = modify_quota['soft_disk_limit']
787 if 'soft_file_limit' in modify_quota:
788 body['files.soft_limit'] = modify_quota['soft_file_limit']
789 if 'perform_user_mapping' in modify_quota:
790 body['user_mapping'] = modify_quota['perform_user_mapping']
791 api = 'storage/quota/rules'
792 dummy, error = rest_generic.patch_async(self.rest_api, api, self.quota_uuid, body)
793 if error is not None:
794 # limits are modified but internal error, require reinitialize quota.
795 if '5308567' in error:
796 self.form_warn_msg_rest('modify', '5308567')
797 else:
798 self.module.fail_json(msg="Error on modifying quotas rule: %s" % error)
799
800 def get_quota_status_or_volume_id_rest(self, get_volume=None):
801 """
802 Get the status info on or off
803 """
804 if not self.use_rest:
805 return self.get_quota_status()
806 api = 'storage/volumes'
807 params = {'name': self.parameters['volume'],
808 'svm.name': self.parameters['vserver'],
809 'fields': 'quota.state,uuid'}
810 record, error = rest_generic.get_one_record(self.rest_api, api, params)
811 if error:
812 msg = "volume uuid" if get_volume else "quota status info"
813 self.module.fail_json(msg="Error on getting %s: %s" % (msg, error))
814 if record:
815 return record['uuid'] if get_volume else record['quota']['state']
816 self.module.fail_json(msg="Error: Volume %s in SVM %s does not exist" % (self.parameters['volume'], self.parameters['vserver']))
817
818 def on_or_off_quota_rest(self, status, cd_action=None):
819 """
820 quota_entry_modify quota status with rest API.
821 """
822 if not self.use_rest:
823 return self.on_or_off_quota(status, cd_action)
824 body = {}
825 body['quota.enabled'] = status == 'quota-on'
826 api = 'storage/volumes'
827 if not self.volume_uuid:
828 self.volume_uuid = self.get_quota_status_or_volume_id_rest(get_volume=True)
829 dummy, error = rest_generic.patch_async(self.rest_api, api, self.volume_uuid, body)
830 if error is not None:
831 self.module.fail_json(msg='Error setting %s for %s: %s'
832 % (status, self.parameters['volume'], to_native(error)))
833
834 def form_warn_msg_rest(self, action, code):
835 start_msg = "Quota policy rule %s opertation succeeded. " % action
836 end_msg = "reinitialize(disable and enable again) the quota for volume %s " \
837 "in SVM %s." % (self.parameters['volume'], self.parameters['vserver'])
838 msg = 'unexpected code: %s' % code
839 if code == '5308572':
840 msg = "However the rule is still being enforced. To stop enforcing, "
841 if code in ['5308568', '5308569', '5308567']:
842 msg = "However quota resize failed due to an internal error. To make quotas active, "
843 if code == '5308571':
844 msg = "but quota resize is skipped. To make quotas active, "
845 self.warn_msg = start_msg + msg + end_msg
846
847 def apply(self):
848 """
849 Apply action to quotas
850 """
851 cd_action = None
852 modify_quota_status = None
853 modify_quota = None
854 current = self.get_quotas_rest()
855 if self.parameters.get('type') is not None:
856 cd_action = self.na_helper.get_cd_action(current, self.parameters)
857 if cd_action is None:
858 modify_quota = self.na_helper.get_modified_attributes(current, self.parameters)
859 quota_status = self.get_quota_status_or_volume_id_rest()
860 if 'set_quota_status' in self.parameters and quota_status is not None:
861 # if 'set_quota_status' == True in create, sometimes there is delay in status update from 'initializing' -> 'on'.
862 # if quota_status == 'on' and options(set_quota_status == True and activate_quota_on_change == 'resize'),
863 # sometimes there is delay in status update from 'resizing' -> 'on'
864 set_quota_status = True if quota_status in ('on', 'resizing', 'initializing') else False
865 quota_status_action = self.na_helper.get_modified_attributes({'set_quota_status': set_quota_status}, self.parameters)
866 if quota_status_action:
867 modify_quota_status = 'quota-on' if quota_status_action['set_quota_status'] else 'quota-off'
868 if (self.parameters.get('activate_quota_on_change') in ['resize', 'reinitialize']
869 and (cd_action is not None or modify_quota is not None)
870 and modify_quota_status is None
871 and quota_status in ('on', None)):
872 modify_quota_status = self.parameters['activate_quota_on_change']
873 if self.na_helper.changed and not self.module.check_mode:
874 if cd_action == 'create':
875 self.quota_entry_set_rest()
876 elif cd_action == 'delete':
877 self.quota_entry_delete_rest()
878 elif modify_quota:
879 self.quota_entry_modify_rest(modify_quota)
880 if modify_quota_status in ['quota-off', 'quota-on']:
881 self.on_or_off_quota_rest(modify_quota_status)
882 elif modify_quota_status == 'resize':
883 if not self.use_rest:
884 self.resize_quota(cd_action)
885 elif modify_quota_status == 'reinitialize':
886 self.on_or_off_quota_rest('quota-off')
887 time.sleep(10) # status switch interval
888 self.on_or_off_quota_rest('quota-on', cd_action)
889 # if warn message and quota not reinitialize, throw warnings to reinitialize in REST.
890 if self.warn_msg and modify_quota_status != 'reinitialize':
891 self.module.warn(self.warn_msg)
892 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify_quota, extra_responses={'modify_quota_status': modify_quota_status})
893 self.module.exit_json(**result)
894
895 def convert_to_kb_or_bytes(self, option):
896 """
897 convert input to kb, and set to self.parameters.
898 :param option: disk_limit or soft_disk_limit.
899 :return: boolean if it can be converted.
900 """
901 self.parameters[option].replace(' ', '')
902 slices = re.findall(r"\d+|\D+", self.parameters[option])
903 if len(slices) < 1 or len(slices) > 2:
904 return False
905 if not slices[0].isdigit():
906 return False
907 if len(slices) > 1 and slices[1].lower() not in ['b', 'kb', 'mb', 'gb', 'tb']:
908 return False
909 # force kb as the default unit for REST
910 if len(slices) == 1 and self.use_rest:
911 slices = (slices[0], 'kb')
912 if len(slices) > 1:
913 if not self.use_rest:
914 # conversion to KB
915 self.parameters[option] = str(int(slices[0]) * netapp_utils.POW2_BYTE_MAP[slices[1].lower()] // 1024)
916 else:
917 # conversion to Bytes
918 self.parameters[option] = str(int(slices[0]) * netapp_utils.POW2_BYTE_MAP[slices[1].lower()])
919 if self.use_rest:
920 # Rounding off the converted bytes
921 self.parameters[option] = str(((int(self.parameters[option]) + 1023) // 1024) * 1024)
922 return True
923
924
925 def main():
926 '''Execute action'''
927 quota_obj = NetAppONTAPQuotas()
928 quota_obj.apply()
929
930
931 if __name__ == '__main__':
932 main()