"""Fixed Atlas Development qualification broker. Candidate SQL never uses SA/root. Invoked only by the existing installed Development helper. The administrative connection executes fixed backup/restore/drop statements against generated names. All candidate SQL executes as the existing database migration identity on a copy. """ import fcntl import grp import json import os from pathlib import Path import pwd import re import shutil import subprocess import tempfile import uuid import activate as core from development import Development, DevelopmentWorker, FIXED, ROOT from development_plan import PLAN_FIELDS, validate_extension from release import canonical, file_digest, load, require, safe_name, snapshot STATE = Path('/var/lib/plotdirector-dev-deployment') def refresh_baseline(): """Called with the deployment lock held; only successfully recorded releases.""" marker = load(Path(ROOT)/'active-deployment.json') release = Path(ROOT)/'releases'/safe_name(marker['release']) receipt = load(Path(ROOT)/'deployment-receipts'/(safe_name(marker['deployment'])+'.json')) require(receipt['status'] == 'activated' and receipt['release']['id'] == marker['release'], 'Current release lacks successful receipt') manifest = load(release/'manifest.json') baseline = STATE/'baseline' gid = grp.getgrnam(FIXED['deployment_group']).gr_gid for area in ('sql', 'evidence'): for source in (release/area).rglob('*'): require(not source.is_symlink(), 'Installed baseline symlink refused') target = baseline/area/source.relative_to(release/area) if source.is_dir(): target.mkdir(exist_ok=True, parents=True) os.chown(target, 0, gid); target.chmod(0o750) else: target.parent.mkdir(exist_ok=True, parents=True) shutil.copyfile(source, target) os.chown(target, 0, gid); target.chmod(0o640) pending = baseline/'.manifest.pending' pending.write_bytes(canonical(manifest)) os.chown(pending, 0, gid); pending.chmod(0o640) os.replace(pending, baseline/'manifest.json') return manifest class CopyWorker(core.Worker): def __init__(self, config): user = pwd.getpwnam(FIXED['migration_account']) self.process = subprocess.Popen(['/usr/bin/dotnet', FIXED['worker'], str(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 Maintenance: def __init__(self): # No candidate values, SQL or scripts are passed to docker/SA. data = json.loads(subprocess.check_output(['/usr/bin/docker','inspect','atlas-sql-server'], env=core.SAFE_ENV))[0] require(data['HostConfig']['PortBindings']['1433/tcp'] == [{'HostIp':'192.168.10.10','HostPort':'1433'}], 'Wrong Atlas SQL endpoint') require(any(m['Source']=='/sql/mssql' and m['Destination']=='/var/opt/mssql' for m in data['Mounts']), 'Wrong Atlas SQL storage') env = dict(v.split('=',1) for v in data['Config']['Env'] if '=' in v) self.password = env.get('MSSQL_SA_PASSWORD', env.get('SA_PASSWORD')) require(bool(self.password), 'Maintenance authentication unavailable') def sql(self, statement): result = subprocess.run(['/usr/bin/docker','exec','-i','-e','SQLCMDPASSWORD', 'atlas-sql-server','/opt/mssql-tools18/bin/sqlcmd','-S','localhost','-U','sa', '-C','-I','-b','-l','10','-t','1800','-y','0'], input='SET NOCOUNT ON;\n'+statement, text=True, capture_output=True, env={**core.SAFE_ENV,'SQLCMDPASSWORD':self.password}, timeout=1900) require(result.returncode == 0, 'Fixed Development backup/restore operation failed') return result.stdout.strip() def restore(self, database, media): require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') files = json.loads(self.sql("SELECT name,type FROM sys.master_files WHERE database_id=DB_ID(N'PlotDirector_Development') ORDER BY file_id FOR JSON PATH;")) require(len(files) == 2 and {f['type'] for f in files} == {0,1}, 'Unexpected Development files') moves = [] for f in files: require(re.fullmatch(r'[A-Za-z0-9_]+', f['name']), 'Unexpected logical file name') suffix = '.mdf' if f['type']==0 else '_log.ldf' moves.append("MOVE N'"+f['name']+"' TO N'/var/opt/mssql/data/"+database+suffix+"'") self.sql(f"IF DB_ID(N'{database}') IS NOT NULL THROW 51000,'Copy already exists',1; RESTORE DATABASE [{database}] FROM DISK=N'{media}' WITH "+','.join(moves)+",RECOVERY,CHECKSUM; "+f"ALTER DATABASE [{database}] SET TRUSTWORTHY OFF; ALTER DATABASE [{database}] SET DB_CHAINING OFF;") def copy_identity(self, database): require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') login = 'pd_qualification_'+database.rsplit('_',1)[1] password = uuid.uuid4().hex+uuid.uuid4().hex+'Aa9!' self.sql(f"CREATE LOGIN [{login}] WITH PASSWORD=N'{password}',CHECK_POLICY=ON; USE [{database}]; CREATE USER [{login}] FOR LOGIN [{login}]; ALTER ROLE db_owner ADD MEMBER [{login}];") return {'database':database,'expected_host':'atlas','expected_server':'192.168.10.10,1433', 'connection':f'Server=192.168.10.10,1433;Database={database};User ID={login};Password={password};Encrypt=True;TrustServerCertificate=True;'} def drop(self, database): require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') self.sql(f"IF DB_ID(N'{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}]; END;") login = 'pd_qualification_'+database.rsplit('_',1)[1] self.sql(f"IF EXISTS(SELECT 1 FROM sys.server_principals WHERE name=N'{login}') DROP LOGIN [{login}];") def qualify(identifier): identifier = safe_name(identifier) Development().configuration() # fixed service, host, accounts and protected code lock = os.open(Path(ROOT)/'deployment.lock', os.O_RDWR|os.O_NOFOLLOW) try: fcntl.flock(lock, fcntl.LOCK_EX|fcntl.LOCK_NB) baseline = refresh_baseline() destination = STATE/'qualified'/identifier require(not destination.exists(), 'Qualification identifier already exists') gid = grp.getgrnam(FIXED['deployment_group']).gr_gid destination.parent.mkdir(mode=0o750, exist_ok=True) core.protected(destination.parent, directory=True) os.chown(destination.parent, 0, gid); destination.parent.chmod(0o750) destination.mkdir(mode=0o750) os.chown(destination, 0, gid); destination.chmod(0o750) result = {'status':'failed','phase':'plan-validation','database_changes_applied':False, 'application_activated':False,'corrective_deployment_safe':True} try: with tempfile.TemporaryDirectory(prefix='.qualification-', dir=ROOT) as temporary: work = Path(temporary) migrate_gid = pwd.getpwnam(FIXED['migration_account']).pw_gid os.chown(work,0,migrate_gid); work.chmod(0o750) request = STATE/'incoming'/identifier/'qualification' snapshot(request/'plan.json', work/'manifest.json', 8*1024*1024) plan = load(work/'manifest.json') validate_extension(plan, baseline) require(len(plan['migrations']) > len(baseline['migrations']), 'No new SQL to qualify') (work/'sql').mkdir() total = 0 for step in plan['migrations']: target = work/'sql'/step['file'] if step in baseline['migrations']: shutil.copyfile(STATE/'baseline/sql'/step['file'],target) else: snapshot(request/'sql'/step['file'],target,8*1024*1024) require(file_digest(target) == step['sha256'], 'SQL checksum differs from plan') total += target.stat().st_size require(total <= 128*1024*1024, 'SQL input limit exceeded') for path in (work/'manifest.json',work/'sql',*(work/'sql').iterdir()): os.chown(path,0,migrate_gid); path.chmod(0o750 if path.is_dir() else 0o640) # Validate the actual live ledger before copying it. No live SQL runs. live = DevelopmentWorker(FIXED) try: result['phase'] = 'live-history-verification' begin = live.call('begin', package_root=str(work), deployment_id='qualification-'+uuid.uuid4().hex, package_sha256='0'*64) result['migration_history'] = begin require(begin['schema'] == plan['starting_schema_sha256'], 'Live Development schema drift') result['phase'] = 'verified-backup' unique = uuid.uuid4().hex backup = 'PlotDirector_Development-qualification-'+unique+'.bak' require(shutil.disk_usage(FIXED['backup']).free > FIXED['minimum_free_bytes']+2*begin['database_bytes'], 'Insufficient recovery space') require(not (Path(FIXED['backup'])/backup).exists(), 'Backup identifier collision') live.call('backup',path=FIXED['database_backup_directory']+'/'+backup) require((Path(FIXED['backup'])/backup).stat().st_size > 0, 'Backup unavailable') result['backup'] = {'file':backup,'verified':True} finally: live.close() result['phase'] = 'disposable-copy-restore' admin = Maintenance() database = 'PlotDirector_Qualification_'+unique restored = False try: admin.restore(database, FIXED['database_backup_directory']+'/'+backup) restored = True config = admin.copy_identity(database) config_path = work/'copy.private.json' config_path.write_bytes(canonical(config)); os.chown(config_path,0,migrate_gid); config_path.chmod(0o640) copy = CopyWorker(config_path) try: copy.call('begin',package_root=str(work),deployment_id='qualification-'+unique,package_sha256='0'*64) result['phase'] = 'migration-on-copy' migrated = copy.call('qualify-migrate') plan['resulting_schema_sha256'] = migrated['schema'] result.update(status='passed', phase='qualified', migrations=migrated, source_starting_schema_sha256=plan['starting_schema_sha256'], resulting_schema_sha256=migrated['schema']) except Exception: result['worker_failure'] = copy.last_error raise finally: copy.close() finally: # Never drop or restore the Development database. Failure to # clean up a generated copy is reported for maintenance. try: admin.drop(database) except Exception: result['copy_cleanup_required'] = database if not restored: raise (destination/'plan.json').write_bytes(canonical(plan)) except Exception as error: result['error'] = core.public_error(error) raise finally: (destination/'result.json').write_bytes(canonical(result)) for path in destination.iterdir(): os.chown(path,0,gid); path.chmod(0o640) print(canonical(result).decode(),end='') finally: os.close(lock) def sync_baseline(): lock = os.open(Path(ROOT)/'deployment.lock',os.O_RDWR|os.O_NOFOLLOW) try: fcntl.flock(lock,fcntl.LOCK_EX) refresh_baseline() finally: os.close(lock)