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 kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

270 Zeilen
9.1KB

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