1 | # |
---|
2 | # Copyright (C) 2022 Soleta Networks <info@soleta.eu> |
---|
3 | # |
---|
4 | # This program is free software: you can redistribute it and/or modify it under |
---|
5 | # the terms of the GNU Affero General Public License as published by the |
---|
6 | # Free Software Foundation; either version 3 of the License, or |
---|
7 | # (at your option) any later version. |
---|
8 | |
---|
9 | import os |
---|
10 | import subprocess |
---|
11 | |
---|
12 | from subprocess import DEVNULL |
---|
13 | |
---|
14 | import psutil |
---|
15 | |
---|
16 | |
---|
17 | def find_mountpoint(path): |
---|
18 | """ |
---|
19 | Returns mountpoint of a given path |
---|
20 | """ |
---|
21 | path = os.path.abspath(path) |
---|
22 | while not os.path.ismount(path): |
---|
23 | path = os.path.dirname(path) |
---|
24 | return path |
---|
25 | |
---|
26 | |
---|
27 | def mount_mkdir(source, target): |
---|
28 | """ |
---|
29 | Mounts and creates the mountpoint directory if it's not present. |
---|
30 | """ |
---|
31 | if not os.path.exists(target): |
---|
32 | os.mkdir(target) |
---|
33 | if not os.path.ismount(target): |
---|
34 | return mount(source, target) |
---|
35 | return False |
---|
36 | |
---|
37 | |
---|
38 | def mount(source, target): |
---|
39 | """ |
---|
40 | Mounts source into target directoru using mount(8). |
---|
41 | |
---|
42 | Return true if exit code is 0. False otherwise. |
---|
43 | """ |
---|
44 | cmd = f'mount {source} {target}' |
---|
45 | proc = subprocess.run(cmd.split(), stderr=DEVNULL) |
---|
46 | |
---|
47 | return not proc.returncode |
---|
48 | |
---|
49 | |
---|
50 | def umount(target): |
---|
51 | """ |
---|
52 | Umounts target using umount(8). |
---|
53 | |
---|
54 | Return true if exit code is 0. False otherwise. |
---|
55 | """ |
---|
56 | cmd = f'umount {target}' |
---|
57 | proc = subprocess.run(cmd.split(), stderr=DEVNULL) |
---|
58 | |
---|
59 | return not proc.returncode |
---|
60 | |
---|
61 | |
---|
62 | def get_usedperc(mountpoint): |
---|
63 | """ |
---|
64 | Returns percetage of used filesystem as decimal number. |
---|
65 | """ |
---|
66 | try: |
---|
67 | total, used, free, perc = psutil.disk_usage(mountpoint) |
---|
68 | except FileNotFoundError: |
---|
69 | return '0' |
---|
70 | return str(perc) |
---|