文件
AiXun-DataGov/script/datagov/native-metadata-nacos.py
2026-11-20 15:32:57 +08:00

55 行
4.0 KiB
Python

#!/usr/bin/env python3
"""Remove only the retired metadata configuration from the live Integration data ID."""
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import urllib.parse
import urllib.request
ROOT=Path(__file__).resolve().parents[2]
spec=importlib.util.spec_from_file_location('m',ROOT/'script/datagov/native-metadata-migrate.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
FOLDER=ROOT/'script/datagov/runtime/openmetadata-replacement-20261011/recovery/nacos-integration'
def main(action):
m.db.own('nacos')
env=dict(line.split('=',1) for line in (ROOT/'script/datagov/.env.datagov').read_text().splitlines() if '=' in line and not line.startswith('#'))
base='http://127.0.0.1:'+env['AIXUN_DATAGOV_NACOS_CLIENT_PORT']+'/nacos/v3/'
login=urllib.parse.urlencode({'username':env['AIXUN_DATAGOV_NACOS_USERNAME'],'password':env['AIXUN_DATAGOV_NACOS_PASSWORD']}).encode()
with urllib.request.urlopen(base+'auth/user/login',data=login,timeout=10) as r:token=json.load(r)['accessToken']
params={'dataId':'aixun-integration.yml','groupName':'AIXUN_DATAGOV_GROUP','namespaceId':'aixun-datagov-local'}
def get():
request=urllib.request.Request(base+'admin/cs/config?'+urllib.parse.urlencode(params),headers={'Authorization':'Bearer '+token})
with urllib.request.urlopen(request,timeout=15) as r:body=json.load(r)
if body.get('code')!=0:raise RuntimeError('Config read failed')
data=body['data'];return data if isinstance(data,str) else data['content']
FOLDER.mkdir(mode=0o700,parents=True,exist_ok=True)
before=get()
if action=='prepare':
if (FOLDER/'before.yml').exists():raise RuntimeError('Preparation already exists; reconcile first')
ruby="require 'yaml'; c=YAML.safe_load(STDIN.read, [], [], true); d=c.fetch('datagov'); d.delete('openmetadata'); e=d['external-entry']; if e; e.delete('openmetadata-url'); d.delete('external-entry') if e.empty?; end; d.fetch('m2').delete('openmetadata'); STDOUT.write(YAML.dump(c))"
after=subprocess.check_output(['ruby','-e',ruby],input=before.encode()).decode()
(FOLDER/'before.yml').write_text(before);(FOLDER/'after.yml').write_text(after)
m.db.save(FOLDER/'plan.json',{'dataId':params['dataId'],'before_sha256':hashlib.sha256(before.encode()).hexdigest(),'after_sha256':hashlib.sha256(after.encode()).hexdigest(),'removed':['datagov.openmetadata','datagov.external-entry.openmetadata-url','datagov.m2.openmetadata']})
print('Prepared one Integration config; runtime unchanged.')
else:
if m.db.sql("SELECT backend FROM md_native_cutover WHERE domain_key='metadata'")!='NATIVE':raise RuntimeError('Native cutover required first')
if before!=(FOLDER/'before.yml').read_text():raise RuntimeError('Live configuration changed; do not overwrite')
attempt=FOLDER/'apply-attempt.json'
if attempt.exists():raise RuntimeError('Prior attempt exists; reconcile before retry')
after=(FOLDER/'after.yml').read_text();m.db.save(attempt,{'state':'STARTED'})
request=urllib.request.Request(base+'admin/cs/config',data=urllib.parse.urlencode(dict(params,content=after,type='yaml')).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/x-www-form-urlencoded'},method='POST')
with urllib.request.urlopen(request,timeout=15) as r:body=json.load(r)
if body.get('code')!=0 or get()!=after:raise RuntimeError('Configuration write not confirmed; reconcile')
m.db.save(FOLDER/'apply-result.json',{'state':'APPLIED','readback':'PASS'})
print('Integration configuration updated and read back; other data IDs unchanged.')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','apply']);a=p.parse_args();os.umask(0o077)
try:main(a.action)
except Exception as e:print(json.dumps({'state':'FAILED','error_type':type(e).__name__,'detail':'Configuration and credentials withheld; reconcile before retry'}));raise SystemExit(1)