Esempio n. 1
0
def test_setup_dependencies():
    backup_file('/etc/jail.conf')
    conf = jailconf.load('/etc/jail.conf')
    jail = jailconf.JailBlock()
    conf['test-setup-dependencies-A'] = jail
    conf['test-setup-dependencies-B'] = jail
    conf['test-setup-dependencies-C'] = jail
    conf.write('/etc/jail.conf')
    setup_dependencies({
        'test-setup-dependencies-A': {},
        'test-setup-dependencies-B': { 'depend': 'test-setup-dependencies-A' },
        'test-setup-dependencies-C': { 'depend': [
            'test-setup-dependencies-A',
            'test-setup-dependencies-B'
        ] }
    }, {
        'test-setup-dependencies-A': 'test-setup-dependencies-A',
        'test-setup-dependencies-B': 'test-setup-dependencies-B',
        'test-setup-dependencies-C': 'test-setup-dependencies-C'
    })
    conf = jailconf.load('/etc/jail.conf')
    assert 'depend' not in conf['test-setup-dependencies-A']
    assert conf['test-setup-dependencies-B']['depend'] == 'test-setup-dependencies-A'
    assert conf['test-setup-dependencies-C']['depend'] == [
        'test-setup-dependencies-A',
        'test-setup-dependencies-B'
    ]
    del conf['test-setup-dependencies-A']
    del conf['test-setup-dependencies-B']
    del conf['test-setup-dependencies-C']
    conf.write('/etc/jail.conf')
Esempio n. 2
0
def test_build_jails():
    backup_file('/etc/jail.conf')
    conf = jailconf.load('/etc/jail.conf')
    for k in list(conf.keys()):
        if conf[k]['host.hostname'].strip('\'"') in ['test-build-jails-A', 'test-build-jails-B']:
            del conf[k]
    conf.write('/etc/jail.conf')
    subprocess.check_output(['focker', 'jail', 'remove', '--force', 'test-build-jails-A'])
    subprocess.check_output(['focker', 'jail', 'remove', '--force', 'test-build-jails-B'])
    subprocess.check_output(['focker', 'image', 'remove', '--force', '-R', 'test-focker-bootstrap'])
    subprocess.check_output(['focker', 'bootstrap', '--empty', '-t', 'test-focker-bootstrap'])
    spec = {
        'test-build-jails-A': {
            'image': 'test-focker-bootstrap',
            'exec.start': 'test-exec-start',
            'exec.stop': 'test-exec-stop',
            'ip4.addr': 'test-ip4-addr',
            'interface': 'test-interface',
            'host.hostname': 'test-build-jails-A',
            'allow.mount': True,
            'ip6.addr': 'abcd:abcd::0'
        }
    }
    spec['test-build-jails-B'] = spec['test-build-jails-A'].copy()
    spec['test-build-jails-B']['host.hostname'] = 'test-build-jails-B'
    build_jails(spec)
    conf = jailconf.load('/etc/jail.conf')
    print(conf.values())
    blocks = list(filter(lambda a: a['host.hostname'].strip('"\'') in [ 'test-build-jails-A',
        'test-build-jails-B' ], conf.values()))
    print(blocks)
    assert len(blocks) == 2
    assert blocks[0]['host.hostname'] != blocks[1]['host.hostname']
    for i in range(2):
        jail_sha256_prefix = os.path.split(blocks[i]['path'].strip('\'"'))[-1]
        assert jail_sha256_prefix in conf
    for b in blocks:
        name, _ = zfs_find(b['host.hostname'].strip('\'"'), focker_type='jail')
        mountpoint = zfs_mountpoint(name)
        assert b['path'].strip('\'"') == mountpoint
        assert b['exec.start'].strip('\'"') == 'test-exec-start'
        assert b['exec.stop'].strip('\'"') == 'test-exec-stop'
        assert b['ip4.addr'].strip('\'"') == 'test-ip4-addr'
        assert b['interface'].strip('\'"') == 'test-interface'
        assert b['allow.mount']
        assert b['ip6.addr'] == '\'abcd:abcd::0\''
    subprocess.check_output(['focker', 'jail', 'remove', '--force', 'test-build-jails-A'])
    subprocess.check_output(['focker', 'jail', 'remove', '--force', 'test-build-jails-B'])
    subprocess.check_output(['focker', 'image', 'remove', '--force', 'test-focker-bootstrap'])
    for k in list(conf.keys()):
        if conf[k]['host.hostname'].strip('\'"') in ['test-build-jails-A', 'test-build-jails-B']:
            del conf[k]
    conf.write('/etc/jail.conf')
