This repository has been archived by the owner on Apr 4, 2024. It is now read-only.
/
ioc_fstab.py
367 lines (304 loc) · 12.5 KB
/
ioc_fstab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# Copyright (c) 2014-2018, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Manipulate a jails fstab"""
import datetime
import os
import shutil
import subprocess as su
import tempfile
import pathlib
import iocage_lib.ioc_common
import iocage_lib.ioc_json
import iocage_lib.ioc_list
import iocage_lib.ioc_exceptions
import texttable
class IOCFstab(object):
"""Will add or remove an entry, and mount or umount the filesystem."""
def __init__(self, uuid, action, source, destination, fstype, fsoptions,
fsdump, fspass, index=None, silent=False, callback=None,
header=False, _fstab_list=None):
self.pool = iocage_lib.ioc_json.IOCJson().json_get_value("pool")
self.iocroot = iocage_lib.ioc_json.IOCJson(
self.pool).json_get_value("iocroot")
self.uuid = uuid
self.action = action
self.src = source
self.dest = destination
self.fstype = fstype
self.fsoptions = fsoptions
self.fsdump = fsdump
self.fspass = fspass
self.index = int(index) if index is not None else None
self.mount = f"{self.src}\t{self.dest}\t{self.fstype}\t" \
f"{self.fsoptions}\t{self.fsdump}\t{self.fspass}"
self._fstab_list = _fstab_list
self.header = header
self.silent = silent
self.callback = callback
if action != "list":
self.fstab = list(self.__read_fstab__())
self.dests = self.__validate_fstab__(self.fstab, 'all')
self.__fstab_parse__()
def __fstab_parse__(self):
"""
Checks which action the user is asking for and calls the
appropriate methods.
"""
actions = ['add', 'remove', 'edit', 'replace']
if self.action not in actions:
raise RuntimeError("Type of operation not specified!")
if self.action == "add":
self.__validate_fstab__([self.mount])
self.__fstab_add__()
try:
self.__fstab_mount__()
except RuntimeError:
iocage_lib.ioc_common.logit({
'level': 'WARNING',
'message': 'Mounting entry failed, check \'mount\''
},
_callback=self.callback,
silent=self.silent
)
elif self.action == "remove":
dest = self.__fstab_remove__()
try:
self.__fstab_umount__(dest)
except RuntimeError:
iocage_lib.ioc_common.logit({
'level': 'WARNING',
'message': 'Unmounting entry failed, check \'mount\''
},
_callback=self.callback,
silent=self.silent
)
elif self.action == "edit":
self.__fstab_edit__()
elif self.action == "replace":
self.__validate_fstab__([self.mount])
self.__fstab_edit__(_string=True)
self.__fstab_mount__()
def __read_fstab__(self):
with open(f"{self.iocroot}/jails/{self.uuid}/fstab", "r") as f:
for line in f:
yield line.rstrip()
def __get_fstab_dests_(self):
dests = []
for line in self.fstab:
source, destination, fstype, options, \
dump, _pass = line.split()[0:6]
dests.append(destination)
return dests
def __validate_fstab__(self, fstab, mode='single'):
dests = []
verrors = []
jail_root = f'{self.iocroot}/jails/{self.uuid}/root'
for line in fstab:
source, destination, fstype, options, \
dump, _pass = line.split()[0:6]
source = pathlib.Path(source)
missing_root = False
dest = pathlib.Path(destination)
if mode != 'all' and (
self.action == 'add' or self.action == 'replace'
):
if destination in self.dests:
verrors.append(f'Destination: {self.dest} already exists!')
break
if jail_root not in self.dest:
verrors.append(
f'Destination: {self.dest} must include '
f'jail\'s mountpoint! ({jail_root})'
)
break
else:
if jail_root not in destination:
verrors.append(
f'Destination: {destination} does not include '
f'jail\'s mountpoint! ({jail_root})'
)
missing_root = True
if not source.is_dir():
verrors.append(f'Source: {source} does not exist!')
if not source.is_absolute():
verrors.append(f'Source: {source} must use an absolute path!')
if not missing_root:
if not dest.is_dir():
verrors.append(f'Destination: {dest} does not exist!')
if not dest.is_absolute():
verrors.append(
f'Destination: {dest} must use an absolute path!'
)
if not dump.isdecimal():
verrors.append(
f'Dump: {dump} must be a digit!'
)
if len(dump) > 1:
verrors.append(
f'Dump: {dump} must be one digit long!'
)
if not _pass.isdecimal():
verrors.append(
f'Pass: {_pass} must be a digit!'
)
if len(_pass) > 1:
verrors.append(
f'Pass: {_pass} must be one digit long!'
)
dests.append(destination)
if verrors:
iocage_lib.ioc_common.logit({
'level': 'EXCEPTION',
'message': verrors
},
_callback=self.callback,
exception=iocage_lib.ioc_exceptions.ValidationFailed
)
return dests
def __fstab_add__(self):
"""Adds a users mount to the jails fstab"""
with iocage_lib.ioc_common.open_atomic(
f'{self.iocroot}/jails/{self.uuid}/fstab',
'w'
) as fstab:
for line in self.fstab:
fstab.write(f'{line}\n')
date = datetime.datetime.utcnow().strftime("%F %T")
fstab.write(f"{self.mount} # Added by iocage on {date}\n")
iocage_lib.ioc_common.logit({
"level": "INFO",
"message": f"Successfully added mount to {self.uuid}'s fstab"
},
_callback=self.callback,
silent=self.silent)
def __fstab_remove__(self):
"""
Removes the users mount by index or matching string.
:return: The destination of the specified mount
"""
removed = False
index = 0
with iocage_lib.ioc_common.open_atomic(
f"{self.iocroot}/jails/{self.uuid}/fstab",
"w") as fstab:
for line in self.fstab:
if line.rsplit("#")[0].rstrip() == self.mount or index \
== self.index and not removed:
removed = True
dest = line.split()[1]
continue
fstab.write(line)
index += 1
if removed:
iocage_lib.ioc_common.logit({
"level": "INFO",
"message": f"Successfully removed mount from {self.uuid}"
"'s fstab"
},
_callback=self.callback,
silent=self.silent)
return dest # Needed for umounting, otherwise we lack context.
iocage_lib.ioc_common.logit({
"level": "EXCEPTION",
"message": "No matching fstab entry."
},
_callback=self.callback,
silent=self.silent)
def __fstab_mount__(self):
"""Mounts the users mount if the jail is running."""
status, _ = iocage_lib.ioc_list.IOCList().list_get_jid(self.uuid)
if not status:
return
os.makedirs(self.dest, exist_ok=True)
proc = su.Popen(["mount", "-t", self.fstype, "-o", self.fsoptions,
self.src, self.dest], stdout=su.PIPE, stderr=su.PIPE)
stdout_data, stderr_data = proc.communicate()
if stderr_data:
raise RuntimeError(f"{stderr_data.decode('utf-8')}")
def __fstab_umount__(self, dest):
"""
Umounts the users mount if the jail is running.
:param dest: The destination to umount.
"""
status, _ = iocage_lib.ioc_list.IOCList().list_get_jid(self.uuid)
if not status:
return
proc = su.Popen(["umount", "-f", dest], stdout=su.PIPE, stderr=su.PIPE)
stdout_data, stderr_data = proc.communicate()
if stderr_data:
raise RuntimeError(f"{stderr_data.decode('utf-8')}")
def __fstab_edit__(self, _string=False):
"""
Opens up the users EDITOR, or vi and replaces the jail's fstab
with the new content.
If _string is True, then we replace the given index with the new mount
"""
jail_fstab = f"{self.iocroot}/jails/{self.uuid}/fstab"
if _string:
matched = False
with iocage_lib.ioc_common.open_atomic(
jail_fstab, "w") as fstab:
for i, line in enumerate(self.fstab):
if i == self.index:
date = datetime.datetime.utcnow().strftime("%F %T")
fstab.write(
f"{self.mount} # Added by iocage on {date}\n")
matched = True
iocage_lib.ioc_common.logit({
"level": "INFO",
"message": f"Index {self.index} replaced."
},
_callback=self.callback,
silent=self.silent)
else:
fstab.write(line)
if not matched:
iocage_lib.ioc_common.logit({
"level": "EXCEPTION",
"message": f"Index {self.index} not found."
},
_callback=self.callback,
silent=self.silent)
return
editor = os.environ.get("EDITOR", "/usr/bin/vi")
err_editor = editor.split("/")[-1]
tmp_fstab = tempfile.NamedTemporaryFile(suffix=".iocage")
shutil.copy2(jail_fstab, tmp_fstab.name)
proc = su.call([editor, tmp_fstab.name])
if proc != 0:
raise RuntimeError(f"An error occurred within {err_editor}!")
with open(jail_fstab, "w") as fstab:
for line in tmp_fstab.readlines():
fstab.write(line.decode("utf-8"))
def fstab_list(self):
"""Returns list of lists, or a table"""
if not self.header:
flat_fstab = [f for f in self._fstab_list]
return flat_fstab
table = texttable.Texttable(max_width=0)
# We get an infinite float otherwise.
table.set_cols_dtype(["t", "t"])
self._fstab_list.insert(0, ["INDEX", "FSTAB ENTRY"])
table.add_rows(self._fstab_list)
return table.draw()