133 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""One-time Atlas provisioning, using the last verified Development package. Never contacts Production."""
import argparse
import grp
import json
import os
from pathlib import Path
import pwd
import shutil
import subprocess
import sys
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import activate as core
import development as dev
from release import require, load, verify_bundle, canonical, file_digest
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('deployment-user', 'database-config', 'worker', 'previous-package', 'previous-public-key', 'public-key'):
parser.add_argument('--'+name, required=True)
args = parser.parse_args()
require(os.geteuid() == 0 and __import__('socket').gethostname() == 'atlas', 'Atlas administrator required')
os.umask(0o077)
require(not dev.CONFIG.exists() and not Path(dev.ROOT).exists(), 'Already provisioned; refuses overwrite')
db = load(args.database_config)
require(db['database'] == 'PlotDirector_Development' and db['expected_server'] == '192.168.10.10,1433' and db['expected_host'] == 'atlas', 'Wrong Development database')
operator = pwd.getpwnam(args.deployment_user)
require(operator.pw_uid != 0, 'Non-root deployment user required')
for group in ('plotdirector-dev-deploy', 'plotdirector-dev-migrate'):
if not any(g.gr_name == group for g in grp.getgrall()):
subprocess.run(['/usr/sbin/groupadd', '--system', group], check=True)
if not any(p.pw_name == 'plotdirector-dev-migrate' for p in pwd.getpwall()):
subprocess.run(['/usr/sbin/useradd', '--system', '--gid', 'plotdirector-dev-migrate', '--no-create-home', '--shell', '/usr/sbin/nologin', 'plotdirector-dev-migrate'], check=True)
subprocess.run(['/usr/sbin/usermod', '-aG', 'plotdirector-dev-deploy', args.deployment_user], check=True)
deploy_gid = grp.getgrnam('plotdirector-dev-deploy').gr_gid
migrate_gid = grp.getgrnam('plotdirector-dev-migrate').gr_gid
runtime_gid = grp.getgrnam('plotdirector').gr_gid
def directory(path, group=0, mode=0o750):
path = Path(path);path.mkdir(parents=True, exist_ok=True)
os.chown(path, 0, group);path.chmod(mode)
return path
def write(path, data, group=0, mode=0o640):
path = Path(path);path.write_bytes(data);os.chown(path, 0, group);path.chmod(mode)
directory('/etc/plotdirector-development', mode=0o755)
write(dev.CONFIG, canonical(dev.FIXED), mode=0o600)
write(dev.FIXED['database_config'], canonical(db), migrate_gid)
write(dev.FIXED['public_key'], Path(args.public_key).read_bytes(), mode=0o644)
lib = directory('/usr/local/lib/plotdirector-dev-deployment', mode=0o755)
tools = Path(__file__).resolve().parents[1]
for name in ('activate.py', 'release.py', 'receipt.py', 'transport.py', 'development.py'):
write(lib/name, (tools/name).read_bytes(), mode=0o644)
worker = directory(lib/'database', mode=0o755)
for source in Path(args.worker).rglob('*'):
require(not source.is_symlink(), 'Worker symlink refused')
target = worker/source.relative_to(args.worker)
if source.is_dir():directory(target, mode=0o755)
else:write(target, source.read_bytes(), mode=0o644)
write('/usr/local/sbin/deploy-plotdirector-development', (tools/'deploy-plotdirector-development').read_bytes(), mode=0o755)
rule = b'%plotdirector-dev-deploy ALL=(root) NOPASSWD: /usr/local/sbin/deploy-plotdirector-development *\n'
staged = Path('/etc/sudoers.d/.plotdirector-development.pending')
write(staged, rule, mode=0o440)
subprocess.run(['/usr/sbin/visudo', '-cf', str(staged)], check=True, stdout=subprocess.DEVNULL)
staged.rename('/etc/sudoers.d/plotdirector-development')
root = directory(dev.ROOT, runtime_gid, 0o751)
directory(root/'releases', runtime_gid)
directory(root/'deployment-evidence')
directory(root/'deployment-receipts', deploy_gid)
write(root/'deployment.lock', b'', mode=0o600)
state = directory('/var/lib/plotdirector-dev-deployment', deploy_gid, 0o751)
directory(state/'incoming', deploy_gid, 0o2770)
shared = directory(root/'shared', runtime_gid)
config = directory(shared/'config', runtime_gid)
old = Path('/srv/apps/plotdirector-dev/current')
require(old.is_dir() and not old.is_symlink(), 'Unexpected legacy Development layout')
for source in old.glob('appsettings*.json'):
write(config/source.name, source.read_bytes(), runtime_gid)
require(list(config.glob('appsettings*.json')), 'Development application configuration missing')
bindings = {}
for name in ('App_Data', 'wwwroot/uploads', 'uploads', 'logs', 'Logs'):
source = old/name
if source.is_dir():bindings[name] = str(source.resolve())
else:
path = shared/name
path.mkdir(parents=True, exist_ok=True)
os.chown(path, pwd.getpwnam('plotdirector').pw_uid, runtime_gid);path.chmod(0o750)
bindings[name] = str(path)
write(shared/'bindings.json', canonical(bindings), runtime_gid)
# Verify the previous signed Development package and its real database history
# before deriving the initial current link or any reusable admission plan.
with tempfile.TemporaryDirectory(prefix='.provision-', dir=root) as work:
os.chmod(work, 0o750);os.chown(work, 0, migrate_gid)
manifest, auth, payload = verify_bundle(args.previous_package, work, args.previous_public_key)
require(file_digest(old/'PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Previous package does not match running Development')
for entry in (payload, *payload.rglob('*')):
os.chown(entry, 0, migrate_gid);entry.chmod(0o750 if entry.is_dir() else 0o640)
session = dev.DevelopmentWorker(dev.FIXED)
try:
begin = session.call('begin', package_root=str(payload), deployment_id='dev-provision-validation', package_sha256=auth['package_sha256'])
require(begin['complete'], 'Incomplete Development history')
previous = begin['history']['latest_successful_release']
require(previous['source_commit'] == manifest['source_commit'], 'Previous Development release identity mismatch')
destination = root/'releases'/manifest['release_id']
dev.Development().install(payload, destination, 'plotdirector')
core.switch(root, destination/'app', 'provision')
write(root/'active-deployment.json', canonical({'deployment': previous['deployment_identifier'], 'release': manifest['release_id'], 'package_sha256':auth['package_sha256']}))
baseline = directory(state/'baseline', deploy_gid)
# The package was verified above. Copy only immutable reviewed plan data.
for area in ('sql', 'evidence'):
target = baseline/area
shutil.copytree(payload/area, target)
write(baseline/'manifest.json', (payload/'manifest.json').read_bytes(), deploy_gid)
for entry in baseline.rglob('*'):
os.chown(entry, 0, deploy_gid);entry.chmod(0o750 if entry.is_dir() else 0o640)
finally:session.close()
# Reload changes the configured target, but does not restart the running app.
directory('/etc/systemd/system/plotdirector-dev.service.d', mode=0o755)
write('/etc/systemd/system/plotdirector-dev.service.d/manifest-target.conf',
('[Service]\nWorkingDirectory='+dev.ROOT+'/current\nExecStart=\nExecStart=/usr/bin/dotnet '+dev.ROOT+'/current/PlotLine.dll\n'+''.join('Environment='+value+'\n' for value in sorted(dev.PERSISTENCE_ENV))).encode(), mode=0o644)
subprocess.run(['/usr/bin/systemctl', 'daemon-reload'], check=True)
print('Development profile provisioned; running service untouched. Validate and activate a signed Development release next.')
if __name__ == '__main__':
try:main()
except Exception as error:
print('Development provisioning refused: '+core.public_error(error));sys.exit(1)