Initial project source
这个提交包含在:
@@ -0,0 +1,318 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additive metadata migration through public OM APIs. No vendor DB access.
|
||||
|
||||
inventory writes a private, allowlisted payload and aggregate report. import applies only
|
||||
the reviewed payload to md_native_* while the old backend remains authoritative.
|
||||
Never restores business tables, changes snapshots, triggers jobs or deletes entities.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
HELPER = ROOT / 'script/datagov/remote/data-transfer.py'
|
||||
if not HELPER.is_file():
|
||||
HELPER = Path(__file__).with_name('data-transfer.py')
|
||||
spec = importlib.util.spec_from_file_location('transfer', HELPER)
|
||||
db = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(db)
|
||||
PRIVATE = ROOT / 'script/datagov/runtime/openmetadata-replacement-20261011/migration'
|
||||
REMOTE = False
|
||||
KINDS = {
|
||||
'SERVICE': ('/services/databaseServices', 'connection'),
|
||||
'DATABASE': ('/databases', 'owners,tags,domains,lifeCycle'),
|
||||
'DATABASE_SCHEMA': ('/databaseSchemas', 'owners,tags,domains,lifeCycle'),
|
||||
'TABLE': ('/tables', 'columns,owners,tags,domains,lifeCycle,tableConstraints,tablePartition'),
|
||||
'PIPELINE': ('/pipelines', 'owners,tags'),
|
||||
'DASHBOARD': ('/dashboards', 'owners,tags'),
|
||||
'INGESTION_PIPELINE': ('/services/ingestionPipelines', None),
|
||||
'OWNER_USER': ('/users', None), 'OWNER_TEAM': ('/teams', None),
|
||||
'GLOSSARY_TERM': ('/glossaryTerms', None), 'DOMAIN': ('/domains', None),
|
||||
'SECURITY_TAG': ('/tags', None), 'CLASSIFICATION': ('/classifications', None),
|
||||
'TYPE': ('/metadata/types', 'customProperties'),
|
||||
}
|
||||
ALLOWED = {'id', 'name', 'displayName', 'fullyQualifiedName', 'description', 'version', 'updatedAt',
|
||||
'deleted', 'service', 'database', 'databaseSchema', 'owners', 'tags', 'domains', 'lifeCycle',
|
||||
'columns', 'tableType', 'tableConstraints', 'tablePartition', 'locationPath', 'changeDescription',
|
||||
'serviceType', 'category', 'customProperties', 'schema', 'type', 'parent', 'children', 'glossary'}
|
||||
|
||||
|
||||
def canonical(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
def sha(value):
|
||||
return hashlib.sha256(canonical(value).encode()).hexdigest()
|
||||
|
||||
|
||||
def literal(value):
|
||||
if value is None:
|
||||
return 'NULL'
|
||||
return 'CONVERT(0x' + str(value).encode().hex() + ' USING utf8mb4)'
|
||||
|
||||
|
||||
def rows(query):
|
||||
if not query.startswith('SELECT JSON_OBJECT(') or ' FROM ' not in query:
|
||||
raise ValueError('Expected structured metadata query')
|
||||
# mysql batch output escapes backslashes; transport JSON as hex for exact round trips.
|
||||
encoded = query.replace('SELECT JSON_OBJECT(', 'SELECT HEX(JSON_OBJECT(', 1).replace(' FROM ', ') FROM ', 1)
|
||||
return [json.loads(bytes.fromhex(line).decode()) for line in db.sql(encoded).splitlines()]
|
||||
|
||||
|
||||
def api_client():
|
||||
container = db.own('m2-openmetadata')
|
||||
port = container['NetworkSettings']['Ports']['8585/tcp'][0]['HostPort']
|
||||
secret = Path('/opt/aixun-datagov/m2/local/secrets/openmetadata-token') if REMOTE else ROOT / 'script/datagov/m2/local/secrets/openmetadata-token'
|
||||
token = secret.read_text().strip()
|
||||
|
||||
def get(path):
|
||||
request = urllib.request.Request('http://127.0.0.1:' + port + '/api/v1' + path,
|
||||
headers={'Authorization': 'Bearer ' + token}, method='GET')
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
return json.load(response)
|
||||
return get
|
||||
|
||||
|
||||
def listing(get, path, fields):
|
||||
result, seen, after, total = [], set(), None, None
|
||||
for _ in range(1000):
|
||||
params = {'include': 'all', 'limit': 100}
|
||||
if fields:
|
||||
params['fields'] = fields
|
||||
if after:
|
||||
params['after'] = after
|
||||
body = get(path + '?' + urllib.parse.urlencode(params))
|
||||
current = body.get('paging', {}).get('total')
|
||||
if total is not None and current != total:
|
||||
raise RuntimeError('Source count changed during export; reconcile snapshot')
|
||||
total = current
|
||||
for entity in body['data']:
|
||||
if entity['id'] in seen:
|
||||
raise RuntimeError('Repeated source identity')
|
||||
seen.add(entity['id'])
|
||||
result.append(entity)
|
||||
after = body.get('paging', {}).get('after')
|
||||
if not after:
|
||||
if total is not None and total != len(result):
|
||||
raise RuntimeError('Incomplete source collection')
|
||||
return result
|
||||
raise RuntimeError('Source pagination bound reached')
|
||||
|
||||
|
||||
def inventory(batch):
|
||||
db.own('mysql')
|
||||
get = api_client()
|
||||
raw = {kind: listing(get, path, fields) for kind, (path, fields) in KINDS.items()}
|
||||
sources = rows("SELECT JSON_OBJECT('id',data_source_id,'org',org_scope_id,'host',host_name,'port',port_no,"
|
||||
"'database',database_name,'user',user_name,'version',version) FROM dg_data_source WHERE del_flag='0'")
|
||||
ownership = {}
|
||||
for service in raw['SERVICE']:
|
||||
c = service.get('connection', {}).get('config', {})
|
||||
matches = [s for s in sources if str(s['host']) + ':' + str(s['port']) == c.get('hostPort')
|
||||
and s['database'] == (c.get('databaseSchema') or c.get('database')) and s['user'] == c.get('username')]
|
||||
if len(matches) == 1 and matches[0]['org'] > 0:
|
||||
ownership[service['id']] = matches[0]
|
||||
entities = []
|
||||
for kind, values in raw.items():
|
||||
for value in values:
|
||||
service_id = value['id'] if kind == 'SERVICE' else value.get('service', {}).get('id')
|
||||
source = ownership.get(service_id)
|
||||
payload = {k: v for k, v in value.items() if k in ALLOWED}
|
||||
# Service connections and user authentication/permissions are never retained.
|
||||
if kind == 'TYPE':
|
||||
category = str(value.get('category', '')).upper()
|
||||
if category not in ('ENTITY', 'FIELD'):
|
||||
raise RuntimeError('Unrecognized type category')
|
||||
payload['category'] = category
|
||||
entities.append({'id': value['id'], 'kind': kind, 'org': source['org'] if source else None,
|
||||
'source': source['id'] if source else None, 'service': service_id,
|
||||
'parent': (value.get('databaseSchema') or value.get('database') or value.get('service') or {}).get('id'),
|
||||
'payload': payload})
|
||||
relations = {}
|
||||
for kind, resource in (('TABLE', 'table'), ('PIPELINE', 'pipeline'), ('DASHBOARD', 'dashboard')):
|
||||
for entity in raw[kind]:
|
||||
if entity.get('deleted'):
|
||||
continue
|
||||
graph = get('/lineage/' + resource + '/' + entity['id'] + '?upstreamDepth=1&downstreamDepth=1')
|
||||
nodes = {n['id']: str(n['type']).upper() for n in graph.get('nodes', [])}
|
||||
nodes[entity['id']] = kind
|
||||
for edge in graph.get('upstreamEdges', []) + graph.get('downstreamEdges', []):
|
||||
source, target = edge['fromEntity'], edge['toEntity']
|
||||
fields = [{'fromField': f, 'toField': mapping['toColumn']}
|
||||
for mapping in (edge.get('lineageDetails') or {}).get('columnsLineage', [])
|
||||
for f in mapping.get('fromColumns', [])]
|
||||
item = {'from': source, 'to': target, 'fromKind': nodes[source], 'toKind': nodes[target], 'fields': fields}
|
||||
relations[sha([source, target])] = item
|
||||
receipts = rows("SELECT JSON_OBJECT('org',c.org_id,'source',c.source_data_source_id,'sourceVersion',c.source_data_source_version,"
|
||||
"'pipeline',r.external_pipeline_id,'pipelineFqn',r.external_pipeline_fqn,'run',r.run_id,'request',q.request_id) "
|
||||
"FROM md_ingestion_connector c JOIN md_ingestion_run r ON r.connector_id=c.connector_id AND r.org_id=c.org_id "
|
||||
"JOIN md_ingestion_request q ON q.org_id=r.org_id AND q.response_entity_id=r.run_id AND q.action_type='RUN' "
|
||||
"WHERE c.del_flag='0' AND r.del_flag='0' AND q.del_flag='0' AND q.request_status='COMPLETED' "
|
||||
"AND r.run_status='SUCCEEDED' AND c.binding_mode='DATA_SOURCE' ORDER BY r.run_id")
|
||||
pipelines = {p['id']: p for p in raw['INGESTION_PIPELINE']}
|
||||
bindings = {}
|
||||
for receipt in receipts:
|
||||
pipeline = pipelines.get(receipt['pipeline'])
|
||||
if not pipeline:
|
||||
continue
|
||||
service = pipeline.get('service', {})
|
||||
source = ownership.get(service.get('id'))
|
||||
if not source or source['id'] != receipt['source'] or source['org'] != receipt['org']:
|
||||
raise RuntimeError('Successful receipt does not match source identity')
|
||||
bindings[(receipt['org'], receipt['source'], service['id'])] = dict(receipt, service=service['id'], serviceFqn=service.get('fullyQualifiedName') or service['name'])
|
||||
payload = {'batch': batch, 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
'entities': entities, 'relations': relations, 'bindings': list(bindings.values())}
|
||||
directory = PRIVATE / batch
|
||||
directory.mkdir(parents=True, mode=0o700, exist_ok=False)
|
||||
db.save(directory / 'payload.json', payload)
|
||||
report = {'batch': batch, 'sha256': db.sha(directory / 'payload.json'), 'entities': {k: len(v) for k, v in raw.items()},
|
||||
'mapped_services': len(ownership), 'quarantined_services': len(raw['SERVICE'])-len(ownership),
|
||||
'relations': len(relations), 'successful_receipt_bindings': len(bindings), 'business_tables_changed': 0}
|
||||
db.save(directory / 'report.json', report)
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
def import_payload(batch):
|
||||
directory = PRIVATE / batch
|
||||
report = json.loads((directory / 'report.json').read_text())
|
||||
if db.sha(directory / 'payload.json') != report['sha256']:
|
||||
raise RuntimeError('Migration payload checksum mismatch')
|
||||
payload = json.loads((directory / 'payload.json').read_text())
|
||||
mode = db.sql("SELECT backend FROM md_native_cutover WHERE domain_key='metadata'")
|
||||
if mode not in ('OPENMETADATA', 'SHADOW'):
|
||||
raise RuntimeError('Import refused after native cutover')
|
||||
statements = ["CREATE TEMPORARY TABLE native_import_assertion (ok INT CHECK(ok=1))", "START TRANSACTION",
|
||||
"SELECT backend FROM md_native_cutover WHERE domain_key='metadata' FOR UPDATE",
|
||||
"INSERT INTO native_import_assertion SELECT IF(backend IN ('OPENMETADATA','SHADOW'),1,0) FROM md_native_cutover WHERE domain_key='metadata'",
|
||||
"INSERT INTO native_import_assertion SELECT IF(COUNT(*)=0,1,0) FROM md_native_entity WHERE row_version<>0"]
|
||||
for e in payload['entities']:
|
||||
p = e['payload']; digest = sha(p)
|
||||
if e['kind']=='TYPE':
|
||||
statements.append("DELETE FROM md_native_entity WHERE entity_kind='TYPE' AND entity_name="+literal(p['name'])+" AND entity_id<>"+literal(e['id'])+" AND row_version=0 AND JSON_EXTRACT(payload,'$.nativeSeed')=TRUE")
|
||||
updated = p.get('updatedAt')
|
||||
observed = datetime.datetime.fromtimestamp(updated/1000, datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f') if updated else None
|
||||
values = [e['id'], e['kind'], e['org'], e['source'], e['service'], e['parent'], p['name'], p.get('fullyQualifiedName') or p['name'],
|
||||
canonical(p), p.get('version') or 0, int(bool(p.get('deleted'))), observed]
|
||||
statements.append("INSERT INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,deleted_flag,observed_at) VALUES("+
|
||||
','.join(map(literal, values))+") ON DUPLICATE KEY UPDATE org_id=VALUES(org_id),source_id=VALUES(source_id),service_id=VALUES(service_id),parent_id=VALUES(parent_id),entity_name=VALUES(entity_name),fqn=VALUES(fqn),payload=VALUES(payload),external_version=VALUES(external_version),deleted_flag=VALUES(deleted_flag),observed_at=VALUES(observed_at)")
|
||||
statements.append("INSERT INTO md_native_migration_item(batch_id,entity_kind,entity_id,source_sha,target_sha,migration_state) VALUES("+
|
||||
','.join(map(literal, [batch,e['kind'],e['id'],digest,digest,'IMPORTED']))+") ON DUPLICATE KEY UPDATE source_sha=VALUES(source_sha),target_sha=VALUES(target_sha)")
|
||||
for id, e in payload['relations'].items():
|
||||
statements.append("INSERT INTO md_native_relation(relation_id,from_kind,from_id,to_kind,to_id,field_mappings,evidence_ref) VALUES("+
|
||||
','.join(map(literal,[id,e['fromKind'],e['from'],e['toKind'],e['to'],canonical(e['fields']),'OPENMETADATA:'+batch]))+") ON DUPLICATE KEY UPDATE field_mappings=VALUES(field_mappings)")
|
||||
for b in payload['bindings']:
|
||||
statements.append("INSERT INTO md_native_source_binding(org_id,source_id,source_version,service_id,service_fqn,pipeline_id,pipeline_fqn,evidence_run_id,evidence_request_id) VALUES("+
|
||||
','.join(map(literal,[b['org'],b['source'],b['sourceVersion'],b['service'],b['serviceFqn'],b['pipeline'],b['pipelineFqn'],b['run'],b['request']]))+") ON DUPLICATE KEY UPDATE source_version=VALUES(source_version),pipeline_id=VALUES(pipeline_id),pipeline_fqn=VALUES(pipeline_fqn),evidence_run_id=VALUES(evidence_run_id),evidence_request_id=VALUES(evidence_request_id)")
|
||||
statements.append('COMMIT')
|
||||
attempt = directory / 'import-attempt.json'
|
||||
if attempt.exists():
|
||||
raise RuntimeError('Prior import attempt exists; reconcile before retry')
|
||||
db.save(attempt, {'payload_sha256': report['sha256'], 'state': 'STARTED'})
|
||||
db.sql(';\n'.join(statements)+';')
|
||||
verified = int(db.sql('SELECT COUNT(*) FROM md_native_migration_item WHERE batch_id='+literal(batch)))
|
||||
if verified != len(payload['entities']):
|
||||
raise RuntimeError('Import count mismatch; reconcile')
|
||||
verify_payload(batch)
|
||||
db.save(directory/'import-result.json', {'state':'IMPORTED','entities':verified,'payload_sha256':report['sha256']})
|
||||
print(json.dumps({'state':'IMPORTED','entities':verified,'backend_unchanged':True}))
|
||||
|
||||
|
||||
def verify_payload(batch):
|
||||
directory = PRIVATE / batch
|
||||
payload = json.loads((directory / 'payload.json').read_text())
|
||||
stored = {(e['kind'], e['id']): e for e in rows("SELECT JSON_OBJECT('kind',entity_kind,'id',entity_id,'payload',payload,'org',org_id,'source',source_id) FROM md_native_entity")}
|
||||
for entity in payload['entities']:
|
||||
actual = stored.get((entity['kind'], entity['id']))
|
||||
if actual is None or sha(actual['payload']) != sha(entity['payload']) or actual['org'] != entity['org'] or actual['source'] != entity['source']:
|
||||
raise RuntimeError('Native payload readback mismatch')
|
||||
actual_edges = {e['id']: e for e in rows("SELECT JSON_OBJECT('id',relation_id,'from',from_id,'to',to_id,'fields',field_mappings) FROM md_native_relation")}
|
||||
for identity, edge in payload['relations'].items():
|
||||
actual = actual_edges.get(identity)
|
||||
if actual is None or any(actual[k] != edge[k] for k in ('from','to','fields')):
|
||||
raise RuntimeError('Native lineage readback mismatch')
|
||||
result = {'state':'VERIFIED','entities':len(payload['entities']),'relations':len(payload['relations']),'payload_sha256':db.sha(directory/'payload.json')}
|
||||
db.save(directory/'verify-result.json', result)
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
def main():
|
||||
global PRIVATE, REMOTE
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('action',choices=['inventory','import','verify','cutover','init-empty'])
|
||||
parser.add_argument('--batch',required=True)
|
||||
parser.add_argument('--remote-record',type=Path,help='Existing server release directory; never use local credentials remotely')
|
||||
args=parser.parse_args()
|
||||
if args.remote_record:
|
||||
record=args.remote_record.resolve()
|
||||
if record.parent!=Path('/opt/aixun-datagov/releases') or not (record/'release.json').is_file():
|
||||
parser.error('Invalid remote release directory')
|
||||
REMOTE=True
|
||||
PRIVATE=record/'metadata-migration'
|
||||
if not re.fullmatch('[a-zA-Z0-9_-]{1,64}',args.batch):
|
||||
parser.error('invalid batch')
|
||||
os.umask(0o077)
|
||||
if args.action=='inventory': inventory(args.batch)
|
||||
elif args.action=='import': import_payload(args.batch)
|
||||
elif args.action=='cutover': cutover(args.batch)
|
||||
elif args.action=='init-empty': init_empty(args.batch)
|
||||
else: verify_payload(args.batch)
|
||||
|
||||
|
||||
def cutover(batch):
|
||||
directory = PRIVATE / batch
|
||||
attempt = directory / 'cutover-attempt.json'
|
||||
if attempt.exists():
|
||||
raise RuntimeError('Prior cutover attempt exists; inspect authoritative state before recovery')
|
||||
executor = db.own('m2-om-ingestion')
|
||||
if executor['State']['Running']:
|
||||
raise RuntimeError('Stop legacy ingestion before cutover')
|
||||
verify_payload(batch)
|
||||
if int(db.sql("SELECT COUNT(*) FROM md_ingestion_request WHERE request_status='PROCESSING' AND update_time>NOW()-INTERVAL 5 MINUTE")):
|
||||
raise RuntimeError('Recent ingestion request still processing')
|
||||
state = rows("SELECT JSON_OBJECT('backend',backend,'epoch',epoch) FROM md_native_cutover WHERE domain_key='metadata'")[0]
|
||||
if state['backend'] not in ('OPENMETADATA','SHADOW'):
|
||||
raise RuntimeError('Unexpected authoritative backend')
|
||||
db.save(attempt, {'before':state,'payload_sha256':db.sha(directory/'payload.json'),'state':'STARTED'})
|
||||
db.sql("CREATE TEMPORARY TABLE native_cutover_assertion(ok INT CHECK(ok=1)); START TRANSACTION; "
|
||||
"SELECT backend FROM md_native_cutover WHERE domain_key='metadata' FOR UPDATE; "
|
||||
"UPDATE md_native_cutover SET backend='NATIVE',epoch=epoch+1,changed_at=NOW(6) "
|
||||
"WHERE domain_key='metadata' AND backend="+literal(state['backend'])+" AND epoch="+str(state['epoch'])+"; "
|
||||
"INSERT INTO native_cutover_assertion VALUES(ROW_COUNT()); COMMIT;")
|
||||
actual=rows("SELECT JSON_OBJECT('backend',backend,'epoch',epoch,'writeEnabled',write_enabled) FROM md_native_cutover WHERE domain_key='metadata'")[0]
|
||||
if actual['backend']!='NATIVE' or actual['epoch']!=state['epoch']+1:
|
||||
raise RuntimeError('Cutover result requires reconciliation')
|
||||
db.save(directory/'cutover-result.json',actual)
|
||||
print(json.dumps(actual))
|
||||
|
||||
|
||||
def init_empty(batch):
|
||||
"""Explicit fresh-install action, after schema migration and before application startup."""
|
||||
mode=db.sql("SELECT backend FROM md_native_cutover WHERE domain_key='metadata'")
|
||||
if mode=='NATIVE':
|
||||
print(json.dumps({'state':'ALREADY_NATIVE','runtimeMutation':False}));return
|
||||
if mode!='OPENMETADATA':raise RuntimeError('Unexpected fresh-install state')
|
||||
directory=PRIVATE/batch;directory.mkdir(mode=0o700,parents=True,exist_ok=False)
|
||||
count="(SELECT COUNT(*) FROM md_ingestion_connector)+(SELECT COUNT(*) FROM md_entity_projection)+(SELECT COUNT(*) FROM asset_detail_asset)+(SELECT COUNT(*) FROM md_native_entity WHERE entity_kind<>'TYPE')+(SELECT COUNT(*) FROM md_native_relation)"
|
||||
if int(db.sql('SELECT '+count))!=0:raise RuntimeError('Existing metadata requires inventory, import and explicit cutover')
|
||||
db.save(directory/'init-attempt.json',{'state':'STARTED'})
|
||||
db.sql("CREATE TEMPORARY TABLE native_init_assertion(ok INT CHECK(ok=1)); START TRANSACTION; "
|
||||
"SELECT backend FROM md_native_cutover WHERE domain_key='metadata' FOR UPDATE; "
|
||||
"INSERT INTO native_init_assertion SELECT IF("+count+"=0,1,0); "
|
||||
"UPDATE md_native_cutover SET backend='NATIVE',epoch=epoch+1,changed_at=NOW(6) WHERE domain_key='metadata' AND backend='OPENMETADATA'; "
|
||||
"INSERT INTO native_init_assertion VALUES(ROW_COUNT()); COMMIT;")
|
||||
if db.sql("SELECT backend FROM md_native_cutover WHERE domain_key='metadata'")!='NATIVE':raise RuntimeError('Fresh initialization requires reconciliation')
|
||||
result={'state':'INITIALIZED_NATIVE','existingBusinessDataChanged':False};db.save(directory/'init-result.json',result);print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try: main()
|
||||
except Exception as exc:
|
||||
print(json.dumps({'state':'FAILED','error_type':type(exc).__name__,'detail':'Sensitive output withheld; reconcile before retry'}))
|
||||
raise SystemExit(1)
|
||||
在新工单中引用
屏蔽一个用户