Initial project source
这个提交包含在:
@@ -0,0 +1,14 @@
|
||||
security:
|
||||
captcha:
|
||||
enabled: false
|
||||
type: math
|
||||
numberLength: 1
|
||||
charLength: 4
|
||||
|
||||
user:
|
||||
password:
|
||||
maxRetryCount: 5
|
||||
lockTime: 10
|
||||
|
||||
justauth:
|
||||
address: http://127.0.0.1:28000
|
||||
@@ -0,0 +1,82 @@
|
||||
security:
|
||||
ignore:
|
||||
whites:
|
||||
- /auth/code
|
||||
- /auth/logout
|
||||
- /auth/login
|
||||
- /auth/register
|
||||
- /system/config/configKey/sys.login.brand
|
||||
- /resource/message/close
|
||||
- /internal/integration/v1/m2/stages/**
|
||||
- /*/v3/api-docs
|
||||
- /*/error
|
||||
- /csrf
|
||||
|
||||
spring:
|
||||
cloud:
|
||||
gateway:
|
||||
requestLog: true
|
||||
httpclient:
|
||||
max-conn-total: 500
|
||||
max-conn-per-route: 200
|
||||
connection-request-timeout: 3s
|
||||
# 普通管理接口失败关闭,避免客户端超时后请求继续长期占用Gateway资源。
|
||||
response-timeout: 10s
|
||||
# 仅/internal/integration/v1/m2/stages及其子路径保留M2外部就绪长等待。
|
||||
m2-callback-response-timeout: 450s
|
||||
# 仅精确数字ID的数据源连接测试路径等待SeaTunnel归一化结果;普通接口仍为10秒。
|
||||
data-source-connection-test-response-timeout: 75s
|
||||
# 仅统一数据采集逐表提交等待建表、READY和外部提交;其他DataOps接口仍为10秒。
|
||||
unified-ingestion-submit-response-timeout: 180s
|
||||
# 仅画像创建及数字ID重试等待同步执行完成;其他Governance接口仍为10秒。
|
||||
data-profile-execution-response-timeout: 120s
|
||||
validate-after-inactivity: 30s
|
||||
server:
|
||||
webmvc:
|
||||
discovery:
|
||||
locator:
|
||||
lowerCaseServiceId: true
|
||||
enabled: true
|
||||
routes:
|
||||
- id: aixun-datagov-auth
|
||||
uri: lb://aixun-datagov-auth
|
||||
predicates:
|
||||
- Path=/auth/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: aixun-datagov-system
|
||||
uri: lb://aixun-datagov-system
|
||||
predicates:
|
||||
- Path=/system/**,/monitor/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: aixun-datagov-resource
|
||||
uri: lb://aixun-datagov-resource
|
||||
predicates:
|
||||
- Path=/resource/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- id: aixun-integration
|
||||
uri: lb://aixun-integration
|
||||
predicates:
|
||||
- Path=/api/integration/**
|
||||
- id: aixun-integration-m2-callback
|
||||
uri: lb://aixun-integration
|
||||
predicates:
|
||||
- Path=/internal/integration/v1/m2/stages/**
|
||||
- id: aixun-dataops
|
||||
uri: lb://aixun-dataops
|
||||
predicates:
|
||||
- Path=/api/dataops/**
|
||||
- id: aixun-governance
|
||||
uri: lb://aixun-governance
|
||||
predicates:
|
||||
- Path=/api/governance/**
|
||||
- id: aixun-dataproduct
|
||||
uri: lb://aixun-dataproduct
|
||||
predicates:
|
||||
- Path=/api/dataproduct/**
|
||||
|
||||
server:
|
||||
jetty:
|
||||
max-http-form-post-size: 100MB
|
||||
@@ -0,0 +1,37 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
primary: master
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
|
||||
message:
|
||||
enabled: false
|
||||
transport: sse
|
||||
path: /message
|
||||
allowedOrigins: http://127.0.0.1:28000
|
||||
sse-timeout: 86400000
|
||||
heartbeat-interval: 60
|
||||
web-socket-send-time-limit: 10000
|
||||
web-socket-buffer-size-limit: 64000
|
||||
|
||||
mail:
|
||||
enabled: false
|
||||
|
||||
sms:
|
||||
enabled: false
|
||||
config-type: yaml
|
||||
restricted: true
|
||||
blends: {}
|
||||
|
||||
aixun:
|
||||
datagov:
|
||||
local-file:
|
||||
enabled: true
|
||||
root: ${AIXUN_DATAGOV_FILE_ROOT:/var/lib/aixun-datagov/files}
|
||||
max-bytes: 10485760
|
||||
@@ -0,0 +1,11 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
primary: master
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
@@ -0,0 +1,45 @@
|
||||
management:
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
dynamic:
|
||||
primary: master
|
||||
strict: true
|
||||
seata: false
|
||||
hikari:
|
||||
schema: ${DM_SCHEMA}
|
||||
maxPoolSize: 20
|
||||
minIdle: 10
|
||||
connectionTimeout: 3000
|
||||
validationTimeout: 2000
|
||||
idleTimeout: 600000
|
||||
maxLifetime: 1800000
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
|
||||
datasource:
|
||||
system-master:
|
||||
# Dedicated DataGov user owns the platform schema; no system-user fallback.
|
||||
url: jdbc:dm://${DM_HOST}:${DM_PORT:5236}
|
||||
username: ${DM_USERNAME}
|
||||
password: ${DM_PASSWORD}
|
||||
|
||||
datagov:
|
||||
unit: dataops
|
||||
enabled: true
|
||||
ingestion:
|
||||
commands:
|
||||
enabled: true
|
||||
m2:
|
||||
integration-api-url: http://integration:9310
|
||||
reconciliation-delay-ms: 15000
|
||||
@@ -0,0 +1,41 @@
|
||||
management:
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
dynamic:
|
||||
primary: master
|
||||
strict: true
|
||||
seata: false
|
||||
hikari:
|
||||
schema: ${DM_SCHEMA}
|
||||
maxPoolSize: 20
|
||||
minIdle: 10
|
||||
connectionTimeout: 3000
|
||||
validationTimeout: 2000
|
||||
idleTimeout: 600000
|
||||
maxLifetime: 1800000
|
||||
keepaliveTime: 30000
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
|
||||
datasource:
|
||||
system-master:
|
||||
# Dedicated DataGov user owns the platform schema; no system-user fallback.
|
||||
url: jdbc:dm://${DM_HOST}:${DM_PORT:5236}
|
||||
username: ${DM_USERNAME}
|
||||
password: ${DM_PASSWORD}
|
||||
|
||||
datagov:
|
||||
unit: dataproduct
|
||||
enabled: true
|
||||
external-data-path: NOT_CONFIGURED
|
||||
@@ -0,0 +1,39 @@
|
||||
management:
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
dynamic:
|
||||
primary: master
|
||||
strict: true
|
||||
seata: false
|
||||
hikari:
|
||||
schema: ${DM_SCHEMA}
|
||||
maxPoolSize: 20
|
||||
minIdle: 10
|
||||
connectionTimeout: 3000
|
||||
validationTimeout: 2000
|
||||
idleTimeout: 600000
|
||||
maxLifetime: 1800000
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
|
||||
datasource:
|
||||
system-master:
|
||||
# Dedicated DataGov user owns the platform schema; no system-user fallback.
|
||||
url: jdbc:dm://${DM_HOST}:${DM_PORT:5236}
|
||||
username: ${DM_USERNAME}
|
||||
password: ${DM_PASSWORD}
|
||||
|
||||
datagov:
|
||||
unit: governance
|
||||
enabled: true
|
||||
@@ -0,0 +1,77 @@
|
||||
management:
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
dynamic:
|
||||
primary: master
|
||||
strict: true
|
||||
seata: false
|
||||
hikari:
|
||||
schema: ${DM_SCHEMA}
|
||||
maxPoolSize: 20
|
||||
minIdle: 10
|
||||
connectionTimeout: 3000
|
||||
validationTimeout: 2000
|
||||
idleTimeout: 600000
|
||||
maxLifetime: 1800000
|
||||
datasource:
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
|
||||
datasource:
|
||||
system-master:
|
||||
# Dedicated DataGov user owns the platform schema; no system-user fallback.
|
||||
url: jdbc:dm://${DM_HOST}:${DM_PORT:5236}
|
||||
username: ${DM_USERNAME}
|
||||
password: ${DM_PASSWORD}
|
||||
|
||||
datagov:
|
||||
unit: integration
|
||||
adapters-enabled: true
|
||||
managed-credentials:
|
||||
root: ${AIXUN_DATAGOV_MANAGED_CREDENTIAL_ROOT:/run/secrets/aixun-datagov}
|
||||
local-non-production: ${AIXUN_DATAGOV_LOCAL_NON_PRODUCTION:false}
|
||||
allow-insecure-local-http: ${AIXUN_DATAGOV_ALLOW_INSECURE_CREDENTIAL_HTTP:false}
|
||||
m2:
|
||||
enabled: ${AIXUN_DATAGOV_M2_ENABLED:false}
|
||||
secret-root: ${AIXUN_DATAGOV_SECRET_ROOT:/run/secrets/aixun-datagov}
|
||||
source:
|
||||
jdbc-url: ${AIXUN_DATAGOV_M2_SOURCE_JDBC_URL:}
|
||||
user: ${AIXUN_DATAGOV_M2_SOURCE_USER:}
|
||||
password-ref: ${AIXUN_DATAGOV_M2_SOURCE_PASSWORD_REF:}
|
||||
seatunnel:
|
||||
api-url: ${AIXUN_DATAGOV_M2_SEATUNNEL_API_URL:}
|
||||
user: ${AIXUN_DATAGOV_M2_SEATUNNEL_USER:}
|
||||
password-ref: ${AIXUN_DATAGOV_M2_SEATUNNEL_PASSWORD_REF:}
|
||||
dolphinscheduler:
|
||||
api-url: ${AIXUN_DATAGOV_M2_DS_API_URL:}
|
||||
token-ref: ${AIXUN_DATAGOV_M2_DS_TOKEN_REF:}
|
||||
project-code: ${AIXUN_DATAGOV_M2_DS_PROJECT_CODE:}
|
||||
project-name: ${AIXUN_DATAGOV_M2_DS_PROJECT_NAME:aixun_m2_golden_project}
|
||||
hive:
|
||||
jdbc-url: ${AIXUN_DATAGOV_M2_HIVE_JDBC_URL:}
|
||||
user: ${AIXUN_DATAGOV_M2_HIVE_USER:}
|
||||
password-ref: ${AIXUN_DATAGOV_M2_HIVE_PASSWORD_REF:}
|
||||
doris:
|
||||
jdbc-url: ${AIXUN_DATAGOV_M2_DORIS_JDBC_URL:}
|
||||
user: ${AIXUN_DATAGOV_M2_DORIS_USER:}
|
||||
password-ref: ${AIXUN_DATAGOV_M2_DORIS_PASSWORD_REF:}
|
||||
query-user: ${AIXUN_DATAGOV_M2_DORIS_QUERY_USER:}
|
||||
query-password-ref: ${AIXUN_DATAGOV_M2_DORIS_QUERY_PASSWORD_REF:}
|
||||
max-rows: 100
|
||||
max-bytes: 1048576
|
||||
max-page-size: 50
|
||||
download-enabled: false
|
||||
timeout-seconds: 5
|
||||
max-concurrency: 2
|
||||
queries-per-minute: 10
|
||||
callback-token-ref: ${AIXUN_DATAGOV_M2_CALLBACK_TOKEN_REF:}
|
||||
@@ -0,0 +1,126 @@
|
||||
spring:
|
||||
threads:
|
||||
virtual:
|
||||
enabled: true
|
||||
task:
|
||||
execution:
|
||||
thread-name-prefix: datagov-async-
|
||||
mode: force
|
||||
messages:
|
||||
basename: i18n/messages
|
||||
servlet:
|
||||
multipart:
|
||||
max-request-size: 100MB
|
||||
max-file-size: 50MB
|
||||
mvc:
|
||||
static-path-pattern: /static/**
|
||||
format:
|
||||
date-time: yyyy-MM-dd HH:mm:ss
|
||||
jackson:
|
||||
serialization:
|
||||
INDENT_OUTPUT: false
|
||||
fail_on_empty_beans: false
|
||||
deserialization:
|
||||
fail_on_unknown_properties: false
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
namespace: aixun-datagov-local
|
||||
group: AIXUN_DATAGOV_GROUP
|
||||
metadata:
|
||||
username: ${AIXUN_DATAGOV_MONITOR_USERNAME:datagov-monitor}
|
||||
userpassword: ${AIXUN_DATAGOV_MONITOR_PASSWORD:disabled}
|
||||
bus:
|
||||
enabled: false
|
||||
data:
|
||||
redis:
|
||||
host: ${SPRING_DATA_REDIS_HOST}
|
||||
port: ${SPRING_DATA_REDIS_PORT:6379}
|
||||
password: ${SPRING_DATA_REDIS_PASSWORD}
|
||||
database: ${SPRING_DATA_REDIS_DATABASE:11}
|
||||
timeout: 10000
|
||||
ssl.enabled: false
|
||||
|
||||
redisson:
|
||||
keyPrefix: 'aixun:datagov:'
|
||||
threads: 4
|
||||
nettyThreads: 8
|
||||
singleServerConfig:
|
||||
clientName: ${spring.application.name}
|
||||
connectionMinimumIdleSize: 2
|
||||
connectionPoolSize: 16
|
||||
idleConnectionTimeout: 10000
|
||||
timeout: 3000
|
||||
subscriptionConnectionPoolSize: 8
|
||||
|
||||
lock4j:
|
||||
acquire-timeout: 3000
|
||||
expire: 30000
|
||||
|
||||
dubbo:
|
||||
consumer:
|
||||
timeout: 5000
|
||||
custom:
|
||||
request-log: false
|
||||
log-level: info
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health,info,loggers
|
||||
endpoint:
|
||||
health:
|
||||
show-details: WHEN_AUTHORIZED
|
||||
|
||||
logging:
|
||||
level:
|
||||
org.springframework: warn
|
||||
org.apache.dubbo: error
|
||||
com.alibaba.nacos: error
|
||||
org.mybatis.spring.mapper: error
|
||||
config: classpath:logback-plus.xml
|
||||
|
||||
sa-token:
|
||||
token-name: Authorization
|
||||
check-same-token: true
|
||||
is-concurrent: true
|
||||
is-share: false
|
||||
jwt-secret-key: ${AIXUN_DATAGOV_JWT_SECRET}
|
||||
|
||||
mybatis-plus:
|
||||
enableLogicDelete: true
|
||||
mapperPackage: cn.aixunkeji.**.mapper
|
||||
mapperLocations: classpath*:mapper/**/*Mapper.xml
|
||||
typeAliasesPackage: cn.aixunkeji.**.domain
|
||||
global-config:
|
||||
dbConfig:
|
||||
idType: ASSIGN_ID
|
||||
|
||||
mybatis-encryptor:
|
||||
enable: false
|
||||
algorithm: BASE64
|
||||
encode: BASE64
|
||||
|
||||
api-decrypt:
|
||||
enabled: false
|
||||
|
||||
xss:
|
||||
enabled: true
|
||||
excludeUrls:
|
||||
- /system/notice
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
enabled: true
|
||||
info:
|
||||
title: AiXun-DataGov API
|
||||
description: AiXun-DataGov M0 common platform API
|
||||
version: 0.1.0
|
||||
contact:
|
||||
name: 艾讯科技
|
||||
url: https://www.aixunkeji.cn
|
||||
|
||||
seata:
|
||||
enabled: false
|
||||
enable-auto-data-source-proxy: false
|
||||
@@ -0,0 +1,26 @@
|
||||
datasource:
|
||||
system-master:
|
||||
# Dedicated DataGov user owns the platform schema; no system-user fallback.
|
||||
url: jdbc:dm://${DM_HOST}:${DM_PORT:5236}
|
||||
username: ${DM_USERNAME}
|
||||
password: ${DM_PASSWORD}
|
||||
|
||||
mybatis-plus:
|
||||
sql-log:
|
||||
enabled: false
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
dynamic:
|
||||
seata: false
|
||||
strict: true
|
||||
hikari:
|
||||
schema: ${DM_SCHEMA}
|
||||
maxPoolSize: 20
|
||||
minIdle: 2
|
||||
connectionTimeout: 30000
|
||||
validationTimeout: 5000
|
||||
idleTimeout: 600000
|
||||
maxLifetime: 1800000
|
||||
keepaliveTime: 30000
|
||||
文件差异内容过多而无法显示
加载差异
@@ -0,0 +1,5 @@
|
||||
# 将此文件夹下所有配置文件导入到 `grafana` 内生成展示看板
|
||||
|
||||
- `Spring Boot 3.x Statistics.json`: 基于 Grafana dashboard `20727`,用于 Spring Boot 3.x/4.x Micrometer Prometheus 指标。
|
||||
- `SLS JVM监控大盘.json`: 基于 Grafana dashboard `4701`,用于 JVM Micrometer 指标。
|
||||
- `Nacos.json`: 基于 Grafana dashboard `13221`,用于 Nacos Prometheus 指标。
|
||||
文件差异内容过多而无法显示
加载差异
文件差异内容过多而无法显示
加载差异
@@ -0,0 +1 @@
|
||||
# 将此文件夹下所有配置文件内容复制到 `nacos` 对应的配置中
|
||||
@@ -0,0 +1,103 @@
|
||||
# 安全配置
|
||||
security:
|
||||
# 验证码
|
||||
captcha:
|
||||
# 是否开启验证码
|
||||
enabled: true
|
||||
# 验证码类型 math 数组计算 char 字符验证
|
||||
type: math
|
||||
# 数字验证码位数
|
||||
numberLength: 1
|
||||
# 字符验证码长度
|
||||
charLength: 4
|
||||
|
||||
# 用户配置
|
||||
user:
|
||||
password:
|
||||
# 密码最大错误次数
|
||||
maxRetryCount: 5
|
||||
# 密码锁定时间(默认10分钟)
|
||||
lockTime: 10
|
||||
|
||||
# 三方授权
|
||||
justauth:
|
||||
# 前端外网访问地址
|
||||
address: http://localhost:80
|
||||
type:
|
||||
maxkey:
|
||||
# maxkey 服务器地址
|
||||
# 注意 如下均配置均不需要修改 maxkey 已经内置好了数据
|
||||
server-url: http://sso.maxkey.top
|
||||
client-id: 876892492581044224
|
||||
client-secret: x1Y5MTMwNzIwMjMxNTM4NDc3Mzche8
|
||||
redirect-uri: ${justauth.address}/social-callback?source=maxkey
|
||||
topiam:
|
||||
# topiam 服务器地址
|
||||
server-url: http://127.0.0.1:1989/api/v1/authorize/y0q************spq***********8ol
|
||||
client-id: 449c4*********937************759
|
||||
client-secret: ac7***********1e0************28d
|
||||
redirect-uri: ${justauth.address}/social-callback?source=topiam
|
||||
scopes: [ openid, email, phone, profile ]
|
||||
qq:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=qq
|
||||
union-id: false
|
||||
weibo:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=weibo
|
||||
gitee:
|
||||
client-id: 91436b7940090d09c72c7daf85b959cfd5f215d67eea73acbf61b6b590751a98
|
||||
client-secret: 02c6fcfd70342980cd8dd2f2c06c1a350645d76c754d7a264c4e125f9ba915ac
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitee
|
||||
dingtalk:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=dingtalk
|
||||
baidu:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=baidu
|
||||
csdn:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=csdn
|
||||
coding:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=coding
|
||||
coding-group-name: xx
|
||||
oschina:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=oschina
|
||||
alipay_wallet:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=alipay_wallet
|
||||
alipay-public-key: MIIB**************DAQAB
|
||||
wechat_open:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=wechat_open
|
||||
wechat_mp:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=wechat_mp
|
||||
wechat_enterprise:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=wechat_enterprise
|
||||
agent-id: 1000002
|
||||
gitlab:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitlab
|
||||
gitea:
|
||||
# 前端需同步处理刷新令牌与请求重放逻辑
|
||||
# gitea 服务器地址
|
||||
server-url: https://demo.gitea.com
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
@@ -0,0 +1,100 @@
|
||||
# 安全配置
|
||||
security:
|
||||
# 不校验白名单
|
||||
ignore:
|
||||
whites:
|
||||
- /auth/code
|
||||
- /auth/logout
|
||||
- /auth/login
|
||||
- /auth/binding/*
|
||||
- /auth/register
|
||||
- /auth/tenant/list
|
||||
- /resource/sms/code
|
||||
- /resource/message/close
|
||||
- /*/v3/api-docs
|
||||
- /*/error
|
||||
- /csrf
|
||||
- /warm-flow-ui/**
|
||||
- /snail-chat/**
|
||||
- /api/snail/chat/**
|
||||
|
||||
spring:
|
||||
cloud:
|
||||
gateway:
|
||||
# 打印请求日志(自定义)
|
||||
requestLog: true
|
||||
# Gateway MVC 转发使用的 HttpClient5 连接池配置
|
||||
httpclient:
|
||||
# 总最大连接数
|
||||
max-conn-total: 1000
|
||||
# 单个下游路由最大连接数,SSE 长连接较多时需按并发量调整
|
||||
max-conn-per-route: 500
|
||||
# 连接池满时等待可用连接的时间
|
||||
connection-request-timeout: 3s
|
||||
# SSE 场景通常不设置响应超时,避免长连接被网关主动断开
|
||||
# response-timeout: 60s
|
||||
# 连接最大存活时间,不配置则使用 HttpClient5 默认值
|
||||
# connection-time-to-live: 10m
|
||||
# 空闲连接可用性校验间隔
|
||||
validate-after-inactivity: 30s
|
||||
server:
|
||||
webmvc:
|
||||
discovery:
|
||||
locator:
|
||||
lowerCaseServiceId: true
|
||||
enabled: true
|
||||
routes:
|
||||
# 认证中心
|
||||
- id: aixun-auth
|
||||
uri: lb://aixun-auth
|
||||
predicates:
|
||||
- Path=/auth/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# 代码生成
|
||||
- id: aixun-gen
|
||||
uri: lb://aixun-gen
|
||||
predicates:
|
||||
- Path=/tool/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# 系统模块
|
||||
- id: aixun-system
|
||||
uri: lb://aixun-system
|
||||
predicates:
|
||||
- Path=/system/**,/monitor/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# 资源服务
|
||||
- id: aixun-resource
|
||||
uri: lb://aixun-resource
|
||||
predicates:
|
||||
- Path=/resource/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# workflow服务
|
||||
- id: aixun-workflow
|
||||
uri: lb://aixun-workflow
|
||||
predicates:
|
||||
- Path=/workflow/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# warm-flow服务
|
||||
- id: warm-flow
|
||||
uri: lb://aixun-workflow
|
||||
predicates:
|
||||
- Path=/warm-flow-ui/**,/warm-flow/**
|
||||
# 演示服务
|
||||
- id: aixun-demo
|
||||
uri: lb://aixun-demo
|
||||
predicates:
|
||||
- Path=/demo/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
# MQ演示服务
|
||||
- id: aixun-test-mq
|
||||
uri: lb://aixun-test-mq
|
||||
predicates:
|
||||
- Path=/test-mq/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
@@ -0,0 +1,37 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
# 设置默认的数据源或者数据源组,默认值即为 master
|
||||
primary: master
|
||||
seata: false
|
||||
datasource:
|
||||
# 主库数据源 (主数据源内包含代码生成数据表 增加其他数据库不要修改主数据源 否则数据无法存储)
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: ${datasource.system-oracle.url}
|
||||
# username: ${datasource.system-oracle.username}
|
||||
# password: ${datasource.system-oracle.password}
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: ${datasource.system-postgres.url}
|
||||
# username: ${datasource.system-postgres.username}
|
||||
# password: ${datasource.system-postgres.password}
|
||||
|
||||
# 代码生成
|
||||
gen:
|
||||
# 作者
|
||||
author: LionLi
|
||||
# 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool
|
||||
packageName: cn.aixunkeji.system
|
||||
# 自动去除表前缀,默认是false
|
||||
autoRemovePre: false
|
||||
# 表前缀(生成类名不会包含表前缀,多个用逗号分隔)
|
||||
tablePrefix: sys_
|
||||
@@ -0,0 +1,96 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
# 设置默认的数据源或者数据源组,默认值即为 master
|
||||
primary: master
|
||||
datasource:
|
||||
# 主库数据源
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: ${datasource.system-oracle.url}
|
||||
# username: ${datasource.system-oracle.username}
|
||||
# password: ${datasource.system-oracle.password}
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: ${datasource.system-postgres.url}
|
||||
# username: ${datasource.system-postgres.username}
|
||||
# password: ${datasource.system-postgres.password}
|
||||
|
||||
# 统一消息推送配置
|
||||
message:
|
||||
enabled: true
|
||||
# sse / websocket
|
||||
transport: sse
|
||||
# 统一访问路径
|
||||
path: /message
|
||||
# websocket 允许的跨域来源
|
||||
allowedOrigins: '*'
|
||||
# SSE 连接超时时间,单位毫秒
|
||||
sse-timeout: 86400000
|
||||
# 本地连接心跳检测间隔,单位秒
|
||||
heartbeat-interval: 60
|
||||
# WebSocket 单次发送超时时间,单位毫秒
|
||||
web-socket-send-time-limit: 10000
|
||||
# WebSocket 发送缓冲区大小
|
||||
web-socket-buffer-size-limit: 64000
|
||||
|
||||
mail:
|
||||
enabled: false
|
||||
host: smtp.163.com
|
||||
port: 465
|
||||
# 是否需要用户名密码验证
|
||||
auth: true
|
||||
# 发送方,遵循RFC-822标准
|
||||
from: xxx@163.com
|
||||
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
|
||||
user: xxx@163.com
|
||||
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
|
||||
pass: xxxxxxxxxx
|
||||
# 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。
|
||||
starttlsEnable: true
|
||||
# 使用SSL安全连接
|
||||
sslEnable: true
|
||||
# SMTP超时时长,单位毫秒,缺省值不超时
|
||||
timeout: 0
|
||||
# Socket连接超时值,单位毫秒,缺省值不超时
|
||||
connectionTimeout: 0
|
||||
|
||||
# sms 短信 支持 阿里云 腾讯云 云片 等等各式各样的短信服务商
|
||||
# https://sms4j.com/doc3/ 差异配置文档地址 支持单厂商多配置,可以配置多个同时使用
|
||||
sms:
|
||||
# 配置源类型用于标定配置来源(interface,yaml)
|
||||
config-type: yaml
|
||||
# 用于标定yml中的配置是否开启短信拦截,接口配置不受此限制
|
||||
restricted: true
|
||||
# 短信拦截限制单手机号每分钟最大发送,只对开启了拦截的配置有效
|
||||
minute-max: 1
|
||||
# 短信拦截限制单手机号每日最大发送量,只对开启了拦截的配置有效
|
||||
account-max: 30
|
||||
# 以下配置来自于 org.dromara.sms4j.provider.config.BaseConfig类中
|
||||
blends:
|
||||
# 唯一ID 用于发送短信寻找具体配置 随便定义别用中文即可
|
||||
# 可以同时存在两个相同厂商 例如: ali1 ali2 两个不同的阿里短信账号 也可用于区分租户
|
||||
config1:
|
||||
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: alibaba
|
||||
# 有些称为accessKey有些称之为apiKey,也有称为sdkKey或者appId。
|
||||
access-key-id: 您的accessKey
|
||||
# 称为accessSecret有些称之为apiSecret
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
config2:
|
||||
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: tencent
|
||||
access-key-id: 您的accessKey
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
@@ -0,0 +1,25 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
# 设置默认的数据源或者数据源组,默认值即为 master
|
||||
primary: master
|
||||
datasource:
|
||||
# 主库数据源
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: ${datasource.system-master.url}
|
||||
username: ${datasource.system-master.username}
|
||||
password: ${datasource.system-master.password}
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: ${datasource.system-oracle.url}
|
||||
# username: ${datasource.system-oracle.username}
|
||||
# password: ${datasource.system-oracle.password}
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: ${datasource.system-postgres.url}
|
||||
# username: ${datasource.system-postgres.username}
|
||||
# password: ${datasource.system-postgres.password}
|
||||
@@ -0,0 +1,50 @@
|
||||
spring:
|
||||
datasource:
|
||||
dynamic:
|
||||
# 设置默认的数据源或者数据源组,默认值即为 master
|
||||
primary: master
|
||||
datasource:
|
||||
# 主库数据源
|
||||
master:
|
||||
type: ${spring.datasource.type}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: ${datasource.workflow.url}
|
||||
username: ${datasource.workflow.username}
|
||||
password: ${datasource.workflow.password}
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: ${datasource.system-oracle.url}
|
||||
# username: ${datasource.system-oracle.username}
|
||||
# password: ${datasource.system-oracle.password}
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: ${datasource.system-postgres.url}
|
||||
# username: ${datasource.system-postgres.username}
|
||||
# password: ${datasource.system-postgres.password}
|
||||
|
||||
# warm-flow工作流配置
|
||||
warm-flow:
|
||||
# 是否开启工作流,默认true
|
||||
enabled: true
|
||||
# 是否开启设计器ui
|
||||
ui: true
|
||||
# 是否显示流程图顶部文字
|
||||
top-text-show: true
|
||||
# 是否渲染节点悬浮提示,默认true
|
||||
node-tooltip: true
|
||||
# 默认Authorization,如果有多个token,用逗号分隔
|
||||
token-name: ${sa-token.token-name},clientid
|
||||
|
||||
# LiteFlow 业务规则编排
|
||||
liteflow:
|
||||
# 跟随工作流模块开关,避免禁用工作流时仍加载任务办理链
|
||||
enable: ${warm-flow.enabled:true}
|
||||
metrics:
|
||||
# 指标自动配置使用独立开关,需同步关闭以避免初始化未启用的 LiteFlow
|
||||
enabled: ${liteflow.enable:true}
|
||||
# 工作流模块用于编排任务办理链路
|
||||
rule-source: classpath:liteflow/*.el.xml
|
||||
# 开启虚拟线程
|
||||
enable-virtual-thread: true
|
||||
@@ -0,0 +1,268 @@
|
||||
server:
|
||||
# jetty 配置
|
||||
jetty:
|
||||
# HTTP post内容的最大大小。当值为-1时,默认值为大小是无限的
|
||||
max-http-form-post-size: 1GB
|
||||
|
||||
dubbo:
|
||||
application:
|
||||
# 关闭qos端口避免单机多生产者端口冲突 如需使用自行开启
|
||||
qos-enable: false
|
||||
protocol:
|
||||
# 如需使用 Triple 3.0 新协议 可查看官方文档
|
||||
# 使用 dubbo 协议通信
|
||||
name: dubbo
|
||||
# dubbo 协议端口(-1表示自增端口,从20880开始)
|
||||
port: -1
|
||||
# 指定dubbo协议注册ip
|
||||
# host: 192.168.0.100
|
||||
# 开启虚拟线程
|
||||
threadpool: virtual
|
||||
# 消费者相关配置
|
||||
consumer:
|
||||
# 超时时间
|
||||
timeout: 3000
|
||||
# 自定义配置
|
||||
custom:
|
||||
# 全局请求log
|
||||
request-log: true
|
||||
# info 基础信息 param 参数信息 full 全部
|
||||
log-level: info
|
||||
|
||||
spring:
|
||||
threads:
|
||||
# 开启虚拟线程 仅jdk21可用
|
||||
virtual:
|
||||
enabled: true
|
||||
task:
|
||||
execution:
|
||||
# 从 springboot 3.5 开始 spring自带线程池
|
||||
# 不再需要 AsyncConfig与ThreadPoolConfig 可直接注入线程池使用
|
||||
thread-name-prefix: async-
|
||||
# 由spring自己初始化线程池
|
||||
mode: force
|
||||
# 资源信息
|
||||
messages:
|
||||
# 国际化资源文件路径
|
||||
basename: i18n/messages
|
||||
servlet:
|
||||
multipart:
|
||||
# 整个请求大小限制
|
||||
max-request-size: 1GB
|
||||
# 上传单个文件大小限制
|
||||
max-file-size: 1GB
|
||||
mvc:
|
||||
# 设置静态资源路径 防止所有请求都去查静态资源
|
||||
static-path-pattern: /static/**
|
||||
format:
|
||||
date-time: yyyy-MM-dd HH:mm:ss
|
||||
#jackson配置
|
||||
jackson:
|
||||
serialization:
|
||||
# 格式化输出
|
||||
INDENT_OUTPUT: false
|
||||
# 忽略无法转换的对象
|
||||
fail_on_empty_beans: false
|
||||
deserialization:
|
||||
# 允许对象忽略json中不存在的属性
|
||||
fail_on_unknown_properties: false
|
||||
cloud:
|
||||
inetutils:
|
||||
# 指定全局使用ip网段
|
||||
preferred-networks:
|
||||
# - 192.168
|
||||
# - 10.0
|
||||
nacos:
|
||||
discovery:
|
||||
metadata:
|
||||
# admin 监控账号密码
|
||||
username: aixun
|
||||
userpassword: 123456
|
||||
bus:
|
||||
id: ${spring.application.name}
|
||||
base-packages: cn.aixunkeji.**.event
|
||||
# 消息总线 也可以使用 kafka 参考 spring-cloud-bus 用法
|
||||
rabbitmq:
|
||||
host: localhost
|
||||
port: 5672
|
||||
username: aixun
|
||||
password: aixun123
|
||||
|
||||
# redis通用配置 子服务可以自行配置进行覆盖
|
||||
data:
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
# redis 密码必须配置
|
||||
password: aixun123
|
||||
database: 0
|
||||
# 需要使用数字
|
||||
timeout: 10000
|
||||
ssl.enabled: false
|
||||
|
||||
# redisson 配置
|
||||
redisson:
|
||||
# redis key前缀
|
||||
keyPrefix:
|
||||
# 线程池数量
|
||||
threads: 4
|
||||
# Netty线程池数量
|
||||
nettyThreads: 8
|
||||
# 单节点配置
|
||||
singleServerConfig:
|
||||
# 客户端名称
|
||||
clientName: ${spring.application.name}
|
||||
# 最小空闲连接数
|
||||
connectionMinimumIdleSize: 8
|
||||
# 连接池大小
|
||||
connectionPoolSize: 32
|
||||
# 连接空闲超时,单位:毫秒
|
||||
idleConnectionTimeout: 10000
|
||||
# 命令等待超时,单位:毫秒
|
||||
timeout: 3000
|
||||
# 发布和订阅连接池大小
|
||||
subscriptionConnectionPoolSize: 50
|
||||
|
||||
# 分布式锁 lock4j 全局配置
|
||||
lock4j:
|
||||
# 获取分布式锁超时时间,默认为 3000 毫秒
|
||||
acquire-timeout: 3000
|
||||
# 分布式锁的超时时间,默认为 30 秒
|
||||
expire: 30000
|
||||
|
||||
# 暴露监控端点
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: '*'
|
||||
endpoint:
|
||||
health:
|
||||
show-details: ALWAYS
|
||||
logfile:
|
||||
external-file: ./logs/${spring.application.name}/console.log
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
org.springframework: warn
|
||||
org.apache.dubbo: error
|
||||
com.alibaba.nacos: error
|
||||
org.mybatis.spring.mapper: error
|
||||
org.apache.fury: warn
|
||||
io.micrometer: error
|
||||
# 临时处理 spring 调整日志级别导致启动警告问题 不影响使用等待 alibaba 适配
|
||||
org.springframework.context.support.PostProcessorRegistrationDelegate: error
|
||||
config: classpath:logback-plus.xml
|
||||
|
||||
# Sa-Token配置
|
||||
sa-token:
|
||||
# token名称 (同时也是cookie名称)
|
||||
token-name: Authorization
|
||||
# 开启内网服务调用鉴权(不允许越过gateway访问内网服务 保障服务安全)
|
||||
check-same-token: true
|
||||
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
|
||||
is-concurrent: true
|
||||
# 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
|
||||
is-share: false
|
||||
# jwt秘钥
|
||||
jwt-secret-key: abcdefghijklmnopqrstuvwxyz
|
||||
|
||||
# MyBatisPlus配置
|
||||
# https://baomidou.com/config/
|
||||
mybatis-plus:
|
||||
# 自定义配置 是否全局开启逻辑删除 关闭后 所有逻辑删除功能将失效
|
||||
enableLogicDelete: true
|
||||
# 多包名使用逗号分隔
|
||||
mapperPackage: cn.aixunkeji.**.mapper
|
||||
# 对应的 XML 文件位置
|
||||
mapperLocations: classpath*:mapper/**/*Mapper.xml
|
||||
# 实体扫描,多个package用逗号或者分号分隔
|
||||
typeAliasesPackage: cn.aixunkeji.**.domain
|
||||
global-config:
|
||||
dbConfig:
|
||||
# 主键类型
|
||||
# AUTO 自增 NONE 空 INPUT 用户输入 ASSIGN_ID 雪花 ASSIGN_UUID 唯一 UUID
|
||||
# 如需改为自增 需要将数据库表全部设置为自增
|
||||
idType: ASSIGN_ID
|
||||
|
||||
# 数据加密
|
||||
mybatis-encryptor:
|
||||
# 是否开启加密
|
||||
enable: false
|
||||
# 默认加密算法
|
||||
algorithm: BASE64
|
||||
# 编码方式 BASE64/HEX。默认BASE64
|
||||
encode: BASE64
|
||||
# 安全秘钥 对称算法的秘钥 如:AES,SM4
|
||||
password:
|
||||
# 公私钥 非对称算法的公私钥 如:SM2,RSA
|
||||
publicKey:
|
||||
privateKey:
|
||||
|
||||
# api接口加密
|
||||
api-decrypt:
|
||||
# 是否开启全局接口加密
|
||||
enabled: true
|
||||
# AES 加密头标识
|
||||
headerFlag: encrypt-key
|
||||
# 响应加密公钥 非对称算法的公私钥 如:SM2,RSA 使用者请自行更换
|
||||
# 对应前端解密私钥 MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAObq7yrxfvyieZtTjAYyrdvi59tYTXxjO5ajmPCRSXBY9M9wQ1tli297JN6mnY53UJMNyOFNSZVi8WSFoIXjpR87FmvChJlzeN/dZdd3SEs48Ee66XKeSePYqxa8oO5GKDsnajgpsOHKXSeeVSIysiIPS2/WsEqk0In9P4w3RsRFAgMBAAECgYBiMEWwce24SPICnRzuScBpvmsudrbEDIH7BOd0a6LZlcnLJwZNJ7mJlshPsHNQb+WgEf135+BBGEhioPtn0yuTdEuKP4kB9UdYUKiayWCoWhJpesv7sAD4RDClV7dhuV+gcd1AXD+YzyRIPbGm0VC2U+4q8/+UPRpVjqskbLVTgQJBAPRpou7g3S8n4XB527kq0D8I3+ZYwMxZhszwhrCDpJU319+ucmpLVwYIzDmZVeID2QQdUaDfIEViFHu95xDrGiUCQQDx3YOKn3yaEctk/ERVn7hDAyAXUbd8/pv2b24/M/l1ZevlsFem8U4Jk5Mu64t3z3YGJoymEjQmbucwT01iKhehAkEAxlnccsRmfFh/KkqauKE4M4++NTAd9zlInpUsmZ+cN8UEGnF2RTEzRKBrLOt1uWCqBB7PGiE6DVTVjr7FAQPrSQJAT5yeY87DcONSk9cFlzmPqV8p/QME5rvYEnHzVBKDlkUKNPyqnWToTvaoh9U4fyNmsfeWbEOprszqhFhWHG3GgQJAK8+ynmyFhaw63+Hx2KU5zR4hVuQso2IzrEurGxCxybV6mR7VBerb4502+EPx3PmOgxQL+niUFhcMWxcvBFP9+A==
|
||||
publicKey: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDm6u8q8X78onmbU4wGMq3b4ufbWE18YzuWo5jwkUlwWPTPcENbZYtveyTepp2Od1CTDcjhTUmVYvFkhaCF46UfOxZrwoSZc3jf3WXXd0hLOPBHuulynknj2KsWvKDuRig7J2o4KbDhyl0nnlUiMrIiD0tv1rBKpNCJ/T+MN0bERQIDAQAB
|
||||
# 请求解密私钥 非对称算法的公私钥 如:SM2,RSA 使用者请自行更换
|
||||
# 对应前端加密公钥 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDvEDuRIOM3oZPWj9Ukoc5pQklR4PFH6/clnjeFqjDLIgDyQvjxhgqAZQA+E9eD6qu6FsXPmK8djcL+nh3cFHz4pX473jDvO3Sve+8yL3VRQ0n2pRgQ2a01MJsy+WwTZCBYWf0VnLRIvANUoWQgy9vz94q7Va44dg7A1/3ICf+xAwIDAQAB
|
||||
privateKey: MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAO8QO5Eg4zehk9aP1SShzmlCSVHg8Ufr9yWeN4WqMMsiAPJC+PGGCoBlAD4T14Pqq7oWxc+Yrx2Nwv6eHdwUfPilfjveMO87dK977zIvdVFDSfalGBDZrTUwmzL5bBNkIFhZ/RWctEi8A1ShZCDL2/P3irtVrjh2DsDX/cgJ/7EDAgMBAAECgYEAhNZAQyRDHWZq/45soS5Hw7VRiG21pIE5k22W7G7lLfp3DCaqrYoNy8pTmCruVh7PzVdaE0CEDaf38gNqFCBOT8iTFQiYV3am4W3hsEQM5wmVBeTvCM5P2jsaaBQbqmneRjiZVbs6ha205JSho1Oc85NbaZa8gFVjwZgZWJrbzgECQQD/iZWhkRPtbdeai/Xk7D/eIXKh1Gxid0rWKQq8ikxbaiergn47XzNKrpROVyka3Gn85o7jJphgxp99R3r8sH71AkEA738Dn7xs+I4Y+MLa2EcT78JG3f/VhlWS/ks3qGJ2dfqwS7ntnmf5Q+2Xw+9UcuiK/TxD8K/0inSCkIMeWBOFFwJBAIoTebq3faEJfTqQ7ekojsokIKC4+2epNdLKknaV8/RhQ9Y0yKikJD7yXkiGaDuPZeW1Xvf2XtfL+1niSd5IMBECQDCOOMbe5dzyuj9dCg+FQZZ/dey2XK0Slm22BD/ATrIWtD12IaXXAKNz/Sv9TsrJOLykxkV69wJHIt13p+RFeNsCQGn5XGRn4ZCRVCesJYXyx29MTqkl8sD/gzYcURTZYjHqX2EvtvAyC6gBm9H0EbxmHIi4Oq0tITzklCXj5SpvBEw=
|
||||
|
||||
# 防止XSS攻击
|
||||
xss:
|
||||
enabled: true
|
||||
excludeUrls:
|
||||
- /system/notice
|
||||
- /warm-flow/save-json
|
||||
|
||||
# 接口文档配置
|
||||
springdoc:
|
||||
api-docs:
|
||||
# 是否开启接口文档
|
||||
enabled: true
|
||||
info:
|
||||
# 标题
|
||||
title: '标题:AiXun-Admin微服务权限管理系统_接口文档'
|
||||
# 描述
|
||||
description: '描述:微服务权限管理系统, 具体包括XXX,XXX模块...'
|
||||
# 版本
|
||||
version: '版本号:系统版本...'
|
||||
# 作者信息
|
||||
contact:
|
||||
name: 艾讯科技
|
||||
email: 343559364@qq.com
|
||||
url: https://www.aixunkeji.cn
|
||||
|
||||
# seata配置
|
||||
seata:
|
||||
# 是否启用
|
||||
enabled: false
|
||||
# Seata 应用编号,默认为应用名
|
||||
application-id: ${spring.application.name}
|
||||
# Seata 事务组编号,用于 TC 集群名
|
||||
tx-service-group: ${spring.application.name}-group
|
||||
config:
|
||||
type: nacos
|
||||
nacos:
|
||||
server-addr: ${spring.cloud.nacos.server-addr}
|
||||
group: ${spring.cloud.nacos.config.group}
|
||||
namespace: public
|
||||
username: ${spring.cloud.nacos.username}
|
||||
password: ${spring.cloud.nacos.password}
|
||||
data-id: seata-server.properties
|
||||
registry:
|
||||
type: nacos
|
||||
nacos:
|
||||
application: aixun-seata-server
|
||||
server-addr: ${spring.cloud.nacos.server-addr}
|
||||
group: ${spring.cloud.nacos.discovery.group}
|
||||
username: ${spring.cloud.nacos.username}
|
||||
password: ${spring.cloud.nacos.password}
|
||||
namespace: public
|
||||
# 关闭自动代理
|
||||
enable-auto-data-source-proxy: false
|
||||
@@ -0,0 +1,55 @@
|
||||
datasource:
|
||||
system-master:
|
||||
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
|
||||
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能
|
||||
url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/aixun_admin?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
username: ${MYSQL_USERNAME:root}
|
||||
password: ${MYSQL_PASSWORD:password}
|
||||
gen:
|
||||
url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/aixun_admin?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
username: ${MYSQL_USERNAME:root}
|
||||
password: ${MYSQL_PASSWORD:password}
|
||||
workflow:
|
||||
url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/aixun_workflow?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: ${MYSQL_USERNAME:root}
|
||||
password: ${MYSQL_PASSWORD:password}
|
||||
# system-oracle:
|
||||
# url: jdbc:oracle:thin:@//localhost:1521/XE
|
||||
# username: ROOT
|
||||
# password: password
|
||||
# system-postgres:
|
||||
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
|
||||
# username: root
|
||||
# password: password
|
||||
|
||||
mybatis-plus:
|
||||
sql-log:
|
||||
# 完整 SQL 输出开关
|
||||
enabled: true
|
||||
# 输出方式,可选 console、log
|
||||
output: console
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
type: com.zaxxer.hikari.HikariDataSource
|
||||
# 动态数据源文档 https://www.kancloud.cn/tracy5546/dynamic-datasource/content
|
||||
dynamic:
|
||||
# 开启seata代理,开启后默认每个数据源都代理,如果某个不需要代理可单独关闭
|
||||
seata: ${seata.enabled}
|
||||
# 严格模式 匹配不到数据源则报错
|
||||
strict: true
|
||||
hikari:
|
||||
# 最大连接池数量
|
||||
maxPoolSize: 20
|
||||
# 最小空闲线程数量
|
||||
minIdle: 10
|
||||
# 配置获取连接等待超时的时间
|
||||
connectionTimeout: 30000
|
||||
# 校验超时时间
|
||||
validationTimeout: 5000
|
||||
# 空闲连接存活最大时间,默认10分钟
|
||||
idleTimeout: 600000
|
||||
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认30分钟
|
||||
maxLifetime: 1800000
|
||||
# 多久检查一次连接的活性
|
||||
keepaliveTime: 30000
|
||||
@@ -0,0 +1,121 @@
|
||||
service.vgroupMapping.aixun-auth-group=default
|
||||
service.vgroupMapping.aixun-system-group=default
|
||||
service.vgroupMapping.aixun-resource-group=default
|
||||
service.vgroupMapping.aixun-workflow-group=default
|
||||
|
||||
service.enableDegrade=false
|
||||
service.disableGlobalTransaction=false
|
||||
|
||||
#Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
|
||||
store.mode=db
|
||||
store.lock.mode=db
|
||||
store.session.mode=db
|
||||
#Used for password encryption
|
||||
#store.publicKey=
|
||||
|
||||
#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
|
||||
store.db.datasource=hikari
|
||||
store.db.dbType=mysql
|
||||
store.db.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
store.db.url=jdbc:mysql://127.0.0.1:3306/aixun_seata?useUnicode=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
store.db.user=root
|
||||
store.db.password=root
|
||||
store.db.minConn=5
|
||||
store.db.maxConn=30
|
||||
store.db.globalTable=global_table
|
||||
store.db.branchTable=branch_table
|
||||
store.db.distributedLockTable=distributed_lock
|
||||
store.db.queryLimit=100
|
||||
store.db.lockTable=lock_table
|
||||
store.db.maxWait=5000
|
||||
|
||||
# redis 模式 store.mode=redis 开启 (控制台查询功能有限,不影响实际执行功能)
|
||||
# store.redis.host=127.0.0.1
|
||||
# store.redis.port=6379
|
||||
# 最大连接数
|
||||
# store.redis.maxConn=10
|
||||
# 最小连接数
|
||||
# store.redis.minConn=1
|
||||
# store.redis.database=0
|
||||
# store.redis.password=
|
||||
# store.redis.queryLimit=100
|
||||
|
||||
#Transaction rule configuration, only for the server
|
||||
server.recovery.committingRetryPeriod=1000
|
||||
server.recovery.asynCommittingRetryPeriod=1000
|
||||
server.recovery.rollbackingRetryPeriod=1000
|
||||
server.recovery.timeoutRetryPeriod=1000
|
||||
server.maxCommitRetryTimeout=-1
|
||||
server.maxRollbackRetryTimeout=-1
|
||||
server.rollbackRetryTimeoutUnlockEnable=false
|
||||
server.distributedLockExpireTime=10000
|
||||
server.xaerNotaRetryTimeout=60000
|
||||
server.session.branchAsyncQueueSize=5000
|
||||
server.session.enableBranchAsyncRemove=false
|
||||
|
||||
#Transaction rule configuration, only for the client
|
||||
client.rm.asyncCommitBufferLimit=10000
|
||||
client.rm.lock.retryInterval=10
|
||||
client.rm.lock.retryTimes=30
|
||||
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
|
||||
client.rm.reportRetryCount=5
|
||||
client.rm.tableMetaCheckEnable=true
|
||||
client.rm.tableMetaCheckerInterval=60000
|
||||
client.rm.sqlParserType=druid
|
||||
client.rm.reportSuccessEnable=false
|
||||
client.rm.sagaBranchRegisterEnable=false
|
||||
client.rm.sagaJsonParser=fastjson
|
||||
client.rm.tccActionInterceptorOrder=-2147482648
|
||||
client.tm.commitRetryCount=5
|
||||
client.tm.rollbackRetryCount=5
|
||||
client.tm.defaultGlobalTransactionTimeout=60000
|
||||
client.tm.degradeCheck=false
|
||||
client.tm.degradeCheckAllowTimes=10
|
||||
client.tm.degradeCheckPeriod=2000
|
||||
client.tm.interceptorOrder=-2147482648
|
||||
client.undo.dataValidation=true
|
||||
client.undo.logSerialization=jackson
|
||||
client.undo.onlyCareUpdateColumns=true
|
||||
server.undo.logSaveDays=7
|
||||
server.undo.logDeletePeriod=86400000
|
||||
client.undo.logTable=undo_log
|
||||
client.undo.compress.enable=true
|
||||
client.undo.compress.type=zip
|
||||
client.undo.compress.threshold=64k
|
||||
|
||||
#For TCC transaction mode
|
||||
tcc.fence.logTableName=tcc_fence_log
|
||||
tcc.fence.cleanPeriod=1h
|
||||
|
||||
#Log rule configuration, for client and server
|
||||
log.exceptionRate=100
|
||||
|
||||
#Metrics configuration, only for the server
|
||||
metrics.enabled=false
|
||||
metrics.registryType=compact
|
||||
metrics.exporterList=prometheus
|
||||
metrics.exporterPrometheusPort=9898
|
||||
|
||||
#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
|
||||
#Transport configuration, for client and server
|
||||
transport.type=TCP
|
||||
transport.server=NIO
|
||||
transport.heartbeat=true
|
||||
transport.enableTmClientBatchSendRequest=false
|
||||
transport.enableRmClientBatchSendRequest=true
|
||||
transport.enableTcServerBatchSendResponse=false
|
||||
transport.rpcRmRequestTimeout=30000
|
||||
transport.rpcTmRequestTimeout=30000
|
||||
transport.rpcTcRequestTimeout=30000
|
||||
transport.threadFactory.bossThreadPrefix=NettyBoss
|
||||
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
|
||||
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
|
||||
transport.threadFactory.shareBossWorker=false
|
||||
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
|
||||
transport.threadFactory.clientSelectorThreadSize=1
|
||||
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
|
||||
transport.threadFactory.bossThreadSize=1
|
||||
transport.threadFactory.workerThreadSize=default
|
||||
transport.shutdown.wait=3
|
||||
transport.serialization=seata
|
||||
transport.compressor=none
|
||||
@@ -0,0 +1,169 @@
|
||||
import java.sql.*;
|
||||
import java.util.Properties;
|
||||
import java.util.Base64;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/** Read-only platform database capability probe. Credentials are never printed. */
|
||||
class DamengProbe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
String host = System.getenv("DATAGOV_DM_HOST");
|
||||
String port = System.getenv("DATAGOV_DM_PORT");
|
||||
if (host == null || !host.matches("[A-Za-z0-9.-]+") || port == null || !port.matches("[0-9]{1,5}")) {
|
||||
throw new IllegalArgumentException("Missing or invalid private connection settings");
|
||||
}
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", System.getenv("DATAGOV_DM_USERNAME"));
|
||||
properties.setProperty("password", System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
properties.setProperty("connectTimeout", "6000");
|
||||
properties.setProperty("socketTimeout", "15000");
|
||||
Class.forName("dm.jdbc.driver.DmDriver");
|
||||
try (Connection connection = DriverManager.getConnection("jdbc:dm://" + host + ":" + port, properties)) {
|
||||
System.out.println("PRODUCT\t" + connection.getMetaData().getDatabaseProductName());
|
||||
System.out.println("DRIVER\t" + connection.getMetaData().getDriverVersion());
|
||||
query(connection, "VERSION", "SELECT * FROM V$VERSION");
|
||||
query(connection, "BUILD", "SELECT ID_CODE() FROM DUAL");
|
||||
query(connection, "INIT", "SELECT SF_GET_PAGE_SIZE()/1024, SF_GET_EXTENT_SIZE(), SF_GET_CASE_SENSITIVE_FLAG(), SF_GET_UNICODE_FLAG() FROM DUAL");
|
||||
query(connection, "PARAMETERS", "SELECT PARA_NAME,PARA_VALUE,SESS_VALUE,FILE_VALUE FROM V$DM_INI WHERE PARA_NAME IN ('COMPATIBLE_MODE','LENGTH_IN_CHAR','BLANK_PAD_MODE') ORDER BY PARA_NAME");
|
||||
query(connection, "INSTR", "SELECT INSTR(','||'0,100,101'||',', ',100,') FROM DUAL");
|
||||
query(connection, "LIMIT", "SELECT 1 FROM DUAL LIMIT 1 OFFSET 0");
|
||||
query(connection, "JSON_VALUE", "SELECT JSON_VALUE('{\"k\":\"v\"}', '$.k') FROM DUAL");
|
||||
query(connection, "JSON_EXTRACT", "SELECT JSON_UNQUOTE(JSON_EXTRACT('{\"k\":\"v\"}', '$.k')) FROM DUAL");
|
||||
query(connection, "JSON_CAST", "SELECT CAST('{\"k\":1}' AS JSON) FROM DUAL");
|
||||
query(connection, "SHA2", "SELECT SHA2('abc',256) FROM DUAL");
|
||||
query(connection, "NOW6", "SELECT NOW(6) FROM DUAL");
|
||||
query(connection, "TIMESTAMP6", "SELECT CURRENT_TIMESTAMP(6) FROM DUAL");
|
||||
query(connection, "BINARY_COMPARE", "SELECT CASE WHEN BINARY 'a'=BINARY 'A' THEN 1 ELSE 0 END FROM DUAL");
|
||||
query(connection, "HASH256", "SELECT LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST('abc' AS CLOB), DBMS_CRYPTO.HASH_SH256))) FROM DUAL");
|
||||
query(connection, "HASH_EMPTY", "SELECT LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST('' AS CLOB), DBMS_CRYPTO.HASH_SH256))) FROM DUAL");
|
||||
query(connection, "IF_FUNCTION", "SELECT IF(1=1,'yes','no') FROM DUAL");
|
||||
if (args.length == 1 && "--write-probe".equals(args[0])) writeProbe(connection);
|
||||
if(args.length==1&&"--prepare-probe".equals(args[0])) {
|
||||
connection.setSchema("AIXUN_DATAGOV_DM_TEST");connection.setReadOnly(true);
|
||||
boolean rejected=false;
|
||||
try(PreparedStatement invalid=connection.prepareStatement("SELECT * FROM DG_DM_NO_SUCH_TABLE")){invalid.getParameterMetaData();}
|
||||
catch(SQLException expected){rejected=true;}
|
||||
if(!rejected)throw new IllegalStateException("Driver preparation did not validate the negative control");
|
||||
var input=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8));
|
||||
String line;int passed=0,failed=0;
|
||||
while((line=input.readLine())!=null){
|
||||
String[] parts=line.split("\t",2);String sql=new String(Base64.getDecoder().decode(parts[1]),StandardCharsets.UTF_8);
|
||||
try(PreparedStatement s=connection.prepareStatement(sql)){s.getParameterMetaData();passed++;}
|
||||
catch(SQLException error){failed++;System.out.println("PREPARE_FAILED "+parts[0]+" CODE="+error.getErrorCode());}
|
||||
}
|
||||
System.out.println("PREPARED="+passed+" FAILED="+failed+" DML_EXECUTED=0");
|
||||
if(failed>0)System.exit(2);
|
||||
}
|
||||
if (args.length == 1 && "--constraint-probe".equals(args[0])) {
|
||||
connection.setSchema("AIXUN_DATAGOV_DM_TEST");
|
||||
var input=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8));
|
||||
String line;
|
||||
while((line=input.readLine())!=null) {
|
||||
String[] parts=line.split("\t",2);
|
||||
ddlProbe(connection,parts[0],new String(Base64.getDecoder().decode(parts[1]),StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
if (args.length == 1 && "--index-probe".equals(args[0])) {
|
||||
connection.setSchema("AIXUN_DATAGOV_DM_TEST");
|
||||
for (String expression : new String[]{"CASE state WHEN 'OPEN' THEN code WHEN 'ASSIGNED' THEN code ELSE NULL END", "DECODE(state,'OPEN',code,'ASSIGNED',code,NULL)", "CASE WHEN id>0 THEN CASE state WHEN 'OPEN' THEN code WHEN 'ASSIGNED' THEN code ELSE NULL END ELSE NULL END"}) {
|
||||
try (ResultSet r=connection.getMetaData().getTables(null,"AIXUN_DATAGOV_DM_TEST","DG_DM_DDL_PROBE",null)) {
|
||||
if(r.next())throw new SQLException("Existing probe table");
|
||||
}
|
||||
try(Statement s=connection.createStatement()) {
|
||||
s.execute("CREATE TABLE DG_DM_DDL_PROBE(id BIGINT,code CHAR(64 CHAR),state VARCHAR(32), active_code CHAR(64 CHAR) GENERATED ALWAYS AS ("+expression+") VIRTUAL)");
|
||||
try { mutation(connection,expression,"CREATE UNIQUE INDEX ix_dg_dm_probe ON DG_DM_DDL_PROBE(active_code)"); }
|
||||
finally { s.execute("DROP TABLE DG_DM_DDL_PROBE"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException error) {
|
||||
System.err.println("CONNECT_FAILED SQLSTATE=" + error.getSQLState() + " CODE=" + error.getErrorCode());
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeProbe(Connection connection) throws SQLException {
|
||||
String schema = "AIXUN_DATAGOV_DM_TEST";
|
||||
boolean exists = false;
|
||||
try (ResultSet schemas = connection.getMetaData().getSchemas()) {
|
||||
while (schemas.next()) if (schema.equals(schemas.getString("TABLE_SCHEM"))) exists = true;
|
||||
}
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
if (!exists) statement.execute("CREATE SCHEMA " + schema + " AUTHORIZATION SYSDBA");
|
||||
connection.setSchema(schema);
|
||||
if (!schema.equals(connection.getSchema())) throw new SQLException("Probe schema mismatch");
|
||||
// Never reuse or delete an existing object.
|
||||
try (ResultSet tables = connection.getMetaData().getTables(null, schema, "DG_DM_COMPAT_PROBE", null)) {
|
||||
if (tables.next()) throw new SQLException("Probe table already exists; reconcile before retry");
|
||||
}
|
||||
statement.execute("CREATE TABLE DG_DM_COMPAT_PROBE(id BIGINT PRIMARY KEY, code VARCHAR(128) UNIQUE, payload JSON, changed_at TIMESTAMP(6))");
|
||||
try {
|
||||
mutation(connection, "INSERT", "INSERT INTO DG_DM_COMPAT_PROBE VALUES(1,'first','{\"k\":1}',NOW(6))");
|
||||
mutation(connection, "UPSERT", "INSERT INTO DG_DM_COMPAT_PROBE VALUES(1,'first','{\"k\":2}',NOW(6)) ON DUPLICATE KEY UPDATE payload=VALUES(payload)");
|
||||
mutation(connection, "IGNORE", "INSERT IGNORE INTO DG_DM_COMPAT_PROBE VALUES(1,'first','{}',NOW(6))");
|
||||
mutation(connection, "DUPLICATE", "INSERT INTO DG_DM_COMPAT_PROBE VALUES(1,'first','{}',NOW(6))");
|
||||
mutation(connection, "IGNORE_HINT", "INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(DG_DM_COMPAT_PROBE) */ INTO DG_DM_COMPAT_PROBE VALUES(1,'first','{}',NOW(6))");
|
||||
mutation(connection, "IGNORE_UNIQUE", "INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(DG_DM_COMPAT_PROBE) */ INTO DG_DM_COMPAT_PROBE VALUES(2,'first','{}',NOW(6))");
|
||||
mutation(connection, "MERGE", "MERGE INTO DG_DM_COMPAT_PROBE t USING (SELECT 1 id,'first' code,'{\"k\":3}' payload FROM DUAL) s ON (t.id=s.id) WHEN MATCHED THEN UPDATE SET t.payload=s.payload WHEN NOT MATCHED THEN INSERT(id,code,payload) VALUES(s.id,s.code,s.payload)");
|
||||
query(connection, "READBACK", "SELECT id,code,payload FROM DG_DM_COMPAT_PROBE ORDER BY id");
|
||||
query(connection, "LOCK", "SELECT id FROM DG_DM_COMPAT_PROBE WHERE id=1 LIMIT 1 FOR UPDATE");
|
||||
query(connection, "SHARE_LOCK", "SELECT id FROM DG_DM_COMPAT_PROBE WHERE id=1 FOR SHARE");
|
||||
query(connection, "SKIP_LOCKED", "SELECT id FROM DG_DM_COMPAT_PROBE WHERE id=1 LIMIT 1 FOR UPDATE SKIP LOCKED");
|
||||
} finally {
|
||||
statement.execute("DROP TABLE DG_DM_COMPAT_PROBE");
|
||||
}
|
||||
ddlProbe(connection, "COLUMN_COMMENT", "id BIGINT PRIMARY KEY COMMENT 'identifier'");
|
||||
ddlProbe(connection, "AUTO_INCREMENT", "id BIGINT AUTO_INCREMENT PRIMARY KEY");
|
||||
ddlProbe(connection, "ON_UPDATE", "id BIGINT PRIMARY KEY, changed_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
|
||||
ddlProbe(connection, "INLINE_KEY", "id BIGINT PRIMARY KEY, code VARCHAR(32), UNIQUE KEY uk_dg_dm_probe_code(code), KEY ix_dg_dm_probe_id(id)");
|
||||
ddlProbe(connection, "GENERATED", "id BIGINT PRIMARY KEY, active_id BIGINT GENERATED ALWAYS AS (CASE WHEN id>0 THEN id ELSE NULL END) STORED");
|
||||
ddlProbe(connection, "LONGTEXT", "id BIGINT PRIMARY KEY, payload LONGTEXT");
|
||||
ddlProbe(connection, "VARCHAR_CHAR", "id BIGINT PRIMARY KEY, payload VARCHAR(4000 CHAR)");
|
||||
ddlProbe(connection, "VARCHAR_16000", "id BIGINT PRIMARY KEY, payload VARCHAR(16000)");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ddlProbe(Connection connection, String label, String columns) throws SQLException {
|
||||
try (ResultSet tables = connection.getMetaData().getTables(null, "AIXUN_DATAGOV_DM_TEST", "DG_DM_DDL_PROBE", null)) {
|
||||
if (tables.next()) throw new SQLException("Existing DDL probe table; reconcile first");
|
||||
}
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
try {
|
||||
statement.execute("CREATE TABLE DG_DM_DDL_PROBE(" + columns + ")");
|
||||
} catch (SQLException error) {
|
||||
if (error.getSQLState() != null && error.getSQLState().startsWith("08")) throw error;
|
||||
System.out.println(label + "\tUNSUPPORTED_OR_DENIED SQLSTATE=" + error.getSQLState() + " CODE=" + error.getErrorCode());
|
||||
return;
|
||||
}
|
||||
System.out.println(label + "\tCREATED");
|
||||
statement.execute("DROP TABLE DG_DM_DDL_PROBE");
|
||||
}
|
||||
}
|
||||
|
||||
private static void mutation(Connection connection, String label, String sql) throws SQLException {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.setQueryTimeout(15);
|
||||
System.out.println(label + "\tAFFECTED=" + statement.executeUpdate(sql));
|
||||
} catch (SQLException error) {
|
||||
if (error.getSQLState() != null && error.getSQLState().startsWith("08")) throw error;
|
||||
System.out.println(label + "\tUNSUPPORTED_OR_DENIED SQLSTATE=" + error.getSQLState() + " CODE=" + error.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static void query(Connection connection, String label, String sql) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.setQueryTimeout(15);
|
||||
try (ResultSet rows = statement.executeQuery(sql)) {
|
||||
while (rows.next()) {
|
||||
StringBuilder line = new StringBuilder(label);
|
||||
for (int i=1; i<=rows.getMetaData().getColumnCount(); i++) line.append('\t').append(rows.getString(i));
|
||||
System.out.println(line);
|
||||
}
|
||||
}
|
||||
} catch (SQLException error) {
|
||||
// No server exception text: it may contain connection or private SQL details.
|
||||
System.out.println(label + "\tUNSUPPORTED_OR_DENIED SQLSTATE=" + error.getSQLState() + " CODE=" + error.getErrorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Explicit schema application with a durable statement journal; never retries UNKNOWN. */
|
||||
class DamengSchema {
|
||||
public static void main(String[] args) throws Exception {
|
||||
boolean verify=args.length==1&&"--verify".equals(args[0]);
|
||||
String schema = System.getenv("DATAGOV_DM_SCHEMA");
|
||||
if (schema == null || !schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+")) throw new IllegalArgumentException("Dedicated DataGov schema required");
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", System.getenv("DATAGOV_DM_USERNAME"));
|
||||
properties.setProperty("password", System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
properties.setProperty("connectTimeout", "6000");
|
||||
properties.setProperty("socketTimeout", "30000");
|
||||
Class.forName("dm.jdbc.driver.DmDriver");
|
||||
try (Connection c = DriverManager.getConnection("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"), properties)) {
|
||||
c.setSchema(schema);
|
||||
if (!schema.equals(c.getSchema())) throw new IllegalArgumentException("Schema does not match");
|
||||
if(!verify)try (Statement s = c.createStatement()) {
|
||||
s.execute("CREATE TABLE IF NOT EXISTS dg_dm_install_step(step_key VARCHAR(256) PRIMARY KEY,sha256 CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,error_code INT,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
|
||||
}
|
||||
if (args.length == 1 && "--reset-empty-test-installation".equals(args[0])) {
|
||||
resetEmptyTestInstallation(c, schema, null);
|
||||
return;
|
||||
}
|
||||
if (args.length == 2 && "--reset-empty-test-table".equals(args[0])) {
|
||||
if(!args[1].matches("[a-z][a-z0-9_]+"))throw new IllegalArgumentException("Invalid table name");
|
||||
resetEmptyTestInstallation(c,schema,args[1]);
|
||||
return;
|
||||
}
|
||||
var input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
|
||||
Map<String,String[]> journal = new HashMap<>();
|
||||
try (Statement s=c.createStatement(); ResultSet r=s.executeQuery("SELECT step_key,sha256,state,error_code FROM dg_dm_install_step")) {
|
||||
while(r.next()) journal.put(r.getString(1),new String[]{r.getString(2),r.getString(3),r.getString(4)});
|
||||
}
|
||||
String line;
|
||||
int applied = 0, skipped = 0;
|
||||
while ((line = input.readLine()) != null) {
|
||||
String[] parts = line.split("\t", 3);
|
||||
String key = parts[0], sha = parts[1];
|
||||
String sql = new String(Base64.getDecoder().decode(parts[2]), StandardCharsets.UTF_8);
|
||||
String[] previous = journal.get(key);
|
||||
String oldSha = previous == null ? null : previous[0], state = previous == null ? null : previous[1];
|
||||
if ("UNKNOWN".equals(state) && Set.of("-6121","-2706","-6119","-6120","-6105","-2026").contains(previous[2]) && sql.startsWith("CREATE TABLE ")) {
|
||||
String table=key.split(":")[0].toUpperCase(Locale.ROOT);
|
||||
try(ResultSet r=c.getMetaData().getTables(null,schema,table,new String[]{"TABLE"})) {
|
||||
if(r.next())throw new IllegalStateException("Rejected table unexpectedly exists; manual reconciliation required");
|
||||
}
|
||||
state="FAILED";
|
||||
System.out.println("RECONCILED_ABSENT_REJECTED_TABLE="+table);
|
||||
}
|
||||
if ("UNKNOWN".equals(state) && "-2169".equals(previous[2]) && sql.startsWith("CREATE UNIQUE INDEX ")) {
|
||||
String[] names=key.split(":");
|
||||
boolean found=false;
|
||||
try(ResultSet r=c.getMetaData().getIndexInfo(null,schema,names[0].toUpperCase(Locale.ROOT),false,false)) {
|
||||
while(r.next())if(names[1].equalsIgnoreCase(r.getString("INDEX_NAME")))found=true;
|
||||
}
|
||||
if(found)throw new IllegalStateException("Rejected index unexpectedly exists; manual reconciliation required");
|
||||
state="FAILED";
|
||||
System.out.println("RECONCILED_ABSENT_REJECTED_INDEX="+names[1]);
|
||||
}
|
||||
if ("SUCCESS".equals(state)) {
|
||||
if (!sha.equals(oldSha)) throw new IllegalStateException("Applied statement checksum drift: " + key);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if(verify)throw new IllegalStateException("Schema statement is not installed: "+key);
|
||||
if (state != null && !"FAILED".equals(state)) throw new IllegalStateException("Reconcile incomplete statement before retry: " + key);
|
||||
if (state == null) {
|
||||
try (PreparedStatement s=c.prepareStatement("INSERT INTO dg_dm_install_step(step_key,sha256,state) VALUES(?,?,'STARTED')")) {
|
||||
s.setString(1,key);s.setString(2,sha);s.executeUpdate();
|
||||
}
|
||||
} else {
|
||||
try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET sha256=?,state='STARTED',error_code=NULL,updated_at=CURRENT_TIMESTAMP WHERE step_key=? AND sha256=? AND state IN ('FAILED','UNKNOWN')")) {
|
||||
s.setString(1,sha);s.setString(2,key);s.setString(3,oldSha);
|
||||
if(s.executeUpdate()!=1)throw new IllegalStateException("Installation state changed concurrently; stop before executing DDL: "+key);
|
||||
}
|
||||
}
|
||||
try (Statement s=c.createStatement()) {
|
||||
s.setQueryTimeout(30);
|
||||
s.execute(sql);
|
||||
} catch (SQLException error) {
|
||||
// Only deterministic statement rejection is retryable after a source correction.
|
||||
Set<Integer> rejected=Set.of(-2007,-2207,-2994,-3719,-2119,-2111,-2665,-2724,-2723,-2707,-6160,-2725,-2169,-6121,-2706,-6119);
|
||||
String outcome=rejected.contains(error.getErrorCode())?"FAILED":"UNKNOWN";
|
||||
try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET state=?,error_code=?,updated_at=CURRENT_TIMESTAMP WHERE step_key=?")) {
|
||||
s.setString(1,outcome);s.setInt(2,error.getErrorCode());s.setString(3,key);s.executeUpdate();
|
||||
}
|
||||
System.err.println("STOP " + key + " " + outcome + " CODE=" + error.getErrorCode());
|
||||
String message=error.getMessage();
|
||||
for(String env:List.of("DATAGOV_DM_PASSWORD","DATAGOV_DM_HOST","DATAGOV_DM_USERNAME")) {
|
||||
String value=System.getenv(env);if(value!=null&&!value.isEmpty())message=message.replace(value,"[withheld]");
|
||||
}
|
||||
System.err.println(message);
|
||||
System.exit(2);
|
||||
}
|
||||
try (PreparedStatement s=c.prepareStatement("UPDATE dg_dm_install_step SET state='SUCCESS',updated_at=CURRENT_TIMESTAMP WHERE step_key=?")) {
|
||||
s.setString(1,key);s.executeUpdate();
|
||||
}
|
||||
applied++;
|
||||
if(applied%100==0)System.out.println("APPLIED="+applied+" SKIPPED="+skipped);
|
||||
}
|
||||
System.out.println((verify?"SCHEMA_VERIFIED=":"SCHEMA_APPLIED=")+(verify?skipped:applied)+" SKIPPED="+skipped);
|
||||
} catch (SQLException error) {
|
||||
System.err.println("CONNECTION_OR_JOURNAL_FAILURE SQLSTATE="+error.getSQLState()+" CODE="+error.getErrorCode());
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void resetEmptyTestInstallation(Connection c, String schema, String onlyTable) throws SQLException {
|
||||
if (!"AIXUN_DATAGOV_DM_TEST".equals(schema)) throw new IllegalArgumentException("Only this task's empty test installation can be reset");
|
||||
List<String> tables = new ArrayList<>();
|
||||
try (Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT step_key,state FROM dg_dm_install_step ORDER BY updated_at DESC")) {
|
||||
while(r.next()) {
|
||||
if(onlyTable!=null&&!r.getString(1).startsWith(onlyTable+":"))continue;
|
||||
String state=r.getString(2);
|
||||
if(!Set.of("SUCCESS","FAILED").contains(state)) throw new IllegalStateException("Unreconciled installation state");
|
||||
String[] key=r.getString(1).split(":");
|
||||
if("SUCCESS".equals(state)&&key.length==2&&key[0].equals(key[1])) {
|
||||
if(!key[0].matches("[a-z][a-z0-9_]+")) throw new IllegalStateException("Invalid tracked object");
|
||||
tables.add(key[0].toUpperCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
}
|
||||
if(onlyTable!=null&&tables.size()!=1)throw new IllegalStateException("Expected exactly one tracked task-created table");
|
||||
try(ResultSet r=c.getMetaData().getTables(null,schema,onlyTable==null?"%":onlyTable.toUpperCase(Locale.ROOT),new String[]{"TABLE"})) {
|
||||
while(r.next()) {
|
||||
String name=r.getString("TABLE_NAME");
|
||||
if(!"DG_DM_INSTALL_STEP".equals(name)&&!tables.contains(name)) throw new IllegalStateException("Untracked table; reset refused");
|
||||
}
|
||||
}
|
||||
// Verify every tracked table is empty before removing any task-created object.
|
||||
for(String table:tables) try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT COUNT(*) FROM "+table)) {
|
||||
if(!r.next()||r.getLong(1)!=0) throw new IllegalStateException("Nonempty table; reset refused");
|
||||
}
|
||||
for(String table:tables)try(Statement s=c.createStatement()){s.execute("DROP TABLE "+table);}
|
||||
try(PreparedStatement s=c.prepareStatement(onlyTable==null?"DELETE FROM dg_dm_install_step":"DELETE FROM dg_dm_install_step WHERE INSTR(step_key,?)=1")) {
|
||||
if(onlyTable!=null)s.setString(1,onlyTable+":");
|
||||
s.executeUpdate();
|
||||
}
|
||||
System.out.println("REMOVED_TASK_CREATED_EMPTY_TABLES="+tables.size()+" SCHEMA_RETAINED=true");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Atomic fresh seed import. Refuses nonempty target tables and never replays committed seeds. */
|
||||
class DamengSeed {
|
||||
public static void main(String[] args) throws Exception {
|
||||
String schema=System.getenv("DATAGOV_DM_SCHEMA");
|
||||
if(schema==null||!schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"))throw new IllegalArgumentException("Dedicated schema required");
|
||||
Properties p=new Properties();p.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));p.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
p.setProperty("connectTimeout","6000");p.setProperty("socketTimeout","30000");
|
||||
var input=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8));
|
||||
String digest=input.readLine();String[] tables=input.readLine().split(",");
|
||||
boolean verify=args.length==1&&"--verify".equals(args[0]);
|
||||
boolean configureAdmin=args.length==1&&"--configure-admin".equals(args[0]);
|
||||
try(Connection c=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),p)) {
|
||||
c.setSchema(schema);
|
||||
if(!schema.equals(c.getSchema()))throw new IllegalStateException("Schema mismatch");
|
||||
c.setAutoCommit(false);
|
||||
boolean committing=false;
|
||||
try {
|
||||
String previous=null,state=null;
|
||||
try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT sha256,state FROM dg_dm_install_step WHERE step_key='seed:baseline'")) {
|
||||
if(r.next()){previous=r.getString(1);state=r.getString(2);}
|
||||
}
|
||||
if(previous!=null) {
|
||||
if(!digest.equals(previous)||!"SUCCESS".equals(state))throw new IllegalStateException("Seed drift or incomplete state; reconcile first");
|
||||
if(configureAdmin) {
|
||||
String hash=System.getenv("DATAGOV_DM_ADMIN_HASH");
|
||||
if(hash==null||!hash.matches("\\$2[aby]\\$12\\$[./A-Za-z0-9]{53}"))throw new IllegalArgumentException("BCrypt administrator hash required");
|
||||
try(PreparedStatement s=c.prepareStatement("UPDATE sys_user SET password=?,status='0',nick_name='艾讯管理员',update_time=LOCALTIMESTAMP WHERE user_id=1761100000000000001 AND user_name='admin' AND del_flag='0'")) {
|
||||
s.setString(1,hash);
|
||||
if(s.executeUpdate()!=1)throw new IllegalStateException("Expected administrator identity is missing");
|
||||
}
|
||||
committing=true;c.commit();committing=false;System.out.println("ADMIN_CONFIGURED=true");return;
|
||||
}
|
||||
System.out.println("SEED_ALREADY_APPLIED=true");return;
|
||||
}
|
||||
if(verify||configureAdmin)throw new IllegalStateException("Seed is not installed");
|
||||
for(String table:tables) {
|
||||
if(!table.matches("[a-z][a-z0-9_]+"))throw new IllegalArgumentException("Invalid table");
|
||||
try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT COUNT(*) FROM "+table)) {
|
||||
if(!r.next()||r.getLong(1)!=0)throw new IllegalStateException("Nonempty seed target: "+table);
|
||||
}
|
||||
}
|
||||
// The unique journal key serializes concurrent fresh importers; transaction rollback removes it on failure.
|
||||
try(PreparedStatement s=c.prepareStatement("INSERT INTO dg_dm_install_step(step_key,sha256,state) VALUES('seed:baseline',?,'STARTED')")) {
|
||||
s.setString(1,digest);s.executeUpdate();
|
||||
}
|
||||
int rows=0;
|
||||
try(Statement s=c.createStatement()) {
|
||||
String line;
|
||||
while((line=input.readLine())!=null) {
|
||||
s.addBatch(new String(Base64.getDecoder().decode(line),StandardCharsets.UTF_8));rows++;
|
||||
if(rows%100==0){s.executeBatch();s.clearBatch();System.out.println("SEED_ROWS_STAGED="+rows+" COMMITTED=false");}
|
||||
}
|
||||
s.executeBatch();
|
||||
}
|
||||
try(Statement s=c.createStatement()) {s.executeUpdate("UPDATE dg_dm_install_step SET state='SUCCESS',updated_at=CURRENT_TIMESTAMP WHERE step_key='seed:baseline'");}
|
||||
committing=true;c.commit();committing=false;
|
||||
System.out.println("SEED_ROWS_COMMITTED="+rows+" ADMIN_ACCOUNT=DISABLED_UNTIL_CONFIGURED");
|
||||
} catch(Exception error) {
|
||||
if(committing) {
|
||||
System.err.println("SEED_COMMIT_UNKNOWN: verify the durable journal before any retry");System.exit(2);
|
||||
}
|
||||
try { c.rollback(); }
|
||||
catch(SQLException rollbackError) {System.err.println("SEED_ROLLBACK_UNKNOWN: reconcile the journal and rows before retry");System.exit(2);}
|
||||
if(error instanceof SQLException sql)System.err.println("SEED_ROLLED_BACK SQLSTATE="+sql.getSQLState()+" CODE="+sql.getErrorCode());
|
||||
else System.err.println(error.getMessage());
|
||||
System.exit(2);
|
||||
}
|
||||
} catch(SQLException error) {System.err.println("SEED_CONNECTION_FAILURE CODE="+error.getErrorCode());System.exit(2);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.nio.file.*;
|
||||
import java.io.*;
|
||||
|
||||
/** Read-only allowlisted installation data export; never exports business connections. */
|
||||
class ExportInstallData {
|
||||
static String literal(String value) {
|
||||
if (value == null) return "NULL";
|
||||
if (value.length() <= 1000) return "'" + value.replace("'", "''") + "'";
|
||||
List<String> chunks = new ArrayList<>();
|
||||
for (int p=0;p<value.length();) {
|
||||
int end=Math.min(p+1000,value.length());
|
||||
if(end<value.length() && Character.isHighSurrogate(value.charAt(end-1))) end--;
|
||||
chunks.add("TO_CLOB('"+value.substring(p,end).replace("'","''")+"')"); p=end;
|
||||
}
|
||||
return String.join("||",chunks);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
String[] tables={"std_national_standard_catalog","std_national_standard_classification","std_national_standard_import_batch","std_national_standard_import_page","std_national_standard_import_item","std_national_standard_observation","std_national_standard_replacement","dq_quality_rule_template","dev_transformation_rule_template","sys_menu","sys_role_menu"};
|
||||
Properties props=new Properties();
|
||||
props.setProperty("user",System.getenv("DM_USERNAME"));
|
||||
props.setProperty("password",System.getenv("DM_PASSWORD"));
|
||||
Class.forName("dm.jdbc.driver.DmDriver");
|
||||
try(Connection c=DriverManager.getConnection("jdbc:dm://"+System.getenv("DM_HOST")+":"+System.getenv("DM_PORT"),props);
|
||||
BufferedWriter out=Files.newBufferedWriter(Path.of(args[0]))) {
|
||||
c.setSchema(System.getenv("DM_SCHEMA")); c.setReadOnly(true); c.setAutoCommit(false);
|
||||
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
|
||||
for(String table:tables) {
|
||||
long count=0;
|
||||
try(Statement s=c.createStatement(); ResultSet r=s.executeQuery("SELECT * FROM "+table)) {
|
||||
ResultSetMetaData m=r.getMetaData(); List<String> cols=new ArrayList<>();
|
||||
for(int i=1;i<=m.getColumnCount();i++) cols.add(m.getColumnName(i));
|
||||
String prefix="INSERT INTO "+table+"("+String.join(",",cols)+") VALUES(";
|
||||
while(r.next()) {
|
||||
List<String> values=new ArrayList<>();
|
||||
for(int i=1;i<=m.getColumnCount();i++) values.add(literal(r.getString(i)));
|
||||
out.write(prefix+String.join(",",values)+");\n"); count++;
|
||||
}
|
||||
}
|
||||
out.write("-- "+table+" rows="+count+"\n");
|
||||
System.out.println(table+"="+count);
|
||||
}
|
||||
c.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
/** Inserts missing rows only, rejects conflicting IDs, preserves IDs and audit fields. */
|
||||
class LibraryTransfer {
|
||||
static final ObjectMapper JSON = new ObjectMapper();
|
||||
static final Set<String> ALLOWED = Set.of(
|
||||
"std_national_standard_catalog", "std_national_standard_classification",
|
||||
"std_national_standard_import_batch", "std_national_standard_import_page",
|
||||
"std_national_standard_import_item", "std_national_standard_observation",
|
||||
"std_national_standard_replacement", "dq_quality_rule_template",
|
||||
"dev_transformation_rule_template");
|
||||
record Col(String name, String type) {}
|
||||
static String table;
|
||||
static long count(Connection c, String t) throws Exception {
|
||||
try(var s=c.createStatement(); var r=s.executeQuery("SELECT COUNT(*) FROM "+t)) {r.next();return r.getLong(1);}
|
||||
}
|
||||
static List<Col> columns(Connection source,String t) throws Exception {
|
||||
var result=new ArrayList<Col>();
|
||||
try(var s=source.prepareStatement("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? AND extra NOT LIKE '%VIRTUAL GENERATED%' AND extra NOT LIKE '%STORED GENERATED%' ORDER BY ordinal_position")) {
|
||||
s.setString(1,t);try(var r=s.executeQuery()){while(r.next())result.add(new Col(r.getString(1),r.getString(2)));}
|
||||
}return result;
|
||||
}
|
||||
static String keyColumn(Connection source,String t) throws Exception {
|
||||
var keys=new ArrayList<String>();
|
||||
try(var r=source.getMetaData().getPrimaryKeys(source.getCatalog(),null,t)){while(r.next())keys.add(r.getString("COLUMN_NAME"));}
|
||||
if(keys.size()!=1)throw new IllegalStateException("Expected single primary key: "+t);
|
||||
return keys.get(0);
|
||||
}
|
||||
static Object value(ResultSet r,int i,Col col) throws Exception {
|
||||
String v=r.getString(i);if(v==null)return null;
|
||||
return switch(col.type) {
|
||||
case "bigint","int","smallint","tinyint","decimal","numeric","float","double" -> new BigDecimal(v).stripTrailingZeros().toPlainString();
|
||||
case "timestamp","datetime" -> r.getTimestamp(i).toLocalDateTime().toString();
|
||||
case "date" -> r.getDate(i).toLocalDate().toString();
|
||||
case "json" -> JSON.readTree(v);
|
||||
default -> v;
|
||||
};
|
||||
}
|
||||
static String digest(ResultSet r,List<Col> cols, boolean ignoreSeedTimes) throws Exception {
|
||||
var values=new ArrayList<Object>();
|
||||
for(int i=0;i<cols.size();i++) {
|
||||
Col c=cols.get(i);
|
||||
if(ignoreSeedTimes && Set.of("create_time","update_time").contains(c.name))continue;
|
||||
Object v=value(r,i+1,c);
|
||||
if(v instanceof JsonNode j) v=canonical(j);
|
||||
values.add(v);
|
||||
}
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JSON.writeValueAsBytes(values)));
|
||||
}
|
||||
static Object canonical(JsonNode n) {
|
||||
if(n.isObject()){var m=new TreeMap<String,Object>();n.properties().forEach(e->m.put(e.getKey(),canonical(e.getValue())));return m;}
|
||||
if(n.isArray()){var a=new ArrayList<Object>();n.forEach(x->a.add(canonical(x)));return a;}
|
||||
return n;
|
||||
}
|
||||
static void bind(PreparedStatement s,int i,ResultSet r,Col c) throws Exception {
|
||||
String v=r.getString(i);
|
||||
if(v==null){s.setNull(i,Types.NULL);return;}
|
||||
switch(c.type) {
|
||||
case "bigint","int","smallint","tinyint","decimal","numeric","float","double" -> s.setBigDecimal(i,new BigDecimal(v));
|
||||
case "timestamp","datetime" -> s.setTimestamp(i,r.getTimestamp(i));
|
||||
case "date" -> s.setDate(i,r.getDate(i));
|
||||
default -> s.setString(i,v);
|
||||
}
|
||||
}
|
||||
static void verifyRelations(Connection c,Set<String> tables) throws Exception {
|
||||
String[][] links={
|
||||
{"std_national_standard_classification","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
|
||||
{"std_national_standard_observation","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
|
||||
{"std_national_standard_observation","batch_id","std_national_standard_import_batch","batch_id"},
|
||||
{"std_national_standard_import_page","batch_id","std_national_standard_import_batch","batch_id"},
|
||||
{"std_national_standard_import_item","batch_id","std_national_standard_import_batch","batch_id"},
|
||||
{"std_national_standard_import_item","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
|
||||
{"std_national_standard_replacement","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"}
|
||||
};
|
||||
int checked=0;
|
||||
for(String[] link:links) {
|
||||
if(!tables.contains(link[0])||!tables.contains(link[2]))continue;
|
||||
try(var s=c.createStatement();var r=s.executeQuery("SELECT COUNT(*) FROM "+link[0]+" c WHERE NOT EXISTS(SELECT 1 FROM "+link[2]+" p WHERE p."+link[3]+"=c."+link[1]+")")) {
|
||||
r.next();if(r.getLong(1)!=0)throw new IllegalStateException("Dangling reference: "+link[0]+"."+link[1]);
|
||||
}
|
||||
checked++;
|
||||
}
|
||||
System.out.println("RELATION_CHECKS_PASS="+checked);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
String mode=args[0];String[] tables=args[1].split(",");
|
||||
if(!Set.of("inventory","plan","apply","verify").contains(mode)||!ALLOWED.containsAll(Arrays.asList(tables)))throw new IllegalArgumentException("Unsupported scope");
|
||||
String schema=System.getenv("DATAGOV_DM_SCHEMA");
|
||||
if(!schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"))throw new IllegalArgumentException("Dedicated schema required");
|
||||
Properties sp=new Properties();sp.setProperty("user","root");sp.setProperty("password",System.getenv("DG_SOURCE_PASSWORD"));
|
||||
sp.setProperty("useCursorFetch","true");sp.setProperty("useSSL","false");sp.setProperty("allowPublicKeyRetrieval","true");sp.setProperty("connectionTimeZone","LOCAL");
|
||||
Properties dp=new Properties();dp.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));dp.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));dp.setProperty("socketTimeout","120000");
|
||||
boolean committing=false;
|
||||
try(Connection src=DriverManager.getConnection("jdbc:mysql://127.0.0.1:"+System.getenv("DG_SOURCE_PORT")+"/aixun_datagov_system",sp);
|
||||
Connection dst=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),dp)) {
|
||||
src.setReadOnly(true);src.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);src.setAutoCommit(false);
|
||||
dst.setSchema(schema);if(!schema.equals(dst.getSchema()))throw new IllegalStateException("Schema mismatch");
|
||||
dst.setAutoCommit(false);
|
||||
try {
|
||||
long totalMissing=0;
|
||||
for(String t:tables) {
|
||||
table=t;
|
||||
long sc=count(src,t),dc=count(dst,t);
|
||||
if(mode.equals("inventory")){System.out.println(t+" source="+sc+" target="+dc);continue;}
|
||||
List<Col> cols=columns(src,t);String pk=keyColumn(src,t);
|
||||
String select=String.join(",",cols.stream().map(c->"\""+c.name.toUpperCase(Locale.ROOT)+"\"").toList());
|
||||
String sourceSelect=String.join(",",cols.stream().map(c->"`"+c.name+"`").toList());
|
||||
boolean seed=t.equals("dev_transformation_rule_template");
|
||||
Map<String,String> existing=new HashMap<>();
|
||||
Map<String,String> expected=new HashMap<>();
|
||||
try(var s=dst.createStatement();var r=s.executeQuery("SELECT "+select+" FROM "+t)) {
|
||||
while(r.next())existing.put(r.getString(pk),digest(r,cols,seed));
|
||||
}
|
||||
long missing=0,matched=0,conflicts=0,processed=0;
|
||||
String insert="INSERT INTO "+t+"("+select+") VALUES("+String.join(",",Collections.nCopies(cols.size(),"?"))+")";
|
||||
try(var read=src.prepareStatement("SELECT "+sourceSelect+" FROM `"+t+"` ORDER BY `"+pk+"`");var write=dst.prepareStatement(insert)) {
|
||||
read.setFetchSize(1000);
|
||||
try(var r=read.executeQuery()) {
|
||||
while(r.next()) {
|
||||
String key=r.getString(pk);String previous=existing.get(key);
|
||||
String hash=(previous!=null||mode.equals("apply"))?digest(r,cols,seed):null;
|
||||
if(mode.equals("apply"))expected.put(key,hash);
|
||||
if(previous!=null){if(previous.equals(hash))matched++;else conflicts++;}
|
||||
else {
|
||||
missing++;
|
||||
if(mode.equals("apply")) {
|
||||
for(int i=0;i<cols.size();i++)bind(write,i+1,r,cols.get(i));
|
||||
write.addBatch();if(missing%500==0){write.executeBatch();write.clearBatch();}
|
||||
}
|
||||
}
|
||||
processed++;
|
||||
if(processed%25000==0)System.out.println(t+" scanned="+processed+" committed=false");
|
||||
}
|
||||
}
|
||||
if(mode.equals("apply")){write.executeBatch();write.clearBatch();}
|
||||
}
|
||||
System.out.println(t+" source="+sc+" target="+dc+" missing="+missing+" matched="+matched+" conflicts="+conflicts);
|
||||
if(processed!=sc||conflicts>0)throw new IllegalStateException("Source count changed or conflicting target IDs");
|
||||
if(mode.equals("verify")&&missing>0)throw new IllegalStateException("Missing source rows");
|
||||
if(mode.equals("apply")&&count(dst,t)!=dc+missing)throw new IllegalStateException("Target count mismatch");
|
||||
if(mode.equals("apply")) {
|
||||
try(var s=dst.createStatement();var r=s.executeQuery("SELECT "+select+" FROM "+t)) {
|
||||
while(r.next()) {
|
||||
String hash=expected.remove(r.getString(pk));
|
||||
if(hash!=null&&!hash.equals(digest(r,cols,seed)))throw new IllegalStateException("Transactional full-column readback mismatch");
|
||||
}
|
||||
}
|
||||
if(!expected.isEmpty())throw new IllegalStateException("Transactional readback has missing IDs");
|
||||
System.out.println(t+" full_column_readback=PASS committed=false");
|
||||
}
|
||||
totalMissing+=missing;
|
||||
}
|
||||
if(mode.equals("apply")||mode.equals("verify"))verifyRelations(dst,Set.of(tables));
|
||||
if(mode.equals("apply")){committing=true;dst.commit();committing=false;System.out.println("COMMITTED_INSERTS="+totalMissing);}
|
||||
else {dst.rollback();System.out.println("READ_ONLY_COMPLETE missing="+totalMissing);}
|
||||
src.rollback();
|
||||
} catch(Exception e) {
|
||||
if(committing){System.err.println("COMMIT_UNKNOWN: run verify before any retry");System.exit(2);}
|
||||
try{dst.rollback();}catch(Exception x){System.err.println("ROLLBACK_UNKNOWN");System.exit(2);}
|
||||
if(e instanceof SQLException sql)System.err.println("ROLLED_BACK table="+table+" SQLSTATE="+sql.getSQLState()+" code="+sql.getErrorCode());
|
||||
else System.err.println("ROLLED_BACK table="+table+" reason="+e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}catch(SQLException e){System.err.println("CONNECTION_FAILED SQLSTATE="+e.getSQLState()+" code="+e.getErrorCode());System.exit(1);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDateTime;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/** Exact two-table synchronization with a bound plan, one backup and atomic readback. */
|
||||
class MenuTransfer {
|
||||
static final ObjectMapper JSON=new ObjectMapper();
|
||||
static final Path DIR=Path.of("runtime/dev-private/menu-mysql-20261118");
|
||||
record Column(String name,String type) {}
|
||||
record Data(List<Column> columns,List<List<String>> rows) {}
|
||||
static String sha(Object value) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JSON.writeValueAsBytes(value)));
|
||||
}
|
||||
static Data read(Connection c,String table,List<Column> columns,boolean mysql) throws Exception {
|
||||
String names=String.join(",",columns.stream().map(x->mysql?"`"+x.name+"`":"\""+x.name.toUpperCase(Locale.ROOT)+"\"").toList());
|
||||
var rows=new ArrayList<List<String>>();
|
||||
try(var s=c.createStatement();var r=s.executeQuery("SELECT "+names+" FROM "+table+" ORDER BY "+(table.equals("sys_menu")?"menu_id":"role_id,menu_id"))) {
|
||||
while(r.next()) {
|
||||
var row=new ArrayList<String>();
|
||||
for(int i=0;i<columns.size();i++) {
|
||||
String v=r.getString(i+1);
|
||||
if(v!=null&&Set.of("datetime","timestamp").contains(columns.get(i).type))v=r.getTimestamp(i+1).toLocalDateTime().toString();
|
||||
row.add(v);
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
}return new Data(columns,rows);
|
||||
}
|
||||
static List<Column> columns(Connection c,String table) throws Exception {
|
||||
var out=new ArrayList<Column>();
|
||||
try(var s=c.prepareStatement("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? ORDER BY ordinal_position")) {
|
||||
s.setString(1,table);try(var r=s.executeQuery()){while(r.next())out.add(new Column(r.getString(1),r.getString(2)));}
|
||||
}return out;
|
||||
}
|
||||
static Map<String,String> roles(Connection c) throws Exception {
|
||||
var out=new TreeMap<String,String>();
|
||||
try(var s=c.createStatement();var r=s.executeQuery("SELECT role_id,role_key FROM sys_role")){while(r.next())out.put(r.getString(1),r.getString(2));}
|
||||
return out;
|
||||
}
|
||||
static int index(Data d,String column){return d.columns.stream().map(Column::name).toList().indexOf(column);}
|
||||
static void validate(Map<String,Data> data,Map<String,String> sourceRoles,Map<String,String> targetRoles) {
|
||||
Data menus=data.get("sys_menu"), grants=data.get("sys_role_menu");
|
||||
var parents=new HashMap<String,String>();
|
||||
for(var row:menus.rows)parents.put(row.get(index(menus,"menu_id")),row.get(index(menus,"parent_id")));
|
||||
for(String id:parents.keySet()) {
|
||||
var seen=new HashSet<String>();String next=id;
|
||||
while(next!=null&&!next.equals("0")) {
|
||||
if(!seen.add(next)||!parents.containsKey(next))throw new IllegalStateException("Invalid menu parent or cycle");
|
||||
next=parents.get(next);
|
||||
}
|
||||
}
|
||||
for(var row:grants.rows) {
|
||||
String role=row.get(index(grants,"role_id"));
|
||||
if(!parents.containsKey(row.get(index(grants,"menu_id")))||!sourceRoles.containsKey(role)||!Objects.equals(sourceRoles.get(role),targetRoles.get(role)))
|
||||
throw new IllegalStateException("Menu grant has missing menu or mismatched role identity");
|
||||
}
|
||||
}
|
||||
static void insert(Connection c,String table,Data data) throws Exception {
|
||||
String cols=String.join(",",data.columns.stream().map(x->"\""+x.name.toUpperCase(Locale.ROOT)+"\"").toList());
|
||||
try(var p=c.prepareStatement("INSERT INTO "+table+"("+cols+") VALUES("+String.join(",",Collections.nCopies(data.columns.size(),"?"))+")")) {
|
||||
int n=0;
|
||||
for(var row:data.rows) {
|
||||
for(int i=0;i<row.size();i++) {
|
||||
String v=row.get(i);String type=data.columns.get(i).type;
|
||||
if(v==null)p.setNull(i+1,Types.NULL);
|
||||
else if(Set.of("datetime","timestamp").contains(type))p.setTimestamp(i+1,Timestamp.valueOf(LocalDateTime.parse(v)));
|
||||
else if(Set.of("bigint","int","smallint","tinyint").contains(type))p.setLong(i+1,Long.parseLong(v));
|
||||
else p.setString(i+1,v);
|
||||
}
|
||||
p.addBatch();if(++n%200==0){p.executeBatch();p.clearBatch();}
|
||||
}
|
||||
p.executeBatch();
|
||||
}
|
||||
}
|
||||
static void differences(String table,Data source,Data target) {
|
||||
var old=new HashMap<String,List<String>>();
|
||||
for(var r:target.rows)old.put(table.equals("sys_menu")?r.get(0):r.get(0)+":"+r.get(1),r);
|
||||
int added=0,changed=0,same=0;
|
||||
var fields=new TreeMap<String,Integer>();
|
||||
for(var r:source.rows) {
|
||||
var before=old.remove(table.equals("sys_menu")?r.get(0):r.get(0)+":"+r.get(1));
|
||||
if(before==null)added++;else if(before.equals(r))same++;else {
|
||||
changed++;
|
||||
for(int i=0;i<r.size();i++)if(!Objects.equals(before.get(i),r.get(i)))fields.merge(source.columns.get(i).name,1,Integer::sum);
|
||||
}
|
||||
}
|
||||
System.out.println(table+" source="+source.rows.size()+" target="+target.rows.size()+" added="+added+" changed="+changed+" removed="+old.size()+" unchanged="+same);
|
||||
if(!fields.isEmpty())System.out.println("changed_fields="+fields);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
String mode=args[0];if(!Set.of("inventory","plan","apply","verify").contains(mode))throw new IllegalArgumentException("Invalid mode");
|
||||
String schema=System.getenv("DATAGOV_DM_SCHEMA");if(!schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"))throw new IllegalArgumentException("Dedicated schema required");
|
||||
Properties sp=new Properties();sp.setProperty("user","root");sp.setProperty("password",System.getenv("DG_SOURCE_PASSWORD"));sp.setProperty("allowPublicKeyRetrieval","true");sp.setProperty("useSSL","false");sp.setProperty("connectionTimeZone","LOCAL");
|
||||
Properties dp=new Properties();dp.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));dp.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));dp.setProperty("socketTimeout","30000");
|
||||
boolean committing=false,committed=false;
|
||||
try(var src=DriverManager.getConnection("jdbc:mysql://127.0.0.1:"+System.getenv("DG_SOURCE_PORT")+"/aixun_datagov_system",sp);
|
||||
var dst=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),dp)) {
|
||||
src.setReadOnly(true);src.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);src.setAutoCommit(false);
|
||||
dst.setSchema(schema);if(!schema.equals(dst.getSchema()))throw new IllegalStateException("Schema mismatch");dst.setAutoCommit(false);
|
||||
try {
|
||||
if(mode.equals("apply"))try(var s=dst.createStatement()){s.execute("LOCK TABLE sys_menu IN EXCLUSIVE MODE");s.execute("LOCK TABLE sys_role_menu IN EXCLUSIVE MODE");}
|
||||
var source=new TreeMap<String,Data>();var target=new TreeMap<String,Data>();
|
||||
for(String table:List.of("sys_menu","sys_role_menu")) {
|
||||
var cols=columns(src,table);source.put(table,read(src,table,cols,true));target.put(table,read(dst,table,cols,false));
|
||||
differences(table,source.get(table),target.get(table));
|
||||
}
|
||||
var sr=roles(src);var dr=roles(dst);validate(source,sr,dr);
|
||||
String sourceHash=sha(source),targetHash=sha(target);
|
||||
var plan=Map.of("sourceSha256",sourceHash,"targetSha256",targetHash,"sourceRolesSha256",sha(sr),"targetRolesSha256",sha(dr),"targetSchema",schema);
|
||||
Path planPath=DIR.resolve("plan.json");
|
||||
if(mode.equals("plan")) {
|
||||
Files.createDirectories(DIR);
|
||||
if(Files.exists(planPath)&&!JSON.readTree(Files.readString(planPath)).equals(JSON.valueToTree(plan)))throw new IllegalStateException("Existing plan changed; reconcile first");
|
||||
if(!Files.exists(planPath))Files.writeString(planPath,JSON.writeValueAsString(plan),StandardOpenOption.CREATE_NEW);
|
||||
System.out.println("PLAN_BOUND; role identities and parent graph verified; database unchanged");
|
||||
} else if(mode.equals("verify")) {
|
||||
if(!sourceHash.equals(targetHash))throw new IllegalStateException("Menu or role-menu content mismatch");
|
||||
System.out.println("FULL_COLUMN_EQUAL=true PARENTS_VALID=true ROLE_MENU_VALID=true");
|
||||
} else if(mode.equals("apply")) {
|
||||
if(!JSON.readTree(Files.readString(planPath)).equals(JSON.valueToTree(plan)))throw new IllegalStateException("Source or target drift since plan");
|
||||
Path backup=DIR.resolve("before.json");
|
||||
if(Files.exists(backup))throw new IllegalStateException("Previous attempt exists; verify before retry");
|
||||
Files.writeString(backup,JSON.writeValueAsString(target),StandardOpenOption.CREATE_NEW);
|
||||
try(var s=dst.createStatement()){s.executeUpdate("DELETE FROM sys_role_menu");s.executeUpdate("DELETE FROM sys_menu");}
|
||||
insert(dst,"sys_menu",source.get("sys_menu"));insert(dst,"sys_role_menu",source.get("sys_role_menu"));
|
||||
var after=new TreeMap<String,Data>();
|
||||
for(String table:source.keySet())after.put(table,read(dst,table,source.get(table).columns,false));
|
||||
if(!sha(after).equals(sourceHash))throw new IllegalStateException("Full-column readback mismatch before commit");
|
||||
validate(after,sr,roles(dst));committing=true;dst.commit();committing=false;committed=true;
|
||||
Files.writeString(DIR.resolve("result.json"),JSON.writeValueAsString(Map.of("status","COMMITTED","sourceSha256",sourceHash,"menus",source.get("sys_menu").rows.size(),"roleMenus",source.get("sys_role_menu").rows.size())),StandardOpenOption.CREATE_NEW);
|
||||
System.out.println("COMMITTED; all menu fields and role-menu grants read back equal");
|
||||
}
|
||||
if(!mode.equals("apply"))dst.rollback();src.rollback();
|
||||
}catch(Exception e){
|
||||
if(committed){System.err.println("COMMITTED_REPORT_FAILED: verify before any further operation");System.exit(2);}
|
||||
if(committing){System.err.println("COMMIT_UNKNOWN: verify before retry");System.exit(2);}
|
||||
try{dst.rollback();}catch(Exception x){System.err.println("ROLLBACK_UNKNOWN");System.exit(2);}
|
||||
if(e instanceof SQLException sql)System.err.println("FAILED SQLSTATE="+sql.getSQLState()+" code="+sql.getErrorCode());
|
||||
else System.err.println("FAILED: "+e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}catch(SQLException e){System.err.println("CONNECTION_FAILED SQLSTATE="+e.getSQLState()+" code="+e.getErrorCode());System.exit(1);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit DM schema installer. Private connection JSON must name a dedicated DataGov schema."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
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")
|
||||
parser.add_argument("--reset-empty-test-installation",action="store_true")
|
||||
parser.add_argument("--reset-empty-test-table")
|
||||
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("configuration must be a 0600 private file under runtime/dev-private")
|
||||
values=json.loads(path.read_text())
|
||||
environment=os.environ.copy()
|
||||
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])
|
||||
if not re.fullmatch(r"[A-Za-z0-9.-]+",str(values['host'])) or not 1<=int(values['port'])<=65535:
|
||||
parser.error("invalid private endpoint")
|
||||
source=(ROOT / "db/dameng/schema.sql").read_text()
|
||||
rows=[]
|
||||
for part in source.split("-- @statement ")[1:]:
|
||||
label,sql=part.split("\n",1)
|
||||
sql=sql.strip()
|
||||
if sql.endswith("/"):sql=sql[:-1].rstrip()
|
||||
elif sql.endswith(";"):sql=sql[:-1]
|
||||
head=re.match(r"CREATE\s+(?:UNIQUE\s+)?(?:TABLE|INDEX|TRIGGER|FUNCTION)\s+(\w+)",sql,re.I)
|
||||
if not head:raise ValueError("unrecognized schema statement")
|
||||
key=label+":"+head.group(1)
|
||||
digest=hashlib.sha256(sql.encode()).hexdigest()
|
||||
rows.append(key+"\t"+digest+"\t"+base64.b64encode(sql.encode()).decode())
|
||||
if not args.apply and not args.verify:
|
||||
print("PLAN_ONLY statements="+str(len(rows))+" database_connection=NOT_RUN")
|
||||
return 0
|
||||
driver=ROOT / "script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar"
|
||||
process=subprocess.run(["java","--class-path",str(driver),str(ROOT / "script/database/DamengSchema.java"),
|
||||
*(["--verify"] if args.verify else ["--reset-empty-test-installation"] if args.reset_empty_test_installation else ["--reset-empty-test-table",args.reset_empty_test_table] if args.reset_empty_test_table else [])],
|
||||
input="\n".join(rows)+"\n",text=True,env=environment)
|
||||
return process.returncode
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Task-124-only forward migration. Plan/backup read business data; apply needs approval.
|
||||
|
||||
No catalog loop, arbitrary SQL argument, credential output or historical backfill.
|
||||
All command diagnostics are suppressed: DB output can contain private row material.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import selectors
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TASK = 'M7-UAT-INGESTION-MANUAL-UAT-RELEASE-124'
|
||||
EVIDENCE = ROOT / 'evidence/M7' / TASK
|
||||
PRIVATE = ROOT / '.local-backups' / TASK
|
||||
ENV = ROOT / 'script/datagov/.env.datagov'
|
||||
CONTAINER = 'aixun-datagov-mysql'
|
||||
SCHEMA = 'aixun_datagov_system'
|
||||
VERSION = '20260921.163'
|
||||
SQL_PATH = ROOT / 'db/migration/dataops/V20260921.163__persist_unified_ingestion_commands.sql'
|
||||
SQL_SHA = '4ef2bfdd87597600d0f6f74c7f36055d34d840644d287f819e5669364bc23ed4'
|
||||
TABLES = ('ing_ingestion_collection', 'ing_ingestion_collection_item')
|
||||
NEW = {
|
||||
TABLES[0]: ['request_payload','payload_version','payload_sha256'],
|
||||
TABLES[1]: ['processing_phase','claim_token','claim_until','next_attempt_at','observe_requested_at','validated_context_json','validated_context_sha256','command_error_code','command_error_summary']}
|
||||
PK = dict(zip(TABLES, ('collection_id','collection_item_id')))
|
||||
CHECKS = {'ck_ing_collection_payload','ck_ing_item_command_phase','ck_ing_item_claim','ck_ing_item_validated_context'}
|
||||
INDEXES = {'idx_ing_item_command_claim','idx_ing_item_observe_request'}
|
||||
NEW_TYPES = {'request_payload':'json','payload_version':'smallint','payload_sha256':'char(64)',
|
||||
'processing_phase':'varchar(24)','claim_token':'char(36)','claim_until':'datetime(6)',
|
||||
'next_attempt_at':'datetime(6)','observe_requested_at':'datetime(6)','validated_context_json':'json',
|
||||
'validated_context_sha256':'char(64)','command_error_code':'varchar(64)','command_error_summary':'varchar(500)'}
|
||||
|
||||
class Blocked(Exception): pass
|
||||
def require(ok, code):
|
||||
if not ok: raise Blocked(code)
|
||||
def digest(b): return hashlib.sha256(b).hexdigest()
|
||||
def canonical(x): return json.dumps(x,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()
|
||||
def write_json(path,value):
|
||||
path.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')
|
||||
def run(args, *, data=None, env=None):
|
||||
p=subprocess.run(args,input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,env=env,cwd=ROOT)
|
||||
require(p.returncode==0, 'COMMAND_FAILED_'+Path(args[0]).name)
|
||||
return p.stdout
|
||||
def read_env():
|
||||
require(not ENV.is_symlink() and stat.S_IMODE(ENV.stat().st_mode)==0o600,'ENV_MODE')
|
||||
keys={'AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD','AIXUN_DATAGOV_DB_SCHEMA','AIXUN_DATAGOV_MYSQL_PORT',
|
||||
'AIXUN_DATAGOV_NACOS_USERNAME','AIXUN_DATAGOV_NACOS_PASSWORD','AIXUN_DATAGOV_NACOS_CLIENT_PORT',
|
||||
'AIXUN_DATAGOV_NACOS_NAMESPACE','AIXUN_DATAGOV_NACOS_GROUP'}
|
||||
out={}
|
||||
for line in ENV.read_text().splitlines():
|
||||
if not line.strip() or line.startswith('#'):continue
|
||||
require(re.fullmatch(r'[A-Z0-9_]+=[A-Za-z0-9+/_=:.-]+',line) is not None,'ENV_SYNTAX')
|
||||
k,v=line.split('=',1)
|
||||
if k in keys:out[k]=v
|
||||
require(out.get('AIXUN_DATAGOV_DB_SCHEMA')==SCHEMA,'SCHEMA_MISMATCH')
|
||||
require(out.get('AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD'),'DB_CREDENTIAL_MISSING')
|
||||
return out
|
||||
def identity():
|
||||
fmt='{{json .Id}}\n{{json .Config.Labels}}\n{{json .NetworkSettings.Ports}}'
|
||||
rows=run(['docker','inspect',CONTAINER,'--format',fmt]).decode().splitlines()
|
||||
cid,labels,ports=map(json.loads,rows)
|
||||
require(labels.get('com.docker.compose.project')=='aixun-datagov-local' and labels.get('com.aixun.project')=='aixun-datagov','DB_OWNER')
|
||||
require(ports.get('3306/tcp')==[{'HostIp':'127.0.0.1','HostPort':'23307'}],'DB_PORT')
|
||||
return {'containerId':cid,'container':CONTAINER,'schema':SCHEMA,'project':'aixun-datagov-local'}
|
||||
def db_env(values):
|
||||
e=os.environ.copy();e['MYSQL_PWD']=values['AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD'];return e
|
||||
def mysql(values,sql):
|
||||
return run(['docker','exec','-i','-e','MYSQL_PWD',CONTAINER,'mysql','--protocol=TCP','-h127.0.0.1','-uroot','--default-character-set=utf8mb4','--batch','--raw','--skip-column-names',SCHEMA],data=sql.encode(),env=db_env(values)).decode()
|
||||
def json_rows(values,sql):return [json.loads(s) for s in mysql(values,sql).splitlines() if s]
|
||||
def catalog():
|
||||
raw=(ROOT/'db/migration/catalog.yml').read_text()
|
||||
entries={}
|
||||
for v,body in re.findall(r" - version: '([^']+)'\n(.*?)(?= - version:|\Z)",raw,re.S):
|
||||
path=re.search(r'^ path: (.+)$',body,re.M).group(1)
|
||||
sha=re.search(r'^ sha256: ([0-9a-f]{64})$',body,re.M).group(1)
|
||||
entries[v]={'path':path,'sha256':sha}
|
||||
require(entries[VERSION]['path']==str(SQL_PATH.relative_to(ROOT)) and entries[VERSION]['sha256']==SQL_SHA and digest(SQL_PATH.read_bytes())==SQL_SHA,'MIGRATION_SOURCE_DRIFT')
|
||||
return entries
|
||||
def table_state(values,table):
|
||||
columns=json_rows(values,f"SELECT JSON_ARRAY(COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLLATION_NAME) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='{table}' ORDER BY ORDINAL_POSITION;")
|
||||
indexes=json_rows(values,f"SELECT JSON_ARRAY(INDEX_NAME,NON_UNIQUE,SEQ_IN_INDEX,COLUMN_NAME,SUB_PART,INDEX_TYPE) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='{table}' ORDER BY INDEX_NAME,SEQ_IN_INDEX;")
|
||||
checks=json_rows(values,f"SELECT JSON_ARRAY(t.CONSTRAINT_NAME,c.CHECK_CLAUSE,t.ENFORCED) FROM information_schema.table_constraints t JOIN information_schema.check_constraints c ON c.CONSTRAINT_SCHEMA=t.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME=t.CONSTRAINT_NAME WHERE t.TABLE_SCHEMA=DATABASE() AND t.TABLE_NAME='{table}' AND t.CONSTRAINT_TYPE='CHECK' ORDER BY t.CONSTRAINT_NAME;")
|
||||
require(columns,'TARGET_TABLE_MISSING')
|
||||
old=[x[0] for x in columns if x[0] not in NEW[table]]
|
||||
require(PK[table] in old and all(re.fullmatch('[a-z_][a-z0-9_]*',s) for s in old),'COLUMN_IDENTIFIER')
|
||||
expr=','.join('`'+s+'`' for s in old)
|
||||
hashes=mysql(values,f"SELECT SHA2(CAST(JSON_ARRAY({expr}) AS CHAR CHARACTER SET utf8mb4),256) FROM `{table}` ORDER BY `{PK[table]}`;").splitlines()
|
||||
require(all(re.fullmatch('[0-9a-f]{64}',s) for s in hashes),'ROW_HASH_FORMAT')
|
||||
ddl=mysql(values,f'SHOW CREATE TABLE `{table}`;')
|
||||
return {'columns':columns,'indexes':indexes,'checks':checks,'rowCount':len(hashes),'originalColumns':old,'originalRowsSha256':digest(('\n'.join(hashes)+'\n').encode()),'ddlSha256':digest(ddl.encode())}
|
||||
def snapshot(values):
|
||||
cat=catalog();obj=identity()
|
||||
require(values.get('AIXUN_DATAGOV_MYSQL_PORT')=='23307','ENV_PORT')
|
||||
history=json_rows(values,'SELECT JSON_ARRAY(version,checksum_sha256,success) FROM dg_schema_history ORDER BY version;')
|
||||
hm={r[0]:r for r in history};required=[]
|
||||
for suffix in ['.007','.018','.021','.125','.134','.144']:
|
||||
version=next(v for v in cat if v.endswith(suffix));expected=cat[version]['sha256']
|
||||
require(version in hm and hm[version][1]==expected and str(hm[version][2])=='1','PREREQUISITE_'+suffix[1:])
|
||||
required.append(hm[version])
|
||||
for v in [v for v in cat if v.endswith(('.158','.159','.160','.161','.162'))]:require(v not in hm,'UNEXPECTED_ASSET_MIGRATION_INSTALLED')
|
||||
state={t:table_state(values,t) for t in TABLES}
|
||||
prior=(ROOT/cat['20260915.144']['path']).read_text()
|
||||
for t,s in state.items():
|
||||
body=prior.split('CREATE TABLE IF NOT EXISTS '+t+' (',1)[1].split(') ENGINE=',1)[0]
|
||||
expected=re.findall(r'^ ([a-z_][a-z0-9_]*)\s+[A-Z]',body,re.M)
|
||||
require(s['originalColumns']==expected,'144_ORIGINAL_COLUMN_LAYOUT_DRIFT')
|
||||
installed=VERSION in hm
|
||||
require(not installed or (hm[VERSION][1]==SQL_SHA and str(hm[VERSION][2])=='1'),'163_HISTORY_DRIFT')
|
||||
for t,s in state.items():
|
||||
names={x[0] for x in s['columns']};present=names.intersection(NEW[t])
|
||||
require(present==set(NEW[t]) if installed else not present,'PARTIAL_163_COLUMNS')
|
||||
allchecks={x[0] for s in state.values() for x in s['checks']};allindexes={x[0] for s in state.values() for x in s['indexes']}
|
||||
require(CHECKS.issubset(allchecks) and INDEXES.issubset(allindexes) if installed else not(CHECKS&allchecks or INDEXES&allindexes),'PARTIAL_163_CONSTRAINTS')
|
||||
if installed:validate_new_structure(state)
|
||||
uuid=mysql(values,'SELECT @@server_uuid;').strip()
|
||||
return {'taskId':TASK,'version':VERSION,'sqlSha256':SQL_SHA,'catalogSha256':digest((ROOT/'db/migration/catalog.yml').read_bytes()),'identity':obj,'serverUuid':uuid,'prerequisites':required,'history':history,'installed':installed,'tables':state}
|
||||
def validate_new_structure(state):
|
||||
for table in TABLES:
|
||||
columns={x[0]:x for x in state[table]['columns']}
|
||||
for name in NEW[table]:
|
||||
require(name in columns,'NEW_COLUMN_MISSING')
|
||||
x=columns[name];nonnull=name=='processing_phase'
|
||||
require(x[1]==NEW_TYPES[name] and x[2]==('NO' if nonnull else 'YES') and x[3]==('LEGACY_UNKNOWN' if nonnull else None) and x[4]=='','NEW_COLUMN_DEFINITION_DRIFT')
|
||||
checks={x[0]:x for s in state.values() for x in s['checks']}
|
||||
def normalized(clause):return re.sub(r'[\s()`]','',clause.lower().replace('_utf8mb4',''))
|
||||
sql=SQL_PATH.read_text()
|
||||
for name in CHECKS:
|
||||
require(name in checks and checks[name][2]=='YES','NEW_CHECK_NOT_ENFORCED')
|
||||
start=sql.index('ADD CONSTRAINT '+name+' CHECK (')+len('ADD CONSTRAINT '+name+' CHECK (');depth=1;i=start
|
||||
while depth:
|
||||
depth+=(sql[i]=='(')-(sql[i]==')');i+=1
|
||||
require(normalized(checks[name][1])==normalized(sql[start:i-1]),'NEW_CHECK_EXPRESSION_DRIFT')
|
||||
expected={'idx_ing_item_command_claim':['processing_phase','next_attempt_at','claim_until','collection_item_id'],'idx_ing_item_observe_request':['observe_requested_at','collection_item_id']}
|
||||
for name,cols in expected.items():
|
||||
rows=[x for x in state[TABLES[1]]['indexes'] if x[0]==name]
|
||||
require([x[3] for x in rows]==cols and all(x[1]==1 and x[4] is None and x[5]=='BTREE' for x in rows),'NEW_INDEX_DEFINITION_DRIFT')
|
||||
def private_dir():
|
||||
require(PRIVATE.parent.exists() and not PRIVATE.parent.is_symlink(),'PRIVATE_PARENT')
|
||||
require(stat.S_IMODE(PRIVATE.parent.stat().st_mode)&0o077==0,'PRIVATE_PARENT_MODE')
|
||||
if not PRIVATE.exists():PRIVATE.mkdir(mode=0o700)
|
||||
require(not PRIVATE.is_symlink() and stat.S_IMODE(PRIVATE.stat().st_mode)==0o700,'PRIVATE_MODE')
|
||||
return PRIVATE
|
||||
def encrypted_backup(values,s,consistent=False):
|
||||
p=private_dir();name=('consistent-' if consistent else 'preparation-')+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%f')
|
||||
directory=p/name;directory.mkdir(mode=0o700)
|
||||
key=secrets.token_hex(48).encode();keyfile=directory/'restore-material';fd=os.open(keyfile,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
||||
with os.fdopen(fd,'wb') as f:f.write(key+b'\n')
|
||||
data=run(['docker','exec','-e','MYSQL_PWD',CONTAINER,'mysqldump','--protocol=TCP','-h127.0.0.1','-uroot','--default-character-set=utf8mb4','--single-transaction','--skip-lock-tables','--no-tablespaces','--set-gtid-purged=OFF','--column-statistics=0','--hex-blob','--skip-comments','--skip-add-drop-table',SCHEMA,*TABLES],env=db_env(values))
|
||||
require(all(t.encode() in data for t in TABLES),'DUMP_TABLE_MISSING')
|
||||
def crypt(payload,decrypt=False):
|
||||
with keyfile.open('rb') as secret:
|
||||
args=['openssl','enc','-aes-256-cbc','-pbkdf2','-iter','200000','-md','sha256','-pass','fd:'+str(secret.fileno())]
|
||||
if decrypt:args.append('-d')
|
||||
result=subprocess.run(args,input=payload,stdout=subprocess.PIPE,stderr=subprocess.PIPE,pass_fds=(secret.fileno(),))
|
||||
require(result.returncode==0,'BACKUP_ENCRYPTION_FAILED')
|
||||
return result.stdout
|
||||
encrypted=crypt(data);signature=hmac.new(key,encrypted,hashlib.sha256).hexdigest()
|
||||
f=directory/'two-tables.sql.enc';f.write_bytes(encrypted);f.chmod(0o600)
|
||||
require(hmac.compare_digest(signature,hmac.new(key,f.read_bytes(),hashlib.sha256).hexdigest()),'BACKUP_HMAC')
|
||||
require(digest(crypt(f.read_bytes(),True))==digest(data),'BACKUP_DECRYPT_HASH')
|
||||
metadata={'taskId':TASK,'consistentMaintenanceBackup':consistent,'path':str(f.relative_to(ROOT)),'encryptedSha256':digest(encrypted),'plaintextSha256':digest(data),'hmacSha256':signature,'bytes':len(encrypted),'sourcePlanSha256':digest(canonical(s)),'tables':{t:{k:s['tables'][t][k] for k in ['rowCount','originalRowsSha256','ddlSha256']} for t in TABLES}}
|
||||
write_json(directory/'metadata.json',metadata);(directory/'metadata.json').chmod(0o600)
|
||||
return metadata
|
||||
|
||||
class Session:
|
||||
"""One mysql session holds the advisory lock through both forward ALTERs."""
|
||||
def __init__(self,values):
|
||||
self.p=subprocess.Popen(['docker','exec','-i','-e','MYSQL_PWD',CONTAINER,'mysql','--protocol=TCP','-h127.0.0.1','-uroot','--default-character-set=utf8mb4','--batch','--raw','--skip-column-names','--unbuffered',SCHEMA],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=db_env(values))
|
||||
self.pending=b''
|
||||
def query(self,sql):
|
||||
marker='END_'+secrets.token_hex(16);self.p.stdin.write((sql+'\nSELECT \''+marker+'\';\n').encode());self.p.stdin.flush()
|
||||
end=time.monotonic()+180;lines=[];sel=selectors.DefaultSelector();sel.register(self.p.stdout,selectors.EVENT_READ)
|
||||
try:
|
||||
while True:
|
||||
while b'\n' in self.pending:
|
||||
line,self.pending=self.pending.split(b'\n',1)
|
||||
if line.decode()==marker:return lines
|
||||
lines.append(line.decode())
|
||||
require(time.monotonic()<end,'MYSQL_SESSION_TIMEOUT_PARTIAL_POSSIBLE')
|
||||
if sel.select(min(1,max(0,end-time.monotonic()))):
|
||||
chunk=os.read(self.p.stdout.fileno(),65536);require(chunk,'MYSQL_SESSION_FAILED_PARTIAL_POSSIBLE');self.pending+=chunk
|
||||
finally:sel.close()
|
||||
def close(self):
|
||||
try:self.p.stdin.close();self.p.wait(timeout=5)
|
||||
except Exception:self.p.terminate()
|
||||
|
||||
def apply(values,approval_path,plan_sha):
|
||||
require(approval_path.resolve()==EVIDENCE/'migration-approval.json','APPROVAL_PATH')
|
||||
a=json.loads(approval_path.read_text())
|
||||
require(a.get('approved') is True and a.get('taskId')==TASK and a.get('version')==VERSION and a.get('sqlSha256')==SQL_SHA,'MIGRATION_APPROVAL_MISSING')
|
||||
require(a.get('toolSha256')==digest(Path(__file__).read_bytes()),'APPROVED_TOOL_DRIFT')
|
||||
require(a.get('planSha256')==plan_sha and a.get('maxAttempts')==1 and a.get('maintenanceApproved') is True,'MAINTENANCE_APPROVAL_MISSING')
|
||||
s=snapshot(values);require(digest(canonical(s))==plan_sha,'LIVE_PLAN_DRIFT')
|
||||
require(not s['installed'],'ALREADY_INSTALLED_NO_APPLY')
|
||||
running=run(['docker','inspect','aixun-datagov-dataops','--format','{{.State.Running}}']).decode().strip()
|
||||
require(running=='false','DATAOPS_NOT_STOPPED')
|
||||
require(a.get('dataopsContainerId')==run(['docker','inspect','aixun-datagov-dataops','--format','{{.Id}}']).decode().strip(),'DATAOPS_ID_DRIFT')
|
||||
session=Session(values);stages=[]
|
||||
try:
|
||||
require(session.query("SELECT GET_LOCK('aixun_datagov_migration_163',0);")==['1'],'MIGRATION_LOCK_BUSY')
|
||||
require(mysql(values,'SELECT COUNT(*) FROM information_schema.innodb_trx;').strip()=='0','OPEN_TRANSACTION')
|
||||
b=encrypted_backup(values,s,True);write_json(EVIDENCE/'migration-consistent-backup.json',b)
|
||||
require(digest(canonical(snapshot(values)))==plan_sha,'BACKUP_WINDOW_DRIFT')
|
||||
attempt=EVIDENCE/'migration-apply-attempt.json'
|
||||
with attempt.open('x') as f:json.dump({'planSha256':plan_sha,'startedAt':datetime.datetime.now(datetime.timezone.utc).isoformat()},f)
|
||||
statements=[x.strip() for x in re.sub(r'--[^\n]*','',SQL_PATH.read_text()).split(';') if x.strip()]
|
||||
require(len(statements)==2 and all(st.startswith('ALTER TABLE '+t) for st,t in zip(statements,TABLES)),'DDL_WHITELIST')
|
||||
for st,t in zip(statements,TABLES):
|
||||
session.query(st+';');stages.append(t);write_json(EVIDENCE/'migration-apply-progress.json',{'completedAlterTables':stages,'historyWritten':False})
|
||||
after={t:table_state(values,t) for t in TABLES}
|
||||
validate_new_structure(after)
|
||||
for t in TABLES:
|
||||
require(after[t]['rowCount']==s['tables'][t]['rowCount'] and after[t]['originalRowsSha256']==s['tables'][t]['originalRowsSha256'],'HISTORICAL_DATA_CHANGED')
|
||||
require(set(NEW[t]).issubset({x[0] for x in after[t]['columns']}),'NEW_COLUMNS_MISSING')
|
||||
require([x for x in after[t]['columns'] if x[0] not in NEW[t]]==s['tables'][t]['columns'],'ORIGINAL_COLUMN_DRIFT')
|
||||
require([x for x in after[t]['indexes'] if x[0] not in INDEXES]==s['tables'][t]['indexes'],'ORIGINAL_INDEX_DRIFT')
|
||||
require([x for x in after[t]['checks'] if x[0] not in CHECKS]==s['tables'][t]['checks'],'ORIGINAL_CHECK_DRIFT')
|
||||
require(CHECKS.issubset({x[0] for v in after.values() for x in v['checks']}),'CHECK_MISSING')
|
||||
require(INDEXES.issubset({x[0] for v in after.values() for x in v['indexes']}),'INDEX_MISSING')
|
||||
require(mysql(values,f'SELECT COUNT(*) FROM {TABLES[0]} WHERE request_payload IS NOT NULL OR payload_version IS NOT NULL OR payload_sha256 IS NOT NULL;').strip()=='0','HISTORY_PAYLOAD_CHANGED')
|
||||
require(mysql(values,f"SELECT COUNT(*) FROM {TABLES[1]} WHERE processing_phase<>'LEGACY_UNKNOWN' OR claim_token IS NOT NULL OR claim_until IS NOT NULL OR next_attempt_at IS NOT NULL OR observe_requested_at IS NOT NULL OR validated_context_json IS NOT NULL OR validated_context_sha256 IS NOT NULL OR command_error_code IS NOT NULL OR command_error_summary IS NOT NULL;").strip()=='0','HISTORY_COMMAND_CHANGED')
|
||||
history=json_rows(values,'SELECT JSON_ARRAY(version,checksum_sha256,success) FROM dg_schema_history ORDER BY version;')
|
||||
require(history==s['history'],'HISTORY_CONCURRENT_CHANGE')
|
||||
session.query(f"INSERT INTO dg_schema_history(version,description,owner_unit,checksum_sha256,success) VALUES ('{VERSION}','{SQL_PATH.stem}','dataops','{SQL_SHA}','1');")
|
||||
final=snapshot(values);require([r for r in final['history'] if r[0]!=VERSION]==s['history'],'HISTORY_SCOPE_CHANGED')
|
||||
write_json(EVIDENCE/'migration-result.json',{'status':'APPLIED','version':VERSION,'final':final,'completedAlterTables':stages})
|
||||
finally:session.close()
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
p=argparse.ArgumentParser();g=p.add_mutually_exclusive_group(required=True);g.add_argument('--plan',action='store_true');g.add_argument('--backup',action='store_true');g.add_argument('--apply',action='store_true')
|
||||
p.add_argument('--approval-file',type=Path);p.add_argument('--plan-sha');args=p.parse_args()
|
||||
v=read_env()
|
||||
if args.apply:
|
||||
require(args.approval_file is not None and args.plan_sha is not None,'APPROVAL_REQUIRED')
|
||||
sys.path.insert(0,str(ROOT/'script/datagov'))
|
||||
from deploy import deployment_lock
|
||||
with deployment_lock():apply(v,args.approval_file,args.plan_sha)
|
||||
print('163 apply completed; details redacted.');return
|
||||
s=snapshot(v);result={'plan':s,'planSha256':digest(canonical(s))}
|
||||
if args.backup:result['preparationBackup']=encrypted_backup(v,s,False)
|
||||
dest=EVIDENCE/('migration-preparation-backup.json' if args.backup else 'migration-plan.json')
|
||||
write_json(dest,result);print(json.dumps({'status':'PLAN_ONLY' if args.plan else 'PREPARATION_BACKUP_ONLY','planSha256':result['planSha256'],'installed':s['installed'],'rowCounts':{t:s['tables'][t]['rowCount'] for t in TABLES}}))
|
||||
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except Exception as error:
|
||||
print('BLOCKED: '+(str(error) if isinstance(error,Blocked) else type(error).__name__)+'; no automatic retry',file=sys.stderr);sys.exit(2)
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
||||
readonly ENV_FILE="${AIXUN_DATAGOV_ENV_FILE:-${PROJECT_ROOT}/script/datagov/.env.datagov}"
|
||||
readonly CONTAINER_NAME="aixun-datagov-mysql"
|
||||
readonly CATALOG="${PROJECT_ROOT}/db/migration/catalog.yml"
|
||||
|
||||
fail() {
|
||||
echo "DataGov migration failed: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
only_version=""
|
||||
case "$#" in
|
||||
0) ;;
|
||||
2)
|
||||
[[ "$1" == "--only-version" ]] || fail "usage: $0 [--only-version VERSION]"
|
||||
only_version="$2"
|
||||
[[ "${only_version}" =~ ^[0-9]{8}\.[0-9]{3}$ ]] ||
|
||||
fail "invalid migration version: ${only_version}"
|
||||
;;
|
||||
*)
|
||||
fail "usage: $0 [--only-version VERSION]"
|
||||
;;
|
||||
esac
|
||||
|
||||
# Only an explicit migration invocation acquires this short process lock.
|
||||
# Development and read-only verification do not reserve a runtime lease.
|
||||
if [[ "${AIXUN_DATAGOV_RUNTIME_LOCKED:-0}" != "1" ]]; then
|
||||
exec python3 "${PROJECT_ROOT}/script/datagov/with-runtime-lock.py" "$0" "$@"
|
||||
fi
|
||||
|
||||
"${PROJECT_ROOT}/script/quality/verify-data-contracts.rb" --catalog-only
|
||||
|
||||
catalog_rows="$(ruby -ryaml -e '
|
||||
catalog_path = ARGV.fetch(0)
|
||||
only_version = ARGV.fetch(1)
|
||||
migrations = YAML.safe_load(File.read(catalog_path)).fetch("migrations")
|
||||
if only_version.empty?
|
||||
selected = migrations
|
||||
else
|
||||
selected = migrations.select { |migration| migration.fetch("version") == only_version }
|
||||
abort "migration version #{only_version} must match exactly one catalog row" unless selected.one?
|
||||
end
|
||||
selected.each do |migration|
|
||||
puts [migration.fetch("version"), migration.fetch("ownerUnit"), migration.fetch("path"), migration.fetch("sha256")].join("\t")
|
||||
end
|
||||
' "${CATALOG}" "${only_version}")"
|
||||
|
||||
[[ -f "${ENV_FILE}" ]] || fail "DataGov environment file is missing"
|
||||
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "${ENV_FILE}"
|
||||
set +a
|
||||
|
||||
project_label="$(docker inspect "${CONTAINER_NAME}" --format '{{index .Config.Labels "com.docker.compose.project"}}' 2>/dev/null)" ||
|
||||
fail "DataGov MySQL container is unavailable"
|
||||
owner_label="$(docker inspect "${CONTAINER_NAME}" --format '{{index .Config.Labels "com.aixun.project"}}')"
|
||||
[[ "${project_label}" == "aixun-datagov-local" && "${owner_label}" == "aixun-datagov" ]] ||
|
||||
fail "refusing to use a MySQL container not owned by DataGov"
|
||||
|
||||
mysql_exec() {
|
||||
docker exec -e MYSQL_PWD="${AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD}" "${CONTAINER_NAME}" \
|
||||
mysql --protocol=TCP -h127.0.0.1 --default-character-set=utf8mb4 \
|
||||
--batch --skip-column-names -uroot "${AIXUN_DATAGOV_DB_SCHEMA}" "$@"
|
||||
}
|
||||
|
||||
mysql_exec_stdin() {
|
||||
docker exec -i -e MYSQL_PWD="${AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD}" "${CONTAINER_NAME}" \
|
||||
mysql --protocol=TCP -h127.0.0.1 --default-character-set=utf8mb4 \
|
||||
--batch --skip-column-names -uroot "${AIXUN_DATAGOV_DB_SCHEMA}"
|
||||
}
|
||||
|
||||
while IFS=$'\t' read -r version owner_unit relative_path expected_sha256 || [[ -n "${version}" ]]; do
|
||||
migration_path="${PROJECT_ROOT}/${relative_path}"
|
||||
history_exists="$(mysql_exec -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='dg_schema_history';")"
|
||||
installed_checksum=""
|
||||
if [[ "${history_exists}" == "1" ]]; then
|
||||
installed_checksum="$(mysql_exec -e "SELECT checksum_sha256 FROM dg_schema_history WHERE version='${version}' AND success='1';")"
|
||||
fi
|
||||
|
||||
if [[ -n "${installed_checksum}" ]]; then
|
||||
[[ "${installed_checksum}" == "${expected_sha256}" ]] || fail "checksum drift for installed migration ${version}"
|
||||
echo "Migration ${version} already applied with the reviewed checksum."
|
||||
continue
|
||||
fi
|
||||
|
||||
mysql_exec_stdin < "${migration_path}"
|
||||
mysql_exec -e "INSERT INTO dg_schema_history(version, description, owner_unit, checksum_sha256, success) VALUES ('${version}', '$(basename "${relative_path}" .sql)', '${owner_unit}', '${expected_sha256}', '1');"
|
||||
echo "Migration ${version} applied for owner ${owner_unit}."
|
||||
done <<< "${catalog_rows}"
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the fresh-install DM schema from the ordered, checksum-verified source catalog.
|
||||
|
||||
Does not replay old runtime guards or migrate business data. Unknown DDL fails closed.
|
||||
"""
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import re
|
||||
from dameng_sql import statements, split_top_level, closing_paren, mask_literals, restore_literals, rewrite_sha256
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def node_key(node):
|
||||
match = re.match(r"(?:CONSTRAINT|(?:UNIQUE\s+)?KEY|(?:UNIQUE\s+)?INDEX)\s+(\w+)", node, re.I)
|
||||
if match:
|
||||
return "constraint:" + match.group(1).lower()
|
||||
if re.match(r"PRIMARY KEY", node, re.I):
|
||||
return "constraint:PRIMARY"
|
||||
return "column:" + node.split()[0].lower()
|
||||
|
||||
|
||||
def sources():
|
||||
yield ROOT / "script/sql/aixun_cloud.sql"
|
||||
catalog = (ROOT / "db/migration/catalog.yml").read_text()
|
||||
rows = re.findall(r"path: (\S+)\s+sha256: ([a-f0-9]{64})", catalog)
|
||||
if not rows:
|
||||
raise ValueError("empty migration catalog")
|
||||
for name, digest in rows:
|
||||
path = ROOT / name
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
|
||||
raise ValueError("migration checksum mismatch: " + name)
|
||||
yield path
|
||||
|
||||
|
||||
def collect():
|
||||
tables = OrderedDict()
|
||||
source_digests = []
|
||||
for path in sources():
|
||||
source_digests.append(str(path.relative_to(ROOT)) + ":" + hashlib.sha256(path.read_bytes()).hexdigest())
|
||||
for raw in statements(path.read_text()):
|
||||
sql = re.sub(r"`([A-Za-z_][A-Za-z_0-9]*)`", r"\1", raw)
|
||||
create = re.match(r"CREATE TABLE\s+(?:IF NOT EXISTS\s+)?(\w+)\s*\(", sql, re.I)
|
||||
alter = re.match(r"ALTER TABLE\s+(\w+)\s+(.+)$", sql, re.I | re.S)
|
||||
if create:
|
||||
name = create.group(1).lower()
|
||||
if path.name == "aixun_cloud.sql" and not name.startswith("sys_"):
|
||||
continue # Generator/demo/Seata are not running DataGov services.
|
||||
if name in tables:
|
||||
raise ValueError("duplicate source table: " + name)
|
||||
end = closing_paren(sql, create.end() - 1)
|
||||
nodes = split_top_level(sql[create.end():end - 1])
|
||||
tables[name] = OrderedDict((node_key(n), n) for n in nodes)
|
||||
if len(tables[name]) != len(nodes):
|
||||
raise ValueError("duplicate source column/constraint: " + name)
|
||||
elif alter:
|
||||
name = alter.group(1).lower()
|
||||
if name not in tables:
|
||||
raise ValueError("unknown ALTER table: " + name)
|
||||
for clause in split_top_level(alter.group(2)):
|
||||
if re.fullmatch(r"(?:ALGORITHM|LOCK)\s*=\s*\w+", clause, re.I):
|
||||
continue # MySQL online ALTER execution hint, irrelevant to fresh CREATE.
|
||||
drop = re.fullmatch(r"DROP\s+(?:INDEX|CHECK|CONSTRAINT)\s+(\w+)", clause, re.I)
|
||||
add = re.match(r"ADD\s+(?:COLUMN\s+)?(.+)", clause, re.I | re.S)
|
||||
modify = re.match(r"MODIFY\s+(?:COLUMN\s+)?(.+)", clause, re.I | re.S)
|
||||
if drop:
|
||||
key = "constraint:" + drop.group(1).lower()
|
||||
if key not in tables[name]:
|
||||
raise ValueError("unknown dropped constraint " + name + "." + key)
|
||||
del tables[name][key]
|
||||
elif add or modify:
|
||||
node = (add or modify).group(1)
|
||||
# Physical column positioning has no business meaning; retain source field names.
|
||||
node, literals = mask_literals(node)
|
||||
node = re.sub(r"\s+(?:AFTER\s+\w+|FIRST)\s*$", "", node, flags=re.I)
|
||||
node = restore_literals(node, literals)
|
||||
key = node_key(node)
|
||||
if bool(modify) != (key in tables[name]):
|
||||
raise ValueError("unexpected column/constraint operation " + name + "." + key)
|
||||
tables[name][key] = node
|
||||
else:
|
||||
raise ValueError("unhandled ALTER in " + str(path.relative_to(ROOT)) + ": " + clause[:100])
|
||||
elif re.match(r"(?:DROP TABLE|RENAME TABLE|CREATE\s+(?:UNIQUE\s+)?INDEX)\b", sql, re.I):
|
||||
raise ValueError("unhandled schema statement: " + sql[:100])
|
||||
return tables, source_digests
|
||||
|
||||
|
||||
def adapt_node(node):
|
||||
masked, literals = mask_literals(node)
|
||||
masked = re.sub(r"\s+CHARACTER SET\s+\w+", "", masked, flags=re.I)
|
||||
masked = re.sub(r"\s+COLLATE\s+\w+", "", masked, flags=re.I)
|
||||
masked = re.sub(r"\s+USING BTREE\b", "", masked, flags=re.I)
|
||||
masked = re.sub(r"NOT NULL\s+AUTO_INCREMENT\s+PRIMARY KEY", "AUTO_INCREMENT PRIMARY KEY", masked, flags=re.I)
|
||||
masked = re.sub(r"\b(?:LONGTEXT|MEDIUMTEXT)\b", "CLOB", masked, flags=re.I)
|
||||
masked = re.sub(r"\b(?:LONGBLOB|MEDIUMBLOB|TINYBLOB)\b", "BLOB", masked, flags=re.I)
|
||||
masked = re.sub(r"\bTINYINT\s+UNSIGNED\b", "SMALLINT", masked, flags=re.I)
|
||||
masked = re.sub(r"\bSMALLINT\s+UNSIGNED\b", "INT", masked, flags=re.I)
|
||||
masked = re.sub(r"\bAS (?:UNSIGNED|SIGNED)\b", "AS BIGINT", masked, flags=re.I)
|
||||
masked = re.sub(r"\bSTORED\b", "VIRTUAL", masked, flags=re.I)
|
||||
if re.match(r"\w+\s+BIGINT\s+GENERATED", masked, re.I):
|
||||
masked = re.sub(r"(GENERATED ALWAYS AS\s*\()\s*(\w+)\s*(\))", r"\1\2+0\3", masked, flags=re.I)
|
||||
masked = re.sub(r"\s+ON UPDATE CURRENT_TIMESTAMP(?:\(\d+\))?", "", masked, flags=re.I)
|
||||
# MySQL integer display widths do not change range or storage.
|
||||
masked = re.sub(r"\b(TINYINT|SMALLINT|INT|BIGINT)\(\d+\)", r"\1", masked, flags=re.I)
|
||||
# Preserve MySQL character-count contracts without changing instance parameters.
|
||||
masked = re.sub(r"\b(VARCHAR|CHAR)\((\d+)\)", r"\1(\2 CHAR)", masked, flags=re.I)
|
||||
masked = re.sub(r"\brows\b", '"ROWS"', masked, flags=re.I)
|
||||
masked = re.sub(r"\bmodel\b", '"MODEL"', masked, flags=re.I)
|
||||
for binary_json in reversed(list(re.finditer(r"BINARY\s+JSON_UNQUOTE\s*\(",masked,re.I))):
|
||||
end=closing_paren(masked,binary_json.end()-1)
|
||||
value=masked[binary_json.start():end]
|
||||
value=re.sub(r"^BINARY\s+","",value,flags=re.I)
|
||||
masked=masked[:binary_json.start()]+"BINARY CAST("+value+" AS VARCHAR(32767))"+masked[end:]
|
||||
for json_number in reversed(list(re.finditer(r"CAST\(JSON_UNQUOTE\s*\(",masked,re.I))):
|
||||
end=closing_paren(masked,json_number.end()-1)
|
||||
if re.match(r"\s+AS BIGINT\)",masked[end:],re.I):
|
||||
start=json_number.start()+len("CAST(")
|
||||
masked=masked[:start]+"CAST("+masked[start:end]+" AS VARCHAR(32767))"+masked[end:]
|
||||
def schema_version(match):
|
||||
if literals[int(match.group(2))] != "'$.schemaVersion'":
|
||||
raise ValueError("unreviewed numeric JSON comparison")
|
||||
args=match.group(1)+",__DG_LITERAL_"+match.group(2)+"__"
|
||||
return "(JSON_TYPE(JSON_EXTRACT("+args+"))='INTEGER' AND JSON_VALUE("+args+")='1')"
|
||||
masked=re.sub(r"JSON_EXTRACT\((\w+),\s*__DG_LITERAL_(\d+)__\)\s*=\s*1\b",schema_version,masked,flags=re.I)
|
||||
masked = re.sub(r"\b(\w+)\s+REGEXP\s+(__DG_LITERAL_\d+__)",
|
||||
r"REGEXP_LIKE(\1, \2, 'c')", masked, flags=re.I)
|
||||
return rewrite_sha256(restore_literals(masked, literals))
|
||||
|
||||
|
||||
def render(tables):
|
||||
result = []
|
||||
for name, nodes in tables.items():
|
||||
columns = []
|
||||
indexes = []
|
||||
timestamps = []
|
||||
computed = []
|
||||
row_checks = []
|
||||
for key, raw in nodes.items():
|
||||
node = adapt_node(raw)
|
||||
if name == "sys_notice" and key == "column:notice_content":
|
||||
node=node.replace("BLOB","CLOB") # RCP6 persists noticeContent as a Java String.
|
||||
if key == "constraint:ck_161_5_7":
|
||||
condition = re.search(r"\bCHECK\s*\((.*)\)\s*$",node,re.I|re.S).group(1)
|
||||
condition,literals=mask_literals(condition)
|
||||
for column_key in nodes:
|
||||
if column_key.startswith("column:"):
|
||||
column=column_key.split(":",1)[1]
|
||||
condition=re.sub(r"\b"+column+r"\b", ":NEW."+column,condition,flags=re.I)
|
||||
row_checks.append("IF NOT ("+restore_literals(condition,literals)+") THEN RAISE_APPLICATION_ERROR(-20001,'ck_161_5_7 violated'); END IF;")
|
||||
continue
|
||||
if name == "dg_metric_calculation_result_evidence" and key == "column:metric_value":
|
||||
# DM DECIMAL supports 38 digits. This evidence is read back as BigDecimal,
|
||||
# never used for database arithmetic; preserve all 65 original digits.
|
||||
node = node.replace("DECIMAL(65,18)","VARCHAR(67 CHAR)")
|
||||
columns.append("CONSTRAINT ck_dm_metric_decimal CHECK (REGEXP_LIKE(metric_value,'^-?[0-9]{1,47}([.][0-9]{1,18})?$','c'))")
|
||||
generated_binary = re.match(r"(\w+\s+BINARY\(\d+\))\s+GENERATED ALWAYS AS\s*\(", node, re.I)
|
||||
if generated_binary:
|
||||
end = closing_paren(node, generated_binary.end()-1)
|
||||
expression = node[generated_binary.end():end-1]
|
||||
expression,literals = mask_literals(expression)
|
||||
for column_key in nodes:
|
||||
if column_key.startswith("column:"):
|
||||
column = column_key.split(":",1)[1]
|
||||
expression = re.sub(r"\b"+column+r"\b", ":NEW."+column, expression, flags=re.I)
|
||||
computed.append(":NEW."+key.split(":",1)[1]+" := "+restore_literals(expression,literals)+";")
|
||||
node = generated_binary.group(1) # DM function indexes cannot return BINARY; retain stored digest bytes.
|
||||
index = re.match(r"(UNIQUE\s+)?(?:KEY|INDEX)\s+(\w+)\s*(\(.+)\s*$", node, re.I | re.S)
|
||||
if index:
|
||||
expression = index.group(3)
|
||||
expression = re.sub(r"\b(\w+)\((\d+)\)", r"SUBSTR(\1,1,\2)", expression)
|
||||
if name == "ops_alert_event" and index.group(2) == "uk_ops_alert_event_active":
|
||||
expression = "(org_id, CASE WHEN del_flag='0' THEN CASE event_status WHEN 'OPEN' THEN fingerprint WHEN 'ASSIGNED' THEN fingerprint WHEN 'PROCESSING' THEN fingerprint ELSE NULL END ELSE NULL END)"
|
||||
if name == "store_physical_space_operation":
|
||||
expression = expression.replace("active_target_external_object_id", "CASE WHEN del_flag='0' THEN CASE operation_status WHEN 'IN_PROGRESS' THEN external_object_id WHEN 'CONFIRMED' THEN external_object_id ELSE NULL END ELSE NULL END")
|
||||
indexes.append("CREATE " + ("UNIQUE " if index.group(1) else "") + "INDEX " + index.group(2)
|
||||
+ " ON " + name + expression)
|
||||
else:
|
||||
columns.append(node)
|
||||
if key.startswith("column:") and re.search(r"\bON UPDATE CURRENT_TIMESTAMP", mask_literals(raw)[0], re.I):
|
||||
timestamps.append(key.split(":", 1)[1])
|
||||
unsigned = re.match(r"(\w+)\s+(TINYINT|SMALLINT)\s+UNSIGNED\b", raw, re.I)
|
||||
if unsigned:
|
||||
maximum = 255 if unsigned.group(2).upper() == "TINYINT" else 65535
|
||||
columns.append("CHECK (" + unsigned.group(1) + " BETWEEN 0 AND " + str(maximum) + ")")
|
||||
width = sum(int(n) * 4 for node in columns for n in re.findall(r"(?:VARCHAR|CHAR)\((\d+) CHAR\)", node, re.I))
|
||||
storage = " STORAGE(USING LONG ROW)" if width > 8000 else ""
|
||||
result.append((name, "CREATE TABLE " + name + " (\n " + ",\n ".join(columns) + "\n)" + storage))
|
||||
result.extend((name, sql) for sql in indexes)
|
||||
if computed or row_checks:
|
||||
result.append((name, "CREATE TRIGGER dg_gc_"+hashlib.sha256(name.encode()).hexdigest()[:16]
|
||||
+" BEFORE INSERT OR UPDATE ON "+name+" FOR EACH ROW BEGIN\n"+"\n".join(computed+row_checks)+"\nEND;"))
|
||||
if timestamps:
|
||||
# Explicit application timestamps remain authoritative.
|
||||
body = "\n".join("IF NOT UPDATING('" + col.upper() + "') THEN :NEW." + col + " := LOCALTIMESTAMP; END IF;" for col in timestamps)
|
||||
result.append((name, "CREATE TRIGGER dg_ut_" + hashlib.sha256(name.encode()).hexdigest()[:16]
|
||||
+ " BEFORE UPDATE ON " + name + " FOR EACH ROW BEGIN\n" + body + "\nEND;"))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
tables, digests = collect()
|
||||
output = ROOT / "db/dameng/schema.sql"
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
fingerprint = hashlib.sha256("\n".join(digests).encode()).hexdigest()
|
||||
header = "-- Fresh-install DM schema; target 8.4.4.80 Pack89.\n-- Source fingerprint: " + fingerprint + "\n"
|
||||
rendered = render(tables)
|
||||
output.write_text(header + "\n".join("-- @statement " + name + "\n" + sql + ("\n/\n" if sql.startswith("CREATE TRIGGER") else ";\n") for name, sql in rendered))
|
||||
print("Generated", len(tables), "tables and", len(rendered), "schema statements; source fingerprint", fingerprint)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile reviewed historical seed DML in memory; emit final fresh-install values only.
|
||||
|
||||
SQLite is an offline calculation engine, never a supported platform database.
|
||||
Unknown statements stop generation. Runtime upgrade guards are replaced by fresh-seed invariants.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from dameng_sql import statements, mask_literals, restore_literals, split_top_level
|
||||
|
||||
spec = importlib.util.spec_from_file_location("baseline", __file__.replace("build-dameng-seed.py", "build-dameng-baseline.py"))
|
||||
baseline = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(baseline)
|
||||
STAMP = "2000-01-01 00:00:00"
|
||||
|
||||
|
||||
def table_sql(name, nodes):
|
||||
columns = []
|
||||
for key, node in nodes.items():
|
||||
if re.match(r"UNIQUE\s+\(",node,re.I):
|
||||
columns.append(node)
|
||||
elif key.startswith("column:"):
|
||||
text, literals = mask_literals(node)
|
||||
field, kind = text.split()[:2]
|
||||
affinity = "INTEGER" if re.match(r"(?:BIG|TINY|SMALL)?INT|BOOLEAN", kind, re.I) else "REAL" if re.match(r"DECIMAL|DOUBLE|FLOAT", kind, re.I) else "TEXT"
|
||||
default = re.search(r"\bDEFAULT\s+(__DG_LITERAL_\d+__|NULL|TRUE|FALSE|[-\d.]+|CURRENT_TIMESTAMP(?:\(\d*\))?)", text, re.I)
|
||||
value = ""
|
||||
if default:
|
||||
term = restore_literals(default.group(1), literals)
|
||||
if term.upper().startswith("CURRENT_TIMESTAMP"): term = "'"+STAMP+"'"
|
||||
value = " DEFAULT "+term
|
||||
columns.append('"'+field+'" '+affinity+value)
|
||||
elif re.match(r"PRIMARY KEY", node, re.I):
|
||||
columns.append(node)
|
||||
elif re.match(r"UNIQUE KEY", node, re.I) and not re.search(r"\(\d+\)",node):
|
||||
columns.append(re.sub(r"UNIQUE KEY\s+\w+", "UNIQUE", node, flags=re.I))
|
||||
columns.sort(key=lambda value: not value.startswith('"'))
|
||||
return "CREATE TABLE "+name+"("+",".join(columns)+")"
|
||||
|
||||
|
||||
def translate(raw, variables):
|
||||
text, literals = mask_literals(raw)
|
||||
text = re.sub(r"`(\w+)`", r"\1", text)
|
||||
text = re.sub(r"NOW\(\d*\)|UTC_TIMESTAMP\(\d*\)", "'"+STAMP+"'", text, flags=re.I)
|
||||
text = text.replace("<=>", " IS ")
|
||||
if "JSON_OBJECT(" in text.upper():
|
||||
text=re.sub(r"\b(TRUE|FALSE)\b",lambda m:"JSON('"+m.group(1).lower()+"')",text,flags=re.I)
|
||||
text = re.sub(r"\bBINARY\s+(?=\w)", "", text, flags=re.I) # SQLite text comparison is binary.
|
||||
text = re.sub(r"INSERT IGNORE", "INSERT OR IGNORE", text, flags=re.I)
|
||||
derived = re.search(r"FROM\s+\((.+)\)\s+AS\s+(\w+)\s*\(([^)]+)\)", text, re.I|re.S)
|
||||
if derived:
|
||||
text = "WITH "+derived.group(2)+"("+derived.group(3)+") AS ("+derived.group(1)+") "+text[:derived.start()]+"FROM "+derived.group(2)+text[derived.end():]
|
||||
duplicate = re.search(r"\s+ON DUPLICATE KEY UPDATE\s+(\w+)\s*=\s*\1\s*$", text, re.I)
|
||||
if duplicate:
|
||||
text = text[:duplicate.start()]
|
||||
text = re.sub(r"^INSERT INTO", "INSERT OR IGNORE INTO", text, flags=re.I)
|
||||
text = re.sub(r"@(\w+)", lambda m: str(variables[m.group(1)]), text)
|
||||
join = re.match(r"UPDATE\s+(\w+)\s+(\w+)\s+JOIN\s+(\w+)\s+(\w+)\s+ON\s+(.+?)\s+SET\s+(.+)", text, re.I|re.S)
|
||||
if join:
|
||||
table, alias, other, other_alias, condition, rest = join.groups()
|
||||
parts = re.split(r"\s+WHERE\s+", rest, maxsplit=1, flags=re.I)
|
||||
assignments = re.sub(r"(^|,)\s*"+alias+r"\.(\w+)\s*=", r"\1\2=", parts[0])
|
||||
text = "UPDATE "+table+" AS "+alias+" SET "+assignments+" FROM "+other+" AS "+other_alias+" WHERE ("+condition+")"
|
||||
if len(parts)>1: text += " AND ("+parts[1]+")"
|
||||
return restore_literals(text,literals)
|
||||
|
||||
|
||||
def main():
|
||||
tables, _ = baseline.collect()
|
||||
db = sqlite3.connect(":memory:")
|
||||
db.create_function("CONCAT", -1, lambda *args: None if None in args else "".join(map(str,args)))
|
||||
db.create_function("IF", 3, lambda test, yes, no: yes if test else no)
|
||||
db.create_function("sysdate", 0, lambda: STAMP)
|
||||
for name,nodes in tables.items(): db.execute(table_sql(name,nodes))
|
||||
variables = {}
|
||||
applied = 0
|
||||
for path in baseline.sources():
|
||||
for raw in statements(path.read_text()):
|
||||
if re.match(r"(?:CREATE DATABASE|CREATE TABLE|ALTER TABLE|SET NAMES|START TRANSACTION|COMMIT|USE)\b", raw, re.I): continue
|
||||
if re.match(r"INSERT INTO\s+`?(?:test_demo|test_tree)\b",raw,re.I): continue
|
||||
if re.match(r"INSERT INTO\s+(?:tmp_\w*guard|sec_vocabulary_\w+_guard|metric_library_guard|model_algorithm_guard|log_tabs_guard)\b",raw,re.I):
|
||||
continue # Old installed-state/count/hash preconditions do not describe a new deployment.
|
||||
if path.name == "V20260916.151__enable_security_vocabulary_request_audit.sql" and raw.startswith("INSERT INTO sec_vocabulary_check_guard"):
|
||||
continue # MySQL 8.4.9 dictionary/DDL preflight; final constraints are verified by the DM schema installer.
|
||||
if path.name == "V20260916.148__repair_ingestion_table_file_layer_binding.sql" and raw.upper().startswith("UPDATE "):
|
||||
if db.execute("SELECT COUNT(*) FROM store_table_file").fetchone()[0] != 0:
|
||||
raise ValueError("Fresh seed unexpectedly contains business table files")
|
||||
continue # A historical repair has no rows in a fresh installation.
|
||||
try:
|
||||
assignment = re.match(r"SET\s+@(\w+)\s*=\s*(.+)$",raw,re.I|re.S)
|
||||
sql = translate(raw, variables) if not assignment and not re.search(r"INTO @",raw,re.I) else raw
|
||||
if assignment:
|
||||
expression = translate(assignment.group(2),variables).strip()
|
||||
variables[assignment.group(1)] = db.execute("SELECT "+expression).fetchone()[0]
|
||||
elif sql.upper().startswith("SET "):
|
||||
if not re.match(r"SET (?:FOREIGN_KEY_CHECKS|SQL_MODE|SESSION group_concat_max_len|TRANSACTION ISOLATION LEVEL SERIALIZABLE)",sql,re.I): raise ValueError("unhandled SET")
|
||||
elif re.match(r"SELECT .+ INTO @",raw,re.I|re.S):
|
||||
match=re.match(r"SELECT\s+(.+?)\s+INTO\s+@(\w+)\s+(.+)",raw,re.I|re.S)
|
||||
variables[match.group(2)] = db.execute(translate("SELECT "+match.group(1)+" "+match.group(3),variables)).fetchone()[0]
|
||||
elif sql.upper().startswith("SELECT "):
|
||||
db.execute(sql).fetchall()
|
||||
elif re.match(r"CREATE TEMPORARY TABLE",sql,re.I):
|
||||
db.execute(sql)
|
||||
elif re.match(r"DROP TEMPORARY TABLE",sql,re.I):
|
||||
db.execute(re.sub("DROP TEMPORARY TABLE","DROP TABLE",sql,flags=re.I))
|
||||
elif re.match(r"(?:INSERT|UPDATE|DELETE|WITH)\b",sql,re.I):
|
||||
db.execute(sql)
|
||||
applied+=1
|
||||
else: raise ValueError("unhandled statement")
|
||||
except Exception as error:
|
||||
# Seed files are public source; never render connection or private settings.
|
||||
raise RuntimeError(path.name+": "+raw[:90]+" -> "+str(error)) from error
|
||||
db.execute("UPDATE md_native_cutover SET backend='NATIVE',epoch=1 WHERE domain_key='metadata'")
|
||||
db.execute("UPDATE sys_user SET password='!DISABLED!',status='1',login_ip=NULL,login_date=NULL")
|
||||
db.execute("UPDATE sys_oss_config SET status='N',access_key='',secret_key=''")
|
||||
db.execute("UPDATE sys_config SET config_value='' WHERE config_key='sys.user.initPassword'")
|
||||
db.execute("""WITH RECURSIVE inactive(menu_id,depth) AS (
|
||||
SELECT menu_id,0 FROM sys_menu WHERE menu_id IN (1761400000000000003,1761400000000000005,1761400000000011616,1761400000000011618)
|
||||
UNION ALL SELECT m.menu_id,i.depth+1 FROM sys_menu m JOIN inactive i ON m.parent_id=i.menu_id WHERE i.depth<3)
|
||||
UPDATE sys_menu SET status='1' WHERE menu_id IN (SELECT menu_id FROM inactive)
|
||||
OR component='system/oss/config' OR perms LIKE 'system:ossConfig:%'""")
|
||||
for query in (
|
||||
"SELECT COUNT(*) FROM sys_role_menu r LEFT JOIN sys_role s ON s.role_id=r.role_id LEFT JOIN sys_menu m ON m.menu_id=r.menu_id WHERE s.role_id IS NULL OR m.menu_id IS NULL",
|
||||
"SELECT COUNT(*) FROM sys_menu m LEFT JOIN sys_menu p ON p.menu_id=m.parent_id WHERE m.parent_id<>0 AND p.menu_id IS NULL",
|
||||
"SELECT COUNT(*) FROM sys_user WHERE status='0'",
|
||||
):
|
||||
if db.execute(query).fetchone()[0]: raise ValueError("Fresh seed relationship/account invariant failed")
|
||||
rows = {}
|
||||
for name in tables:
|
||||
values = db.execute("SELECT * FROM "+name).fetchall()
|
||||
if values:
|
||||
columns = [r[1] for r in db.execute("PRAGMA table_info("+name+")")]
|
||||
rows[name] = {"columns":columns,"rows":values}
|
||||
output=baseline.ROOT/"db/dameng/seed.json"
|
||||
output.write_text(json.dumps(rows,ensure_ascii=False,indent=2)+"\n")
|
||||
print("SEED_DML="+str(applied)+" TABLES="+str(len(rows))+" ROWS="+str(sum(len(v['rows']) for v in rows.values())))
|
||||
|
||||
|
||||
if __name__=="__main__": main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""SQL lexical helpers for reviewed, offline DM initialization generation.
|
||||
|
||||
These helpers do not connect to a database or rewrite application SQL at runtime.
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
def statements(sql):
|
||||
"""Split reviewed MySQL inputs, honoring comments, quoted text and escapes."""
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(sql):
|
||||
if sql.startswith("--", i) or sql[i] == "#":
|
||||
end = sql.find("\n", i)
|
||||
i = len(sql) if end < 0 else end
|
||||
out.append(" ")
|
||||
elif sql.startswith("/*", i):
|
||||
end = sql.find("*/", i + 2)
|
||||
if end < 0:
|
||||
raise ValueError("unterminated comment")
|
||||
i = end + 2
|
||||
out.append(" ")
|
||||
elif sql[i] in "'\"`":
|
||||
quote = sql[i]
|
||||
start = i
|
||||
i += 1
|
||||
while i < len(sql):
|
||||
if sql[i] == "\\":
|
||||
i += 2
|
||||
elif sql[i] == quote:
|
||||
i += 1
|
||||
if i < len(sql) and sql[i] == quote:
|
||||
i += 1
|
||||
else:
|
||||
break
|
||||
else:
|
||||
i += 1
|
||||
out.append(sql[start:i])
|
||||
elif sql[i] == ";":
|
||||
value = "".join(out).strip()
|
||||
if value:
|
||||
yield value
|
||||
out = []
|
||||
i += 1
|
||||
else:
|
||||
out.append(sql[i])
|
||||
i += 1
|
||||
value = "".join(out).strip()
|
||||
if value:
|
||||
yield value
|
||||
|
||||
|
||||
def mask_literals(sql):
|
||||
literals = []
|
||||
def replace(match):
|
||||
literals.append(match.group(0))
|
||||
return "__DG_LITERAL_%d__" % (len(literals) - 1)
|
||||
masked = re.sub(r"'(?:''|\\.|[^'\\])*'", replace, sql)
|
||||
return masked, literals
|
||||
|
||||
|
||||
def restore_literals(sql, literals):
|
||||
return re.sub(r"__DG_LITERAL_(\d+)__", lambda m: literals[int(m.group(1))], sql)
|
||||
|
||||
|
||||
def rewrite_sha256(sql):
|
||||
masked, literals = mask_literals(sql)
|
||||
for match in reversed(list(re.finditer(r"SHA2\s*\(", masked, re.I))):
|
||||
end = closing_paren(masked, match.end() - 1)
|
||||
args = split_top_level(masked[match.end():end - 1])
|
||||
if len(args) != 2 or args[1].strip() != "256":
|
||||
raise ValueError("only SHA-256 is supported")
|
||||
value = args[0]
|
||||
replacement = ("(CASE WHEN " + value + " IS NULL THEN NULL WHEN LENGTH(" + value + ")=0 THEN "
|
||||
+ "'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' ELSE "
|
||||
+ "LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(" + value + " AS CLOB),DBMS_CRYPTO.HASH_SH256))) END)")
|
||||
masked = masked[:match.start()] + replacement + masked[end:]
|
||||
return restore_literals(masked, literals)
|
||||
|
||||
|
||||
def split_top_level(sql, separator=","):
|
||||
masked, literals = mask_literals(sql)
|
||||
depth = 0
|
||||
start = 0
|
||||
parts = []
|
||||
for i, char in enumerate(masked):
|
||||
depth += (char == "(") - (char == ")")
|
||||
if depth < 0:
|
||||
raise ValueError("unbalanced SQL")
|
||||
if char == separator and depth == 0:
|
||||
parts.append(restore_literals(masked[start:i].strip(), literals))
|
||||
start = i + 1
|
||||
if depth:
|
||||
raise ValueError("unbalanced SQL")
|
||||
parts.append(restore_literals(masked[start:].strip(), literals))
|
||||
return parts
|
||||
|
||||
|
||||
def closing_paren(sql, start):
|
||||
if sql[start] != "(":
|
||||
raise ValueError("expected opening parenthesis")
|
||||
depth = 0
|
||||
i = start
|
||||
while i < len(sql):
|
||||
char=sql[i]
|
||||
if char in "'\"`":
|
||||
quote=char
|
||||
i+=1
|
||||
while i<len(sql):
|
||||
if sql[i]=="\\": i+=2
|
||||
elif sql[i]==quote:
|
||||
i+=1
|
||||
if i<len(sql) and sql[i]==quote: i+=1
|
||||
else: break
|
||||
else: i+=1
|
||||
continue
|
||||
depth += (char == "(") - (char == ")")
|
||||
if depth == 0:
|
||||
return i+1
|
||||
i+=1
|
||||
raise ValueError("unbalanced SQL")
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble reviewed schema, safe seeds and allowlisted exported data for a fresh install."""
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
OUT = ROOT / 'release/dameng-20261118'
|
||||
spec = importlib.util.spec_from_file_location('seed', ROOT / 'script/database/apply-dameng-seed.py')
|
||||
seed = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(seed)
|
||||
data = json.loads((ROOT / 'db/dameng/seed.json').read_text())
|
||||
source = OUT / 'database/library-data.sql'
|
||||
counts, samples, longest = {}, {}, {}
|
||||
buffer = ''
|
||||
for line in source.open():
|
||||
if not buffer and line.startswith('-- '):
|
||||
name, count = line[3:].strip().split(' rows=')
|
||||
assert counts.get(name, 0) == int(count), name
|
||||
counts[name] = int(count)
|
||||
continue
|
||||
buffer += line
|
||||
if buffer.count("'") % 2 or not buffer.rstrip().endswith(';'):
|
||||
continue
|
||||
table = buffer.split('(', 1)[0].split()[-1]
|
||||
counts[table] = counts.get(table, 0) + 1
|
||||
samples.setdefault(table, buffer.rstrip().removesuffix(';'))
|
||||
if len(buffer) > len(longest.get(table, '')):
|
||||
longest[table] = buffer.rstrip().removesuffix(';')
|
||||
buffer = ''
|
||||
assert not buffer
|
||||
sql = OUT / 'database/aixun-datagov-init.sql'
|
||||
with sql.open('w') as out:
|
||||
out.write('-- DM8 fresh install only. Execute as SYSDBA; stop on any error. UTF-8.\n')
|
||||
out.write('-- Never run on an existing schema. Configure application DM_SCHEMA=AIXUN_DATAGOV_PROD.\n')
|
||||
out.write('CREATE SCHEMA AIXUN_DATAGOV_PROD AUTHORIZATION SYSDBA;\nSET SCHEMA AIXUN_DATAGOV_PROD;\n')
|
||||
out.write((ROOT / 'db/dameng/schema.sql').read_text())
|
||||
out.write('\n-- Built-in initialization data; accounts disabled until password configured.\n')
|
||||
for table, values in data.items():
|
||||
if table in counts:
|
||||
continue
|
||||
counts[table] = len(values['rows'])
|
||||
for row in values['rows']:
|
||||
statement = 'INSERT INTO '+table+'('+','.join(values['columns'])+') VALUES('+','.join(map(seed.literal,row))+')'
|
||||
out.write(statement+';\n')
|
||||
samples.setdefault(table, statement)
|
||||
with source.open() as incoming:
|
||||
shutil.copyfileobj(incoming, out)
|
||||
out.write('\nCOMMIT;\n-- Expected row counts for post-install verification:\n')
|
||||
for table,count in counts.items():
|
||||
out.write(f"SELECT '{table}' AS TABLE_NAME, COUNT(*) AS ACTUAL_ROWS, {count} AS EXPECTED_ROWS FROM {table};\n")
|
||||
(OUT / 'database/row-counts.json').write_text(json.dumps(counts, indent=2)+'\n')
|
||||
with (OUT / 'database/prepare-samples.txt').open('w') as out:
|
||||
for name, statement in list(samples.items())+[(k+'_longest',v) for k,v in longest.items()]:
|
||||
out.write(name+'\t'+base64.b64encode(statement.encode()).decode()+'\n')
|
||||
backend = OUT / 'backend'
|
||||
backend.mkdir(exist_ok=True)
|
||||
jars=[]
|
||||
for base in ['aixun-auth','aixun-gateway','aixun-modules','aixun-common','aixun-api']:
|
||||
for jar in sorted((ROOT/base).glob('**/target/*.jar')):
|
||||
with zipfile.ZipFile(jar) as archive:
|
||||
executable='BOOT-INF/classes/' in archive.namelist()
|
||||
target=backend / ('services' if executable else 'libraries') / jar.name
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
shutil.copy2(jar,target)
|
||||
jars.append({'file':str(target.relative_to(OUT)),'source':str(jar.relative_to(ROOT)),'executable':executable})
|
||||
(OUT/'backend/jars.json').write_text(json.dumps(jars,indent=2)+'\n')
|
||||
shutil.copytree(ROOT/'aixun-ui/dist', OUT/'frontend/dist', dirs_exist_ok=True)
|
||||
print('TABLES_WITH_DATA',len(counts),'ROWS',sum(counts.values()),'JARS',len(jars),'SERVICES',sum(j['executable'] for j in jars))
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only DM inspection using private JSON credentials and the pinned JDBC jar."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True, type=Path)
|
||||
parser.add_argument("--write-probe", action="store_true", help="create and remove a probe table only in AIXUN_DATAGOV_DM_TEST")
|
||||
parser.add_argument("--index-probe", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = args.config.resolve()
|
||||
if not path.is_relative_to(ROOT / "runtime/dev-private") or not path.is_file():
|
||||
parser.error("configuration must be a private file under runtime/dev-private")
|
||||
if stat.S_IMODE(path.stat().st_mode) & 0o077:
|
||||
parser.error("private configuration permissions must be 0600 or stricter")
|
||||
values = json.loads(path.read_text())
|
||||
environment = os.environ.copy()
|
||||
for key in ("host", "port", "username", "password"):
|
||||
if key not in values or not str(values[key]):
|
||||
parser.error("missing private connection field: " + key)
|
||||
environment["DATAGOV_DM_" + key.upper()] = str(values[key])
|
||||
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/DamengProbe.java"), *(["--index-probe"] if args.index_probe else ["--write-probe"] if args.write_probe else [])
|
||||
], env=environment, timeout=90).returncode
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from dameng_sql import closing_paren, mask_literals, restore_literals, statements
|
||||
|
||||
spec=importlib.util.spec_from_file_location("baseline",Path(__file__).with_name("build-dameng-baseline.py"))
|
||||
baseline=importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(baseline)
|
||||
|
||||
|
||||
class DamengSqlTest(unittest.TestCase):
|
||||
def test_parenthesis_scan_handles_quoted_delimiters_and_masked_literals(self):
|
||||
sql="fn('中文)(',nested('it''s)')) trailing"
|
||||
self.assertEqual(sql[:closing_paren(sql,2)],"fn('中文)(',nested('it''s)'))")
|
||||
masked,_=mask_literals(sql)
|
||||
self.assertTrue(masked[:closing_paren(masked,2)].endswith("))"))
|
||||
|
||||
def test_statement_split_preserves_strings_and_ignores_comments(self):
|
||||
self.assertEqual(list(statements("-- ignored;\nSELECT ';--保留' FROM DUAL; /* ignored ; */ SELECT 2;")),
|
||||
["SELECT ';--保留' FROM DUAL","SELECT 2"])
|
||||
|
||||
def test_literal_mask_roundtrip_is_lossless(self):
|
||||
sql="CHECK(code='REGEXP; VARCHAR(2) SHA2(''x'',256) 中文')"
|
||||
masked,literals=mask_literals(sql)
|
||||
self.assertEqual(restore_literals(masked,literals),sql)
|
||||
|
||||
def test_conversion_never_rewrites_literal_documentation(self):
|
||||
value=baseline.adapt_node("name VARCHAR(128) COMMENT 'VARCHAR(2) ON UPDATE CURRENT_TIMESTAMP'")
|
||||
self.assertEqual(value,"name VARCHAR(128 CHAR) COMMENT 'VARCHAR(2) ON UPDATE CURRENT_TIMESTAMP'")
|
||||
|
||||
def test_json_numeric_cast_has_explicit_lob_to_text_boundary(self):
|
||||
value=baseline.adapt_node("CHECK(CAST(JSON_UNQUOTE(JSON_EXTRACT(payload,'$.size')) AS SIGNED)>0)")
|
||||
self.assertIn("CAST(CAST(JSON_UNQUOTE(JSON_EXTRACT(payload,'$.size')) AS VARCHAR(32767)) AS BIGINT)",value)
|
||||
|
||||
def test_unbalanced_input_is_rejected(self):
|
||||
with self.assertRaises(ValueError):closing_paren("fn('x',nested(1)",2)
|
||||
|
||||
|
||||
if __name__=="__main__":unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit additive library transfer. Passwords remain in process environment."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('mode', choices=['inventory', 'plan', 'apply', 'verify'])
|
||||
p.add_argument('--config', type=Path, required=True)
|
||||
p.add_argument('--tables')
|
||||
p.add_argument('--menus', action='store_true', help='synchronize menus and existing-role menu grants exactly')
|
||||
a = p.parse_args()
|
||||
if bool(a.tables) == bool(a.menus):
|
||||
p.error('Select exactly one of --tables or --menus')
|
||||
os.umask(0o077)
|
||||
path = a.config.resolve()
|
||||
if not path.is_relative_to(ROOT/'runtime/dev-private') or path.stat().st_mode & 0o077:
|
||||
p.error('Private configuration must be under runtime/dev-private with mode 0600')
|
||||
c = json.loads(subprocess.check_output(['docker', 'inspect', 'aixun-datagov-mysql']))[0]
|
||||
labels = c['Config']['Labels']
|
||||
assert labels['com.aixun.project'] == 'aixun-datagov'
|
||||
assert labels['com.docker.compose.project'] == 'aixun-datagov-local'
|
||||
assert c['State']['Running']
|
||||
port = c['HostConfig']['PortBindings']['3306/tcp'][0]['HostPort']
|
||||
source = dict(x.split('=', 1) for x in c['Config']['Env'] if '=' in x)
|
||||
env = os.environ.copy()
|
||||
env.update(DG_SOURCE_PORT=port, DG_SOURCE_PASSWORD=source['MYSQL_ROOT_PASSWORD'])
|
||||
for k, v in json.loads(path.read_text()).items():
|
||||
env['DATAGOV_DM_'+k.upper()] = str(v)
|
||||
repo = Path.home()/'.m2/repository'
|
||||
jars = [ROOT/'script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar',
|
||||
repo/'com/mysql/mysql-connector-j/9.7.0/mysql-connector-j-9.7.0.jar',
|
||||
repo/'com/fasterxml/jackson/core/jackson-databind/2.21.4/jackson-databind-2.21.4.jar',
|
||||
repo/'com/fasterxml/jackson/core/jackson-core/2.21.4/jackson-core-2.21.4.jar',
|
||||
repo/'com/fasterxml/jackson/core/jackson-annotations/2.21/jackson-annotations-2.21.jar']
|
||||
assert all(x.is_file() for x in jars)
|
||||
java = 'MenuTransfer.java' if a.menus else 'LibraryTransfer.java'
|
||||
return subprocess.run(['java', '-Xmx1536m', '--class-path', os.pathsep.join(map(str,jars)),
|
||||
str(ROOT/'script/database'/java), a.mode, *([] if a.menus else [a.tables])], env=env, cwd=ROOT).returncode
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a project command using a private DM JSON file, without putting secrets in argv or shell text."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config",required=True,type=Path)
|
||||
parser.add_argument("command",nargs=argparse.REMAINDER)
|
||||
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")
|
||||
values=json.loads(path.read_text());environment=os.environ.copy()
|
||||
for key in ("host","port","username","password","schema"):
|
||||
if not values.get(key):parser.error("missing private field: "+key)
|
||||
environment["DM_"+key.upper()]=str(values[key])
|
||||
environment["DATAGOV_DM_"+key.upper()]=str(values[key])
|
||||
if not re.fullmatch(r"AIXUN_DATAGOV_[A-Z0-9_]+",values['schema']):parser.error("dedicated DataGov schema required")
|
||||
environment['DATAGOV_DM_CONFIG']=str(path)
|
||||
command=args.command[1:] if args.command[:1]==['--'] else args.command
|
||||
if not command:parser.error("missing project command")
|
||||
os.chdir(ROOT)
|
||||
os.execvpe(command[0],command,environment)
|
||||
@@ -0,0 +1,35 @@
|
||||
# Copy with ./script/datagov/init-env.sh. Never commit .env.datagov.
|
||||
COMPOSE_PROJECT_NAME=aixun-datagov-local
|
||||
|
||||
AIXUN_DATAGOV_FRONTEND_PORT=28000
|
||||
AIXUN_DATAGOV_GATEWAY_PORT=28080
|
||||
AIXUN_DATAGOV_NACOS_CONSOLE_PORT=28081
|
||||
AIXUN_DATAGOV_NACOS_CLIENT_PORT=28848
|
||||
AIXUN_DATAGOV_NACOS_GRPC_PORT=29848
|
||||
AIXUN_DATAGOV_NACOS_GRPC_RAFT_PORT=29849
|
||||
AIXUN_DATAGOV_MYSQL_PORT=23307
|
||||
AIXUN_DATAGOV_REDIS_PORT=26380
|
||||
AIXUN_DATAGOV_AUTH_PORT=29210
|
||||
AIXUN_DATAGOV_SYSTEM_PORT=29201
|
||||
AIXUN_DATAGOV_RESOURCE_PORT=29204
|
||||
AIXUN_DATAGOV_INTEGRATION_PORT=29310
|
||||
AIXUN_DATAGOV_DATAOPS_PORT=29320
|
||||
AIXUN_DATAGOV_GOVERNANCE_PORT=29330
|
||||
AIXUN_DATAGOV_DATAPRODUCT_PORT=29340
|
||||
AIXUN_DATAGOV_OPENMETADATA_URL=http://127.0.0.1:33185
|
||||
|
||||
AIXUN_DATAGOV_DB_SCHEMA=aixun_datagov_system
|
||||
AIXUN_DATAGOV_DB_USERNAME=datagov_app
|
||||
AIXUN_DATAGOV_DB_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_MYSQL_ROOT_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_REDIS_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_NACOS_NAMESPACE=aixun-datagov-local
|
||||
AIXUN_DATAGOV_NACOS_GROUP=AIXUN_DATAGOV_GROUP
|
||||
AIXUN_DATAGOV_NACOS_USERNAME=nacos
|
||||
AIXUN_DATAGOV_NACOS_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_NACOS_AUTH_TOKEN=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_NACOS_IDENTITY_KEY=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_NACOS_IDENTITY_VALUE=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_JWT_SECRET=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_ADMIN_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
AIXUN_DATAGOV_UAT_PASSWORD=GENERATED_BY_INIT_ENV
|
||||
@@ -0,0 +1,29 @@
|
||||
package cn.aixunkeji.datagov.dataproduct.bi;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery;
|
||||
import cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
/** Executes no database access. Uses the already-built production compiler and Owner result decoder. */
|
||||
public final class BiOtherMysqlProbe {
|
||||
private static String encode(String value){return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));}
|
||||
private static String decode(String value){return "-".equals(value)?null:new String(Base64.getDecoder().decode(value),StandardCharsets.UTF_8);}
|
||||
public static void main(String[] args) throws ReflectiveOperationException {
|
||||
String mode=args[0],aggregate=args[1];int top=Integer.parseInt(args[2]);
|
||||
if(!Set.of("AVG","COUNT_DISTINCT","SUM").contains(aggregate)||top<1||top>2)throw new IllegalArgumentException();
|
||||
if("compile".equals(mode)){
|
||||
var plan=new AnalyticsQuery.Plan(List.of(),List.of("category"),List.of(new AnalyticsQuery.Measure("amount",aggregate,"value")),List.of(new AnalyticsQuery.Filter("tenant","EQ",List.of("fixture' OR 1=1 --"))),List.of(),10,false,new AnalyticsQuery.CategoryRemainder(top));
|
||||
var compiled=AnalyticsSqlCompiler.compileForSource(plan,List.of("category","amount","tenant"),"MYSQL","aixun_datagov_system",null,"bi_other_fixture");
|
||||
System.out.println(encode(compiled.sql()));System.out.println(String.join(",",compiled.parameters().stream().map(BiOtherMysqlProbe::encode).toList()));return;
|
||||
}
|
||||
if(!"decode".equals(mode))throw new IllegalArgumentException();
|
||||
var rows=new ArrayList<Map<String,String>>();try(var input=new Scanner(System.in,StandardCharsets.UTF_8)){while(input.hasNextLine()){var values=input.nextLine().split("\\t",-1);if(values.length!=3)throw new IllegalArgumentException();var row=new LinkedHashMap<String,String>();row.put("category",decode(values[0]));row.put("value",decode(values[1]));row.put(AnalyticsQuery.CATEGORY_LEVEL,decode(values[2]));rows.add(row);}}
|
||||
var plan=new BiQuerySource.Plan(List.of("category","amount"),List.of("category"),List.of(new BiQuerySource.Measure("amount",aggregate,"value")),List.of(),List.of(),10,false,new BiQuerySource.CategoryLimit(top));
|
||||
// Source-file launch uses a distinct classloader. Reflection reaches the fixed package-private Owner method without changing production visibility.
|
||||
var decoder=Class.forName("cn.aixunkeji.datagov.dataproduct.bi.BiCategoryResults").getDeclaredMethod("decode",BiQuerySource.Plan.class,BiQuerySource.Result.class);decoder.setAccessible(true);
|
||||
try{var result=(BiQuerySource.Result)decoder.invoke(null,plan,new BiQuerySource.Result("SUCCEEDED",List.of("category","value",AnalyticsQuery.CATEGORY_LEVEL),List.copyOf(rows),false,LocalDateTime.now(),"Synthetic MySQL observation"));System.out.println("SUCCEEDED\t"+result.rows().size()+"\t"+Objects.toString(result.categoryRemainder().otherRowIndex(),"NONE"));}
|
||||
catch(java.lang.reflect.InvocationTargetException error){var cause=error.getCause();if(!cause.getClass().getName().equals("cn.aixunkeji.datagov.dataproduct.bi.BiException"))throw error;var code=cause.getClass().getDeclaredField("code");code.setAccessible(true);System.out.println("REJECTED\t"+code.get(cause));}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package cn.aixunkeji.datagov.integration.tablefile;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/** Actual production plan/compiler over synthetic rows, without claiming Native policy or Browser acceptance. */
|
||||
public final class BiPeriodComparisonMysqlProbe {
|
||||
static String encode(String value){return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));}
|
||||
public static void main(String[] args){
|
||||
var bucket=new AnalyticsQuery.TimeBucket("day",args[0],args.length>3?Integer.valueOf(args[3]):null);
|
||||
var comparison=new AnalyticsQuery.PeriodComparison("PREVIOUS_YEAR",args[1],args[2],List.of(new AnalyticsQuery.ComparisonOutput("average","baseline","difference","rate"),new AnalyticsQuery.ComparisonOutput("people","people_baseline","people_difference","people_rate")));
|
||||
var plan=new AnalyticsQuery.Plan(List.of(),List.of("day","area"),List.of(new AnalyticsQuery.Measure("amount","AVG","average"),new AnalyticsQuery.Measure("person","COUNT_DISTINCT","people")),List.of(new AnalyticsQuery.Filter("tenant","EQ",List.of("fixture' OR 1=1 --"))),List.of(),50,false,null,bucket,comparison);
|
||||
var compiled=AnalyticsSqlCompiler.compileForSource(plan,List.of("day","area","amount","person","tenant"),"MYSQL","aixun_datagov_system",null,"bi_yoy_fixture");
|
||||
if(!comparison.equals(compiled.comparison()))throw new IllegalStateException("Comparison execution evidence is missing");
|
||||
System.out.println(encode(compiled.sql()));System.out.println(String.join(",",compiled.parameters().stream().map(BiPeriodComparisonMysqlProbe::encode).toList()));System.out.println(String.join(",",compiled.columns()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package cn.aixunkeji.datagov.integration.tablefile;
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.*;
|
||||
import java.time.Instant;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/** Actual production DATE arithmetic and compiler. Inputs and all source rows are synthetic. */
|
||||
public final class BiRelativeWindowMysqlProbe {
|
||||
static String encode(String value){return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));}
|
||||
public static void main(String[] args){
|
||||
var window=AnalyticsRelativeWindow.resolve(new AnalyticsQuery.RelativeWindow("day",args[0],Integer.parseInt(args[1]),args[2]),Instant.parse(args[3]));
|
||||
var filters=new ArrayList<AnalyticsQuery.Filter>();filters.add(new AnalyticsQuery.Filter("tenant","EQ",List.of("fixture' OR 1=1 --")));if(args.length>4)filters.add(new AnalyticsQuery.Filter("day","GTE",List.of(args[4])));
|
||||
var plan=new AnalyticsQuery.Plan(List.of(),List.of(),List.of(new AnalyticsQuery.Measure("amount","AVG","average"),new AnalyticsQuery.Measure("person","COUNT_DISTINCT","people")),List.copyOf(filters),List.of(),50,false,null,null,null,window);
|
||||
var compiled=AnalyticsSqlCompiler.compileForSource(plan,List.of("day","amount","person","tenant"),"MYSQL","aixun_datagov_system",null,"bi_relative_fixture");
|
||||
if(!window.equals(compiled.relativeWindow()))throw new IllegalStateException("Frozen window metadata missing");
|
||||
System.out.println(encode(compiled.sql()));System.out.println(String.join(",",compiled.parameters().stream().map(BiRelativeWindowMysqlProbe::encode).toList()));System.out.println(String.join(",",compiled.columns()));System.out.println(window.referenceDate()+","+window.startDate()+","+window.endDateExclusive());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package cn.aixunkeji.datagov.dataproduct.bi;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery;
|
||||
import cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
/** Source-file fixture only: actual production compiler and Owner validation, no database access here. */
|
||||
public final class BiTimeBucketMysqlProbe {
|
||||
static String encode(String value){return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));}
|
||||
static String decode(String value){return value.equals("-")?null:new String(Base64.getDecoder().decode(value),StandardCharsets.UTF_8);}
|
||||
public static void main(String[] args)throws ReflectiveOperationException {
|
||||
String mode=args[0],unit=args[1];if(!Set.of("DAY","WEEK","MONTH","QUARTER","YEAR","FISCAL_QUARTER","FISCAL_YEAR").contains(unit))throw new IllegalArgumentException();
|
||||
Integer fiscalMonth=args.length>3?Integer.valueOf(args[3]):null;
|
||||
if(mode.equals("compile")){
|
||||
var filters=new ArrayList<AnalyticsQuery.Filter>();filters.add(new AnalyticsQuery.Filter("tenant","EQ",List.of("fixture' OR 1=1 --")));
|
||||
if(args.length>2&&!args[2].equals("-"))filters.add(new AnalyticsQuery.Filter("day","GTE",List.of(args[2])));
|
||||
var plan=new AnalyticsQuery.Plan(List.of(),List.of("day"),List.of(new AnalyticsQuery.Measure("amount","AVG","average"),new AnalyticsQuery.Measure("person","COUNT_DISTINCT","people")),filters,List.of(new AnalyticsQuery.Sort("day","ASC")),50,false,null,new AnalyticsQuery.TimeBucket("day",unit,fiscalMonth));
|
||||
var sql=AnalyticsSqlCompiler.compileForSource(plan,List.of("day","amount","person","tenant"),"MYSQL","aixun_datagov_system",null,"bi_date_fixture");
|
||||
System.out.println(encode(sql.sql()));System.out.println(String.join(",",sql.parameters().stream().map(BiTimeBucketMysqlProbe::encode).toList()));return;
|
||||
}
|
||||
if(!mode.equals("validate"))throw new IllegalArgumentException();
|
||||
var rows=new ArrayList<Map<String,String>>();try(var input=new Scanner(System.in,StandardCharsets.UTF_8)){while(input.hasNextLine()){String[] values=input.nextLine().split("\\t",-1);if(values.length!=3)throw new IllegalArgumentException();var row=new LinkedHashMap<String,String>();row.put("day",decode(values[0]));row.put("average",decode(values[1]));row.put("people",decode(values[2]));rows.add(row);}}
|
||||
var bucket=new BiQuerySource.TimeBucket("day",unit,fiscalMonth);var plan=new BiQuerySource.Plan(List.of("day","amount","person"),List.of("day"),List.of(new BiQuerySource.Measure("amount","AVG","average"),new BiQuerySource.Measure("person","COUNT_DISTINCT","people")),List.of(),List.of(),50,false,null,bucket);
|
||||
var returned=new BiQuerySource.Result("SUCCEEDED",List.of("day","average","people"),rows,false,LocalDateTime.now(),null,null,Map.of(),null,null,bucket);
|
||||
var owner=Class.forName("cn.aixunkeji.datagov.dataproduct.bi.BiTimeBuckets").getDeclaredMethod("result",BiQuerySource.Plan.class,BiQuerySource.Result.class);owner.setAccessible(true);owner.invoke(null,plan,returned);System.out.println("SUCCEEDED\t"+rows.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# DataGov本地运行与局部交付
|
||||
|
||||
2026-10-10起使用deploy.sh和deployment/正式配置。旧租约、固定发布窗口、历史任务号和逐制品人工审批已撤销,见ADR-0033。
|
||||
|
||||
## 日常修复
|
||||
|
||||
先用script/quality/check.sh选择受影响检查/构建,再按deployment/README.md生成实际制品计划,连续完成用户已授权的局部apply。使用deploy.sh --help查看参数,--check-config SERVICE只读核对当前配置。
|
||||
|
||||
镜像也只构建目标应用,复用现有Docker构建缓存;下面是Governance示例,tag替换为本次交付名称:
|
||||
|
||||
~~~bash
|
||||
./script/quality/check.sh --backend-build aixun-modules/aixun-governance
|
||||
docker build --pull=false -f script/datagov/docker/java-service.Dockerfile --build-arg JAR_FILE=aixun-modules/aixun-governance/target/aixun-governance.jar --build-arg SERVICE_NAME=governance --build-arg RELEASE_ID=repair-20261010 -t aixun-datagov/governance:repair-20261010 .
|
||||
~~~
|
||||
|
||||
前端使用check.sh --frontend-build后,单独docker build --pull=false -f script/datagov/docker/frontend.Dockerfile --build-arg RELEASE_ID=repair-20261010 -t aixun-datagov/frontend:repair-20261010 .。普通交付不使用--no-cache或整栈Compose build,不导出镜像tar。
|
||||
|
||||
每个镜像流式验证一次,后续复用绑定不可变image ID的验证缓存,不保存大tar副本。Integration保持backend 172.21.0.8及m2-integration 172.29.0.8;Gateway发现地址保持backend 172.21.0.11。九个应用均保留原网络ID/IP、挂载和端口;网络/卷使用external引用,发布只重建目标服务,不build/pull/启动依赖。
|
||||
|
||||
前端保留现有持久资源卷和旧hash资源;现行Dockerfile携带实际public文件目录,favicon、品牌图片等公共URL随入口页更新,并在激活失败时恢复。构建生成的不可变资源仍拒绝同名不同内容。使用此标准Dockerfile构建新前端镜像,避免旧临时Dockerfile缺少公共文件映射。源码、容器部署和功能验收分别报告。
|
||||
|
||||
## 完整环境初始化
|
||||
|
||||
已有环境不要重复初始化。确需新建DataGov专属环境时才使用init-env.sh、preflight.sh和AIXUN_DATAGOV_INFRA_ONLY=1 ./script/datagov/start-local.sh --bootstrap。start-local.sh无参数和--help只显示帮助,初始化使用自动短锁。完整应用启动需已构建产物和明确范围;日常修复不使用start-local覆盖现有服务。stop-local.sh停止整个本项目环境,不用于日常修复,不删除卷。
|
||||
|
||||
## 隔离与恢复
|
||||
|
||||
仅使用aixun-datagov-local、aixun-datagov-*及专属网络/卷/端口/schema/Redis/Nacos。禁止复用其他项目。preflight检查归属、端口、.env权限和命名,不打印秘密。
|
||||
|
||||
.env.datagov、m2/local/secrets和runtime私有文件保留,不复制到证据或构建上下文。检查不应用迁移;迁移显式前向,未知写入先对账。数据恢复/删除遵守用户授权和D-020。
|
||||
|
||||
file-store-dr/、managed-credential-dr/保留业务恢复工具及数据一致性契约;按对应README使用,并非每次修复前置。release/仅用于确需完整发布/恢复的范围。
|
||||
|
||||
编号历史脚本(ingestion-test/run-123.py、数据库exact-163等)仅适用于原特殊数据操作,不作为新开发或普通部署入口,旧授权不可复用。新开发无人工租约。
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Production DATE compiler + Owner against literal CTEs in this project's MySQL only.
|
||||
|
||||
No tables, business records, migrations or stored configuration are read or written.
|
||||
The fixed fixture FROM identity alone is replaced with the literal CTE name.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
module = importlib.util.spec_from_file_location("bi_fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py")
|
||||
helpers = importlib.util.module_from_spec(module)
|
||||
module.loader.exec_module(helpers)
|
||||
run, literal = helpers.run, helpers.literal
|
||||
CONTAINER, TENANT = helpers.CONTAINER, helpers.TENANT
|
||||
PHYSICAL = "`aixun_datagov_system`.`bi_date_fixture`"
|
||||
CASES = [
|
||||
("leap_day_and_null", "DAY", [(None, 7, None), ("2024-02-28", 10, "a"), ("2024-02-29", 20, "a"), ("2024-02-29", 30, "b")], [(None, "7", "0"), ("2024-02-28", "10", "1"), ("2024-02-29", "25", "2")], None),
|
||||
("monday_week_across_year", "WEEK", [("2024-12-29", 8, "a"), ("2024-12-30", 10, "a"), ("2025-01-05", 30, "b"), ("2025-01-06", 50, "c")], [("2024-12-23", "8", "1"), ("2024-12-30", "20", "2"), ("2025-01-06", "50", "1")], None),
|
||||
("monthly_raw_average_and_distinct", "MONTH", [("2024-02-01", 10, "a"), ("2024-02-28", 20, "a"), ("2024-02-28", 40, "b"), ("2024-02-29", 90, "b"), ("2024-03-01", 7, "c")], [("2024-02-01", "40", "2"), ("2024-03-01", "7", "1")], None),
|
||||
("gregorian_quarter_boundary", "QUARTER", [("2024-01-31", 10, "a"), ("2024-03-31", 20, "a"), ("2024-04-01", 100, "b")], [("2024-01-01", "15", "1"), ("2024-04-01", "100", "1")], None),
|
||||
("gregorian_year_and_leap_day", "YEAR", [("2023-12-31", 10, "a"), ("2024-01-01", 20, "a"), ("2024-02-29", 50, "b")], [("2023-01-01", "10", "1"), ("2024-01-01", "35", "2")], None),
|
||||
("filter_raw_dates_before_bucketing", "MONTH", [("2024-02-01", 100, "excluded"), ("2024-02-20", 20, "a"), ("2024-02-29", 40, "b")], [("2024-02-01", "30", "2")], "2024-02-15"),
|
||||
("empty_does_not_invent_zero", "MONTH", [], [], None),
|
||||
("fiscal_april_year_raw_average_distinct_null", "FISCAL_YEAR", [(None, 7, None), ("2023-04-01", 10, "a"), ("2024-02-28", 20, "a"), ("2024-02-29", 40, "b"), ("2024-03-31", 90, "b"), ("2024-04-01", 12, "c")], [(None, "7", "0"), ("2023-04-01", "40", "2"), ("2024-04-01", "12", "1")], None, 4),
|
||||
("fiscal_february_quarter_crosses_year", "FISCAL_QUARTER", [("2023-11-01", 10, "a"), ("2024-01-31", 30, "b"), ("2024-02-01", 50, "c")], [("2023-11-01", "20", "2"), ("2024-02-01", "50", "1")], None, 2),
|
||||
("fiscal_december_quarter_includes_leap_day", "FISCAL_QUARTER", [("2023-12-31", 10, "a"), ("2024-02-29", 30, "a"), ("2024-03-01", 50, "c")], [("2023-12-01", "20", "1"), ("2024-03-01", "50", "1")], None, 12),
|
||||
("fiscal_january_matches_explicit_calendar_year", "FISCAL_YEAR", [("2023-12-31", 10, "a"), ("2024-02-29", 30, "b")], [("2023-01-01", "10", "1"), ("2024-01-01", "30", "1")], None, 1),
|
||||
("fiscal_december_year_boundary", "FISCAL_YEAR", [("2024-11-30", 10, "a"), ("2024-12-01", 30, "b")], [("2023-12-01", "10", "1"), ("2024-12-01", "30", "1")], None, 12),
|
||||
("fiscal_raw_date_filter_precedes_period", "FISCAL_YEAR", [("2023-04-01", 999, "excluded"), ("2024-02-29", 10, "a"), ("2024-03-31", 30, "a")], [("2023-04-01", "20", "1")], "2024-02-01", 4),
|
||||
]
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); parser.add_argument("--compiled-dir", type=Path); args = parser.parse_args()
|
||||
if not args.execute:
|
||||
print(json.dumps({"status": "NOT_RUN", "container": CONTAINER, "cases": [case[0] for case in CASES], "writes": "NONE"})); return
|
||||
identity = run(["docker", "inspect", "--format", '{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}', CONTAINER]).strip().split("|")
|
||||
if identity[:4] != ["/" + CONTAINER, "aixun-datagov-local", "mysql", "true"] or not identity[4].split() or any(not n.startswith("aixun-datagov-local-") for n in identity[4].split()):
|
||||
raise RuntimeError("DataGov container ownership mismatch")
|
||||
classes = [ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes", ROOT / "aixun-modules/aixun-dataproduct/target/classes"]
|
||||
source_files = ["aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/tablefile/AnalyticsQuery.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/AnalyticsSqlCompiler.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/DateBucketSql.java", "aixun-modules/aixun-dataproduct/src/main/java/cn/aixunkeji/datagov/dataproduct/bi/BiQuerySource.java", "aixun-modules/aixun-dataproduct/src/main/java/cn/aixunkeji/datagov/dataproduct/bi/BiTimeBuckets.java"]
|
||||
if args.compiled_dir:
|
||||
approved = ROOT / ".local-evidence/bi-axes-wave8/date-classes"
|
||||
if args.compiled_dir.resolve() != approved.resolve(): raise RuntimeError("Only the task's isolated check output is supported")
|
||||
expected = json.loads((approved / "source-sha256.json").read_text())
|
||||
if expected != {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in source_files}: raise RuntimeError("Compiled production sources changed; rebuild the isolated check output")
|
||||
classes.insert(0, approved)
|
||||
spring = Path.home() / ".m2/repository/org/springframework/spring-web/7.0.8/spring-web-7.0.8.jar"
|
||||
if not spring.is_file() or any(not path.is_dir() for path in classes): raise RuntimeError("Coordinated production classes unavailable")
|
||||
java = ["java", "--class-path", os.pathsep.join(str(path) for path in classes + [spring]), str(ROOT / "script/datagov/BiTimeBucketMysqlProbe.java")]
|
||||
shell = 'test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
|
||||
mysql = ["docker", "exec", "-i", CONTAINER, "sh", "-c", shell]
|
||||
version = run(mysql, "SELECT VERSION();\n").strip(); outcomes = []
|
||||
for case in CASES:
|
||||
name, unit, rows, expected, minimum, *fiscal = case
|
||||
fiscal_args = [minimum or "-", str(fiscal[0])] if fiscal else ([minimum] if minimum else [])
|
||||
generated = run(java + ["compile", unit] + fiscal_args).splitlines()
|
||||
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(value).decode() for value in generated[1].split(",")]
|
||||
if sql.count(PHYSICAL) != 1 or parameters != [TENANT] + ([minimum] if minimum else []): raise AssertionError("Compiler binding changed")
|
||||
data = [(day, amount, person, TENANT) for day, amount, person in rows] + [("2024-01-01", 999999, "foreign", "outside")]
|
||||
fixture = "WITH `bi_date_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,CAST({literal(amount)} AS DECIMAL(20,6)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, amount, person, tenant in data) + ") "
|
||||
projection = ",".join(f"IF({column} IS NULL,'-',TO_BASE64(CAST({column} AS CHAR)))" for column in ("day", "average", "people"))
|
||||
statement = fixture + f"SELECT {projection} FROM (" + sql.replace(PHYSICAL, "`bi_date_fixture`") + ") AS observed"
|
||||
commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"]
|
||||
commands += [f"SET @fixture_p{i}={literal(value)}" for i, value in enumerate(parameters)]
|
||||
commands += ["EXECUTE fixture_statement USING " + ",".join(f"@fixture_p{i}" for i in range(len(parameters))), "DEALLOCATE PREPARE fixture_statement"]
|
||||
returned = run(mysql, ";\n".join(commands) + ";\n")
|
||||
actual = [tuple(None if value == "-" else base64.b64decode(value).decode() for value in line.split("\t")) for line in returned.splitlines()]
|
||||
if len(actual) != len(expected): raise AssertionError(name + " unexpected row count")
|
||||
for received, wanted in zip(actual, expected):
|
||||
if received[0] != wanted[0] or Decimal(received[1]) != Decimal(wanted[1]) or received[2] != wanted[2]: raise AssertionError(f"{name}: {received!r} != {wanted!r}")
|
||||
owner = run(java + ["validate", unit] + (["-", str(fiscal[0])] if fiscal else []), returned).strip()
|
||||
if owner != f"SUCCEEDED\t{len(expected)}": raise AssertionError("Owner did not validate actual dates")
|
||||
outcomes.append({"case": name, "status": "PASS", "rows": len(actual), "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
|
||||
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "compiler": "ACTUAL_SOURCE_ISOLATED_CHECK" if args.compiled_dir else "COORDINATED_TARGET_CLASSES", "sourceSha256": {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in source_files}, "cases": outcomes, "limits": ["Native authorization end-to-end NOT_RUN", "Browser NOT_RUN", "MariaDB NOT_RUN", "No prior-year comparison"]}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__": main()
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise actual export-repository SQL in connection-local temporary MySQL tables.
|
||||
|
||||
No migration or persisted business data is changed. SQL is taken from production
|
||||
source, not copied into a second implementation. Credentials stay in the container.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
helper_spec = importlib.util.spec_from_file_location("fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py")
|
||||
helpers = importlib.util.module_from_spec(helper_spec)
|
||||
helper_spec.loader.exec_module(helpers)
|
||||
run, CONTAINER = helpers.run, helpers.CONTAINER
|
||||
SOURCE = ROOT / "aixun-modules/aixun-dataproduct/src/main/java/cn/aixunkeji/datagov/dataproduct/bi/BiExportJobRepository.java"
|
||||
DDL = ROOT / "db/migration/dataproduct/V20261012.239__create_bi_export_jobs.sql"
|
||||
|
||||
|
||||
def literal(value):
|
||||
return "''" if value == "" else helpers.literal(value)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); args = parser.parse_args()
|
||||
if not args.execute:
|
||||
print(json.dumps({"status": "NOT_RUN", "container": CONTAINER, "writes": "SESSION_TEMPORARY_TABLES_ONLY"})); return
|
||||
identity = run(["docker", "inspect", "--format", '{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}', CONTAINER]).strip().split("|")
|
||||
if identity[:4] != ["/" + CONTAINER, "aixun-datagov-local", "mysql", "true"] or not identity[4].split() or any(not name.startswith("aixun-datagov-local-") for name in identity[4].split()):
|
||||
raise RuntimeError("DataGov container ownership mismatch")
|
||||
production = re.findall(r'"((?:INSERT|UPDATE|SELECT)[^"\n]+)"', SOURCE.read_text())
|
||||
def sql(prefix):
|
||||
matches = [value for value in production if value.startswith(prefix)]
|
||||
if len(matches) != 1: raise AssertionError("Production SQL selector is no longer unique")
|
||||
return matches[0]
|
||||
statements = [statement.replace("CREATE TABLE", "CREATE TEMPORARY TABLE", 1) for statement in re.findall(r"CREATE TABLE .*?;", DDL.read_text(), re.S)]
|
||||
if len(statements) != 4: raise AssertionError("Unexpected export table set")
|
||||
statements += ["SET SESSION MAX_EXECUTION_TIME=10000", "START TRANSACTION"]
|
||||
def execute(query, values=()):
|
||||
if query.count("?") != len(values): raise AssertionError("Production SQL parameter count changed")
|
||||
statements.extend(["SET @fixture_sql=" + literal(query), "PREPARE fixture_statement FROM @fixture_sql"])
|
||||
statements.extend("SET @fixture_p%d=%s" % (index, literal(value)) for index, value in enumerate(values))
|
||||
statements.append("EXECUTE fixture_statement" + (" USING " + ",".join("@fixture_p%d" % index for index in range(len(values))) if values else ""))
|
||||
statements.append("DEALLOCATE PREPARE fixture_statement")
|
||||
def observe(name, condition):
|
||||
statements.append("SELECT " + literal(name) + ",IF(" + condition + ",'PASS','FAIL')")
|
||||
execute(sql("INSERT IGNORE INTO svc_bi_export_admission"), [7,10,10,7,7])
|
||||
execute(sql("INSERT IGNORE INTO svc_bi_export_admission"), [7,10,10,7,7])
|
||||
observe("admission_is_idempotent_and_audited", "(SELECT COUNT(*)=1 AND MIN(create_by)=7 AND MIN(create_dept)=10 FROM svc_bi_export_admission)")
|
||||
ids = ["00000000-0000-4000-8000-%012d" % number for number in range(1, 6)]
|
||||
for index, job in enumerate(ids):
|
||||
execute(sql("INSERT INTO svc_bi_export_job("), [job,ids[0],2,7,10,"request%d" % index,"a"*64,'{"version":2}',"{}","b"*64,1,0,"CSV","", "2099-01-01 00:00:00",10,7,7])
|
||||
observe("all_jobs_have_actor_audit", "(SELECT COUNT(*)=5 FROM svc_bi_export_job WHERE create_dept=10 AND create_by=7 AND update_by=7)")
|
||||
statements.append("UPDATE svc_bi_export_job SET state='RUNNING',attempts=3,lease_nonce='old',lease_fence=3,lease_until=DATE_SUB(NOW(6),INTERVAL 1 MINUTE),file_bytes=0x0102,target_json=JSON_OBJECT('identity','retained'),operation_key=SHA2(job_id,256)")
|
||||
statements.append("UPDATE svc_bi_export_job SET attempts=2 WHERE job_id=" + literal(ids[1]))
|
||||
statements.append("UPDATE svc_bi_export_job SET lease_until=DATE_ADD(NOW(6),INTERVAL 1 MINUTE) WHERE job_id=" + literal(ids[2]))
|
||||
statements.append("UPDATE svc_bi_export_job SET expires_at=DATE_SUB(NOW(6),INTERVAL 1 MINUTE) WHERE job_id=" + literal(ids[3]))
|
||||
statements.append("UPDATE svc_bi_export_job SET state='READY' WHERE job_id=" + literal(ids[4]))
|
||||
execute(sql("UPDATE svc_bi_export_job SET state='UNKNOWN',safe_code='RECOVERY_EXHAUSTED'"))
|
||||
observe("crashed_third_attempt_is_recoverable_without_new_file", "(SELECT state='UNKNOWN' AND safe_code='RECOVERY_EXHAUSTED' AND lease_nonce IS NULL AND lease_fence=3 AND HEX(file_bytes)='0102' AND target_json->>'$.identity'='retained' AND operation_key=SHA2(job_id,256) FROM svc_bi_export_job WHERE job_id=" + literal(ids[0]) + ")")
|
||||
observe("earlier_attempt_live_lease_expired_and_ready_are_not_exhausted", "(SELECT COUNT(*)=4 FROM svc_bi_export_job WHERE safe_code IS NULL)")
|
||||
execute(sql("UPDATE svc_bi_export_job SET state='QUEUED'"), [ids[0],1])
|
||||
execute(sql("UPDATE svc_bi_export_job SET state='RUNNING'"), ["11111111-1111-4111-8111-111111111111",ids[0]])
|
||||
observe("explicit_retry_reuses_job_and_advances_lease_fence", "(SELECT state='RUNNING' AND attempts=1 AND lease_fence=4 AND version=3 AND HEX(file_bytes)='0102' FROM svc_bi_export_job WHERE job_id=" + literal(ids[0]) + ")")
|
||||
execute(sql("UPDATE svc_bi_export_job SET state='READY'"), [ids[0],"old",3])
|
||||
observe("old_worker_cannot_complete_new_lease", "(SELECT state='RUNNING' AND version=3 FROM svc_bi_export_job WHERE job_id=" + literal(ids[0]) + ")")
|
||||
execute(sql("INSERT IGNORE INTO svc_bi_export_mutation"), [7,10,"retry001","c"*64,10,7,7])
|
||||
execute(sql("UPDATE svc_bi_export_mutation SET job_id="), [ids[0],7,10,"retry001"])
|
||||
observe("mutation_receipt_has_actor_and_version", "(SELECT job_id=" + literal(ids[0]) + " AND version=1 AND create_by=7 AND create_dept=10 FROM svc_bi_export_mutation)")
|
||||
execute(sql("INSERT INTO svc_bi_export_event("), [ids[0],7,10,"RETRY",3,10,7,7])
|
||||
observe("job_event_has_actor_and_version", "(SELECT event_type='RETRY' AND job_version=3 AND create_by=7 AND create_dept=10 FROM svc_bi_export_event)")
|
||||
statements.append("ROLLBACK")
|
||||
shell = 'test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
|
||||
returned = run(["docker", "exec", "-i", CONTAINER, "sh", "-c", shell], ";\n".join(statements) + ";\n")
|
||||
outcomes = [dict(zip(["case", "status"], line.split("\t"))) for line in returned.splitlines()]
|
||||
if len(outcomes) != 8 or any(value.get("status") != "PASS" for value in outcomes): raise AssertionError(json.dumps(outcomes))
|
||||
print(json.dumps({"status":"PASS", "container":CONTAINER, "writes":"SESSION_TEMPORARY_TABLES_ONLY_ROLLED_BACK", "sourceSha256":hashlib.sha256(SOURCE.read_bytes()).hexdigest(), "schemaSha256":hashlib.sha256(DDL.read_bytes()).hexdigest(), "cases":outcomes, "limits":["Multi-session SKIP LOCKED race NOT_RUN", "HTTP and Resource file roundtrip NOT_RUN"]}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__": main()
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Production compiler/decoder against pure synthetic CTEs in DataGov's own MySQL.
|
||||
|
||||
No real table is read, created or modified. The sole target substitution binds the
|
||||
compiler's fixed physical fixture identifier to a literal CTE. All aggregation,
|
||||
top ordering, anti-match and four prepared parameters remain compiler-produced.
|
||||
The local container's existing credential is used only inside that container.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from decimal import Decimal
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
CONTAINER = "aixun-datagov-mysql"
|
||||
PHYSICAL = "`aixun_datagov_system`.`bi_other_fixture`"
|
||||
TENANT = "fixture' OR 1=1 --"
|
||||
CASES = [
|
||||
("unequal_group_average", "AVG", 1, [("a", 100), ("a", 100), ("b", 10), ("c", 0), ("c", 0), ("c", 0)], [("a", "100", "0"), (None, "2.5", "1"), (None, "0", "2")], False),
|
||||
("cross_category_distinct", "COUNT_DISTINCT", 1, [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("c", 2), ("c", 4)], [("a", "3", "0"), (None, "3", "1"), (None, "2", "2")], False),
|
||||
("null_and_actual_other", "SUM", 2, [(None, 100), ("其他", 90), ("b", 20)], [(None, "100", "0"), ("其他", "90", "0"), (None, "20", "1"), (None, "20", "2")], False),
|
||||
("stable_ties_null_last", "SUM", 2, [("b", 10), (None, 10), ("a", 10)], [("a", "10", "0"), ("b", "10", "0"), (None, "10", "1"), (None, "10", "2")], False),
|
||||
("hidden_negative_positive_remainder", "SUM", 1, [("a", 100), ("b", -10), ("c", 20)], [("a", "100", "0"), (None, "10", "1"), (None, "-10", "2")], True),
|
||||
("no_remainder", "AVG", 2, [("a", 4)], [("a", "4", "0"), (None, "4", "2")], False),
|
||||
("all_null_remaining_values", "AVG", 1, [("a", 10), ("b", None), ("c", None)], [("a", "10", "0"), (None, None, "1"), (None, "10", "2")], False),
|
||||
("empty_filtered_result", "AVG", 1, [], [(None, None, "2")], False),
|
||||
]
|
||||
|
||||
def run(command, data=None, timeout=45):
|
||||
result = subprocess.run(command, input=data, text=True, capture_output=True, timeout=timeout, cwd=ROOT)
|
||||
if result.returncode:
|
||||
# The invocation has no literal credentials; preserve a bounded error for diagnosis.
|
||||
raise RuntimeError(result.stderr[-1800:] or "Process failed")
|
||||
return result.stdout
|
||||
|
||||
def b64(value):
|
||||
return base64.b64encode(value.encode()).decode()
|
||||
|
||||
def literal(value):
|
||||
return "NULL" if value is None else f"CONVERT(0x{str(value).encode().hex()} USING utf8mb4)"
|
||||
|
||||
def fixture(rows):
|
||||
# A foreign synthetic tenant must be excluded on every source occurrence.
|
||||
values = [(category, amount, TENANT) for category, amount in rows] + [("foreign", 99999, "outside")]
|
||||
return "WITH `bi_other_fixture` AS (" + " UNION ALL ".join(
|
||||
f"SELECT CAST({literal(c)} AS CHAR(128)) AS category,CAST({literal(v)} AS DECIMAL(20,6)) AS amount,{literal(t)} AS tenant"
|
||||
for c, v, t in values) + ") "
|
||||
|
||||
def compare(actual, expected):
|
||||
if len(actual) != len(expected):
|
||||
raise AssertionError(f"row count {len(actual)} != {len(expected)}")
|
||||
for received, wanted in zip(actual, expected):
|
||||
if received[0] != wanted[0] or received[2] != wanted[2]:
|
||||
raise AssertionError(f"category/level mismatch {received!r} != {wanted!r}")
|
||||
if (received[1] is None) != (wanted[1] is None) or wanted[1] is not None and Decimal(received[1]) != Decimal(wanted[1]):
|
||||
raise AssertionError(f"aggregate mismatch {received!r} != {wanted!r}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); args = parser.parse_args()
|
||||
if not args.execute:
|
||||
print(json.dumps({"status": "NOT_RUN", "container": CONTAINER, "cases": [c[0] for c in CASES], "writes": "NONE; literal CTE only"}, ensure_ascii=False)); return
|
||||
identity = run(["docker", "inspect", "--format", '{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}', CONTAINER]).strip().split("|")
|
||||
if identity[:4] != ["/" + CONTAINER, "aixun-datagov-local", "mysql", "true"] or not identity[4].split() or any(not n.startswith("aixun-datagov-local-") for n in identity[4].split()):
|
||||
raise RuntimeError("DataGov container ownership mismatch")
|
||||
dependencies = [ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes", ROOT / "aixun-modules/aixun-dataproduct/target/classes"]
|
||||
for path in dependencies:
|
||||
if not path.is_dir(): raise RuntimeError("Production classes are unavailable; run the coordinated affected tests first")
|
||||
spring = Path.home() / ".m2/repository/org/springframework/spring-web/7.0.8/spring-web-7.0.8.jar"
|
||||
if not spring.is_file(): raise RuntimeError("Expected managed Spring Web dependency unavailable")
|
||||
java = ["java", "--class-path", os.pathsep.join(str(p) for p in dependencies + [spring]), str(ROOT / "script/datagov/BiOtherMysqlProbe.java")]
|
||||
shell = 'test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
|
||||
mysql = ["docker", "exec", "-i", CONTAINER, "sh", "-c", shell]
|
||||
version = run(mysql, "SELECT VERSION();\n").strip()
|
||||
results = []
|
||||
for name, aggregate, top, rows, expected, rejected in CASES:
|
||||
generated = run(java + ["compile", aggregate, str(top)]).splitlines()
|
||||
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")]
|
||||
if sql.count(PHYSICAL) != 4 or parameters != [TENANT] * 4: raise AssertionError("Production plan binding changed")
|
||||
sql = sql.rstrip(";")
|
||||
projection = ",".join(f"IF({column} IS NULL,'-',TO_BASE64(CAST({column} AS CHAR)))" for column in ("category", "value", "__aixun_category_level"))
|
||||
statement = fixture(rows) + f"SELECT {projection} FROM (" + sql.replace(PHYSICAL, "`bi_other_fixture`") + ") AS observed"
|
||||
commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"]
|
||||
commands += [f"SET @fixture_p{i}={literal(value)}" for i, value in enumerate(parameters)]
|
||||
commands += ["EXECUTE fixture_statement USING " + ",".join(f"@fixture_p{i}" for i in range(len(parameters))), "DEALLOCATE PREPARE fixture_statement"]
|
||||
received = run(mysql, ";\n".join(commands) + ";\n")
|
||||
actual = [tuple(None if value == "-" else base64.b64decode(value).decode() for value in line.split("\t")) for line in received.splitlines()]
|
||||
compare(actual, expected)
|
||||
owner = run(java + ["decode", aggregate, str(top)], received).strip()
|
||||
if rejected and owner != "REJECTED\t149109" or not rejected and not owner.startswith("SUCCEEDED\t"):
|
||||
raise AssertionError(f"Owner outcome mismatch: {owner}")
|
||||
results.append({"case": name, "status": "PASS", "rawRowCount": len(actual), "owner": owner.split("\t"), "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
|
||||
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "binding": "fixed physical fixture identifier to literal CTE only", "cases": results, "limits": ["Not a Browser test", "Does not prove Native source registration or live reader RBAC", "Other database engines NOT_RUN"]}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Actual production comparison Plan/compiler over literal CTEs; no business rows or writes."""
|
||||
import argparse
|
||||
import base64
|
||||
from decimal import Decimal
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
module = importlib.util.spec_from_file_location("bi_fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py")
|
||||
helpers = importlib.util.module_from_spec(module); module.loader.exec_module(helpers)
|
||||
run, literal, CONTAINER, TENANT = helpers.run, helpers.literal, helpers.CONTAINER, helpers.TENANT
|
||||
SOURCES = ["aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/tablefile/AnalyticsQuery.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/AnalyticsSqlCompiler.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/DateBucketSql.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/PeriodComparisonSql.java", "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/CategoryRemainderSql.java"]
|
||||
CASES = [
|
||||
("raw_average_and_cross_day_distinct", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-01", "A", 10, "a"), ("2023-02-28", "A", 30, "b"), ("2024-02-01", "A", 10, "a"), ("2024-02-28", "A", 20, "a"), ("2024-02-29", "A", 40, "b"), ("2024-02-29", "A", 90, "b")], [("2024-02-01", "A", "40", "2", "20", "20", "1", "2", "0", "0")]),
|
||||
("null_key_and_missing_sides_zero_baseline", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", None, 0, "a"), ("2024-02-10", None, 10, "a"), ("2024-02-10", "A", 15, "a"), ("2023-02-10", "B", 5, "b")], [("2024-02-01", None, "10", "1", "0", "10", None, "1", "0", "0"), ("2024-02-01", "A", "15", "1", None, None, None, None, None, None), ("2024-02-01", "B", None, None, "5", None, None, "1", None, None)]),
|
||||
("negative_baseline_does_not_flip_rate_meaning", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", -5, "a"), ("2024-02-10", "A", 10, "a")], [("2024-02-01", "A", "10", "1", "-5", "15", None, "1", "0", "0")]),
|
||||
("fiscal_quarter_aligns_real_bucket_start", "FISCAL_QUARTER", "2023-12-01", "2024-03-01", 12, [("2023-01-31", "A", 10, "a"), ("2024-01-31", "A", 30, "b")], [("2023-12-01", "A", "30", "1", "10", "20", "2", "1", "0", "0")]),
|
||||
("empty_does_not_create_comparison_zeroes", "MONTH", "2024-02-01", "2024-03-01", None, [], []),
|
||||
("fractional_decimal_difference_and_ratio", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", "0.1", "a"), ("2024-02-10", "A", "0.3", "a")], [("2024-02-01", "A", "0.3", "1", "0.1", "0.2", "2", "1", "0", "0")]),
|
||||
("large_decimal_preserves_above_javascript_integer_limit", "MONTH", "2024-02-01", "2024-03-01", None, [("2023-02-10", "A", "9007199254740993", "a"), ("2024-02-10", "A", "18014398509481986", "a")], [("2024-02-01", "A", "18014398509481986", "1", "9007199254740993", "9007199254740993", "1", "1", "0", "0")]),
|
||||
]
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); args = parser.parse_args()
|
||||
if not args.execute:
|
||||
print(json.dumps({"status": "NOT_RUN", "cases": [c[0] for c in CASES], "writes": "NONE"})); return
|
||||
identity = run(["docker", "inspect", "--format", '{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}', CONTAINER]).strip().split("|")
|
||||
if identity[:4] != ["/" + CONTAINER, "aixun-datagov-local", "mysql", "true"] or not identity[4].split() or any(not n.startswith("aixun-datagov-local-") for n in identity[4].split()): raise RuntimeError("DataGov ownership mismatch")
|
||||
compiled = ROOT / ".local-evidence/bi-axes-wave8/date-classes"
|
||||
hashes = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in SOURCES}
|
||||
if json.loads((compiled / "comparison-source-sha256.json").read_text()) != hashes: raise RuntimeError("Recompile actual production comparison sources")
|
||||
classes = [compiled, ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes"]
|
||||
classpath = os.pathsep.join(str(p) for p in classes)
|
||||
# Package-private production compiler and its fixture must share the same application classloader.
|
||||
run(["javac", "--release", "21", "-cp", classpath, "-d", str(compiled), str(ROOT / "script/datagov/BiPeriodComparisonMysqlProbe.java")])
|
||||
java = ["java", "--class-path", classpath, "cn.aixunkeji.datagov.integration.tablefile.BiPeriodComparisonMysqlProbe"]
|
||||
shell = 'test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
|
||||
mysql = ["docker", "exec", "-i", CONTAINER, "sh", "-c", shell]
|
||||
version = run(mysql, "SELECT VERSION();\n").strip(); outcomes = []
|
||||
for name, unit, start, end, fiscal, rows, expected in CASES:
|
||||
generated = run(java + [unit, start, end] + ([str(fiscal)] if fiscal else [])).splitlines()
|
||||
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")]; columns = generated[2].split(",")
|
||||
physical = "`aixun_datagov_system`.`bi_yoy_fixture`"
|
||||
if sql.count(physical) != 2 or parameters[0] != TENANT or parameters[3] != TENANT: raise AssertionError("Compiler bindings changed")
|
||||
data = [(day, area, amount, person, TENANT) for day, area, amount, person in rows] + [("2024-02-01", "foreign", 999999, "foreign", "outside")]
|
||||
fixture = "WITH `bi_yoy_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,{literal(area)} AS area,CAST({literal(amount)} AS DECIMAL(38,10)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, area, amount, person, tenant in data) + ") "
|
||||
projection = ",".join(f"IF(`{c}` IS NULL,'-',TO_BASE64(CAST(`{c}` AS CHAR)))" for c in columns)
|
||||
statement = fixture + f"SELECT {projection} FROM (" + sql.replace(physical, "`bi_yoy_fixture`") + ") AS observed"
|
||||
commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"]
|
||||
commands += [f"SET @fixture_p{i}={literal(p)}" for i, p in enumerate(parameters)]
|
||||
commands += ["EXECUTE fixture_statement USING " + ",".join(f"@fixture_p{i}" for i in range(len(parameters))), "DEALLOCATE PREPARE fixture_statement"]
|
||||
returned = run(mysql, ";\n".join(commands) + ";\n")
|
||||
actual = [tuple(None if p == "-" else base64.b64decode(p).decode() for p in line.split("\t")) for line in returned.splitlines()]
|
||||
if len(actual) != len(expected): raise AssertionError(name + " row count changed")
|
||||
for received, wanted in zip(actual, expected):
|
||||
if len(received) != len(wanted): raise AssertionError(name + " column count changed")
|
||||
for i, (a, b) in enumerate(zip(received, wanted)):
|
||||
if (a != b if i < 2 or a is None or b is None else Decimal(a) != Decimal(b)): raise AssertionError(f"{name}: {received!r} != {wanted!r}")
|
||||
outcomes.append({"case": name, "status": "PASS", "rows": len(actual), "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
|
||||
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "sourceSha256": hashes, "cases": outcomes, "limits": ["Actual Plan/compiler SQL and result metadata; Native policy and Browser NOT_RUN", "MariaDB NOT_RUN"]}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__": main()
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Production relative DATE arithmetic + compiler against literal CTEs. No business data/DDL/writes."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location("bi_fixture_helpers", ROOT / "script/datagov/bi-other-mysql-smoke.py")
|
||||
helpers = importlib.util.module_from_spec(spec); spec.loader.exec_module(helpers)
|
||||
run, literal, CONTAINER, TENANT = helpers.run, helpers.literal, helpers.CONTAINER, helpers.TENANT
|
||||
API = "aixun-api/aixun-api-integration/src/main/java/cn/aixunkeji/datagov/integration/api/tablefile/"
|
||||
SQL = "aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/tablefile/"
|
||||
SOURCES = [API + n + ".java" for n in ["AnalyticsQuery", "AnalyticsRelativeWindow"]] + [SQL + n + ".java" for n in ["AnalyticsSqlCompiler", "RelativeWindowSql", "DateBucketSql", "PeriodComparisonSql", "CategoryRemainderSql"]]
|
||||
CASES = [
|
||||
("east_leap_day", "DAY", 1, "Asia/Shanghai", "2024-03-01T00:30:00Z", "2024-03-01", "2024-02-29", "2024-03-01", False),
|
||||
("same_instant_west", "DAY", 1, "America/Los_Angeles", "2024-03-01T00:30:00Z", "2024-02-29", "2024-02-28", "2024-02-29", False),
|
||||
("dst_date_not_duration", "DAY", 2, "America/New_York", "2024-03-11T04:30:00Z", "2024-03-11", "2024-03-09", "2024-03-11", False),
|
||||
("monday_week_cross_year", "WEEK", 1, "UTC", "2025-01-01T12:00:00Z", "2025-01-01", "2024-12-23", "2024-12-30", False),
|
||||
("complete_months", "MONTH", 2, "UTC", "2025-01-31T12:00:00Z", "2025-01-31", "2024-11-01", "2025-01-01", False),
|
||||
("gregorian_quarter", "QUARTER", 2, "UTC", "2025-02-12T12:00:00Z", "2025-02-12", "2024-07-01", "2025-01-01", False),
|
||||
("complete_year", "YEAR", 1, "UTC", "2025-12-31T12:00:00Z", "2025-12-31", "2024-01-01", "2025-01-01", False),
|
||||
("source_date_policy_intersection", "MONTH", 1, "UTC", "2024-03-15T12:00:00Z", "2024-03-15", "2024-02-01", "2024-03-01", True),
|
||||
]
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(); parser.add_argument("--execute", action="store_true"); args = parser.parse_args()
|
||||
if not args.execute:
|
||||
print(json.dumps({"status": "NOT_RUN", "cases": [c[0] for c in CASES], "writes": "NONE"})); return
|
||||
identity = run(["docker", "inspect", "--format", '{{.Name}}|{{index .Config.Labels "com.docker.compose.project"}}|{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Running}}|{{range $n,$v := .NetworkSettings.Networks}}{{$n}} {{end}}', CONTAINER]).strip().split("|")
|
||||
if identity[:4] != ["/" + CONTAINER, "aixun-datagov-local", "mysql", "true"] or not identity[4].split() or any(not n.startswith("aixun-datagov-local-") for n in identity[4].split()): raise RuntimeError("DataGov ownership mismatch")
|
||||
compiled = ROOT / ".local-evidence/bi-axes-wave8/date-classes"
|
||||
hashes = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in SOURCES}
|
||||
if json.loads((compiled / "relative-source-sha256.json").read_text()) != hashes: raise RuntimeError("Recompile production relative sources")
|
||||
classpath = os.pathsep.join(str(p) for p in [compiled, ROOT / "aixun-api/aixun-api-integration/target/classes", ROOT / "aixun-modules/aixun-integration/target/classes"])
|
||||
run(["javac", "--release", "21", "-cp", classpath, "-d", str(compiled), str(ROOT / "script/datagov/BiRelativeWindowMysqlProbe.java")])
|
||||
java = ["java", "--class-path", classpath, "cn.aixunkeji.datagov.integration.tablefile.BiRelativeWindowMysqlProbe"]
|
||||
shell = 'test "$MYSQL_DATABASE" = aixun_datagov_system && test -n "$MYSQL_ROOT_PASSWORD" || exit 21; MYSQL_PWD="$MYSQL_ROOT_PASSWORD"; export MYSQL_PWD; exec mysql --user=root --database="$MYSQL_DATABASE" --batch --raw --skip-column-names --default-character-set=utf8mb4 --connect-timeout=5'
|
||||
mysql = ["docker", "exec", "-i", CONTAINER, "sh", "-c", shell]
|
||||
version = run(mysql, "SELECT VERSION();\n").strip(); outcomes = []
|
||||
for name, unit, count, zone, instant, reference, start, end, policy in CASES:
|
||||
last = (date.fromisoformat(end) - timedelta(days=1)).isoformat()
|
||||
generated = run(java + [unit, str(count), zone, instant] + ([last] if policy else [])).splitlines()
|
||||
sql = base64.b64decode(generated[0]).decode(); parameters = [base64.b64decode(p).decode() for p in generated[1].split(",")]
|
||||
if generated[3] != ",".join([reference, start, end]) or generated[2] != "average,people": raise AssertionError(name + " frozen metadata changed")
|
||||
physical = "`aixun_datagov_system`.`bi_relative_fixture`"
|
||||
if sql.count(physical) != 1 or parameters != [TENANT] + ([last] if policy else []) + [start, end]: raise AssertionError("Production bindings changed")
|
||||
rows = [(start, 10, "a", TENANT), (last, 20, "a", TENANT), (last, 30, "b", TENANT), ((date.fromisoformat(start)-timedelta(days=1)).isoformat(), 999, "before", TENANT), (end, 999, "after", TENANT), (None, 999, "null", TENANT), (last, 999, "foreign", "outside")]
|
||||
fixture = "WITH `bi_relative_fixture` AS (" + " UNION ALL ".join(f"SELECT CAST({literal(day)} AS DATE) AS day,CAST({literal(amount)} AS DECIMAL(38,10)) AS amount,{literal(person)} AS person,{literal(tenant)} AS tenant" for day, amount, person, tenant in rows) + ") "
|
||||
statement = fixture + sql.replace(physical, "`bi_relative_fixture`")
|
||||
commands = ["SET SESSION MAX_EXECUTION_TIME=10000", f"SET @fixture_sql={literal(statement)}", "PREPARE fixture_statement FROM @fixture_sql"] + [f"SET @fixture_p{i}={literal(p)}" for i, p in enumerate(parameters)] + ["EXECUTE fixture_statement USING " + ",".join(f"@fixture_p{i}" for i in range(len(parameters))), "DEALLOCATE PREPARE fixture_statement"]
|
||||
returned = run(mysql, ";\n".join(commands) + ";\n").strip().split("\t")
|
||||
if len(returned) != 2 or Decimal(returned[0]) != Decimal(25 if policy else 20) or returned[1] != "2": raise AssertionError(name + " aggregate mismatch")
|
||||
outcomes.append({"case": name, "status": "PASS", "window": generated[3], "compilerSha256": hashlib.sha256(sql.encode()).hexdigest(), "executedSha256": hashlib.sha256(statement.encode()).hexdigest()})
|
||||
print(json.dumps({"status": "PASS", "container": CONTAINER, "mysqlVersion": version, "writes": "NONE", "sourceSha256": hashes, "cases": outcomes, "limits": ["Native policies, Browser, MariaDB NOT_RUN", "Only literal synthetic CTEs, no business reads"]}, ensure_ascii=False, indent=2))
|
||||
|
||||
if __name__ == "__main__": main()
|
||||
@@ -0,0 +1,30 @@
|
||||
-- 合成测试数据,只能在已登记的 DataGov 本项目测试 MySQL/MariaDB 数据库中人工确认后执行。
|
||||
-- 本文件不是迁移;不创建数据库、不改账户、不删除现有表。重复执行因表已存在而停止。
|
||||
-- 必须随后运行本项目 Native 完整扫描,不能手写 Native UUID、扫描证据或唯一键声明。
|
||||
CREATE TABLE dg_bi_semantic_departments (
|
||||
id BIGINT NOT NULL PRIMARY KEY,
|
||||
region_id BIGINT NOT NULL,
|
||||
department_name VARCHAR(64) NOT NULL
|
||||
);
|
||||
CREATE TABLE dg_bi_semantic_orders (
|
||||
id BIGINT NOT NULL PRIMARY KEY,
|
||||
department_id BIGINT NOT NULL,
|
||||
amount DECIMAL(18,2) NULL,
|
||||
contact_label VARCHAR(64) NULL
|
||||
);
|
||||
INSERT INTO dg_bi_semantic_departments(id, region_id, department_name) VALUES
|
||||
(10, 50, '合成甲部门'), (20, 50, '合成乙部门'), (30, 60, '合成丙部门');
|
||||
INSERT INTO dg_bi_semantic_orders(id, department_id, amount, contact_label) VALUES
|
||||
(1,10,100.10,'合成联系人A'), (2,10,NULL,'合成联系人B'),
|
||||
(3,20,200.20,'合成联系人C'), (4,20,-20.20,'合成联系人D'),
|
||||
(5,30,0.00,NULL), (6,999,5.00,'合成未匹配联系人');
|
||||
-- 正向 LEFT JOIN departments.id,按 department_name + SUM(amount):
|
||||
-- 合成甲部门 100.10;合成乙部门 180.00;合成丙部门 0.00;NULL 5.00。
|
||||
-- 全部事实金额 285.10,非空金额COUNT=5,行数=6;NULL金额不可当成另一笔0元收入。
|
||||
-- 反例改关联到 departments.region_id:该列非唯一,必须拒绝,不能执行后再补SUM去重。
|
||||
-- 行策略仅允许 orders.department_id=10:必须只返回甲部门100.10。
|
||||
-- 将关联键设为受保护列:必须拒绝;仅输出contact_label时按真实脱敏策略处理。
|
||||
-- 透视验证使用 department_name(行)+ orders.id(列),不使用联系人字段:
|
||||
-- AVG(amount)行汇总:甲100.10、乙90.00、丙0.00、NULL部门5.00;源重算总计57.02。
|
||||
-- 总计不能是四个行平均值的平均48.775;金额为NULL的订单2仍为单元格NULL。
|
||||
-- COUNT_DISTINCT(department_id)总计必须为4,不能将六个订单单元格的计数相加为6。
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"sourceId": "REPLACE_WITH_REGISTERED_DATAGOV_TEST_SOURCE_ID",
|
||||
"databaseName": "REPLACE_WITH_SELECTED_TEST_DATABASE",
|
||||
"nativeTables": {
|
||||
"REPLACE_WITH_SCANNED_ORDERS_UUID": "dg_bi_semantic_orders",
|
||||
"REPLACE_WITH_SCANNED_DEPARTMENTS_UUID": "dg_bi_semantic_departments"
|
||||
},
|
||||
"cases": [
|
||||
{
|
||||
"name": "same-source-left-join-exact-decimal",
|
||||
"objectId": "REPLACE_WITH_SAVED_ANALYSIS_UUID",
|
||||
"version": 0,
|
||||
"expect": "SUCCEEDED",
|
||||
"columns": ["department", "revenue"],
|
||||
"rows": [
|
||||
{"department": "合成甲部门", "revenue": "100.10"},
|
||||
{"department": "合成乙部门", "revenue": "180.00"},
|
||||
{"department": "合成丙部门", "revenue": "0.00"},
|
||||
{"department": null, "revenue": "5.00"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "non-unique-dimension-key-denied",
|
||||
"objectId": "REPLACE_WITH_NON_UNIQUE_KEY_ANALYSIS_UUID",
|
||||
"version": 0,
|
||||
"expect": "DENIED",
|
||||
"messageContains": ["唯一索引核验"]
|
||||
},
|
||||
{
|
||||
"name": "current-reader-without-source-permission-denied",
|
||||
"objectId": "REPLACE_WITH_SAVED_ANALYSIS_UUID",
|
||||
"version": 0,
|
||||
"expect": "DENIED",
|
||||
"tokenEnv": "AIXUN_BI_READER_TOKEN",
|
||||
"messageContains": ["SEMANTIC_QUERY_NOT_AUTHORIZED_OR_UNAVAILABLE"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read/query only BI acceptance. No SQL, source scan, migrations, permissions or fixtures are mutated."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def request(base, token, path, payload=None):
|
||||
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
|
||||
if os.environ.get('AIXUN_BI_CLIENT_ID'):
|
||||
headers['clientid'] = os.environ['AIXUN_BI_CLIENT_ID']
|
||||
req = urllib.request.Request(base + path, headers=headers,
|
||||
data=None if payload is None else json.dumps(payload).encode('utf-8'))
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=50) as response:
|
||||
return response.status, json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
return error.code, json.load(error)
|
||||
except (ValueError, TypeError):
|
||||
return error.code, {}
|
||||
|
||||
|
||||
def assert_query(status, body, case):
|
||||
"""No transport error, unknown result or authentication expiry counts as the expected policy rejection."""
|
||||
code = body.get('code')
|
||||
result = body.get('data') or {}
|
||||
if case['expect'] == 'DENIED':
|
||||
denied = status == 403 or code in (403, 149103)
|
||||
denied = denied or (status == 200 and code == 200 and result.get('state') == 'UNAVAILABLE'
|
||||
and not result.get('rows') and any(term in result.get('message', '')
|
||||
for term in case.get('messageContains', [])))
|
||||
if not denied:
|
||||
raise ValueError('expected explicit permission or policy denial')
|
||||
return {'state': 'PASS', 'case': case['name'], 'returnedRows': 0}
|
||||
if status != 200 or code != 200 or result.get('state') != 'SUCCEEDED' or result.get('truncated'):
|
||||
raise ValueError('query did not return a complete successful result')
|
||||
if not result.get('observedAt') or result.get('columns') != case['columns']:
|
||||
raise ValueError('result evidence or columns mismatch')
|
||||
rows = sorted((json.dumps(row, ensure_ascii=False, sort_keys=True) for row in result.get('rows', [])))
|
||||
expected = sorted((json.dumps(row, ensure_ascii=False, sort_keys=True) for row in case['rows']))
|
||||
if rows != expected:
|
||||
raise ValueError('fixture result mismatch')
|
||||
if 'pivotTotals' in case:
|
||||
totals = result.get('pivotTotals')
|
||||
expected_totals = case['pivotTotals']
|
||||
if not isinstance(totals, dict) or totals.get('scope') != 'ALL_FILTERED':
|
||||
raise ValueError('source pivot totals missing')
|
||||
for key in ('rowField', 'columnField', 'measure', 'scope', 'grandTotal'):
|
||||
if key not in totals or totals[key] != expected_totals[key]:
|
||||
raise ValueError('source pivot total value mismatch')
|
||||
for key in ('rowTotals', 'columnTotals'):
|
||||
if not isinstance(totals.get(key), list) or sorted(json.dumps(row, sort_keys=True) for row in totals[key]) \
|
||||
!= sorted(json.dumps(row, sort_keys=True) for row in expected_totals[key]):
|
||||
raise ValueError('source pivot total groups mismatch')
|
||||
return {'state': 'PASS', 'case': case['name'], 'returnedRows': len(rows)}
|
||||
|
||||
|
||||
def run(base, manifest):
|
||||
source_id = manifest['sourceId']
|
||||
if not isinstance(source_id, str) or not re.fullmatch(r'[1-9][0-9]{0,18}', source_id):
|
||||
raise ValueError('sourceId must be an exact string')
|
||||
if not manifest.get('databaseName') or len(manifest['cases']) > 20:
|
||||
raise ValueError('fixture scope or cases invalid')
|
||||
token = os.environ['AIXUN_BI_TOKEN']
|
||||
status, body = request(base, token, '/api/integration/v1/data-sources/' + source_id)
|
||||
source = body.get('data') or {}
|
||||
if status != 200 or body.get('code') != 200 or str(source.get('id')) != source_id \
|
||||
or source.get('type') not in ('MYSQL', 'MARIADB') or source.get('databaseName') != manifest['databaseName']:
|
||||
raise ValueError('selected registered test source could not be verified')
|
||||
expected_tables = manifest['nativeTables']
|
||||
if set(expected_tables.values()) != {'dg_bi_semantic_orders', 'dg_bi_semantic_departments'}:
|
||||
raise ValueError('exact two fixture tables required')
|
||||
for table_id, table_name in expected_tables.items():
|
||||
if not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', table_id):
|
||||
raise ValueError('table must be an observed Native UUID')
|
||||
status, body = request(base, token, '/api/governance/v1/metadata-catalog/TABLE/' + table_id + '?sourceId=' + source_id)
|
||||
observed = (body.get('data') or {}).get('item') or {}
|
||||
if status != 200 or body.get('code') != 200 or observed.get('externalId') != table_id or observed.get('name') != table_name:
|
||||
raise ValueError('fixture Native table does not belong to selected source')
|
||||
reports = []
|
||||
for case in manifest['cases']:
|
||||
if not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', case['objectId']) \
|
||||
or not isinstance(case['version'], int) or case['version'] < 0 \
|
||||
or case.get('tokenEnv', 'AIXUN_BI_TOKEN') not in ('AIXUN_BI_TOKEN', 'AIXUN_BI_READER_TOKEN'):
|
||||
raise ValueError('case identity invalid')
|
||||
selected_token = os.environ[case.get('tokenEnv', 'AIXUN_BI_TOKEN')]
|
||||
status, body = request(base, token, '/api/dataproduct/v1/bi/objects/' + case['objectId'])
|
||||
observed = body.get('data') or {}
|
||||
spec = observed.get('spec') or {}
|
||||
if status != 200 or body.get('code') != 200 or observed.get('version') != case['version'] or observed.get('kind') != 'DATASET' or not spec.get('semantic'):
|
||||
raise ValueError('saved semantic analysis version not verified')
|
||||
dataset_ids = [spec['sourceDatasetId']] + [d['sourceDatasetId'] for d in spec['semantic']['dimensions']]
|
||||
for dataset_id in dataset_ids:
|
||||
if not isinstance(dataset_id, str) or not re.fullmatch(r'[1-9][0-9]{0,18}', dataset_id):
|
||||
raise ValueError('dataset identity invalid')
|
||||
status, body = request(base, token, '/api/dataproduct/v1/dataset-publications/' + dataset_id)
|
||||
dataset = (body.get('data') or {}).get('dataset') or {}
|
||||
if status != 200 or body.get('code') != 200 or dataset.get('sourceRef') not in {'table:' + table_id for table_id in expected_tables}:
|
||||
raise ValueError('analysis references a non-fixture source')
|
||||
status, body = request(base, selected_token, '/api/dataproduct/v1/bi/objects/' + case['objectId'] + '/query', {'version': case['version']})
|
||||
reports.append(assert_query(status, body, case))
|
||||
return reports
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base', default='http://127.0.0.1:28000/prod-api')
|
||||
parser.add_argument('--manifest', required=True)
|
||||
parser.add_argument('--execute', action='store_true')
|
||||
args = parser.parse_args()
|
||||
parsed = urllib.parse.urlparse(args.base)
|
||||
if parsed.scheme not in ('http', 'https') or parsed.hostname not in ('127.0.0.1', 'localhost') \
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path != '/prod-api':
|
||||
raise SystemExit('Only the project local /prod-api gateway is allowed')
|
||||
try:
|
||||
with open(args.manifest, encoding='utf-8') as stream:
|
||||
manifest = json.load(stream)
|
||||
if not args.execute:
|
||||
print(json.dumps({'state': 'NOT_RUN', 'cases': len(manifest.get('cases', [])), 'reason': 'requires deployed source identities and explicit --execute'}))
|
||||
else:
|
||||
print(json.dumps({'state': 'PASS', 'cases': run(args.base.rstrip('/'), manifest)}, ensure_ascii=False))
|
||||
except Exception as error:
|
||||
print(json.dumps({'state': 'FAILED', 'errorType': type(error).__name__, 'reason': 'query evidence mismatch or dependency unavailable; credentials and response withheld'}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"project": "aixun-datagov-local",
|
||||
"owner": "aixun-datagov",
|
||||
"service": "dataops",
|
||||
"container": "aixun-datagov-dataops",
|
||||
"network": {
|
||||
"composeKey": "backend",
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"targetIp": "172.21.0.6",
|
||||
"aliases": ["aixun-datagov-dataops", "dataops"]
|
||||
},
|
||||
"portBindings": {"9320/tcp": [{"HostIp": "127.0.0.1", "HostPort": "29320"}]}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# Compatibility name for the current interface; legacy lease modes are retired.
|
||||
set -euo pipefail
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
service=integration
|
||||
if [[ "${1:-}" == --service ]]; then service="${2:?service required}"; shift 2; fi
|
||||
mode="${1:---help}"
|
||||
if [[ "$mode" == --help ]]; then exec "$DIR/deploy.sh" --help; fi
|
||||
shift
|
||||
case "$mode" in
|
||||
--plan|--apply|--check-config) exec "$DIR/deploy.sh" "$mode" "$service" "$@" ;;
|
||||
*) echo 'Legacy upgrade/config modes retired. Use script/datagov/deploy.sh --help.' >&2; exit 2 ;;
|
||||
esac
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
exec python3 "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/remote/release.py" "$@"
|
||||
可执行文件
+336
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Targeted local delivery: no task leases, whole builds or manual SHA approval."""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from deployment_artifacts import artifact_digest, verify_image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = ROOT / 'script/datagov'
|
||||
CONFIG = BASE / 'deployment'
|
||||
STATE = ROOT / '.cache/datagov'
|
||||
PROJECT = 'aixun-datagov-local'
|
||||
OWNER = 'aixun-datagov'
|
||||
SERVICES = ('auth', 'gateway', 'system', 'resource', 'integration', 'dataops', 'governance', 'dataproduct', 'frontend')
|
||||
CONFIGURABLE_FIELDS = {'image','environment','command','entrypoint','working_dir','restart'}
|
||||
|
||||
class Rejected(Exception):
|
||||
pass
|
||||
|
||||
def need(condition, code):
|
||||
if not condition:
|
||||
raise Rejected(code)
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
def stable_model_sha(item):
|
||||
return digest({k:v for k,v in item.items() if k not in CONFIGURABLE_FIELDS})
|
||||
|
||||
def compose_input(value):
|
||||
# Compose interpolates input again. Preserve literal dollars in resolved
|
||||
# values without persisting the secret-bearing model to a temporary file.
|
||||
if isinstance(value,str):
|
||||
return value.replace('$','$$')
|
||||
if isinstance(value,list):
|
||||
return [compose_input(v) for v in value]
|
||||
if isinstance(value,dict):
|
||||
return {k:compose_input(v) for k,v in value.items()}
|
||||
return value
|
||||
|
||||
def run(args, env=None, input_text=None):
|
||||
try:
|
||||
p = subprocess.run(args, cwd=ROOT, env={**os.environ, **(env or {})}, input=input_text, capture_output=True, text=True, timeout=120)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Rejected('command timed out: ' + Path(args[0]).name + '; reconcile any apply attempt before retrying') from None
|
||||
need(p.returncode == 0, 'command failed: ' + Path(args[0]).name + '; raw output withheld')
|
||||
return p.stdout
|
||||
|
||||
def docker(*args):
|
||||
return json.loads(run(['docker', *args]))
|
||||
|
||||
def env_values(values):
|
||||
return dict(item.split('=', 1) for item in values or [] if '=' in item)
|
||||
|
||||
def own(labels, service=None):
|
||||
need(labels.get('com.aixun.project') == OWNER and labels.get('com.docker.compose.project') == PROJECT, 'foreign runtime object')
|
||||
if service:
|
||||
need(labels.get('com.docker.compose.service') == service, 'wrong service')
|
||||
|
||||
def mount_source(mount):
|
||||
source = mount['Source']
|
||||
if mount['Type'] == 'bind' and source.startswith('/host_mnt/'):
|
||||
return source[len('/host_mnt'):]
|
||||
return source
|
||||
|
||||
def mounts(container):
|
||||
return sorted([{'type':m['Type'], 'source':mount_source(m), 'destination':m['Destination'], 'rw':m['RW']} for m in container['Mounts']], key=lambda m:m['destination'])
|
||||
|
||||
def identity(service):
|
||||
return json.loads((CONFIG/'identities.json').read_text())[service]
|
||||
|
||||
def network_ip(value):
|
||||
return value['IPAddress'] or (value.get('IPAMConfig') or {}).get('IPv4Address', '')
|
||||
|
||||
def current(service, allow_stopped=False):
|
||||
b = identity(service)
|
||||
c = docker('inspect', b['container'])[0]
|
||||
own(c['Config'].get('Labels') or {}, service)
|
||||
need(c['Name'] == '/' + b['container'] and (c['State']['Running'] or (allow_stopped and c['State']['Status'] == 'exited')), 'target is not the expected running or stopped container')
|
||||
observed = {k:{'id':v['NetworkID'], 'ip':network_ip(v)} for k,v in c['NetworkSettings']['Networks'].items()}
|
||||
need(observed == b['networks'], 'network identity or IP drift')
|
||||
for name, expected in b['networks'].items():
|
||||
network = docker('network', 'inspect', name)[0]
|
||||
own(network.get('Labels') or {})
|
||||
need(network['Id'] == expected['id'], 'network replacement detected')
|
||||
need(mounts(c) == sorted(b['mounts'], key=lambda m:m['destination']), 'mount identity drift')
|
||||
for mount in b['mounts']:
|
||||
if mount['type'] == 'volume':
|
||||
own(docker('volume', 'inspect', Path(mount['source']).parts[-2])[0].get('Labels') or {})
|
||||
return c
|
||||
|
||||
def snapshot(c):
|
||||
config = dict(c['Config'])
|
||||
config.pop('Hostname', None)
|
||||
config.pop('Image', None)
|
||||
config['Labels'] = {k:v for k,v in (config.get('Labels') or {}).items() if not k.startswith('com.docker.compose.') and k != 'org.opencontainers.image.version'}
|
||||
return digest({'config':config, 'host':c['HostConfig'], 'mounts':mounts(c), 'networks':{k:{'id':v['NetworkID'],'ip':v['IPAddress']} for k,v in c['NetworkSettings']['Networks'].items()}})
|
||||
|
||||
def compose(service, image, config_change=False):
|
||||
env = {'AIXUN_DATAGOV_DEPLOY_IMAGE':image}
|
||||
cmd = ['docker', 'compose', '--project-directory', str(BASE), '--env-file', str(BASE/'.env.datagov'), '-p', PROJECT, '-f', str(CONFIG/(service+'.json'))]
|
||||
model = json.loads(run(cmd + ['config', '--format', 'json'], env))
|
||||
need(model.get('name') == PROJECT and set(model['services']) == {service}, 'unexpected deployment scope')
|
||||
item = model['services'][service]
|
||||
need(item['container_name'] == 'aixun-datagov-' + service and item['labels']['com.aixun.project'] == OWNER and item['image'] == image, 'invalid service model')
|
||||
need(all(n.get('external') for n in model['networks'].values()), 'deployment cannot manage network lifecycle')
|
||||
need(all(v.get('external') for v in model.get('volumes', {}).values()), 'deployment cannot manage volume lifecycle')
|
||||
if config_change:
|
||||
need(stable_model_sha(item)==identity(service).get('stableModelSha256'),'configuration note covers only environment, launch and restart; runtime identity or privilege fields changed')
|
||||
else:
|
||||
need(digest({k:v for k,v in item.items() if k != 'image'}) == identity(service)['runtimeModelSha256'], 'configuration changed; record the intended change with --config-change-note in this plan')
|
||||
return cmd, env, model
|
||||
|
||||
def validate_runtime_model(service, model, c, config_change=False):
|
||||
s = model['services'][service]
|
||||
for key,value in s.get('environment',{}).items():
|
||||
name=key.upper().replace('.','_').replace('-','_')
|
||||
if 'NACOS' in name and name.endswith('NAMESPACE'):
|
||||
need(value==PROJECT,'Nacos namespace must remain DataGov-only')
|
||||
if 'NACOS' in name and name.endswith('GROUP'):
|
||||
need(value=='AIXUN_DATAGOV_GROUP','Nacos group must remain DataGov-only')
|
||||
if not config_change:
|
||||
need(all(env_values(c['Config']['Env']).get(k) == str(v) for k,v in s.get('environment',{}).items()), 'declared environment drift')
|
||||
expected_ports = {}
|
||||
for port in s.get('ports', []):
|
||||
key = str(port['target']) + '/' + port.get('protocol','tcp')
|
||||
expected_ports.setdefault(key, []).append({'HostIp':port.get('host_ip',''), 'HostPort':str(port['published'])})
|
||||
# Docker represents explicit 0.0.0.0 as either 0.0.0.0 or empty.
|
||||
normalize = lambda values: {k:sorted((p['HostIp'] or '0.0.0.0',p['HostPort']) for p in v) for k,v in values.items()}
|
||||
need(normalize(expected_ports) == normalize(c['HostConfig'].get('PortBindings') or {}), 'declared port drift')
|
||||
expected_mounts = []
|
||||
for m in s.get('volumes', []):
|
||||
source = model['volumes'][m['source']]['name'] if m['type'] == 'volume' else m['source']
|
||||
expected_mounts.append((m['type'], source, m['target'], not m.get('read_only',False)))
|
||||
actual_mounts = [(m['Type'], m.get('Name') if m['Type']=='volume' else mount_source(m), m['Destination'], m['RW']) for m in c['Mounts']]
|
||||
need(sorted(expected_mounts) == sorted(actual_mounts), 'declared mount drift')
|
||||
declared = {model['networks'][k]['name']:v.get('ipv4_address') for k,v in s['networks'].items()}
|
||||
need(declared == {k:network_ip(v) for k,v in c['NetworkSettings']['Networks'].items()}, 'declared network drift')
|
||||
if not config_change:
|
||||
need(s.get('restart','no') == c['HostConfig']['RestartPolicy']['Name'], 'restart policy drift')
|
||||
|
||||
def effective_launch(service, model, image):
|
||||
s=model['services'][service];config=image['Config']
|
||||
result={k:config.get(k) for k in ('Entrypoint','Cmd','WorkingDir','User')}
|
||||
for field,key in [('entrypoint','Entrypoint'),('command','Cmd'),('working_dir','WorkingDir'),('user','User')]:
|
||||
if field in s and s[field] is not None:
|
||||
result[key]=s[field]
|
||||
# An explicit Compose entrypoint suppresses the image's default command.
|
||||
if s.get('entrypoint') is not None and s.get('command') is None:
|
||||
result['Cmd']=None
|
||||
return result
|
||||
|
||||
def validate_launch(service, model, image, c, config_change=False):
|
||||
launch=effective_launch(service,model,image)
|
||||
changed=[k for k,v in launch.items() if (v or None)!=(c['Config'].get(k) or None)]
|
||||
need('User' not in changed,'container user change needs an explicit runtime identity change')
|
||||
need(config_change or not changed,'launch configuration changed; record it with --config-change-note')
|
||||
return changed
|
||||
|
||||
def inspect_image(service, ref):
|
||||
need(bool(re.fullmatch(r'aixun-datagov/'+service+r':[a-z0-9][a-z0-9_.-]*',ref)) and not ref.endswith(':latest'), 'use an exact DataGov image tag')
|
||||
image = docker('image', 'inspect', ref)[0]
|
||||
need((image['Config'].get('Labels') or {}).get('com.aixun.project') == OWNER, 'foreign image')
|
||||
return image
|
||||
|
||||
def artifact_source(service, image):
|
||||
if service != 'frontend':
|
||||
return None
|
||||
values = env_values(image['Config'].get('Env'))
|
||||
source = values.get('AIXUN_DATAGOV_FRONTEND_SOURCE', '/opt/aixun-datagov/frontend-current')
|
||||
need(bool(re.fullmatch(r'/opt/aixun-datagov/frontend-[A-Za-z0-9_.-]+', source)),
|
||||
'unexpected frontend artifact source')
|
||||
return source
|
||||
|
||||
@contextmanager
|
||||
def deployment_lock():
|
||||
STATE.mkdir(parents=True, exist_ok=True)
|
||||
with (STATE/'deployment.lock').open('a') as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise Rejected('another deployment is applying; coding remains available')
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||
|
||||
def plan_path(service, release):
|
||||
need(bool(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,95}',release)), 'invalid release name')
|
||||
return CONFIG/'releases'/(release+'-'+service+'.json')
|
||||
|
||||
def write_json(path, value, exclusive=False):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('x' if exclusive else 'w') as f:
|
||||
json.dump(value, f, indent=2); f.write('\n')
|
||||
path.chmod(0o600)
|
||||
|
||||
def plan(args):
|
||||
need(args.image is not None, 'plan needs IMAGE_TAG')
|
||||
path = plan_path(args.service,args.release)
|
||||
c = current(args.service, allow_stopped=True)
|
||||
image = inspect_image(args.service,args.image)
|
||||
source = artifact_source(args.service,image)
|
||||
note=(getattr(args,'config_change_note',None) or '').strip()
|
||||
cmd, env, model = compose(args.service,image['Id'],config_change=bool(note))
|
||||
validate_runtime_model(args.service,model,c,config_change=bool(note))
|
||||
launch_changes=validate_launch(args.service,model,image,c,config_change=bool(note))
|
||||
expected = artifact_digest(args.artifact) if args.artifact else args.artifact_sha
|
||||
need(bool(expected and re.fullmatch('[0-9a-f]{64}',expected)), 'supply --artifact PATH or --artifact-sha SHA256')
|
||||
verification = verify_image(image['Id'],expected,STATE/'artifacts',args.service=='frontend',
|
||||
source or '/opt/aixun-datagov/frontend-current')
|
||||
result = {'version':1,'service':args.service,'release':args.release,'imageTag':args.image,'imageId':image['Id'],'artifactSha256':expected,'sourceContainerId':c['Id'],'sourceImageId':c['Image'],'sourceImageTag':c['Config']['Image'],'sourceStateSha256':snapshot(c),'modelSha256':digest(model),'identitySha256':digest(identity(args.service))}
|
||||
if source:
|
||||
result['artifactPath'] = source
|
||||
if note:
|
||||
declared=model['services'][args.service]
|
||||
result['configurationChange']={'note':note,'environmentKeys':[k for k,v in declared.get('environment',{}).items() if env_values(c['Config']['Env']).get(k)!=str(v)],'launchFields':launch_changes,'restartPolicyChanged':declared.get('restart','no')!=c['HostConfig']['RestartPolicy']['Name'],'previousModelSha256':identity(args.service)['runtimeModelSha256'],'desiredModelSha256':digest({k:v for k,v in declared.items() if k!='image'})}
|
||||
if path.exists():
|
||||
need(json.loads(path.read_text()) == result, 'plan changed; use a new release name')
|
||||
else:
|
||||
write_json(path,result,exclusive=True)
|
||||
print(json.dumps({'plan':str(path.relative_to(ROOT)),'service':args.service,'imageId':image['Id'],'artifactVerification':verification,'runtimeMutation':False}))
|
||||
|
||||
def verify_deployed_artifact(service, container_id, expected,
|
||||
frontend_source='/opt/aixun-datagov/frontend-current'):
|
||||
if service != 'frontend':
|
||||
actual = run(['docker','exec',container_id,'sha256sum','/aixun-datagov/app/app.jar']).split()
|
||||
need(bool(actual) and actual[0] == expected, 'deployed JAR hash mismatch')
|
||||
return
|
||||
# The existing entrypoint activates index.html after copying immutable assets.
|
||||
# Wait only for that technical activation, not for functional UAT.
|
||||
# The measured wave15 asset activation took 67s while backend images started.
|
||||
# This remains a bounded, read-only activation check; it never retries apply.
|
||||
deadline = time.monotonic() + 120
|
||||
while True:
|
||||
output = run(['docker','exec',container_id,'sha256sum',frontend_source + '/index.html',
|
||||
'/usr/share/nginx/html/index.html'])
|
||||
hashes = [line.split()[0] for line in output.splitlines() if line.split()]
|
||||
if len(hashes) == 2 and hashes[0] == hashes[1]:
|
||||
return
|
||||
need(time.monotonic() < deadline, 'frontend entrypoint did not activate the image index')
|
||||
time.sleep(0.5)
|
||||
|
||||
def apply(args):
|
||||
need(bool(args.authorized_by and args.authorized_by.strip()), 'record the existing user deployment request with --authorized-by')
|
||||
path = plan_path(args.service,args.release)
|
||||
p = json.loads(path.read_text())
|
||||
need(p.get('version')==1 and p['service']==args.service and p['release']==args.release, 'plan scope mismatch')
|
||||
attempt = path.with_name(path.stem+'-attempt.json')
|
||||
with deployment_lock():
|
||||
need(not attempt.exists(), 'prior apply outcome must be reconciled; no automatic retry')
|
||||
# Target preflight is performed below: owned live container/network/volume,
|
||||
# exact immutable image and declared config. Bootstrap seeds and unrelated
|
||||
# services are not prerequisites for updating an existing application.
|
||||
c = current(args.service, allow_stopped=True)
|
||||
need(c['Id']==p['sourceContainerId'] and c['Image']==p['sourceImageId'] and snapshot(c)==p['sourceStateSha256'], 'live source drift; replan')
|
||||
need(digest(identity(args.service))==p['identitySha256'], 'identity baseline drift')
|
||||
image = inspect_image(args.service,p['imageTag'])
|
||||
need(image['Id']==p['imageId'], 'image tag moved; replan')
|
||||
source = artifact_source(args.service,image)
|
||||
if source:
|
||||
need(p.get('artifactPath') == source, 'frontend artifact source is not bound by this plan')
|
||||
verify_image(image['Id'],p['artifactSha256'],STATE/'artifacts',args.service=='frontend',
|
||||
source or '/opt/aixun-datagov/frontend-current')
|
||||
config_change=bool(p.get('configurationChange',{}).get('note'))
|
||||
cmd, env, model = compose(args.service,image['Id'],config_change=config_change)
|
||||
need(digest(model)==p['modelSha256'], 'configuration changed; replan')
|
||||
validate_runtime_model(args.service,model,c,config_change=config_change)
|
||||
validate_launch(args.service,model,image,c,config_change=config_change)
|
||||
# Bind the immutable image ID, avoiding mutable-tag races.
|
||||
operation = ['up','-d','--no-deps','--no-build','--pull','never','--force-recreate',args.service]
|
||||
write_json(attempt,{'sourceContainerId':c['Id'],'imageId':image['Id'],'authorizedBy':args.authorized_by,'startedAt':time.time()},exclusive=True)
|
||||
# Apply exactly the model just checked. A concurrent edit of the source
|
||||
# Compose/env files cannot silently change this deployment's inputs.
|
||||
frozen_cmd=['docker','compose','--project-directory',str(BASE),'-p',PROJECT,'-f','-']
|
||||
run(frozen_cmd+operation,env,input_text=json.dumps(compose_input(model)))
|
||||
after = current(args.service)
|
||||
need(after['Id']!=c['Id'] and after['Image']==image['Id'], 'post-apply image identity mismatch')
|
||||
validate_runtime_model(args.service,model,after)
|
||||
validate_launch(args.service,model,image,after)
|
||||
if source:
|
||||
verify_deployed_artifact(args.service,after['Id'],p['artifactSha256'],source)
|
||||
else:
|
||||
verify_deployed_artifact(args.service,after['Id'],p['artifactSha256'])
|
||||
after = current(args.service)
|
||||
need(not after['State'].get('OOMKilled') and after['RestartCount']==0,'post-apply startup failure')
|
||||
result = {'service':args.service,'containerId':after['Id'],'imageId':image['Id'],'status':'DEPLOYED_FUNCTIONAL_UAT_NOT_RUN','artifactReadback':'PASS','applicationReadiness':'NOT_RUN','recoveryImageId':p['sourceImageId']}
|
||||
if config_change:
|
||||
baselines=json.loads((CONFIG/'identities.json').read_text())
|
||||
baselines[args.service]['runtimeModelSha256']=digest({k:v for k,v in model['services'][args.service].items() if k!='image'})
|
||||
temporary=CONFIG/'identities.json.tmp'
|
||||
write_json(temporary,baselines)
|
||||
os.replace(temporary,CONFIG/'identities.json')
|
||||
result['configurationChangeVerified']=True
|
||||
write_json(path.with_name(path.stem+'-result.json'),result)
|
||||
print(json.dumps(result))
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
modes = parser.add_mutually_exclusive_group(required=True)
|
||||
modes.add_argument('--plan',action='store_true')
|
||||
modes.add_argument('--apply',action='store_true')
|
||||
modes.add_argument('--check-config',action='store_true',help='inspect live identity/config without creating a release')
|
||||
parser.add_argument('service',choices=SERVICES)
|
||||
parser.add_argument('release',nargs='?')
|
||||
parser.add_argument('image',nargs='?')
|
||||
parser.add_argument('--artifact',help='local JAR or frontend dist directory')
|
||||
parser.add_argument('--artifact-sha',help='known JAR/tree SHA when no local artifact copy is needed')
|
||||
parser.add_argument('--authorized-by',help='existing user request authorizing this local deployment; not a new approval')
|
||||
parser.add_argument('--config-change-note',help='describe an intended environment/launch/restart change in this authorized task; no new approval')
|
||||
args = parser.parse_args(argv)
|
||||
if args.check_config:
|
||||
c = current(args.service)
|
||||
_,_,model = compose(args.service,c['Image'])
|
||||
validate_runtime_model(args.service,model,c)
|
||||
print(json.dumps({'service':args.service,'configuration':'PASS','runtimeMutation':False}))
|
||||
else:
|
||||
need(args.release is not None,'release name required')
|
||||
plan(args) if args.plan else apply(args)
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (Rejected,ValueError,KeyError,OSError) as exc:
|
||||
# Avoid printing configuration/secret values from parser or command errors.
|
||||
print('BLOCKED: '+(str(exc) if isinstance(exc,Rejected) else type(exc).__name__),file=sys.stderr)
|
||||
sys.exit(2)
|
||||
可执行文件
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
exec python3 "$DIR/deploy.py" "$@"
|
||||
@@ -0,0 +1,26 @@
|
||||
# 当前局部部署配置
|
||||
|
||||
2026-10-10从九个现有应用服务各自的实际Compose文件链整理;通过逐服务有效配置对比。仅移除构建/依赖启动/配置profile,网络固定为当时真实IP,所有网络和卷使用external以保护现有生命周期。无服务重启。
|
||||
|
||||
每个服务一份JSON,不再依赖历史evidence中的Compose叠加链。相对路径以script/datagov为基准,秘密仍来自原.env/secretRef,不写入这些文件。
|
||||
|
||||
~~~bash
|
||||
# 当前运行身份和配置检查,不创建候选或变更运行对象
|
||||
./script/datagov/deploy.sh --check-config governance
|
||||
# 镜像已经按需构建后,绑定实际JAR和不可变image ID
|
||||
./script/datagov/deploy.sh --plan governance repair-20261010 aixun-datagov/governance:repair-20261010 --artifact aixun-modules/aixun-governance/target/aixun-governance.jar
|
||||
# 用户原请求已包含部署时连续执行,记录原请求,无二次SHA审批
|
||||
./script/datagov/deploy.sh --apply governance repair-20261010 --authorized-by '用户在当前任务要求修复并部署本地governance'
|
||||
~~~
|
||||
|
||||
前端同样使用frontend服务,--artifact指向aixun-ui/dist;已有准确SHA可用--artifact-sha避免复制制品。计划仅写本地小JSON和验证缓存,Docker侧只读。apply使用不可变image ID、短进程锁及即时前态检查,只重建指定服务,不build/pull/启动依赖;不自动回滚或重试未知结果。
|
||||
|
||||
镜像内容通过流式读取核对,仅缓存image ID+制品SHA+验证器版本,不保存tar。运行状态或配置检查不使用缓存。保留当前镜像及必要恢复制品;releases记录前后身份,成功部署不代表功能UAT通过。
|
||||
|
||||
环境变量、启动命令/工作目录和restart策略需要修改时,在同一计划加--config-change-note说明原因,不重复申请用户已授予的部署权限。计划记录变更字段及前后摘要,不保存秘密值;apply绑定已检查的完整配置,经标准输入传给Compose,不因其他任务随后编辑源配置而改变本次部署。成功读回后自动更新目标配置基线。容器用户/特权、网络/IP、端口和挂载变化不在此参数范围,需要按实际运行变更范围处理。
|
||||
|
||||
例如:deploy.sh --plan governance repair-config-20261010 aixun-datagov/governance:repair-20261010 --artifact aixun-modules/aixun-governance/target/aixun-governance.jar --config-change-note '按本次需求调整应用启动参数'。随后用相同release执行apply。
|
||||
|
||||
局部apply已内置目标预检,不调用bootstrap整栈preflight,不依赖管理员初始化SQL或无关应用的构建/配置。只读检查可使用check.sh --runtime SERVICE。Docker命令最多等待120秒;超时保留已开始的apply记录,核实结果后处理,禁止自动循环重试。
|
||||
|
||||
原运行容器标签仍保留其创建时的历史文件名;本次保留这些少量文件以兼容追溯。新交付使用本目录。bootstrap用的docker-compose.local.yml继续保留,不能用它覆盖现有应用局部发布配置。
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"auth": {
|
||||
"container_name": "aixun-datagov-auth",
|
||||
"environment": {
|
||||
"AIXUN_DATAGOV_JWT_SECRET": "${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"JAVA_OPTS": "-Xms128m -Xmx448m -XX:MaxMetaspaceSize=224m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k",
|
||||
"DM_HOST": "${DM_HOST:?required}",
|
||||
"DM_PASSWORD": "${DM_PASSWORD:?required}",
|
||||
"DM_PORT": "${DM_PORT:-5236}",
|
||||
"DM_USERNAME": "${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA": "${DM_SCHEMA:?required}",
|
||||
"SECURITY_CAPTCHA_ENABLED": "false",
|
||||
"SERVER_PORT": "9210",
|
||||
"SPRING_APPLICATION_NAME": "aixun-datagov-auth",
|
||||
"SPRING_CLOUD_BUS_ENABLED": "false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD": "${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR": "nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME": "${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE": "11",
|
||||
"SPRING_DATA_REDIS_HOST": "redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD": "${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT": "6379",
|
||||
"SPRING_PROFILES_ACTIVE": "prod",
|
||||
"TZ": "Asia/Shanghai"
|
||||
},
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.2"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_AUTH_PORT:-29210}:9210"
|
||||
],
|
||||
"restart": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"dataops": {
|
||||
"container_name": "aixun-datagov-dataops",
|
||||
"environment": {
|
||||
"AIXUN_DATAGOV_INGESTION_PILOT_SOURCE_ID": "${AIXUN_DATAGOV_INGESTION_PILOT_SOURCE_ID:-0}",
|
||||
"AIXUN_DATAGOV_JWT_SECRET": "${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"DATAGOV_BATCH_INGESTION_HIVE_METASTORE_URI": "thrift://m2-hive-metastore:9083",
|
||||
"JAVA_OPTS": "-Xms96m -Xmx384m -XX:MaxMetaspaceSize=224m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k",
|
||||
"DM_HOST": "${DM_HOST:?required}",
|
||||
"DM_PASSWORD": "${DM_PASSWORD:?required}",
|
||||
"DM_PORT": "${DM_PORT:-5236}",
|
||||
"DM_USERNAME": "${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA": "${DM_SCHEMA:?required}",
|
||||
"SERVER_PORT": "9320",
|
||||
"SPRING_APPLICATION_NAME": "aixun-dataops",
|
||||
"SPRING_CLOUD_BUS_ENABLED": "false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD": "${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR": "nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME": "${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE": "11",
|
||||
"SPRING_DATA_REDIS_HOST": "redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD": "${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT": "6379",
|
||||
"SPRING_PROFILES_ACTIVE": "prod",
|
||||
"TZ": "Asia/Shanghai"
|
||||
},
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.12"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_DATAOPS_PORT:-29320}:9320"
|
||||
],
|
||||
"restart": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"dataproduct": {
|
||||
"container_name": "aixun-datagov-dataproduct",
|
||||
"environment": {
|
||||
"AIXUN_DATAGOV_JWT_SECRET": "${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"JAVA_OPTS": "-Xms96m -Xmx384m -XX:MaxMetaspaceSize=224m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k",
|
||||
"DM_HOST": "${DM_HOST:?required}",
|
||||
"DM_PASSWORD": "${DM_PASSWORD:?required}",
|
||||
"DM_PORT": "${DM_PORT:-5236}",
|
||||
"DM_USERNAME": "${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA": "${DM_SCHEMA:?required}",
|
||||
"SERVER_PORT": "9340",
|
||||
"SPRING_APPLICATION_NAME": "aixun-dataproduct",
|
||||
"SPRING_CLOUD_BUS_ENABLED": "false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD": "${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR": "nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME": "${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE": "11",
|
||||
"SPRING_DATA_REDIS_HOST": "redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD": "${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT": "6379",
|
||||
"SPRING_PROFILES_ACTIVE": "prod",
|
||||
"TZ": "Asia/Shanghai"
|
||||
},
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.5"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_DATAPRODUCT_PORT:-29340}:9340"
|
||||
],
|
||||
"pull_policy": "never",
|
||||
"restart": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"frontend": {
|
||||
"container_name": "aixun-datagov-frontend",
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"frontend": {
|
||||
"ipv4_address": "172.22.0.3"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"0.0.0.0:${AIXUN_DATAGOV_FRONTEND_PORT:-28000}:80"
|
||||
],
|
||||
"restart": "unless-stopped",
|
||||
"volumes": [
|
||||
{
|
||||
"source": "frontend-assets",
|
||||
"target": "/usr/share/nginx/html",
|
||||
"type": "volume",
|
||||
"volume": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"frontend": {
|
||||
"name": "aixun-datagov-local-frontend",
|
||||
"external": true
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"frontend-assets": {
|
||||
"name": "aixun-datagov-local-frontend-assets",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"gateway": {
|
||||
"container_name": "aixun-datagov-gateway",
|
||||
"environment": [
|
||||
"AIXUN_DATAGOV_JWT_SECRET=${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"JAVA_OPTS=-Xms128m -Xmx384m -XX:MaxMetaspaceSize=192m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k",
|
||||
"DM_HOST=${DM_HOST:?required}",
|
||||
"DM_PASSWORD=${DM_PASSWORD:?required}",
|
||||
"DM_PORT=${DM_PORT:-5236}",
|
||||
"DM_USERNAME=${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA=${DM_SCHEMA:?required}",
|
||||
"SERVER_PORT=8080",
|
||||
"SPRING_APPLICATION_NAME=aixun-datagov-gateway",
|
||||
"SPRING_CLOUD_BUS_ENABLED=false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP=AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE=aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP=AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE=aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD=${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR=nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME=${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE=11",
|
||||
"SPRING_DATA_REDIS_HOST=redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD=${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT=6379",
|
||||
"SPRING_PROFILES_ACTIVE=prod",
|
||||
"TZ=Asia/Shanghai",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_IP=172.21.0.11"
|
||||
],
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": [
|
||||
"com.aixun.environment=local",
|
||||
"com.aixun.project=aixun-datagov",
|
||||
"org.opencontainers.image.version=m7-ingestion-draft-timeout-20260920-001"
|
||||
],
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.11"
|
||||
},
|
||||
"frontend": {
|
||||
"ipv4_address": "172.22.0.2"
|
||||
},
|
||||
"m2-integration": {
|
||||
"ipv4_address": "172.29.0.2"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_GATEWAY_PORT:-28080}:8080"
|
||||
],
|
||||
"pull_policy": "never",
|
||||
"restart": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
},
|
||||
"frontend": {
|
||||
"name": "aixun-datagov-local-frontend",
|
||||
"external": true
|
||||
},
|
||||
"m2-integration": {
|
||||
"name": "aixun-datagov-local-m2-integration",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"governance": {
|
||||
"container_name": "aixun-datagov-governance",
|
||||
"environment": {
|
||||
"AIXUN_DATAGOV_JWT_SECRET": "${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"JAVA_OPTS": "-Xms96m -Xmx384m -XX:MaxMetaspaceSize=224m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k",
|
||||
"DM_HOST": "${DM_HOST:?required}",
|
||||
"DM_PASSWORD": "${DM_PASSWORD:?required}",
|
||||
"DM_PORT": "${DM_PORT:-5236}",
|
||||
"DM_USERNAME": "${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA": "${DM_SCHEMA:?required}",
|
||||
"SERVER_PORT": "9330",
|
||||
"SPRING_APPLICATION_NAME": "aixun-governance",
|
||||
"SPRING_CLOUD_BUS_ENABLED": "false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP": "AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE": "aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD": "${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR": "nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME": "${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE": "11",
|
||||
"SPRING_DATA_REDIS_HOST": "redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD": "${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT": "6379",
|
||||
"SPRING_PROFILES_ACTIVE": "prod",
|
||||
"TZ": "Asia/Shanghai"
|
||||
},
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.10"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_GOVERNANCE_PORT:-29330}:9330"
|
||||
],
|
||||
"restart": "unless-stopped"
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
{
|
||||
"auth": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.2"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-auth",
|
||||
"initialImageId": "sha256:068d5c30fbf457ff1b66cabf8da2b3ab5947d63453705ae0341b23c8ca9c34d0",
|
||||
"runtimeModelSha256": "249c3a81742da317d79ddd2f3a11a5b8c19e8fb4db6d49379354b30e788000c9",
|
||||
"stableModelSha256": "0e66d5244a9c9dcc4044e339227a4d71b0767b2d9c462224c7d1230d2da460bf"
|
||||
},
|
||||
"gateway": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.11"
|
||||
},
|
||||
"aixun-datagov-local-frontend": {
|
||||
"id": "fd5a9c9f35d06101a75e5d8edaf3dd73b5ef7bfe5bbb112224048f4a968d025d",
|
||||
"ip": "172.22.0.2"
|
||||
},
|
||||
"aixun-datagov-local-m2-integration": {
|
||||
"id": "64f4cce15ac06ce7c8f1ad1f04895e1232c10ae7a6f6076c8b6025ff553b58ba",
|
||||
"ip": "172.29.0.2"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-gateway",
|
||||
"initialImageId": "sha256:101533e52cefdc5e78a9419d3e9ed63af738c5a9803d193bcd2b557d68818d61",
|
||||
"runtimeModelSha256": "841e8575de2d62c9fd9d9a979751f9d4b57d6d64c0200a6399683d98866d6391",
|
||||
"stableModelSha256": "2056c519155e28bbee81d51c82494f9116d2c20160aa8143d8cef147a3a4101d"
|
||||
},
|
||||
"system": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.6"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-system",
|
||||
"initialImageId": "sha256:51cc508e90d343ec33ca43bbf3027041995df9f53c99f9247daca7ce3038b2bd",
|
||||
"runtimeModelSha256": "5860d7c86820452c05d3d221ba1efccc47640371b00d5df9e82dce22a1a42503",
|
||||
"stableModelSha256": "c0c23e755e96389cca09497a839e7b23878807c734af04ec269e6cd978ab7c21"
|
||||
},
|
||||
"resource": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.4"
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "/var/lib/docker/volumes/aixun-datagov-local-file-data/_data",
|
||||
"destination": "/var/lib/aixun-datagov/files",
|
||||
"rw": true
|
||||
}
|
||||
],
|
||||
"container": "aixun-datagov-resource",
|
||||
"initialImageId": "sha256:bcc8a5d1551d0c0f96502eed4dff8cb6fd7867480d587d940003522429a12729",
|
||||
"runtimeModelSha256": "e605935ef21613dd2bce1e380aec853fe2e41dc7c8bacc96c1f41ca2816f72f5",
|
||||
"stableModelSha256": "8c0b6035dbcb2a4093a387491855d578f1575d5df88852ea538604d86b761bd3"
|
||||
},
|
||||
"integration": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.8"
|
||||
},
|
||||
"aixun-datagov-local-m2-integration": {
|
||||
"id": "64f4cce15ac06ce7c8f1ad1f04895e1232c10ae7a6f6076c8b6025ff553b58ba",
|
||||
"ip": "172.29.0.8"
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
{
|
||||
"type": "bind",
|
||||
"source": "/Users/apple/Documents/AiXun-DataGov/script/datagov/m2/local/secrets",
|
||||
"destination": "/run/secrets/aixun-datagov/m2",
|
||||
"rw": false
|
||||
},
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "/var/lib/docker/volumes/aixun-datagov-local-managed-credential-data/_data",
|
||||
"destination": "/run/secrets/aixun-datagov/managed",
|
||||
"rw": true
|
||||
},
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "/var/lib/docker/volumes/aixun-datagov-local-file-ingestion-data/_data",
|
||||
"destination": "/var/lib/aixun-datagov/ingestion",
|
||||
"rw": true
|
||||
}
|
||||
],
|
||||
"container": "aixun-datagov-integration",
|
||||
"initialImageId": "sha256:553d05e2da41ef9b90029c771bf3f44fcc99dfa52dd1705c5f90ed5213b70db7",
|
||||
"runtimeModelSha256": "9a224f8a0c167d0e8d04dc751b4b908a5410dc3540695741a20ac990fc19b031",
|
||||
"stableModelSha256": "af4efb84a9dda8b0c16974347a77b7841dca2d7b0a7760350b443e67c979195a"
|
||||
},
|
||||
"dataops": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.12"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-dataops",
|
||||
"initialImageId": "sha256:7359df0d2ef67feeca94263696565de0edef8f18dae2ae49e10bcfcc9e098afb",
|
||||
"runtimeModelSha256": "5de1a10daca27657f2099fcc6b0bd4de8ce27e45dbc701c1d51328fa5497931f",
|
||||
"stableModelSha256": "facbc2f5201c0c58982200640160917254d183f79d46770c98d7d633213c8a43"
|
||||
},
|
||||
"governance": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.10"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-governance",
|
||||
"initialImageId": "sha256:03b84a618107d9246569e9c733f04903bb7787a156ddd3246c20526d51a105ab",
|
||||
"runtimeModelSha256": "b9384ca577d90f850cf644e6f878cfce4b69a3fe9aff304387232cb830508f69",
|
||||
"stableModelSha256": "5f6e16dd3194b4ad718c952eda64d8f844e7bf255da00bb29d27fe7b12932357"
|
||||
},
|
||||
"dataproduct": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-backend": {
|
||||
"id": "b87d572ee1c15bd96a30fdb46dd0a1b6849980ddd36c50548bcbfa35de9502ac",
|
||||
"ip": "172.21.0.5"
|
||||
}
|
||||
},
|
||||
"mounts": [],
|
||||
"container": "aixun-datagov-dataproduct",
|
||||
"initialImageId": "sha256:67e459cef0cb972da8442eb5d9e433fb8e4f989882677db0b16fb422f4443dcf",
|
||||
"runtimeModelSha256": "03856f1a393605ec5ef4aa3c5286e32b71889d86188d1211366cdf1a853fa9d9",
|
||||
"stableModelSha256": "424127c705f8735eb227946f0015502ce526071f8526d0354b6cfdccf299d82f"
|
||||
},
|
||||
"frontend": {
|
||||
"networks": {
|
||||
"aixun-datagov-local-frontend": {
|
||||
"id": "fd5a9c9f35d06101a75e5d8edaf3dd73b5ef7bfe5bbb112224048f4a968d025d",
|
||||
"ip": "172.22.0.3"
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
{
|
||||
"type": "volume",
|
||||
"source": "/var/lib/docker/volumes/aixun-datagov-local-frontend-assets/_data",
|
||||
"destination": "/usr/share/nginx/html",
|
||||
"rw": true
|
||||
}
|
||||
],
|
||||
"container": "aixun-datagov-frontend",
|
||||
"initialImageId": "sha256:9c501b9d535742d6ff26a8d91327bd31daf2a609891bab2df5ffb712fbfcfacf",
|
||||
"runtimeModelSha256": "f4a76c2841f63bea5964fc7bf4faeedbe1a5c47c17747f4bc3ba88b8646eb180",
|
||||
"stableModelSha256": "6300c283a2bbd47047f4d595ee8c9601e462325a3199e44caaa0e0ff5fc354ab"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"name": "aixun-datagov-local",
|
||||
"services": {
|
||||
"integration": {
|
||||
"container_name": "aixun-datagov-integration",
|
||||
"environment": [
|
||||
"AIXUN_DATAGOV_INGESTION_PILOT_SOURCE_ID=${AIXUN_DATAGOV_INGESTION_PILOT_SOURCE_ID:-0}",
|
||||
"AIXUN_DATAGOV_ALLOW_INSECURE_CREDENTIAL_HTTP=true",
|
||||
"AIXUN_DATAGOV_JWT_SECRET=${AIXUN_DATAGOV_JWT_SECRET:?required}",
|
||||
"AIXUN_DATAGOV_LOCAL_NON_PRODUCTION=true",
|
||||
"AIXUN_DATAGOV_M2_CALLBACK_TOKEN_REF=file:///m2/callback-token?version=v1",
|
||||
"AIXUN_DATAGOV_M2_DORIS_JDBC_URL=jdbc:mysql://m2-doris-fe:9030",
|
||||
"AIXUN_DATAGOV_M2_DORIS_PASSWORD_REF=file:///m2/doris-loader-password?version=v1",
|
||||
"AIXUN_DATAGOV_M2_DORIS_QUERY_PASSWORD_REF=file:///m2/doris-query-password?version=v1",
|
||||
"AIXUN_DATAGOV_M2_DORIS_QUERY_USER=aixun_m2_doris_query",
|
||||
"AIXUN_DATAGOV_M2_DORIS_USER=aixun_m2_doris_loader",
|
||||
"AIXUN_DATAGOV_M2_DS_API_URL=http://m2-dolphinscheduler:12345/dolphinscheduler",
|
||||
"AIXUN_DATAGOV_M2_DS_PROJECT_NAME=aixun_m2_golden_project",
|
||||
"AIXUN_DATAGOV_M2_DS_TOKEN_REF=file:///m2/dolphinscheduler-token?version=v1",
|
||||
"AIXUN_DATAGOV_M2_ENABLED=${AIXUN_DATAGOV_M2_ENABLED:-false}",
|
||||
"AIXUN_DATAGOV_M2_HIVE_JDBC_URL=jdbc:hive2://m2-hive:10000/default",
|
||||
"AIXUN_DATAGOV_M2_HIVE_PASSWORD_REF=file:///m2/hive-loader-password?version=v1",
|
||||
"AIXUN_DATAGOV_M2_HIVE_USER=aixun_m2_hive_loader",
|
||||
"AIXUN_DATAGOV_M2_SEATUNNEL_API_URL=http://m2-seatunnel:8080",
|
||||
"AIXUN_DATAGOV_M2_SEATUNNEL_PASSWORD_REF=file:///m2/seatunnel-password?version=v1",
|
||||
"AIXUN_DATAGOV_M2_SEATUNNEL_USER=aixun_m2_seatunnel",
|
||||
"AIXUN_DATAGOV_M2_SOURCE_JDBC_URL=jdbc:mysql://m2-source-mysql:3306/aixun_m2_source?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai",
|
||||
"AIXUN_DATAGOV_M2_SOURCE_PASSWORD_REF=file:///m2/source-password?version=v1",
|
||||
"AIXUN_DATAGOV_M2_SOURCE_USER=aixun_m2_ingestion",
|
||||
"AIXUN_DATAGOV_MANAGED_CREDENTIAL_ROOT=/run/secrets/aixun-datagov",
|
||||
"AIXUN_DATAGOV_SECRET_ROOT=/run/secrets/aixun-datagov",
|
||||
"DATAGOV_FILE_INGESTION_ROOT=/var/lib/aixun-datagov/ingestion",
|
||||
"JAVA_OPTS=-Xms96m -Xmx384m -XX:MaxMetaspaceSize=224m -XX:MaxDirectMemorySize=96m -XX:ReservedCodeCacheSize=64m -Xss512k -DDUBBO_IP_TO_REGISTRY=integration",
|
||||
"DM_HOST=${DM_HOST:?required}",
|
||||
"DM_PASSWORD=${DM_PASSWORD:?required}",
|
||||
"DM_PORT=${DM_PORT:-5236}",
|
||||
"DM_USERNAME=${DM_USERNAME:?required}",
|
||||
"DM_SCHEMA=${DM_SCHEMA:?required}",
|
||||
"SERVER_PORT=9310",
|
||||
"SPRING_APPLICATION_NAME=aixun-integration",
|
||||
"SPRING_CLOUD_BUS_ENABLED=false",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_GROUP=AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_CONFIG_NAMESPACE=aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_GROUP=AIXUN_DATAGOV_GROUP",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE=aixun-datagov-local",
|
||||
"SPRING_CLOUD_NACOS_PASSWORD=${AIXUN_DATAGOV_NACOS_PASSWORD:?required}",
|
||||
"SPRING_CLOUD_NACOS_SERVER_ADDR=nacos:8848",
|
||||
"SPRING_CLOUD_NACOS_USERNAME=${AIXUN_DATAGOV_NACOS_USERNAME:?required}",
|
||||
"SPRING_DATA_REDIS_DATABASE=11",
|
||||
"SPRING_DATA_REDIS_HOST=redis",
|
||||
"SPRING_DATA_REDIS_PASSWORD=${AIXUN_DATAGOV_REDIS_PASSWORD:?required}",
|
||||
"SPRING_DATA_REDIS_PORT=6379",
|
||||
"SPRING_PROFILES_ACTIVE=prod",
|
||||
"TZ=Asia/Shanghai",
|
||||
"SPRING_CLOUD_NACOS_DISCOVERY_IP=172.21.0.8"
|
||||
],
|
||||
"image": "${AIXUN_DATAGOV_DEPLOY_IMAGE:?explicit local image required}",
|
||||
"labels": {
|
||||
"com.aixun.environment": "local",
|
||||
"com.aixun.project": "aixun-datagov"
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"ipv4_address": "172.21.0.8"
|
||||
},
|
||||
"m2-integration": {
|
||||
"ipv4_address": "172.29.0.8"
|
||||
}
|
||||
},
|
||||
"ports": [
|
||||
"127.0.0.1:${AIXUN_DATAGOV_INTEGRATION_PORT:-29310}:9310"
|
||||
],
|
||||
"restart": "unless-stopped",
|
||||
"volumes": [
|
||||
{
|
||||
"bind": {
|
||||
"create_host_path": true
|
||||
},
|
||||
"read_only": true,
|
||||
"source": "./m2/local/secrets",
|
||||
"target": "/run/secrets/aixun-datagov/m2",
|
||||
"type": "bind"
|
||||
},
|
||||
{
|
||||
"source": "managed-credential-data",
|
||||
"target": "/run/secrets/aixun-datagov/managed",
|
||||
"type": "volume",
|
||||
"volume": {}
|
||||
},
|
||||
{
|
||||
"source": "file-ingestion-data",
|
||||
"target": "/var/lib/aixun-datagov/ingestion",
|
||||
"type": "volume",
|
||||
"volume": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"networks": {
|
||||
"backend": {
|
||||
"name": "aixun-datagov-local-backend",
|
||||
"external": true
|
||||
},
|
||||
"m2-integration": {
|
||||
"name": "aixun-datagov-local-m2-integration",
|
||||
"external": true
|
||||
}
|
||||
},
|
||||
"volumes": {
|
||||
"managed-credential-data": {
|
||||
"name": "aixun-datagov-local-managed-credential-data",
|
||||
"external": true
|
||||
},
|
||||
"file-ingestion-data": {
|
||||
"name": "aixun-datagov-local-file-ingestion-data",
|
||||
"external": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "ec8b446d3c592a2b05f46cbc26ea81ce23798dde72ff3326f790cab29c9fff07",
|
||||
"imageId": "sha256:ce6f02ff448fb397ecdc17cd151a39e4132d73973ef02e3145405bbb2dcf9d41",
|
||||
"authorizedBy": "\u7528\u62372026-10-25\u63a5\u624bA01\u8981\u6c42\u4fee\u590d\u3001\u68c0\u67e5\u3001\u6784\u5efa\u548c\u5df2\u6709\u6388\u6743\u8303\u56f4\u5185\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1792890753.434746
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "dataops",
|
||||
"containerId": "40f8c2425a6b437f193006e53a93ca0b6584b4ae4dd7bbbfbec2c0cc24600141",
|
||||
"imageId": "sha256:ce6f02ff448fb397ecdc17cd151a39e4132d73973ef02e3145405bbb2dcf9d41",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:e2b37c364f596a74cf50e6fd3afee401986a28ec1ff45c7d91d73f034205d24d"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "dataops",
|
||||
"release": "a01-scheduling-20261025",
|
||||
"imageTag": "aixun-datagov/dataops:a01-scheduling-20261025",
|
||||
"imageId": "sha256:ce6f02ff448fb397ecdc17cd151a39e4132d73973ef02e3145405bbb2dcf9d41",
|
||||
"artifactSha256": "48bf6d7ad8aed006e870befa1c3df5f6970bc18ca3d62bb31762b777fc44df74",
|
||||
"sourceContainerId": "ec8b446d3c592a2b05f46cbc26ea81ce23798dde72ff3326f790cab29c9fff07",
|
||||
"sourceImageId": "sha256:e2b37c364f596a74cf50e6fd3afee401986a28ec1ff45c7d91d73f034205d24d",
|
||||
"sourceImageTag": "sha256:e2b37c364f596a74cf50e6fd3afee401986a28ec1ff45c7d91d73f034205d24d",
|
||||
"sourceStateSha256": "3f4606a0eb01fafb00ba11a076f2bb69e7407302885d7f892f3dc439f639ee1c",
|
||||
"modelSha256": "9b6e92c6e6198faf2c1c33c592c66fb8574c182007035153ebf6d95312da6a52",
|
||||
"identitySha256": "ea6543ab531296436dd5850fa7a9d19c9ecba54092ef48cb8918ad53ad494fed"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "392cd72a8697da7e0920665199d8e2e02bdbe4a9bf0a2c0ab1665076a0dd1a41",
|
||||
"imageId": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad",
|
||||
"authorizedBy": "\u7528\u62372026-10-25\u63a5\u624bA01\u8981\u6c42\u4fee\u590d\u3001\u68c0\u67e5\u3001\u6784\u5efa\u548c\u5df2\u6709\u6388\u6743\u8303\u56f4\u5185\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1792890160.296781
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "16f912c5538d125742a8da241d3c4801ad59281025b008d40bcc06c3116b895e",
|
||||
"imageId": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:2843fb1e51a5d2ef461b377570c9bfb5bc59253cb637907671fcbeea745eded1"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "a01-scheduling-20261025",
|
||||
"imageTag": "aixun-datagov/frontend:a01-scheduling-20261025",
|
||||
"imageId": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad",
|
||||
"artifactSha256": "c2e2de8aaae4b0b3efa5c5f4923b79ce0576b92dbef9b16b999e448537615035",
|
||||
"sourceContainerId": "392cd72a8697da7e0920665199d8e2e02bdbe4a9bf0a2c0ab1665076a0dd1a41",
|
||||
"sourceImageId": "sha256:2843fb1e51a5d2ef461b377570c9bfb5bc59253cb637907671fcbeea745eded1",
|
||||
"sourceImageTag": "sha256:2843fb1e51a5d2ef461b377570c9bfb5bc59253cb637907671fcbeea745eded1",
|
||||
"sourceStateSha256": "161217bfb96c622f88b6ee6681b9ddd0a7d9e77dcd15e42b672b3620dfec78e4",
|
||||
"modelSha256": "6ce793021044be776b9778a09142f21e3f74bff0ecda5de5a9e7b5d28291b31a",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "1278d5d258d286efbb55a0a1504d95e9eb0dd0484b86b9d741a686690de6d3a1",
|
||||
"imageId": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552",
|
||||
"authorizedBy": "\u7528\u6237\u63a5\u624bA01\u5e76\u8fde\u7eed\u5b8c\u6210\u7f3a\u9677\u4fee\u590d\u3001\u5fc5\u8981\u68c0\u67e5\u3001\u6784\u5efa\u53ca\u5df2\u6709\u8303\u56f4\u672c\u5730\u4ea4\u4ed8\uff1b\u8865\u9f50\u771f\u5b9e\u5143\u6570\u636e\u539f\u56de\u6267GET",
|
||||
"startedAt": 1792894977.7252638
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "governance",
|
||||
"containerId": "55c7d8dad6c958bb9d7f6cb1c1ffd4c1156da8015a4772758bf0932f9079f8a0",
|
||||
"imageId": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:70298555c8bd68386f519492ef50643349a01379e06faa6b8ca4ff69004ff3d6"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "governance",
|
||||
"release": "a01-scheduling-20261025",
|
||||
"imageTag": "aixun-datagov/governance:a01-scheduling-20261025",
|
||||
"imageId": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552",
|
||||
"artifactSha256": "8f685b2456cf280e3753d86ba6080e451fad0fd3e8a5a9678b7bbe79b6689cf3",
|
||||
"sourceContainerId": "1278d5d258d286efbb55a0a1504d95e9eb0dd0484b86b9d741a686690de6d3a1",
|
||||
"sourceImageId": "sha256:70298555c8bd68386f519492ef50643349a01379e06faa6b8ca4ff69004ff3d6",
|
||||
"sourceImageTag": "sha256:70298555c8bd68386f519492ef50643349a01379e06faa6b8ca4ff69004ff3d6",
|
||||
"sourceStateSha256": "fe38602c6ebf85cba1fef27c235c24f73928fbb67c0232f4325ab618db763e53",
|
||||
"modelSha256": "c6caf67b15a127da931199a2d78b09e2094baaf116f11983794ed3fda9d11610",
|
||||
"identitySha256": "bcb26c58b37350900feb90dcf1eea31ba93c9e1a471eb0139587ce3c45487e3e"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "b925a022af46ebe35db62da66088d9b7eda676dacb8ab16e0bf7dd5c24745075",
|
||||
"imageId": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393",
|
||||
"authorizedBy": "\u7528\u62372026-10-25\u63a5\u624bA01\u8981\u6c42\u4fee\u590d\u3001\u68c0\u67e5\u3001\u6784\u5efa\u548c\u5df2\u6709\u6388\u6743\u8303\u56f4\u5185\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1792890473.025255
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "integration",
|
||||
"containerId": "759d7bc729c0bcaf1ccdd8eed5bced57f495772c387e8a764d23978253faa9e6",
|
||||
"imageId": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:3b0e4114e7ad859911de8ced0be5a827d7e94b0e59fed1725e34ae5b6dd8b0ed"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "integration",
|
||||
"release": "a01-scheduling-20261025",
|
||||
"imageTag": "aixun-datagov/integration:a01-scheduling-20261025",
|
||||
"imageId": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393",
|
||||
"artifactSha256": "200604aaed809b742c25c19ed9def5f8babcb683657158e3a26921bc5f80cd1e",
|
||||
"sourceContainerId": "b925a022af46ebe35db62da66088d9b7eda676dacb8ab16e0bf7dd5c24745075",
|
||||
"sourceImageId": "sha256:3b0e4114e7ad859911de8ced0be5a827d7e94b0e59fed1725e34ae5b6dd8b0ed",
|
||||
"sourceImageTag": "sha256:3b0e4114e7ad859911de8ced0be5a827d7e94b0e59fed1725e34ae5b6dd8b0ed",
|
||||
"sourceStateSha256": "95c22ecc644c6cccb4bb318aa290f0a5dbb1e707f6709f0a3733713b13e82588",
|
||||
"modelSha256": "25855b2a930ec36693b369b680f490c8f477761a59113b411ce2c13f1c56dfd8",
|
||||
"identitySha256": "a816797f89c94de08c94837c25798b89fe092975a876fd0a8de5320ef5f70391"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "16f912c5538d125742a8da241d3c4801ad59281025b008d40bcc06c3116b895e",
|
||||
"imageId": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f",
|
||||
"authorizedBy": "\u7528\u6237\u63a5\u624bA01\u5e76\u8fde\u7eed\u5b8c\u6210\u7f3a\u9677\u4fee\u590d\u3001\u5fc5\u8981\u68c0\u67e5\u3001\u6784\u5efa\u53ca\u5df2\u6709\u8303\u56f4\u672c\u5730\u4ea4\u4ed8\uff1b\u672c\u6279\u8865\u9f50\u771f\u5b9e\u6cbb\u7406\u539f\u56de\u6267\u8bfb\u53d6",
|
||||
"startedAt": 1792894876.610795
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "e8c47eaac3aa551303569273abce398dd1e0dc469f69d0ebff1df14db338bc4a",
|
||||
"imageId": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "a01-scheduling-20261025-r2",
|
||||
"imageTag": "aixun-datagov/frontend:a01-scheduling-20261025-r2",
|
||||
"imageId": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f",
|
||||
"artifactSha256": "1106390c8b2aaad8c31fc7a9baa4c3470abda8bf159d64b64badc0e0370a2464",
|
||||
"sourceContainerId": "16f912c5538d125742a8da241d3c4801ad59281025b008d40bcc06c3116b895e",
|
||||
"sourceImageId": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad",
|
||||
"sourceImageTag": "sha256:9123575212f4168b393a7630b979e0c12f942517067ed4f850b7f764de4f3fad",
|
||||
"sourceStateSha256": "ba866d22fa30f060b3f13c840a04ee5c1dc885719fb8ec9b80f6a603b1b52218",
|
||||
"modelSha256": "a13af52e780b2f636fbb5ed34057fa18f154ea6a3d698068ba39298152b77f71",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "55c7d8dad6c958bb9d7f6cb1c1ffd4c1156da8015a4772758bf0932f9079f8a0",
|
||||
"imageId": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0",
|
||||
"authorizedBy": "\u7528\u6237\u7ee7\u7eed\u591a\u667a\u80fd\u4f53\u5b8c\u6210A01\uff1b\u4fee\u590d\u6807\u51c6\u6821\u9a8c\u53ef\u4fe1\u540e\u53f0\u8bfb\u53d6\u4e0e\u539f\u6743\u9650\u6838\u5bf9\uff0c\u6cbf\u5df2\u6709\u672c\u5730\u4ea4\u4ed8\u6388\u6743",
|
||||
"startedAt": 1792938042.0674372
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "governance",
|
||||
"containerId": "577bc9bee6b14a839dcf0299eb0a7fcf71ef904b51ca5ae94ccdf44816ce2cd7",
|
||||
"imageId": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "governance",
|
||||
"release": "a01-scheduling-20261025-r2",
|
||||
"imageTag": "aixun-datagov/governance:a01-scheduling-20261025-r2",
|
||||
"imageId": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0",
|
||||
"artifactSha256": "e9b34ff3331fd5840c5f48f045a091688a33c171027f043909f2d13b7dcb7f9d",
|
||||
"sourceContainerId": "55c7d8dad6c958bb9d7f6cb1c1ffd4c1156da8015a4772758bf0932f9079f8a0",
|
||||
"sourceImageId": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552",
|
||||
"sourceImageTag": "sha256:c7dc01ebed0fe7c9fd12b3e98e5425a9a48813e415139a5029a1307f35fa9552",
|
||||
"sourceStateSha256": "83fa07490b415aabcf1a9f89b8c097b6aa5232ae1ba4e62a771ff83e129496c7",
|
||||
"modelSha256": "1559029b0598a9492c84554fb9e4c499eaaaa7fe29de6f0a0d8dfde72838500d",
|
||||
"identitySha256": "bcb26c58b37350900feb90dcf1eea31ba93c9e1a471eb0139587ce3c45487e3e"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "759d7bc729c0bcaf1ccdd8eed5bced57f495772c387e8a764d23978253faa9e6",
|
||||
"imageId": "sha256:4f669ee6069490a45ce1d07d74358639ad84a4e13d18559563d6104e2bb29d45",
|
||||
"authorizedBy": "\u7528\u62372026-10-25\u63a5\u624bA01\u8fde\u7eed\u4fee\u590d\u53ca\u672c\u5730\u4ea4\u4ed8\uff1b\u771f\u5b9eDS\u5931\u8d25\u540e\u4fee\u590d\u56fa\u5b9a\u56de\u8c03\u8fd0\u884c\u914d\u7f6e\u8def\u5f84",
|
||||
"startedAt": 1792891616.9659572
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "integration",
|
||||
"containerId": "9d5f2c97a1e75bfcfafcf3b712b553a98ff761dc894b1dbce00d26167ed35bc4",
|
||||
"imageId": "sha256:4f669ee6069490a45ce1d07d74358639ad84a4e13d18559563d6104e2bb29d45",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "integration",
|
||||
"release": "a01-scheduling-20261025-r2",
|
||||
"imageTag": "aixun-datagov/integration:a01-scheduling-20261025-r2",
|
||||
"imageId": "sha256:4f669ee6069490a45ce1d07d74358639ad84a4e13d18559563d6104e2bb29d45",
|
||||
"artifactSha256": "a30dc8829abc4c064b0d49ab4d7ba3321db017c05026ba2d2fe32ba60cd62dee",
|
||||
"sourceContainerId": "759d7bc729c0bcaf1ccdd8eed5bced57f495772c387e8a764d23978253faa9e6",
|
||||
"sourceImageId": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393",
|
||||
"sourceImageTag": "sha256:d3b68142b0a5787b045b9c718f75fa9822e6c2a12efc2a0a835070b057302393",
|
||||
"sourceStateSha256": "dacfd51b32582d9470d4175ce3218a36e116cdbd2e85a4c06f7fec2ba579f834",
|
||||
"modelSha256": "36bab2220f0f7a3fbb72a765870edfaf4a6d49aa6859b625089ebece0e5ab36d",
|
||||
"identitySha256": "a816797f89c94de08c94837c25798b89fe092975a876fd0a8de5320ef5f70391"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "e8c47eaac3aa551303569273abce398dd1e0dc469f69d0ebff1df14db338bc4a",
|
||||
"imageId": "sha256:02f74a0eaca3d5f955f45369759ec4233a89e3195e684cda296a9d60f634e075",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u7ee7\u7eed\u8c03\u7528\u591a\u667a\u80fd\u4f53\u5feb\u901f\u5b8c\u6210A01\uff1b\u6cbf\u5df2\u6709\u672c\u5730\u4ea4\u4ed8\u6388\u6743\u8865\u9f50\u6807\u51c6\u6821\u9a8c\u53ca\u5206\u7c7b\u8bc6\u522b\u56de\u6267",
|
||||
"startedAt": 1792937104.845228
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "a303a08b20d83284ef994f7da6ccbdef2daa99be2f3715cdbae8638762a06bf2",
|
||||
"imageId": "sha256:02f74a0eaca3d5f955f45369759ec4233a89e3195e684cda296a9d60f634e075",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "a01-scheduling-20261025-r3",
|
||||
"imageTag": "aixun-datagov/frontend:a01-scheduling-20261025-r3",
|
||||
"imageId": "sha256:02f74a0eaca3d5f955f45369759ec4233a89e3195e684cda296a9d60f634e075",
|
||||
"artifactSha256": "187459b8a08030839b2d4741c4b722d8e31533153ad0aa600ed284686ac77f4c",
|
||||
"sourceContainerId": "e8c47eaac3aa551303569273abce398dd1e0dc469f69d0ebff1df14db338bc4a",
|
||||
"sourceImageId": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f",
|
||||
"sourceImageTag": "sha256:2d57a2d22642ad579a279538bb89c71f9779178bd34b0afa5eb4a66d0f7d662f",
|
||||
"sourceStateSha256": "e417ea29d5cbbffbfeee6413ad1e904dd2a01345c06ba8de9c00150a43c558fb",
|
||||
"modelSha256": "46ea6fe086df1b8fde3c51d0a9f6be05dfbee0168a7abb02be251e0e4622e5b2",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "577bc9bee6b14a839dcf0299eb0a7fcf71ef904b51ca5ae94ccdf44816ce2cd7",
|
||||
"imageId": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3",
|
||||
"authorizedBy": "\u7528\u6237\u7ee7\u7eed\u591a\u667a\u80fd\u4f53\u5b8c\u6210A01\uff1b\u8865\u6807\u51c6\u539f\u952e\u89c2\u5bdf\u5c01\u5b58\u548c\u9636\u6bb5\u7248\u672c\u8854\u63a5\uff0c\u6cbf\u5df2\u6709\u672c\u5730\u4ea4\u4ed8\u6388\u6743",
|
||||
"startedAt": 1792939145.58046
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "governance",
|
||||
"containerId": "a51aa518fe5132f0a86052a6c915ecbed135ae2561ea07969f476f9cf31f6daf",
|
||||
"imageId": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "governance",
|
||||
"release": "a01-scheduling-20261025-r3",
|
||||
"imageTag": "aixun-datagov/governance:a01-scheduling-20261025-r3",
|
||||
"imageId": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3",
|
||||
"artifactSha256": "38781b4dee83056c7cdd7ea34f19bc1b1214bc2f9fc74af24888e1a325afce91",
|
||||
"sourceContainerId": "577bc9bee6b14a839dcf0299eb0a7fcf71ef904b51ca5ae94ccdf44816ce2cd7",
|
||||
"sourceImageId": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0",
|
||||
"sourceImageTag": "sha256:790baa9af48d9d10e9ccbd87d8462a48ec0b08ffe546a1a6a45ea0cf49512bd0",
|
||||
"sourceStateSha256": "9851a04c9e072dcc831b8e7cafc0e3c0a17e6b8f22fac6b5027e390df0131258",
|
||||
"modelSha256": "463aa6c2c61a9c68580b76e4a46096a0742a44183cf5ed5b4341fb9e9876bf20",
|
||||
"identitySha256": "bcb26c58b37350900feb90dcf1eea31ba93c9e1a471eb0139587ce3c45487e3e"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "a51aa518fe5132f0a86052a6c915ecbed135ae2561ea07969f476f9cf31f6daf",
|
||||
"imageId": "sha256:0390611a4de6c65fbf8d53fa1ac3d657d5a5a786be464ed0463e357e6de2d188",
|
||||
"authorizedBy": "\u7528\u6237\u7ee7\u7eed\u591a\u667a\u80fd\u4f53\u5b8c\u6210A01\uff1b\u6807\u51c6\u8bc1\u636e\u7248\u672c\u6570\u503c\u6bd4\u8f83\u6700\u5c0f\u4fee\u590d\uff0c\u6cbf\u5df2\u6709\u672c\u5730\u4ea4\u4ed8\u6388\u6743",
|
||||
"startedAt": 1792939523.6881878
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "governance",
|
||||
"containerId": "4799f1230e24a26e9ccd593591ca6df593dcf96b07d0eecf50f270d474bfacad",
|
||||
"imageId": "sha256:0390611a4de6c65fbf8d53fa1ac3d657d5a5a786be464ed0463e357e6de2d188",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "governance",
|
||||
"release": "a01-scheduling-20261025-r4",
|
||||
"imageTag": "aixun-datagov/governance:a01-scheduling-20261025-r4",
|
||||
"imageId": "sha256:0390611a4de6c65fbf8d53fa1ac3d657d5a5a786be464ed0463e357e6de2d188",
|
||||
"artifactSha256": "3213c8f064094655f80375e409b50640daf73fb10921a587b81c919f849e37b9",
|
||||
"sourceContainerId": "a51aa518fe5132f0a86052a6c915ecbed135ae2561ea07969f476f9cf31f6daf",
|
||||
"sourceImageId": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3",
|
||||
"sourceImageTag": "sha256:647a85d9a135bd39f7af5dd17daead9aedf0dc2e4e1758d633c72eae516e2ee3",
|
||||
"sourceStateSha256": "d174f4fa60777f1efc9d803a71d30c584dcca2bb6b08fbe12611cf89e8f95cbb",
|
||||
"modelSha256": "21348f4899d404d94f83091519897328c15dfcf4e144729a665469086509fdf3",
|
||||
"identitySha256": "bcb26c58b37350900feb90dcf1eea31ba93c9e1a471eb0139587ce3c45487e3e"
|
||||
}
|
||||
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
在新工单中引用
屏蔽一个用户