liab-deployments/liab_deployments/deploy/dumpthings.py

324 lines
11 KiB
Python

"""
# Deploy one or more rootless Podman-based dumpthings services.
Deploy one or more `dump-things-service` instances as per-user systemd
services, optionally exposing them through Caddy.
Each site receives its own application data directory, admin credential,
systemd service, listening port, and optional Caddy configuration. The
application is installed as a `uv` tool for the configured Unix user.
## Setup
Configure the deployment under the host's `dumpthings` inventory key:
- `defaults` contains values inherited by every site
- `sites` contains the site-specific configuration
- values in an individual site override values from `defaults`
- each site is installed and managed as a user-mode systemd service
- the application listens on `127.0.0.1`; external access is expected to
be provided by Caddy or another reverse proxy
The deployment expects the admin token to be supplied through a controller-side
environment variable. The token is written to the target user's credential
file and loaded into the service through systemd's credential mechanism.
## Constraints and environmental assumptions
- Git is installed on the target host because it is a deployment dependency.
- Every site has a unique `name` on the host.
- Every site has a unique `host_port` on the host.
- Site names should be stable, systemd-safe identifiers. They should not
contain whitespace, shell metacharacters, newlines, or characters that
are invalid in systemd service names.
- `user_spec` identifies an existing or deployable Unix user. Its normal
form is `(username, uid, home_directory)`.
- The deployment assumes that sites sharing one Unix user use compatible
application and Python versions. Different application versions for sites
using the same user are not supported unless the `uv` installation is
explicitly isolated per site.
- `data_dir` defaults to `<user_home>/data` when omitted.
- The application data directory is created with mode `0700` and is owned by
the configured Unix user.
- `dumpthings_args` is a sequence of individual command-line arguments.
- `host_port` is the local port used by the application and must be available
on the target host.
- The application binds only to `127.0.0.1`, the application port is not
intended to be directly internet-facing.
- If `caddyfile_block` is provided, the configuration section is included
in the Caddyfile and caddy is reloaded as needed. A site with
`caddyfile_block=None` is suitable for a deployment embedded in
another site or for a service that is intentionally not exposed by Caddy.
- `admin_token_env` names an environment variable available to the pyinfra
controller or deployment process. Its value must be present when the
credential operation runs.
- Secrets must not be committed to the inventory. Only the name of the
environment variable containing the secret should be stored there.
- `dumpthings_version=None` installs or updates the latest available version
according to the uv operation. Pin the version in production when
reproducible deployments are required.
- `uvtool_extraargs` is passed to `uv tool` and can be used to set things
like Python version or inject additional packages into the tool's
environment.
An example inventory may look like this:
```python
group = [
(
'myhost',
{
'dumpthings': {
'defaults': {
# Do not add a Caddy configuration block for sites unless
# a site overrides this value with its own block.
'caddyfile_block': None,
# Common command-line arguments inherited by every site.
# None means that each site supplies its own arguments, or
# that the service is started without extra arguments.
'dumpthings_args': None,
# Python interpreter used to install and run the uv tool.
'uvtool_extraargs': ['--python', '3.14'],
# Application version inherited by every site.
# None requests the latest version supported by the uv
# installation; pin this for reproducible production runs.
'dumpthings_version': None,
},
'sites': [
{
# Stable identifier for the site and its user-mode
# systemd service. Keep this unique on the host and use
# a systemd-safe value.
'name': 'myservice-dumpthings',
# User identity and home directory used for the uv tool,
# systemd service, credential file, and default data
# directory. The expanded form is:
# (username, uid, home_directory).
'user_spec': (
'myservice-dumpthings',
2002,
'/data/dumpthings',
),
# Local TCP port on which the service listens. This
# deployment binds the service to 127.0.0.1.
'host_port': 30002,
# Name of the controller-side environment variable
# containing the admin token. The token itself must not
# be stored in this inventory.
'admin_token_env': (
'MYSERVICE_DUMPTHINGS_ADMIN_TOKEN'
),
# Individual application arguments. These are passed
# as arguments rather than as a shell fragment.
'dumpthings_args': [
'--root-path',
'/api/dumpthings/v1',
],
},
],
},
},
),
]
```
"""
from collections.abc import Sequence
from pyinfra.api import deploy as pyinfra_deploy
from pyinfra import (
host,
)
from pyinfra.operations import (
files,
systemd,
uv,
)
from shlex import quote as shlex_quote
from liab_deployments.deploy import (
all_sites,
check_dependencies,
check_no_duplicates,
get_user_info,
)
from liab_deployments.operations import (
caddy,
network,
user,
user_systemd,
uv as liab_uv,
)
service_unit_tmpl = """\
[Unit]
Description={name} service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
WorkingDirectory={user_home}
LoadCredential=admin_token:{user_home}/.admin_token
ExecStart=/bin/bash -c '\\
set -eu; \\
export PATH={user_home}/.local/bin:$PATH; \\
export DTS_ADMIN_TOKEN="$$(cat "$${{CREDENTIALS_DIRECTORY}}/admin_token")"; \\
exec dump-things-service \\
--host 127.0.0.1 \\
--port {host_port} \\
{dumpthings_args} \\
{data_dir} \\
'
[Install]
WantedBy=default.target
"""
# used for the systemd service (lower), and the caddy block marker (upper),
# and in documentation (verbatim capitalization)
deploy_name = 'Dumpthings'
service_name = deploy_name.lower()
@pyinfra_deploy(f"Deploy {deploy_name}")
def deploy():
"""
Installing multiple dumpthings sites using different versions under
the same user account is not supported.
"""
if not hasattr(host.data, service_name):
return
defaults = host.data.dumpthings.get('defaults', {})
sites = host.data.dumpthings.get('sites', [])
check_dependencies(('git',))
check_no_duplicates(all_sites(host.data.dict()), ('host_port',), context='host')
check_no_duplicates(all_sites(host.data.dict()), ('name',), context='host')
for spec in sites:
kwargs = {
# fallback values from the deployment itself
"caddyfile_block": None,
"service_unit_tmpl": service_unit_tmpl,
# override with inventory-provided site defaults
**defaults,
# override with inventory-provided site specifics
**spec,
}
_deploy_dumpthings(**kwargs)
def _deploy_dumpthings(
*,
name: str,
user_spec: tuple[str, int] | tuple[str, int, str],
host_port: int,
service_unit_tmpl: str,
caddyfile_block: str | None = None,
data_dir: str | None = None,
dumpthings_args: Sequence[str] | None = None,
#systemd_service_params: str,
dumpthings_version: str | None = None,
uvtool_extraargs: Sequence[str] | None = None,
admin_token_env: str | None = None,
):
user_name, uid, user_home = get_user_info(user_spec)
if data_dir is None:
data_dir = f'{user_home}/data'
user.systemd_service(
name=f'user {user_name}({uid})',
user_name=user_name,
user_id=uid,
user_home=user_home,
)
liab_uv.deploy_uv(
replace=True,
_sudo_user=user_name,
)
uv.tools(
tools=[
f'dump-things-service{dumpthings_version or ""}'
],
present=True,
latest=True,
extra_args=uvtool_extraargs,
_sudo_user=user_name,
_env={
# put uv in the PATH for this operations
'PATH': f'{user_home}/.local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
},
name=f'{name!r} uv tool',
)
files.directory(
path=data_dir,
present=True,
mode='0700',
user=user_name,
group=user_name,
name=f'{name!r} data directory',
)
user_systemd.credential_file(
path=f'{user_home}/.admin_token',
env_var=admin_token_env,
user=user_name,
name=f'{name!r} admin credential',
)
user_systemd.service_unit(
user_name,
user_home,
name,
service_unit_tmpl.format(
name=name,
user_home=user_home,
host_port=host_port,
#service_params=systemd_service_params or '',
dumpthings_args=' '.join(
shlex_quote(arg) for arg in dumpthings_args
) if dumpthings_args else '',
data_dir=shlex_quote(data_dir),
),
name=f'{name!r} service unit',
)
dumpthings_service = systemd.service(
name=f'Launch {name!r}',
service=name,
running=True,
restarted=True,
enabled=True,
daemon_reload=True,
user_mode=True,
user_name=user_name,
)
network.wait_host_port_active(
host_port,
name=f"Wait for {name!r} to start",
_timeout=120,
_if=dumpthings_service.did_change,
)
if caddyfile_block:
caddy.caddyfile_block(
marker=f'DUMPTHINGS {name}'.upper(),
content=caddyfile_block,
)