#!/usr/bin/env python3 """Launch one Linux Manager server VM on an LXD remote to work with, or remove it: lm-dev-vm.py create|remove. create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project --project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project made by lm-dev-lxd-project.py, which tmp/lxd-project-PROJECT.json describes, the VM gets the package from that project's repository, as its apt source, so later dev builds reach it as updates; elsewhere it gets the newest out/linux-manager_*_all.deb. The administrator is admin with a generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env. The VM gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its network and @PSK@ a generated key, written to tmp/vm-VM.env. The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a network forward's on the project's WAN, allocated from its uplink's routes; elsewhere NAT proxy devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of the remote's URL). remove deletes the VM, its forward and tmp/vm-VM.env; .env is left as it is. """ import argparse import ipaddress import json import os import re import secrets import socket import subprocess import sys import time import urllib.parse from lm_dev import PROJECT, ROOT, TESTS, lxc_exec, set_dotenv # The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH. PORTS = ((7080, 7080), (7081, 7081), (2222, 22)) def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('action', choices=('create', 'remove')) parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)') parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT), help=f'the project of the VM (LXD_PROJECT, default {PROJECT})') parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)') parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'), help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)') parser.add_argument('--config', default='core.json', help='the configuration from tests/remote/configs/ (default core.json)') parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'), help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, " "default the IPv4 address of the remote URL's host)") args = parser.parse_args() if not args.remote: parser.error('--remote or LXD_REMOTE is required') project_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json' project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None if project and project['remote'] != args.remote: sys.exit(f'{project_file} is of remote {project["remote"]}, not {args.remote}') if not project and args.action == 'create' and not args.listen: # The default listen address is the IPv4 address of the remote's host in its lxc URL. remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True, text=True, check=True).stdout) host = urllib.parse.urlsplit(remotes.get(args.remote, {}).get('Addr', '')).hostname try: args.listen = socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None except socket.gaierror: pass if not args.listen: parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN') where = f'{args.remote}:{args.vm} (project {args.project})' exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project], capture_output=True).returncode == 0 env = ROOT / 'tmp' / f'vm-{args.vm}.env' def inside(*command, input=None): return lxc_exec(args.remote, args.project, args.vm, *command, input=input) def push(source, path, mode): return subprocess.run(['lxc', 'file', 'push', str(source), f'{args.remote}:{args.vm}{path}', '--project', args.project, '--mode', mode], capture_output=True).returncode == 0 # In a test project the VM is reached through a network forward on the project's WAN, tagged with user.vm. wan = f'{args.remote}:{project["networks"][0]}' if project else None def forward_of_vm(): listing = subprocess.run(['lxc', 'network', 'forward', 'list', wan, '-f', 'json', '--project', args.project], capture_output=True, text=True, check=True).stdout return next((forward['listen_address'] for forward in json.loads(listing) or [] if forward.get('config', {}).get('user.vm') == args.vm), None) if args.action == 'remove': if not exists: sys.exit(f'no VM {where}') if project and (listen := forward_of_vm()): subprocess.run(['lxc', 'network', 'forward', 'delete', wan, listen, '--project', args.project], check=True) subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.vm}', '--project', args.project], check=True) env.unlink(missing_ok=True) print(f'removed {where}') return if exists: sys.exit(f'{where} exists; remove it with remove or choose another --vm') config = TESTS / 'configs' / args.config if not config.is_file(): parser.error(f'no tests/remote/configs/{args.config}') debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb')) if not project and not debs: sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first') source = f'the repository {project["repository"]}' if project else debs[-1].name password, psk = secrets.token_hex(16), secrets.token_hex(24) env.parent.mkdir(parents=True, exist_ok=True) env.touch(mode=0o600) env.chmod(0o600) env.write_text(f'PSK={psk}\n', encoding='utf-8') set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password}) reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}' print(f'launching {where} from {args.image} with {source}; reached through {reached}') subprocess.run(['lxc', 'launch', args.image, f'{args.remote}:{args.vm}', '--vm', '-c', 'limits.cpu=2', '-c', 'limits.memory=4GiB', '-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'server.yaml').read_text(encoding='utf-8'), '--project', args.project], check=True) # Wait for the agent and cloud-init (status 2 is done with recoverable errors), then for the default route. for _ in range(120): if inside('cloud-init', 'status', '--wait').returncode in (0, 2): break time.sleep(5) else: sys.exit(f'{args.vm} did not boot; remove it with remove') for _ in range(24): route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout) address = route and re.search(r' inet (\S+) ', inside('ip', '-4', '-o', 'addr', 'show', 'dev', route.group(1)).stdout) if address: break time.sleep(5) else: sys.exit(f'{args.vm} has no default route or address; remove it with remove') nic, interface = route.group(1), ipaddress.IPv4Interface(address.group(1)) # Pin the leased address on the profile's NIC, then forward or proxy the ports to the VM. mac = inside('cat', f'/sys/class/net/{nic}/address').stdout.strip() expanded = subprocess.run(['lxc', 'config', 'show', '--expanded', f'{args.remote}:{args.vm}', '--project', args.project], capture_output=True, text=True, check=True).stdout device = next((m.group(1) for m in re.finditer(r'^\s*volatile\.(\S+)\.hwaddr: "?([0-9a-f:]+)"?$', expanded, re.M) if m.group(2) == mac), None) if not device: sys.exit(f'no LXD device of {args.vm} has the MAC address {mac} of {nic}') subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device, f'ipv4.address={interface.ip}', '--project', args.project], check=True) if project: # An OVN network refuses NAT proxies; the forward's listen address is allocated from the uplink's routes. subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.vm}', '--project', args.project], check=True) args.listen = forward_of_vm() if not args.listen: sys.exit(f'no forward of {args.vm} on {wan}; remove the VM with remove') for listen_port, vm_port in PORTS: subprocess.run(['lxc', 'network', 'forward', 'port', 'add', wan, args.listen, 'tcp', str(listen_port), str(interface.ip), str(vm_port), '--project', args.project], check=True) else: for listen_port, vm_port in PORTS: subprocess.run(['lxc', 'config', 'device', 'add', f'{args.remote}:{args.vm}', f'proxy-{vm_port}', 'proxy', f'listen=tcp:{args.listen}:{listen_port}', f'connect=tcp:{interface.ip}:{vm_port}', 'nat=true', '--project', args.project], check=True) # Install the package with the test administrator, from the test project's repository when there is one. if project: sources = (f'Types: deb\nURIs: {project["repository"]}\nSuites: resolute\nComponents: main\n' f'Signed-By: /etc/apt/keyrings/linux-manager-test.gpg\n') if (inside('mkdir', '-p', '/etc/apt/keyrings').returncode != 0 or not push(project['key'], '/etc/apt/keyrings/linux-manager-test.gpg', '0644') or inside('tee', '/etc/apt/sources.list.d/linux-manager-test.sources', input=sources).returncode != 0): sys.exit(f'could not add the repository of project {args.project} to {args.vm}') updated = inside('apt-get', 'update') if updated.returncode != 0: sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}') package = 'linux-manager' else: if not push(debs[-1], '/tmp/linux-manager.deb', '0644'): sys.exit(f'could not copy {debs[-1].name} into {args.vm}') package = '/tmp/linux-manager.deb' preseed = (f'linux-manager linux-manager/admin_username string admin\n' f'linux-manager linux-manager/admin_password password {password}\n') if inside('debconf-set-selections', input=preseed).returncode != 0: sys.exit(f'debconf-set-selections failed in {args.vm}') result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package) log = ROOT / 'tmp' / f'vm-{args.vm}-install.log' log.write_text(result.stdout + result.stderr, encoding='utf-8') if result.returncode != 0: sys.exit(f'the package did not install; see {log}') # Apply the configuration twice, as the server's certificates follow the first run. text = (config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network)) .replace('@PSK@', psk)) rendered = ROOT / 'tmp' / f'vm-{args.vm}.json' rendered.touch(mode=0o600) rendered.chmod(0o600) rendered.write_text(text, encoding='utf-8') pushed = push(rendered, '/etc/linux-manager/linux-manager.json', '0600') rendered.unlink() if not pushed: sys.exit(f'could not copy {args.config} into {args.vm}') for _ in range(2): if inside('systemctl', 'restart', 'linux-manager-setup').returncode != 0: sys.exit(f'linux-manager-setup failed with {args.config}; see journalctl -u linux-manager-setup in the VM') print(f'{args.vm} is up at {interface.ip} with {args.config}') print(f'administrator: admin password: {password} (also in {ROOT / ".env"})') print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222') print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l') print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}') if __name__ == '__main__': main()