Esempio n. 3
0
def init(ip4_network):
    check_compatibility()
    address4 = str(ip4_network.network_address + 1)
    netmask = str(ip4_network.netmask)
    rc_conf_mod('cloned_interfaces+=%s' % cloned_if())
    cmd('service', 'netif', 'cloneup')
    rc_conf_mod('ifconfig_%s=inet %s netmask %s' % (cloned_if(), address4, netmask))
    cmd('ifconfig', cloned_if(), 'inet', address4, 'netmask', netmask)
    rc_conf_mod('jail_enable=YES')
    cmd(
        'mkdir', '-p', 
        '/var/mjail/instances/',
        '/var/mjail/releases/',
        '/var/mjail/generated_confs/'
    )
    cmd('chmod', '700', '/var/mjail/instances/', '/var/mjail/releases/')
    cmd('chmod', '755', '/var/mjail/', '/var/mjail/generated_confs/')
    try:
        jail_conf = jailconf.load('/etc/jail.conf')
    except FileNotFoundError:
        jail_conf = jailconf.JailConf()
    jail_conf['exec.start'] = '"/bin/sh /etc/rc"'
    jail_conf['exec.stop'] = '"/bin/sh /etc/rc.shutdown"'
    jail_conf['exec.clean'] = True
    jail_conf['mount.devfs'] = True
    jail_conf['path'] = '"/var/mjail/instances/$name"'
    jail_conf.write('/etc/jail.conf')
    release = Release()
    if not release.built():
        release.build()
    LocalUnboundManager.enable()
    PFManager.enable()
Esempio n. 4
0
def jail_create(spec: dict, name: str) -> None:
    if os.path.exists('/etc/jail.conf'):
        conf = jailconf.load('/etc/jail.conf')
    else:
        conf = jailconf.JailConf()
    blk = jailspec_to_jailconf(spec, name)
    conf[name] = blk
    jail_conf_write(conf)
Esempio n. 5
0
def jail_remove(path):
    print('Removing jail:', path)
    jail_stop(path)
    focker_subprocess_run(['zfs', 'destroy', '-r', '-f', zfs_name(path)])
    if os.path.exists('/etc/jail.conf'):
        conf = jailconf.load('/etc/jail.conf')
        name = os.path.split(path)[-1]
        if name in conf:
            del conf[name]
            jail_conf_write(conf)
Esempio n. 6
0
def init(ip4_network: IPv4Network, ip6_network: IPv6Network):
    if not ip4_network.is_private:
        raise ValueError(
            "The network should be private. "
            "see https://en.wikipedia.org/wiki/Private_network#Private_IPv4_addresses"
        )
    if not ip6_network.is_private or not ip6_network.prefixlen == 64:
        raise ValueError(
            "The network should be a private network as defined in https://tools.ietf.org/html/rfc4193.html"
        )
    check_compatibility()

    rc_conf_mod('cloned_interfaces+=%s' % cloned_if())
    cmd('service', 'netif', 'cloneup')

    address4 = str(ip4_network.network_address + 1)
    netmask = str(ip4_network.netmask)
    rc_conf_mod('ifconfig_%s=inet %s netmask %s' %
                (cloned_if(), address4, netmask))
    cmd('ifconfig', cloned_if(), 'inet', address4, 'netmask', netmask)

    address6 = str(ip6_network.network_address + 1)
    rc_conf_mod('ifconfig_%s_ipv6=inet6 %s prefixlen 64' %
                (cloned_if(), address6))
    cmd('ifconfig', cloned_if(), 'inet6', address6, 'prefixlen', '64')

    rc_conf_mod('jail_enable=YES')
    cmd('mkdir', '-p', '/var/mjail/instances/', '/var/mjail/releases/',
        '/var/mjail/generated_confs/')
    cmd('chmod', '700', '/var/mjail/instances/', '/var/mjail/releases/')
    cmd('chmod', '755', '/var/mjail/', '/var/mjail/generated_confs/')
    try:
        jail_conf = jailconf.load('/etc/jail.conf')
    except FileNotFoundError:
        jail_conf = jailconf.JailConf()
    jail_conf['exec.start'] = '"/bin/sh /etc/rc"'
    jail_conf['exec.stop'] = '"/bin/sh /etc/rc.shutdown"'
    jail_conf['exec.clean'] = True
    jail_conf['mount.devfs'] = True
    jail_conf['path'] = '"/var/mjail/instances/$name"'
    jail_conf.write('/etc/jail.conf')
    release = Release()
    if not release.built():
        release.build()
    LocalUnboundManager.enable()
    PFManager.enable()
