Debian Codegraph @

pkg/storaged/nfs/nfs-mounts.py

raw
1 #! /usr/bin/python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 # nfs-mounts -- Monitor and manage NFS mounts
5 #
6 # This is similar to how UDisks2 monitors and manages block device
7 # mounts, but for NFS. This might be moved into UDisks2, or not.
8
9 # We monitor all NFS remotes listed in /etc/fstab and in /proc/self/mounts.
10 # If a entry from mtab is also found in fstab, we report only the
11 # fstab entry and mark it is "mounted".
12
13 import json
14 import os
15 import re
16 import select
17 import subprocess
18 import sys
19
20
21 class Watcher:
22 def __init__(self, path):
23 self.inotify = Inotify()
24 self.path = path
25 self.setup()
26
27 def setup(self):
28 self.wd = self.inotify.add_watch(self.path, IN_CLOSE_WRITE)
29
30 def process(self, callback=None):
31 def event(_wd, mask, name):
32 if callback:
33 callback()
34 if mask & IN_IGNORED:
35 self.setup()
36 self.inotify.process(event)
37
38
39 def field_escape(field):
40 return field.replace("\\", r"\134").replace(" ", r"\040").replace("\t", r"\011")
41
42
43 def field_unescape(field):
44 return re.sub(r"\\([0-7]{1,3})", lambda m: chr(int(m.group(1), 8)), field)
45
46
47 def parse_tab(name):
48 entries = []
49 with open(name, "r") as f:
50 for line in f:
51 sline = line.strip()
52 if sline == "" or sline[0] == "#":
53 continue
54 fields = list(map(field_unescape, re.split(r"[ \t]+", sline)))
55 if len(fields) > 2 and ":" in fields[0] and fields[2].startswith("nfs"):
56 entries.append(fields)
57 return entries
58
59
60 def index_tab(tab):
61 by_remote = {}
62 for t in tab:
63 if t[0] not in by_remote:
64 by_remote[t[0]] = []
65 by_remote[t[0]].append(t)
66 return by_remote
67
68
69 def modify_tab(name, modify):
70 with open(name) as f:
71 lines = f.read().splitlines()
72
73 new_lines = []
74 for line in lines:
75 sline = line.strip()
76 if sline == "" or sline[0] == "#":
77 new_lines.append(line)
78 else:
79 fields = list(map(field_unescape, re.split(r"[ \t]+", sline)))
80 if len(fields) > 0 and ":" in fields[0]:
81 new_fields = modify(fields)
82 if new_fields:
83 if new_fields == fields:
84 new_lines.append(line)
85 else:
86 new_lines.append(" ".join(map(field_escape, new_fields)))
87 else:
88 new_lines.append(line)
89 new_fields = modify(None)
90 if new_fields:
91 new_lines.append(" ".join(map(field_escape, new_fields)))
92
93 with open(name + ".tmp", "w") as f:
94 f.write("\n".join(new_lines) + "\n")
95 f.flush()
96 os.fsync(f.fileno())
97 os.rename(name + ".tmp", name)
98
99
100 fstab = []
101 fstab_by_remote = {}
102
103 mtab = []
104 mtab_by_remote = {}
105
106
107 def process_fstab():
108 global fstab, fstab_by_remote
109 fstab = parse_tab("/etc/fstab")
110 fstab_by_remote = index_tab(fstab)
111
112
113 def process_mtab():
114 global mtab, mtab_by_remote
115 mtab = parse_tab("/proc/self/mounts")
116 mtab_by_remote = index_tab(mtab)
117
118
119 def find_in_tab(tab_by_remote, fields):
120 for t in tab_by_remote.get(fields[0], []):
121 if t[0] == fields[0] and t[1] == fields[1]:
122 return t
123 return None
124
125
126 def report():
127 data = []
128 for f in fstab:
129 m = find_in_tab(mtab_by_remote, f)
130 data.append({"fstab": True, "fields": f, "mounted": m is not None})
131 for m in mtab:
132 if not find_in_tab(fstab_by_remote, m):
133 data.append({"fstab": False, "fields": m, "mounted": True})
134 sys.stdout.write(json.dumps(data) + "\n")
135 sys.stdout.flush()
136
137
138 def monitor():
139 process_mtab()
140 process_fstab()
141 report()
142 fstab_watcher = Watcher("/etc/fstab")
143 with open("/proc/self/mounts", "r") as mtab_file:
144 while True:
145 r, _w, x = select.select([fstab_watcher.inotify.fd], [], [mtab_file])
146 if mtab_file in x:
147 process_mtab()
148 report()
149 if fstab_watcher.inotify.fd in r:
150 fstab_watcher.process()
151 process_fstab()
152 report()
153
154
155 def mkdir_if_necessary(path):
156 if not os.path.exists(path):
157 os.makedirs(path)
158
159
160 def rmdir_maybe(path):
161 try:
162 os.rmdir(path)
163 except OSError:
164 pass
165
166
167 def update(entry, new_fields):
168 old_fields = entry["fields"]
169 if old_fields[1] != new_fields[1]:
170 mkdir_if_necessary(new_fields[1])
171 if entry["mounted"]:
172 if (new_fields[0] == old_fields[0] and
173 new_fields[1] == old_fields[1] and
174 new_fields[2] == old_fields[2]):
175 remount(new_fields)
176 else:
177 try:
178 unmount(entry)
179 if old_fields[1] != new_fields[1]:
180 rmdir_maybe(old_fields[1])
181 except subprocess.CalledProcessError:
182 pass
183 mount({"fields": new_fields})
184 else:
185 if old_fields[1] != new_fields[1]:
186 rmdir_maybe(old_fields[1])
187 modify_tab("/etc/fstab", lambda fields: new_fields if fields == old_fields else fields)
188
189
190 def add(new_fields):
191 mkdir_if_necessary(new_fields[1])
192 mount({"fields": new_fields})
193 modify_tab("/etc/fstab", lambda fields: new_fields if fields is None else fields)
194
195
196 def remove(entry):
197 old_fields = entry["fields"]
198 if entry["mounted"]:
199 unmount(entry)
200 rmdir_maybe(old_fields[1])
201 modify_tab("/etc/fstab", lambda fields: None if fields == old_fields else fields)
202
203
204 def mount(entry):
205 fields = entry["fields"]
206 mkdir_if_necessary(fields[1])
207 subprocess.check_call(["mount",
208 "-t", fields[2],
209 "-o", fields[3],
210 fields[0],
211 fields[1]])
212
213
214 def remount(fields):
215 subprocess.check_call(["mount",
216 "-o", "remount," + fields[3],
217 fields[0],
218 fields[1]])
219
220
221 def unmount(entry):
222 subprocess.check_call(["umount", entry["fields"][1]])
223
224
225 def dispatch(argv):
226 if argv[1] == "monitor":
227 monitor()
228 elif argv[1] == "update":
229 update(json.loads(argv[2]), json.loads(argv[3]))
230 elif argv[1] == "add":
231 add(json.loads(argv[2]))
232 elif argv[1] == "remove":
233 remove(json.loads(argv[2]))
234 elif argv[1] == "mount":
235 mount(json.loads(argv[2]))
236 elif argv[1] == "unmount":
237 unmount(json.loads(argv[2]))
238
239
240 try:
241 dispatch(sys.argv)
242 except subprocess.CalledProcessError as e:
243 sys.exit(e.returncode)
244 except Exception as e:
245 sys.stderr.write(str(e) + "\n")
246 sys.exit(1)