Debian Codegraph @

ansible_collections/community/general/plugins/modules/xfs_quota.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2018, Emmanouil Kampitakis <[email protected]>
4 # Copyright (c) 2018, William Leemans <[email protected]>
5
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: xfs_quota
13 short_description: Manage quotas on XFS filesystems
14 description:
15 - Configure quotas on XFS filesystems.
16 - Before using this module /etc/projects and /etc/projid need to be configured.
17 author:
18 - William Leemans (@bushvin)
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 type:
28 description:
29 - The XFS quota type.
30 type: str
31 required: true
32 choices:
33 - user
34 - group
35 - project
36 name:
37 description:
38 - The name of the user, group or project to apply the quota to, if other than default.
39 type: str
40 mountpoint:
41 description:
42 - The mount point on which to apply the quotas.
43 type: str
44 required: true
45 bhard:
46 description:
47 - Hard blocks quota limit.
48 - This argument supports human readable sizes.
49 type: str
50 bsoft:
51 description:
52 - Soft blocks quota limit.
53 - This argument supports human readable sizes.
54 type: str
55 ihard:
56 description:
57 - Hard inodes quota limit.
58 type: int
59 isoft:
60 description:
61 - Soft inodes quota limit.
62 type: int
63 rtbhard:
64 description:
65 - Hard realtime blocks quota limit.
66 - This argument supports human readable sizes.
67 type: str
68 rtbsoft:
69 description:
70 - Soft realtime blocks quota limit.
71 - This argument supports human readable sizes.
72 type: str
73 state:
74 description:
75 - Whether to apply the limits or remove them.
76 - When removing limit, they are set to 0, and not quite removed.
77 type: str
78 default: present
79 choices:
80 - present
81 - absent
82
83 requirements:
84 - xfsprogs
85 """
86
87 EXAMPLES = r"""
88 - name: Set default project soft and hard limit on /opt of 1g
89 community.general.xfs_quota:
90 type: project
91 mountpoint: /opt
92 bsoft: 1g
93 bhard: 1g
94 state: present
95
96 - name: Remove the default limits on /opt
97 community.general.xfs_quota:
98 type: project
99 mountpoint: /opt
100 state: absent
101
102 - name: Set default soft user inode limits on /home of 1024 inodes and hard of 2048
103 community.general.xfs_quota:
104 type: user
105 mountpoint: /home
106 isoft: 1024
107 ihard: 2048
108 """
109
110 RETURN = r"""
111 bhard:
112 description: The current C(bhard) setting in bytes.
113 returned: always
114 type: int
115 sample: 1024
116 bsoft:
117 description: The current C(bsoft) setting in bytes.
118 returned: always
119 type: int
120 sample: 1024
121 ihard:
122 description: The current C(ihard) setting in bytes.
123 returned: always
124 type: int
125 sample: 100
126 isoft:
127 description: The current C(isoft) setting in bytes.
128 returned: always
129 type: int
130 sample: 100
131 rtbhard:
132 description: The current C(rtbhard) setting in bytes.
133 returned: always
134 type: int
135 sample: 1024
136 rtbsoft:
137 description: The current C(rtbsoft) setting in bytes.
138 returned: always
139 type: int
140 sample: 1024
141 """
142
143 import grp
144 import os
145 import pwd
146
147 from ansible.module_utils.basic import AnsibleModule, human_to_bytes
148
149
150 def main():
151 module = AnsibleModule(
152 argument_spec=dict(
153 bhard=dict(type="str"),
154 bsoft=dict(type="str"),
155 ihard=dict(type="int"),
156 isoft=dict(type="int"),
157 mountpoint=dict(type="str", required=True),
158 name=dict(type="str"),
159 rtbhard=dict(type="str"),
160 rtbsoft=dict(type="str"),
161 state=dict(type="str", default="present", choices=["absent", "present"]),
162 type=dict(type="str", required=True, choices=["group", "project", "user"]),
163 ),
164 supports_check_mode=True,
165 )
166
167 quota_type = module.params["type"]
168 name = module.params["name"]
169 mountpoint = module.params["mountpoint"]
170 bhard = module.params["bhard"]
171 bsoft = module.params["bsoft"]
172 ihard = module.params["ihard"]
173 isoft = module.params["isoft"]
174 rtbhard = module.params["rtbhard"]
175 rtbsoft = module.params["rtbsoft"]
176 state = module.params["state"]
177
178 xfs_quota_bin = module.get_bin_path("xfs_quota", True)
179
180 if bhard is not None:
181 bhard = human_to_bytes(bhard)
182
183 if bsoft is not None:
184 bsoft = human_to_bytes(bsoft)
185
186 if rtbhard is not None:
187 rtbhard = human_to_bytes(rtbhard)
188
189 if rtbsoft is not None:
190 rtbsoft = human_to_bytes(rtbsoft)
191
192 result = dict(
193 changed=False,
194 )
195
196 if not os.path.ismount(mountpoint):
197 module.fail_json(msg=f"Path '{mountpoint}' is not a mount point", **result)
198
199 mp = get_fs_by_mountpoint(mountpoint)
200 if mp is None:
201 module.fail_json(
202 msg=f"Path '{mountpoint}' is not a mount point or not located on an xfs file system.", **result
203 )
204
205 if quota_type == "user":
206 type_arg = "-u"
207 quota_default = "root"
208 if name is None:
209 name = quota_default
210
211 if (
212 "uquota" not in mp["mntopts"]
213 and "usrquota" not in mp["mntopts"]
214 and "quota" not in mp["mntopts"]
215 and "uqnoenforce" not in mp["mntopts"]
216 and "qnoenforce" not in mp["mntopts"]
217 ):
218 module.fail_json(
219 msg=f"Path '{mountpoint}' is not mounted with the uquota/usrquota/quota/uqnoenforce/qnoenforce option.",
220 **result,
221 )
222 try:
223 pwd.getpwnam(name)
224 except KeyError:
225 module.fail_json(msg=f"User '{name}' does not exist.", **result)
226
227 elif quota_type == "group":
228 type_arg = "-g"
229 quota_default = "root"
230 if name is None:
231 name = quota_default
232
233 if "gquota" not in mp["mntopts"] and "grpquota" not in mp["mntopts"] and "gqnoenforce" not in mp["mntopts"]:
234 module.fail_json(
235 msg=f"Path '{mountpoint}' is not mounted with the gquota/grpquota/gqnoenforce option. (current options: {mp['mntopts']})",
236 **result,
237 )
238 try:
239 grp.getgrnam(name)
240 except KeyError:
241 module.fail_json(msg=f"User '{name}' does not exist.", **result)
242
243 elif quota_type == "project":
244 type_arg = "-p"
245 quota_default = "#0"
246 if name is None:
247 name = quota_default
248
249 if "pquota" not in mp["mntopts"] and "prjquota" not in mp["mntopts"] and "pqnoenforce" not in mp["mntopts"]:
250 module.fail_json(
251 msg=f"Path '{mountpoint}' is not mounted with the pquota/prjquota/pqnoenforce option.", **result
252 )
253
254 if name != quota_default and not os.path.isfile("/etc/projects"):
255 module.fail_json(msg="Path '/etc/projects' does not exist.", **result)
256
257 if name != quota_default and not os.path.isfile("/etc/projid"):
258 module.fail_json(msg="Path '/etc/projid' does not exist.", **result)
259
260 if name != quota_default and name is not None and get_project_id(name) is None:
261 module.fail_json(msg=f"Entry '{name}' has not been defined in /etc/projid.", **result)
262
263 prj_set = True
264 if name != quota_default:
265 cmd = f"project {name}"
266 rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd, mountpoint)
267 if rc != 0:
268 result["cmd"] = cmd
269 result["rc"] = rc
270 result["stdout"] = stdout
271 result["stderr"] = stderr
272 module.fail_json(msg="Could not get project state.", **result)
273 else:
274 for line in stdout.split("\n"):
275 if "Project Id '%s' - is not set." in line or "project identifier is not set" in line:
276 prj_set = False
277 break
278
279 if state == "present" and not prj_set:
280 if not module.check_mode:
281 cmd = f"project -s {name}"
282 rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd, mountpoint)
283 if rc != 0:
284 result["cmd"] = cmd
285 result["rc"] = rc
286 result["stdout"] = stdout
287 result["stderr"] = stderr
288 module.fail_json(msg="Could not get quota realtime block report.", **result)
289
290 result["changed"] = True
291
292 elif state == "absent" and prj_set and name != quota_default:
293 if not module.check_mode:
294 cmd = f"project -C {name}"
295 rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd, mountpoint)
296 if rc != 0:
297 result["cmd"] = cmd
298 result["rc"] = rc
299 result["stdout"] = stdout
300 result["stderr"] = stderr
301 module.fail_json(msg="Failed to clear managed tree from project quota control.", **result)
302
303 result["changed"] = True
304
305 current_bsoft, current_bhard = quota_report(module, xfs_quota_bin, mountpoint, name, quota_type, "b")
306 current_isoft, current_ihard = quota_report(module, xfs_quota_bin, mountpoint, name, quota_type, "i")
307 current_rtbsoft, current_rtbhard = quota_report(module, xfs_quota_bin, mountpoint, name, quota_type, "rtb")
308
309 # Set limits
310 if state == "absent":
311 bhard = 0
312 bsoft = 0
313 ihard = 0
314 isoft = 0
315 rtbhard = 0
316 rtbsoft = 0
317
318 # Ensure that a non-existing quota does not trigger a change
319 current_bsoft = current_bsoft if current_bsoft is not None else 0
320 current_bhard = current_bhard if current_bhard is not None else 0
321 current_isoft = current_isoft if current_isoft is not None else 0
322 current_ihard = current_ihard if current_ihard is not None else 0
323 current_rtbsoft = current_rtbsoft if current_rtbsoft is not None else 0
324 current_rtbhard = current_rtbhard if current_rtbhard is not None else 0
325
326 result["xfs_quota"] = dict(
327 bsoft=current_bsoft,
328 bhard=current_bhard,
329 isoft=current_isoft,
330 ihard=current_ihard,
331 rtbsoft=current_rtbsoft,
332 rtbhard=current_rtbhard,
333 )
334
335 limit = []
336 if bsoft is not None and int(bsoft) != current_bsoft:
337 limit.append(f"bsoft={bsoft}")
338 result["bsoft"] = int(bsoft)
339
340 if bhard is not None and int(bhard) != current_bhard:
341 limit.append(f"bhard={bhard}")
342 result["bhard"] = int(bhard)
343
344 if isoft is not None and isoft != current_isoft:
345 limit.append(f"isoft={isoft}")
346 result["isoft"] = isoft
347
348 if ihard is not None and ihard != current_ihard:
349 limit.append(f"ihard={ihard}")
350 result["ihard"] = ihard
351
352 if rtbsoft is not None and int(rtbsoft) != current_rtbsoft:
353 limit.append(f"rtbsoft={rtbsoft}")
354 result["rtbsoft"] = int(rtbsoft)
355
356 if rtbhard is not None and int(rtbhard) != current_rtbhard:
357 limit.append(f"rtbhard={rtbhard}")
358 result["rtbhard"] = int(rtbhard)
359
360 if len(limit) > 0:
361 if not module.check_mode:
362 if name == quota_default:
363 cmd = f"limit {type_arg} -d {' '.join(limit)}"
364 else:
365 cmd = f"limit {type_arg} {' '.join(limit)} {name}"
366
367 rc, stdout, stderr = exec_quota(module, xfs_quota_bin, cmd, mountpoint)
368 if rc != 0:
369 result["cmd"] = cmd
370 result["rc"] = rc
371 result["stdout"] = stdout
372 result["stderr"] = stderr
373 module.fail_json(msg="Could not set limits.", **result)
374
375 result["changed"] = True
376
377 module.exit_json(**result)
378
379
380 def quota_report(module, xfs_quota_bin, mountpoint, name, quota_type, used_type):
381 soft = None
382 hard = None
383
384 if quota_type == "project":
385 type_arg = "-p"
386 elif quota_type == "user":
387 type_arg = "-u"
388 elif quota_type == "group":
389 type_arg = "-g"
390
391 if used_type == "b":
392 used_arg = "-b"
393 used_name = "blocks"
394 factor = 1024
395 elif used_type == "i":
396 used_arg = "-i"
397 used_name = "inodes"
398 factor = 1
399 elif used_type == "rtb":
400 used_arg = "-r"
401 used_name = "realtime blocks"
402 factor = 1024
403
404 rc, stdout, stderr = exec_quota(module, xfs_quota_bin, f"report {type_arg} {used_arg}", mountpoint)
405
406 if rc != 0:
407 result = dict(
408 changed=False,
409 rc=rc,
410 stdout=stdout,
411 stderr=stderr,
412 )
413 module.fail_json(msg=f"Could not get quota report for {used_name}.", **result)
414
415 for line in stdout.split("\n"):
416 line = line.strip().split()
417 if len(line) > 3 and line[0] == name:
418 soft = int(line[2]) * factor
419 hard = int(line[3]) * factor
420 break
421
422 return soft, hard
423
424
425 def exec_quota(module, xfs_quota_bin, cmd, mountpoint):
426 cmd = [xfs_quota_bin, "-x", "-c", cmd, mountpoint]
427 (rc, stdout, stderr) = module.run_command(cmd)
428 if (
429 "XFS_GETQUOTA: Operation not permitted" in stderr.split("\n")
430 or rc == 1
431 and "xfs_quota: cannot set limits: Operation not permitted" in stderr.split("\n")
432 ):
433 module.fail_json(msg="You need to be root or have CAP_SYS_ADMIN capability to perform this operation")
434
435 return rc, stdout, stderr
436
437
438 def get_fs_by_mountpoint(mountpoint):
439 mpr = None
440 with open("/proc/mounts") as s:
441 for line in s.readlines():
442 mp = line.strip().split()
443 if len(mp) == 6 and mp[1] == mountpoint and mp[2] == "xfs":
444 mpr = dict(zip(["spec", "file", "vfstype", "mntopts", "freq", "passno"], mp))
445 mpr["mntopts"] = mpr["mntopts"].split(",")
446 break
447 return mpr
448
449
450 def get_project_id(name):
451 prjid = None
452 with open("/etc/projid") as s:
453 for line in s.readlines():
454 line = line.strip().partition(":")
455 if line[0] == name:
456 prjid = line[2]
457 break
458
459 return prjid
460
461
462 if __name__ == "__main__":
463 main()