Files
linux-cloud-router/bin/lm-dev-vm.py
T

254 lines
15 KiB
Python
Executable File

#!/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 .lm-dev-config/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 --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with a
generated password, kept as username and password in .lm-dev-config/vm-PROJECT-VM.json, and a TOTP
token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given;
lm-dev-otp-code.py prints its codes. 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. The VM gets an AppRole of its own in the project's Vault
(lm_dev.enrol_instance), with which it reads the debconf preseed with the admin's password and the
configuration with its key, kept there as VM/preseed and VM/config, and creates its TOTP key; no
secret is an argument or on standard input, so create needs a project with a Vault
(lm-dev-lxd-project.py vault create). The admin's password is also kept there as VM/admin.
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, --forward-address (LXD_FORWARD_ADDRESS) or else one 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, its .lm-dev-config/vm-PROJECT-VM.json and what
the Vault keeps for it. The defaults of the options come from the environment, else from
.lm-dev-config/settings.json (lm_dev.setting).
"""
import argparse
import ipaddress
import json
import pathlib
import re
import secrets
import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, PROJECT, ROOT, TESTS, VAULT_MOUNT, MissingSetting, VaultError, config_path, \
credentials_path, enrol_instance, enrol_otp, forget_instance, hand_over, host_address, lxc_exec, newest_deb, \
setting, store_secret, vault_state, write_private
# 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', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('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=setting('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=setting('LXD_LISTEN', None),
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)")
parser.add_argument('--forward-address', default=setting('LXD_FORWARD_ADDRESS', None),
help="with create in a test project, the forward's listen address, one of the uplink's routes "
"(LXD_FORWARD_ADDRESS); without it one is allocated")
parser.add_argument('--no-otp', action='store_true', help='with create, enrol no TOTP token for admin')
parser.add_argument('--deb', help='outside a test project, the package to install (default the one built last, '
'in out/ or out/dev/)')
args = parser.parse_args()
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
project_file = config_path(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.
args.listen = host_address(args.remote)
if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN, in the '
'environment or .lm-dev-config/settings.json')
where = f'{args.remote}:{args.vm} (project {args.project})'
credentials = credentials_path(args.project, args.vm)
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0
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)
if (vault := vault_state(args.project)) is not None:
try:
forget_instance(vault, args.vm)
except VaultError as error:
print(f'the Vault keeps what it had for {args.vm}: {error}', file=sys.stderr)
credentials.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}')
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not project and (deb is None or not deb.is_file()):
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
source = f'the repository {project["repository"]}' if project else str(deb)
vault = vault_state(args.project)
if vault is None:
sys.exit(f'project {args.project} has no Vault, which the secrets reach the VM through; make it with '
'lm-dev-lxd-project.py vault create')
password, psk = secrets.token_hex(16), secrets.token_hex(24)
write_private(credentials, json.dumps({'username': 'admin', 'password': password}, indent=2) + '\n')
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')
problem = enrol_instance(args.remote, args.project, args.vm, vault)
if problem:
sys.exit(f'{problem}; remove the VM 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 --forward-address, or one allocated
# from the uplink's routes.
address = [args.forward_address] if args.forward_address else ['--allocate=ipv4']
subprocess.run(['lxc', 'network', 'forward', 'create', wan, *address, 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(deb, '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {deb} into {args.vm}')
package = '/tmp/linux-manager.deb'
preseed = ('linux-manager linux-manager/admin_username string admin\n'
f'linux-manager linux-manager/admin_password password {password}\n')
try:
store_secret(vault, f'{args.vm}/admin', {'password': password})
except VaultError as error:
sys.exit(f'the admin password cannot be kept in the Vault: {error}')
if inside('install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0:
sys.exit(f'{HANDOVER_DIR} cannot be made in {args.vm}')
problem = hand_over(args.remote, args.project, args.vm, vault, 'preseed', preseed, f'{HANDOVER_DIR}/preseed', '0600')
if problem:
sys.exit(problem)
if inside('sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; rm -f {HANDOVER_DIR}/preseed; '
'exit $status').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))
problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk),
'/etc/linux-manager/linux-manager.json', '0600')
if problem:
sys.exit(f'could not give {args.vm} {args.config}: {problem}')
for _ in range(2):
if inside('linux-manager-config-edit', 'apply').returncode != 0:
sys.exit(f'linux-manager-setup failed with {args.config}; see journalctl -u linux-manager-setup in the VM')
if not args.no_otp:
problem = enrol_otp(args.remote, args.project, args.vm, 'admin')
if problem:
sys.exit(f'{args.vm} is up, but {problem}')
print(f'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin, password in {credentials} and the Vault ({VAULT_MOUNT}/{args.vm}/admin)')
if not args.no_otp:
print(f'administrator TOTP: otp_url in {credentials}; codes: bin/lm-dev-otp-code.py --project {args.project} '
f'--vm {args.vm}')
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()