update: the history of the package is CHANGELOG.md, from which the build writes debian/changelog, the build, publish and development scripts are in Python, and the development tools keep their settings and credentials in .lm-dev-config.
Release / release (push) Failing after 14m43s

This commit is contained in:
slawek committed 2026-11-24 06:51:04 +01:00
1 parent a7bfabcb89
commit 6911d16fa3
26 files changed
+1966 -2105

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Read CHANGELOG.md and write debian/changelog from it: changelog.py CHANGELOG CONTROL OUTPUT [--version V].
CHANGELOG.md is the history of the package. Its entries, newest first, are "## VERSION" headings,
"## VERSION - YYYY-MM-DD HH:MM:SS +ZZZZ" once released, each followed by a summary paragraph and
"- " items whose continuation lines are indented by two spaces; an older entry may have items only.
VERSION x.y.z is the Debian version x.y.z-1, and x.y.z-n, n from 2, is x.y.z-n.
The command writes OUTPUT in Debian's format: the package name (Source) and the maintainer
(Maintainer) of the debian/control CONTROL, the summary and the items wrapped at 80 columns, and the
entry's date, the current time for an entry without one. --version replaces the Debian version of
the newest entry, as the dev builds do. A malformed CHANGELOG.md is a message on standard error and
the exit status 1.
"""
import argparse
import datetime
import email.utils
import pathlib
import re
import sys
import textwrap
#: The format of the date in a heading.
DATE_FORMAT = '%Y-%m-%d %H:%M:%S %z'
#: A heading: its version, and its date once the entry is released.
HEADING = re.compile(r'## (\d+\.\d+\.\d+(?:-\d+)?)(?: - (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}))?$')
def entries(text):
"""The entries of the CHANGELOG.md text, newest first: dicts of version, date (a datetime or None), summary (a
string or None), items (strings) and line, the index of the heading's line; ValueError when it is malformed."""
found = []
# Where the entry is: right after its heading, in its summary, after the summary, or in its items.
state = None
for index, line in enumerate(text.splitlines()):
if line.startswith('## '):
match = HEADING.match(line)
if not match:
raise ValueError(f'line {index + 1}: a heading is "## x.y.z" or "## x.y.z - {DATE_FORMAT}": {line}')
date = datetime.datetime.strptime(match.group(2), DATE_FORMAT) if match.group(2) else None
found.append({'version': match.group(1), 'date': date, 'summary': None, 'items': [], 'line': index})
state = 'heading'
elif state is None:
continue
elif not line.strip():
state = 'after' if state == 'summary' else state
elif line.startswith('- '):
found[-1]['items'].append(line[2:].strip())
state = 'items'
elif line.startswith(' ') and state == 'items':
found[-1]['items'][-1] += ' ' + line.strip()
elif state in ('heading', 'summary'):
found[-1]['summary'] = f'{found[-1]["summary"]} {line.strip()}' if state == 'summary' else line.strip()
state = 'summary'
else:
raise ValueError(f'line {index + 1}: neither a summary line, an item nor its continuation: {line}')
return found
def debian_version(version):
"""The Debian version of a CHANGELOG.md version: x.y.z-1 for x.y.z, x.y.z-n as it is."""
return version if '-' in version else f'{version}-1'
def wrapped(text, first, rest):
"""The text wrapped at 80 columns, its first line indented by first and the others by rest."""
return textwrap.fill(text, width=80, initial_indent=first, subsequent_indent=rest, break_long_words=False,
break_on_hyphens=False)
def debian(found, package, maintainer, version=None):
"""The debian/changelog of the entries, with the version as the newest entry's Debian version when given."""
blocks = []
for index, entry in enumerate(found):
number = version if index == 0 and version else debian_version(entry['version'])
date = entry['date'] or datetime.datetime.now().astimezone()
lines = [f'{package} ({number}) unstable; urgency=medium', '']
if entry['summary']:
lines += [wrapped(entry['summary'], ' ', ' '), '']
lines += [wrapped(item, ' * ', ' ') for item in entry['items']]
if entry['items']:
lines.append('')
lines.append(f' -- {maintainer} {email.utils.format_datetime(date)}')
blocks.append('\n'.join(lines) + '\n')
return '\n'.join(blocks)
def control_field(text, name):
"""The value of the field name of the source paragraph of the debian/control text."""
match = re.search(rf'^{name}:\s*(.+)$', text.split('\n\n', 1)[0], re.MULTILINE)
if not match:
raise ValueError(f'debian/control has no {name}')
return match.group(1).strip()
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('changelog', type=pathlib.Path, help='CHANGELOG.md')
parser.add_argument('control', type=pathlib.Path, help='debian/control')
parser.add_argument('output', type=pathlib.Path, help='the debian/changelog to write')
parser.add_argument('--version', help='the Debian version of the newest entry instead of its own')
args = parser.parse_args()
try:
found = entries(args.changelog.read_text(encoding='utf-8'))
control = args.control.read_text(encoding='utf-8')
if not found:
raise ValueError('no entry')
text = debian(found, control_field(control, 'Source'), control_field(control, 'Maintainer'), args.version)
except (OSError, ValueError) as error:
print(f'changelog.py: {args.changelog}: {error}', file=sys.stderr)
return 1
args.output.write_text(text, encoding='utf-8')
return 0
if __name__ == '__main__':
sys.exit(main())
+22 -20
View File
@@ -1,10 +1,11 @@
#!/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
The serial N, the setting LXD_DEV_BUILD_SERIAL (lm_dev.setting, 0 by default), is that of the last
dev build; each build that succeeds writes its own, one higher, into .lm-dev-config/settings.json,
and release.py writes 0 there when it releases. The build's version is the Debian version of the
newest entry of CHANGELOG.md (bin/changelog.py) with ~devN before its revision, 0.41.0 (0.41.0-1)
becoming 0.41.0~dev7-1, so the release of that entry is newer than all its dev builds. ./build.py 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
@@ -13,20 +14,19 @@ made by lm-dev-lxd-project.py, and published there. The remote is the project's,
import argparse
import json
import os
import re
import subprocess
import sys
from lm_dev import PROJECT, ROOT, config_path, lxc_exec
import changelog
from lm_dev import PROJECT, ROOT, config_path, lxc_exec, save_setting, setting
SERIAL = ROOT / '.dev-build.serial'
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
CHANGELOG = ROOT / 'CHANGELOG.md'
CONTROL = ROOT / 'debian-package' / 'debian' / 'control'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('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()
@@ -35,19 +35,21 @@ def main():
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}'
try:
found = changelog.entries(CHANGELOG.read_text(encoding='utf-8'))
package = changelog.control_field(CONTROL.read_text(encoding='utf-8'), 'Source')
except ValueError as error:
sys.exit(f'{CHANGELOG}: {error}')
if not found:
sys.exit(f'{CHANGELOG} has no entry')
number = int(setting('LXD_DEV_BUILD_SERIAL', 0)) + 1
upstream, _, revision = changelog.debian_version(found[0]['version']).rpartition('-')
dev = f'{upstream}~dev{number}-{revision}'
print(f'building {package} {dev}')
if subprocess.run(['./build.sh', '--build-arg', f'DEB_VERSION={dev}'], cwd=ROOT).returncode != 0:
if subprocess.run(['./build.py', '--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')
save_setting('LXD_DEV_BUILD_SERIAL', number)
# The dev build leaves out/ to out/dev/, so out/ keeps the release builds.
target = ROOT / 'out' / 'dev'
+30 -22
View File
@@ -21,17 +21,20 @@ project and those files.
import argparse
import json
import os
import re
import subprocess
import sys
import time
from lm_dev import PROJECT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, lxc_exec, vault_initialise, \
vault_state, vault_unseal
from lm_dev import PROJECT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, lxc_exec, \
setting, vault_initialise, vault_state, vault_unseal
NETWORKS = ('wan', 'lana', 'lanb')
# The settings of the options of uplink setup, which have no defaults.
UPLINK_SETTINGS = {'parent': 'LXD_UPLINK_PARENT', 'gateway': 'LXD_UPLINK_GATEWAY', 'dns': 'LXD_UPLINK_DNS',
'ovn_ranges': 'LXD_UPLINK_OVN_RANGES', 'routes': 'LXD_UPLINK_ROUTES'}
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."""
@@ -217,10 +220,11 @@ def uplink(args):
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)}')
for option, name in UPLINK_SETTINGS.items():
try:
setattr(args, option, getattr(args, option) or setting(name))
except MissingSetting as missing:
sys.exit(f'uplink setup: --{option.replace("_", "-")} or {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')
@@ -233,31 +237,33 @@ def main():
parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink'))
parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'),
help='after vault: create, unseal or remove; after uplink: setup or remove')
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool',
help='the storage pool of the project, for create (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--vault-address', default=os.environ.get('LXD_VAULT_ADDRESS'),
parser.add_argument('--vault-address', default=setting('LXD_VAULT_ADDRESS', None),
help="the listen address of the Vault's forward, one of the uplink's routes "
'(LXD_VAULT_ADDRESS); without it one is allocated')
parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'),
parser.add_argument('--uplink', default=setting('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'),
parser.add_argument('--parent',
help='uplink setup: the host bridge on the LAN (LXD_UPLINK_PARENT)')
parser.add_argument('--gateway', default=os.environ.get('LXD_UPLINK_GATEWAY'),
parser.add_argument('--gateway',
help='uplink setup: the LAN gateway as address/prefix (LXD_UPLINK_GATEWAY)')
parser.add_argument('--dns', default=os.environ.get('LXD_UPLINK_DNS'),
parser.add_argument('--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'),
parser.add_argument('--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'),
parser.add_argument('--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')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')}
if args.operation not in operations.get(args.action, (None,)):
parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else')
@@ -292,8 +298,10 @@ def main():
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')
try:
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--pool or {missing}')
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)
+2 -3
View File
@@ -7,15 +7,14 @@ lm-dev-otp-register.py or lm-dev-vm.py create enrolled.
"""
import argparse
import os
import sys
from lm_dev import PROJECT, VaultError, otp_code
from lm_dev import PROJECT, VaultError, otp_code, setting
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--user', default='admin', help='the user (default admin)')
+7 -6
View File
@@ -9,22 +9,23 @@ VM; lm-dev-otp-code.py prints the user's codes.
"""
import argparse
import os
import sys
from lm_dev import PROJECT, enrol_otp, totp_key
from lm_dev import PROJECT, MissingSetting, enrol_otp, setting, totp_key
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),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
problem = enrol_otp(args.remote, args.project, args.vm, args.user)
if problem:
sys.exit(problem)
+12 -12
View File
@@ -16,7 +16,6 @@ import argparse
import importlib
import ipaddress
import json
import os
import pathlib
import re
import secrets
@@ -24,8 +23,8 @@ import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, hand_over, \
host_address, lxc_exec, newest_deb, store_secret, vault_initialise
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, MissingSetting, VaultError, config_path, enrol_instance, hand_over, \
host_address, lxc_exec, newest_deb, setting, store_secret, vault_initialise
TMP = ROOT / 'tmp' / 'remote-test'
@@ -388,20 +387,21 @@ class Lab:
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'),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--pool',
help='the storage pool of the project (LXD_POOL)')
parser.add_argument('--project', default=os.environ.get('LXD_TEST_PROJECT', 'lm-test'),
parser.add_argument('--project', default=setting('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'),
parser.add_argument('--image', default=setting('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')
parser.add_argument('--deb', help='the package to test (default the one built last, in out/ or out/dev/)')
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')
try:
args.remote = args.remote or setting('LXD_REMOTE')
args.pool = args.pool or setting('LXD_POOL')
except MissingSetting as missing:
parser.error(f'--{missing.name.removeprefix("LXD_").lower()} or {missing}')
scenarios = SCENARIOS if args.scenarios == ['all'] else args.scenarios
unknown = [name for name in scenarios if name not in SCENARIOS]
if unknown:
@@ -409,7 +409,7 @@ def main():
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if deb is None or not deb.is_file():
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first')
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py 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')
+25 -19
View File
@@ -6,7 +6,7 @@ create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMO
made by lm-dev-lxd-project.py, which .lm-dev-config/lxd-project-PROJECT.json describes, the VM gets the package
from that project's repository, as its apt source, so later dev builds reach it as updates;
elsewhere it gets --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with a
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and a TOTP
generated password, kept as username and password in .lm-dev-config/vm-PROJECT-VM.json, and a TOTP
token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given;
lm-dev-otp-code.py prints its codes. The VM gets a configuration from tests/remote/configs/
(--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its
@@ -21,14 +21,14 @@ the same ports of the VM, and port 2222 to its SSH port. In a test project the l
network forward's on the project's WAN, --forward-address (LXD_FORWARD_ADDRESS) or else one allocated
from its uplink's routes; elsewhere NAT proxy
devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of
the remote's URL). remove deletes the VM, its forward and what the Vault keeps for it; .env is left
as it is.
the remote's URL). remove deletes the VM, its forward, its .lm-dev-config/vm-PROJECT-VM.json and what
the Vault keeps for it. The defaults of the options come from the environment, else from
.lm-dev-config/settings.json (lm_dev.setting).
"""
import argparse
import ipaddress
import json
import os
import pathlib
import re
import secrets
@@ -36,8 +36,9 @@ import subprocess
import sys
import time
from lm_dev import HANDOVER_DIR, PROJECT, ROOT, TESTS, VAULT_MOUNT, VaultError, config_path, enrol_instance, enrol_otp, \
forget_instance, hand_over, host_address, lxc_exec, newest_deb, set_dotenv, store_secret, vault_state
from lm_dev import HANDOVER_DIR, PROJECT, ROOT, TESTS, VAULT_MOUNT, MissingSetting, VaultError, config_path, \
credentials_path, enrol_instance, enrol_otp, forget_instance, hand_over, host_address, lxc_exec, newest_deb, \
setting, store_secret, vault_state, write_private
# The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH.
PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
@@ -46,26 +47,28 @@ 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),
parser.add_argument('--remote', help='the lxc remote (LXD_REMOTE)')
parser.add_argument('--project', default=setting('LXD_PROJECT', PROJECT),
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'),
help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)')
parser.add_argument('--config', default='core.json',
help='the configuration from tests/remote/configs/ (default core.json)')
parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'),
parser.add_argument('--listen', default=setting('LXD_LISTEN', None),
help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, "
"default the IPv4 address of the remote URL's host)")
parser.add_argument('--forward-address', default=os.environ.get('LXD_FORWARD_ADDRESS'),
parser.add_argument('--forward-address', default=setting('LXD_FORWARD_ADDRESS', None),
help="with create in a test project, the forward's listen address, one of the uplink's routes "
"(LXD_FORWARD_ADDRESS); without it one is allocated")
parser.add_argument('--no-otp', action='store_true', help='with create, enrol no TOTP token for admin')
parser.add_argument('--deb', help='outside a test project, the package to install (default the one built last, '
'in out/ or out/dev/)')
args = parser.parse_args()
if not args.remote:
parser.error('--remote or LXD_REMOTE is required')
try:
args.remote = args.remote or setting('LXD_REMOTE')
except MissingSetting as missing:
parser.error(f'--remote or {missing}')
project_file = config_path(f'lxd-project-{args.project}.json')
project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None
if project and project['remote'] != args.remote:
@@ -74,8 +77,10 @@ def main():
# The default listen address is the IPv4 address of the remote's host in its lxc URL.
args.listen = host_address(args.remote)
if not args.listen:
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN')
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN, in the '
'environment or .lm-dev-config/settings.json')
where = f'{args.remote}:{args.vm} (project {args.project})'
credentials = credentials_path(args.project, args.vm)
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
capture_output=True).returncode == 0
@@ -106,6 +111,7 @@ def main():
forget_instance(vault, args.vm)
except VaultError as error:
print(f'the Vault keeps what it had for {args.vm}: {error}', file=sys.stderr)
credentials.unlink(missing_ok=True)
print(f'removed {where}')
return
@@ -116,7 +122,7 @@ def main():
parser.error(f'no tests/remote/configs/{args.config}')
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
if not project and (deb is None or not deb.is_file()):
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first')
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.py first')
source = f'the repository {project["repository"]}' if project else str(deb)
vault = vault_state(args.project)
if vault is None:
@@ -124,7 +130,7 @@ def main():
'lm-dev-lxd-project.py vault create')
password, psk = secrets.token_hex(16), secrets.token_hex(24)
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password})
write_private(credentials, json.dumps({'username': 'admin', 'password': password}, indent=2) + '\n')
reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}'
print(f'launching {where} from {args.image} with {source}; reached through {reached}')
@@ -234,10 +240,10 @@ def main():
sys.exit(f'{args.vm} is up, but {problem}')
print(f'{args.vm} is up at {interface.ip} with {args.config}')
print(f'administrator: admin, password in {ROOT / ".env"} (ADMIN_PASSWORD) and the Vault ({VAULT_MOUNT}/'
f'{args.vm}/admin)')
print(f'administrator: admin, password in {credentials} and the Vault ({VAULT_MOUNT}/{args.vm}/admin)')
if not args.no_otp:
print(f'administrator TOTP codes: bin/lm-dev-otp-code.py --project {args.project} --vm {args.vm}')
print(f'administrator TOTP: otp_url in {credentials}; codes: bin/lm-dev-otp-code.py --project {args.project} '
f'--vm {args.vm}')
print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l')
print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}')
+59 -16
View File
@@ -1,5 +1,5 @@
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the .env of the repository, the
persistent state in .lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the persistent state and settings in
.lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
secrets to an instance through it, and the TOTP tokens of the users of a VM, kept in the Vault's TOTP engine.
A secret never reaches an instance as a command-line argument or on standard input. Each instance has an AppRole of
@@ -25,8 +25,10 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent
TESTS = ROOT / 'tests' / 'remote'
# The project of the manual tests, which lm-dev-lxd-project.py makes.
PROJECT = 'lm-dev'
# The state of the scripts that outlives a clean-up of tmp/: project and Vault states, keys and secrets; 0700.
# The state of the scripts that outlives a clean-up of tmp/: settings, project and Vault states, keys and secrets; 0700.
CONFIG = ROOT / '.lm-dev-config'
# The settings of the scripts, the defaults of their options: a JSON object of LXD_* names and their values.
SETTINGS = CONFIG / 'settings.json'
# The Vault: its port, the KV v2 and TOTP mounts, the lifetimes of a wrapping token and of an instance's token.
VAULT_PORT = 8200
@@ -66,15 +68,42 @@ def lxc_push(remote, project, instance, source, path, mode):
'--project', project], capture_output=True, text=True).returncode == 0
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')
class MissingSetting(Exception):
"""A setting without a default that neither the environment nor SETTINGS has; name is the setting."""
def __init__(self, name):
super().__init__(f'{name}, in the environment or {SETTINGS.relative_to(ROOT)}, is required')
self.name = name
# The default of a setting that has none.
REQUIRED = object()
def setting(name, default=REQUIRED):
"""The value of the setting name, such as LXD_REMOTE: the environment's, else that of SETTINGS, else default;
MissingSetting without a default."""
if name in os.environ:
return os.environ[name]
try:
values = json.loads(SETTINGS.read_text(encoding='utf-8'))
except FileNotFoundError:
values = {}
except ValueError as error:
raise SystemExit(f'{SETTINGS} is not JSON: {error}')
if name in values:
return values[name]
if default is REQUIRED:
raise MissingSetting(name)
return default
def save_setting(name, value):
"""Set the setting name to the value in SETTINGS, keeping its other settings."""
path = config_path(SETTINGS.name)
values = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
values[name] = value
write_private(path, json.dumps(values, indent=2) + '\n')
def newest_deb():
@@ -250,6 +279,11 @@ def hand_over(remote, project, instance, state, name, content, destination, mode
return None
def credentials_path(project, instance):
"""The file of the administrator of the VM lm-dev-vm.py made, JSON of username, password and otp_url; 0600."""
return config_path(f'vm-{project}-{instance}.json')
def totp_key(instance, user):
"""The name of the TOTP key of the user of the instance in the Vault's TOTP engine."""
return f'{instance}-{user}'
@@ -258,8 +292,9 @@ def totp_key(instance, user):
def enrol_otp(remote, project, instance, user):
"""Enrol a new TOTP token for the user of the VM, replacing one the user had; the problem, or None.
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the secret is
held by the Vault and the VM only, and the codes are read from the Vault (otp_code).
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the codes are
read from the Vault (otp_code). When the user is the administrator of the VM's credentials_path, the key's otpauth
URI, read from the VM's file before it is removed, is kept there as otp_url, to add the token to an authenticator.
"""
state = vault_state(project)
if state is None:
@@ -270,11 +305,19 @@ def enrol_otp(remote, project, instance, user):
except VaultError as error:
return f'the TOTP key {key} cannot be replaced: {error}'
target = f'{HANDOVER_DIR}/otp-url'
for command in (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
('python3', '-c', OTP_ENROL, user, target)):
credentials = credentials_path(project, instance)
known = json.loads(credentials.read_text(encoding='utf-8')) if credentials.is_file() else {}
keep = known.get('username') == user
steps = (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
*((('cat', target),) if keep else ()), ('python3', '-c', OTP_ENROL, user, target))
for command in steps:
result = lxc_exec(remote, project, instance, *command)
if result.returncode != 0:
return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}'
if command[0] == 'cat':
known['otp_url'] = result.stdout.strip()
if keep:
write_private(credentials, json.dumps(known, indent=2) + '\n')
return None