forked from unimatrix/web
68 lines
2.6 KiB
Python
68 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Retain production and two rollback releases; preserve live dependencies."""
|
|
import argparse
|
|
import fcntl
|
|
import json
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
|
|
|
|
def candidates(app):
|
|
releases = (app / 'releases').resolve(strict=True)
|
|
current = (app / 'current').resolve(strict=True)
|
|
if current.parent != releases:
|
|
raise RuntimeError('Current release is outside the release directory')
|
|
versions = [p for p in releases.iterdir()
|
|
if not p.is_symlink() and p.is_dir()
|
|
and re.fullmatch(r'ci-[0-9a-f]{40}', p.name)]
|
|
keep = {current}
|
|
keep.update(sorted((p for p in versions if p != current),
|
|
key=lambda p: p.stat().st_mtime, reverse=True)[:2])
|
|
# Explicit rollback links and shared node_modules must remain usable.
|
|
keep.update(p.resolve(strict=True) for p in app.iterdir() if p.is_symlink())
|
|
for proc in pathlib.Path('/proc').glob('[0-9]*/cwd'):
|
|
try:
|
|
location = proc.resolve(strict=True)
|
|
if location.parent == releases:
|
|
keep.add(location)
|
|
except (OSError, RuntimeError):
|
|
pass
|
|
pending = list(keep)
|
|
while pending:
|
|
directory = pending.pop()
|
|
if directory.parent != releases or not directory.is_dir():
|
|
continue
|
|
for link in directory.rglob('*'):
|
|
if not link.is_symlink():
|
|
continue
|
|
target = link.resolve(strict=True)
|
|
if target.is_relative_to(releases):
|
|
owner = releases / target.relative_to(releases).parts[0]
|
|
if owner not in keep:
|
|
keep.add(owner)
|
|
pending.append(owner)
|
|
return releases, [p for p in versions if p not in keep], keep
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--apply', action='store_true')
|
|
args = parser.parse_args()
|
|
app = pathlib.Path('/home/dunerealms/apps/dunerealms')
|
|
# Share the promoter lock: never remove a candidate during traffic switch.
|
|
with open('/var/lib/dunerealms-ci-promote/safe-lock', 'a') as lock:
|
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
releases, obsolete, keep = candidates(app)
|
|
for release in obsolete:
|
|
if release.is_symlink() or release.resolve().parent != releases:
|
|
raise RuntimeError('Unsafe deletion target')
|
|
if args.apply:
|
|
shutil.rmtree(release)
|
|
print(json.dumps({'applied': args.apply,
|
|
'obsolete': [p.name for p in obsolete],
|
|
'protected': sorted(p.name for p in keep)}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|

Staff