oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Write or check the production runner's service.env and unit, for
3scripts/cutover-finish-thin.sh and scripts/upgrade-thin.sh.
4
5 runner-config.py render <snapshot-dir> <runner-root> --exec PATH KEY=VALUE...
6 runner-config.py check <runner-root> --exec PATH KEY=VALUE...
7
8render reads the recorded snapshot (service.env, equipo-runner.service),
9never the live files, so running it again gives the same result. Each KEY
10must appear exactly once in service.env; ExecStart, RestartSec and
11EnvironmentFile (naming <runner-root>/service.env) exactly once in the
12unit. Values are restricted to plain path, origin and id characters, so
13nothing needs escaping. RestartPreventExitStatus=3 follows RestartSec.
14Both files are written to a temporary file, synced and renamed into
15place, then checked. check refuses unless the live files hold exactly
16those values.
17"""
18import os
19from pathlib import Path
20import re
21import sys
22
23SAFE = re.compile(r'[A-Za-z0-9/._:-]{1,512}')
24ENV, UNIT = 'service.env', 'equipo-runner.service'
25
26
27def fail(msg):
28 print('refused: ' + msg, file=sys.stderr)
29 sys.exit(1)
30
31
32def once(lines, prefix, where):
33 hits = [i for i, line in enumerate(lines) if line.startswith(prefix)]
34 if len(hits) != 1:
35 fail(f'{where} has {len(hits)} {prefix} lines, not one')
36 return hits[0]
37
38
39def args(argv):
40 if len(argv) < 2 or argv[0] != '--exec':
41 fail('usage: --exec PATH KEY=VALUE...')
42 exe, pairs = argv[1], argv[2:]
43 values = {}
44 for pair in pairs:
45 key, _, value = pair.partition('=')
46 if not re.fullmatch(r'EQUIPO_[A-Z_]+', key) or key in values:
47 fail('bad key ' + key)
48 values[key] = value
49 for value in [exe, *values.values()]:
50 if not SAFE.fullmatch(value):
51 fail('unexpected characters in ' + repr(value))
52 if not values:
53 fail('no keys')
54 return exe, values
55
56
57def rendered(env, unit, root, exe, values):
58 env = env.splitlines()
59 for key, value in values.items():
60 env[once(env, key + '=', ENV)] = f'{key}="{value}"'
61 unit = [line for line in unit.splitlines() if not line.startswith('RestartPreventExitStatus=')]
62 if unit[once(unit, 'EnvironmentFile=', UNIT)] != f'EnvironmentFile={root}/{ENV}':
63 fail(f'{UNIT} does not read {root}/{ENV}')
64 unit[once(unit, 'ExecStart=', UNIT)] = f'ExecStart={exe} run'
65 unit.insert(once(unit, 'RestartSec=', UNIT) + 1, 'RestartPreventExitStatus=3')
66 return '\n'.join(env) + '\n', '\n'.join(unit) + '\n'
67
68
69def write(path, text):
70 tmp = path.with_name('.' + path.name + '.new')
71 fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
72 with os.fdopen(fd, 'w') as f:
73 f.write(text)
74 f.flush()
75 os.fsync(f.fileno())
76 os.replace(tmp, path)
77 dirfd = os.open(path.parent, os.O_RDONLY)
78 try:
79 os.fsync(dirfd)
80 finally:
81 os.close(dirfd)
82
83
84def check(root, exe, values):
85 env = (root / ENV).read_text().splitlines()
86 unit = (root / UNIT).read_text().splitlines()
87 for key, value in values.items():
88 if env[once(env, key + '=', ENV)] != f'{key}="{value}"':
89 fail(f'{ENV} does not hold {key}={value}')
90 if unit[once(unit, 'ExecStart=', UNIT)] != f'ExecStart={exe} run':
91 fail(f'{UNIT} does not start {exe}')
92 if unit[once(unit, 'RestartSec=', UNIT) + 1:][:1] != ['RestartPreventExitStatus=3']:
93 fail(f'{UNIT} lacks RestartPreventExitStatus=3 after RestartSec')
94 if unit[once(unit, 'EnvironmentFile=', UNIT)] != f'EnvironmentFile={root}/{ENV}':
95 fail(f'{UNIT} does not read {root}/{ENV}')
96
97
98def main(argv):
99 if len(argv) >= 3 and argv[0] == 'render':
100 snap, root = Path(argv[1]), Path(argv[2])
101 exe, values = args(argv[3:])
102 env, unit = rendered((snap / ENV).read_text(), (snap / UNIT).read_text(), root, exe, values)
103 write(root / ENV, env)
104 write(root / UNIT, unit)
105 check(root, exe, values)
106 return 0
107 if len(argv) >= 2 and argv[0] == 'check':
108 root = Path(argv[1])
109 exe, values = args(argv[2:])
110 check(root, exe, values)
111 return 0
112 print(__doc__, file=sys.stderr)
113 return 2
114
115
116if __name__ == '__main__':
117 sys.exit(main(sys.argv[1:]))
118