am-freescan/scripts/migrate_standalone.py

220 lines
17 KiB
Python
Raw Permalink Normal View History

"""Private migration bundle: stopped source -> empty localhost deployment. Nothing is uploaded to Git.
Requires official mysqldump on the source; the target imports with its local MySQL container.
"""
from __future__ import annotations
import argparse, hashlib, json, os, re, shutil, socket, subprocess, sys, tempfile, uuid
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
import bootstrap_db as source_bootstrap
import bootstrap_standalone as standalone
ROOT = Path(__file__).resolve().parents[1]
def reparse(path):
"""Do not follow Windows junctions or symbolic links into unrelated directories."""
return path.is_symlink() or bool(getattr(path.lstat(), 'st_file_attributes', 0) & 0x400)
def digest(path):
h=hashlib.sha256()
with path.open('rb') as f:
while chunk:=f.read(1024*1024):h.update(chunk)
return h.hexdigest()
def copy_tree(source,target):
source=Path(source)
if source.exists() and reparse(source):raise ValueError('Source directory must not be a link or junction')
source=source.resolve()
if not source.is_dir():raise ValueError('Missing source data directory: '+str(source))
target.mkdir(parents=True,exist_ok=True)
for p in source.rglob('*'):
if reparse(p):raise ValueError('Migration does not follow symlinks or junctions: '+str(p))
destination=target/p.relative_to(source)
if p.is_dir():destination.mkdir(parents=True,exist_ok=True)
else:shutil.copy2(p,destination)
def idle(cursor):
standalone.ensure_idle(cursor)
def export_bundle(args):
if not args.confirm_source_stopped:raise ValueError('Explicit --confirm-source-stopped is required after stopping all physical operations and the source backend')
with socket.socket() as probe:
if probe.connect_ex(('127.0.0.1',48090))==0:raise ValueError('Source backend still listens on 48090; do not export while it can modify files')
runtime=json.loads(args.source_runtime.read_text(encoding='utf-8-sig'));mysql=runtime['mysql'];source_bootstrap.validate_target(mysql)
import pymysql
connection=pymysql.connect(host=mysql['host'],port=int(mysql.get('port',3306)),user=mysql['user'],password=mysql['password'],database='am-freescan',charset='utf8mb4',autocommit=True)
output=args.output.resolve()
if output.is_relative_to(args.artifacts.resolve()):raise ValueError('Bundle output must be outside source artifacts')
if output.exists():raise ValueError('Output must be a new directory; partial/previous bundles are never overwritten')
output.mkdir(parents=True)
try:
if os.name=='nt':
principal=subprocess.run(['whoami'],capture_output=True,text=True,check=True).stdout.strip()
secured=subprocess.run(['icacls',str(output),'/inheritance:r','/grant:r',principal+':(OI)(CI)F','*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F'],capture_output=True)
if secured.returncode:raise ValueError('Cannot restrict private migration directory permissions')
with connection.cursor() as cursor:
cursor.execute('SET SESSION TRANSACTION READ ONLY');idle(cursor)
cursor.execute("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan' AND TABLE_TYPE='BASE TABLE' ORDER BY TABLE_NAME")
tables=[r[0] for r in cursor.fetchall()]
if not tables or any(not re.fullmatch(r'[A-Za-z0-9_]+',t) for t in tables):raise ValueError('Unexpected source table inventory')
counts={}
for t in tables:cursor.execute(f'SELECT COUNT(*) FROM `{t}`');counts[t]=cursor.fetchone()[0]
cursor.execute('SELECT id,storage,config FROM infra_file_config WHERE deleted=0')
clients=cursor.fetchall()
if len(clients)!=1 or clients[0][1]!=10:raise ValueError('This migration requires the current single LOCAL file client; export other object storage separately before proceeding')
file_client=json.loads(clients[0][2]);uploads=Path(file_client['basePath']).resolve()
if output.is_relative_to(uploads):raise ValueError('Bundle output must be outside source uploads')
roots={str(args.artifacts.resolve()).replace('\\','/'):'artifacts',str(uploads).replace('\\','/'):'uploads'}
missing=[]
for table in ('lab_artifact_file','lab_dimension_file'):
cursor.execute(f"SELECT id,storage_path FROM `{table}` WHERE storage_path IS NOT NULL AND storage_path<>''")
for identifier,path in cursor.fetchall():
normalized=path.replace('\\','/')
matched=next(((root,kind) for root,kind in roots.items() if normalized.lower().startswith(root.lower()+'/')),None)
if matched is None:
marker='/.local/artifacts/'
offset=normalized.lower().find(marker)
if offset<0:raise ValueError('Unmapped historical file path; review it before exporting: '+normalized)
root=normalized[:offset]+marker[:-1];roots[root]='artifacts';matched=(root,'artifacts')
root,kind=matched;relative=normalized[len(root)+1:]
if '..' in Path(relative).parts or Path(relative).is_absolute():raise ValueError('Unsafe source storage path')
source=(args.artifacts if kind=='artifacts' else uploads)/relative
if not source.is_file():missing.append(dict(table=table,id=str(identifier),sourcePath=path,targetRelative=kind+'/'+relative))
dump=Path(args.mysqldump).resolve()
if not dump.is_file():raise ValueError('Provide the official Windows mysqldump executable')
def quoted(v):return '"'+str(v).replace('\\','\\\\').replace('"','\\"')+'"'
defaults=output/'client-private.cnf'
defaults.write_text('[client]\nhost='+quoted(mysql['host'])+'\nport='+str(mysql.get('port',3306))+'\nuser='+quoted(mysql['user'])+'\npassword='+quoted(mysql['password'])+'\n',encoding='utf-8')
try:
command=[str(dump),'--defaults-extra-file='+str(defaults),'--single-transaction','--skip-lock-tables','--skip-add-drop-table','--no-tablespaces','--set-gtid-purged=OFF','--hex-blob','--routines','--events','--triggers','--column-statistics=0','--default-character-set=utf8mb4','--result-file='+str(output/'database.sql'),'am-freescan']
result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if result.returncode:raise ValueError('mysqldump failed; check source client compatibility and credentials privately')
finally:defaults.unlink(missing_ok=True)
copy_tree(args.artifacts,output/'artifacts');copy_tree(uploads,output/'uploads')
private=output/'private';private.mkdir()
if runtime.get('adminPassword'):(private/'login.json').write_text(json.dumps(dict(adminPassword=runtime['adminPassword'])),encoding='utf-8')
scanner=ROOT/'.local/scanner-private.yaml'
if scanner.exists():
shutil.copy2(scanner,private/'source-scanner-private.yaml')
import yaml
cfg=yaml.safe_load(scanner.read_text(encoding='utf-8-sig')) or {}
tls=cfg.get('cmvr',{}).get('quic',{}).get('tls',{})
for key in ('certificate','private-key','client-ca'):
if tls.get(key):
p=Path(tls[key]);p=p if p.is_absolute() else ROOT/p
if p.is_file():shutil.copy2(p,private/(key+'.pem'))
source_commit=subprocess.run(['git','-C',str(ROOT),'rev-parse','HEAD'],capture_output=True,text=True,check=True).stdout.strip()
manifest=dict(format='am-freescan-migration-v1',sourceDatabase='am-freescan',sourceConfirmedStopped=True,
createdUtc=datetime.now(timezone.utc).isoformat(),sourceCommit=source_commit,snapshotId=uuid.uuid4().hex,
sourceArtifactRoot=str(args.artifacts.resolve()),sourceUploadRoot=str(uploads),sourceFileDomain=file_client['domain'],tableCounts=counts,
storageRoots=roots,missingReferences=missing)
manifest['files']=[dict(path=p.relative_to(output).as_posix(),size=p.stat().st_size,sha256=digest(p)) for p in sorted(output.rglob('*')) if p.is_file()]
(output/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(dict(exported=True,tables=len(tables),files=len(manifest['files']),missingHistoricalFiles=len(missing),bundle=str(output),containsPrivateData=True)))
finally:connection.close()
def check_bundle(directory):
if reparse(directory):raise ValueError('Bundle root must not be a link or junction')
directory=directory.resolve()
inventory=set()
for entry in directory.rglob('*'):
if reparse(entry):raise ValueError('Bundle contains a link or junction')
if entry.is_file():inventory.add(entry.relative_to(directory).as_posix())
manifest=json.loads((directory/'manifest.json').read_text(encoding='utf-8-sig'))
if manifest.get('format')!='am-freescan-migration-v1' or manifest.get('sourceDatabase')!='am-freescan' or not manifest.get('sourceConfirmedStopped'):raise ValueError('Unrecognized migration bundle')
paths=set()
for item in manifest['files']:
name=item['path'];path=(directory/name).resolve()
if path.is_relative_to(directory) is False or name!=path.relative_to(directory).as_posix() or name in paths:raise ValueError('Unsafe bundle path')
paths.add(name)
if not path.is_file() or path.stat().st_size!=item['size'] or digest(path)!=item['sha256']:raise ValueError('Bundle checksum failed: '+name)
if 'database.sql' not in paths:raise ValueError('Bundle has no database dump')
if inventory != paths | {'manifest.json'}:raise ValueError('Bundle contains unverified extra or missing files')
roots=manifest.get('storageRoots',{})
if not roots or any(kind not in ('artifacts','uploads') or not Path(root).is_absolute() or '..' in Path(root).parts for root,kind in roots.items()):raise ValueError('Bundle storage mapping is missing or invalid')
return manifest
def import_bundle(args):
if not args.confirm_source_stopped:raise ValueError('Confirm the source remains stopped before enabling the new instance')
cfg=standalone.configuration(args.config);manifest=check_bundle(args.package)
with socket.socket() as probe:
if probe.connect_ex(('127.0.0.1',48090))==0:raise ValueError('Stop the target backend before importing')
with standalone.connect(cfg) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan'")
if cursor.fetchone()[0]:raise ValueError('Target must be empty: never run Bootstrap before historical migration, and never overwrite an existing database')
home=Path(cfg['dataRoot']).resolve()
for name in ('artifacts','uploads'):
destination=home/name
if destination.exists() and any(destination.iterdir()):raise ValueError('Target data directory is not empty: '+name)
# Reject database/user administration outside the designated schema, including executable comments.
with (args.package/'database.sql').open(encoding='utf-8-sig') as sql:
for line in sql:
command=re.sub(r'^/\*!\d+\s*','',line.strip())
if re.match(r'(?i)^(?:CREATE|DROP)\s+DATABASE\b|^(?:GRANT|REVOKE)\b|^(?:CREATE|ALTER|DROP)\s+USER\b|^USE\b',command):raise ValueError('Dump contains database/user switching; export without --databases')
staging=home/'backups'/('migration-'+uuid.uuid4().hex+'.sql');shutil.copy2(args.package/'database.sql',staging)
compose=ROOT/'deploy/windows11/compose.yaml';env=ROOT/'.local/standalone/compose.env'
shell='MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql -uroot --binary-mode=1 am-freescan < /backup/'+staging.name
project=cfg.get('composeProject','am-freescan-standalone')
if not re.fullmatch(r'[a-z0-9][a-z0-9_-]*',project):raise ValueError('Invalid standalone Compose project')
result=subprocess.run(['docker','compose','-p',project,'--env-file',str(env),'-f',str(compose),'exec','-T','mysql','sh','-c',shell],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if result.returncode:
(args.config.parent/'migration-error.log').write_bytes(result.stderr)
raise ValueError('Import stopped; preserve the partial instance and inspect private migration-error.log. Do not delete or reimport over it automatically')
for name in ('artifacts','uploads'):copy_tree(args.package/name,home/name)
mappings=[(old,str(home/kind)) for old,kind in manifest['storageRoots'].items()]
def remap(value):
if not value:return value
normalized=value.replace('\\','/')
for old,new in mappings:
old=old.replace('\\','/').rstrip('/')
if normalized.lower().startswith(old.lower()+'/'):
relative=normalized[len(old)+1:]
if '..' in Path(relative).parts or Path(relative).is_absolute():raise ValueError('Unsafe storage path in database')
return new.replace('\\','/')+'/'+relative
raise ValueError('Unmapped storage path requires manual review: '+value)
with standalone.connect(cfg) as connection:
with connection.cursor() as cursor:
for table,expected in manifest['tableCounts'].items():
if not re.fullmatch(r'[A-Za-z0-9_]+',table):raise ValueError('Invalid table name')
cursor.execute(f'SELECT COUNT(*) FROM `{table}`')
if cursor.fetchone()[0]!=expected:raise ValueError('Row-count mismatch: '+table)
connection.begin()
for table in ('lab_artifact_file','lab_dimension_file'):
cursor.execute(f'SELECT id,storage_path FROM `{table}` WHERE storage_path IS NOT NULL AND storage_path<>\'\'')
for identifier,path in cursor.fetchall():cursor.execute(f'UPDATE `{table}` SET storage_path=%s WHERE id=%s',(remap(path),identifier))
cursor.execute('SELECT id,config FROM infra_file_config WHERE storage=10')
for identifier,text in cursor.fetchall():
value=json.loads(text);value['basePath']=cfg['uploadRoot'];value['domain']=cfg['publicBaseUrl']
cursor.execute('UPDATE infra_file_config SET config=%s WHERE id=%s',(json.dumps(value),identifier))
for table,column in (('infra_file','url'),('lab_artifact_file','file_url')):
cursor.execute(f'SELECT id,`{column}` FROM `{table}` WHERE `{column}` IS NOT NULL')
for identifier,url in cursor.fetchall():
if url and url.startswith(manifest['sourceFileDomain'].rstrip('/')+'/'):
cursor.execute(f'UPDATE `{table}` SET `{column}`=%s WHERE id=%s',(cfg['publicBaseUrl'].rstrip('/')+url[len(manifest['sourceFileDomain'].rstrip('/')):],identifier))
for table in ('system_oauth2_access_token','system_oauth2_refresh_token'):cursor.execute(f'DELETE FROM `{table}`')
cursor.execute("UPDATE iot_robot SET connect_status='0'");cursor.execute("UPDATE iot_device SET online_status='0'")
for key,value in (('owner',standalone.OWNER),('instance',cfg['instanceId'])):
cursor.execute(f'INSERT INTO `{source_bootstrap.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',(key,value))
connection.commit()
login=args.package/'private/login.json'
if login.exists():
cfg['adminPassword']=json.loads(login.read_text(encoding='utf-8'))['adminPassword']
args.config.write_text(json.dumps(cfg,ensure_ascii=False,indent=2),encoding='utf-8')
(args.config.parent/'initial-admin.txt').write_text('迁移保留原账号及密码;初始化生成的新密码不适用。请使用源系统有效账号。\n',encoding='utf-8')
print(json.dumps(dict(imported=True,tablesVerified=len(manifest['tableCounts']),filesVerified=len(manifest['files']),missingHistoricalFiles=len(manifest.get('missingReferences',[])),runtimeConnectionsReset=True,redisSessionsNotMigrated=True)))
def main():
parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='mode',required=True)
export=sub.add_parser('export');export.add_argument('--source-runtime',type=Path,default=ROOT/'.local/runtime.json');export.add_argument('--artifacts',type=Path,default=ROOT/'.local/artifacts');export.add_argument('--output',type=Path,required=True);export.add_argument('--mysqldump',required=True);export.add_argument('--confirm-source-stopped',action='store_true')
restore=sub.add_parser('import');restore.add_argument('--config',type=Path,required=True);restore.add_argument('--package',type=Path,required=True);restore.add_argument('--confirm-source-stopped',action='store_true')
verify=sub.add_parser('verify');verify.add_argument('--package',type=Path,required=True)
args=parser.parse_args()
if args.mode=='export':export_bundle(args)
elif args.mode=='import':import_bundle(args)
else:manifest=check_bundle(args.package);print(json.dumps(dict(verified=True,files=len(manifest['files']))))
if __name__=='__main__':
try:main()
except Exception as error:
print('Migration stopped: '+(str(error) if isinstance(error,ValueError) else type(error).__name__+'; inspect private configuration without printing credentials'),file=sys.stderr);raise SystemExit(1)