Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # Copyright: (c) 2021-2025, Dell Technologies
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt))
4
5 """Ansible module for managing quota tree on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: tree_quota
14 short_description: Manage quota tree on the Unity storage system
15 description:
16 - Managing Quota tree on the Unity storage system includes
17 Create quota tree,
18 Get quota tree,
19 Modify quota tree and
20 Delete quota tree.
21 version_added: '1.2.0'
22 extends_documentation_fragment:
23 - dellemc.unity.unity
24 author:
25 - Spandita Panigrahi (@panigs7) <[email protected]>
26 options:
27 filesystem_name:
28 description:
29 - The name of the filesystem for which quota tree is created.
30 - For creation or modification of a quota tree either I(filesystem_name) or
31 I(filesystem_id) is required.
32 type: str
33 filesystem_id:
34 description:
35 - The ID of the filesystem for which the quota tree is created.
36 - For creation of a quota tree either I(filesystem_id) or
37 I(filesystem_name) is required.
38 type: str
39 nas_server_name:
40 description:
41 - The name of the NAS server in which the filesystem is created.
42 - For creation of a quota tree either I(nas_server_name) or
43 I(nas_server_id) is required.
44 type: str
45 nas_server_id:
46 description:
47 - The ID of the NAS server in which the filesystem is created.
48 - For creation of a quota tree either I(filesystem_id) or
49 I(filesystem_name) is required.
50 type: str
51 tree_quota_id:
52 description:
53 - The ID of the quota tree.
54 - Either I(tree_quota_id) or I(path) to quota tree is required to
55 view/modify/delete quota tree.
56 type: str
57 path:
58 description:
59 - The path to the quota tree.
60 - Either I(tree_quota_id) or I(path) to quota tree is required to
61 create/view/modify/delete a quota tree.
62 - Path must start with a forward slash '/'.
63 type: str
64 hard_limit:
65 description:
66 - Hard limitation for a quota tree on the total space available. If exceeded,
67 users in quota tree cannot write data.
68 - Value C(0) implies no limit.
69 - One of the values of I(soft_limit) and I(hard_limit) can be C(0), however, both cannot be both C(0)
70 during creation of a quota tree.
71 type: int
72 soft_limit:
73 description:
74 - Soft limitation for a quota tree on the total space available. If exceeded,
75 notification will be sent to users in the quota tree for the grace period mentioned, beyond
76 which users cannot use space.
77 - Value C(0) implies no limit.
78 - Both I(soft_limit) and I(hard_limit) cannot be C(0) during creation of quota tree.
79 type: int
80 cap_unit:
81 description:
82 - Unit of I(soft_limit) and I(hard_limit) size.
83 - It defaults to C(GB) if not specified.
84 choices: ['MB', 'GB', 'TB']
85 type: str
86 description:
87 description:
88 - Description of a quota tree.
89 type: str
90 state:
91 description:
92 - The state option is used to mention the existence of the filesystem
93 quota tree.
94 type: str
95 required: true
96 choices: ['absent', 'present']
97
98 notes:
99 - The I(check_mode) is not supported.
100 '''
101
102 EXAMPLES = r'''
103 - name: Get quota tree details by quota tree id
104 tree_quota:
105 unispherehost: "{{unispherehost}}"
106 username: "{{username}}"
107 password: "{{password}}"
108 validate_certs: "{{validate_certs}}"
109 tree_quota_id: "treequota_171798700679_10"
110 state: "present"
111
112 - name: Get quota tree details by quota tree path
113 tree_quota:
114 unispherehost: "{{unispherehost}}"
115 username: "{{username}}"
116 password: "{{password}}"
117 validate_certs: "{{validate_certs}}"
118 filesystem_name: "fs_2171"
119 nas_server_id: "nas_21"
120 path: "/test"
121 state: "present"
122
123 - name: Create quota tree for a filesystem with filesystem id
124 tree_quota:
125 unispherehost: "{{unispherehost}}"
126 username: "{{username}}"
127 password: "{{password}}"
128 validate_certs: "{{validate_certs}}"
129 filesystem_id: "fs_2171"
130 hard_limit: 6
131 cap_unit: "TB"
132 soft_limit: 5
133 path: "/test_new"
134 state: "present"
135
136 - name: Create quota tree for a filesystem with filesystem name
137 tree_quota:
138 unispherehost: "{{unispherehost}}"
139 username: "{{username}}"
140 password: "{{password}}"
141 validate_certs: "{{validate_certs}}"
142 filesystem_name: "Test_filesystem"
143 nas_server_name: "lglad068"
144 hard_limit: 6
145 cap_unit: "TB"
146 soft_limit: 5
147 path: "/test_new"
148 state: "present"
149
150 - name: Modify quota tree limit usage by quota tree path
151 tree_quota:
152 unispherehost: "{{unispherehost}}"
153 username: "{{username}}"
154 password: "{{password}}"
155 validate_certs: "{{validate_certs}}"
156 path: "/test_new"
157 hard_limit: 10
158 cap_unit: "TB"
159 soft_limit: 8
160 state: "present"
161
162 - name: Modify quota tree by quota tree id
163 tree_quota:
164 unispherehost: "{{unispherehost}}"
165 username: "{{username}}"
166 password: "{{password}}"
167 validate_certs: "{{validate_certs}}"
168 filesystem_id: "fs_2171"
169 tree_quota_id: "treequota_171798700679_10"
170 hard_limit: 12
171 cap_unit: "TB"
172 soft_limit: 10
173 state: "present"
174
175 - name: Delete quota tree by quota tree id
176 tree_quota:
177 unispherehost: "{{unispherehost}}"
178 username: "{{username}}"
179 password: "{{password}}"
180 validate_certs: "{{validate_certs}}"
181 filesystem_id: "fs_2171"
182 tree_quota_id: "treequota_171798700679_10"
183 state: "absent"
184
185 - name: Delete quota tree by path
186 tree_quota:
187 unispherehost: "{{unispherehost}}"
188 username: "{{username}}"
189 password: "{{password}}"
190 validate_certs: "{{validate_certs}}"
191 filesystem_id: "fs_2171"
192 path: "/test_new"
193 state: "absent"
194 '''
195
196 RETURN = r'''
197 changed:
198 description: Whether or not the resource has changed.
199 returned: always
200 type: bool
201 sample: true
202
203 get_tree_quota_details:
204 description: Details of the quota tree.
205 returned: When quota tree exists
206 type: dict
207 contains:
208 filesystem:
209 description: Filesystem details for which the quota
210 tree is created.
211 type: dict
212 contains:
213 UnityFileSystem:
214 description: Filesystem details for which the
215 quota tree is created.
216 type: dict
217 contains:
218 id:
219 description: ID of the filesystem for
220 which the quota tree is create.
221 type: str
222 description:
223 description: Description of the quota tree.
224 type: str
225 path:
226 description: Path to quota tree.
227 A valid path must start with a forward slash '/'.
228 It is mandatory while creating a quota tree.
229 type: str
230 hard_limit:
231 description: Hard limit of quota tree.
232 If the quota tree's space usage exceeds
233 the hard limit, users in quota tree cannot write data.
234 type: int
235 soft_limit:
236 description: Soft limit of the quota tree.
237 If the quota tree's space usage exceeds the soft limit,
238 the storage system starts to count down based
239 on the specified grace period.
240 type: int
241 id:
242 description: Quota tree ID.
243 type: str
244 size_used:
245 description: Size of used space in the filesystem by the user files.
246 type: int
247 gp_left:
248 description: The grace period left after the
249 soft limit for the user quota is exceeded.
250 type: int
251 state:
252 description: State of the quota tree.
253 type: int
254 sample: {
255 "description": "",
256 "existed": true,
257 "filesystem": {
258 "UnityFileSystem": {
259 "hash": 8788549469862,
260 "id": "fs_137",
261 "name": "test",
262 "nas_server": {
263 "id": "nas_1",
264 "name": "lglad072"
265 }
266 }
267 },
268 "gp_left": null,
269 "hard_limit": "6.0 TB",
270 "hash": 8788549497558,
271 "id": "treequota_171798694897_1",
272 "path": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
273 "size_used": 0,
274 "soft_limit": "5.0 TB",
275 "state": 0
276 }
277 '''
278
279 from ansible.module_utils.basic import AnsibleModule
280 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
281 import utils
282
283 LOG = utils.get_logger('tree_quota')
284
285 application_type = "Ansible/1.7.1"
286
287
288 class QuotaTree(object):
289 """Class with Quota Tree operations"""
290
291 def __init__(self):
292 """Define all parameters required by this module"""
293 self.module_params = utils.get_unity_management_host_parameters()
294 self.module_params.update(get_quota_tree_parameters())
295
296 mutually_exclusive = [['filesystem_name', 'filesystem_id'],
297 ['nas_server_name', 'nas_server_id']]
298
299 # initialize the Ansible module
300 self.module = AnsibleModule(
301 argument_spec=self.module_params,
302 supports_check_mode=False,
303 mutually_exclusive=mutually_exclusive)
304 utils.ensure_required_libs(self.module)
305
306 self.unity_conn = utils.get_unity_unisphere_connection(
307 self.module.params, application_type)
308
309 def check_quota_tree_is_present(self, fs_id, path, tree_quota_id):
310 """
311 Check if quota tree is present in filesystem.
312 :param fs_id: ID of filesystem where quota tree is searched.
313 :param path: Path to the quota tree
314 :param tree_quota_id: ID of the quota tree
315 :return: ID of quota tree if it exists else None.
316 """
317 if tree_quota_id is None and path is None:
318 return None
319
320 all_tree_quota = self.unity_conn.get_tree_quota(filesystem=fs_id,
321 id=tree_quota_id,
322 path=path)
323
324 if tree_quota_id and len(all_tree_quota) == 0 \
325 and self.module.params['state'] == "present":
326 errormsg = "Tree quota %s does not exist." % tree_quota_id
327 LOG.error(errormsg)
328 self.module.fail_json(msg=errormsg)
329
330 if len(all_tree_quota) > 0:
331 msg = "Quota tree with id %s is present in filesystem %s" % (all_tree_quota[0].id,
332 fs_id)
333 LOG.info(msg)
334 return all_tree_quota[0].id
335 else:
336 return None
337
338 def create_quota_tree(self, fs_id, soft_limit, hard_limit, unit, path, description):
339 """
340 Create quota tree of a filesystem.
341 :param fs_id: ID of filesystem where quota tree is to be created.
342 :param soft_limit: Soft limit
343 :param hard_limit: Hard limit
344 :param unit: Unit of soft limit and hard limit
345 :param path: Path to quota tree
346 :param description: Description for quota tree
347 :return: Dict containing new quota tree details.
348 """
349
350 if soft_limit is None and hard_limit is None:
351 errormsg = "Both soft limit and hard limit cannot be empty. " \
352 "Please provide atleast one to create quota tree."
353 LOG.error(errormsg)
354 self.module.fail_json(msg=errormsg)
355
356 soft_limit_in_bytes = utils.get_size_bytes(soft_limit, unit)
357 hard_limit_in_bytes = utils.get_size_bytes(hard_limit, unit)
358 try:
359 obj_tree_quota = self.unity_conn.create_tree_quota(filesystem_id=fs_id, hard_limit=hard_limit_in_bytes,
360 soft_limit=soft_limit_in_bytes, path=path,
361 description=description)
362 LOG.info("Successfully created quota tree")
363
364 if obj_tree_quota:
365 return obj_tree_quota
366 else:
367 return None
368
369 except Exception as e:
370 errormsg = "Create quota tree operation at path {0} failed in filesystem {1}" \
371 " with error {2}".format(path, fs_id, str(e))
372 LOG.error(errormsg)
373 self.module.fail_json(msg=errormsg)
374
375 def get_filesystem_tree_quota_display_attributes(self, tree_quota_id):
376 """Display quota tree attributes
377 :param tree_quota_id: Quota tree ID
378 :return: Quota tree dict to display
379 """
380 try:
381 tree_quota_obj = self.unity_conn.get_tree_quota(_id=tree_quota_id)
382 tree_quota_details = tree_quota_obj._get_properties()
383 if tree_quota_obj and tree_quota_obj.existed:
384 tree_quota_details['soft_limit'] = utils. \
385 convert_size_with_unit(int(tree_quota_details['soft_limit']))
386 tree_quota_details['hard_limit'] = utils. \
387 convert_size_with_unit(int(tree_quota_details['hard_limit']))
388
389 tree_quota_details['filesystem']['UnityFileSystem']['name'] = \
390 tree_quota_obj.filesystem.name
391 tree_quota_details['filesystem']['UnityFileSystem'].update(
392 {'nas_server': {'name': tree_quota_obj.filesystem.nas_server.name,
393 'id': tree_quota_obj.filesystem.nas_server.id}})
394 return tree_quota_details
395
396 except Exception as e:
397 errormsg = "Failed to display quota tree details {0} with " \
398 "error {1}".format(tree_quota_obj.id, str(e))
399 LOG.error(errormsg)
400 self.module.fail_json(msg=errormsg)
401
402 def get_filesystem(self, nas_server=None, name=None, id=None):
403 """
404 Get filesystem details.
405 :param nas_server: Nas server object.
406 :param name: Name of filesystem.
407 :param id: ID of filesystem.
408 :return: Dict containing filesystem details if it exists.
409 """
410 id_or_name = id if id else name
411 try:
412 obj_fs = None
413 if name:
414 if not nas_server:
415 err_msg = "NAS Server is required to get the FileSystem."
416 LOG.error(err_msg)
417 self.module.fail_json(msg=err_msg)
418 obj_fs = self.unity_conn.get_filesystem(name=name,
419 nas_server=nas_server)
420 if obj_fs and obj_fs.existed:
421 LOG.info("Successfully got the filesystem object %s.",
422 obj_fs)
423 return obj_fs
424 if id:
425 if nas_server:
426 obj_fs = self.unity_conn \
427 .get_filesystem(id=id, nas_server=nas_server)
428 else:
429 obj_fs = self.unity_conn.get_filesystem(id=id)
430 if obj_fs and obj_fs.existed:
431 LOG.info("Successfully got the filesystem object %s.",
432 obj_fs)
433 return obj_fs
434 except Exception as e:
435 error_msg = "Failed to get filesystem %s with error %s." \
436 % (id_or_name, str(e))
437 LOG.error(error_msg)
438 self.module.fail_json(msg=error_msg)
439
440 def get_nas_server_obj(self, name=None, id=None):
441 """
442 Get nas server details.
443 :param name: Nas server name.
444 :param id: Nas server ID.
445 :return: Dict containing nas server details if it exists.
446 """
447 nas_server = id if id else name
448 error_msg = ("Failed to get NAS server %s." % nas_server)
449 try:
450 obj_nas = self.unity_conn.get_nas_server(_id=id, name=name)
451 if name and obj_nas.existed:
452 LOG.info("Successfully got the NAS server object %s.",
453 obj_nas)
454 return obj_nas
455 elif id and obj_nas.existed:
456 LOG.info("Successfully got the NAS server object %s.",
457 obj_nas)
458 return obj_nas
459 else:
460 LOG.error(error_msg)
461 self.module.fail_json(msg=error_msg)
462 except Exception as e:
463 error_msg = "Failed to get NAS server %s with error %s." \
464 % (nas_server, str(e))
465 LOG.error(error_msg)
466 self.module.fail_json(msg=error_msg)
467
468 def modify_tree_quota(self, tree_quota_id, soft_limit, hard_limit, unit, description):
469 """
470 Modify quota tree of filesystem.
471 :param tree_quota_id: ID of the quota tree
472 :param soft_limit: Soft limit
473 :param hard_limit: Hard limit
474 :param unit: Unit of soft limit and hard limit
475 :param description: Description of quota tree
476 :return: Boolean value whether modify quota tree operation is successful.
477 """
478 try:
479 if soft_limit is None and hard_limit is None:
480 return False
481 tree_quota_obj = self.unity_conn.get_tree_quota(tree_quota_id)._get_properties()
482 if soft_limit is None:
483 soft_limit_in_bytes = tree_quota_obj['soft_limit']
484 else:
485 soft_limit_in_bytes = utils.get_size_bytes(soft_limit, unit)
486 if hard_limit is None:
487 hard_limit_in_bytes = tree_quota_obj['hard_limit']
488 else:
489 hard_limit_in_bytes = utils.get_size_bytes(hard_limit, unit)
490
491 if description is None:
492 description = tree_quota_obj['description']
493
494 if tree_quota_obj:
495 if tree_quota_obj['soft_limit'] == soft_limit_in_bytes and \
496 tree_quota_obj['hard_limit'] == hard_limit_in_bytes and \
497 tree_quota_obj['description'] == description:
498 return False
499 else:
500 modify_tree_quota = self.unity_conn.modify_tree_quota(tree_quota_id=tree_quota_id,
501 hard_limit=hard_limit_in_bytes,
502 soft_limit=soft_limit_in_bytes,
503 description=description)
504 LOG.info("Successfully modified quota tree")
505 if modify_tree_quota:
506 return True
507 except Exception as e:
508 errormsg = "Modify quota tree operation {0} failed" \
509 " with error {1}".format(tree_quota_id, str(e))
510 LOG.error(errormsg)
511 self.module.fail_json(msg=errormsg)
512
513 def delete_tree_quota(self, tree_quota_id):
514 """
515 Delete quota tree of a filesystem.
516 :param tree_quota_id: ID of quota tree
517 :return: Boolean whether quota tree is deleted
518 """
519
520 try:
521 delete_tree_quota_obj = self.unity_conn.delete_tree_quota(tree_quota_id=tree_quota_id)
522
523 if delete_tree_quota_obj:
524 return True
525
526 except Exception as e:
527 errormsg = "Delete operation of quota tree id:{0} " \
528 "failed with error {1}".format(tree_quota_id,
529 str(e))
530 LOG.error(errormsg)
531 self.module.fail_json(msg=errormsg)
532
533 def perform_module_operation(self):
534 """
535 Perform different actions on quota tree module based on parameters
536 passed in the playbook
537 """
538 filesystem_id = self.module.params['filesystem_id']
539 filesystem_name = self.module.params['filesystem_name']
540 nas_server_name = self.module.params['nas_server_name']
541 nas_server_id = self.module.params['nas_server_id']
542 cap_unit = self.module.params['cap_unit']
543 state = self.module.params['state']
544 hard_limit = self.module.params['hard_limit']
545 soft_limit = self.module.params['soft_limit']
546 path = self.module.params['path']
547 description = self.module.params['description']
548 tree_quota_id = self.module.params['tree_quota_id']
549 create_tree_quota_obj = None
550 nas_server_resource = None
551 fs_id = None
552
553 '''
554 result is a dictionary to contain end state and quota tree details
555 '''
556 result = dict(
557 changed=False,
558 create_tree_quota=False,
559 modify_tree_quota=False,
560 get_tree_quota_details={},
561 delete_tree_quota=False
562
563 )
564
565 if (soft_limit or hard_limit) and cap_unit is None:
566 cap_unit = 'GB'
567
568 if soft_limit and utils.is_size_negative(soft_limit):
569 error_message = "Invalid soft_limit provided, " \
570 "must be greater than or equal to 0"
571 LOG.error(error_message)
572 self.module.fail_json(msg=error_message)
573
574 if hard_limit and utils.is_size_negative(hard_limit):
575 error_message = "Invalid hard_limit provided, " \
576 "must be greater than or equal to 0"
577 LOG.error(error_message)
578 self.module.fail_json(msg=error_message)
579
580 '''
581 Get NAS server Object
582 '''
583
584 if nas_server_name is not None:
585 if utils.is_input_empty(nas_server_name):
586 self.module.fail_json(msg="Invalid nas_server_name given,"
587 " Please provide a valid name.")
588 nas_server_resource = self \
589 .get_nas_server_obj(name=nas_server_name)
590 elif nas_server_id is not None:
591 if utils.is_input_empty(nas_server_id):
592 self.module.fail_json(msg="Invalid nas_server_id given,"
593 " Please provide a valid ID.")
594 nas_server_resource = self.get_nas_server_obj(id=nas_server_id)
595
596 '''
597 Get filesystem Object
598 '''
599 if filesystem_name is not None:
600 if utils.is_input_empty(filesystem_name):
601 self.module.fail_json(msg="Invalid filesystem_name given,"
602 " Please provide a valid name.")
603 filesystem_obj = self \
604 .get_filesystem(nas_server=nas_server_resource,
605 name=filesystem_name)
606 fs_id = filesystem_obj.id
607 elif filesystem_id is not None:
608 if utils.is_input_empty(filesystem_id):
609 self.module.fail_json(msg="Invalid filesystem_id given,"
610 " Please provide a valid ID.")
611 filesystem_obj = self \
612 .get_filesystem(id=filesystem_id)
613 if filesystem_obj:
614 fs_id = filesystem_obj[0].id
615 else:
616 self.module.fail_json(msg="Filesystem does not exist.")
617
618 '''
619 Validate path to quota tree
620 '''
621 if path is not None:
622 if utils.is_input_empty(path):
623 self.module.fail_json(msg=" Please provide a valid path.")
624 elif not path.startswith('/'):
625 self.module.fail_json(msg="The path is relative to the root of the file system "
626 "and must start with a forward slash '/'.")
627
628 if filesystem_id is None and filesystem_name is None:
629 self.module.fail_json(msg="Please provide either filesystem_name or fileystem_id.")
630
631 quota_tree_id_present = self.check_quota_tree_is_present(fs_id, path, tree_quota_id)
632 tree_quota_id = quota_tree_id_present
633
634 '''
635 Create quota tree
636 '''
637
638 if (filesystem_id or filesystem_name) and path is not None and state == "present":
639 if not tree_quota_id:
640 LOG.info("Creating quota tree")
641 create_tree_quota_obj = self.create_quota_tree(fs_id, soft_limit, hard_limit,
642 cap_unit, path, description)
643
644 if create_tree_quota_obj:
645 tree_quota_id = create_tree_quota_obj.id
646 result['create_tree_quota'] = True
647
648 '''
649 Modify quota tree
650 '''
651
652 if tree_quota_id and state == "present":
653 LOG.info("Modifying quota tree")
654 result['modify_tree_quota'] = self.modify_tree_quota(tree_quota_id, soft_limit, hard_limit, cap_unit,
655 description)
656
657 '''
658 Delete quota tree
659 '''
660
661 if tree_quota_id is not None and state == "absent":
662 LOG.info("Deleting quota tree")
663 result['delete_tree_quota'] = self.delete_tree_quota(tree_quota_id)
664
665 '''
666 Get quota tree details
667 '''
668 if state == "present" and tree_quota_id is not None:
669 result['get_tree_quota_details'] = self.get_filesystem_tree_quota_display_attributes(tree_quota_id)
670 else:
671 result['get_tree_quota_details'] = {}
672
673 if result['create_tree_quota'] or result['modify_tree_quota'] or result['delete_tree_quota']:
674 result['changed'] = True
675
676 self.module.exit_json(**result)
677
678
679 def get_quota_tree_parameters():
680 """This method provide parameters required for the ansible
681 quota tree module on Unity"""
682 return dict(
683 filesystem_id=dict(required=False, type='str'),
684 filesystem_name=dict(required=False, type='str'),
685 state=dict(required=True, type='str', choices=['present', 'absent']),
686 hard_limit=dict(required=False, type='int'),
687 soft_limit=dict(required=False, type='int'),
688 cap_unit=dict(required=False, type='str', choices=['MB', 'GB', 'TB']),
689 tree_quota_id=dict(required=False, type='str'),
690 nas_server_name=dict(required=False, type='str'),
691 nas_server_id=dict(required=False, type='str'),
692 path=dict(required=False, type='str', no_log=True),
693 description=dict(required=False, type='str')
694 )
695
696
697 def main():
698 """ Create Unity quota tree object and perform action on it
699 based on user input from playbook"""
700 obj = QuotaTree()
701 obj.perform_module_operation()
702
703
704 if __name__ == '__main__':
705 main()