Files
zyt/identity-admin/.test-runtime/production-x/activate_remote.py
T
2026-11-11 14:22:02 +08:00

138 lines
6.5 KiB
Python

import os,sys,json,hashlib,shutil,subprocess,time,pwd,grp
ROOT='/www/wwwroot/x.zhenyangtang.com.cn'
SOURCE='/www/wwwroot/zyt/server'
CERT=os.path.realpath(sys.argv[1])
assert CERT.startswith('/www/server/panel/vhost/')
assert os.path.isfile(CERT+'/fullchain.pem') and os.path.isfile(CERT+'/privkey.pem')
# Provision the dedicated FPM pools before activation; never send pool-changing
# PHP_ADMIN_VALUE parameters to BaoTa's shared PHP workers.
assert os.path.exists('/tmp/x-identity-group-82.sock') and os.path.exists('/tmp/x-identity-source-82.sock')
NGINX='/www/server/nginx/sbin/nginx'
def run(args):
result=subprocess.run(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
assert result.returncode==0,result.stderr[:900]
return result.stdout
def sha(path):
with open(path,'rb') as f:return hashlib.sha256(f.read()).hexdigest()
run([NGINX,'-t'])
manifest=json.load(open(ROOT+'/incoming/source-overlay/overlay-manifest.json'))
for item in manifest['files']:
target=SOURCE+'/'+item['path']
assert (sha(target) if os.path.exists(target) else None)==item['production_sha256'],'source changed: '+item['path']
assert sha(ROOT+'/incoming/source-overlay/'+item['path'])==item['overlay_sha256']
backup=ROOT+'/backups/activation-'+time.strftime('%Y%m%d-%H%M%S')
os.makedirs(backup,mode=0o700)
for item in manifest['files']:
target=SOURCE+'/'+item['path']
if os.path.exists(target):
saved=backup+'/original/'+item['path'];os.makedirs(os.path.dirname(saved),exist_ok=True);shutil.copy2(target,saved)
site='/www/server/panel/vhost/nginx/x.zhenyangtang.com.cn.conf'
source_site='/www/server/panel/vhost/nginx/x-identity-source-internal.conf'
extension='/www/server/panel/vhost/nginx/extension/admin.zhenyangtang.com.cn/group-identity-x.conf'
assert os.path.isfile(site) and not os.path.exists(source_site) and not os.path.exists(extension)
shutil.copy2(site,backup+'/x-site-before.conf')
web=ROOT+'/current/web/dist'
api=ROOT+'/current/server/public/index.php'
runtime=ROOT+'/current/server/runtime'
if not os.path.lexists(runtime):os.symlink(ROOT+'/shared/runtime',runtime)
nginx='''server {
listen 80;
server_name x.zhenyangtang.com.cn;
root @WEB@;
location ^~ /.well-known/acme-challenge/ { try_files $uri =404; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 443 ssl;
server_name x.zhenyangtang.com.cn;
root @WEB@;
index index.html;
ssl_certificate @CERT@/fullchain.pem;
ssl_certificate_key @CERT@/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:x_identity_tls:1m;
client_max_body_size 1m;
access_log /www/wwwlogs/x.zhenyangtang.com.cn.log;
error_log /www/wwwlogs/x.zhenyangtang.com.cn.error.log;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
location ^~ /.well-known/acme-challenge/ { try_files $uri =404; }
location ^~ /adminapi/ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME @API@;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param PATH_INFO $uri;
fastcgi_param HTTPS on;
fastcgi_param HTTP_AUTHORIZATION $http_authorization;
fastcgi_param HTTP_X_COMPANY_ID $http_x_company_id;
fastcgi_param HTTP_PROXY "";
fastcgi_pass unix:/tmp/x-identity-group-82.sock;
}
location ~ /\. { deny all; }
location ~ ^/(server|shared|releases|vendor|runtime|integration|incoming|backups)(/|$) { return 404; }
location ~ \.php(/|$) { return 404; }
# PHP-INFO-START: API above uses the same PHP 8.2 pool.
include enable-php-82.conf;
# PHP-INFO-END
location /assets/ { try_files $uri =404; expires 1y; add_header Cache-Control "public, immutable"; }
location / { try_files $uri $uri/ /index.html; add_header Cache-Control no-cache; }
}
'''.replace('@WEB@',web).replace('@CERT@',CERT).replace('@API@',api).replace('@ROOT@',ROOT)
private='''server {
listen 127.0.0.1:8082;
server_name 127.0.0.1;
root /www/wwwroot/zyt/server/public;
access_log /www/wwwlogs/x-identity-source.log;
error_log /www/wwwlogs/x-identity-source.error.log;
location / {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME @ROOT@/current/server/scripts/project-api-router.php;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param PATH_INFO $uri;
fastcgi_param IAM_SOURCE_PROJECT_ROOT /www/wwwroot/zyt/server;
fastcgi_param HTTP_HOST admin.zhenyangtang.com.cn;
fastcgi_param HTTPS on;
fastcgi_param HTTP_PROXY "";
fastcgi_pass unix:/tmp/x-identity-source-82.sock;
}
}
'''.replace('@ROOT@',ROOT)
hospital='''location = /admin/group-login {
alias @ROOT@/current/hospital/group-login.html;
default_type text/html;
add_header Cache-Control no-store always;
add_header Referrer-Policy no-referrer always;
access_log off;
}
location = /admin/group-sso.mjs {
alias @ROOT@/current/hospital/group-sso.mjs;
default_type application/javascript;
add_header Cache-Control no-cache;
}
'''.replace('@ROOT@',ROOT)
for path,content in ((site,nginx),(source_site,private),(extension,hospital)):
os.makedirs(os.path.dirname(path),exist_ok=True)
with open(path+'.x-staged','w') as f:f.write(content)
os.replace(path+'.x-staged',path)
try:run([NGINX,'-t'])
except Exception:
shutil.copy2(backup+'/x-site-before.conf',site)
os.remove(source_site);os.remove(extension)
raise
www=pwd.getpwnam('www').pw_uid;gid=grp.getgrnam('www').gr_gid
priority={'AdminTerminalEnum.php':0,'AdminTokenCache.php':1,'AdminAuthCache.php':2,'AdminTokenService.php':3,'OperationLog.php':4,'AuthMiddleware.php':99}
items=sorted(manifest['files'],key=lambda i:(i['production_sha256'] is not None,priority.get(os.path.basename(i['path']),10)))
for item in items:
target=SOURCE+'/'+item['path'];os.makedirs(os.path.dirname(target),exist_ok=True)
temporary=target+'.group-x-staged'
assert not os.path.exists(temporary)
shutil.copyfile(ROOT+'/incoming/source-overlay/'+item['path'],temporary)
os.chmod(temporary,0o644);os.chown(temporary,www,gid)
os.replace(temporary,target)
assert sha(target)==item['overlay_sha256']
run([NGINX,'-t']);run([NGINX,'-s','reload'])
state={'ok':True,'backup':backup,'source_files':len(items),'new_site':site,'private_source':source_site,'hospital_extension':extension,'group_runtime':ROOT+'/shared/runtime','certificate_dir':CERT,'kf_changed':False}
with open(ROOT+'/shared/deployment-state.json','w') as f:json.dump(state,f,indent=2)
os.chmod(ROOT+'/shared/deployment-state.json',0o600)
print(json.dumps(state))