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!
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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