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!
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

315 lines
10KB

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