liab-deployments/liab_deployments/deploy/hedgedoc.py

160 lines
3.6 KiB
Python

# Example host configuration
#
# 'hedgedoc': {
# "sites": [
# {
# #'name': 'hedgedoc',
# 'serve_address': 'hedgedoc.psychoinformatics.de',
# 'container_tag': 'quay.io/hedgedoc/hedgedoc:alpine',
# 'config_file': 'assets/hedgedoc-psychoinformatics-config.json',
# 'user': ('hedgedoc', 1006),
# 'host_port': 30000,
# },
# ],
# },
from pyinfra.api import deploy
from pyinfra import (
host,
)
from pyinfra.operations import (
files,
server,
)
from liab_deployments.operations import (
caddy,
user,
user_systemd,
)
service_unit_tmpl = """\
[Unit]
Description=Podman-managed hedgedoc service
Wants=network-online.target
After=network-online.target
RequiresMountsFor=%t/containers
[Service]
Environment=PODMAN_SYSTEMD_UNIT=%n
Restart=always
TimeoutStopSec=300
ExecStartPre=/bin/rm \\
-f %t/%n.ctr-id
ExecStart=/usr/bin/podman container run \\
--cidfile=%t/%n.ctr-id \\
--cgroups=no-conmon \\
--rm \\
--sdnotify=conmon \\
-d \\
--replace \\
--pull always \\
--name hedgedoc \\
--userns=keep-id \\
-e CMD_CONFIG_FILE=/config/config.json \\
-p {host_port}:3000 \\
-v {user_home}/db:/db:U \\
-v {user_home}/config:/config:ro \\
{container_tag}
ExecStop=/usr/bin/podman stop \\
--ignore -t 10 \\
--cidfile=%t/%n.ctr-id
ExecStopPost=/usr/bin/podman rm \\
-f \\
--ignore -t 10 \\
--cidfile=%t/%n.ctr-id
Type=notify
NotifyAccess=all
[Install]
WantedBy=default.target
"""
caddyfile_block_tmpl = """\
{serve_address} {{
reverse_proxy localhost:{host_port}
}}
"""
@deploy("Deploy hedgedoc")
def deploy_sites():
if not hasattr(host.data, 'hedgedoc'):
return
for spec in host.data.hedgedoc.get('sites', []):
_deploy_site(
spec['serve_address'],
spec['container_tag'],
spec['config_file'],
spec['user'],
spec['host_port'],
name=spec.get('name', 'hedgedoc'),
caddyfile_block_tmpl=spec.get(
'caddyfile_block_tmpl', caddyfile_block_tmpl
),
)
def _deploy_site(
serve_address,
container_tag,
config_file,
user_spec: tuple[str, int],
host_port,
*,
name,
caddyfile_block_tmpl,
):
user_name, uid = user_spec
user_home = f'/home/{user_name}'
user.systemd_service(
user_name,
uid,
user_home,
)
for i in ['config', 'db', 'db/img']:
files.directory(
path=f'{user_home}/{i}',
present=True,
_sudo_user=user_name,
)
user_systemd.service_unit(
user_name,
user_home,
name,
service_unit_tmpl.format(
user_home=user_home,
container_tag=container_tag,
host_port=host_port,
),
)
files.put(
name=f'Hedgedoc {serve_address!r} config',
src=config_file,
dest=f'{user_home}/config/config.json',
_sudo_user=user_name,
)
user_systemd.run_service(
user_name,
uid,
'hedgedoc',
)
server.wait(
name=f"Wait for hedgedoc {serve_address!r} to start",
port=host_port,
)
caddy.caddyfile_block(
marker=f'HEDGEDOC {serve_address}',
content=caddyfile_block_tmpl.format(
serve_address=serve_address,
host_port=host_port,
),
)