#!/usr/bin/env python3 """Create or remove an LXD project for manual tests, its Vault, or its uplink: lm-dev-lxd-project.py create|remove|vault|uplink. uplink setup creates the physical uplink network once per remote, and uplink remove deletes it (see uplink). vault create makes the project's Vault, vault unseal unseals it after a restart, and vault remove deletes it (see vault_create). create makes, on the remote (--remote or LXD_REMOTE), the project (--project or LXD_PROJECT, lm-dev by default) with its root disks on --pool (LXD_POOL) and networks of its own, OVN networks on the uplink --uplink (LXD_UPLINK, uplink by default): wan, with NAT and DHCP on a subnet LXD picks, and lana and lanb, on subnets LXD picks without DHCP. The project's default profile puts eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP; lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. The container vault is the project's Vault, made first, which the scripts hand secrets to the instances through; every other instance gets an AppRole of its own in it and /etc/vault (lm_dev.enrol_instance). What they need is written to .lm-dev-config/lxd-project-PROJECT.json, with the repository's key in .lm-dev-config/lxd-project-PROJECT.gpg. remove deletes the project's instances, its networks, the project and those files. """ import argparse import json import os import re import subprocess import sys import time from lm_dev import PROJECT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, lxc_exec, vault_initialise, \ vault_state, vault_unseal NETWORKS = ('wan', 'lana', 'lanb') def lxc(*args, project, check=True, input=None): """Run lxc with the arguments in the project; raise CalledProcessError when it fails, unless check is false.""" return subprocess.run(['lxc', *args, '--project', project], input=input, capture_output=True, text=True, check=check) def launch(args, name, user_data): """Launch the container with the cloud-init user data on the project's default profile, wait until it has booted and has an address on eth0, and pin that address; the address.""" lxc('launch', args.image, f'{args.remote}:{name}', '-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / user_data).read_text(encoding='utf-8'), project=args.project) # cloud-init's status 2 is done with recoverable errors. for _ in range(120): if lxc_exec(args.remote, args.project, name, 'cloud-init', 'status', '--wait').returncode in (0, 2): break time.sleep(5) else: raise RuntimeError(f'the container {name} did not boot') for _ in range(24): match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/', lxc_exec(args.remote, args.project, name, 'ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout) if match: break time.sleep(5) else: raise RuntimeError(f'the container {name} has no address on eth0') lxc('config', 'device', 'override', f'{args.remote}:{name}', 'eth0', f'ipv4.address={match.group(1)}', project=args.project) return match.group(1) def vault_forward(args): """The listen address of the forward of the project's Vault on wan, or None.""" listing = lxc('network', 'forward', 'list', f'{args.remote}:wan', '-f', 'json', project=args.project, check=False) if listing.returncode != 0: return None return next((forward['listen_address'] for forward in json.loads(listing.stdout) or [] if forward.get('config', {}).get('user.service') == 'vault'), None) def vault_create(args): """Make the project's Vault: the container vault (cloud-init vault.yaml), a forward of its port on wan at --vault-address or an allocated one, which the scripts reach it on, and its initialisation with one key share, unsealed, with KV v2, TOTP and AppRole; its key and root token are kept in .lm-dev-config/vault-PROJECT.json; the state.""" if vault_state(args.project) is not None: raise RuntimeError(f'project {args.project} has a Vault; remove it with vault remove first') print(f'launching the Vault container {args.remote}:vault (project {args.project})') address = launch(args, 'vault', 'vault.yaml') listen = [args.vault_address] if args.vault_address else ['--allocate=ipv4'] lxc('network', 'forward', 'create', f'{args.remote}:wan', *listen, 'user.service=vault', project=args.project) forward = vault_forward(args) if not forward: raise RuntimeError('the forward of the Vault was not made') lxc('network', 'forward', 'port', 'add', f'{args.remote}:wan', forward, 'tcp', str(VAULT_PORT), address, str(VAULT_PORT), project=args.project) state = vault_initialise(args.project, f'http://{forward}:{VAULT_PORT}', f'http://{address}:{VAULT_PORT}') print(f'the Vault of {args.project} is at {state["url"]}, for the instances {state["internal_url"]}; ' f'state: {config_path(f"vault-{args.project}.json")}') return state def vault_remove(args): """Delete the project's Vault, its forward and its state; True when all went.""" ok = True if lxc('info', f'{args.remote}:vault', project=args.project, check=False).returncode == 0: result = lxc('delete', '--force', f'{args.remote}:vault', project=args.project, check=False) if result.returncode != 0: ok = False print(f'could not delete vault: {result.stderr.strip()}', file=sys.stderr) forward = vault_forward(args) if forward: lxc('network', 'forward', 'delete', f'{args.remote}:wan', forward, project=args.project, check=False) if ok: config_path(f'vault-{args.project}.json').unlink(missing_ok=True) print(f'project {args.project} has no Vault') return ok def create(args, state, key): """Create the project with its networks and default profile, the Vault and the repository container.""" subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool, '-c', 'features.images=false', '-c', 'features.networks=true'], capture_output=True, text=True, check=True) print(f'project {args.project} created; creating its OVN networks on {args.uplink}') lxc('network', 'create', f'{args.remote}:wan', '--type=ovn', f'network={args.uplink}', 'ipv4.address=auto', 'ipv4.nat=true', 'ipv4.dhcp=true', 'ipv6.address=none', project=args.project) # OVN gives every network's router an address; without DHCP the LAN hosts keep their own gateways. for name in ('lana', 'lanb'): lxc('network', 'create', f'{args.remote}:{name}', '--type=ovn', f'network={args.uplink}', 'ipv4.address=auto', 'ipv4.nat=true', 'ipv4.dhcp=false', 'ipv6.address=none', project=args.project) # The project's default profile has the root disk on the pool of project create's -s. lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0', project=args.project) vault = vault_create(args) print(f'launching the repository container {args.remote}:repo (project {args.project})') address = launch(args, 'repo', 'repo.yaml') problem = enrol_instance(args.remote, args.project, 'repo', vault) if problem: raise RuntimeError(problem) def inside(*command): return lxc_exec(args.remote, args.project, 'repo', *command) # The signing key, the publishing script and the empty indexes. generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', 'Linux Manager test repository', 'default', 'default', 'never') export = ('gpg', '--batch', '--yes', '--export', '-o', '/root/linux-manager-test.gpg') for step, command in (('key generation', generate), ('key export', export)): result = inside(*command) if result.returncode != 0: raise RuntimeError(f'the {step} failed in repo: {result.stderr.strip()}') lxc('file', 'push', str(TESTS / 'repo' / 'publish.sh'), f'{args.remote}:repo/usr/local/sbin/linux-manager-repo-publish', '--mode', '0755', project=args.project) result = inside('linux-manager-repo-publish') if result.returncode != 0: raise RuntimeError(f'the repository was not published: {result.stderr.strip()}') lxc('file', 'pull', f'{args.remote}:repo/root/linux-manager-test.gpg', str(key), project=args.project) state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS), 'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n', encoding='utf-8') state.chmod(0o600) print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, ' f'repository http://{address}/') print(f'state: {state}') def remove(args, state, key): """Delete the project's instances, the networks, the project and the local files; True when all went.""" ok = True listing = lxc('list', f'{args.remote}:', '-c', 'n', '-f', 'csv', project=args.project, check=False) for name in listing.stdout.split(): result = lxc('delete', '--force', f'{args.remote}:{name}', project=args.project, check=False) if result.returncode != 0: ok = False print(f'could not delete {name}: {result.stderr.strip()}', file=sys.stderr) # The default profile's eth0 keeps wan in use. lxc('profile', 'device', 'remove', f'{args.remote}:default', 'eth0', project=args.project, check=False) for name in NETWORKS: if lxc('network', 'show', f'{args.remote}:{name}', project=args.project, check=False).returncode != 0: continue result = lxc('network', 'delete', f'{args.remote}:{name}', project=args.project, check=False) if result.returncode != 0: ok = False print(f'could not delete network {name}: {result.stderr.strip()}', file=sys.stderr) result = subprocess.run(['lxc', 'project', 'delete', f'{args.remote}:{args.project}'], capture_output=True, text=True) if result.returncode != 0: ok = False print(f'could not delete project {args.project}: {result.stderr.strip()}', file=sys.stderr) if ok: state.unlink(missing_ok=True) key.unlink(missing_ok=True) config_path(f'vault-{args.project}.json').unlink(missing_ok=True) print(f'removed project {args.project} and its networks from {args.remote}') return ok def uplink(args): """Create the physical uplink network of the OVN networks on a host bridge of the LAN, or delete it. setup creates --uplink in the default project with parent --parent, the LAN's gateway --gateway (address/prefix), its name servers --dns, the LAN addresses OVN routers take (--ovn-ranges, FIRST-LAST) and the LAN subnets for network forwards (--routes, CIDR); OVN answers ARP for those on the LAN (ovn.ingress_mode l2proxy, the default). It leaves an existing network of that name as it is. remove deletes the network. """ network = f'{args.remote}:{args.uplink}' exists = lxc('network', 'show', network, project='default', check=False).returncode == 0 if args.operation == 'remove': if exists: lxc('network', 'delete', network, project='default') print(f'{args.remote} has no network {args.uplink}') return if exists: print(f'{args.remote} has the network {args.uplink} already') return missing = [option for option, value in (('--parent', args.parent), ('--gateway', args.gateway), ('--dns', args.dns), ('--ovn-ranges', args.ovn_ranges), ('--routes', args.routes)) if not value] if missing: sys.exit(f'uplink setup needs {", ".join(missing)}') lxc('network', 'create', network, '--type=physical', f'parent={args.parent}', f'ipv4.gateway={args.gateway}', f'dns.nameservers={args.dns}', f'ipv4.ovn.ranges={args.ovn_ranges}', f'ipv4.routes={args.routes}', project='default') print(f'{args.uplink} on {args.remote}: physical on {args.parent}, gateway {args.gateway}, OVN routers ' f'{args.ovn_ranges}, forwards {args.routes}') def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink')) parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'), help='after vault: create, unseal or remove; after uplink: setup or remove') parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') parser.add_argument('--pool', default=os.environ.get('LXD_POOL'), help='the storage pool of the project, for create (LXD_POOL)') parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), help=f'the project (LXD_PROJECT, default {PROJECT})') parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)') parser.add_argument('--vault-address', default=os.environ.get('LXD_VAULT_ADDRESS'), help="the listen address of the Vault's forward, one of the uplink's routes " '(LXD_VAULT_ADDRESS); without it one is allocated') parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'), help='the physical uplink network of the OVN networks (LXD_UPLINK, default uplink)') parser.add_argument('--parent', default=os.environ.get('LXD_UPLINK_PARENT'), help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)') parser.add_argument('--gateway', default=os.environ.get('LXD_UPLINK_GATEWAY'), help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)') parser.add_argument('--dns', default=os.environ.get('LXD_UPLINK_DNS'), help='uplink setup: the LAN name servers, comma-separated (LXD_UPLINK_DNS)') parser.add_argument('--ovn-ranges', default=os.environ.get('LXD_UPLINK_OVN_RANGES'), help='uplink setup: LAN addresses for OVN routers, FIRST-LAST (LXD_UPLINK_OVN_RANGES)') parser.add_argument('--routes', default=os.environ.get('LXD_UPLINK_ROUTES'), help='uplink setup: LAN subnets for network forwards, CIDR (LXD_UPLINK_ROUTES)') args = parser.parse_args() if not args.remote: parser.error('--remote or LXD_REMOTE is required') operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')} if args.operation not in operations.get(args.action, (None,)): parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else') if args.action == 'uplink': try: uplink(args) except subprocess.CalledProcessError as error: sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}') return state = config_path(f'lxd-project-{args.project}.json') key = config_path(f'lxd-project-{args.project}.gpg') if args.action == 'vault': try: if args.operation == 'create': vault_create(args) elif args.operation == 'unseal': current = vault_state(args.project) if current is None: sys.exit(f'project {args.project} has no Vault') vault_unseal(current) print(f'the Vault of {args.project} is unsealed') elif not vault_remove(args): sys.exit(1) except subprocess.CalledProcessError as error: sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}') except (RuntimeError, VaultError) as error: sys.exit(str(error)) return if args.action == 'remove': sys.exit(0 if remove(args, state, key) else 1) if not args.pool: parser.error('--pool or LXD_POOL is required') if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0: sys.exit(f'project {args.project} exists on {args.remote}; remove it first or choose another --project') state.parent.mkdir(parents=True, exist_ok=True) try: create(args, state, key) except subprocess.CalledProcessError as error: sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}\n' f'remove what was made with: {sys.argv[0]} remove --remote {args.remote} --project {args.project}') except (RuntimeError, VaultError) as error: sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} ' f'--project {args.project}') if __name__ == '__main__': main()