diff --git a/focker.py b/focker.py index 68a8c32..5f1d348 100644 --- a/focker.py +++ b/focker.py @@ -6,6 +6,7 @@ from .image import command_image_build, \ command_image_untag import sys from .zfs import zfs_init +from .jail import command_jail_run def create_parser(): @@ -22,6 +23,12 @@ def create_parser(): parser.set_defaults(func=command_image_untag) parser.add_argument('tags', type=str, nargs='+', default=[]) + subparsers = subparsers_top.add_parser('jail').add_subparsers() + parser = subparsers.add_parser('run') + parser.set_defaults(func=command_jail_run) + parser.add_argument('image', type=str) + parser.add_argument('--command', '-c', type=str, default='/bin/sh') + return parser_top diff --git a/jail.py b/jail.py index b64643a..d612bbc 100644 --- a/jail.py +++ b/jail.py @@ -1,6 +1,31 @@ import subprocess +from .zfs import * +import random +import shutil + def jail_run(path, command): - command = ['jail', '-c', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + path, 'command', '/bin/sh', '-c', command] + command = ['jail', '-c', 'host.hostname=' + os.path.split(path)[1], 'mount.devfs=1', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + path, 'command', '/bin/sh', '-c', command] print('Running:', ' '.join(command)) - subprocess.check_output(command) + res = subprocess.run(command) + if res.returncode != 0: + raise RuntimeError('Command failed') + + +def command_jail_run(args): + base, _ = zfs_snapshot_by_tag_or_sha256(args.image) + # root = '/'.join(base.split('/')[:-1]) + for _ in range(10**6): + name = bytes([ random.randint(0, 256) for _ in range(4) ]).hex()[:7] + name = base.split('/')[0] + '/focker/jails/' + name + if not zfs_exists(name): + break + zfs_run(['zfs', 'clone', base, name]) + try: + shutil.copyfile('/etc/resolv.conf', os.path.join(zfs_mountpoint(name), 'etc/resolv.conf')) + jail_run(zfs_mountpoint(name), args.command) + # subprocess.check_output(['jail', '-c', 'interface=lo1', 'ip4.addr=127.0.1.0', 'path=' + zfs_mountpoint(name), 'command', command]) + finally: + subprocess.run(['umount', zfs_mountpoint(name) + '/dev']) + zfs_run(['zfs', 'destroy', '-f', name]) + # raise diff --git a/zfs.py b/zfs.py index 0e38deb..d258ea2 100644 --- a/zfs.py +++ b/zfs.py @@ -111,5 +111,5 @@ def zfs_init(): zfs_run(['zfs', 'create', '-o', 'canmount=off', poolname + '/focker/images']) if not zfs_exists(poolname + '/focker/volumes'): zfs_run(['zfs', 'create', '-o', 'canmount=off', poolname + '/focker/volumes']) - if not zfs_exists(poolname + '/focker/volumes'): + if not zfs_exists(poolname + '/focker/jails'): zfs_run(['zfs', 'create', '-o', 'canmount=off', poolname + '/focker/jails'])