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.

248 lines
8.5KB

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