CI / Lint (JS) (pull_request) Successful in 12s
CI / Lint (Python) (pull_request) Successful in 35s
CI / Test (pull_request) Successful in 59s
CI / Security (pull_request) Successful in 39s
CI / Scan (pull_request) Successful in 29s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
gandalf#55, part 2 (the server side; needs installing on CT 157). deploy/gandalf_deploy.sh <sha> <ts>, run by the gandalf-deploy webhook from its installed copy /usr/local/bin/gandalf_app_deploy.sh: - refuses a request signed more than 5 minutes ago, or one not newer than the last accepted (replay), and any sha not on origin/main; - checks out exactly that sha (detached), installs requirements.txt and restarts gandalf and gandalf-monitor; - waits for /health to report the sha for both with status ok, and rolls back to the previous commit otherwise; one deploy at a time (flock). tests/test_deploy_script.py runs the real script in a sandbox with fake systemctl, pip3 and curl: exact commit, untracked config.json kept, replay, stale, off-main and malformed requests refused, an unhealthy build rolled back, and the running commit a no-op. Co-Authored-By: Claude Opus 5.5 <[email protected]>
145 lines
5.7 KiB
Python
145 lines
5.7 KiB
Python
"""Runs deploy/gandalf_deploy.sh in a sandbox (gandalf#55 part 2).
|
|
|
|
A throwaway git origin and checkout, with fake systemctl, pip3 and curl on PATH. "Production"
|
|
health is simulated by the fake curl: it reports whatever commit the fake systemctl last
|
|
started, for both the web app and the monitor, and a commit containing a BROKEN file reports
|
|
status "degraded" (an unhealthy build). Each test builds on the state the previous one left.
|
|
"""
|
|
import os
|
|
import shutil
|
|
import subprocess # nosec B404: runs the deploy script and git in a temporary sandbox
|
|
import time
|
|
|
|
import pytest
|
|
|
|
SCRIPT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'deploy', 'gandalf_deploy.sh')
|
|
|
|
pytestmark = pytest.mark.skipif(not (shutil.which('bash') and shutil.which('git') and shutil.which('flock')),
|
|
reason='needs bash, git and flock')
|
|
|
|
|
|
def _git(cwd, *args):
|
|
return subprocess.run(['git', *args], cwd=cwd, check=True, capture_output=True, # nosec B603 B607
|
|
text=True).stdout.strip()
|
|
|
|
|
|
def _commit(repo, name, files, remove=()):
|
|
for f, content in files.items():
|
|
with open(os.path.join(repo, f), 'w') as fh:
|
|
fh.write(content)
|
|
for f in remove:
|
|
os.unlink(os.path.join(repo, f))
|
|
_git(repo, 'add', '-A')
|
|
_git(repo, '-c', 'user.name=t', '-c', '[email protected]', 'commit', '-qm', name)
|
|
return _git(repo, 'rev-parse', 'HEAD')
|
|
|
|
|
|
@pytest.fixture(scope='module')
|
|
def sandbox(tmp_path_factory):
|
|
root = str(tmp_path_factory.mktemp('gandalf-deploy'))
|
|
work, origin, app, bin_dir = (os.path.join(root, d) for d in ('work', 'origin.git', 'app', 'bin'))
|
|
os.makedirs(work)
|
|
os.makedirs(bin_dir)
|
|
_git(root, 'init', '-q', '--bare', '-b', 'main', origin)
|
|
_git(root, 'init', '-q', '-b', 'main', work)
|
|
c = {'a': _commit(work, 'a', {'app.py': 'a', 'requirements.txt': ''})}
|
|
_git(work, 'remote', 'add', 'origin', origin)
|
|
_git(work, 'push', '-q', 'origin', 'main')
|
|
_git(root, 'clone', '-q', origin, app)
|
|
with open(os.path.join(app, 'config.json'), 'w') as fh:
|
|
fh.write('{"secret": "keep-me"}') # untracked, must survive every checkout
|
|
|
|
c['b'] = _commit(work, 'b', {'app.py': 'b'})
|
|
c['broken'] = _commit(work, 'broken', {'app.py': 'c', 'BROKEN': '1'})
|
|
c['fixed'] = _commit(work, 'fixed', {'app.py': 'd'}, remove=['BROKEN'])
|
|
_git(work, 'push', '-q', 'origin', 'main')
|
|
_git(work, 'checkout', '-q', '-b', 'side', c['a'])
|
|
c['side'] = _commit(work, 'side', {'app.py': 'side'})
|
|
_git(work, 'push', '-q', 'origin', 'side')
|
|
|
|
running = os.path.join(root, 'running')
|
|
|
|
def fake(name, body):
|
|
p = os.path.join(bin_dir, name)
|
|
with open(p, 'w') as fh:
|
|
fh.write('#!/bin/bash\n' + body + '\n')
|
|
os.chmod(p, 0o755) # nosec B103: a test stub in a temporary directory
|
|
|
|
fake('pip3', 'exit 0')
|
|
fake('systemctl', f'git -C "{app}" rev-parse HEAD > "{running}"')
|
|
fake('curl', f'''s=$(cat "{running}" 2>/dev/null) || exit 7
|
|
if [ -e "{app}/BROKEN" ]; then st=degraded; else st=ok; fi
|
|
echo "{{\\"status\\":\\"$st\\",\\"sha\\":\\"$s\\",\\"monitor_sha\\":\\"$s\\"}}"''')
|
|
with open(running, 'w') as fh:
|
|
fh.write(c['a'])
|
|
|
|
env = dict(os.environ, PATH=f'{bin_dir}:{os.environ["PATH"]}',
|
|
GANDALF_DEPLOY_APP_ROOT=app, GANDALF_DEPLOY_STATE_DIR=os.path.join(root, 'state'),
|
|
GANDALF_DEPLOY_LOG=os.path.join(root, 'deploy.log'), GANDALF_DEPLOY_LOCK=os.path.join(root, 'lock'),
|
|
GANDALF_DEPLOY_HEALTH_TRIES='3', GANDALF_DEPLOY_HEALTH_SLEEP='0')
|
|
|
|
def deploy(sha, ts=None):
|
|
ts = int(time.time()) if ts is None else ts
|
|
r = subprocess.run(['bash', SCRIPT, sha, str(ts)], env=env, # nosec B603 B607
|
|
capture_output=True, text=True)
|
|
return r.returncode, r.stdout + r.stderr
|
|
|
|
def head():
|
|
return _git(app, 'rev-parse', 'HEAD')
|
|
|
|
def runs():
|
|
with open(running) as fh:
|
|
return fh.read().strip()
|
|
|
|
return {'c': c, 'deploy': deploy, 'head': head, 'running': runs, 'app': app}
|
|
|
|
|
|
def test_deploys_exactly_the_requested_commit(sandbox):
|
|
s = sandbox
|
|
code, out = s['deploy'](s['c']['b'])
|
|
assert code == 0, out
|
|
assert s['head']() == s['c']['b'] and s['running']() == s['c']['b']
|
|
with open(os.path.join(s['app'], 'config.json')) as fh:
|
|
assert fh.read() == '{"secret": "keep-me"}'
|
|
|
|
|
|
def test_a_replayed_request_is_refused(sandbox):
|
|
s = sandbox
|
|
ts = int(time.time()) + 5
|
|
assert s['deploy'](s['c']['fixed'], ts)[0] == 0
|
|
code, out = s['deploy'](s['c']['b'], ts)
|
|
assert code == 1 and 'replay or out of order' in out
|
|
assert s['head']() == s['c']['fixed']
|
|
|
|
|
|
def test_a_stale_request_is_refused(sandbox):
|
|
code, out = sandbox['deploy'](sandbox['c']['b'], int(time.time()) - 3600)
|
|
assert code == 1 and 'old (limit 300s)' in out
|
|
|
|
|
|
def test_a_commit_not_on_main_is_refused(sandbox):
|
|
s = sandbox
|
|
code, out = s['deploy'](s['c']['side'], int(time.time()) + 10)
|
|
assert code == 1 and ('is not on main' in out or 'not found after fetch' in out)
|
|
assert s['head']() == s['c']['fixed']
|
|
|
|
|
|
def test_malformed_input_is_refused(sandbox):
|
|
s = sandbox
|
|
assert 'invalid sha' in s['deploy']('abc', int(time.time()) + 11)[1]
|
|
assert 'invalid timestamp' in s['deploy'](s['c']['b'], 'x')[1]
|
|
|
|
|
|
def test_an_unhealthy_build_is_rolled_back(sandbox):
|
|
s = sandbox
|
|
code, out = s['deploy'](s['c']['broken'], int(time.time()) + 20)
|
|
assert code == 1
|
|
assert 'rolling back' in out and 'healthy' in out.split('rolled back to', 1)[1]
|
|
assert s['head']() == s['c']['fixed'] and s['running']() == s['c']['fixed']
|
|
|
|
|
|
def test_the_running_commit_is_a_no_op(sandbox):
|
|
s = sandbox
|
|
code, out = s['deploy'](s['c']['fixed'], int(time.time()) + 30)
|
|
assert code == 0 and 'nothing to do' in out
|