IF YOU WOULD LIKE TO GET AN ACCOUNT, please write an email to s dot adaszewski at gmail dot com. User accounts are meant only to report issues and/or generate pull requests. This is a purpose-specific Git hosting for ADARED projects. Thank you for your understanding!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

335 lines
11KB

  1. #
  2. # Copyright (C) Stanislaw Adaszewski, 2020
  3. # License: GNU General Public License v3.0
  4. # URL: https://github.com/sadaszewski/focker
  5. # URL: https://adared.ch/focker
  6. #
  7. import subprocess
  8. from .zfs import *
  9. import random
  10. import shutil
  11. import json
  12. from tabulate import tabulate
  13. import os
  14. import jailconf
  15. from .mount import getmntinfo
  16. import shlex
  17. import stat
  18. from .misc import focker_lock, \
  19. focker_unlock, \
  20. random_sha256_hexdigest
  21. def backup_file(fname, nbackups=10, chmod=0o600):
  22. existing_backups = []
  23. for i in range(nbackups):
  24. bakname = '%s.%d' % (fname, i)
  25. if os.path.exists(bakname):
  26. st = os.stat(bakname)
  27. existing_backups.append((bakname, st.st_mtime))
  28. else:
  29. shutil.copyfile(fname, bakname)
  30. os.chmod(bakname, chmod)
  31. return bakname
  32. existing_backups.sort(key=lambda a: a[1])
  33. # overwrite the oldest
  34. bakname = existing_backups[0][0]
  35. shutil.copyfile(fname, bakname)
  36. os.chmod(bakname, chmod)
  37. return bakname
  38. def jail_conf_write(conf):
  39. conf.write('/etc/jail.conf')
  40. def jail_fs_create(image=None):
  41. sha256 = random_sha256_hexdigest()
  42. lst = zfs_list(fields=['focker:sha256'], focker_type='image')
  43. lst = list(filter(lambda a: a[0] == sha256, lst))
  44. if lst:
  45. raise ValueError('Whew, a collision...')
  46. poolname = zfs_poolname()
  47. for pre in range(7, 32):
  48. name = poolname + '/focker/jails/' + sha256[:pre]
  49. if not zfs_exists(name):
  50. break
  51. if image:
  52. image, _ = zfs_find(image, focker_type='image', zfs_type='snapshot')
  53. zfs_parse_output(['zfs', 'clone', '-o', 'focker:sha256=' + sha256, image, name])
  54. else:
  55. print('Creating empty jail:', name)
  56. zfs_parse_output(['zfs', 'create', '-o', 'focker:sha256=' + sha256, name])
  57. return name
  58. def gen_env_command(command, env):
  59. if any(map(lambda a: ' ' in a, env.keys())):
  60. raise ValueError('Environment variable names cannot contain spaces')
  61. env = [ 'export ' + k + '=' + shlex.quote(v) \
  62. for (k, v) in env.items() ]
  63. command = ' && '.join(env + [ command ])
  64. return command
  65. def quote(s):
  66. s = s.replace('\\', '\\\\')
  67. s = s.replace('\'', '\\\'')
  68. s = '\'' + s + '\''
  69. return s
  70. def jail_create(path, command, env, mounts, hostname=None, overrides={}):
  71. name = os.path.split(path)[-1]
  72. if os.path.exists('/etc/jail.conf'):
  73. conf = jailconf.load('/etc/jail.conf')
  74. else:
  75. conf = jailconf.JailConf()
  76. conf[name] = blk = jailconf.JailBlock()
  77. blk['path'] = path
  78. if command:
  79. command = gen_env_command(command, env)
  80. command = quote(command)
  81. print('command:', command)
  82. blk['exec.start'] = command
  83. prestart = [ 'cp /etc/resolv.conf ' +
  84. shlex.quote(os.path.join(path, 'etc/resolv.conf')) ]
  85. poststop = []
  86. if mounts:
  87. for (from_, on) in mounts:
  88. if not from_.startswith('/'):
  89. from_, _ = zfs_find(from_, focker_type='volume')
  90. from_ = zfs_mountpoint(from_)
  91. prestart.append('mount -t nullfs ' + shlex.quote(from_) +
  92. ' ' + shlex.quote(os.path.join(path, on.strip('/'))))
  93. poststop += [ 'umount -f ' +
  94. os.path.join(path, on.strip('/')) \
  95. for (_, on) in reversed(mounts) ]
  96. if prestart:
  97. blk['exec.prestart'] = quote(' && '.join(prestart))
  98. if poststop:
  99. blk['exec.poststop'] = quote(' && '.join(poststop))
  100. blk['persist'] = True
  101. blk['interface'] = 'lo1'
  102. blk['ip4.addr'] = '127.0.1.0'
  103. blk['mount.devfs'] = True
  104. blk['exec.clean'] = True
  105. blk['host.hostname'] = hostname or name
  106. for (k, v) in overrides.items():
  107. blk[k] = quote(v) \
  108. if isinstance(v, str) \
  109. else v
  110. jail_conf_write(conf)
  111. return name
  112. def get_jid(path):
  113. data = json.loads(subprocess.check_output(['jls', '--libxo=json']))
  114. lst = data['jail-information']['jail']
  115. lst = list(filter(lambda a: a['path'] == path, lst))
  116. if len(lst) == 0:
  117. raise ValueError('JID not found for path: ' + path)
  118. if len(lst) > 1:
  119. raise ValueError('Ambiguous JID for path: ' + path)
  120. return str(lst[0]['jid'])
  121. def do_mounts(path, mounts):
  122. print('mounts:', mounts)
  123. for (source, target) in mounts:
  124. if source.startswith('/'):
  125. name = source
  126. else:
  127. name, _ = zfs_find(source, focker_type='volume')
  128. name = zfs_mountpoint(name)
  129. while target.startswith('/'):
  130. target = target[1:]
  131. subprocess.check_output(['mount', '-t', 'nullfs',
  132. shlex.quote(name), shlex.quote(os.path.join(path, target))])
  133. def undo_mounts(path, mounts):
  134. for (_, target) in reversed(mounts):
  135. while target.startswith('/'):
  136. target = target[1:]
  137. subprocess.check_output(['umount', '-f',
  138. shlex.quote(os.path.join(path, target))])
  139. def jail_run(path, command, mounts=[]):
  140. command = ['jail', '-c', 'host.hostname=' + os.path.split(path)[1], 'persist=1', 'mount.devfs=1', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + path, 'command', '/bin/sh', '-c', command]
  141. print('Running:', ' '.join(command))
  142. try:
  143. do_mounts(path, mounts)
  144. os.makedirs(os.path.join(path, 'etc'), exist_ok=True)
  145. os.makedirs(os.path.join(path, 'dev'), exist_ok=True)
  146. shutil.copyfile('/etc/resolv.conf', os.path.join(path, 'etc/resolv.conf'))
  147. res = subprocess.run(command)
  148. finally:
  149. try:
  150. subprocess.run(['jail', '-r', get_jid(path)])
  151. except ValueError:
  152. pass
  153. subprocess.run(['umount', '-f', os.path.join(path, 'dev')])
  154. undo_mounts(path, mounts)
  155. if res.returncode != 0:
  156. # subprocess.run(['umount', os.path.join(path, 'dev')])
  157. raise RuntimeError('Command failed')
  158. def jail_stop(path):
  159. try:
  160. jid = get_jid(path)
  161. jailname = os.path.split(path)[-1]
  162. subprocess.run(['jail', '-r', jailname])
  163. except ValueError:
  164. print('JID could not be determined')
  165. # import time
  166. # time.sleep(1)
  167. mi = getmntinfo()
  168. for m in mi:
  169. mntonname = m['f_mntonname'].decode('utf-8')
  170. if mntonname.startswith(path + os.path.sep):
  171. print('Unmounting:', mntonname)
  172. subprocess.run(['umount', '-f', mntonname])
  173. def jail_remove(path):
  174. print('Removing jail:', path)
  175. jail_stop(path)
  176. subprocess.run(['zfs', 'destroy', '-r', '-f', zfs_name(path)])
  177. if os.path.exists('/etc/jail.conf'):
  178. conf = jailconf.load('/etc/jail.conf')
  179. name = os.path.split(path)[-1]
  180. if name in conf:
  181. del conf[name]
  182. jail_conf_write(conf)
  183. def command_jail_create(args):
  184. backup_file('/etc/jail.conf')
  185. name = jail_fs_create(args.image)
  186. if args.tags:
  187. zfs_tag(name, args.tags)
  188. path = zfs_mountpoint(name)
  189. jail_create(path, args.command,
  190. { a.split(':')[0]: ':'.join(a.split(':')[1:]) \
  191. for a in args.env },
  192. [ [a.split(':')[0], ':'.join(a.split(':')[1:])] \
  193. for a in args.mounts ],
  194. args.hostname )
  195. # print(sha256)
  196. print(path)
  197. def command_jail_start(args):
  198. name, _ = zfs_find(args.reference, focker_type='jail')
  199. path = zfs_mountpoint(name)
  200. jailname = os.path.split(path)[-1]
  201. subprocess.run(['jail', '-c', jailname])
  202. def command_jail_stop(args):
  203. name, _ = zfs_find(args.reference, focker_type='jail')
  204. path = zfs_mountpoint(name)
  205. jail_stop(path)
  206. def command_jail_remove(args):
  207. try:
  208. name, _ = zfs_find(args.reference, focker_type='jail')
  209. except AmbiguousValueError:
  210. raise
  211. except ValueError:
  212. if args.force:
  213. return
  214. raise
  215. path = zfs_mountpoint(name)
  216. jail_remove(path)
  217. def command_jail_exec(args):
  218. name, _ = zfs_find(args.reference, focker_type='jail')
  219. path = zfs_mountpoint(name)
  220. jid = get_jid(path)
  221. focker_unlock()
  222. subprocess.run(['jexec', str(jid)] + args.command)
  223. focker_lock()
  224. def jail_oneshot(image, command, env, mounts):
  225. # pdb.set_trace()
  226. backup_file('/etc/jail.conf')
  227. name = jail_fs_create(image)
  228. path = zfs_mountpoint(name)
  229. jailname = jail_create(path,
  230. ' '.join(map(shlex.quote, command or ['/bin/sh'])),
  231. env, mounts)
  232. focker_unlock()
  233. subprocess.run(['jail', '-c', jailname])
  234. focker_lock()
  235. jail_remove(path)
  236. def command_jail_oneshot(args):
  237. env = { a.split(':')[0]: ':'.join(a.split(':')[1:]) \
  238. for a in args.env }
  239. mounts = [ [ a.split(':')[0], a.split(':')[1] ] \
  240. for a in args.mounts]
  241. jail_oneshot(args.image, args.command, env, mounts)
  242. # Deprecated
  243. def command_jail_oneshot_old():
  244. base, _ = zfs_snapshot_by_tag_or_sha256(args.image)
  245. # root = '/'.join(base.split('/')[:-1])
  246. for _ in range(10**6):
  247. sha256 = random_sha256_hexdigest()
  248. name = sha256[:7]
  249. name = base.split('/')[0] + '/focker/jails/' + name
  250. if not zfs_exists(name):
  251. break
  252. zfs_run(['zfs', 'clone', '-o', 'focker:sha256=' + sha256, base, name])
  253. try:
  254. mounts = list(map(lambda a: a.split(':'), args.mounts))
  255. jail_run(zfs_mountpoint(name), args.command, mounts)
  256. # subprocess.check_output(['jail', '-c', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + zfs_mountpoint(name), 'command', command])
  257. finally:
  258. # subprocess.run(['umount', zfs_mountpoint(name) + '/dev'])
  259. zfs_run(['zfs', 'destroy', '-f', name])
  260. # raise
  261. def command_jail_list(args):
  262. lst = zfs_list(fields=['focker:sha256,focker:tags,mountpoint'], focker_type='jail')
  263. jails = subprocess.check_output(['jls', '--libxo=json'])
  264. jails = json.loads(jails)['jail-information']['jail']
  265. jails = { j['path']: j for j in jails }
  266. lst = list(map(lambda a: [ a[1],
  267. a[0] if args.full_sha256 else a[0][:7],
  268. a[2],
  269. jails[a[2]]['jid'] if a[2] in jails else '-' ], lst))
  270. print(tabulate(lst, headers=['Tags', 'SHA256', 'mountpoint', 'JID']))
  271. def command_jail_tag(args):
  272. name, _ = zfs_find(args.reference, focker_type='jail')
  273. zfs_untag(args.tags, focker_type='jail')
  274. zfs_tag(name, args.tags)
  275. def command_jail_untag(args):
  276. zfs_untag(args.tags, focker_type='jail')
  277. def command_jail_prune(args):
  278. jails = subprocess.check_output(['jls', '--libxo=json'])
  279. jails = json.loads(jails)['jail-information']['jail']
  280. used = set()
  281. for j in jails:
  282. used.add(j['path'])
  283. lst = zfs_list(fields=['focker:sha256,focker:tags,mountpoint,name'], focker_type='jail')
  284. for j in lst:
  285. if j[1] == '-' and (j[2] not in used or args.force):
  286. jail_remove(j[2])