PlotDirector/Tools/Deployment/development.py

164 lines
8.0 KiB
Python

#!/usr/bin/env python3
"""Atlas-only activation profile. Production entry point/configuration is never used."""
import grp
import os
from pathlib import Path
import pwd
import signal
import shlex
import socket
import subprocess
import sys
import activate as core
from release import load, keys, require, safe_name, canonical
CONFIG = Path('/etc/plotdirector-development/target.json')
ROOT = '/opt/plotdirector-dev'
PERSISTENCE_ENV = {
'DataProtection__KeysPath=/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys',
'DataProtection__ApplicationName=/srv/apps/plotdirector-dev/current/',
}
FIXED = {
'format': 1, 'host': 'atlas', 'environment': 'Development',
'database': 'PlotDirector_Development', 'root': ROOT,
'inbox': '/var/lib/plotdirector-dev-deployment/incoming',
'evidence': ROOT + '/deployment-evidence', 'backup': '/sql/mssql/backup',
'database_backup_directory': '/var/opt/mssql/backup',
'service': 'plotdirector-dev.service', 'runtime_account': 'plotdirector',
'migration_account': 'plotdirector-dev-migrate',
'deployment_group': 'plotdirector-dev-deploy',
'worker': '/usr/local/lib/plotdirector-dev-deployment/database/DatabaseWorker.dll',
'database_config': '/etc/plotdirector-development/database.json',
'public_key': '/etc/plotdirector-development/release-signing-public.pem',
'runtime_config': '/etc/plotdirector/plotdirector.env',
'health_base': 'http://127.0.0.1:5050', 'health_host': 'dev.plotdirector.com',
'minimum_free_bytes': 2147483648,
}
def validate_target(cfg):
keys(cfg, FIXED)
require(cfg == FIXED and socket.gethostname() == 'atlas', 'Wrong Development target')
class DevelopmentWorker(core.Worker):
def __init__(self, cfg):
validate_target(cfg)
core.protected(cfg['database_config'], secret=True)
data = load(cfg['database_config'])
require(data['database'] == 'PlotDirector_Development' and
data['expected_server'] == '192.168.10.10,1433' and
data['expected_host'] == 'atlas', 'Wrong Development SQL target')
user = pwd.getpwnam(cfg['migration_account'])
self.process = subprocess.Popen(['/usr/bin/dotnet', cfg['worker'], cfg['database_config']],
env=core.SAFE_ENV, cwd='/', user=user.pw_uid, group=user.pw_gid, extra_groups=[],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
self.last_error = None
self.read()
class Development:
worker = DevelopmentWorker
skip_unchanged_migrations = True
def configuration(self):
require(os.geteuid() == 0, 'Restricted sudo invocation required')
core.protected(CONFIG, secret=True)
cfg = load(CONFIG)
validate_target(cfg)
for name in ('root', 'evidence'):
core.protected(cfg[name], directory=True)
core.protected(Path(cfg['inbox']).parent, directory=True)
for name in ('releases', 'shared', 'deployment-receipts'):
core.protected(Path(ROOT) / name, directory=True)
for name in ('public_key', 'database_config', 'runtime_config', 'worker'):
core.protected(cfg[name], secret=name.endswith('config'))
for entry in Path(cfg['worker']).parent.rglob('*'):
core.protected(entry, directory=entry.is_dir())
require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'User', '--value']) == cfg['runtime_account'], 'Development service user mismatch')
require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'WorkingDirectory', '--value']) == ROOT + '/current', 'Development service directory mismatch')
executable = core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ExecStart', '--value'])
require('path=/usr/bin/dotnet ;' in executable and 'argv[]=/usr/bin/dotnet ' + ROOT + '/current/PlotLine.dll' in executable, 'Development executable mismatch')
require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'EnvironmentFiles', '--value']).split()[0] == cfg['runtime_config'], 'Development environment mismatch')
environment = core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'Environment', '--value'])
require(PERSISTENCE_ENV <= set(shlex.split(environment)), 'Development data-protection identity must remain stable')
return cfg
def install(self, payload, destination, runtime_group):
core.install(payload, destination, runtime_group)
app = destination / 'app'
shared = Path(ROOT) / 'shared'
bindings = load(shared / 'bindings.json')
require(set(bindings) == {'App_Data', 'wwwroot/uploads', 'uploads', 'logs', 'Logs'}, 'Invalid persistent bindings')
for name, target in bindings.items():
require(target.startswith('/srv/apps/plotdirector-dev/') or target == str(shared / name), 'Persistent path outside Development')
location = app / name
require(not location.exists() and not location.is_symlink(), 'Persistent path in package')
location.parent.mkdir(parents=True, exist_ok=True)
location.symlink_to(target, target_is_directory=True)
for config in sorted((shared / 'config').glob('appsettings*.json')):
core.protected(config, secret=True)
(app / config.name).symlink_to(config)
def main():
os.umask(0o077)
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(core.Refused('Development deployment timeout')))
signal.alarm(7200)
args = sys.argv[1:]
if args == ['--status']:
Development().configuration()
import fcntl
from release import file_digest
lock = os.open(Path(ROOT)/'deployment.lock',os.O_RDWR|os.O_NOFOLLOW)
worker = None
try:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
marker = load(Path(ROOT)/'active-deployment.json')
active = (Path(ROOT)/'current').resolve().parent
manifest = load(active/'manifest.json')
require(file_digest(active/'app/PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Active binary mismatch')
worker = DevelopmentWorker(FIXED)
print(canonical({'source_commit':manifest['source_commit'],'release_id':manifest['release_id'],
'last_successful_activation':marker,'database':worker.call('inspect'),
'service_state':core.command(['/usr/bin/systemctl','show',FIXED['service'],'-p','ActiveState','--value'])}).decode(),end='')
finally:
if worker: worker.close()
os.close(lock)
return
if len(args) == 2 and args[0] == '--receipt':
require(os.geteuid() == 0, 'Restricted sudo invocation required')
identifier = safe_name(args[1])
target = Path(ROOT) / 'deployment-receipts' / (identifier + '.json')
core.protected(target, secret=True)
print(canonical(load(target)).decode(), end='')
return
if len(args) == 2 and args[0] == '--qualify':
from development_qualification import qualify
qualify(args[1])
return
require(len(args) == 2 and args[0] in ('--validate', '--activate', '--rollback'),
'Usage: deploy-plotdirector-development --validate|--activate|--rollback <release-id>')
import retention
retention.preflight()
core.activate(args[1], validate=args[0] == '--validate', rollback=args[0] == '--rollback', profile=Development())
if args[0] != '--validate':
from development_qualification import sync_baseline
sync_baseline()
# Activation has completed and released its lock. Housekeeping reacquires the
# same lock and rechecks current; a competing deployment causes a safe skip.
try:
retention.run(apply=True)
except Exception as error:
print('WARNING Development retention skipped/failed: ' + type(error).__name__)
if __name__ == '__main__':
try:
main()
except Exception as error:
print('DEVELOPMENT DEPLOYMENT REFUSED: ' + core.public_error(error))
sys.exit(1)