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!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jail.py 1.9KB

4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import subprocess
  2. from .zfs import *
  3. import random
  4. import shutil
  5. import json
  6. def get_jid(path):
  7. data = json.loads(subprocess.check_output(['jls', '--libxo=json']))
  8. lst = data['jail-information']['jail']
  9. lst = list(filter(lambda a: a['path'] == path, lst))
  10. if len(lst) == 0:
  11. raise ValueError('JID not found for path: ' + path)
  12. if len(lst) > 1:
  13. raise ValueError('Ambiguous JID for path: ' + path)
  14. return str(lst[0]['jid'])
  15. def jail_run(path, command):
  16. 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]
  17. print('Running:', ' '.join(command))
  18. try:
  19. shutil.copyfile('/etc/resolv.conf', os.path.join(path, 'etc/resolv.conf'))
  20. res = subprocess.run(command)
  21. finally:
  22. try:
  23. subprocess.run(['jail', '-r', get_jid(path)])
  24. except ValueError:
  25. pass
  26. subprocess.run(['umount', '-f', os.path.join(path, 'dev')])
  27. if res.returncode != 0:
  28. # subprocess.run(['umount', os.path.join(path, 'dev')])
  29. raise RuntimeError('Command failed')
  30. def command_jail_run(args):
  31. base, _ = zfs_snapshot_by_tag_or_sha256(args.image)
  32. # root = '/'.join(base.split('/')[:-1])
  33. for _ in range(10**6):
  34. name = bytes([ random.randint(0, 255) for _ in range(4) ]).hex()[:7]
  35. name = base.split('/')[0] + '/focker/jails/' + name
  36. if not zfs_exists(name):
  37. break
  38. zfs_run(['zfs', 'clone', base, name])
  39. try:
  40. jail_run(zfs_mountpoint(name), args.command)
  41. # subprocess.check_output(['jail', '-c', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + zfs_mountpoint(name), 'command', command])
  42. finally:
  43. # subprocess.run(['umount', zfs_mountpoint(name) + '/dev'])
  44. zfs_run(['zfs', 'destroy', '-f', name])
  45. # raise