Add scanner API integration, workflow components, execution-bound live images and 3D model viewing. Harden task control, parameters, resource protection and reports, with automated regressions and detailed verification records.
304 lines
17 KiB
Python
304 lines
17 KiB
Python
"""Initialize only 192.168.28.10/am-freescan. Dry-run is the default.
|
|
|
|
Never imports a database dump. Existing nonempty databases require this tool's
|
|
ownership marker. Repeated runs add missing structures and reference rows only.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / ".tools" / "python"))
|
|
DATABASE = "am-freescan"
|
|
HOST = "192.168.28.10"
|
|
OWNER = "am-freescan/bootstrap-v1"
|
|
META = "am_freescan_bootstrap_meta"
|
|
SQL_ROOT = ROOT / "am-backend" / "sql" / "freescan"
|
|
|
|
|
|
def validate_target(mysql):
|
|
if mysql.get("database") != DATABASE:
|
|
raise ValueError("Database must be exactly am-freescan; no other database is permitted")
|
|
if mysql.get("host") != HOST:
|
|
raise ValueError("Host must be exactly 192.168.28.10")
|
|
|
|
|
|
def validate_existing_database(tables, owner):
|
|
if tables and owner != OWNER:
|
|
raise RuntimeError("Refusing a nonempty database without AM FreeScan ownership; no tables were changed")
|
|
|
|
|
|
def split_sql(source):
|
|
"""Split MySQL statements without splitting quoted comments or semicolons."""
|
|
statements, chunk = [], []
|
|
quote, comment, i = None, None, 0
|
|
while i < len(source):
|
|
ch = source[i]
|
|
pair = source[i:i + 2]
|
|
if comment == "line":
|
|
if ch == "\n":
|
|
comment = None
|
|
chunk.append(ch)
|
|
i += 1
|
|
continue
|
|
if comment == "block":
|
|
if pair == "*/":
|
|
comment = None
|
|
i += 2
|
|
chunk.append(" ")
|
|
else:
|
|
i += 1
|
|
continue
|
|
if quote:
|
|
chunk.append(ch)
|
|
if ch == "\\" and i + 1 < len(source):
|
|
chunk.append(source[i + 1])
|
|
i += 2
|
|
continue
|
|
if ch == quote:
|
|
if i + 1 < len(source) and source[i + 1] == quote:
|
|
chunk.append(source[i + 1])
|
|
i += 2
|
|
continue
|
|
quote = None
|
|
elif ch in "'\"`":
|
|
quote = ch
|
|
chunk.append(ch)
|
|
elif pair == "--" and (i + 2 == len(source) or source[i + 2].isspace()):
|
|
comment = "line"
|
|
i += 2
|
|
continue
|
|
elif ch == "#":
|
|
comment = "line"
|
|
elif pair == "/*":
|
|
comment = "block"
|
|
i += 2
|
|
continue
|
|
elif ch == ";":
|
|
if "".join(chunk).strip():
|
|
statements.append("".join(chunk).strip())
|
|
chunk = []
|
|
else:
|
|
chunk.append(ch)
|
|
i += 1
|
|
if quote or comment == "block":
|
|
raise ValueError("Unterminated SQL quote or comment")
|
|
if "".join(chunk).strip():
|
|
statements.append("".join(chunk).strip())
|
|
return statements
|
|
|
|
|
|
def load_schema(path, allowed_prefixes=("system_", "infra_", "lab_")):
|
|
schema = {}
|
|
for statement in split_sql(path.read_text(encoding="utf-8")):
|
|
match = re.match(r"CREATE TABLE IF NOT EXISTS `([a-z_0-9]+)`\s*\(", statement)
|
|
if not match:
|
|
raise ValueError(f"Only idempotent CREATE TABLE statements allowed in {path.name}")
|
|
table = match.group(1)
|
|
if not table.startswith(allowed_prefixes):
|
|
raise ValueError(f"Unexpected schema table {table}")
|
|
columns, indexes = {}, {}
|
|
for line in statement.splitlines()[1:]:
|
|
definition = line.strip().rstrip(",")
|
|
column = re.match(r"`([a-z_0-9]+)`\s+", definition)
|
|
index = re.match(r"(?:UNIQUE (?:KEY|INDEX)|KEY|INDEX) `([a-z_0-9]+)`", definition)
|
|
if column:
|
|
columns[column.group(1)] = definition
|
|
elif index:
|
|
indexes[index.group(1)] = definition
|
|
schema[table] = {"sql": statement, "columns": columns, "indexes": indexes}
|
|
return schema
|
|
|
|
|
|
def validate_seed_statement(statement, filename="seed"):
|
|
if not re.match(r"(?i)^(INSERT (?:IGNORE )?INTO|UPDATE)\s+`?(system_(?:menu|role|role_menu|dict_type|dict_data))`?(?:\s|\()", statement):
|
|
raise ValueError(f"Non-whitelisted reference statement in {filename}")
|
|
if re.search(r"`\s*\.\s*`", statement):
|
|
raise ValueError(f"Qualified database references are forbidden in {filename}")
|
|
if re.search(r"(?i)\b(?:FROM|JOIN|INTO|UPDATE|TABLE)\s+`?[a-z_0-9]+`?\s*\.", statement):
|
|
raise ValueError(f"Cross-database reference is forbidden in {filename}")
|
|
|
|
|
|
def load_assets():
|
|
schema = {}
|
|
for path in sorted(SQL_ROOT.glob("*_schema.sql")):
|
|
additions = load_schema(path)
|
|
if schema.keys() & additions.keys():
|
|
raise ValueError(f"Duplicate schema tables in {path.name}")
|
|
schema.update(additions)
|
|
seeds = {}
|
|
for path in sorted(SQL_ROOT.glob("*.sql")):
|
|
if path.name.endswith("_schema.sql") or path.name in {"005_scan_only.sql", "006_resource_scheduling.sql",
|
|
"007_scanner_integration.sql", "008_scanner_execution_view.sql"}:
|
|
# Dedicated additive migration runs after bootstrap_cmvr. It is not
|
|
# a reference seed and must never pass through the seed executor.
|
|
continue
|
|
source = path.read_text(encoding="utf-8")
|
|
statements = split_sql(source)
|
|
for statement in statements:
|
|
validate_seed_statement(statement, path.name)
|
|
seeds[path.name] = (hashlib.sha256(source.encode()).hexdigest(), statements)
|
|
return schema, seeds
|
|
|
|
|
|
def insert_new(cursor, table, values, identity):
|
|
"""Insert a known seed only when its logical identity is not present."""
|
|
where = " AND ".join(f"`{key}` = %s" for key in identity)
|
|
cursor.execute(f"SELECT 1 FROM `{table}` WHERE {where} LIMIT 1", tuple(values[key] for key in identity))
|
|
if cursor.fetchone():
|
|
return False
|
|
columns = ",".join(f"`{key}`" for key in values)
|
|
placeholders = ",".join("%s" for _ in values)
|
|
cursor.execute(f"INSERT INTO `{table}` ({columns}) VALUES ({placeholders})", tuple(values.values()))
|
|
return True
|
|
|
|
|
|
def ensure_schema(cursor, schema):
|
|
added = 0
|
|
for table, definition in schema.items():
|
|
cursor.execute(definition["sql"])
|
|
cursor.execute("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s", (DATABASE, table))
|
|
existing = {row[0] for row in cursor.fetchall()}
|
|
for column, column_sql in definition["columns"].items():
|
|
if column not in existing:
|
|
cursor.execute(f"ALTER TABLE `{table}` ADD COLUMN {column_sql}")
|
|
added += 1
|
|
cursor.execute("SELECT DISTINCT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s", (DATABASE, table))
|
|
existing_indexes = {row[0] for row in cursor.fetchall()}
|
|
for index, index_sql in definition["indexes"].items():
|
|
if index not in existing_indexes:
|
|
cursor.execute(f"ALTER TABLE `{table}` ADD {index_sql}")
|
|
added += 1
|
|
return added
|
|
|
|
|
|
def provision_identity(cursor, config):
|
|
password = os.environ.get("AM_FREESCAN_ADMIN_PASSWORD") or config.get("adminPassword")
|
|
generated = not password
|
|
password = password or 'admin123'
|
|
if len(password) < 8:
|
|
raise ValueError("Initial administrator password must contain at least 8 characters")
|
|
if len(password) > 16:
|
|
raise ValueError("Initial administrator password must fit the framework login limit of 16 characters")
|
|
import bcrypt
|
|
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
|
audit = {"creator": "bootstrap", "updater": "bootstrap", "deleted": 0}
|
|
insert_new(cursor, "system_tenant_package", dict(id=1, name="AM FreeScan", status=0, remark="Independent AM FreeScan baseline", menu_ids="[]", **audit), ["id"])
|
|
insert_new(cursor, "system_tenant", dict(id=1, name="AM FreeScan", contact_user_id=1, contact_name="Administrator", status=0, websites='["127.0.0.1","localhost"]', package_id=0, expire_time="2099-12-31 23:59:59", account_count=10000, **audit), ["id"])
|
|
insert_new(cursor, "system_dept", dict(id=1, name="AM FreeScan", parent_id=0, sort=0, status=0, tenant_id=1, **audit), ["id"])
|
|
insert_new(cursor, "system_role", dict(id=1, name="FreeScan Administrator", code="super_admin", sort=0, data_scope=1, data_scope_dept_ids="[]", status=0, type=1, remark="Independent administrator", tenant_id=1, **audit), ["id"])
|
|
admin_created = insert_new(cursor, "system_users", dict(id=1, username="admin", password=password_hash, nickname="FreeScan Admin", remark="Created independently for AM FreeScan", dept_id=1, post_ids="[]", status=0, tenant_id=1, **audit), ["id"])
|
|
insert_new(cursor, "system_user_role", dict(user_id=1, role_id=1, tenant_id=1, **audit), ["user_id", "role_id", "tenant_id"])
|
|
insert_new(cursor, "system_oauth2_client", dict(id=1, client_id="default", secret=secrets.token_urlsafe(32), name="AM FreeScan", logo="", description="Independent local admin client", status=0, access_token_validity_seconds=1800, refresh_token_validity_seconds=2592000, redirect_uris='["http://127.0.0.1:5180"]', authorized_grant_types='["password","refresh_token"]', scopes="[]", auto_approve_scopes="[]", **audit), ["client_id"])
|
|
insert_new(cursor, "infra_config", dict(id=1, category="system", type=1, name="Account registration", config_key="system.user.register-enabled", value="false", visible=0, remark="Independent baseline: registration disabled", **audit), ["config_key"])
|
|
# A local filesystem client is configured without inheriting old cloud keys.
|
|
storage_root = (ROOT / ".local" / "files").as_posix()
|
|
file_config = {"@class": "cn.iocoder.yudao.module.infra.framework.file.core.client.local.LocalFileClientConfig", "basePath": storage_root, "domain": config.get("backendUrl", "http://localhost:48090")}
|
|
insert_new(cursor, "infra_file_config", dict(id=1, name="AM FreeScan local files", storage=10, remark="Independent local directory", master=1, config=json.dumps(file_config), **audit), ["id"])
|
|
(ROOT / ".local" / "files").mkdir(parents=True, exist_ok=True)
|
|
if generated and admin_created:
|
|
local = ROOT / ".local"
|
|
local.mkdir(exist_ok=True)
|
|
(local / "initial-admin.txt").write_text(f"username=admin\npassword={password}\n", encoding="utf-8")
|
|
|
|
|
|
def provision_demo(cursor):
|
|
"""Optional clearly labelled resources; never claims that hardware is online."""
|
|
audit = {"creator": "bootstrap-demo", "updater": "bootstrap-demo", "deleted": 0, "tenant_id": 1}
|
|
insert_new(cursor, "lab_laboratory", dict(id=900001, lab_code="DEMO-LAB", lab_name="DEMO software validation laboratory", location="Local software validation only", owner_id=1, status="ENABLED", remark="DEMO: software workflow resource, no physical laboratory connection", **audit), ["lab_code", "tenant_id"])
|
|
insert_new(cursor, "lab_sample", dict(id=900001, sample_code="DEMO-SAMPLE", sample_name="DEMO validation sample", part_no="DEMO-PART", sample_source="SELF", sample_type="PART", project_name="AM FreeScan DEMO", quantity=1, status="ENABLED", remark="DEMO: independently created placeholder; no historic sample data", **audit), ["sample_code", "tenant_id"])
|
|
insert_new(cursor, "lab_device", dict(id=900001, device_code="DEMO-SOFTWARE", device_name="DEMO software resource (no hardware)", device_type="OTHER", vendor="AM FreeScan DEMO", model="SOFTWARE-ONLY", laboratory_id=900001, owner_id=1, capability_tags='["SOFTWARE_ONLY"]', sync_status="UNMAPPED", business_status="ENABLED", limit_desc="No scanner or robot capability; hardware nodes must fail until configured", remark="DEMO: software workflow resource; not a connected device", **audit), ["device_code", "tenant_id"])
|
|
|
|
|
|
def finalize_permissions(cursor):
|
|
cursor.execute("SELECT id FROM system_menu WHERE deleted=0 ORDER BY id")
|
|
ids = [row[0] for row in cursor.fetchall()]
|
|
cursor.execute("UPDATE system_tenant_package SET menu_ids=%s WHERE id=1", (json.dumps(ids),))
|
|
cursor.execute("INSERT INTO system_role_menu (role_id,menu_id,creator,updater,deleted,tenant_id) SELECT 1,m.id,'bootstrap','bootstrap',0,1 FROM system_menu m WHERE m.deleted=0 AND NOT EXISTS (SELECT 1 FROM system_role_menu r WHERE r.role_id=1 AND r.menu_id=m.id AND r.tenant_id=1 AND r.deleted=0)")
|
|
cursor.execute("SELECT COUNT(*) FROM system_users WHERE id=1 AND username='admin' AND tenant_id=1 AND deleted=0")
|
|
if cursor.fetchone()[0] != 1:
|
|
raise RuntimeError("Administrator baseline verification failed")
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--config", type=Path, default=ROOT / ".local" / "runtime.json")
|
|
parser.add_argument("--apply", action="store_true", help="connect and apply to the hardcoded new database")
|
|
parser.add_argument("--demo", action="store_true", help="add clearly labelled DEMO sample/laboratory/software resource")
|
|
args = parser.parse_args(argv)
|
|
schema, seeds = load_assets()
|
|
if not args.apply:
|
|
print(f"DRY RUN: target {HOST}/{DATABASE}; {len(schema)} tables; seeds: {', '.join(seeds)}; DEMO={args.demo}. No database connection.")
|
|
return 0
|
|
config = json.loads(args.config.read_text(encoding="utf-8-sig"))
|
|
mysql = config["mysql"]
|
|
validate_target(mysql)
|
|
# Fail missing libraries/password constraints before making any database changes.
|
|
import pymysql
|
|
import bcrypt
|
|
password = os.environ.get("AM_FREESCAN_ADMIN_PASSWORD") or config.get("adminPassword")
|
|
if password and len(password) < 8:
|
|
raise ValueError("Initial administrator password must contain at least 8 characters")
|
|
if password and len(password) > 16:
|
|
raise ValueError("Initial administrator password must fit the framework login limit of 16 characters")
|
|
connection = pymysql.connect(host=HOST, port=int(mysql.get("port", 3306)), user=mysql["user"], password=mysql["password"], charset="utf8mb4", autocommit=True, connect_timeout=10)
|
|
locked = False
|
|
try:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute("SELECT GET_LOCK(%s,10)", (OWNER,))
|
|
locked = cursor.fetchone()[0] == 1
|
|
if not locked:
|
|
raise RuntimeError("Another bootstrap is running")
|
|
cursor.execute("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=%s", (DATABASE,))
|
|
existing_tables = [row[0] for row in cursor.fetchall()]
|
|
owner = None
|
|
if META in existing_tables:
|
|
cursor.execute(f"SELECT value FROM `{DATABASE}`.`{META}` WHERE name='owner'")
|
|
row = cursor.fetchone()
|
|
owner = row[0] if row else None
|
|
validate_existing_database(existing_tables, owner)
|
|
cursor.execute(f"CREATE DATABASE IF NOT EXISTS `{DATABASE}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
|
connection.select_db(DATABASE)
|
|
cursor.execute("SELECT DATABASE()")
|
|
if cursor.fetchone()[0] != DATABASE:
|
|
raise RuntimeError("Database selection guard failed")
|
|
cursor.execute(f"CREATE TABLE IF NOT EXISTS `{META}` (name varchar(80) PRIMARY KEY,value text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")
|
|
cursor.execute(f"INSERT IGNORE INTO `{META}` (name,value) VALUES ('owner',%s)", (OWNER,))
|
|
added = ensure_schema(cursor, schema)
|
|
provision_identity(cursor, config)
|
|
for filename, (checksum, statements) in seeds.items():
|
|
cursor.execute(f"SELECT value FROM `{META}` WHERE name=%s", (filename,))
|
|
row = cursor.fetchone()
|
|
if row and row[0] == checksum:
|
|
continue
|
|
for statement in statements:
|
|
cursor.execute(statement)
|
|
cursor.execute(f"INSERT INTO `{META}` (name,value) VALUES (%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (filename, checksum))
|
|
if args.demo:
|
|
provision_demo(cursor)
|
|
finalize_permissions(cursor)
|
|
print(f"Initialized {DATABASE}: {len(schema)} tables; {added} additive schema changes; admin=admin; credentials stay in .local/runtime.json or .local/initial-admin.txt")
|
|
finally:
|
|
if locked:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,))
|
|
connection.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
raise SystemExit(main())
|
|
except Exception as exc:
|
|
# SQL/driver exceptions can contain account values: do not print raw SQL.
|
|
detail = str(exc) if isinstance(exc, (ValueError, RuntimeError)) else (f"driver code {exc.args[0]}" if exc.args and isinstance(exc.args[0], int) else "check local configuration")
|
|
print(f"Bootstrap stopped ({type(exc).__name__}): {detail}; never retry against another database.", file=sys.stderr)
|
|
raise SystemExit(1)
|