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.

218 Zeilen
7.7KB

  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):
  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. subprocess.run(['jail', '-r', jid])
  104. except ValueError:
  105. print('JID could not be determined')
  106. mi = getmntinfo()
  107. for m in mi:
  108. mntonname = m['f_mntonname'].decode('utf-8')
  109. if mntonname.startswith(path + os.path.sep):
  110. print('Unmounting:', mntonname)
  111. subprocess.run(['umount', '-f', mntonname])
  112. def jail_remove(path):
  113. print('Removing jail:', path)
  114. jail_stop(path)
  115. subprocess.run(['zfs', 'destroy', '-r', '-f', zfs_name(path)])
  116. if os.path.exists('/etc/jail.conf'):
  117. conf = jailconf.load('/etc/jail.conf')
  118. name = os.path.split(path)[-1]
  119. if name in conf:
  120. del conf[name]
  121. conf.write('/etc/jail.conf')
  122. def command_jail_create(args):
  123. image, _ = zfs_find(args.image, focker_type='image', zfs_type='snapshot')
  124. sha256 = bytes([ random.randint(0, 255) for _ in range(32) ]).hex()
  125. lst = zfs_list(fields=['focker:sha256'], focker_type='image')
  126. lst = list(filter(lambda a: a[0] == sha256, lst))
  127. if lst:
  128. raise ValueError('Whew, a collision...')
  129. poolname = zfs_poolname()
  130. for pre in range(7, 32):
  131. name = poolname + '/focker/jails/' + sha256[:pre]
  132. if not zfs_exists(name):
  133. break
  134. zfs_run(['zfs', 'clone', '-o', 'focker:sha256=' + sha256, image, name])
  135. if args.tags:
  136. zfs_tag(name, args.tags)
  137. path = zfs_mountpoint(name)
  138. jail_create(path, args.command,
  139. { a.split(':')[0]: ':'.join(a.split(':')[1:]) \
  140. for a in args.env },
  141. [ [a.split(':')[0], ':'.join(a.split(':')[1:])] \
  142. for a in args.mounts ] )
  143. print(sha256)
  144. print(path)
  145. def command_jail_run(args):
  146. base, _ = zfs_snapshot_by_tag_or_sha256(args.image)
  147. # root = '/'.join(base.split('/')[:-1])
  148. for _ in range(10**6):
  149. sha256 = bytes([ random.randint(0, 255) for _ in range(32) ]).hex()
  150. name = sha256[:7]
  151. name = base.split('/')[0] + '/focker/jails/' + name
  152. if not zfs_exists(name):
  153. break
  154. zfs_run(['zfs', 'clone', '-o', 'focker:sha256=' + sha256, base, name])
  155. try:
  156. mounts = list(map(lambda a: a.split(':'), args.mounts))
  157. jail_run(zfs_mountpoint(name), args.command, mounts)
  158. # subprocess.check_output(['jail', '-c', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + zfs_mountpoint(name), 'command', command])
  159. finally:
  160. # subprocess.run(['umount', zfs_mountpoint(name) + '/dev'])
  161. zfs_run(['zfs', 'destroy', '-f', name])
  162. # raise
  163. def command_jail_list(args):
  164. lst = zfs_list(fields=['focker:sha256,focker:tags,mountpoint'], focker_type='jail')
  165. jails = subprocess.check_output(['jls', '--libxo=json'])
  166. jails = json.loads(jails)['jail-information']['jail']
  167. jails = { j['path']: j for j in jails }
  168. lst = list(map(lambda a: [ a[1],
  169. a[0] if args.full_sha256 else a[0][:7],
  170. a[2],
  171. jails[a[2]]['jid'] if a[2] in jails else '-' ], lst))
  172. print(tabulate(lst, headers=['Tags', 'SHA256', 'mountpoint', 'JID']))
  173. def command_jail_tag(args):
  174. name, _ = zfs_find(args.reference, focker_type='jail')
  175. zfs_untag(args.tags, focker_type='jail')
  176. zfs_tag(name, args.tags)
  177. def command_jail_untag(args):
  178. zfs_untag(args.tags, focker_type='jail')
  179. def command_jail_prune(args):
  180. jails = subprocess.check_output(['jls', '--libxo=json'])
  181. jails = json.loads(jails)['jail-information']['jail']
  182. used = set()
  183. for j in jails:
  184. used.add(j['path'])
  185. lst = zfs_list(fields=['focker:sha256,focker:tags,mountpoint,name'], focker_type='jail')
  186. for j in lst:
  187. if j[1] == '-' and j[2] not in used:
  188. jail_remove(j[2])