56 行
3.1 KiB
Python
56 行
3.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Explicit transactional fresh seed import; plan is the default."""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import getpass
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import stat
|
|
import subprocess
|
|
|
|
ROOT=Path(__file__).resolve().parents[2]
|
|
|
|
def literal(value):
|
|
if value is None: return "NULL"
|
|
if isinstance(value,(int,float)): return str(value)
|
|
if value=="2000-01-01 00:00:00": return "LOCALTIMESTAMP"
|
|
return "'"+str(value).replace("'","''")+"'"
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--config",required=True,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("--configure-admin",action="store_true",help="explicitly set the admin password using a hidden terminal prompt")
|
|
args=parser.parse_args();path=args.config.resolve()
|
|
if not path.is_relative_to(ROOT/"runtime/dev-private") or not path.is_file() or stat.S_IMODE(path.stat().st_mode)&0o077:
|
|
parser.error("private 0600 configuration required under runtime/dev-private")
|
|
environment=os.environ.copy();values=json.loads(path.read_text())
|
|
for key in ("host","port","username","password","schema"):
|
|
if not values.get(key):parser.error("missing private field: "+key)
|
|
environment["DATAGOV_DM_"+key.upper()]=str(values[key])
|
|
source=(ROOT/"db/dameng/seed.json").read_bytes();seed=json.loads(source)
|
|
rows=[]
|
|
for table,data in seed.items():
|
|
if not all(re.fullmatch(r"[a-z][a-z0-9_]*",n) for n in [table,*data['columns']]):raise ValueError("Invalid identifier")
|
|
for row in data['rows']:
|
|
sql="INSERT INTO "+table+"("+",".join(data['columns'])+") VALUES("+",".join(map(literal,row))+")"
|
|
rows.append(base64.b64encode(sql.encode()).decode())
|
|
if not args.apply and not args.verify and not args.configure_admin:
|
|
print("PLAN_ONLY SEED_ROWS="+str(len(rows))+" database_connection=NOT_RUN");return 0
|
|
body=hashlib.sha256(source).hexdigest()+"\n"+",".join(seed)+"\n"+"\n".join(rows)+"\n"
|
|
if args.configure_admin:
|
|
password=getpass.getpass("New DataGov administrator password: ")
|
|
if len(password)<12 or len(password.encode())>72:parser.error("password must have at least 12 characters and at most 72 UTF-8 bytes")
|
|
if password!=getpass.getpass("Repeat password: "):parser.error("passwords do not match")
|
|
result=subprocess.run(["htpasswd","-niBC","12","datagov"],input=password+"\n",text=True,capture_output=True)
|
|
if result.returncode:parser.error("BCrypt generation failed")
|
|
environment['DATAGOV_DM_ADMIN_HASH']=result.stdout.strip().split(":",1)[1]
|
|
del password
|
|
driver=ROOT/"script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar"
|
|
return subprocess.run(["java","--class-path",str(driver),str(ROOT/"script/database/DamengSeed.java"),*(["--verify"] if args.verify else ["--configure-admin"] if args.configure_admin else [])],input=body,text=True,env=environment).returncode
|
|
|
|
if __name__=="__main__":raise SystemExit(main())
|