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
Release / release (push) Failing after 14m20s
This commit is contained in:
1 parent
ff0c93ed73
commit
a649331aa2
49 files changed
+1597
-637
No files matched your search
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the next numbered dev build and publish it to a test project's repository: lm-dev-build.py.
|
||||
|
||||
The serial N in .dev-build.serial of the repository is that of the last dev build; each build that
|
||||
succeeds writes its own, one higher, and release.py writes 0 when it releases. 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 (LXD_PROJECT, lm-dev by default)
|
||||
made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
|
||||
tmp/lxd-project-PROJECT.json, so the script takes no --remote.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from lm_dev import PROJECT, ROOT, lxc_exec
|
||||
|
||||
SERIAL = ROOT / '.dev-build.serial'
|
||||
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', PROJECT),
|
||||
help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, '
|
||||
f'default {PROJECT})')
|
||||
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 lm-dev-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(SERIAL.read_text(encoding='utf-8').strip()) + 1 if SERIAL.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 serial stays {number - 1}')
|
||||
SERIAL.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}')
|
||||
|
||||
pool = f'{state["remote"]}:repo/var/www/html/pool/main/{deb.name}'
|
||||
pushed = subprocess.run(['lxc', 'file', 'push', str(deb), pool, '--mode', '0644', '--project', state['project']],
|
||||
capture_output=True, text=True)
|
||||
if pushed.returncode != 0:
|
||||
sys.exit(f'could not copy {deb.name} into the repository: {pushed.stderr.strip()}')
|
||||
published = lxc_exec(state['remote'], state['project'], 'repo', 'linux-manager-repo-publish')
|
||||
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()
|
||||
Executable
+221
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create or remove an LXD project for manual tests, or its uplink: lm-dev-lxd-project.py create|remove|uplink.
|
||||
|
||||
uplink setup creates the physical uplink network once per remote, and 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;
|
||||
lm-dev-build.py publishes into it and lm-dev-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 re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec
|
||||
|
||||
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=' + (TESTS / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'),
|
||||
project=args.project)
|
||||
|
||||
def inside(*command):
|
||||
return lxc_exec(args.remote, args.project, 'repo', *command)
|
||||
|
||||
# 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.
|
||||
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')
|
||||
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='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('--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()
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py.
|
||||
|
||||
The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project
|
||||
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE), through lxc exec: inside the
|
||||
VM, as root, linuxmanager_users makes a new secret, and stores it once a code computed here 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, so otp.py code prints the user's codes.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from lm_dev import PROJECT, lxc_exec
|
||||
from otp import code_of
|
||||
|
||||
# Run in the VM as python3 -c CODE ARGUMENTS..., with the package's modules on the path.
|
||||
NEW = ("import json, sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
|
||||
"with users.session() as connection: print(json.dumps(users.otp_new(connection, sys.argv[1])))")
|
||||
ENROL = ("import sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
|
||||
"with users.session() as connection: users.otp_enrol(connection, sys.argv[1], sys.argv[2], sys.argv[3])")
|
||||
|
||||
|
||||
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=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('--user', default='admin', help='the user to enrol (default admin)')
|
||||
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
|
||||
help='the file the base32 secret is written to (OTP_FILE)')
|
||||
args = parser.parse_args()
|
||||
if not args.remote:
|
||||
parser.error('--remote or LXD_REMOTE is required')
|
||||
if not args.secret_file:
|
||||
parser.error('--secret-file or OTP_FILE is required')
|
||||
secret_file = pathlib.Path(args.secret_file)
|
||||
|
||||
def failure(result):
|
||||
return (result.stderr.strip().splitlines() or ['lxc exec failed'])[-1]
|
||||
|
||||
created = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', NEW, args.user)
|
||||
if created.returncode != 0:
|
||||
sys.exit(f'no new secret for {args.user}: {failure(created)}')
|
||||
secret = json.loads(created.stdout)['secret']
|
||||
enrolled = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', ENROL, args.user, secret, code_of(secret))
|
||||
if enrolled.returncode != 0:
|
||||
sys.exit(f'{args.user} was not enrolled: {failure(enrolled)}')
|
||||
|
||||
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
secret_file.touch(mode=0o600)
|
||||
secret_file.chmod(0o600)
|
||||
secret_file.write_text(f'{secret}\n', encoding='utf-8')
|
||||
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token; its secret is in {secret_file}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+360
@@ -0,0 +1,360 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the Linux Manager test scenarios on an LXD remote: lm-dev-run.py core|nat|s2s...|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, --project (LXD_TEST_PROJECT, lm-test by
|
||||
default), 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. The administrator's name and
|
||||
password are set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and the pre-shared
|
||||
key is written to tmp/remote-test.env. 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 re
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from lm_dev import ROOT, TESTS, lxc_exec, set_dotenv
|
||||
|
||||
TMP = ROOT / 'tmp' / 'remote-test'
|
||||
SCENARIOS = sorted(path.stem for path in (TESTS / '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 lxc_exec(self.remote, self.project, name, *command, input=input)
|
||||
|
||||
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=' + (TESTS / '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 = (TESTS / '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(TESTS / '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(TESTS / '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_TEST_PROJECT', 'lm-test'),
|
||||
help='the project the instances live in (LXD_TEST_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'PSK={lab.psk}\n', encoding='utf-8')
|
||||
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': lab.admin_password})
|
||||
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
|
||||
|
||||
sys.path.insert(0, str(TESTS))
|
||||
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()
|
||||
Executable
+219
@@ -0,0 +1,219 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""What the lm-dev scripts share: the repository's paths, lxc exec in an instance, and the .env of the repository."""
|
||||
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
# The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in.
|
||||
TESTS = ROOT / 'tests' / 'remote'
|
||||
# The project of the manual tests, which lm-dev-lxd-project.py makes.
|
||||
PROJECT = 'lm-dev'
|
||||
|
||||
|
||||
def lxc_exec(remote, project, instance, *command, input=None):
|
||||
"""Run the command in the instance as root with the input, and return its CompletedProcess."""
|
||||
return subprocess.run(['lxc', 'exec', f'{remote}:{instance}', '--project', project, '-T', '--', *command],
|
||||
input=input, capture_output=True, text=True)
|
||||
|
||||
|
||||
def set_dotenv(values):
|
||||
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines."""
|
||||
dotenv = ROOT / '.env'
|
||||
lines = dotenv.read_text(encoding='utf-8').splitlines() if dotenv.is_file() else []
|
||||
kept = [line for line in lines if line.split('=', 1)[0] not in values]
|
||||
dotenv.touch(mode=0o600)
|
||||
dotenv.chmod(0o600)
|
||||
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]),
|
||||
encoding='utf-8')
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code.
|
||||
|
||||
The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner
|
||||
only. new makes a new secret of 20 random bytes in that file, refusing to replace one without
|
||||
--force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints
|
||||
the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm
|
||||
(sha1 by default), --digits (6) and --period (30 seconds).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import pathlib
|
||||
import secrets
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
ALGORITHMS = ('sha1', 'sha256', 'sha512')
|
||||
|
||||
|
||||
def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'):
|
||||
"""The TOTP code of the base32 secret at the Unix time now, the current time by default."""
|
||||
counter = int((time.time() if now is None else now) // period)
|
||||
key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8))
|
||||
digest = hmac.new(key, struct.pack('>Q', counter), getattr(hashlib, algorithm)).digest()
|
||||
offset = digest[-1] & 0x0F
|
||||
value = struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7FFFFFFF
|
||||
return f'{value % 10 ** digits:0{digits}d}'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('action', choices=('new', 'code'))
|
||||
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
|
||||
help='the file of the base32 secret (OTP_FILE)')
|
||||
parser.add_argument('--algorithm', choices=ALGORITHMS, default='sha1', help='the HMAC hash (default sha1)')
|
||||
parser.add_argument('--digits', type=int, default=6, help='the digits of a code (default 6)')
|
||||
parser.add_argument('--period', type=int, default=30, help='the seconds a code is valid (default 30)')
|
||||
parser.add_argument('--at', type=float, help='code: the Unix time of the code instead of now')
|
||||
parser.add_argument('--account', help='new: the account name in the otpauth URI')
|
||||
parser.add_argument('--issuer', help='new: the issuer in the otpauth URI')
|
||||
parser.add_argument('--force', action='store_true', help='new: replace an existing secret')
|
||||
args = parser.parse_args()
|
||||
if not args.secret_file:
|
||||
parser.error('--secret-file or OTP_FILE is required')
|
||||
if not 6 <= args.digits <= 10 or args.period < 1:
|
||||
parser.error('--digits must be 6 to 10 and --period at least 1')
|
||||
secret_file = pathlib.Path(args.secret_file)
|
||||
|
||||
if args.action == 'code':
|
||||
if not secret_file.is_file():
|
||||
sys.exit(f'no {secret_file}; make a secret with new')
|
||||
print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm))
|
||||
return
|
||||
|
||||
if secret_file.exists() and not args.force:
|
||||
sys.exit(f'{secret_file} exists; give --force to replace its secret')
|
||||
secret = base64.b32encode(secrets.token_bytes(20)).decode()
|
||||
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
secret_file.touch(mode=0o600)
|
||||
secret_file.chmod(0o600)
|
||||
secret_file.write_text(f'{secret}\n', encoding='utf-8')
|
||||
label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp')
|
||||
query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period}
|
||||
if args.issuer:
|
||||
query['issuer'] = args.issuer
|
||||
print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user