Esempio n. 7
0
def test_jail_create():
    subprocess.check_output(
        ['focker', 'jail', 'remove', '--force', 'test-jail-create'])
    subprocess.check_output(
        ['focker', 'volume', 'remove', '--force', 'test-jail-create'])
    name = jail_fs_create()
    zfs_tag(name, ['test-jail-create'])
    subprocess.check_output(
        ['focker', 'volume', 'create', '-t', 'test-jail-create'])
    mountpoint = zfs_mountpoint(name)

    spec = {
        'path': mountpoint,
        'exec.start': '/bin/sh /etc/rc',
        'env': {
            'DUMMY_1': 'foo',
            'DUMMY_2': 'bar'
        },
        'mounts': {
            'test-jail-create': '/test-jail-create',
            '/tmp': '/test-tmp'
        },
        'ip4.addr': '127.1.2.3',
        'host.hostname': 'test-jail-create'
    }
    jail_name = os.path.split(mountpoint)[-1]
    jail_create(spec, jail_name)

    assert jail_name == os.path.split(mountpoint)[-1]
    assert os.path.exists(mountpoint)
    vol_name, _ = zfs_find('test-jail-create', focker_type='volume')
    vol_mountpoint = zfs_mountpoint(vol_name)
    assert os.path.exists(vol_mountpoint)
    conf = jailconf.load('/etc/jail.conf')
    assert jail_name in conf
    conf = conf[jail_name]
    assert conf['path'] == quote(mountpoint)
    assert conf[
        'exec.start'] == '\'export DUMMY_1=foo && export DUMMY_2=bar && /bin/sh /etc/rc\''
    assert conf[
        'exec.prestart'] == f'\'cp /etc/resolv.conf {mountpoint}/etc/resolv.conf && mount -t nullfs {vol_mountpoint} {mountpoint}/test-jail-create && mount -t nullfs /tmp {mountpoint}/test-tmp\''
    assert conf['ip4.addr'] == '\'127.1.2.3\''
    subprocess.check_output(['focker', 'jail', 'remove', 'test-jail-create'])
    subprocess.check_output(['focker', 'volume', 'remove', 'test-jail-create'])
Esempio n. 8
0
def setup_dependencies(spec, generated_names):
    if os.path.exists('/etc/jail.conf'):
        conf = jailconf.load('/etc/jail.conf')
    else:
        conf = jailconf.JailConf()
    for (jailname, jailspec) in spec.items():
        if 'depend' not in jailspec:
            continue
        depend = jailspec.get('depend', [])
        if isinstance(depend, str):
            depend = [ depend ]
        if not isinstance(depend, list):
            raise ValueError('depend must be a string or a list of strings')
        # pdb.set_trace()
        depend = list(map(lambda a: generated_names[a], depend))
        if len(depend) == 1:
            depend = depend[0]
        conf[generated_names[jailname]]['depend'] = \
            depend
    conf.write('/etc/jail.conf')
Esempio n. 9
0
def test_command_jail_create_01():
    args = lambda: 0
    args.image = 'test-jail'
    args.tags = ['test-command-jail-create-01']
    args.command = '/bin/sh /etc/rc'
    args.env = ['FOO:1', 'BAR:2']
    args.mounts = [f'/no/path:/mnt']
    args.hostname = 'test-command-jail-create-01'
    command_jail_create(args)
    name, _ = zfs_find('test-command-jail-create-01', focker_type='jail')
    mountpoint = zfs_mountpoint(name)
    jail_sha256_prefix = name.split('/')[-1]
    conf = jailconf.load('/etc/jail.conf')
    assert jail_sha256_prefix in conf
    blk = conf[jail_sha256_prefix]
    assert blk['path'] == f'\'{mountpoint}\''
    assert blk[
        'exec.start'] == f'\'export FOO=1 && export BAR=2 && {args.command}\''
    assert blk[
        'exec.prestart'] == f'\'cp /etc/resolv.conf {mountpoint}/etc/resolv.conf && mount -t nullfs /no/path {mountpoint}/mnt\''
    assert blk['host.hostname'] == f'\'{args.hostname}\''
    subprocess.check_output(
        ['focker', 'jail', 'remove', 'test-command-jail-create-01'])
Esempio n. 10
0
def get_jail_conf():
    try:
        return jailconf.load('/etc/jail.conf')
    except FileNotFoundError:
        raise Exception("No /etc/jail.conf. You need to run `mjail init`.")