fix: the root CA is created by the server, an offline CA or a Simple CA service, chosen at setup; the shell can stay open in a tab of its own, the Docker page is offered only with Docker, and the test scripts are in bin/.
Release / release (push) Failing after 14m20s

This commit is contained in:
slawek committed 2026-11-23 06:45:23 +01:00
1 parent ff0c93ed73
commit a649331aa2
49 files changed
+1597 -637

No files matched your search

+114 -45
View File
@@ -1,7 +1,10 @@
# Remote tests
`run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD remote and
checks the router and VPN components in three scenarios:
The scripts are in `bin/` of the repository; this directory holds their data: `scenarios/`,
`configs/`, `cloud-init/`, `repo/` and the files copied into instances.
`bin/lm-dev-run.py` installs the newest `out/linux-manager_*_all.deb` into instances of an LXD
remote and checks the router and VPN components in three scenarios:
- `core`: one interface, router and VPN off;
- `nat`: VPN on, router off, one interface; WireGuard and OpenVPN clients reach a target through
@@ -11,7 +14,7 @@ checks the router and VPN components in three scenarios:
`site_to_site` is set, which setup refuses.
Servers are virtual machines, clients and LAN hosts containers, all from `ubuntu:26.04`. Each
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `run.py`.
scenario is a module in `scenarios/` whose `run(lab)` uses the `Lab` class of `lm-dev-run.py`.
`wireguard_peer.py` and `echo.py` are copied into the instances: the first gives the test user a
WireGuard peer on the server, the second answers HTTP with the client's address.
@@ -22,11 +25,11 @@ export LXD_POOL=...
```sh
./build.sh
tests/remote/run.py core nat s2s
bin/lm-dev-run.py core nat s2s
```
```sh
tests/remote/run.py all
bin/lm-dev-run.py all
```
Options:
@@ -35,14 +38,16 @@ Options:
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--pool` | `LXD_POOL` | required | The storage pool of the project's root disks |
| `--project` | `LXD_PROJECT` | `lm-test` | The project the instances live in; it must not exist |
| `--project` | `LXD_TEST_PROJECT` | `lm-test` | The project the instances live in; it must not exist |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of every instance |
| `--keep` | | off | Leaves the project and the networks in place; run one scenario then |
Each scenario creates the project and its networks (`lmt-<scenario>-<net>`) and removes them at
its end. The administrator password and the pre-shared key are generated per run and written to
`tmp/remote-test.env`. The run prints PASS, FAIL or SKIP per check and exits non-zero on a
failure; WireGuard is skipped when the host kernel has no WireGuard module.
its end. The administrator password and the pre-shared key are generated per run. The
administrator's name and password are set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
repository's `.env`, keeping its other lines, and the key is written to `tmp/remote-test.env`.
The run prints PASS, FAIL or SKIP per check and exits non-zero on a failure; WireGuard is skipped
when the host kernel has no WireGuard module.
The configurations in `configs/` have placeholders that are filled in for each server:
@@ -52,53 +57,56 @@ The configurations in `configs/` have placeholders that are filled in for each s
## A VM to work with
`vm.py` launches one server VM, `lm-dev` by default, on the LXD remote and leaves it
running. The VM is created in a project, `default` by default, with that project's default
profile, and takes its address from DHCP. It gets the newest package with the administrator
`admin` and a generated password, written to `tmp/vm-<name>.env`, and a configuration from
`configs/`, `core.json` by default; `@ETH0@` is the interface of the VM's default route.
`lm-dev-vm.py create` launches one server VM, `lm-dev` by default, on the LXD remote and leaves
it running. The VM is created in a project, the test project `lm-dev` by default, with that
project's default profile, and takes its address from DHCP. It gets the package with the
administrator `admin` and a generated password, set as `ADMIN_USERNAME` and `ADMIN_PASSWORD` in the
repository's `.env`, and a configuration from `configs/`, `core.json` by default; `@ETH0@` is the
interface of the VM's default route.
The leased address is pinned on the VM's NIC, as NAT proxy devices require a static address.
Proxy devices then forward ports of the LXD host address `--listen` to the VM; by default that is
the IPv4 address of the host in the remote's URL (`lxc remote list`), which must be an address of
the LXD host itself:
In a test project made by `lm-dev-lxd-project.py`, the VM installs the package from the project's
repository, so later dev builds reach it as updates; in another project it installs the newest
`out/linux-manager_*_all.deb`. The leased address is pinned on the VM's NIC, and these ports lead
to the VM:
- `7080` to the Manager;
- `7081` to the status web service;
- `2222` to SSH, port `22`.
The script prints the VM's address, the administrator's password, the proxied URLs, the command
of a shell in it and the command that removes it.
In a test project they lead through a network forward on the project's `wan`, whose listen address
LXD allocates from the uplink's `--routes`, as LXD refuses NAT proxy devices in a project with
networks of its own. In another project NAT proxy devices listen on the LXD host address
`--listen`, by default the IPv4 address of the host in the remote's URL (`lxc remote list`), which
must be an address of the LXD host itself.
The script prints the VM's address, the administrator's password, the URLs, the command of a
shell in it and the command that removes it.
```sh
tests/remote/vm.py
bin/lm-dev-vm.py create
```
```sh
tests/remote/vm.py --remove
bin/lm-dev-vm.py remove
```
`--remove` deletes the VM and its env file. Options:
`remove` deletes the VM, its forward and `tmp/vm-<vm>.env`, its pre-shared key; `.env` is left as
it is. Options:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | | `default` | The project of the VM |
| `--name` | | `lm-dev` | The name of the VM; it must not exist |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM; it must not exist for `create` |
| `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM |
| `--config` | | `core.json` | The configuration from `configs/` |
| `--listen` | `LXD_LISTEN` | the remote URL's host | An address of the LXD host the proxies listen on |
In a test project made by `lxd-project.py`, `vm.py` installs the package from the project's
repository instead of `out/`, so later dev builds reach the VM as updates. LXD refuses NAT proxy
devices in a project with networks of its own, so there the ports lead through a network forward
on the project's `wan`, whose listen address LXD allocates from the uplink's `--routes`;
`--listen` does not apply, and `--remove` deletes the forward with the VM.
| `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on |
## A test project with dev builds
`lxd-project.py create` makes a project for manual tests that stays until
`lxd-project.py remove`; `run.py` keeps making and removing its own projects. The project has:
`lm-dev-lxd-project.py create` makes a project for manual tests that stays until
`lm-dev-lxd-project.py remove`; `lm-dev-run.py` keeps making and removing its own projects. The
project has:
- networks of its own (`features.networks`), OVN networks on the physical uplink `--uplink`:
`wan`, with NAT and DHCP on a subnet LXD picks, and `lana` and `lanb`, on subnets LXD picks
@@ -127,19 +135,19 @@ OVN answers ARP for its routers' and forwards' addresses on the LAN (`ovn.ingres
of that name as it is; `uplink remove` deletes it.
```sh
tests/remote/lxd-project.py uplink setup
bin/lm-dev-lxd-project.py uplink setup
```
```sh
tests/remote/lxd-project.py uplink remove
bin/lm-dev-lxd-project.py uplink remove
```
```sh
tests/remote/lxd-project.py create
bin/lm-dev-lxd-project.py create
```
```sh
tests/remote/lxd-project.py remove
bin/lm-dev-lxd-project.py remove
```
| Option | Variable | Default | Meaning |
@@ -155,21 +163,82 @@ tests/remote/lxd-project.py remove
| `--ovn-ranges` | `LXD_UPLINK_OVN_RANGES` | required by `uplink setup` | LAN addresses for OVN routers |
| `--routes` | `LXD_UPLINK_ROUTES` | required by `uplink setup` | A LAN subnet for network forwards |
`dev-build.py` builds and publishes the next dev build. Its version is the newest changelog
`lm-dev-build.py` builds and publishes the next dev build. Its version is the newest changelog
entry's with `~dev<N>` before the Debian revision, `0.41.0~dev7-1` for `0.41.0-1`, so the release
of that entry is newer than its dev builds. `N` is kept in `tmp/test-number` and goes up with each
build that succeeds. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the
of that entry is newer than its dev builds. `N` is that of the last dev build, kept in
`.dev-build.serial` of the repository; each build that succeeds writes its own, one higher, and
`release.py` writes 0 when it releases, so the next entry's builds start at `~dev1`. `./build.sh` builds it, with `CONTAINER_RUNTIME` and `DOCKER_CONTEXT` from the
environment; the build is moved to `out/dev/`, copied into the repository and published there. A
VM of the project then gets it with Check update and Upgrade in the Manager, or `apt-get update`
and `apt-get upgrade`.
```sh
tests/remote/dev-build.py
bin/lm-dev-build.py
```
`--project` (`LXD_PROJECT`, `lm-dev` by default) names the project.
`--project` (`LXD_PROJECT`, `lm-dev` by default) names the project; the remote is the project's,
read from its state file, so the script takes no `--remote`.
## A TOTP token for a user of a test VM
`bin/lm-dev-otp-register.py` enrols a new TOTP token for a user of a VM, `admin` of `lm-dev` by
default, through `lxc exec`: in the VM, as root, the package's `linuxmanager_users` makes a new
secret and stores it once a code the script computes from it verifies, replacing a token the user
had. The secret, base32, is then written to the file `--secret-file` or `OTP_FILE` names,
readable by its owner only; `otp.py code` prints its codes (see below).
```sh
export OTP_FILE=tmp/admin.otp
bin/lm-dev-otp-register.py
```
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file the secret is written to |
| `--remote` | `LXD_REMOTE` | required | The `lxc` remote |
| `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM |
| `--vm` | | `lm-dev` | The name of the VM |
| `--user` | | `admin` | The user to enrol |
## A command-line authenticator app
`bin/otp.py` is an authenticator app on the command line, in place of one on a phone, not tied to
Linux Manager or LXD. It keeps a base32 secret in the file `--secret-file` or `OTP_FILE` names,
readable by its owner only. The codes are
RFC 6238's, SHA-1, 6 digits and 30 seconds by default.
Options of both actions:
| Option | Variable | Default | Meaning |
|---|---|---|---|
| `--secret-file` | `OTP_FILE` | required | The file of the base32 secret |
| `--algorithm` | | `sha1` | `sha1`, `sha256` or `sha512` |
| `--digits` | | `6` | The digits of a code, 6 to 10 |
| `--period` | | `30` | The seconds a code is valid |
`new` makes a new secret of 20 random bytes in the file and prints its `otpauth://` URI, with the
algorithm, digits and period, for a server or an app that enrols a given secret:
```sh
bin/otp.py new --account admin --issuer lm-dev
```
| Option | Default | Meaning |
|---|---|---|
| `--account`, `--issuer` | none | The label of the URI |
| `--force` | off | Replace an existing secret |
`code` prints the current code of the secret, for the Manager's sign-in, SSH or `sudo`:
```sh
bin/otp.py code
```
| Option | Default | Meaning |
|---|---|---|
| `--at` | now | The Unix time of the code |
## Scope of the tests
Not covered by `run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and
passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules.
Not covered by `lm-dev-run.py`: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID
Provider and passkeys, PowerDNS answering from outside, and the Azure and GCP platform modules.
+11
View File
@@ -0,0 +1,11 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-offline.test"},
"local": {"cidrs": ["@CIDR0@"]},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"pki": {"root": "offline"},
"https": {"enabled": false}
}
+11
View File
@@ -0,0 +1,11 @@
{
"general": {"platform": "generic", "mode": "manual"},
"router": {"enabled": false},
"vpn": {"enabled": true},
"interfaces": {"external": "@ETH0@"},
"wan": {"local_fqdn": "lm-simple-ca.test"},
"local": {"cidrs": ["@CIDR0@"]},
"openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"},
"pki": {"root": "simple-ca", "simple_ca_url": "https://10.188.96.4:8443"},
"https": {"enabled": false}
}
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env python3
"""Build the next numbered dev build and publish it to a test project's repository: dev-build.py.
The test number in tmp/test-number goes up by one for each build that succeeds. The build's version
is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1 becoming
0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.sh builds it
with CONTAINER_RUNTIME and DOCKER_CONTEXT from the environment; the build is moved to out/dev/,
copied into the repository container of the project (--project or LXD_PROJECT, lm-dev by default)
made by lxd-project.py, and published there.
"""
import argparse
import json
import os
import pathlib
import re
import subprocess
import sys
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
NUMBER = ROOT / 'tmp' / 'test-number'
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', 'lm-dev'),
help='the test project made by lxd-project.py (LXD_PROJECT, default lm-dev)')
args = parser.parse_args()
state_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
if not state_file.is_file():
sys.exit(f'no {state_file}; create the project with lxd-project.py create')
state = json.loads(state_file.read_text(encoding='utf-8'))
# The newest entry's first line is "package (version) distribution; urgency=...".
match = re.match(r'(\S+) \(([^)]+)\)', CHANGELOG.read_text(encoding='utf-8'))
if not match:
sys.exit(f'no version in the first line of {CHANGELOG}')
package, version = match.groups()
number = int(NUMBER.read_text(encoding='utf-8').strip()) + 1 if NUMBER.is_file() else 1
upstream, dash, revision = version.rpartition('-')
dev = f'{upstream}~dev{number}-{revision}' if dash else f'{version}~dev{number}'
print(f'building {package} {dev}')
if subprocess.run(['./build.sh', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
sys.exit(f'the build of {dev} failed; the test number stays {number - 1}')
NUMBER.write_text(f'{number}\n', encoding='utf-8')
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
target.mkdir(exist_ok=True)
for artifact in (ROOT / 'out').glob(f'{package}_{dev}_*'):
artifact.replace(target / artifact.name)
deb = target / f'{package}_{dev}_all.deb'
if not deb.is_file():
sys.exit(f'the build made no {deb.name}')
where = ['--project', state['project']]
pushed = subprocess.run(['lxc', 'file', 'push', str(deb), f'{state["remote"]}:repo/var/www/html/pool/main/{deb.name}',
'--mode', '0644', *where], capture_output=True, text=True)
if pushed.returncode != 0:
sys.exit(f'could not copy {deb.name} into the repository: {pushed.stderr.strip()}')
published = subprocess.run(['lxc', 'exec', f'{state["remote"]}:repo', *where, '-T', '--',
'linux-manager-repo-publish'], capture_output=True, text=True)
if published.returncode != 0:
sys.exit(f'the repository was not published: {published.stderr.strip()}')
print(f'{package} {dev} is published at {state["repository"]} (resolute main)')
if __name__ == '__main__':
main()
-221
View File
@@ -1,221 +0,0 @@
#!/usr/bin/env python3
"""Create or remove an LXD project for manual tests: lxd-project.py create|remove|uplink setup|remove.
uplink setup creates the physical uplink network once per remote, uplink remove deletes it (see
uplink).
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; dev-build.py publishes into it and vm.py installs from it. What they need is
written to tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg.
remove deletes the project's instances, its networks, the project and those files.
"""
import argparse
import json
import os
import pathlib
import re
import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
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 create(args, state, key):
"""Create the project with its networks and default profile, 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)
print(f'launching the repository container {args.remote}:repo (project {args.project})')
lxc('launch', args.image, f'{args.remote}:repo',
'-c', 'cloud-init.user-data=' + (HERE / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'),
project=args.project)
def inside(*command):
return subprocess.run(['lxc', 'exec', f'{args.remote}:repo', '--project', args.project, '-T', '--', *command],
capture_output=True, text=True)
# Wait for cloud-init (status 2 is done with recoverable errors), then for the address of eth0.
for _ in range(120):
if inside('cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
raise RuntimeError('the repository container did not boot')
for _ in range(24):
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/', inside('ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout)
if match:
break
time.sleep(5)
else:
raise RuntimeError('the repository container has no address on eth0')
address = match.group(1)
lxc('config', 'device', 'override', f'{args.remote}:repo', 'eth0', f'ipv4.address={address}',
project=args.project)
# The signing key, the publishing script and the empty indexes.
for step, command in (('key generation', ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '',
'--quick-generate-key', 'Linux Manager test repository', 'default',
'default', 'never')),
('key export', ('gpg', '--batch', '--yes', '--export', '-o', '/root/linux-manager-test.gpg'))):
result = inside(*command)
if result.returncode != 0:
raise RuntimeError(f'the {step} failed in repo: {result.stderr.strip()}')
lxc('file', 'push', str(HERE / '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')
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)
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', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='with 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', 'lm-dev'),
help='the project (LXD_PROJECT, default lm-dev)')
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('--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')
if (args.action == 'uplink') != (args.operation is not None):
parser.error('setup or remove follows uplink, and only uplink')
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 = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
key = ROOT / 'tmp' / f'lxd-project-{args.project}.gpg'
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 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()
-360
View File
@@ -1,360 +0,0 @@
#!/usr/bin/env python3
"""Run the Linux Manager test scenarios on an LXD remote: run.py core|nat|s2s... or run.py all.
The remote and its storage pool are required, as --remote and --pool or LXD_REMOTE and
LXD_POOL. The instances live in a project of their own, which must not exist and is removed
with its networks after each scenario unless --keep is given. The package is the newest
out/linux-manager_*_all.deb. Each check prints PASS, FAIL or SKIP; the run exits 1 when a
check failed.
"""
import argparse
import importlib
import ipaddress
import json
import os
import pathlib
import re
import secrets
import subprocess
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
TMP = ROOT / 'tmp' / 'remote-test'
SCENARIOS = sorted(path.stem for path in (HERE / 'scenarios').glob('*.py') if path.stem != '__init__')
class Lab:
"""The instances and networks of a run on one LXD remote and project, and the results of its checks.
A NIC is a (network, mac, address/prefix[, gateway]) tuple; an address of None is taken from
DHCP.
"""
def __init__(self, remote, project, pool, image, keep, deb, admin_password, psk):
self.remote = remote
self.project = project
self.pool = pool
self.image = image
self.keep = keep
self.deb = deb
self.admin_password = admin_password
self.psk = psk
self.passed = self.failed = self.skipped = 0
self.networks = []
self.macs = {}
self.addresses = {}
def lxc(self, *args, check=True):
"""Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false."""
return subprocess.run(['lxc', *args, '--project', self.project], capture_output=True, text=True, check=check)
def on(self, name, *command, input=None):
"""Run the command in the instance with the input, and return its CompletedProcess."""
return subprocess.run(
['lxc', 'exec', f'{self.remote}:{name}', '--project', self.project, '-T', '--', *command],
input=input, capture_output=True, text=True)
def push(self, source, name, path, mode='0644'):
"""Copy the local file into the instance; True when it was copied."""
result = self.lxc('file', 'push', str(source), f'{self.remote}:{name}{path}', '--mode', mode, check=False)
return result.returncode == 0
def push_text(self, text, name, path, mode='0644'):
"""Write the text to a local file readable by its owner only, copy it into the instance and remove it."""
local = TMP / f'{name}{path.replace("/", "_")}'
local.touch(mode=0o600)
local.chmod(0o600)
local.write_text(text, encoding='utf-8')
try:
return self.push(local, name, path, mode)
finally:
local.unlink()
def json_of(self, name, *command):
"""The JSON output of the command in the instance, or None when the command fails or its output is no JSON."""
result = self.on(name, *command)
try:
return json.loads(result.stdout) if result.returncode == 0 else None
except ValueError:
return None
def result(self, description, ok):
"""Count and print the check as PASS when ok, else FAIL."""
if ok:
self.passed += 1
print(f'PASS {description}')
else:
self.failed += 1
print(f'FAIL {description}')
def skip(self, description):
"""Count and print the check as SKIP."""
self.skipped += 1
print(f'SKIP {description}')
def check(self, description, name, *command):
"""Pass when the command succeeds in the instance."""
self.result(description, self.on(name, *command).returncode == 0)
def expect(self, description, pattern, name, *command):
"""Pass when a line of the command's output, standard error included, matches the regular expression."""
result = self.on(name, *command)
self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is not None)
def refuse(self, description, pattern, name, *command):
"""Pass when no line of the command's output, standard error included, matches the regular expression."""
result = self.on(name, *command)
self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is None)
def network(self, name, address):
"""Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None.
A bridge without a host address is reachable only through the instances on it.
"""
if address is None:
self.lxc('network', 'create', f'{self.remote}:{name}', 'ipv4.address=none', 'ipv6.address=none')
else:
self.lxc('network', 'create', f'{self.remote}:{name}', f'ipv4.address={address}', 'ipv4.nat=true',
'ipv4.dhcp=false', 'ipv6.address=none')
self.networks.append(name)
def instance(self, name, kind, user_data, *nics):
"""Create and start a vm or container with the NICs, whose static addresses are set through cloud-init.
A container's NICs are eth0 and on, named by LXD, as a veth has no permanent MAC address for
netplan to match; a VM's NICs keep their kernel names, which the initramfs sets before
netplan could rename them, and are matched by MAC address (nic_of).
"""
self.macs[name] = [nic[1] for nic in nics]
self.addresses[name] = nics[0][2]
netcfg = 'version: 2\nethernets:\n'
for index, (_, mac, address, *gateway) in enumerate(nics):
if kind == 'vm':
netcfg += f' nic{index}:\n match:\n macaddress: "{mac}"\n'
else:
netcfg += f' eth{index}:\n'
netcfg += f' addresses: [{address}]\n' if address else ' dhcp4: true\n'
if gateway:
netcfg += (f' routes:\n - to: default\n via: {gateway[0]}\n'
f' nameservers:\n addresses: [{gateway[0]}]\n')
limits = ['-c', 'limits.cpu=2', '-c', 'limits.memory=4GiB'] if kind == 'vm' else \
['-c', 'limits.cpu=1', '-c', 'limits.memory=1GiB']
self.lxc('init', self.image, f'{self.remote}:{name}', *(['--vm'] if kind == 'vm' else []), *limits,
'-c', 'cloud-init.user-data=' + (HERE / 'cloud-init' / user_data).read_text(encoding='utf-8'),
'-c', 'cloud-init.network-config=' + netcfg)
if kind != 'vm':
self.lxc('config', 'device', 'add', f'{self.remote}:{name}', 'tun', 'unix-char', 'path=/dev/net/tun')
for index, (network, mac, *_) in enumerate(nics):
self.lxc('config', 'device', 'add', f'{self.remote}:{name}', f'eth{index}', 'nic', f'network={network}',
f'hwaddr={mac}', *([] if kind == 'vm' else [f'name=eth{index}']))
self.lxc('start', f'{self.remote}:{name}')
def ready(self, *names):
"""Wait for each instance's agent and cloud-init, then for its first address; False when one is not ready.
cloud-init's status 2, done with recoverable errors, counts as booted. An instance whose first
NIC takes its address from DHCP waits for any IPv4 address outside lo.
"""
for name in names:
for _ in range(120):
if self.on(name, 'cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
print(f'{name} did not boot', file=sys.stderr)
return False
address = self.addresses[name]
pattern = f' inet {re.escape(address.split("/")[0])}/' if address else r'^\d+: (?!lo\b)\S+ +inet '
for _ in range(24):
if re.search(pattern, self.on(name, 'ip', '-4', '-o', 'addr', 'show').stdout, re.M):
break
time.sleep(5)
else:
print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr)
return False
return True
def nic_of(self, name, index):
"""The name of the instance's NIC index, counted from 0, or None when it has no such NIC."""
if index >= len(self.macs[name]):
return None
marker = f'link/ether {self.macs[name][index]} '
for line in self.on(name, 'ip', '-o', 'link', 'show').stdout.splitlines():
if marker in line:
return line.split()[1].rstrip(':').split('@')[0]
return None
def address(self, name):
"""The IPv4 interface address of the instance's first NIC: the static one, else the one it holds."""
if self.addresses.get(name):
return ipaddress.IPv4Interface(self.addresses[name])
nic = self.nic_of(name, 0)
match = re.search(r' inet (\S+) ', self.on(name, 'ip', '-4', '-o', 'addr', 'show', 'dev', nic).stdout) \
if nic else None
if not match:
raise RuntimeError(f'{name} has no IPv4 address on its first NIC')
return ipaddress.IPv4Interface(match.group(1))
def client(self, name):
"""Install the tools of a VPN client; True when they are installed."""
return (self.on(name, 'apt-get', 'update', '-q').returncode == 0 and
self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', '-q',
'wireguard-tools', 'openvpn', 'curl').returncode == 0)
def setup_run(self, name):
"""Run linux-manager-setup and wait for it; True when it succeeded."""
return self.on(name, 'systemctl', 'restart', 'linux-manager-setup').returncode == 0
def server(self, name, config):
"""Install the package with the test administrator, then apply the configuration; True when both succeeded."""
if not self.push(self.deb, name, '/tmp/linux-manager.deb'):
return False
preseed = (f'linux-manager linux-manager/admin_username string admin\n'
f'linux-manager linux-manager/admin_password password {self.admin_password}\n')
if self.on(name, 'debconf-set-selections', input=preseed).returncode != 0:
return False
result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y',
'/tmp/linux-manager.deb')
(TMP / f'{name}-install.log').write_text(result.stdout + result.stderr, encoding='utf-8')
return result.returncode == 0 and self.configure(name, config)
def render(self, name, config):
"""Replace the server's configuration, with its placeholders filled in.
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the
network of its first address.
"""
text = (HERE / 'configs' / config).read_text(encoding='utf-8').replace('@PSK@', self.psk)
for index in (0, 1):
placeholder = f'@ETH{index}@'
if placeholder in text:
nic = self.nic_of(name, index)
if nic is None:
raise RuntimeError(f'{name} has no NIC {index} for {placeholder} of {config}')
text = text.replace(placeholder, nic)
if '@CIDR0@' in text:
text = text.replace('@CIDR0@', str(self.address(name).network))
return self.push_text(text, name, '/etc/linux-manager/linux-manager.json', '0600')
def configure(self, name, config):
"""Render the configuration and apply it twice, as the server's certificates follow the first run."""
return self.render(name, config) and self.setup_run(name) and self.setup_run(name)
def echo_server(self, name):
"""Answer HTTP on port 8080 of the instance with the address of the client."""
return (self.push(HERE / 'echo.py', name, '/root/echo.py') and
self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0)
def vpn_user(self, name):
"""Add the VPN user alice, whose password is the administrator's; True when it was added."""
return self.on(name, 'linux-manager-user', '--json', 'add', 'alice', '--first-name', 'Alice',
'--last-name', 'Test', '--email', 'alice@example.org',
input=self.admin_password + '\n').returncode == 0
def alice(self, name):
"""User alice from the server's user list, or None."""
listing = self.json_of(name, 'linux-manager-user', '--json', 'list') or {}
return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None)
def wireguard_client(self, client, server, endpoint, address, allowed):
"""Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only."""
private_key = self.on(client, 'wg', 'genkey').stdout.strip()
public_key = self.on(client, 'wg', 'pubkey', input=private_key + '\n').stdout.strip()
if not private_key or not public_key:
return False
if not self.push(HERE / 'wireguard_peer.py', server, '/root/wireguard_peer.py'):
return False
if self.on(server, 'python3', '/root/wireguard_peer.py', public_key, address).returncode != 0:
return False
if not self.setup_run(server):
return False
server_key = self.on(server, 'cat', '/etc/wireguard/wg0.pub').stdout.strip()
conf = (f'[Interface]\nPrivateKey = {private_key}\nAddress = {address}/32\n\n'
f'[Peer]\nPublicKey = {server_key}\nEndpoint = {endpoint}:51820\nAllowedIPs = {allowed}\n')
return (self.push_text(conf, client, '/etc/wireguard/wg0.conf', '0600') and
self.on(client, 'bash', '/usr/bin/wg-quick', 'up', 'wg0').returncode == 0)
def wireguard_module(self, name):
"""True when the instance can create a WireGuard link, that is the host kernel has the module."""
if self.on(name, 'ip', 'link', 'add', 'lm-probe', 'type', 'wireguard').returncode != 0:
return False
self.on(name, 'ip', 'link', 'delete', 'lm-probe')
return True
def cleanup(self):
"""Delete the project's instances, the networks and the project, or with keep say what is left."""
if self.keep:
print(f'--keep: project {self.project} and networks {" ".join(self.networks)} are left on {self.remote}')
return
listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False)
for name in listing.stdout.split():
self.lxc('delete', '--force', f'{self.remote}:{name}', check=False)
for name in self.networks:
subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True)
self.networks = []
subprocess.run(['lxc', 'project', 'delete', f'{self.remote}:{self.project}'], capture_output=True)
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('scenarios', nargs='+', metavar='scenario', help=f'{", ".join(SCENARIOS)} or all')
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 (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', 'lm-test'),
help='the project the instances live in (LXD_PROJECT, default lm-test)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of every instance (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--keep', action='store_true', help='leave the project and the networks in place')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
if not args.pool:
parser.error('--pool or LXD_POOL is required')
scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios
unknown = [name for name in scenarios if name not in SCENARIOS]
if unknown:
parser.error(f'no scenario {", ".join(unknown)}')
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb'))
if not debs:
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first')
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 or choose another with --project')
TMP.mkdir(parents=True, exist_ok=True)
lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, debs[-1],
secrets.token_hex(16), secrets.token_hex(24))
env = ROOT / 'tmp' / 'remote-test.env'
env.touch(mode=0o600)
env.chmod(0o600)
env.write_text(f'ADMIN_USERNAME=admin\nADMIN_PASSWORD={lab.admin_password}\nPSK={lab.psk}\n', encoding='utf-8')
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
sys.path.insert(0, str(HERE))
try:
for name in scenarios:
subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool,
'-c', 'features.images=false'], capture_output=True, check=True)
print(f'== {name}')
try:
importlib.import_module(f'scenarios.{name}').run(lab)
except (subprocess.CalledProcessError, RuntimeError) as error:
detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error)
lab.result(f'{name}: scenario ran to its end ({detail})', False)
finally:
lab.cleanup()
except KeyboardInterrupt:
sys.exit(130)
print(f'== passed {lab.passed}, failed {lab.failed}, skipped {lab.skipped}')
print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and passkeys,")
print('PowerDNS answering from outside, the Azure and GCP platform modules.')
sys.exit(1 if lab.failed else 0)
if __name__ == '__main__':
main()
-220
View File
@@ -1,220 +0,0 @@
#!/usr/bin/env python3
"""Launch one Linux Manager server VM on an LXD remote to work with, or remove it: vm.py [--remove].
The VM is launched on the remote (--remote or LXD_REMOTE) in --project with that project's
default profile. It gets the newest out/linux-manager_*_all.deb with the administrator admin and
a generated password; in a test project made by lxd-project.py, which tmp/lxd-project-PROJECT.json
describes, it gets the package instead from that project's repository, as its apt source, so later
dev builds reach it as updates. It also gets a configuration from configs/ (core.json by
default), whose @ETH0@ is the interface of the VM's default route, @CIDR0@ its network and @PSK@
a generated key. The password and the key are written to tmp/vm-NAME.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 (or LXD_LISTEN, by default the IPv4 address of the host of the
remote's URL). --remove deletes the VM, its forward and that file.
"""
import argparse
import ipaddress
import json
import os
import pathlib
import re
import secrets
import socket
import subprocess
import sys
import time
import urllib.parse
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent.parent
# The host port and the VM port of each proxy: the Manager, the status web service and SSH.
PROXIES = ((7080, 7080), (7081, 7081), (2222, 22))
def inside(args, *command, input=None):
"""Run the command in the VM with the input, and return its CompletedProcess."""
return subprocess.run(['lxc', 'exec', f'{args.remote}:{args.name}', '--project', args.project, '-T', '--',
*command], input=input, capture_output=True, text=True)
def push(args, source, path, mode):
"""Copy the local file into the VM at the path with the mode; True when it was copied."""
return subprocess.run(['lxc', 'file', 'push', str(source), f'{args.remote}:{args.name}{path}',
'--project', args.project, '--mode', mode], capture_output=True).returncode == 0
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default='default', help='the project of the VM (default default)')
parser.add_argument('--name', 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 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)')
parser.add_argument('--remove', action='store_true', help='delete the VM and its env file')
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 not args.remove 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.name} (project {args.project})'
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.name}', '--project', args.project],
capture_output=True).returncode == 0
env = ROOT / 'tmp' / f'vm-{args.name}.env'
# 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.name), None)
if args.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.name}', '--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 --name')
config = HERE / 'configs' / args.config
if not config.is_file():
parser.error(f'no 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'ADMIN_USERNAME=admin\nADMIN_PASSWORD={password}\nPSK={psk}\n', encoding='utf-8')
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.name}', '--vm', '-c', 'limits.cpu=2',
'-c', 'limits.memory=4GiB',
'-c', 'cloud-init.user-data=' + (HERE / '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(args, 'cloud-init', 'status', '--wait').returncode in (0, 2):
break
time.sleep(5)
else:
sys.exit(f'{args.name} did not boot; remove it with --remove')
for _ in range(24):
route = re.search(r'\bdev (\S+)', inside(args, 'ip', '-4', '-o', 'route', 'show', 'default').stdout)
address = route and re.search(r' inet (\S+) ',
inside(args, 'ip', '-4', '-o', 'addr', 'show', 'dev', route.group(1)).stdout)
if address:
break
time.sleep(5)
else:
sys.exit(f'{args.name} 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(args, 'cat', f'/sys/class/net/{nic}/address').stdout.strip()
expanded = subprocess.run(['lxc', 'config', 'show', '--expanded', f'{args.remote}:{args.name}',
'--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.name} has the MAC address {mac} of {nic}')
subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.name}', 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.name}',
'--project', args.project], check=True)
args.listen = forward_of_vm()
if not args.listen:
sys.exit(f'no forward of {args.name} on {wan}; remove the VM with --remove')
for host_port, vm_port in PROXIES:
subprocess.run(['lxc', 'network', 'forward', 'port', 'add', wan, args.listen, 'tcp', str(host_port),
str(interface.ip), str(vm_port), '--project', args.project], check=True)
else:
for host_port, vm_port in PROXIES:
subprocess.run(['lxc', 'config', 'device', 'add', f'{args.remote}:{args.name}', f'proxy-{vm_port}',
'proxy', f'listen=tcp:{args.listen}:{host_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(args, 'mkdir', '-p', '/etc/apt/keyrings').returncode != 0 or
not push(args, project['key'], '/etc/apt/keyrings/linux-manager-test.gpg', '0644') or
inside(args, '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.name}')
updated = inside(args, 'apt-get', 'update')
if updated.returncode != 0:
sys.exit(f'apt-get update failed in {args.name}: {updated.stderr.strip()}')
package = 'linux-manager'
else:
if not push(args, debs[-1], '/tmp/linux-manager.deb', '0644'):
sys.exit(f'could not copy {debs[-1].name} into {args.name}')
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(args, 'debconf-set-selections', input=preseed).returncode != 0:
sys.exit('debconf-set-selections failed')
result = inside(args, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package)
log = ROOT / 'tmp' / f'vm-{args.name}-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.name}.json'
rendered.touch(mode=0o600)
rendered.chmod(0o600)
rendered.write_text(text, encoding='utf-8')
pushed = push(args, rendered, '/etc/linux-manager/linux-manager.json', '0600')
rendered.unlink()
if not pushed:
sys.exit(f'could not copy {args.config} into {args.name}')
for _ in range(2):
if inside(args, '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.name} is up at {interface.ip} with {args.config}')
print(f'administrator: admin password: {password} (also in {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.name} --project {args.project} -- su -l')
print(f'remove: {sys.argv[0]} --remote {args.remote} --project {args.project} --name {args.name} --remove')
if __name__ == '__main__':
main()