"""Independent localhost-only deployment bootstrap. Never uses .local/runtime.json or a LAN DB. Default: parse/validate the complete schema offline. --apply requires a private runtime generated by deploy/windows11/manage.ps1. An unrelated nonempty database is always rejected. """ from __future__ import annotations import argparse import hashlib import json import os from pathlib import Path import sys from urllib.parse import urlparse import bootstrap_db as base import bootstrap_cmvr as native from apply_scan_only import apply_schema, load_migration OWNER = "am-freescan/standalone-v1" MIGRATIONS = ( "005_scan_only.sql", "006_resource_scheduling.sql", "007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", ) def plan(): schema, seeds = base.load_assets() cmvr = base.load_schema(native.SCHEMA, native.PREFIXES) reference = native.load_reference() migrations = [(name, load_migration(base.SQL_ROOT / name)) for name in MIGRATIONS] discovered = {p.name for p in base.SQL_ROOT.glob("*.sql") if p.name[:3].isdigit() and int(p.name[:3]) >= 5} if discovered != set(MIGRATIONS) | {"016_coordinate_management.sql"}: raise ValueError("Migration inventory changed; review the standalone initialization plan first") return schema, seeds, cmvr, reference, migrations def configuration(path): cfg = json.loads(path.read_text(encoding="utf-8-sig")) db = cfg["mysql"] if db.get("host") != "127.0.0.1" or int(db.get("port", 0)) != 3306 or db.get("database") != "am-freescan" or db.get("user") != "freescan": raise ValueError("Standalone bootstrap only permits freescan@127.0.0.1:3306/am-freescan") if not cfg.get("instanceId") or not db.get("password"): raise ValueError("Missing instance identity or local database credential") admin = cfg.get("adminPassword", "") if not 8 <= len(admin) <= 16: raise ValueError("Initial admin password must contain 8 to 16 characters") if os.environ.get("AM_FREESCAN_ADMIN_PASSWORD", admin) != admin: raise ValueError("Conflicting administrator environment variable; do not override this instance") home = Path(cfg["dataRoot"]).resolve() if not Path(cfg["dataRoot"]).is_absolute() or Path(cfg["uploadRoot"]).resolve() != home / "uploads": raise ValueError("Upload storage must be the uploads directory of this independent data root") public = urlparse(cfg["publicBaseUrl"]) if public.scheme not in {"http", "https"} or not public.hostname or public.username or public.password or public.query or public.fragment or public.path not in {"", "/"}: raise ValueError("Public base URL must be a plain browser-accessible HTTP(S) origin") return cfg def connect(cfg): import pymysql m = cfg["mysql"] return pymysql.connect(host="127.0.0.1", port=3306, user="freescan", password=m["password"], database="am-freescan", charset="utf8mb4", autocommit=True, connect_timeout=5, read_timeout=60, write_timeout=60) def ownership(cursor, cfg, allow_empty=False): cursor.execute("SELECT DATABASE()") if cursor.fetchone() != ("am-freescan",): raise ValueError("Unexpected database") cursor.execute("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan'") tables = {r[0] for r in cursor.fetchall()} if not tables and allow_empty: return if base.META not in tables: raise ValueError("Nonempty database has no standalone ownership marker; refusing to change it") cursor.execute(f"SELECT name,value FROM `{base.META}` WHERE name IN ('owner','instance')") values = dict(cursor.fetchall()) if values.get("owner") != OWNER or values.get("instance") != cfg["instanceId"]: raise ValueError("Database belongs to another deployment; refusing to change it") def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path) mode = parser.add_mutually_exclusive_group() mode.add_argument("--apply", action="store_true") mode.add_argument("--verify", action="store_true") mode.add_argument("--check-idle", action="store_true") args = parser.parse_args(argv) schema, seeds, cmvr, reference, migrations = plan() if not any((args.apply, args.verify, args.check_idle)): print(json.dumps(dict(mode="offline", target="127.0.0.1:3306/am-freescan", baseTables=len(schema), nativeTables=len(cmvr), migrations=[n for n, _ in migrations], referenceSeeds=list(seeds), noDatabaseConnection=True))) return 0 if args.config is None: raise ValueError("An explicit standalone --config is required") cfg = configuration(args.config) if args.apply: import bcrypt # Verify availability before any writes. with connect(cfg) as connection: with connection.cursor() as cursor: ownership(cursor, cfg, allow_empty=args.apply) if args.check_idle: for sql in ( "SELECT COUNT(*) FROM te_task_inst WHERE status IN ('1','3')", "SELECT COUNT(*) FROM lab_execution WHERE status IN ('RUNNING','PAUSED','STOPPING') AND deleted=0", "SELECT COUNT(*) FROM lab_resource_occupation WHERE tenant_id=1 AND deleted=0", ): cursor.execute(sql) if cursor.fetchone()[0]: raise ValueError("Active execution or occupation remains; stop safely through the platform first") print("No active platform execution or occupation; physical state still requires onsite confirmation") return 0 if args.verify: # A migrated business instance may have deliberately reorganized menus. # Validate usable identity/navigation without rewriting it to seed values. for sql in ( "SELECT COUNT(*) FROM system_users WHERE id=1 AND username='admin' AND tenant_id=1 AND deleted=0", "SELECT COUNT(*) FROM system_tenant WHERE id=1 AND deleted=0", "SELECT COUNT(*) FROM system_menu WHERE deleted=0 AND status=0 AND type IN (1,2)", ): cursor.execute(sql) if cursor.fetchone()[0] < 1: raise ValueError("Required identity or navigation data is missing") for table in set(schema) | set(cmvr) | {"lab_dimension_delivery", "lab_fixture_trajectory", "lab_resource_occupation", "lab_scanner_command"}: cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan' AND TABLE_NAME=%s", (table,)) if cursor.fetchone()[0] != 1: raise ValueError("Missing required table: " + table) print("Standalone schema, ownership, reference data and menus verified") return 0 cursor.execute("SELECT GET_LOCK(%s,10)", (OWNER,)) if cursor.fetchone() != (1,): raise ValueError("Another standalone bootstrap is running") try: # Recheck ownership after taking the lock, before creating even the marker table. ownership(cursor, cfg, allow_empty=True) cursor.execute(f"CREATE TABLE IF NOT EXISTS `{base.META}` (name varchar(80) PRIMARY KEY,value text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") for key, value in (("owner", OWNER), ("instance", cfg["instanceId"])): cursor.execute(f"INSERT IGNORE INTO `{base.META}` (name,value) VALUES(%s,%s)", (key, value)) changed = base.ensure_schema(cursor, schema) + base.ensure_schema(cursor, cmvr) for name, operations in migrations: changed += apply_schema(cursor, operations) checksum = hashlib.sha256((base.SQL_ROOT / name).read_bytes()).hexdigest() cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (name, checksum)) base.provision_identity(cursor, dict(adminPassword=cfg["adminPassword"], uploadRoot=cfg["uploadRoot"], backendUrl=cfg["publicBaseUrl"])) for filename, (checksum, statements) in seeds.items(): cursor.execute(f"SELECT value FROM `{base.META}` WHERE name=%s", (filename,)) if cursor.fetchone() == (checksum,): continue for statement in statements: cursor.execute(statement) cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (filename, checksum)) native.references(cursor, reference) base.finalize_permissions(cursor) native.verify_references(cursor, reference) print(json.dumps(dict(initialized=True, target="127.0.0.1/am-freescan", additiveChanges=changed, user="admin", passwordPrinted=False, originalBusinessDataImported=False))) finally: cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,)) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as error: detail = str(error) if isinstance(error, ValueError) else "check the private config, local middleware and deployment logs" print(f"Standalone bootstrap stopped ({type(error).__name__}): {detail}", file=sys.stderr) raise SystemExit(1)