更新
This commit is contained in:
@@ -2,6 +2,9 @@
|
||||
APP_DOMAIN=app.example.com
|
||||
ADMIN_DOMAIN=admin.example.com
|
||||
API_DOMAIN=api.example.com
|
||||
# Keep /admin/v1 for same-origin reverse proxy, or use
|
||||
# https://api.example.com/admin/v1 for a separate API origin.
|
||||
ADMIN_API_URL=/admin/v1
|
||||
|
||||
MYSQL_DATABASE=im
|
||||
MYSQL_USER=xingyu_app
|
||||
|
||||
@@ -12,6 +12,8 @@ RUN npm run build:h5
|
||||
FROM node:22-alpine AS admin-builder
|
||||
WORKDIR /src/admin
|
||||
ENV CI=true
|
||||
ARG VITE_ADMIN_API_URL=/admin/v1
|
||||
ENV VITE_GLOB_API_URL=${VITE_ADMIN_API_URL}
|
||||
RUN corepack enable
|
||||
COPY admin/package.json admin/pnpm-lock.yaml admin/pnpm-workspace.yaml ./
|
||||
COPY admin/.npmrc ./
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
umask 0027
|
||||
|
||||
# BaoTa sends SIGTERM and immediately starts the replacement. go-zero drains
|
||||
# existing connections asynchronously, so wait for the old listener to close.
|
||||
for attempt in $(seq 1 120); do
|
||||
if ! /usr/sbin/ss -H -ltn 'sport = :18888' | /usr/bin/grep -q .; then
|
||||
exec /www/server/xingyu-im/bt/xingyu-api
|
||||
fi
|
||||
sleep 0.25
|
||||
done
|
||||
printf '%s\n' 'Cannot start Xingyu: local port 18888 is still occupied after 30 seconds.' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env bash
|
||||
# Publish the admin build without restarting Go or changing BaoTa/Nginx routes.
|
||||
set -euo pipefail
|
||||
umask 0022
|
||||
|
||||
archive=$(realpath -- "${1:?Usage: baota-publish-admin.sh /tmp/build.zip SHA256}")
|
||||
expected=${2:?Missing archive SHA256}
|
||||
[[ $EUID -eq 0 && $archive == /tmp/*.zip && -f $archive ]]
|
||||
[[ $expected =~ ^[a-fA-F0-9]{64}$ ]]
|
||||
[[ $(sha256sum "$archive" | cut -d ' ' -f 1) == "${expected,,}" ]]
|
||||
|
||||
root=/www/wwwroot/im.bchongw.com
|
||||
releases=/www/wwwroot/xingyu-admin/releases
|
||||
entry=$root/admin
|
||||
[[ -L $entry ]]
|
||||
previous=$(readlink -f -- "$entry")
|
||||
[[ $previous == "$releases/"* && -f $previous/index.html ]]
|
||||
[[ -f /www/server/panel/vhost/nginx/go_xingyu_im.conf ]]
|
||||
/www/server/nginx/sbin/nginx -t
|
||||
|
||||
# Accept only relative archive paths. The ZIP is built locally and SHA-256
|
||||
# checked above; reject path traversal before extracting into a new version.
|
||||
while IFS= read -r item; do
|
||||
case "$item" in
|
||||
/*|*\\*|../*|*/../*|*/..|..|*:*) exit 1 ;;
|
||||
esac
|
||||
done < <(unzip -Z1 "$archive")
|
||||
|
||||
version=$(date +%Y%m%d-%H%M%S)
|
||||
release=$releases/$version
|
||||
next=$root/admin.next-$version
|
||||
[[ ! -e $next && ! -L $next ]]
|
||||
mkdir -m 0755 -- "$release"
|
||||
unzip -q "$archive" -d "$release"
|
||||
[[ -f $release/index.html && -f $release/_app.config.js ]]
|
||||
grep -q '/admin/jse/' "$release/index.html"
|
||||
grep -q '"/admin/v1"' "$release/_app.config.js"
|
||||
|
||||
# Keep the previous hashed chunks reachable for tabs opened before deployment.
|
||||
# Never overwrite files in the new build or copy the old HTML/runtime config.
|
||||
for directory in js jse css; do
|
||||
[[ -d $release/$directory && -d $previous/$directory ]]
|
||||
cp -an -- "$previous/$directory/." "$release/$directory/"
|
||||
done
|
||||
chown -R www:www -- "$release"
|
||||
find "$release" -type d -exec chmod 0755 {} +
|
||||
find "$release" -type f -exec chmod 0644 {} +
|
||||
|
||||
switched=false
|
||||
rollback() {
|
||||
if [[ $switched == true ]]; then
|
||||
ln -s -- "$previous" "$next"
|
||||
mv -Tf -- "$next" "$entry"
|
||||
printf 'ROLLED_BACK=%s\n' "$previous" >&2
|
||||
fi
|
||||
}
|
||||
trap rollback ERR
|
||||
ln -s -- "$release" "$next"
|
||||
mv -Tf -- "$next" "$entry"
|
||||
switched=true
|
||||
|
||||
cmp -s "$release/index.html" <(curl -fsS --max-time 20 "https://im.bchongw.com/admin/?release=$version")
|
||||
cmp -s "$release/_app.config.js" <(curl -fsS --max-time 20 "https://im.bchongw.com/admin/_app.config.js?release=$version")
|
||||
curl -fsS --max-time 20 https://im.bchongw.com/healthz
|
||||
curl -fsS --max-time 20 -o /dev/null https://im.bchongw.com/app/
|
||||
trap - ERR
|
||||
printf '\nADMIN_PUBLISHED=%s\nPREVIOUS_RELEASE=%s\nARCHIVE_SHA256=%s\n' "$release" "$previous" "${expected,,}"
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move this site's domain and HTTPS gateway into its actual BaoTa Go project.
|
||||
|
||||
This migrates only panel metadata/configuration. It never deletes site files,
|
||||
restarts the Go process, or touches the application's MySQL database.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PANEL = Path('/www/server/panel')
|
||||
DOMAIN = 'im.bchongw.com'
|
||||
PROJECT = 'xingyu_im'
|
||||
OLD_CONF = PANEL / 'vhost/nginx/html_im.bchongw.com.conf'
|
||||
GO_CONF = PANEL / 'vhost/nginx/go_xingyu_im.conf'
|
||||
ROUTES = PANEL / 'vhost/nginx/extension/xingyu_im/xingyu_routes.conf'
|
||||
CERT = PANEL / 'vhost/cert/xingyu_im'
|
||||
SITE_DB = PANEL / 'data/db/site.db'
|
||||
|
||||
|
||||
def run(*args):
|
||||
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError('{} failed: {}'.format(args[0], result.stderr.strip()))
|
||||
|
||||
|
||||
def write_private(path, text, mode=0o600):
|
||||
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as target:
|
||||
target.write(text)
|
||||
|
||||
|
||||
def check_public():
|
||||
for path, content in (('/healthz', '"status":"ok"'), ('/admin/', '星遇社交运营中心'),
|
||||
('/app/', '星遇社交'), ('/app/static/favicon.svg', '<svg')):
|
||||
for attempt in range(20):
|
||||
try:
|
||||
with urllib.request.urlopen('https://' + DOMAIN + path, timeout=5) as response:
|
||||
assert response.status == 200
|
||||
assert content in response.read().decode('utf-8')
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 19:
|
||||
raise RuntimeError('Public verification failed: ' + path)
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def verify():
|
||||
model = GoProject()
|
||||
get = public.dict_obj()
|
||||
get.project_name = PROJECT
|
||||
project = model.get_project_find(PROJECT)
|
||||
domains = model.project_get_domain(get)
|
||||
assert any(item['name'] == DOMAIN and int(item['port']) == 80 for item in domains)
|
||||
assert int(project['project_config']['bind_extranet']) == 1
|
||||
assert model.get_project_run_state(project_name=PROJECT)
|
||||
ssl_info = model.get_ssl_end_date(PROJECT)
|
||||
assert isinstance(ssl_info, dict) and DOMAIN in ssl_info.get('dns', [])
|
||||
ssl_get = public.dict_obj()
|
||||
ssl_get.siteName = PROJECT
|
||||
ssl_state = panelSite.panelSite().GetSSL(ssl_get)
|
||||
assert ssl_state['status'] and ssl_state['httpTohttps']
|
||||
assert ROUTES.is_file() and str(ROUTES.parent) in GO_CONF.read_text()
|
||||
check_public()
|
||||
print(json.dumps({
|
||||
'project': PROJECT, 'domains': [{'name': d['name'], 'port': d['port']} for d in domains],
|
||||
'external_mapping': True, 'running': True, 'ssl_enabled': ssl_state['status'],
|
||||
'force_https': ssl_state['httpTohttps'], 'certificate_expires': ssl_info['notAfter'],
|
||||
'nginx_config': str(GO_CONF), 'routes_config': str(ROUTES),
|
||||
}, ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
def migrate():
|
||||
model = GoProject()
|
||||
project = model.get_project_find(PROJECT)
|
||||
assert project and not project['project_config']['domains']
|
||||
assert OLD_CONF.is_file() and not GO_CONF.exists() and not ROUTES.exists() and not CERT.exists()
|
||||
html_site = public.M('sites').where('name=? AND project_type=?', (DOMAIN, 'html')).find()
|
||||
assert html_site and html_site['path'] == '/www/wwwroot/im.bchongw.com'
|
||||
domain_rows = public.M('domain').where('name=?', (DOMAIN,)).select()
|
||||
assert len(domain_rows) == 1 and domain_rows[0]['pid'] == html_site['id'] and int(domain_rows[0]['port']) == 80
|
||||
assert public.M('domain').where('pid=?', (html_site['id'],)).count() == 1
|
||||
check_public()
|
||||
backup = Path('/www/backup/xingyu-go-domain-' + time.strftime('%Y%m%d-%H%M%S'))
|
||||
backup.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
os.chmod(str(backup), 0o700)
|
||||
shutil.copy2(str(OLD_CONF), str(backup / OLD_CONF.name))
|
||||
with sqlite3.connect(str(SITE_DB)) as db:
|
||||
with sqlite3.connect(str(backup / 'site.db')) as out:
|
||||
db.backup(out)
|
||||
original_go = public.M('sites').where('id=?', (project['id'],)).find()
|
||||
write_private(backup / 'original-records.json', json.dumps({
|
||||
'html_site': html_site, 'go_site': original_go, 'domains': domain_rows,
|
||||
}, ensure_ascii=False))
|
||||
|
||||
# Custom routes live in BaoTa's supported per-project extension directory;
|
||||
# saving/rebuilding the Go project's main Nginx file retains this include.
|
||||
old_text = OLD_CONF.read_text()
|
||||
start = old_text.index(' # XINGYU_H5_START')
|
||||
end = old_text.index('\n location / {', start)
|
||||
routes = '''# Xingyu frontend routes and WebSocket gateway. Keep in this extension.
|
||||
server_tokens off;
|
||||
client_max_body_size 16m;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
default_type text/plain;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
''' + old_text[start:end] + '\n'
|
||||
ROUTES.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_private(ROUTES, routes, 0o644)
|
||||
CERT.mkdir(mode=0o700)
|
||||
for filename in ('fullchain.pem', 'privkey.pem'):
|
||||
source = Path('/etc/letsencrypt/live') / DOMAIN / filename
|
||||
assert source.is_file()
|
||||
os.symlink(str(source), str(CERT / filename))
|
||||
rewrite = PANEL / 'vhost/rewrite/go_xingyu_im.conf'
|
||||
if not rewrite.exists():
|
||||
write_private(rewrite, '# Project-specific rewrite rules; frontend routes are in the extension directory.\n', 0o644)
|
||||
well_known = PANEL / 'vhost/nginx/well-known/xingyu_im.conf'
|
||||
if not well_known.exists():
|
||||
write_private(well_known, '# ACME routes are in extension/xingyu_im/xingyu_routes.conf.\n', 0o644)
|
||||
|
||||
ssl = '''ssl_certificate /www/server/panel/vhost/cert/xingyu_im/fullchain.pem;
|
||||
ssl_certificate_key /www/server/panel/vhost/cert/xingyu_im/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_session_cache shared:IMSSL:10m;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_tickets off;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
error_page 497 https://$host$request_uri;
|
||||
#HTTP_TO_HTTPS_START
|
||||
if ($server_port !~ 443) {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
#HTTP_TO_HTTPS_END'''
|
||||
template = (PANEL / 'vhost/template/nginx/go_http.conf').read_text()
|
||||
body = template.format(
|
||||
listen_ports='listen 80;\n listen 443 ssl;\n http2 on;', domains=DOMAIN,
|
||||
site_path=project['path'], project_name=PROJECT, panel_path=str(PANEL),
|
||||
log_path='/www/wwwlogs', url='http://127.0.0.1:18888', host='$host', ssl_config=ssl,
|
||||
)
|
||||
body = body.replace('proxy_set_header X-Scheme $scheme;',
|
||||
'proxy_set_header X-Scheme $scheme;\n proxy_set_header X-Forwarded-Proto $scheme;')
|
||||
from mod.base.web_conf import ng_ext
|
||||
body = ng_ext.set_extension_by_config(PROJECT, body)
|
||||
stage = GO_CONF.with_name(GO_CONF.name + '.prepared')
|
||||
write_private(stage, body, 0o644)
|
||||
metadata_changed = False
|
||||
files_switched = False
|
||||
try:
|
||||
os.rename(str(OLD_CONF), str(backup / 'original-html-active.conf'))
|
||||
files_switched = True
|
||||
os.rename(str(stage), str(GO_CONF))
|
||||
run('/www/server/nginx/sbin/nginx', '-t')
|
||||
new_config = dict(project['project_config'])
|
||||
new_config['domains'] = [DOMAIN + ':80']
|
||||
new_config['bind_extranet'] = 1
|
||||
with sqlite3.connect(str(SITE_DB), timeout=10) as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
assert db.execute('SELECT pid FROM domain WHERE id=?', (domain_rows[0]['id'],)).fetchone()[0] == html_site['id']
|
||||
db.execute('UPDATE domain SET pid=? WHERE id=? AND pid=?',
|
||||
(project['id'], domain_rows[0]['id'], html_site['id']))
|
||||
db.execute('UPDATE sites SET project_config=?, ps=? WHERE id=? AND project_type=?',
|
||||
(json.dumps(new_config), '星遇 IM · im.bchongw.com · 管理端 /admin/ · H5 /app/', project['id'], 'Go'))
|
||||
# Merge the now-redundant HTML project record only. All its files,
|
||||
# release symlinks, certificate links, and backups remain intact.
|
||||
db.execute('DELETE FROM sites WHERE id=? AND name=? AND project_type=?',
|
||||
(html_site['id'], DOMAIN, 'html'))
|
||||
metadata_changed = True
|
||||
run('/etc/init.d/nginx', 'reload')
|
||||
verify()
|
||||
public.WriteLog('项目管理', '域名 im.bchongw.com、HTTPS、管理端和 H5 网关已合并至 Go 项目 xingyu_im;备份:' + str(backup))
|
||||
print('DOMAIN_MIGRATION_BACKUP=' + str(backup), flush=True)
|
||||
except Exception:
|
||||
if metadata_changed:
|
||||
with sqlite3.connect(str(SITE_DB), timeout=10) as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
db.execute('UPDATE domain SET pid=? WHERE id=?', (html_site['id'], domain_rows[0]['id']))
|
||||
db.execute('UPDATE sites SET project_config=?, ps=? WHERE id=?',
|
||||
(original_go['project_config'], original_go['ps'], project['id']))
|
||||
keys = list(html_site)
|
||||
db.execute('INSERT INTO sites ({}) VALUES ({})'.format(','.join(keys), ','.join('?' for _ in keys)),
|
||||
[html_site[k] for k in keys])
|
||||
if files_switched:
|
||||
if GO_CONF.exists():
|
||||
os.rename(str(GO_CONF), str(backup / 'failed-go.conf'))
|
||||
os.rename(str(backup / 'original-html-active.conf'), str(OLD_CONF))
|
||||
run('/www/server/nginx/sbin/nginx', '-t')
|
||||
run('/etc/init.d/nginx', 'reload')
|
||||
print('ROLLED_BACK; backup=' + str(backup), flush=True)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
assert os.geteuid() == 0 and PANEL.is_dir()
|
||||
os.chdir(str(PANEL))
|
||||
sys.path.insert(0, str(PANEL))
|
||||
sys.path.insert(0, str(PANEL / 'class'))
|
||||
import public
|
||||
import panelSite
|
||||
from projectModel.goModel import main as GoProject
|
||||
action = sys.argv[1] if len(sys.argv) > 1 else 'verify'
|
||||
if action not in ('migrate', 'verify'):
|
||||
raise SystemExit('Usage: baota_bind_go_domain.py [migrate|verify]')
|
||||
{'migrate': migrate, 'verify': verify}[action]()
|
||||
@@ -0,0 +1,235 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-time, reversible takeover by the installed BaoTa project manager.
|
||||
|
||||
Run as root using /www/server/panel/pyenv/bin/python on the target host.
|
||||
Secrets are read only on the server and are never printed.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shlex
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PANEL = Path('/www/server/panel')
|
||||
NAME = 'xingyu_im'
|
||||
DOMAIN = 'im.bchongw.com'
|
||||
EXECUTABLE = Path('/www/server/xingyu-im/bt/xingyu-api')
|
||||
ENV_FILE = Path('/etc/xingyu-im-bt.env')
|
||||
OLD_NGINX = PANEL / 'vhost/nginx/im.bchongw.com.conf'
|
||||
HTML_NGINX = PANEL / 'vhost/nginx/html_im.bchongw.com.conf'
|
||||
GO_NGINX = PANEL / 'vhost/nginx/go_xingyu_im.conf'
|
||||
|
||||
|
||||
def command(*args):
|
||||
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError('Command failed: {}: {}'.format(args[0], result.stderr.strip()))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def atomic_write(path, content, mode=0o600):
|
||||
temporary = path.with_name(path.name + '.takeover-new')
|
||||
descriptor = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as target:
|
||||
target.write(content)
|
||||
os.replace(str(temporary), str(path))
|
||||
|
||||
|
||||
def env_values():
|
||||
values = {}
|
||||
for line in Path('/etc/xingyu-im.env').read_text().splitlines():
|
||||
if not line.strip() or line.lstrip().startswith('#'):
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
parts = shlex.split(value)
|
||||
if len(parts) > 1:
|
||||
raise RuntimeError('Unexpected environment syntax for ' + key)
|
||||
values[key] = parts[0] if parts else ''
|
||||
assert values['IM_HOST'] == '127.0.0.1'
|
||||
assert values['IM_PORT'] == '18888'
|
||||
assert values['IM_ENV'] == 'production'
|
||||
return values
|
||||
|
||||
|
||||
def health(url='http://127.0.0.1:18888/healthz'):
|
||||
for _ in range(140):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as response:
|
||||
data = json.load(response)
|
||||
if data.get('code') == 0 and data.get('data', {}).get('status') == 'ok':
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError('Health check failed: ' + url)
|
||||
|
||||
|
||||
def request(**values):
|
||||
obj = public.dict_obj()
|
||||
for key, value in values.items():
|
||||
setattr(obj, key, value)
|
||||
return obj
|
||||
|
||||
|
||||
def status():
|
||||
go = GoProject()
|
||||
project = go.get_project_find(NAME)
|
||||
domain = public.M('domain').where('name=? AND port=?', (DOMAIN, 80)).find()
|
||||
site = public.M('sites').where('id=?', (domain['pid'],)).find() if domain else {}
|
||||
print(json.dumps({
|
||||
'go_project': NAME if project else None,
|
||||
'running': go.get_project_run_state(project_name=NAME) if project else False,
|
||||
'auto_start': project['project_config']['is_power_on'] if project else None,
|
||||
'environment_file': project['project_config']['env_file'] if project else None,
|
||||
'web_project_type': site.get('project_type'),
|
||||
'web_project_name': site.get('name'),
|
||||
'web_root': site.get('path'),
|
||||
'domains': project['project_config']['domains'] if project else [],
|
||||
'external_mapping': bool(project['project_config']['bind_extranet']) if project else False,
|
||||
'gateway_nginx_config': str(GO_NGINX if GO_NGINX.is_file() else HTML_NGINX),
|
||||
}, ensure_ascii=False))
|
||||
|
||||
|
||||
def takeover():
|
||||
go = GoProject()
|
||||
if go.get_project_find(NAME):
|
||||
raise RuntimeError('The BaoTa project already exists; use status/verify instead.')
|
||||
site = public.M('sites').where('name=?', (DOMAIN,)).find()
|
||||
assert site and site['project_type'] == 'PHP'
|
||||
assert site['path'] == '/www/wwwroot/im.bchongw.com'
|
||||
assert OLD_NGINX.is_file() and not HTML_NGINX.exists()
|
||||
assert not EXECUTABLE.parent.exists() and not ENV_FILE.exists()
|
||||
health()
|
||||
values = env_values()
|
||||
backup = Path('/www/backup/xingyu-panel-takeover-' + time.strftime('%Y%m%d-%H%M%S'))
|
||||
backup.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
os.chmod(str(backup), 0o700)
|
||||
for source in (OLD_NGINX, Path('/etc/systemd/system/xingyu-im.service'), Path('/etc/xingyu-im.env')):
|
||||
shutil.copy2(str(source), str(backup / source.name))
|
||||
for source in (PANEL / 'data/db/site.db', PANEL / 'data/default.db'):
|
||||
with sqlite3.connect(str(source)) as connection:
|
||||
with sqlite3.connect(str(backup / source.name)) as destination:
|
||||
connection.backup(destination)
|
||||
atomic_write(backup / 'original-site.json', json.dumps(site, ensure_ascii=False))
|
||||
shutil.copytree('/www/server/xingyu-im/current', str(EXECUTABLE.parent))
|
||||
launcher = Path(__file__).with_name('baota-go-start.sh')
|
||||
assert launcher.is_file(), 'Upload baota-go-start.sh alongside this script.'
|
||||
shutil.copy2(str(launcher), str(EXECUTABLE.parent / 'start.sh'))
|
||||
os.chmod(str(EXECUTABLE.parent / 'start.sh'), 0o750)
|
||||
original_hash = hashlib.sha256(Path('/www/server/xingyu-im/current/xingyu-api').read_bytes()).hexdigest()
|
||||
assert hashlib.sha256(EXECUTABLE.read_bytes()).hexdigest() == original_hash
|
||||
atomic_write(ENV_FILE, '# BaoTa Go project environment. Keep this file private.\n' + ''.join(
|
||||
'export {}={}\n'.format(key, shlex.quote(value)) for key, value in values.items()))
|
||||
os.chown(str(ENV_FILE), 0, pwd.getpwnam('www').pw_gid)
|
||||
os.chmod(str(ENV_FILE), 0o640)
|
||||
print('BACKUP=' + str(backup), flush=True)
|
||||
old_stopped = False
|
||||
site_changed = False
|
||||
try:
|
||||
command('systemctl', 'stop', 'xingyu-im')
|
||||
old_stopped = True
|
||||
result = go.create_project(request(
|
||||
project_name=NAME, project_exe=str(EXECUTABLE),
|
||||
project_ps='星遇 IM 后端 · im.bchongw.com · 内网 18888',
|
||||
bind_extranet=0, domains=[], is_power_on=1, run_user='www',
|
||||
project_cmd=str(EXECUTABLE.parent / 'start.sh'), port=18888,
|
||||
env_file=str(ENV_FILE), env_list=[], release_firewall=0,
|
||||
))
|
||||
if not result.get('status'):
|
||||
raise RuntimeError('BaoTa create_project failed: ' + str(result.get('msg')))
|
||||
health()
|
||||
assert go.get_project_run_state(project_name=NAME)
|
||||
os.rename(str(OLD_NGINX), str(HTML_NGINX))
|
||||
site_changed = True
|
||||
public.M('sites').where('id=? AND name=?', (site['id'], DOMAIN)).update({
|
||||
'project_type': 'html',
|
||||
'project_config': site.get('project_config') or '{}',
|
||||
'ps': '星遇管理端 /admin/ · IM HTTPS/WSS 网关',
|
||||
})
|
||||
command('/www/server/nginx/sbin/nginx', '-t')
|
||||
command('/etc/init.d/nginx', 'reload')
|
||||
health('https://im.bchongw.com/healthz')
|
||||
command('systemctl', 'disable', 'xingyu-im')
|
||||
public.WriteLog('项目管理', '星遇服务已由 systemd 接管至 Go 项目 xingyu_im;域名网页转为 HTML 项目;备份:' + str(backup))
|
||||
atomic_write(backup / 'result.json', json.dumps({
|
||||
'go_project': NAME, 'site_id': site['id'], 'executable_sha256': original_hash,
|
||||
'html_config': str(HTML_NGINX), 'previous_systemd': 'xingyu-im.service',
|
||||
}, ensure_ascii=False))
|
||||
print('TAKEOVER_OK', flush=True)
|
||||
status()
|
||||
except Exception:
|
||||
# Restore only this project's settings; never replace the full panel database.
|
||||
if site_changed:
|
||||
if HTML_NGINX.exists():
|
||||
os.rename(str(HTML_NGINX), str(OLD_NGINX))
|
||||
public.M('sites').where('id=?', (site['id'],)).update({
|
||||
'project_type': site['project_type'], 'project_config': site.get('project_config'), 'ps': site['ps'],
|
||||
})
|
||||
command('/www/server/nginx/sbin/nginx', '-t')
|
||||
command('/etc/init.d/nginx', 'reload')
|
||||
project = go.get_project_find(NAME)
|
||||
if project:
|
||||
if go.get_project_run_state(project_name=NAME):
|
||||
go.stop_project(request(project_name=NAME))
|
||||
time.sleep(1)
|
||||
config = project['project_config']
|
||||
config['is_power_on'] = 0
|
||||
public.M('sites').where('id=?', (project['id'],)).setField('project_config', json.dumps(config))
|
||||
if old_stopped:
|
||||
command('systemctl', 'enable', '--now', 'xingyu-im')
|
||||
health()
|
||||
print('ROLLED_BACK_TO_SYSTEMD; backup=' + str(backup), flush=True)
|
||||
raise
|
||||
|
||||
|
||||
def verify():
|
||||
go = GoProject()
|
||||
project = go.get_project_find(NAME)
|
||||
assert project and project['project_config']['is_power_on'] == 1
|
||||
before_pid = go.get_pid_by_command(NAME)
|
||||
result = go.restart_project(request(project_name=NAME))
|
||||
if not result.get('status'):
|
||||
time.sleep(2)
|
||||
recovered = go.start_project(request(project_name=NAME))
|
||||
health()
|
||||
raise RuntimeError('BaoTa restart failed; service recovery status: ' + str(recovered.get('status')))
|
||||
health()
|
||||
after_pid = go.get_pid_by_command(NAME)
|
||||
assert after_pid and after_pid != before_pid
|
||||
health('https://im.bchongw.com/healthz')
|
||||
domain = public.M('domain').where('name=? AND port=?', (DOMAIN, 80)).find()
|
||||
assert domain
|
||||
if project['project_config']['bind_extranet']:
|
||||
assert domain['pid'] == project['id'] and GO_NGINX.is_file()
|
||||
else:
|
||||
assert public.M('sites').where('id=?', (domain['pid'],)).getField('project_type') == 'html'
|
||||
assert command('systemctl', 'is-active', 'xingyu-mysql8') == 'active'
|
||||
old = subprocess.run(['systemctl', 'is-active', 'xingyu-im'], stdout=subprocess.PIPE, universal_newlines=True)
|
||||
assert old.stdout.strip() == 'inactive'
|
||||
with urllib.request.urlopen('https://im.bchongw.com/admin/', timeout=10) as response:
|
||||
assert '星遇社交运营中心' in response.read().decode('utf-8')
|
||||
data = go.get_project_list(request(p=1, limit=20, search=NAME))
|
||||
assert any(row['name'] == NAME and row['run'] for row in data['data'])
|
||||
print('PANEL_RESTART_OK; PUBLIC_API_OK; ADMIN_WEB_OK; MYSQL_UNCHANGED; GO_LIST_RUNNING', flush=True)
|
||||
status()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('status', 'takeover', 'verify'))
|
||||
args = parser.parse_args()
|
||||
if os.geteuid() != 0 or not PANEL.is_dir():
|
||||
raise SystemExit('Run on the BaoTa host as root.')
|
||||
os.chdir(str(PANEL))
|
||||
sys.path.insert(0, str(PANEL))
|
||||
sys.path.insert(0, str(PANEL / 'class'))
|
||||
import public
|
||||
from projectModel.goModel import main as GoProject
|
||||
{'status': status, 'takeover': takeover, 'verify': verify}[args.action]()
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish this reviewed application release on the existing BaoTa host.
|
||||
|
||||
Uses the installed, previously verified transport/filesystem helpers. Never
|
||||
seeds data, changes credentials, enables OAuth channels, or restores a live DB.
|
||||
"""
|
||||
import fcntl
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, WEB, database, digest, env_values, extract, fetch, health, query, restart, switch
|
||||
|
||||
EXPECTED_OLD = '92b306000ab787e2eb20e69daf25cc3374d082a88f7301e24811a2b7d0022d9d'
|
||||
MIGRATIONS = ['027_app_oauth_login.sql', '029_admin_create_users.sql']
|
||||
|
||||
|
||||
def marker(conn):
|
||||
# Fingerprints only; configuration values and personal records never leave
|
||||
# this process or appear in deployment logs.
|
||||
configs = query(conn, "SELECT config_key,config_value FROM system_configs WHERE config_key NOT LIKE 'oauth.app.%%' ORDER BY config_key")
|
||||
profiles = query(conn, "SELECT u.id,u.public_id,u.is_test,u.test_batch,p.avatar_url FROM users u JOIN user_profiles p ON p.user_id=u.id WHERE u.is_test=1 ORDER BY u.id")
|
||||
return {
|
||||
'configValuesSha256': hashlib.sha256(repr(configs).encode()).hexdigest(),
|
||||
'testProfilesSha256': hashlib.sha256(repr(profiles).encode()).hexdigest(),
|
||||
'testUsers': len(profiles),
|
||||
}
|
||||
|
||||
|
||||
def prepare_static(stage, kind, stamp):
|
||||
entry = WEB / ('admin' if kind == 'admin' else 'app')
|
||||
releases = Path('/www/wwwroot/xingyu-' + kind + '/releases')
|
||||
assert entry.is_symlink()
|
||||
previous = entry.resolve()
|
||||
assert previous.parent == releases
|
||||
release = releases / ('application-' + stamp)
|
||||
extract(stage / (kind + '.zip'), release)
|
||||
index = (release / 'index.html').read_text()
|
||||
assert ('/admin/jse/' if kind == 'admin' else '/app/assets/') in index
|
||||
if kind == 'admin':
|
||||
assert '"/admin/v1"' in (release / '_app.config.js').read_text()
|
||||
# Preserve resources used by tabs opened before the atomic entry switch.
|
||||
for folder in (['js', 'jse', 'css'] if kind == 'admin' else ['assets']):
|
||||
for source in (previous / folder).rglob('*'):
|
||||
if source.is_file():
|
||||
destination = release / source.relative_to(previous)
|
||||
if not destination.exists():
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(source), str(destination))
|
||||
www = pwd.getpwnam('www')
|
||||
for parent, directories, files in os.walk(str(release)):
|
||||
os.chown(parent, www.pw_uid, www.pw_gid)
|
||||
os.chmod(parent, 0o755)
|
||||
for name in files:
|
||||
path = os.path.join(parent, name)
|
||||
os.chown(path, www.pw_uid, www.pw_gid)
|
||||
os.chmod(path, 0o644)
|
||||
return entry, previous, release
|
||||
|
||||
|
||||
def replace_binary(source, suffix):
|
||||
target = BT / ('xingyu-api.' + suffix)
|
||||
assert not target.exists()
|
||||
shutil.copy2(str(source), str(target))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(target), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(target), 0o750)
|
||||
os.replace(str(target), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def public_checks(admin, h5):
|
||||
for prefix, release in [('/admin/', admin), ('/app/', h5)]:
|
||||
status, headers, body = fetch(prefix)
|
||||
assert status == 200 and body == (release / 'index.html').read_bytes()
|
||||
assert 'no-store' in ','.join(headers.get_all('Cache-Control', []))
|
||||
paths = re.findall(r'(?:src|href)="(/(?:admin|app)/[^"?#]+)', body.decode())
|
||||
for path in paths:
|
||||
if path.endswith(('.js', '.css')):
|
||||
assert fetch(path)[0] == 200
|
||||
assert fetch('/admin/_app.config.js')[2] == (admin / '_app.config.js').read_bytes()
|
||||
for path in ['/admin/v1/users', '/admin/v1/auth/codes', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
for platform in ['app', 'h5']:
|
||||
status, _, body = fetch('/api/v1/auth/oauth/providers?platform=' + platform)
|
||||
assert status == 200 and json.loads(body)['code'] == 0
|
||||
health()
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and re.fullmatch('[a-f0-9]{64}', expected)
|
||||
assert digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
values = env_values()
|
||||
conn, db_options = database(values)
|
||||
assert digest(BT / 'xingyu-api') == EXPECTED_OLD, 'production changed; re-audit required'
|
||||
health()
|
||||
subprocess.run(['/www/server/nginx/sbin/nginx', '-t'], check=True)
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/application-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name, sha in manifest['files'].items():
|
||||
path = (stage / name).resolve()
|
||||
assert stage in path.parents and path.is_file() and digest(path) == sha
|
||||
recorded = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, checksum in recorded.items():
|
||||
assert (stage / 'migrations' / name).is_file() and digest(stage / 'migrations' / name) == checksum, 'migration history mismatch: ' + name
|
||||
pending = sorted(file.name for file in (stage / 'migrations').glob('*.sql') if file.name not in recorded)
|
||||
assert pending == MIGRATIONS, 'unreviewed pending migrations'
|
||||
before = marker(conn)
|
||||
state = {
|
||||
'stamp': stamp, 'archiveSha256': expected, 'stage': str(stage),
|
||||
'previousBackendSha256': EXPECTED_OLD,
|
||||
'rollbackBackendSha256': manifest['files']['xingyu-api-rollback'],
|
||||
'previousAdmin': str((WEB / 'admin').resolve()), 'previousH5': str((WEB / 'app').resolve()),
|
||||
'before': before,
|
||||
}
|
||||
backup = Path('/www/backup/xingyu-application-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
state['backup'] = str(backup)
|
||||
dump = subprocess.Popen(['/opt/mysql-8.4.11/bin/mysqldump', '-h', '127.0.0.1', '-P', '3307', '-u', db_options['user'], '--single-transaction', '--no-tablespaces', '--set-gtid-purged=OFF', '--routines', '--triggers', 'im'], env=dict(os.environ, MYSQL_PWD=db_options['password']), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
with gzip.open(str(backup / 'im.sql.gz'), 'wb') as output:
|
||||
shutil.copyfileobj(dump.stdout, output)
|
||||
_, errors = dump.communicate()
|
||||
if dump.returncode:
|
||||
raise RuntimeError('database backup failed')
|
||||
os.chmod(str(backup / 'im.sql.gz'), 0o600)
|
||||
with gzip.open(str(backup / 'im.sql.gz'), 'rb') as check:
|
||||
assert b'MySQL dump' in check.read(4096)
|
||||
while check.read(1024 * 1024):
|
||||
pass
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
shutil.copy2(str(stage / 'xingyu-api-rollback'), str(backup / 'xingyu-api-compatible-rollback'))
|
||||
shutil.copy2('/etc/xingyu-im-bt.env', str(backup / 'environment.env'))
|
||||
os.chmod(str(backup / 'environment.env'), 0o600)
|
||||
(backup / 'state.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
admin = prepare_static(stage, 'admin', stamp)
|
||||
h5 = prepare_static(stage, 'h5', stamp)
|
||||
switched = []
|
||||
binary_changed = False
|
||||
try:
|
||||
for name in pending:
|
||||
file = stage / 'migrations' / name
|
||||
sql = '\n'.join(line for line in file.read_text().splitlines() if not line.lstrip().startswith('--'))
|
||||
for statement in sql.split(';'):
|
||||
if statement.strip():
|
||||
query(conn, statement)
|
||||
query(conn, 'INSERT INTO schema_migrations(version,checksum) VALUES(%s,%s)', (name, digest(file)))
|
||||
shutil.copy2(str(file), str(BT / 'migrations' / name))
|
||||
print('MIGRATION_APPLIED=' + name, flush=True)
|
||||
assert marker(conn) == before, 'existing data or config changed during migrations'
|
||||
assert query(conn, "SELECT COUNT(*) FROM admin_role_permissions rp JOIN admin_roles r ON r.id=rp.role_id WHERE r.role_code='super_admin' AND rp.permission_code='users:create'")[0][0] == 1
|
||||
replace_binary(stage / 'xingyu-api', 'next-' + stamp)
|
||||
binary_changed = True
|
||||
print('BACKEND_RESTARTING', flush=True)
|
||||
restart()
|
||||
print('BACKEND_HEALTHY', flush=True)
|
||||
for entry, previous, release in [admin, h5]:
|
||||
switch(entry, release, stamp)
|
||||
switched.append((entry, previous))
|
||||
public_checks(admin[2], h5[2])
|
||||
assert marker(conn) == before, 'existing config or test profiles changed during release'
|
||||
assert digest(BT / 'xingyu-api') == manifest['files']['xingyu-api']
|
||||
state.update({'backendSha256': digest(BT / 'xingyu-api'), 'admin': str(admin[2]), 'h5': str(h5[2]), 'migrationsApplied': pending, 'publicChecks': True, 'preservedExistingDataAndConfig': True})
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print('PUBLISHED=' + json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
for entry, previous in reversed(switched):
|
||||
switch(entry, previous, stamp + '-rollback')
|
||||
if binary_changed:
|
||||
replace_binary(backup / 'xingyu-api-compatible-rollback', 'rollback-' + stamp)
|
||||
restart()
|
||||
print('APPLICATION_ROLLED_BACK; added schema retained; backup=' + str(backup), flush=True)
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(sys.argv[1], sys.argv[2])
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish reviewed avatar processing and H5 assets without changing user data."""
|
||||
import fcntl
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, WEB, DOMAIN, database, digest, env_values, extract, fetch, health, query, restart, switch
|
||||
|
||||
OLD = '812ceedad7a7714ad9d04558946370d5665b0a2a9231b0e1282cb65def9f03ab'
|
||||
BASE = Path('/www/server/xingyu-im/releases/im-unread-20260831-124713')
|
||||
ALLOWED = {'backend/go.mod', 'backend/go.sum', 'backend/internal/app/media.go',
|
||||
'backend/internal/app/avatar_images.go', 'backend/internal/app/avatar_images_test.go',
|
||||
'backend/internal/app/media_batch.go', 'backend/internal/app/media_batch_test.go',
|
||||
'backend/internal/app/media_upload_test.go', 'backend/docs/avatar-thumbnails.md'}
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1
|
||||
return pids
|
||||
|
||||
|
||||
def marker(conn):
|
||||
configs = query(conn, 'SELECT config_key,config_value FROM system_configs ORDER BY config_key')
|
||||
profiles = query(conn, 'SELECT p.user_id,p.avatar_url FROM user_profiles p JOIN users u ON u.id=p.user_id WHERE u.is_test=1 ORDER BY p.user_id')
|
||||
return {'configValuesSha256': hashlib.sha256(repr(configs).encode()).hexdigest(),
|
||||
'testAvatarsSha256': hashlib.sha256(repr(profiles).encode()).hexdigest(), 'testUsers': len(profiles)}
|
||||
|
||||
|
||||
def replace_binary(source, stamp):
|
||||
target = BT / ('xingyu-api.avatars-' + stamp)
|
||||
assert not target.exists()
|
||||
shutil.copy2(str(source), str(target))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(target), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(target), 0o750)
|
||||
os.replace(str(target), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def prepare_h5(stage, stamp):
|
||||
entry = WEB / 'app'
|
||||
previous = entry.resolve()
|
||||
releases = Path('/www/wwwroot/xingyu-h5/releases')
|
||||
assert entry.is_symlink() and previous.parent == releases
|
||||
release = releases / ('avatars-' + stamp)
|
||||
extract(stage / 'h5.zip', release)
|
||||
assert '/app/assets/' in (release / 'index.html').read_text()
|
||||
scripts = '\n'.join(p.read_text() for p in (release / 'assets').glob('*.js'))
|
||||
assert all(value in scripts for value in ['uploadAvatar', '-av1', '-thumb.jpg', 'https://im.bchongw.com'])
|
||||
for source in (previous / 'assets').rglob('*'):
|
||||
if source.is_file():
|
||||
target = release / source.relative_to(previous)
|
||||
if not target.exists():
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(source), str(target))
|
||||
www = pwd.getpwnam('www')
|
||||
for parent, _, files in os.walk(str(release)):
|
||||
os.chown(parent, www.pw_uid, www.pw_gid)
|
||||
os.chmod(parent, 0o755)
|
||||
for name in files:
|
||||
path = os.path.join(parent, name)
|
||||
os.chown(path, www.pw_uid, www.pw_gid)
|
||||
os.chmod(path, 0o644)
|
||||
return entry, previous, release
|
||||
|
||||
|
||||
def public_checks(stage):
|
||||
verified = []
|
||||
with zipfile.ZipFile(str(stage / 'h5.zip')) as package:
|
||||
index = package.read('index.html')
|
||||
status, headers, body = fetch('/app/')
|
||||
assert status == 200 and body == index
|
||||
assert 'no-store' in ','.join(headers.get_all('Cache-Control', []))
|
||||
paths = set(re.findall(r'(?:src|href)="(/app/[^"?#]+)', index.decode()))
|
||||
for name in package.namelist():
|
||||
if name.startswith(('assets/pages-edit-profile-', 'assets/pages-home-', 'assets/pages-chat-', 'assets/pages-messages-', 'assets/AvatarImage')) and name.endswith(('.js', '.css')):
|
||||
paths.add('/app/' + name)
|
||||
paths.add('/app/static/favicon.svg')
|
||||
for path in sorted(paths):
|
||||
if path.endswith(('.js', '.css', '.svg')):
|
||||
status, _, body = fetch(path)
|
||||
assert status == 200 and body == package.read(path[len('/app/'):]), path
|
||||
verified.append(path)
|
||||
assert fetch('/admin/')[0] == 200
|
||||
for path, method in [('/api/v1/media/upload', 'POST'), ('/api/v1/im/conversations', 'GET'), ('/admin/v1/users', 'GET'), ('/ws', 'GET')]:
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(DOMAIN + path, method=method), timeout=20):
|
||||
raise RuntimeError('private endpoint became public')
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
health()
|
||||
return verified
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0 and re.fullmatch('[a-f0-9]{64}', expected)
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
subprocess.run(['/www/server/nginx/sbin/nginx', '-t'], check=True)
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/avatars-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name, sha in manifest['files'].items():
|
||||
path = (stage / name).resolve()
|
||||
assert stage in path.parents and path.is_file() and digest(path) == sha
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
for name in ['xingyu-api', 'avatar-check.test']:
|
||||
assert (stage / name).read_bytes()[:4] == b'\x7fELF'
|
||||
probe = stage / 'avatar-check.test'
|
||||
os.chmod(str(probe), 0o700)
|
||||
# These exact tests use temporary local files and in-memory database/storage
|
||||
# fixtures. They do not authenticate as a user or touch production records.
|
||||
cases = 'TestAvatarVariantsDimensionsAndSource|TestAvatarPhoneEXIFOrientation|TestAvatarSmallTransparentImageIsNotEnlarged|TestAvatarRejectsInvalidAndExcessivePixels|TestAvatarGIFAndWebP|TestAvatarUploadStoresAndServesAllVariants|TestAvatarUploadFinalizationFailureCleansEveryObject|TestOrdinaryMediaUploadPreservesOriginal|TestInvalidAvatarUploadCreatesNoRecords|TestMediaVariantUploadCleanup|TestLocalUploadCollisionPreservesExistingObject'
|
||||
subprocess.run([str(probe), '-test.run=^(' + cases + ')$', '-test.v'], cwd=str(stage), check=True, timeout=90)
|
||||
print('LINUX_AVATAR_TESTS_PASSED', flush=True)
|
||||
conn, options = database(env_values())
|
||||
try:
|
||||
migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
assert {name: sha for name, sha in new_source.items() if name.startswith('backend/migrations/')} == {'backend/migrations/' + name: sha for name, sha in migrations.items()}
|
||||
# Original binary rollback is safe for current COS objects; local
|
||||
# storage would additionally need the new av1 static filename rule.
|
||||
assert query(conn, "SELECT config_value FROM system_configs WHERE config_key='storage.provider'")[0][0] == 'tencent_cos'
|
||||
before = marker(conn)
|
||||
admin = str((WEB / 'admin').resolve())
|
||||
backup = Path('/www/backup/xingyu-avatars-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
dump = subprocess.Popen(['/opt/mysql-8.4.11/bin/mysqldump', '-h', '127.0.0.1', '-P', '3307', '-u', options['user'], '--single-transaction', '--no-tablespaces', '--set-gtid-purged=OFF', '--routines', '--triggers', 'im'], env=dict(os.environ, MYSQL_PWD=options['password']), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
with gzip.open(str(backup / 'im.sql.gz'), 'wb') as output:
|
||||
shutil.copyfileobj(dump.stdout, output)
|
||||
dump.communicate()
|
||||
assert dump.returncode == 0, 'database backup failed'
|
||||
os.chmod(str(backup / 'im.sql.gz'), 0o600)
|
||||
with gzip.open(str(backup / 'im.sql.gz'), 'rb') as check:
|
||||
assert b'MySQL dump' in check.read(4096)
|
||||
while check.read(1024 * 1024):
|
||||
pass
|
||||
entry, previous, release = prepare_h5(stage, stamp)
|
||||
state = {'stage': str(stage), 'backup': str(backup), 'archiveSha256': expected,
|
||||
'previousBackendSha256': OLD, 'backendSha256': manifest['files']['xingyu-api'],
|
||||
'previousH5': str(previous), 'h5': str(release), 'adminUnchanged': admin,
|
||||
'changedBackendSourceFiles': sorted(changed), 'before': before,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': False, 'linuxAvatarTests': True}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
binary_changed = switched = False
|
||||
try:
|
||||
replace_binary(stage / 'xingyu-api', stamp)
|
||||
binary_changed = True
|
||||
print('BACKEND_RESTARTING', flush=True)
|
||||
restart()
|
||||
state['runningPids'] = running(state['backendSha256'])
|
||||
switch(entry, release, stamp)
|
||||
switched = True
|
||||
state['publicAssetsVerified'] = public_checks(stage)
|
||||
assert marker(conn) == before, 'configuration or test avatars changed during release'
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == migrations
|
||||
assert str((WEB / 'admin').resolve()) == admin
|
||||
state['healthAndAuthChecks'] = True
|
||||
state['preservedConfigurationAndTestAvatars'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print('PUBLISHED=' + json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if switched:
|
||||
switch(entry, previous, stamp + '-rollback')
|
||||
if binary_changed:
|
||||
replace_binary(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
print('ROLLED_BACK_APPLICATION; database untouched; backup=' + str(backup), flush=True)
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a versioned uni-app H5 build through the existing BaoTa gateway."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('archive')
|
||||
parser.add_argument('sha256')
|
||||
args = parser.parse_args()
|
||||
archive = Path(args.archive).resolve()
|
||||
assert archive.is_file() and archive.parent == Path('/tmp')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == args.sha256.lower()
|
||||
assert os.geteuid() == 0
|
||||
root = Path('/www/wwwroot/im.bchongw.com')
|
||||
go_config = Path('/www/server/panel/vhost/nginx/go_xingyu_im.conf')
|
||||
main_config = go_config if go_config.is_file() else Path('/www/server/panel/vhost/nginx/html_im.bchongw.com.conf')
|
||||
config = Path('/www/server/panel/vhost/nginx/extension/xingyu_im/xingyu_routes.conf') if go_config.is_file() else main_config
|
||||
old_config = config.read_text()
|
||||
assert 'server_name im.bchongw.com;' in main_config.read_text()
|
||||
release = Path('/www/wwwroot/xingyu-h5/releases') / time.strftime('%Y%m%d-%H%M%S')
|
||||
release.mkdir(mode=0o755, parents=True, exist_ok=False)
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
for info in package.infolist():
|
||||
candidate = (release / info.filename.replace('\\', '/')).resolve()
|
||||
assert os.path.commonpath([str(candidate), str(release)]) == str(release)
|
||||
# Windows PowerShell archives may store backslash separators. Normalize
|
||||
# them explicitly instead of creating literal backslashes on Linux.
|
||||
if info.is_dir() or info.filename.endswith(('\\', '/')):
|
||||
candidate.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
candidate.parent.mkdir(parents=True, exist_ok=True)
|
||||
with package.open(info) as source, candidate.open('wb') as target:
|
||||
shutil.copyfileobj(source, target)
|
||||
www = pwd.getpwnam('www')
|
||||
for parent, directories, files in os.walk(str(release)):
|
||||
os.chown(parent, www.pw_uid, www.pw_gid)
|
||||
os.chmod(parent, 0o755)
|
||||
for filename in files:
|
||||
path = os.path.join(parent, filename)
|
||||
os.chown(path, www.pw_uid, www.pw_gid)
|
||||
os.chmod(path, 0o644)
|
||||
assert '/app/assets/' in (release / 'index.html').read_text()
|
||||
assert (release / 'static/favicon.svg').is_file()
|
||||
entry = root / 'app'
|
||||
assert not entry.exists() or entry.is_symlink()
|
||||
previous = os.readlink(str(entry)) if entry.is_symlink() else None
|
||||
backup = Path('/www/backup/xingyu-h5-publish-' + time.strftime('%Y%m%d-%H%M%S'))
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(config), str(backup / config.name))
|
||||
block = '''
|
||||
# XINGYU_H5_START
|
||||
location = /app { return 301 /app/; }
|
||||
location = /app/ {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files /app/index.html =404;
|
||||
}
|
||||
location = /app/index.html {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /app/assets/ {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /app/static/ {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
expires 1h;
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /app/ {
|
||||
root /www/wwwroot/im.bchongw.com;
|
||||
try_files $uri $uri/ /app/index.html;
|
||||
}
|
||||
# XINGYU_H5_END
|
||||
|
||||
'''
|
||||
|
||||
|
||||
def switch(target):
|
||||
next_link = root / 'app.next'
|
||||
assert not next_link.exists() and not next_link.is_symlink()
|
||||
os.symlink(target, str(next_link))
|
||||
os.replace(str(next_link), str(entry))
|
||||
|
||||
|
||||
try:
|
||||
switch(str(release))
|
||||
if '# XINGYU_H5_START' not in old_config:
|
||||
marker = ' location = /admin {'
|
||||
assert old_config.count(marker) == 1
|
||||
config.write_text(old_config.replace(marker, block + marker))
|
||||
subprocess.run(['/www/server/nginx/sbin/nginx', '-t'], check=True)
|
||||
subprocess.run(['/etc/init.d/nginx', 'reload'], check=True)
|
||||
assert entry.resolve() == release.resolve()
|
||||
assert (release / 'index.html').is_file() and (release / 'static/favicon.svg').is_file()
|
||||
assert (root / 'admin').resolve().joinpath('index.html').is_file()
|
||||
with urllib.request.urlopen('http://127.0.0.1:18888/healthz', timeout=10) as response:
|
||||
assert response.status == 200
|
||||
os.chdir('/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel/class')
|
||||
import public
|
||||
project_name = 'xingyu_im' if go_config.is_file() else 'im.bchongw.com'
|
||||
public.M('sites').where('name=?', (project_name,)).setField(
|
||||
'ps', '星遇 IM · im.bchongw.com · 管理端 /admin/ · H5 /app/')
|
||||
print('H5_PUBLISHED=' + str(release))
|
||||
print('NGINX_BACKUP=' + str(backup))
|
||||
except Exception:
|
||||
config.write_text(old_config)
|
||||
if previous:
|
||||
switch(previous)
|
||||
else:
|
||||
# Remove only the symlink just created; retain all release files for diagnosis.
|
||||
assert entry.is_symlink() and os.readlink(str(entry)) == str(release)
|
||||
entry.unlink()
|
||||
subprocess.run(['/www/server/nginx/sbin/nginx', '-t'], check=True)
|
||||
subprocess.run(['/etc/init.d/nginx', 'reload'], check=True)
|
||||
raise
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish only the reviewed IM hotfix; no DB writes, migrations, or frontend changes."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, WEB, database, digest, env_values, extract, fetch, health, query, restart
|
||||
|
||||
OLD = '54e699a73fd6d3cec7baae3b1224a03cca6f2ddfdcb91c23f05e1fa258514b56'
|
||||
BASE = Path('/www/server/xingyu-im/releases/application-20260831-121140')
|
||||
ALLOWED = {'backend/internal/app/im.go', 'backend/internal/app/im_unread_integration_test.go'}
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.im-unread-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/im-unread-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
conn, _ = database(env_values())
|
||||
try:
|
||||
before_migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in before_migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(before_migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
backup = Path('/www/backup/xingyu-im-unread-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
state = {'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD, 'backendSha256': new_hash,
|
||||
'archiveSha256': expected, 'changedSourceFiles': sorted(changed), 'frontendUnchanged': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': False}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == before_migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
for path in ['/api/v1/im/conversations', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['healthAndAuthChecks'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary restored. No database restore performed.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,307 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish nearby-distance support and backfill only the labelled fixture batch."""
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, WEB, database, digest, env_values, extract, query
|
||||
|
||||
OLD = 'e8344e81cc828e6817bc7c232a261884fbb5d7e8123420da121ede908502329e'
|
||||
BASE = Path('/www/server/xingyu-im/releases/read-badge-20260901-183536')
|
||||
BATCH = 'cn-adults-20260831-v1'
|
||||
LOCAL = 'http://127.0.0.1:18888'
|
||||
ALLOWED = {
|
||||
'backend/internal/app/social.go',
|
||||
'backend/internal/testusers/fixtures.go',
|
||||
'backend/internal/testusers/seed.go',
|
||||
'fixtures/test-users/users.json',
|
||||
}
|
||||
|
||||
|
||||
def fetch(path):
|
||||
with urllib.request.urlopen(LOCAL + path, timeout=20) as response:
|
||||
return response.status, response.headers, response.read()
|
||||
|
||||
|
||||
def health():
|
||||
for _ in range(100):
|
||||
try:
|
||||
status, _, data = fetch('/healthz')
|
||||
if status == 200 and json.loads(data)['data']['status'] == 'ok':
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('backend failed local health check')
|
||||
|
||||
|
||||
def restart():
|
||||
os.chdir('/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel/class')
|
||||
import public
|
||||
from projectModel.goModel import main as GoProject
|
||||
request = public.dict_obj()
|
||||
request.project_name = 'xingyu_im'
|
||||
manager = GoProject()
|
||||
project = manager.get_project_find('xingyu_im')
|
||||
assert project and project['project_config']['is_power_on'] == 1
|
||||
result = manager.restart_project(request)
|
||||
if not result.get('status'):
|
||||
recovered = manager.start_project(request)
|
||||
if not recovered.get('status'):
|
||||
raise RuntimeError('BaoTa could not start project')
|
||||
health()
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.nearby-distance-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def encode_json(value):
|
||||
raw = json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
|
||||
|
||||
|
||||
def user_token(secret, user_id, nickname, version):
|
||||
now = int(time.time())
|
||||
header = encode_json({'alg': 'HS256', 'typ': 'JWT'})
|
||||
payload = encode_json({'role': 'user', 'name': nickname, 'ver': version, 'sub': str(user_id), 'iat': now, 'exp': now + 300})
|
||||
signing_input = (header + '.' + payload).encode()
|
||||
signature = base64.urlsafe_b64encode(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()).rstrip(b'=').decode()
|
||||
return header + '.' + payload + '.' + signature
|
||||
|
||||
|
||||
def fixture_rows(conn):
|
||||
return query(conn, """SELECT user.id,user.public_id,profile.nickname
|
||||
FROM users user JOIN user_profiles profile ON profile.user_id=user.id
|
||||
WHERE user.is_test=1 AND user.test_batch=%s AND user.status=1 AND user.deleted_at IS NULL
|
||||
ORDER BY user.id""", (BATCH,))
|
||||
|
||||
|
||||
def privacy_rows(conn):
|
||||
return query(conn, """SELECT privacy.user_id,privacy.distance_visible,
|
||||
DATE_FORMAT(privacy.updated_at,'%%Y-%%m-%%d %%H:%%i:%%s.%%f')
|
||||
FROM user_privacy_settings privacy JOIN users user ON user.id=privacy.user_id
|
||||
WHERE user.is_test=1 AND user.test_batch=%s AND user.deleted_at IS NULL ORDER BY privacy.user_id""", (BATCH,))
|
||||
|
||||
|
||||
def location_rows(conn):
|
||||
return query(conn, """SELECT location.user_id,location.city_code,location.location_cell,
|
||||
CAST(location.latitude AS CHAR),CAST(location.longitude AS CHAR),
|
||||
DATE_FORMAT(location.last_location_at,'%%Y-%%m-%%d %%H:%%i:%%s.%%f'),location.source,
|
||||
DATE_FORMAT(location.created_at,'%%Y-%%m-%%d %%H:%%i:%%s.%%f'),
|
||||
DATE_FORMAT(location.updated_at,'%%Y-%%m-%%d %%H:%%i:%%s.%%f')
|
||||
FROM user_location_states location JOIN users user ON user.id=location.user_id
|
||||
WHERE user.is_test=1 AND user.test_batch=%s AND user.deleted_at IS NULL ORDER BY location.user_id""", (BATCH,))
|
||||
|
||||
|
||||
def restore_data(conn, privacy_before, locations_before):
|
||||
fixture_ids = [row[0] for row in privacy_before]
|
||||
assert len(fixture_ids) == 100
|
||||
placeholders = ','.join(['%s'] * len(fixture_ids))
|
||||
with conn.cursor() as cursor:
|
||||
cursor.executemany(
|
||||
'UPDATE user_privacy_settings SET distance_visible=%s,updated_at=%s WHERE user_id=%s',
|
||||
[(distance, updated, user_id) for user_id, distance, updated in privacy_before],
|
||||
)
|
||||
cursor.execute('DELETE FROM user_location_states WHERE user_id IN (' + placeholders + ')', fixture_ids)
|
||||
if locations_before:
|
||||
cursor.executemany("""INSERT INTO user_location_states
|
||||
(user_id,city_code,location_cell,latitude,longitude,last_location_at,source,created_at,updated_at)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)""", locations_before)
|
||||
|
||||
|
||||
def verify_api(conn, values):
|
||||
selected = query(conn, """SELECT user.id,profile.nickname,security.token_version
|
||||
FROM users user JOIN user_profiles profile ON profile.user_id=user.id
|
||||
JOIN user_security_controls security ON security.user_id=user.id
|
||||
WHERE user.is_test=1 AND user.test_batch=%s AND user.status=1 AND user.deleted_at IS NULL
|
||||
ORDER BY user.id LIMIT 1""", (BATCH,))
|
||||
assert selected
|
||||
user_id, nickname, version = selected[0]
|
||||
token = user_token(values['IM_JWT_SECRET'], user_id, nickname, version)
|
||||
request = urllib.request.Request(
|
||||
LOCAL + '/api/v1/nearby/users?page=1&pageSize=20',
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
assert response.status == 200
|
||||
result = json.loads(response.read())['data']
|
||||
assert result.get('locationReady') is True
|
||||
distance_items = [item for item in result.get('items', []) if item.get('distanceText') and float(item.get('distance', 0)) >= 0]
|
||||
assert distance_items, 'nearby API returned no visible distances'
|
||||
return {
|
||||
'viewerUserId': user_id,
|
||||
'items': len(result.get('items', [])),
|
||||
'itemsWithDistance': len(distance_items),
|
||||
'sampleDistanceText': distance_items[0]['distanceText'],
|
||||
}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/nearby-distance-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip', 'fixture-locations.json']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
profiles = json.loads((stage / 'fixture-locations.json').read_text())
|
||||
assert len(profiles) == 100
|
||||
profile_map = {item['publicId']: item for item in profiles}
|
||||
assert len(profile_map) == 100
|
||||
assert all(item['testBatch'] == BATCH and item['isTest'] is True for item in profiles)
|
||||
assert len({(item['latitude'], item['longitude']) for item in profiles}) == 100
|
||||
assert all(18 < item['latitude'] < 54 and 73 < item['longitude'] < 136 for item in profiles)
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
fixtures = fixture_rows(conn)
|
||||
assert len(fixtures) == 100 and {row[1] for row in fixtures} == set(profile_map)
|
||||
privacy_before = privacy_rows(conn)
|
||||
locations_before = location_rows(conn)
|
||||
assert len(privacy_before) == 100
|
||||
backup = Path('/www/backup/xingyu-nearby-distance-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
for name, rows in [('privacy-before.json', privacy_before), ('locations-before.json', locations_before)]:
|
||||
path = backup / name
|
||||
path.write_text(json.dumps(rows, ensure_ascii=False, default=str))
|
||||
os.chmod(str(path), 0o600)
|
||||
state = {
|
||||
'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD,
|
||||
'backendSha256': new_hash, 'archiveSha256': expected,
|
||||
'changedSourceFiles': sorted(changed), 'frontendBefore': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': True,
|
||||
'dataScope': 'is_test=1 and test_batch=' + BATCH,
|
||||
'locationRowsBefore': len(locations_before),
|
||||
}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
data_changed = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("""UPDATE user_privacy_settings privacy JOIN users user ON user.id=privacy.user_id
|
||||
SET privacy.distance_visible=1
|
||||
WHERE user.is_test=1 AND user.test_batch=%s AND user.deleted_at IS NULL""", (BATCH,))
|
||||
state['privacyRowsChanged'] = cursor.rowcount
|
||||
data_changed = True
|
||||
existing_ids = {row[0] for row in locations_before}
|
||||
inserts = []
|
||||
for user_id, public_id, _ in fixtures:
|
||||
if user_id in existing_ids:
|
||||
continue
|
||||
item = profile_map[public_id]
|
||||
inserts.append((user_id, item['cityCode'], item['latitude'], item['longitude']))
|
||||
if inserts:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.executemany("""INSERT INTO user_location_states
|
||||
(user_id,city_code,location_cell,latitude,longitude,source)
|
||||
VALUES(%s,%s,'fixture',%s,%s,'fixture')""", inserts)
|
||||
state['locationRowsInserted'] = len(inserts)
|
||||
after_locations = location_rows(conn)
|
||||
assert len(after_locations) == 100
|
||||
assert all(int(row[1]) == 1 for row in privacy_rows(conn))
|
||||
before_by_id = {row[0]: row for row in locations_before}
|
||||
after_by_id = {row[0]: row for row in after_locations}
|
||||
assert all(after_by_id[user_id] == row for user_id, row in before_by_id.items())
|
||||
for path in ['/api/v1/nearby/users', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['nearbyApi'] = verify_api(conn, values)
|
||||
state['healthAndAuthChecks'] = True
|
||||
state['locationRowsAfter'] = len(after_locations)
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if data_changed:
|
||||
restore_data(conn, privacy_before, locations_before)
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary and scoped fixture distance data restored.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish the reviewed nearby-post-media API hotfix with automatic rollback."""
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, DOMAIN, WEB, database, digest, env_values, extract, fetch, health, query, restart
|
||||
|
||||
OLD = 'b7eeb926d063855e4271815872ba8c90e226554a3824d48e0995479a671e546e'
|
||||
BASE = Path('/www/server/xingyu-im/releases/avatars-20260831-180014')
|
||||
ALLOWED = {'backend/internal/app/social.go'}
|
||||
TARGET_PUBLIC_ID = 'TESTCN000100'
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.nearby-post-media-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def encode_json(value):
|
||||
raw = json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
|
||||
|
||||
|
||||
def user_token(secret, user_id, nickname, version):
|
||||
now = int(time.time())
|
||||
header = encode_json({'alg': 'HS256', 'typ': 'JWT'})
|
||||
payload = encode_json({'role': 'user', 'name': nickname, 'ver': version, 'sub': str(user_id), 'iat': now, 'exp': now + 300})
|
||||
signing_input = (header + '.' + payload).encode()
|
||||
signature = base64.urlsafe_b64encode(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()).rstrip(b'=').decode()
|
||||
return header + '.' + payload + '.' + signature
|
||||
|
||||
|
||||
def verify_nearby_response(conn, values):
|
||||
target = query(conn, "SELECT post.id,COUNT(media.id) FROM posts post JOIN users user ON user.id=post.user_id LEFT JOIN post_media media ON media.post_id=post.id WHERE user.public_id=%s AND post.status=1 AND post.moderation_status=1 AND post.deleted_at IS NULL GROUP BY post.id ORDER BY post.created_at DESC,post.id DESC LIMIT 1", (TARGET_PUBLIC_ID,))
|
||||
assert target and target[0][1] == 2, 'expected the reviewed two-image post'
|
||||
viewer = query(conn, "SELECT user.id,profile.nickname,security.token_version FROM users user JOIN user_profiles profile ON profile.user_id=user.id JOIN user_security_controls security ON security.user_id=user.id WHERE user.public_id<>%s AND user.status=1 AND user.deleted_at IS NULL ORDER BY user.id LIMIT 1", (TARGET_PUBLIC_ID,))[0]
|
||||
token = user_token(values['IM_JWT_SECRET'], viewer[0], viewer[1], viewer[2])
|
||||
found = None
|
||||
for page in (1, 2, 3):
|
||||
request = urllib.request.Request(
|
||||
DOMAIN + '/api/v1/nearby/users?page=' + str(page) + '&pageSize=50',
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
assert response.status == 200
|
||||
payload = json.loads(response.read())
|
||||
for item in payload['data']['items']:
|
||||
if item.get('publicId') == TARGET_PUBLIC_ID:
|
||||
found = item
|
||||
break
|
||||
if found:
|
||||
break
|
||||
assert found, 'target user was not returned by nearby API'
|
||||
latest = found.get('latestPost') or {}
|
||||
assert latest.get('id') == target[0][0]
|
||||
assert len(latest.get('media') or []) == 2
|
||||
assert latest.get('mediaThumbnails') == latest.get('media')
|
||||
return {'publicId': TARGET_PUBLIC_ID, 'postId': latest['id'], 'mediaCount': len(latest['media'])}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/nearby-post-media-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
before_migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in before_migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(before_migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
backup = Path('/www/backup/xingyu-nearby-post-media-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
state = {
|
||||
'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD,
|
||||
'backendSha256': new_hash, 'archiveSha256': expected,
|
||||
'changedSourceFiles': sorted(changed), 'frontendUnchanged': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': False,
|
||||
}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == before_migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
for path in ['/api/v1/nearby/users', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['nearbyPostMedia'] = verify_nearby_response(conn, values)
|
||||
state['healthAndAuthChecks'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary restored. No database restore performed.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish authoritative realtime presence with automatic rollback."""
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, DOMAIN, WEB, database, digest, env_values, extract, fetch, health, query, restart
|
||||
|
||||
OLD = 'e8e071ec7006a32303f7cd654cddad8afda22ecb4fe83464305a9d3aef4d7280'
|
||||
BASE = Path('/www/server/xingyu-im/releases/nearby-post-media-20260901-115131')
|
||||
ALLOWED = {
|
||||
'backend/internal/app/auth.go',
|
||||
'backend/internal/app/public_auth.go',
|
||||
'backend/internal/app/im.go',
|
||||
'backend/internal/app/social.go',
|
||||
'backend/internal/app/presence_test.go',
|
||||
'backend/internal/testusers/seed.go',
|
||||
}
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.presence-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def encode_json(value):
|
||||
raw = json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
|
||||
|
||||
|
||||
def user_token(secret, user_id, nickname, version):
|
||||
now = int(time.time())
|
||||
header = encode_json({'alg': 'HS256', 'typ': 'JWT'})
|
||||
payload = encode_json({'role': 'user', 'name': nickname, 'ver': version, 'sub': str(user_id), 'iat': now, 'exp': now + 300})
|
||||
signing_input = (header + '.' + payload).encode()
|
||||
signature = base64.urlsafe_b64encode(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()).rstrip(b'=').decode()
|
||||
return header + '.' + payload + '.' + signature
|
||||
|
||||
|
||||
def receive_exact(stream, count):
|
||||
output = b''
|
||||
while len(output) < count:
|
||||
chunk = stream.recv(count - len(output))
|
||||
if not chunk:
|
||||
raise RuntimeError('WebSocket closed before AUTH_ACK')
|
||||
output += chunk
|
||||
return output
|
||||
|
||||
|
||||
def first_websocket_command(stream, initial=b''):
|
||||
class Buffered:
|
||||
def __init__(self, buffered, source):
|
||||
self.buffered, self.source = buffered, source
|
||||
def recv(self, count):
|
||||
if self.buffered:
|
||||
chunk, self.buffered = self.buffered[:count], self.buffered[count:]
|
||||
return chunk
|
||||
return self.source.recv(count)
|
||||
reader = Buffered(initial, stream)
|
||||
first, second = receive_exact(reader, 2)
|
||||
size = second & 0x7f
|
||||
if size == 126:
|
||||
size = int.from_bytes(receive_exact(reader, 2), 'big')
|
||||
elif size == 127:
|
||||
size = int.from_bytes(receive_exact(reader, 8), 'big')
|
||||
return json.loads(receive_exact(reader, size)).get('command')
|
||||
|
||||
|
||||
def profile_online(user_id, token):
|
||||
request = urllib.request.Request(
|
||||
DOMAIN + '/api/v1/users/' + str(user_id),
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
assert response.status == 200
|
||||
return bool(json.loads(response.read())['data']['online'])
|
||||
|
||||
|
||||
def verify_presence(conn, values):
|
||||
selected = query(conn, """SELECT target.id,target_profile.nickname,target_security.token_version,
|
||||
viewer.id,viewer_profile.nickname,viewer_security.token_version
|
||||
FROM users target JOIN user_profiles target_profile ON target_profile.user_id=target.id
|
||||
JOIN user_security_controls target_security ON target_security.user_id=target.id
|
||||
JOIN user_privacy_settings target_privacy ON target_privacy.user_id=target.id
|
||||
JOIN users viewer ON viewer.id<>target.id AND viewer.status=1 AND viewer.deleted_at IS NULL
|
||||
JOIN user_profiles viewer_profile ON viewer_profile.user_id=viewer.id
|
||||
JOIN user_security_controls viewer_security ON viewer_security.user_id=viewer.id
|
||||
WHERE target.status=1 AND target.deleted_at IS NULL AND target.is_test=1
|
||||
AND target_privacy.online_visible=1
|
||||
AND NOT EXISTS(SELECT 1 FROM user_blocks block WHERE
|
||||
(block.user_id=viewer.id AND block.blocked_user_id=target.id) OR
|
||||
(block.user_id=target.id AND block.blocked_user_id=viewer.id))
|
||||
ORDER BY target.id,viewer.id LIMIT 1""")
|
||||
assert selected, 'no isolated presence verification users available'
|
||||
target_id, target_name, target_version, viewer_id, viewer_name, viewer_version = selected[0]
|
||||
target_token = user_token(values['IM_JWT_SECRET'], target_id, target_name, target_version)
|
||||
viewer_token = user_token(values['IM_JWT_SECRET'], viewer_id, viewer_name, viewer_version)
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
request = ('\r\n'.join([
|
||||
'GET /ws HTTP/1.1', 'Host: im.bchongw.com', 'Upgrade: websocket',
|
||||
'Connection: Upgrade', 'Sec-WebSocket-Version: 13',
|
||||
'Sec-WebSocket-Key: ' + key, 'Origin: https://im.bchongw.com',
|
||||
'Sec-WebSocket-Protocol: xingyu.jwt.' + target_token,
|
||||
]) + '\r\n\r\n').encode()
|
||||
context = ssl.create_default_context()
|
||||
with socket.create_connection(('im.bchongw.com', 443), timeout=10) as raw:
|
||||
with context.wrap_socket(raw, server_hostname='im.bchongw.com') as stream:
|
||||
stream.settimeout(10)
|
||||
stream.sendall(request)
|
||||
response = b''
|
||||
while b'\r\n\r\n' not in response:
|
||||
response += stream.recv(4096)
|
||||
head, remainder = response.split(b'\r\n\r\n', 1)
|
||||
assert b' 101 ' in head.split(b'\r\n', 1)[0]
|
||||
assert first_websocket_command(stream, remainder) == 'AUTH_ACK'
|
||||
assert profile_online(target_id, viewer_token), 'connected user was reported offline'
|
||||
disconnected = False
|
||||
for _ in range(30):
|
||||
if not profile_online(target_id, viewer_token):
|
||||
disconnected = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
assert disconnected, 'closed final socket was still reported online'
|
||||
return {'targetUserId': target_id, 'viewerUserId': viewer_id, 'connected': True, 'disconnected': True}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/presence-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
before_migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in before_migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(before_migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
backup = Path('/www/backup/xingyu-presence-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
privacy_before = query(conn, """SELECT privacy.user_id,privacy.online_visible
|
||||
FROM user_privacy_settings privacy JOIN users user ON user.id=privacy.user_id
|
||||
WHERE user.is_test=1 AND user.deleted_at IS NULL ORDER BY privacy.user_id""")
|
||||
assert privacy_before, 'expected existing demonstration accounts'
|
||||
privacy_backup = backup / 'privacy-before.json'
|
||||
privacy_backup.write_text(json.dumps(privacy_before))
|
||||
os.chmod(str(privacy_backup), 0o600)
|
||||
state = {
|
||||
'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD,
|
||||
'backendSha256': new_hash, 'archiveSha256': expected,
|
||||
'changedSourceFiles': sorted(changed), 'frontendUnchanged': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': True,
|
||||
'privacyScope': 'existing is_test=1 accounts only',
|
||||
}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
privacy_changed = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == before_migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("""UPDATE user_privacy_settings privacy JOIN users user ON user.id=privacy.user_id
|
||||
SET privacy.online_visible=1 WHERE user.is_test=1 AND user.deleted_at IS NULL""")
|
||||
state['demonstrationPrivacyRowsMatched'] = cursor.rowcount
|
||||
privacy_changed = True
|
||||
for path in ['/api/v1/nearby/users', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['presence'] = verify_presence(conn, values)
|
||||
state['healthAndAuthChecks'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if privacy_changed:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.executemany('UPDATE user_privacy_settings SET online_visible=%s WHERE user_id=%s',
|
||||
[(online, user_id) for user_id, online in privacy_before])
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary restored. No database restore performed.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,240 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish seeded discovery shuffling with automatic binary rollback."""
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, WEB, database, digest, env_values, extract, query
|
||||
|
||||
OLD = '313e8216c3a225d2eb6a8b6cacb516b7cd9b35c6ef2c03d01721c8d521f7a436'
|
||||
BASE = Path('/www/server/xingyu-im/releases/nearby-distance-20260902-083423')
|
||||
LOCAL = 'http://127.0.0.1:18888'
|
||||
ALLOWED = {'backend/internal/app/social.go'}
|
||||
|
||||
|
||||
def fetch(path):
|
||||
with urllib.request.urlopen(LOCAL + path, timeout=20) as response:
|
||||
return response.status, response.headers, response.read()
|
||||
|
||||
|
||||
def health():
|
||||
for _ in range(100):
|
||||
try:
|
||||
status, _, data = fetch('/healthz')
|
||||
if status == 200 and json.loads(data)['data']['status'] == 'ok':
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('backend failed local health check')
|
||||
|
||||
|
||||
def restart():
|
||||
os.chdir('/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel/class')
|
||||
import public
|
||||
from projectModel.goModel import main as GoProject
|
||||
request = public.dict_obj()
|
||||
request.project_name = 'xingyu_im'
|
||||
manager = GoProject()
|
||||
project = manager.get_project_find('xingyu_im')
|
||||
assert project and project['project_config']['is_power_on'] == 1
|
||||
result = manager.restart_project(request)
|
||||
if not result.get('status'):
|
||||
recovered = manager.start_project(request)
|
||||
if not recovered.get('status'):
|
||||
raise RuntimeError('BaoTa could not start project')
|
||||
health()
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.random-refresh-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def encode_json(value):
|
||||
raw = json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
|
||||
|
||||
|
||||
def user_token(secret, user_id, nickname, version):
|
||||
now = int(time.time())
|
||||
header = encode_json({'alg': 'HS256', 'typ': 'JWT'})
|
||||
payload = encode_json({'role': 'user', 'name': nickname, 'ver': version, 'sub': str(user_id), 'iat': now, 'exp': now + 300})
|
||||
signing_input = (header + '.' + payload).encode()
|
||||
signature = base64.urlsafe_b64encode(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()).rstrip(b'=').decode()
|
||||
return header + '.' + payload + '.' + signature
|
||||
|
||||
|
||||
def api_json(path, token):
|
||||
request = urllib.request.Request(
|
||||
LOCAL + path,
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
assert response.status == 200
|
||||
return json.loads(response.read())['data']
|
||||
|
||||
|
||||
def item_ids(result):
|
||||
return [int(item['id']) for item in result.get('items', [])]
|
||||
|
||||
|
||||
def verify_seeded_endpoint(path, token):
|
||||
joiner = '&' if '?' in path else '?'
|
||||
first = api_json(path + joiner + 'page=1&pageSize=20&seed=1234567', token)
|
||||
repeat = api_json(path + joiner + 'page=1&pageSize=20&seed=1234567', token)
|
||||
second_page = api_json(path + joiner + 'page=2&pageSize=20&seed=1234567', token)
|
||||
changed = api_json(path + joiner + 'page=1&pageSize=20&seed=7654321', token)
|
||||
first_ids = item_ids(first)
|
||||
repeat_ids = item_ids(repeat)
|
||||
second_ids = item_ids(second_page)
|
||||
changed_ids = item_ids(changed)
|
||||
assert len(first_ids) >= 2, 'not enough rows to verify shuffling'
|
||||
assert first_ids == repeat_ids, 'same seed returned a different order'
|
||||
assert first_ids != changed_ids, 'different seeds returned the same order'
|
||||
assert not set(first_ids).intersection(second_ids), 'seeded pages overlap'
|
||||
assert len(first_ids + second_ids) == len(set(first_ids + second_ids)), 'seeded pagination contains duplicates'
|
||||
invalid = api_json(path + joiner + 'page=1&pageSize=20&seed=invalid', token)
|
||||
assert item_ids(invalid), 'invalid seed broke the normal list fallback'
|
||||
return {
|
||||
'firstPageItems': len(first_ids),
|
||||
'secondPageItems': len(second_ids),
|
||||
'sameSeedStable': True,
|
||||
'differentSeedChanged': True,
|
||||
'pagesDisjoint': True,
|
||||
}
|
||||
|
||||
|
||||
def verify_random_refresh(conn, values):
|
||||
selected = query(conn, """SELECT user.id,profile.nickname,security.token_version
|
||||
FROM users user JOIN user_profiles profile ON profile.user_id=user.id
|
||||
JOIN user_security_controls security ON security.user_id=user.id
|
||||
WHERE user.status=1 AND user.deleted_at IS NULL ORDER BY user.id LIMIT 1""")
|
||||
assert selected, 'no active user available for random-refresh verification'
|
||||
user_id, nickname, version = selected[0]
|
||||
token = user_token(values['IM_JWT_SECRET'], user_id, nickname, version)
|
||||
nearby = verify_seeded_endpoint('/api/v1/nearby/users', token)
|
||||
discover = verify_seeded_endpoint('/api/v1/discover/recommendations', token)
|
||||
return {'viewerUserId': user_id, 'nearby': nearby, 'discover': discover}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/random-refresh-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
backup = Path('/www/backup/xingyu-random-refresh-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
state = {
|
||||
'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD,
|
||||
'backendSha256': new_hash, 'archiveSha256': expected,
|
||||
'changedSourceFiles': sorted(changed), 'frontendBefore': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': False,
|
||||
}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
for path in ['/api/v1/nearby/users', '/api/v1/discover/recommendations', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['randomRefresh'] = verify_random_refresh(conn, values)
|
||||
state['healthAndAuthChecks'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary restored. No database restore was required.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish authoritative conversation read state with automatic rollback."""
|
||||
import base64
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, '/www/server/xingyu-im/ops')
|
||||
from baota_publish_test_users import BT, DOMAIN, WEB, database, digest, env_values, extract, fetch, health, query, restart
|
||||
|
||||
OLD = 'becf85bcf60f087ef6b4e52d8c55b3e47f930fb95dcf710739715ed402bf93ab'
|
||||
BASE = Path('/www/server/xingyu-im/releases/read-badge-20260901-183130')
|
||||
ALLOWED = {'backend/internal/app/im.go'}
|
||||
|
||||
|
||||
def source_hashes(archive):
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
result = {}
|
||||
for item in package.infolist():
|
||||
if item.is_dir():
|
||||
continue
|
||||
name = item.filename.replace('\\', '/')
|
||||
assert name not in result and not name.startswith('/') and '..' not in Path(name).parts
|
||||
result[name] = hashlib.sha256(package.read(item)).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def running(expected):
|
||||
pids = []
|
||||
for proc in Path('/proc').iterdir():
|
||||
if not proc.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
if os.readlink(str(proc / 'exe')) == str(BT / 'xingyu-api'):
|
||||
assert digest(proc / 'exe') == expected
|
||||
pids.append(int(proc.name))
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
assert len(pids) == 1, 'expected one running project executable'
|
||||
return pids
|
||||
|
||||
|
||||
def replace(source, stamp):
|
||||
temporary = BT / ('xingyu-api.read-badge-' + stamp)
|
||||
assert not temporary.exists()
|
||||
shutil.copy2(str(source), str(temporary))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(temporary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(temporary), 0o750)
|
||||
os.replace(str(temporary), str(BT / 'xingyu-api'))
|
||||
|
||||
|
||||
def encode_json(value):
|
||||
raw = json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
|
||||
|
||||
|
||||
def user_token(secret, user_id, nickname, version):
|
||||
now = int(time.time())
|
||||
header = encode_json({'alg': 'HS256', 'typ': 'JWT'})
|
||||
payload = encode_json({'role': 'user', 'name': nickname, 'ver': version, 'sub': str(user_id), 'iat': now, 'exp': now + 300})
|
||||
signing_input = (header + '.' + payload).encode()
|
||||
signature = base64.urlsafe_b64encode(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()).rstrip(b'=').decode()
|
||||
return header + '.' + payload + '.' + signature
|
||||
|
||||
|
||||
def verify_read_state(conn, values):
|
||||
selected = query(conn, """SELECT m.user_id,p.nickname,security.token_version,m.conversation_id,m.read_seq,c.last_seq,
|
||||
(SELECT COUNT(*) FROM im_messages unread_msg WHERE unread_msg.conversation_id=m.conversation_id
|
||||
AND unread_msg.seq>GREATEST(m.read_seq,m.clear_seq,m.join_seq) AND unread_msg.sender_id<>m.user_id
|
||||
AND unread_msg.recalled_at IS NULL AND unread_msg.admin_removed_at IS NULL)
|
||||
FROM im_conversation_members m JOIN im_conversations c ON c.id=m.conversation_id JOIN users u ON u.id=m.user_id
|
||||
JOIN user_profiles p ON p.user_id=u.id JOIN user_security_controls security ON security.user_id=u.id
|
||||
WHERE u.is_test=1 AND u.status=1 AND u.deleted_at IS NULL AND m.status=1
|
||||
ORDER BY m.user_id,m.conversation_id LIMIT 1""")
|
||||
assert selected, 'no demonstration conversation available for read-state verification'
|
||||
user_id, nickname, version, conversation_id, read_seq, last_seq, unread = selected[0]
|
||||
token = user_token(values['IM_JWT_SECRET'], user_id, nickname, version)
|
||||
body = json.dumps({'readSeq': read_seq}).encode()
|
||||
request = urllib.request.Request(
|
||||
DOMAIN + '/api/v1/im/conversations/' + str(conversation_id) + '/settings',
|
||||
data=body,
|
||||
method='PATCH',
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json', 'Content-Type': 'application/json'},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
assert response.status == 200
|
||||
data = json.loads(response.read())['data']
|
||||
assert data['success'] is True
|
||||
expected_ack_seq = last_seq if int(unread) == 0 and int(last_seq) > int(read_seq) else read_seq
|
||||
assert int(data['readSeq']) == int(expected_ack_seq)
|
||||
assert int(data['unread']) == int(unread)
|
||||
return {'userId': user_id, 'conversationId': conversation_id, 'storedReadSeq': read_seq, 'ackReadSeq': expected_ack_seq, 'unread': unread}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and digest(archive) == expected
|
||||
lock = open('/www/server/xingyu-im/ops/application-release.lock', 'a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
assert digest(BT / 'xingyu-api') == OLD, 'production changed; re-audit required'
|
||||
running(OLD)
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
stage = Path('/www/server/xingyu-im/releases/read-badge-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
old_source = source_hashes(BASE / 'backend-source.zip')
|
||||
new_source = source_hashes(stage / 'backend-source.zip')
|
||||
changed = {name for name in set(old_source) | set(new_source) if old_source.get(name) != new_source.get(name)}
|
||||
assert changed == ALLOWED, 'unreviewed source changes: ' + repr(changed)
|
||||
new_hash = digest(stage / 'xingyu-api')
|
||||
assert (stage / 'xingyu-api').read_bytes()[:4] == b'\x7fELF' and new_hash != OLD
|
||||
manifest = json.loads((stage / 'manifest.json').read_text())
|
||||
for name in ['xingyu-api', 'backend-source.zip']:
|
||||
assert digest(stage / name) == manifest['files'][name]
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
migrations = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for name, sha in migrations.items():
|
||||
assert new_source['backend/migrations/' + name] == sha
|
||||
assert len(migrations) == len([name for name in new_source if name.startswith('backend/migrations/')])
|
||||
frontend = {name: str((WEB / name).resolve()) for name in ['admin', 'app']}
|
||||
backup = Path('/www/backup/xingyu-read-badge-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api-original'))
|
||||
state = {
|
||||
'backup': str(backup), 'stage': str(stage), 'previousBackendSha256': OLD,
|
||||
'backendSha256': new_hash, 'archiveSha256': expected,
|
||||
'changedSourceFiles': sorted(changed), 'frontendBefore': frontend,
|
||||
'databaseMigrationsApplied': [], 'businessDataWrites': False,
|
||||
}
|
||||
(backup / 'before.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP_VERIFIED=' + str(backup), flush=True)
|
||||
changed_binary = False
|
||||
try:
|
||||
replace(stage / 'xingyu-api', stamp)
|
||||
changed_binary = True
|
||||
restart()
|
||||
state['runningPids'] = running(new_hash)
|
||||
assert digest(BT / 'xingyu-api') == new_hash
|
||||
assert dict(query(conn, 'SELECT version,checksum FROM schema_migrations')) == migrations
|
||||
assert {name: str((WEB / name).resolve()) for name in frontend} == frontend
|
||||
for path in ['/api/v1/im/conversations', '/admin/v1/users', '/ws']:
|
||||
try:
|
||||
fetch(path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint became public')
|
||||
state['readState'] = verify_read_state(conn, values)
|
||||
state['healthAndAuthChecks'] = True
|
||||
(backup / 'result.json').write_text(json.dumps(state, indent=2))
|
||||
print(json.dumps(state), flush=True)
|
||||
except Exception:
|
||||
if changed_binary:
|
||||
replace(backup / 'xingyu-api-original', stamp + '-rollback')
|
||||
restart()
|
||||
running(OLD)
|
||||
(backup / 'rolled-back.txt').write_text('Original binary restored. No database restore was required.\n')
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish only the missing immutable thumbnails for the fixed test-user batch."""
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, "/www/server/xingyu-im/ops")
|
||||
from baota_publish_test_users import database, env_values, query
|
||||
|
||||
BATCH = "cn-adults-20260831-v1"
|
||||
BUCKET = "gz-1349751149"
|
||||
BACKUP_ROOT = Path("/www/backup")
|
||||
LOCK = Path("/www/server/xingyu-im/ops/application-release.lock")
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def profile_marker(conn):
|
||||
rows = query(
|
||||
conn,
|
||||
"SELECT p.user_id,p.avatar_url FROM user_profiles p JOIN users u ON u.id=p.user_id "
|
||||
"WHERE u.is_test=1 AND u.test_batch=%s ORDER BY p.user_id",
|
||||
(BATCH,),
|
||||
)
|
||||
return hashlib.sha256(repr(rows).encode()).hexdigest(), rows
|
||||
|
||||
|
||||
def thumbnail_url(source):
|
||||
assert "/media/test-users/" + BATCH + "/" in source
|
||||
return re.sub(r"\.(?:jpeg|jpg|png|webp)$", "-thumb.jpg", source, flags=re.I)
|
||||
|
||||
|
||||
def publish(binary_name, expected_sha):
|
||||
assert os.geteuid() == 0
|
||||
assert re.fullmatch(r"[a-f0-9]{64}", expected_sha)
|
||||
binary = Path(binary_name).resolve()
|
||||
assert binary.parent == Path("/tmp") and binary.is_file()
|
||||
assert digest(binary) == expected_sha and binary.read_bytes()[:4] == b"\x7fELF"
|
||||
os.chmod(binary, 0o700)
|
||||
|
||||
with LOCK.open("a") as release_lock:
|
||||
fcntl.flock(release_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
values = env_values()
|
||||
assert values["IM_ENV"] == "production"
|
||||
environment = dict(os.environ, **values)
|
||||
conn, _ = database(values)
|
||||
try:
|
||||
before_hash, rows = profile_marker(conn)
|
||||
assert len(rows) == 100 and len({url for _, url in rows}) == 10
|
||||
assert query(conn, "SELECT config_value FROM system_configs WHERE config_key='storage.provider'")[0][0] == "tencent_cos"
|
||||
|
||||
base_args = [
|
||||
str(binary),
|
||||
"--confirm-database", "im",
|
||||
"--confirm-bucket", BUCKET,
|
||||
"--media-dir", "/www/wwwroot/xingyu-data/uploads",
|
||||
]
|
||||
dry_run = subprocess.run(base_args, env=environment, text=True, capture_output=True, timeout=180, check=True)
|
||||
preview = json.loads(dry_run.stdout.strip().splitlines()[-1])
|
||||
assert preview["dryRun"] is True and preview["users"] == 100 and len(preview["objects"]) == 10
|
||||
|
||||
stamp = __import__("time").strftime("%Y%m%d-%H%M%S")
|
||||
# The migration binary intentionally accepts only this audited backup prefix.
|
||||
backup = BACKUP_ROOT / ("xingyu-cos-avatars-thumbnails-" + stamp)
|
||||
completed = subprocess.run(
|
||||
base_args + ["--apply", "--backup-dir", str(backup)],
|
||||
env=environment,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=600,
|
||||
check=True,
|
||||
)
|
||||
result = json.loads(completed.stdout.strip().splitlines()[-1])
|
||||
assert result["updated"] == 0 and result["users"] == 100
|
||||
assert result["objects"] == 20 and result["publicURLsVerified"] == 20
|
||||
after_hash, after_rows = profile_marker(conn)
|
||||
assert after_hash == before_hash and after_rows == rows
|
||||
|
||||
verified = []
|
||||
for source in sorted({url for _, url in rows}):
|
||||
url = thumbnail_url(source)
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "xingyu-thumbnail-verify/1"})
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
body = response.read(128 * 1024)
|
||||
assert response.status == 200
|
||||
assert response.headers.get_content_type() == "image/jpeg"
|
||||
assert body.startswith(b"\xff\xd8") and body.endswith(b"\xff\xd9")
|
||||
assert 0 < len(body) < 128 * 1024
|
||||
verified.append({"url": url, "bytes": len(body)})
|
||||
|
||||
record = {
|
||||
"backup": str(backup),
|
||||
"binarySha256": expected_sha,
|
||||
"databaseProfilesUnchanged": True,
|
||||
"verifiedObjects": result["objects"],
|
||||
"newThumbnailObjects": len(verified),
|
||||
"thumbnails": verified,
|
||||
}
|
||||
verification = backup / "thumbnail-verification.json"
|
||||
verification.write_text(json.dumps(record, ensure_ascii=False, indent=2))
|
||||
os.chmod(verification, 0o600)
|
||||
print("PUBLISHED=" + json.dumps(record, ensure_ascii=False), flush=True)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
publish(*sys.argv[1:])
|
||||
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scoped release of the labelled 100-user fixture batch on the existing BaoTa host.
|
||||
|
||||
Run with the panel Python as root. DB credentials stay in memory; backups are
|
||||
root-only. No admin login, fabricated sessions, or OAuth migration is performed.
|
||||
"""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
|
||||
DOMAIN = 'https://im.bchongw.com'
|
||||
BATCH = 'cn-adults-20260831-v1'
|
||||
BT = Path('/www/server/xingyu-im/bt')
|
||||
WEB = Path('/www/wwwroot/im.bchongw.com')
|
||||
MEDIA = Path('/www/wwwroot/xingyu-data/uploads')
|
||||
OLD_BINARY = '23ab263e16593b6f588e42bf480e08f364f8f46a12cf8c143077b767860b8b30'
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def env_values():
|
||||
values = {}
|
||||
for line in Path('/etc/xingyu-im-bt.env').read_text().splitlines():
|
||||
line = line[7:] if line.startswith('export ') else line
|
||||
if not line.strip() or line.lstrip().startswith('#'):
|
||||
continue
|
||||
key, value = line.split('=', 1)
|
||||
parts = shlex.split(value)
|
||||
assert len(parts) <= 1
|
||||
values[key] = parts[0] if parts else ''
|
||||
assert values['IM_ENV'] == 'production'
|
||||
assert values['IM_HOST'] == '127.0.0.1' and values['IM_PORT'] == '18888'
|
||||
return values
|
||||
|
||||
|
||||
def database(values):
|
||||
match = re.fullmatch(r'([^:]+):(.*?)@tcp\(([^:]+):(\d+)\)/([^?]+)\?.*', values['IM_DB_DSN'])
|
||||
assert match and match[3] == '127.0.0.1' and match[4] == '3307' and match[5] == 'im'
|
||||
options = dict(host=match[3], port=int(match[4]), user=match[1], password=match[2], database=match[5], charset='utf8mb4', autocommit=True)
|
||||
return pymysql.connect(**options), options
|
||||
|
||||
|
||||
def query(conn, sql, args=()):
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute(sql, args)
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def fetch(path):
|
||||
with urllib.request.urlopen(DOMAIN + path, timeout=20) as response:
|
||||
return response.status, response.headers, response.read()
|
||||
|
||||
|
||||
def health():
|
||||
for _ in range(100):
|
||||
try:
|
||||
status, _, data = fetch('/healthz')
|
||||
if status == 200 and json.loads(data)['data']['status'] == 'ok':
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('backend failed health check')
|
||||
|
||||
|
||||
def restart():
|
||||
os.chdir('/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel')
|
||||
sys.path.insert(0, '/www/server/panel/class')
|
||||
import public
|
||||
from projectModel.goModel import main as GoProject
|
||||
request = public.dict_obj()
|
||||
request.project_name = 'xingyu_im'
|
||||
manager = GoProject()
|
||||
project = manager.get_project_find('xingyu_im')
|
||||
assert project and project['project_config']['is_power_on'] == 1
|
||||
result = manager.restart_project(request)
|
||||
if not result.get('status'):
|
||||
recovered = manager.start_project(request)
|
||||
if not recovered.get('status'):
|
||||
raise RuntimeError('BaoTa could not start project')
|
||||
health()
|
||||
|
||||
|
||||
def extract(archive, directory):
|
||||
directory.mkdir(mode=0o755, parents=True, exist_ok=False)
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
seen = set()
|
||||
for item in package.infolist():
|
||||
name = item.filename.replace('\\', '/')
|
||||
target = (directory / name).resolve()
|
||||
assert name not in seen and name and ':' not in name
|
||||
assert not name.startswith('/') and '..' not in Path(name).parts
|
||||
assert os.path.commonpath([str(directory.resolve()), str(target)]) == str(directory.resolve())
|
||||
assert (item.external_attr >> 16) & 0o170000 != 0o120000
|
||||
seen.add(name)
|
||||
if item.is_dir() or name.endswith('/'):
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with package.open(item) as source, target.open('xb') as output:
|
||||
shutil.copyfileobj(source, output)
|
||||
|
||||
|
||||
def switch(entry, target, stamp):
|
||||
next_link = entry.with_name(entry.name + '.next-' + stamp)
|
||||
assert not next_link.exists() and not next_link.is_symlink()
|
||||
os.symlink(str(target), str(next_link))
|
||||
os.replace(str(next_link), str(entry))
|
||||
|
||||
|
||||
def prepare_static(archive, kind, stamp):
|
||||
entry = WEB / ('admin' if kind == 'admin' else 'app')
|
||||
releases = Path('/www/wwwroot/xingyu-' + kind + '/releases')
|
||||
assert entry.is_symlink()
|
||||
previous = entry.resolve()
|
||||
assert previous.parent == releases
|
||||
release = releases / ('test-users-' + stamp)
|
||||
extract(archive, release)
|
||||
index = (release / 'index.html').read_text()
|
||||
assert ('/admin/jse/' if kind == 'admin' else '/app/assets/') in index
|
||||
if kind == 'admin':
|
||||
assert '"/admin/v1"' in (release / '_app.config.js').read_text()
|
||||
# Keep hashed resources used by tabs opened before this release.
|
||||
for folder in (['js', 'jse', 'css'] if kind == 'admin' else ['assets']):
|
||||
if not (previous / folder).is_dir():
|
||||
continue
|
||||
for source in (previous / folder).rglob('*'):
|
||||
if source.is_file():
|
||||
target = release / source.relative_to(previous)
|
||||
if not target.exists():
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(str(source), str(target))
|
||||
www = pwd.getpwnam('www')
|
||||
for path in [release] + list(release.rglob('*')):
|
||||
assert not path.is_symlink()
|
||||
os.chown(str(path), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(path), 0o755 if path.is_dir() else 0o644)
|
||||
return entry, previous, release
|
||||
|
||||
|
||||
def verify(conn):
|
||||
rows = query(conn, "SELECT p.gender,COUNT(*) FROM users u JOIN user_profiles p ON p.user_id=u.id WHERE u.is_test=1 AND u.test_batch=%s AND u.deleted_at IS NULL GROUP BY p.gender ORDER BY p.gender", (BATCH,))
|
||||
assert rows == ((1, 50), (2, 50)), rows
|
||||
count = query(conn, "SELECT COUNT(*) FROM users WHERE is_test=1 AND test_batch=%s AND phone_hash IS NULL AND phone_cipher IS NULL AND password_hash='!TEST_PROFILE_NO_LOGIN'", (BATCH,))[0][0]
|
||||
assert count == 100
|
||||
avatars = query(conn, "SELECT DISTINCT p.avatar_url FROM users u JOIN user_profiles p ON p.user_id=u.id WHERE u.is_test=1 AND u.test_batch=%s", (BATCH,))
|
||||
assert len(avatars) == 10
|
||||
for (url,) in avatars:
|
||||
assert url.startswith(DOMAIN + '/uploads/')
|
||||
status, headers, body = fetch(url[len(DOMAIN):])
|
||||
assert status == 200 and headers.get_content_type() == 'image/png' and body.startswith(b'\x89PNG\r\n\x1a\n')
|
||||
for public_path in ['/admin/', '/app/']:
|
||||
status, headers, data = fetch(public_path)
|
||||
cache_control = ','.join(headers.get_all('Cache-Control', []))
|
||||
assert status == 200 and b'<html' in data.lower() and 'no-store' in cache_control
|
||||
for private_path in ['/admin/v1/users?userType=test', '/api/v1/discover/recommendations', '/ws']:
|
||||
try:
|
||||
fetch(private_path)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
else:
|
||||
raise RuntimeError('private endpoint did not require authentication')
|
||||
health()
|
||||
return {'batch': BATCH, 'total': 100, 'male': 50, 'female': 50, 'avatarsHttp200': len(avatars), 'privateEndpointsRequireAuth': True}
|
||||
|
||||
|
||||
def publish(archive, expected):
|
||||
assert os.geteuid() == 0
|
||||
archive = Path(archive).resolve()
|
||||
assert archive.parent == Path('/tmp') and re.fullmatch('[a-f0-9]{64}', expected)
|
||||
assert digest(archive) == expected
|
||||
values = env_values()
|
||||
conn, db_options = database(values)
|
||||
assert digest(BT / 'xingyu-api') == OLD_BINARY, 'online binary changed; re-audit before deployment'
|
||||
assert query(conn, "SELECT COUNT(*) FROM schema_migrations WHERE version='027_app_oauth_login.sql'")[0][0] == 0, 'OAuth release changed; do not replace it'
|
||||
assert query(conn, "SELECT COUNT(*) FROM users WHERE public_id LIKE 'TESTCN%%'")[0][0] == 0, 'test IDs already exist; inspect before retry'
|
||||
assert query(conn, "SELECT config_value FROM system_configs WHERE config_key='storage.local.directory'")[0][0] == './uploads'
|
||||
pid = int(Path('/var/tmp/gopids/xingyu_im.pid').read_text().strip())
|
||||
assert Path('/proc/{}/cwd'.format(pid)).resolve() == BT
|
||||
assert not (BT / 'uploads').exists() and not (BT / 'uploads').is_symlink()
|
||||
assert MEDIA.is_dir()
|
||||
health()
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
backup = Path('/www/backup/xingyu-test-users-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
state = {
|
||||
'stamp': stamp, 'archiveSha256': expected, 'previousBackendSha256': OLD_BINARY,
|
||||
'usersBefore': query(conn, 'SELECT COUNT(*) FROM users')[0][0],
|
||||
'previousAdmin': str((WEB / 'admin').resolve()), 'previousH5': str((WEB / 'app').resolve()),
|
||||
'unchangedCounts': {table: query(conn, 'SELECT COUNT(*) FROM ' + table)[0][0] for table in ['orders', 'posts', 'im_messages', 'subscriptions', 'user_sessions', 'admin_users']},
|
||||
}
|
||||
# Dump only this application database using the matching MySQL 8 client.
|
||||
dump_env = dict(os.environ, MYSQL_PWD=db_options['password'])
|
||||
dump = subprocess.Popen(['/opt/mysql-8.4.11/bin/mysqldump', '-h', '127.0.0.1', '-P', '3307', '-u', db_options['user'], '--single-transaction', '--no-tablespaces', '--set-gtid-purged=OFF', '--routines', '--triggers', 'im'], env=dump_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
with gzip.open(str(backup / 'im.sql.gz'), 'wb') as output:
|
||||
shutil.copyfileobj(dump.stdout, output)
|
||||
_, errors = dump.communicate()
|
||||
if dump.returncode:
|
||||
raise RuntimeError('database backup failed: ' + errors.decode('utf-8', errors='replace'))
|
||||
os.chmod(str(backup / 'im.sql.gz'), 0o600)
|
||||
shutil.copy2(str(BT / 'xingyu-api'), str(backup / 'xingyu-api'))
|
||||
shutil.copy2('/etc/xingyu-im-bt.env', str(backup / 'environment.env'))
|
||||
os.chmod(str(backup / 'environment.env'), 0o600)
|
||||
(backup / 'state.json').write_text(json.dumps(state, indent=2))
|
||||
print('BACKUP=' + str(backup), flush=True)
|
||||
stage = Path('/www/server/xingyu-im/releases/test-users-' + stamp)
|
||||
extract(archive, stage)
|
||||
os.chmod(str(stage), 0o700)
|
||||
# Validate all deployed migrations, then add only the test-user migration.
|
||||
recorded = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
for file in (stage / 'migrations').glob('*.sql'):
|
||||
if file.name == '028_test_users.sql':
|
||||
continue
|
||||
assert recorded.get(file.name) == digest(file), 'migration history mismatch: ' + file.name
|
||||
migration = stage / 'migrations/028_test_users.sql'
|
||||
assert migration.is_file() and '028_test_users.sql' not in recorded
|
||||
sql = '\n'.join(line for line in migration.read_text().splitlines() if not line.lstrip().startswith('--'))
|
||||
for statement in sql.split(';'):
|
||||
if statement.strip():
|
||||
query(conn, statement)
|
||||
query(conn, 'INSERT INTO schema_migrations (version,checksum) VALUES (%s,%s)', (migration.name, digest(migration)))
|
||||
shutil.copy2(str(migration), str(BT / 'migrations' / migration.name))
|
||||
www = pwd.getpwnam('www')
|
||||
os.chown(str(BT / 'migrations' / migration.name), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(BT / 'migrations' / migration.name), 0o640)
|
||||
# The existing local-storage config is relative to the BaoTa working dir.
|
||||
# Preserve that config and make it point at the established persistent data dir.
|
||||
os.symlink(str(MEDIA), str(BT / 'uploads'))
|
||||
admin = prepare_static(stage / 'admin.zip', 'admin', stamp)
|
||||
h5 = prepare_static(stage / 'h5.zip', 'h5', stamp)
|
||||
switched = []
|
||||
try:
|
||||
new_binary = BT / ('xingyu-api.next-' + stamp)
|
||||
shutil.copy2(str(stage / 'xingyu-api'), str(new_binary))
|
||||
os.chown(str(new_binary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(new_binary), 0o750)
|
||||
os.replace(str(new_binary), str(BT / 'xingyu-api'))
|
||||
restart()
|
||||
for entry, previous, release in [admin, h5]:
|
||||
switch(entry, release, stamp)
|
||||
switched.append((entry, previous))
|
||||
for _, _, release in [admin, h5]:
|
||||
prefix = '/admin/' if release == admin[2] else '/app/'
|
||||
assert fetch(prefix)[2] == (release / 'index.html').read_bytes()
|
||||
seeder = stage / 'seed-test-users'
|
||||
os.chmod(str(seeder), 0o700)
|
||||
seed_env = dict(os.environ, **values)
|
||||
command = [str(seeder), '--apply', '--allow-production-test-data', '--confirm-database', 'im', '--public-base', DOMAIN + '/uploads', '--avatars-dir', str(stage / 'avatars'), '--media-dir', str(MEDIA)]
|
||||
result = subprocess.run(command, env=seed_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=90)
|
||||
if result.returncode:
|
||||
raise RuntimeError('seed failed: ' + result.stderr)
|
||||
imported = json.loads(result.stdout)
|
||||
assert imported['created'] == 100 and imported['male'] == 50 and imported['female'] == 50
|
||||
report = verify(conn)
|
||||
assert query(conn, 'SELECT COUNT(*) FROM users WHERE is_test=0')[0][0] == state['usersBefore']
|
||||
for table, count in state['unchangedCounts'].items():
|
||||
assert query(conn, 'SELECT COUNT(*) FROM ' + table)[0][0] == count, 'unexpected change to ' + table
|
||||
repeat = subprocess.run(command, env=seed_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=90)
|
||||
assert repeat.returncode == 0
|
||||
repeated = json.loads(repeat.stdout)
|
||||
assert repeated['created'] == 0 and repeated['skipped'] == 100
|
||||
state.update(report)
|
||||
state.update({'backendSha256': digest(BT / 'xingyu-api'), 'admin': str(admin[2]), 'h5': str(h5[2]), 'idempotencySkipped': 100, 'seedResult': imported, 'backup': str(backup), 'stage': str(stage)})
|
||||
(backup / 'result.json').write_text(json.dumps(state, ensure_ascii=False, indent=2))
|
||||
print(json.dumps(state, ensure_ascii=False), flush=True)
|
||||
except Exception:
|
||||
# Keep additive schema and fixture data for diagnosis; never restore a
|
||||
# full DB dump over users who may have registered during deployment.
|
||||
for entry, previous in reversed(switched):
|
||||
switch(entry, previous, stamp + '-rollback')
|
||||
restore = BT / ('xingyu-api.rollback-' + stamp)
|
||||
shutil.copy2(str(backup / 'xingyu-api'), str(restore))
|
||||
os.chown(str(restore), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(restore), 0o750)
|
||||
os.replace(str(restore), str(BT / 'xingyu-api'))
|
||||
restart()
|
||||
print('APPLICATION_ROLLED_BACK; additive schema/data retained; backup=' + str(backup), flush=True)
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def resume(backup_path):
|
||||
"""Resume this exact backed-up release after an application-only rollback.
|
||||
|
||||
No migration, initial import, environment change, or DB restoration occurs.
|
||||
The original preflight deliberately rejects retries after a partial release.
|
||||
"""
|
||||
assert os.geteuid() == 0
|
||||
backup = Path(backup_path).resolve()
|
||||
assert backup.parent == Path('/www/backup')
|
||||
assert re.fullmatch(r'xingyu-test-users-\d{8}-\d{6}', backup.name)
|
||||
state = json.loads((backup / 'state.json').read_text())
|
||||
stamp = state['stamp']
|
||||
assert backup.name == 'xingyu-test-users-' + stamp
|
||||
stage = Path('/www/server/xingyu-im/releases/test-users-' + stamp)
|
||||
archive = Path('/tmp/xingyu-test-users-20260831.zip')
|
||||
assert digest(archive) == state['archiveSha256']
|
||||
with zipfile.ZipFile(str(archive)) as package:
|
||||
for name in ['xingyu-api', 'seed-test-users', 'admin.zip', 'h5.zip', 'migrations/028_test_users.sql']:
|
||||
matching = [item for item in package.infolist() if item.filename.replace('\\', '/') == name]
|
||||
assert len(matching) == 1
|
||||
assert digest(stage / name) == hashlib.sha256(package.read(matching[0])).hexdigest()
|
||||
assert digest(BT / 'xingyu-api') == OLD_BINARY == state['previousBackendSha256']
|
||||
assert (BT / 'uploads').is_symlink() and (BT / 'uploads').resolve() == MEDIA
|
||||
admin = (WEB / 'admin', Path(state['previousAdmin']), Path('/www/wwwroot/xingyu-admin/releases/test-users-' + stamp))
|
||||
h5 = (WEB / 'app', Path(state['previousH5']), Path('/www/wwwroot/xingyu-h5/releases/test-users-' + stamp))
|
||||
for entry, previous, release in [admin, h5]:
|
||||
assert entry.is_symlink() and entry.resolve() == previous
|
||||
assert previous.parent == release.parent
|
||||
assert (release / 'index.html').is_file()
|
||||
values = env_values()
|
||||
conn, _ = database(values)
|
||||
recorded = dict(query(conn, 'SELECT version,checksum FROM schema_migrations'))
|
||||
assert '027_app_oauth_login.sql' not in recorded
|
||||
assert recorded['028_test_users.sql'] == digest(stage / 'migrations/028_test_users.sql')
|
||||
health()
|
||||
# The complete fixture import must already exist. The seeder's transactional
|
||||
# repeat check is a no-op and refuses partial/modified/conflicting batches.
|
||||
assert query(conn, 'SELECT COUNT(*) FROM users WHERE is_test=1 AND test_batch=%s', (BATCH,))[0][0] == 100
|
||||
command = [str(stage / 'seed-test-users'), '--apply', '--allow-production-test-data', '--confirm-database', 'im', '--public-base', DOMAIN + '/uploads', '--avatars-dir', str(stage / 'avatars'), '--media-dir', str(MEDIA)]
|
||||
repeated = subprocess.run(command, env=dict(os.environ, **values), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=90)
|
||||
assert repeated.returncode == 0, 'existing fixture batch failed repeat verification'
|
||||
imported = json.loads(repeated.stdout)
|
||||
assert imported['created'] == 0 and imported['skipped'] == 100
|
||||
switched = []
|
||||
www = pwd.getpwnam('www')
|
||||
try:
|
||||
new_binary = BT / ('xingyu-api.resume-' + stamp)
|
||||
assert not new_binary.exists()
|
||||
shutil.copy2(str(stage / 'xingyu-api'), str(new_binary))
|
||||
os.chown(str(new_binary), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(new_binary), 0o750)
|
||||
os.replace(str(new_binary), str(BT / 'xingyu-api'))
|
||||
restart()
|
||||
for entry, previous, release in [admin, h5]:
|
||||
switch(entry, release, stamp + '-resume')
|
||||
switched.append((entry, previous))
|
||||
assert fetch('/admin/')[2] == (admin[2] / 'index.html').read_bytes()
|
||||
assert fetch('/app/')[2] == (h5[2] / 'index.html').read_bytes()
|
||||
state.update(verify(conn))
|
||||
assert query(conn, 'SELECT COUNT(*) FROM users WHERE is_test=0')[0][0] == state['usersBefore']
|
||||
for table, count in state['unchangedCounts'].items():
|
||||
assert query(conn, 'SELECT COUNT(*) FROM ' + table)[0][0] == count, 'unexpected change to ' + table
|
||||
state.update({'backendSha256': digest(BT / 'xingyu-api'), 'admin': str(admin[2]), 'h5': str(h5[2]), 'idempotencySkipped': 100, 'repeatSeedResult': imported, 'backup': str(backup), 'stage': str(stage), 'resumedAfterCacheHeaderCheckFix': True})
|
||||
(backup / 'result.json').write_text(json.dumps(state, ensure_ascii=False, indent=2))
|
||||
print(json.dumps(state, ensure_ascii=False), flush=True)
|
||||
except Exception:
|
||||
for entry, previous in reversed(switched):
|
||||
switch(entry, previous, stamp + '-resume-rollback')
|
||||
restore = BT / ('xingyu-api.resume-rollback-' + stamp)
|
||||
shutil.copy2(str(backup / 'xingyu-api'), str(restore))
|
||||
os.chown(str(restore), www.pw_uid, www.pw_gid)
|
||||
os.chmod(str(restore), 0o750)
|
||||
os.replace(str(restore), str(BT / 'xingyu-api'))
|
||||
restart()
|
||||
print('APPLICATION_ROLLED_BACK; imported fixtures retained', flush=True)
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('archive', nargs='?')
|
||||
parser.add_argument('sha256', nargs='?')
|
||||
parser.add_argument('--resume-backup')
|
||||
args = parser.parse_args()
|
||||
if args.resume_backup:
|
||||
assert not args.archive and not args.sha256
|
||||
resume(args.resume_backup)
|
||||
else:
|
||||
assert args.archive and args.sha256
|
||||
publish(args.archive, args.sha256)
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Register the existing project database in BaoTa without changing MySQL data."""
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
PANEL = Path('/www/server/panel')
|
||||
if os.geteuid() != 0 or not PANEL.is_dir():
|
||||
raise SystemExit('Run on the BaoTa host as root.')
|
||||
os.chdir(str(PANEL))
|
||||
sys.path.insert(0, str(PANEL))
|
||||
sys.path.insert(0, str(PANEL / 'class'))
|
||||
import public
|
||||
import database
|
||||
|
||||
dsn = None
|
||||
for line in Path('/etc/xingyu-im.env').read_text().splitlines():
|
||||
if line.startswith('IM_DB_DSN='):
|
||||
dsn = shlex.split(line.split('=', 1)[1])[0]
|
||||
assert dsn is not None
|
||||
credentials, endpoint = dsn.split('@tcp(', 1)
|
||||
username, password = credentials.split(':', 1)
|
||||
address, database_part = endpoint.split(')/', 1)
|
||||
host, port = address.rsplit(':', 1)
|
||||
name = database_part.split('?', 1)[0]
|
||||
assert host == '127.0.0.1' and port == '3307'
|
||||
assert name.lower() == 'im'
|
||||
|
||||
existing = public.M('databases').where("name=? AND LOWER(type)=LOWER('mysql')", (name,)).find()
|
||||
if not existing:
|
||||
backup = Path('/www/backup/xingyu-panel-takeover-database-' + time.strftime('%Y%m%d-%H%M%S'))
|
||||
backup.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
os.chmod(str(backup), 0o700)
|
||||
with sqlite3.connect(str(PANEL / 'data/db/database.db')) as connection:
|
||||
with sqlite3.connect(str(backup / 'database.db')) as destination:
|
||||
connection.backup(destination)
|
||||
get = public.dict_obj()
|
||||
get.db_host = host
|
||||
get.db_port = int(port)
|
||||
get.db_user = username
|
||||
get.db_name = name
|
||||
get.db_password = password
|
||||
get.db_ps = '星遇 IM · 独立 MySQL 8.4 · 127.0.0.1:3307'
|
||||
result = database.database().AddCloudDatabase(get)
|
||||
if not result.get('status'):
|
||||
raise RuntimeError('BaoTa database registration failed; no business data has been modified.')
|
||||
|
||||
record = public.M('databases').where("name=? AND LOWER(type)=LOWER('mysql')", (name,)).find()
|
||||
config = json.loads(record['conn_config'])
|
||||
assert config['db_host'] == host and int(config['db_port']) == int(port)
|
||||
assert config['db_name'] == name
|
||||
check = public.dict_obj()
|
||||
for key, value in config.items():
|
||||
setattr(check, key, value)
|
||||
assert database.database().CheckCloudDatabase(check) is True
|
||||
print(json.dumps({'status': 'DATABASE_REGISTERED_AND_CONNECTED', 'database': name,
|
||||
'panel_id': record['id'], 'host': host, 'port': int(port)}, ensure_ascii=False))
|
||||
@@ -74,6 +74,7 @@ services:
|
||||
args:
|
||||
VITE_API_ORIGIN: https://${API_DOMAIN}
|
||||
VITE_WS_ORIGIN: wss://${API_DOMAIN}
|
||||
VITE_ADMIN_API_URL: ${ADMIN_API_URL:-/admin/v1}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
api:
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
# im.bchongw.com 正式环境部署记录
|
||||
|
||||
初次部署日期:2026-08-30
|
||||
宝塔项目接管及 H5 发布日期:2026-08-31
|
||||
运行方式:宝塔 Go 项目(域名、HTTPS、管理端/H5 网关)+ 独立 MySQL 8.4 LTS(非 Docker)
|
||||
|
||||
此前 Go 服务由独立 systemd 管理,没有出现在宝塔 Go 项目列表。现已纠正:后端的启动、停止、重启、日志和开机启动均纳入宝塔 Go 项目管理;原 systemd 服务已停止并禁用,保留用于回滚。
|
||||
|
||||
2026-08-31 已进一步将域名与 HTTPS 从原 HTML 网关迁入 Go 项目:`xingyu_im` 直接绑定 `im.bchongw.com:80`,开启外网映射和 HTTPS(443),HTTP 强制跳转 HTTPS。原 HTML 网关的项目记录已合并,网页文件、发布版本、证书及业务数据全部保留,没有重复绑定同一域名。
|
||||
|
||||
## 在宝塔哪里操作
|
||||
|
||||
| 宝塔入口 | 项目 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| 网站 → Go 项目 | `xingyu_im` | 后端启停/重启、运行日志、环境文件、域名管理、外网映射、SSL 和管理端/H5/API/WSS 网关 |
|
||||
| 数据库 → MySQL | `im`(远程数据库类型,实际连接本机 `127.0.0.1:3307`) | 查看与管理现有 IM 数据库 |
|
||||
|
||||
关闭已打开的设置窗口并刷新宝塔项目列表,进入 `xingyu_im → 域名管理` 即可看到 `im.bchongw.com`、端口 `80`;`SSL` 中可看到有效证书和强制 HTTPS 状态。这里的端口 80 是域名绑定入口,不表示关闭 HTTPS;SSL 监听端口为 443。
|
||||
|
||||
## 对外地址
|
||||
|
||||
- API:`https://im.bchongw.com`
|
||||
- 健康检查:`https://im.bchongw.com/healthz`
|
||||
- WebSocket:`wss://im.bchongw.com/ws`
|
||||
- 管理端网页:`https://im.bchongw.com/admin/`
|
||||
- uni-app H5:`https://im.bchongw.com/app/`
|
||||
- 管理 API:`https://im.bchongw.com/admin/v1`
|
||||
|
||||
HTTP 会永久重定向到 HTTPS。后端和独立数据库只监听本机回环地址,不直接暴露到公网。
|
||||
|
||||
## 服务与目录
|
||||
|
||||
| 项目 | 值 |
|
||||
| --- | --- |
|
||||
| 宝塔 Go 项目 | `xingyu_im` |
|
||||
| Go 监听地址 | `127.0.0.1:18888` |
|
||||
| 当前可执行文件 | `/www/server/xingyu-im/bt/xingyu-api` |
|
||||
| 启动命令 | `/www/server/xingyu-im/bt/start.sh` |
|
||||
| 后端生效环境文件 | `/etc/xingyu-im-bt.env`(`root:www 0640`) |
|
||||
| Go 运行用户 | `www` |
|
||||
| Go 日志 | `/www/wwwlogs/go/xingyu_im.log` |
|
||||
| 运维/接管脚本 | `/www/server/xingyu-im/ops`(仅 root 可访问) |
|
||||
| 旧 systemd 服务 | `xingyu-im.service`,已停止并禁用,不能与宝塔 Go 项目同时启动 |
|
||||
| 旧后端版本/环境备份 | `/www/server/xingyu-im/releases/20260830-1345`、`/etc/xingyu-im.env` |
|
||||
| 上传目录 | `/www/wwwroot/xingyu-data/uploads` |
|
||||
| 宝塔站点目录 | `/www/wwwroot/im.bchongw.com` |
|
||||
| Go 项目绑定域名 | `im.bchongw.com:80`,外网映射已开启 |
|
||||
| 宝塔 Nginx 主配置 | `/www/server/panel/vhost/nginx/go_xingyu_im.conf` |
|
||||
| 管理端/H5/WS 路由扩展配置 | `/www/server/panel/vhost/nginx/extension/xingyu_im/xingyu_routes.conf` |
|
||||
| Go 项目证书目录 | `/www/server/panel/vhost/cert/xingyu_im`(证书文件链接到 Let's Encrypt 自动续签目录) |
|
||||
| 网站访问日志 | `/www/wwwlogs/xingyu_im.log` |
|
||||
| 管理端发布根目录 | `/www/wwwroot/xingyu-admin/releases` |
|
||||
| 管理端当前版本 | `/www/wwwroot/xingyu-admin/releases/20260831-095050` |
|
||||
| 管理端入口软链接 | `/www/wwwroot/im.bchongw.com/admin` |
|
||||
| H5 当前版本 | `/www/wwwroot/xingyu-h5/releases/20260831-091056` |
|
||||
| H5 入口软链接 | `/www/wwwroot/im.bchongw.com/app` |
|
||||
| MySQL 服务 | `xingyu-mysql8.service` |
|
||||
| MySQL 版本 | `8.4.11 LTS` |
|
||||
| MySQL 监听地址 | `127.0.0.1:3307` |
|
||||
| MySQL 配置 | `/etc/xingyu-mysql8.cnf` |
|
||||
| MySQL 数据目录 | `/www/server/xingyu-mysql8-data` |
|
||||
|
||||
服务器原有宝塔 MySQL 5.6 保持不变;项目使用独立 MySQL 8.4 实例,避免影响现有网站。该实例通过宝塔自带的“添加远程数据库”功能接入,数据库条目 ID 为 `3`,没有重新建库或迁移业务数据。MySQL 8 实例本身仍由 `xingyu-mysql8.service` 托管;不要通过宝塔软件商店替换原有 MySQL 5.6。
|
||||
|
||||
## 常用运维命令
|
||||
|
||||
```bash
|
||||
cd /www/server/panel
|
||||
./pyenv/bin/python /www/server/xingyu-im/ops/baota_panel_takeover.py status
|
||||
./pyenv/bin/python /www/server/xingyu-im/ops/baota_bind_go_domain.py verify
|
||||
systemctl status xingyu-mysql8 --no-pager
|
||||
tail -n 200 /www/wwwlogs/go/xingyu_im.log
|
||||
curl -fsS http://127.0.0.1:18888/healthz
|
||||
curl -fsS https://im.bchongw.com/healthz
|
||||
/www/server/nginx/sbin/nginx -t
|
||||
```
|
||||
|
||||
后端重启:在宝塔“网站 → Go 项目 → xingyu_im”中点“重启”。不要再执行 `systemctl restart xingyu-im`。启动脚本会等待旧 Go 进程释放 18888 端口,已修复宝塔立即重启与 go-zero 优雅退出产生的端口冲突。
|
||||
|
||||
只重新加载 Nginx:
|
||||
|
||||
```bash
|
||||
/etc/init.d/nginx reload
|
||||
```
|
||||
|
||||
验收脚本(会实际重启一次后端,维护窗口使用):
|
||||
|
||||
```bash
|
||||
cd /www/server/panel
|
||||
./pyenv/bin/python /www/server/xingyu-im/ops/baota_panel_takeover.py verify
|
||||
```
|
||||
|
||||
## 管理员凭据
|
||||
|
||||
初始管理员用户名和密码保存在服务器 root 专用文件:
|
||||
|
||||
```text
|
||||
/root/.xingyu-initial-credentials
|
||||
```
|
||||
|
||||
文件权限为 `0600`。首次登录后应在管理端修改密码;引导密码已从 `/etc/xingyu-im.env` 清空,不会在服务重启时重复创建管理员。
|
||||
|
||||
## HTTPS 与续签
|
||||
|
||||
- 证书:Let's Encrypt
|
||||
- 当前到期时间:2026-11-28
|
||||
- 自动续签:`certbot-renew.timer`
|
||||
- Nginx 重载钩子:`/etc/letsencrypt/renewal-hooks/deploy/reload-baota-nginx`
|
||||
- Go 项目证书文件:`/www/server/panel/vhost/cert/xingyu_im/fullchain.pem`、`privkey.pem`,软链接到 `/etc/letsencrypt/live/im.bchongw.com/` 下的同名文件,续签后无需手动复制。
|
||||
- ACME 验证目录:`/www/wwwroot/im.bchongw.com`;Go 路由扩展保留 `/.well-known/acme-challenge/` 的静态验证入口。
|
||||
- 2026-08-31 域名迁入 Go 项目后,再次执行证书续签 dry-run 成功。
|
||||
|
||||
当前续签由 Certbot 负责。不要同时另建一套宝塔自动申请任务;如果以后改用宝塔托管申请,应先安排切换续签机制和证书路径。
|
||||
|
||||
检查续签任务:
|
||||
|
||||
```bash
|
||||
systemctl status certbot-renew.timer --no-pager
|
||||
certbot renew --dry-run --no-random-sleep-on-renew
|
||||
```
|
||||
|
||||
## 前端生产配置
|
||||
|
||||
uni-app:
|
||||
|
||||
```dotenv
|
||||
VITE_API_ORIGIN=https://im.bchongw.com
|
||||
VITE_WS_ORIGIN=wss://im.bchongw.com
|
||||
VITE_H5_BASE=/app/
|
||||
```
|
||||
|
||||
以上配置保存在项目 `mobile/.env.production`;开发模式仍默认使用本机接口和根路径。运行 `pnpm type-check` 与 `pnpm build:h5` 后,产物位于 `mobile/dist/build/h5`。
|
||||
|
||||
管理端:
|
||||
|
||||
```dotenv
|
||||
VITE_BASE=/admin/
|
||||
VITE_GLOB_API_URL=/admin/v1
|
||||
```
|
||||
|
||||
管理端和 API 使用同一域名,采用相对接口地址,避免跨域配置和域名切换造成的构建耦合。
|
||||
|
||||
当前后端 CORS 仅允许 `https://im.bchongw.com`。H5 或管理端部署到其他正式域名后,需要把对应 HTTPS Origin 追加到 `/etc/xingyu-im-bt.env` 的 `IM_ALLOWED_ORIGINS`,再到宝塔 Go 项目中重启。此文件使用 `export KEY=value` 格式,包含密钥,不能放到网站根目录或公开下载。
|
||||
|
||||
管理端、H5、WebSocket 及 ACME 路由保存在上述 `xingyu_routes.conf` 扩展中,由宝塔 Go 项目主配置自动包含。维护这些路由时编辑扩展文件,执行 `nginx -t` 成功后再重载。H5 发布脚本 `baota_publish_h5.py` 已兼容此布局;不要重新创建同域名的 HTML 项目。
|
||||
|
||||
### 2026-08-31 管理端登录后 404 修复
|
||||
|
||||
根因不是缺少伪静态:管理端使用 hash 路由,`#/analytics` 不会发送给 Nginx。原代码的业务路由使用 `dashboard:view` 等权限码作为 `meta.authority`,但路由守卫传入的是 `super` 等角色名,导致已授权页面被错误过滤。
|
||||
|
||||
本次修改:
|
||||
|
||||
- 路由初始化从 `/admin/v1/auth/codes` 获取最新权限码,按权限码生成本地业务路由;不再混用角色名,也不受旧浏览器“后端菜单模式”偏好影响。
|
||||
- 刷新页面重新加载权限,替换过期的权限缓存;保留登录后回到原深链接的行为。
|
||||
- 账号安全页面同样要求登录,仅登录和第三方回调页面公开。
|
||||
- 新增 7 项路由回归测试;加上原有权限/路由测试,共 18 项通过。类型检查和生产构建通过。
|
||||
- 新包 SHA-256:`d6fa3ed37a710222dabee9c7e72812f8fe1c4821ff31a1014f484ca4c0b8791b`。
|
||||
- 新版本通过原子切换 `admin` 软链接上线,旧版 `/www/wwwroot/xingyu-admin/releases/20260830-142433` 保留用于回滚;新目录兼容保留旧版散列资源,避免尚未刷新的标签页加载旧资源时 404。
|
||||
- 已验证线上登录页面可渲染、新入口/仪表盘 JS 返回 200、入口 HTML 不缓存、API 健康检查和 H5 正常。新版本的生产管理员实际登录及登录后界面验收尚待用户授权;未通过其他方式绕过登录限制。
|
||||
|
||||
管理端发布脚本:`/www/server/xingyu-im/ops/baota-publish-admin.sh`。上传构建包至 `/tmp` 后,使用 root 执行:
|
||||
|
||||
```bash
|
||||
bash /www/server/xingyu-im/ops/baota-publish-admin.sh /tmp/admin-build.zip <构建包SHA256>
|
||||
```
|
||||
|
||||
脚本校验构建包、保留旧版本并原子切换网页入口;验证失败自动切回旧版本,不重启 Go、不修改数据库或 Nginx 配置。升级后已打开的管理端页面需要刷新(必要时使用 `Ctrl+F5`)加载新路由代码。
|
||||
|
||||
## 验收结果
|
||||
|
||||
- 后端单元测试通过并使用 Linux/amd64 静态二进制发布。
|
||||
- 发布文件 SHA-256:`23ab263e16593b6f588e42bf480e08f364f8f46a12cf8c143077b767860b8b30`。
|
||||
- 数据库迁移 `001` 至 `026` 全部执行成功,共 66 张业务表。
|
||||
- 本机和公网健康检查均返回 HTTP 200。
|
||||
- HTTPS 证书链和域名校验通过。
|
||||
- 未认证 WSS 握手返回 HTTP 401,证明 WSS 反向代理已进入后端鉴权层。
|
||||
- 管理员登录、JWT 会话、RBAC 仪表盘接口通过。
|
||||
- 会员套餐公开接口返回 3 个初始套餐。
|
||||
- 自动续签 dry-run 成功。
|
||||
- Go 项目已设置宝塔开机启动/守护,MySQL 8 服务已设置 systemd 开机启动;本次未执行整机重启测试。
|
||||
- 新增 `/swap-xingyu` 1 GB Swap 作为 OOM 保护,`vm.swappiness=10`。
|
||||
- 首次管理端发布的 Vue/TypeScript 类型检查及生产构建通过,原生产包 SHA-256:`404b42391f201e4f500f16275941594ae1569459aa44617c8466b021571dcb3f`;当前包见上述登录 404 修复记录。
|
||||
- 管理端首页、SPA 路由回退、运行时接口配置和管理员登录 API 均通过线上验收。
|
||||
- 真实浏览器访问自动进入 `https://im.bchongw.com/admin/#/auth/login`,页面控制台无错误、无警告。
|
||||
- 上一版管理端保留在 `/www/wwwroot/xingyu-admin/releases/20260830-1410`,可通过切换入口软链接快速回滚。
|
||||
- 2026-08-31 已通过宝塔原生 Go 项目接口执行重启,PID 发生变化,随后本机及公网健康检查恢复正常。
|
||||
- 宝塔 Go 列表接口返回 `xingyu_im`、`run=true`、`listen=[18888]`、`listen_ok=true`。
|
||||
- 域名迁入后,宝塔 Go 项目域名接口返回 `im.bchongw.com:80`,外网映射开启;Go 项目 SSL 接口返回证书已启用、强制 HTTPS 已启用、证书到期日 2026-11-28。
|
||||
- 域名迁入后,HTTP 健康检查返回 301,HTTPS 健康检查、`/admin/`、`/app/` 均返回 200,未认证 WSS 请求返回 401;证书模拟续签再次通过。本次只平滑重载 Nginx,未重启后端或迁移数据库。
|
||||
- 宝塔数据库连接验证通过,IM 业务表数量保持 66 张;原有网站和数据库未替换。
|
||||
- H5 类型检查与生产构建通过,发布包 SHA-256:`04f02657050cf0fa4e6d97d3736ec995255f6aef14672048a76266297ff759b0`。
|
||||
- H5 启动页 → 登录页真实浏览器跳转通过,生产页面使用 `/app/` 资源基址;favicon 返回 HTTP 200,H5/管理端控制台无错误、无警告。
|
||||
- 宝塔面板 URL 使用自签名证书,自动浏览器被证书校验阻止;面板项目列表、数据库连接及启停采用该服务器实际安装的宝塔模块接口验证,未绕过浏览器证书校验。
|
||||
|
||||
## 本次接管回滚备份
|
||||
|
||||
- 后端、原站点记录及面板数据库快照:`/www/backup/xingyu-panel-takeover-20260831-085613`
|
||||
- H5 发布前 Nginx 配置:`/www/backup/xingyu-h5-publish-20260831-091056`
|
||||
- 域名迁入 Go 项目前的项目/域名记录、面板站点数据库快照和原 HTML Nginx 配置:`/www/backup/xingyu-go-domain-20260831-092720`
|
||||
- 原后端二进制和原环境文件仍保留;不要在宝塔 Go 项目运行时启动旧 systemd 服务,以免抢占同一端口。
|
||||
- 面板数据库快照仅用于灾难恢复,不能直接覆盖当前面板数据库,否则会覆盖其他站点后续变更。正常回滚应仅还原本项目的记录和配置。
|
||||
|
||||
## 备份范围
|
||||
|
||||
至少备份以下内容:
|
||||
|
||||
```text
|
||||
/www/server/xingyu-mysql8-data
|
||||
/www/wwwroot/xingyu-data/uploads
|
||||
/etc/xingyu-im.env
|
||||
/etc/xingyu-im-bt.env
|
||||
/etc/xingyu-mysql8.cnf
|
||||
/www/server/xingyu-im/releases
|
||||
/www/server/xingyu-im/bt
|
||||
/www/server/xingyu-im/ops
|
||||
/www/wwwroot/xingyu-admin/releases
|
||||
/www/wwwroot/xingyu-h5/releases
|
||||
/www/server/panel/vhost/nginx/go_xingyu_im.conf
|
||||
/www/server/panel/vhost/nginx/extension/xingyu_im
|
||||
/www/server/panel/vhost/cert/xingyu_im
|
||||
/www/server/panel/data/db/site.db
|
||||
/www/server/panel/data/db/database.db
|
||||
/etc/letsencrypt
|
||||
/root/.xingyu-initial-credentials
|
||||
```
|
||||
|
||||
所有包含密钥或密码的备份必须加密并限制访问。
|
||||
|
||||
## 2026-08-31 测试用户同步上线
|
||||
|
||||
本次仅发布测试用户相关功能到现有宝塔 Go 项目和同域名管理端/H5,没有迁移托管环境,也没有改变支付、短信、对象存储或第三方登录的配置值。
|
||||
|
||||
### 数据与显示规则
|
||||
|
||||
- 已在生产 `im` 库导入批次 `cn-adults-20260831-v1`,共 **100 人:男 50、女 50**;本次 ID 为 1–100,公开编号为 `TESTCN000001` 至 `TESTCN000100`。
|
||||
- 每条资料均为 `is_test=1`,有独立的 `test_batch` 字段,昵称带 `测试·` 前缀,个人简介注明虚构测试资料。管理端支持按“测试用户 / 正式注册用户”和批次筛选,客户端的推荐、附近、用户列表和个人主页显示测试标签。
|
||||
- 头像为 **10 张 AI 生成的虚构中国成年人肖像(5 男、5 女),每张复用 10 次**,并非 100 张不同头像,也非真实用户照片。生成来源说明保存在发布目录 `avatar-provenance.json`。
|
||||
- 仅创建用户、资料及隐私设置,不创建手机号、有效登录密码、登录会话、实名认证、付费会员、订单、动态或聊天记录。隐私设置关闭虚构在线状态、最后活跃时间和距离展示。
|
||||
- 导入前正式注册用户为 0;导入后仍为 0。管理端的正式用户、新增、活跃和资料完善率统计排除测试用户,另行显示测试用户数量。
|
||||
- 重复运行已验证:`created=0, skipped=100`,不会重复新增或覆盖已存在的资料。
|
||||
|
||||
### 发布与备份位置
|
||||
|
||||
| 内容 | 位置 |
|
||||
| --- | --- |
|
||||
| 发布前数据库、后端、环境文件和发布状态备份 | `/www/backup/xingyu-test-users-20260831-113046` |
|
||||
| 发布结果记录 | `/www/backup/xingyu-test-users-20260831-113046/result.json` |
|
||||
| 新后端、导入工具、头像、迁移和前端压缩包 | `/www/server/xingyu-im/releases/test-users-20260831-113046` |
|
||||
| 新管理端目录 | `/www/wwwroot/xingyu-admin/releases/test-users-20260831-113046` |
|
||||
| 新 H5 目录 | `/www/wwwroot/xingyu-h5/releases/test-users-20260831-113046` |
|
||||
| 上一管理端目录(保留) | `/www/wwwroot/xingyu-admin/releases/20260831-095050` |
|
||||
| 上一 H5 目录(保留) | `/www/wwwroot/xingyu-h5/releases/20260831-091056` |
|
||||
| 发布脚本 | `/www/server/xingyu-im/ops/baota_publish_test_users.py` |
|
||||
|
||||
发布包 SHA-256:`9a783aef2f6b37d025a0e33454081d43136f06a863c2c80cb9c87e973627933a`。
|
||||
|
||||
后端 SHA-256:`92b306000ab787e2eb20e69daf25cc3374d082a88f7301e24811a2b7d0022d9d`。
|
||||
|
||||
管理端 ZIP SHA-256:`eafa92003b31ce78ca24b28576c4dfc5e45a99754de5d004b3c0727575b71e30`。
|
||||
|
||||
H5 ZIP SHA-256:`e10e213e293776c67f8e248eaf2d56735bd122ce6d279a6a156efc2cccce0b57`。
|
||||
|
||||
### 迁移和运行目录注意事项
|
||||
|
||||
生产原有迁移 001–026 校验一致,本次仅新增执行 **028_test_users.sql**。工作区中另一批原生 App 第三方登录功能未合并到本次后端发布,**027_app_oauth_login.sql 仍未执行**。不要因版本号存在间隔而直接补执行它,后续发布该功能应单独评估、部署和验证。
|
||||
|
||||
发布目录中的 `backend-source.zip` 是本次实际构建的后端源码快照,已隔离未发布的原生 OAuth 改动;本地对应源码目录为 `.tools/test-users-release-20260831/backend`。当前开发工作区并不等同于这份生产快照,不能以最新的工作区内容代替本次发布产物复现。管理端和 H5 以本次归档的 ZIP 和上述哈希为准;本地 `dist` 可能被后续构建替换。
|
||||
|
||||
H5 的 OAuth 请求已兼容线上严格 JSON 解码:不发送空 `appProof` 或 H5 不需要的 `platform` 字段;有值的原生 App 字段仍保留在开发源码中。
|
||||
|
||||
发现线上存储配置为 `storage.local.directory=./uploads`,宝塔实际工作目录为 `/www/server/xingyu-im/bt`,该相对目录原先不存在。本次创建软链接:
|
||||
|
||||
```text
|
||||
/www/server/xingyu-im/bt/uploads -> /www/wwwroot/xingyu-data/uploads
|
||||
```
|
||||
|
||||
头像保存到既有持久化目录,并经 `https://im.bchongw.com/uploads/<文件名>.png` 访问。没有改动原有存储配置值,也没有覆盖其他头像文件。
|
||||
|
||||
### 本次验收
|
||||
|
||||
- 后端源码快照 `go test ./...`、管理端类型检查/生产构建、H5 类型检查/生产构建通过;测试标签与 OAuth 请求兼容回归用例通过。
|
||||
- 数据库独立复核:100 条测试资料、100 个测试昵称标签、男女各 50;正式注册用户数量保持 0。
|
||||
- 所有 10 张头像均经 HTTPS 返回 200 和 PNG 内容;生产入口 HTML 与发布包一致,管理端入口 JS、用户管理/仪表盘模块及 H5 测试标签模块的响应内容 SHA-256 与发布包一致。
|
||||
- `/healthz` 返回 200;管理接口、推荐接口和 WebSocket 在未登录时均返回 401,未为测试或验收创建管理员会话。
|
||||
- 订单、动态、聊天消息、订阅、用户会话数量均保持 0,管理员数量保持 1。
|
||||
- Go 服务通过宝塔原生项目管理接口重启,未启用旧 systemd 服务;前端以软链接原子切换,保留旧散列资源,未改动 Nginx 配置。
|
||||
- 初次发布时,验收脚本仅读取首条 `Cache-Control`,误判管理端缺少 `no-store` 并自动回退应用。实际响应同时含有 `no-cache` 与 `no-store, no-cache, must-revalidate` 两条头。本次修正为读取全部同名响应头,校验已导入批次和备份后恢复相同发布包,最终验收通过,没有重复导入或恢复整库。
|
||||
- 发布前数据库 gzip 备份完整性复核通过。备份仅限 root 访问;不得直接恢复整库覆盖发布后的真实注册或业务数据。
|
||||
- 本次未进行生产管理员登录后的真实浏览器验收,未绕过此前的登录授权限制。
|
||||
|
||||
访问 [管理端用户管理](https://im.bchongw.com/admin/#/users),将用户类型筛选为“测试用户”;访问 [H5](https://im.bchongw.com/app/) 后刷新加载新版。已安装的原生 App 不会因网页发布而自动升级,新版专用标签组件需要重新构建/安装 App;测试资料和昵称前缀已经由服务端提供。
|
||||
|
||||
## 2026-08-31 测试头像迁移至腾讯云 COS
|
||||
|
||||
根据用户后续指示,将上文 100 个测试用户共用的 10 张头像上传至管理端已配置的腾讯云 COS,并替换生产数据库链接。
|
||||
|
||||
- 存储桶:`gz-1349751149`,区域 `ap-guangzhou`。
|
||||
- 对象前缀:`media/test-users/cn-adults-20260831-v1/`;对象名包含原文件 SHA-256 的前 20 位及原文件名,防止缓存混淆和名称冲突。
|
||||
- 新地址格式:`https://gz-1349751149.cos.ap-guangzhou.myqcloud.com/media/test-users/cn-adults-20260831-v1/<sha20>-<原文件名>.png`,无临时签名和过期查询参数。
|
||||
- 备份目录:`/www/backup/xingyu-cos-avatars-20260831-115707`。`before.json` 保存逐用户的新旧链接和文件摘要,`uploaded.json` 保存对象上传结果,`result.json` 保存迁移统计;目录权限 0700,文件权限 0600。
|
||||
- 已新增上传 10 个对象,匿名 GET 逐张验证与本地 PNG 内容一致后,在单个 MySQL 事务中更新 100 条 `user_profiles.avatar_url`;再次核对 COS 链接 100 条、原本地头像链接 0 条,男女数量仍各 50。
|
||||
- 外部网络独立检查全部 10 个 COS URL,均返回 HTTP 200 和 `image/png`。原本地文件全部保留,不删除也不覆盖其他对象。
|
||||
- 线上在迁移前已选用 `tencent_cos`;本次未修改任何系统配置值,也没有修改任何对象 ACL 或存储桶权限。凭证仅在服务器进程内读取解密,没有打印或复制到本地。
|
||||
- Go 主服务 PID 保持不变,无需重新部署前端或重启后端。客户端/管理端重新加载用户列表即可获取新地址。
|
||||
|
||||
迁移工具源码:`backend/cmd/migrate-test-avatars-cos`;服务器工具:`/www/server/xingyu-im/ops/migrate-test-avatars-cos`。本次二进制 SHA-256 为 `68d55ce62b2e515f5e0dee27ff048353e13477f434f0f875a43cf400250e52fc`。离线回归测试覆盖配置密文兼容、路径和 HTTPS 校验、重复上传不覆盖、已有对象冲突拒绝、匿名访问和内容一致性。
|
||||
|
||||
如需撤销本次头像链接修改,仅针对 `before.json` 中的用户逐行核对当前链接仍等于记录的 `newUrl`,再在事务内恢复为 `oldUrl`;不能覆盖后来由用户或管理员修改的头像,不能恢复整库覆盖后续业务数据。先确认本地旧地址可访问,COS 对象也应保留到引用核对结束。
|
||||
|
||||
## 2026-08-31 应用功能发布(12:11)
|
||||
|
||||
用户授权“部署线上”后,已将本次后端、管理端及 H5 发布到现有宝塔项目。此次发布替代上文测试用户版本;没有改动 Nginx、服务器环境变量或已有支付、短信、存储及第三方登录配置值。
|
||||
|
||||
- 管理端“用户管理”增加“新增用户”,后端新增 `users:create` 权限,并授予现有超级管理员角色。
|
||||
- 密码取消长度和字符复杂度限制,移除前端强度提示;仍保留必填、旧密码身份验证和两次输入一致性检查。原 bcrypt 密码兼容,超过 bcrypt 字节上限的新密码采用 Argon2id 保存,不截断输入。
|
||||
- 上线 App 第三方登录接口及管理端 App 渠道开关;现有渠道启用状态保持不变,新 App 开关默认关闭,需要有效的平台参数及对应客户端配置才能使用。
|
||||
- H5 使用正式 HTTPS/WSS 地址。原生 App 的服务器地址修正、登录入口和表单变化仍需重新构建并安装 App,不会随本次网页发布自动更新。
|
||||
|
||||
### 发布产物与备份
|
||||
|
||||
- 服务器发布目录:`/www/server/xingyu-im/releases/application-20260831-121140`。
|
||||
- 管理端当前目录:`/www/wwwroot/xingyu-admin/releases/application-20260831-121140`。
|
||||
- H5 当前目录:`/www/wwwroot/xingyu-h5/releases/application-20260831-121140`。
|
||||
- 发布包 SHA-256:`865952392f733cefcdd9ad257fd701a55be57c434a55f381a7045a5b035d0c17`。
|
||||
- 新后端 SHA-256:`54e699a73fd6d3cec7baae3b1224a03cca6f2ddfdcb91c23f05e1fa258514b56`。
|
||||
- 备份目录:`/www/backup/xingyu-application-20260831-121140`,权限 0700。包括发布前完整 `im.sql.gz`、原二进制、兼容回滚二进制、环境文件及发布前后状态记录;数据库和环境文件权限 0600。
|
||||
- 本次应用迁移 `027_app_oauth_login.sql` 和 `029_admin_create_users.sql`,保留已上线的 028;数据库现有 001–029 共 29 条迁移记录,历史校验值一致。
|
||||
- 本地发布包和源码快照:`.deploy/application-20260831-120612`。服务器发布目录中的 `backend-source.zip` 归档了实际构建源码、兼容回滚源码及测试夹具,不在公开网站目录内。
|
||||
|
||||
前端保留旧散列资源,入口软链接原子切换;后端通过宝塔 Go 项目接口重启。若需回滚,使用备份中的 `xingyu-api-compatible-rollback`(SHA-256:`c041e6549b06e32314e131cabcdc5bd2035ae08f494feb5cb3f5b8b332d1035b`),并将前端软链接切回各自的 `test-users-20260831-113046` 目录。此回滚程序基于上一线上源码,只补充 Argon2id 密码验证,以免新长密码在回滚后无法登录;不要直接使用不支持新哈希的原二进制。增量迁移保留,不得恢复整库覆盖发布后的数据。
|
||||
|
||||
### 本次验证
|
||||
|
||||
- 新后端及兼容回滚源码快照的 `go test ./...` 均通过,管理端及移动端类型检查通过,管理端与 H5 生产构建通过。
|
||||
- 公网 HTTPS 证书校验通过;管理端、H5、健康检查和 App/H5 登录渠道接口均返回 200。两个入口 HTML 和 5 个入口资源的内容与发布包一致,入口 HTML 包含 `no-store`。
|
||||
- 管理接口及 WebSocket 未登录请求均返回 401;未为验收创建账户、修改密码或创建管理员会话。
|
||||
- `/proc` 中唯一运行的后端进程 PID 为 733469,运行映像摘要与新后端一致,确认不是仅替换了磁盘文件。
|
||||
- 发布前后现有配置值及测试用户资料指纹一致;100 个测试用户的 COS 头像保持不变。复核时用户总数 100、管理员 1、用户会话 2、订单 0、动态 0,未导入额外测试数据。
|
||||
- 数据库备份 gzip 完整性验证通过,回滚材料已保留;未实际执行生产回滚,也未进行登录后的业务写入验收。
|
||||
|
||||
访问 [管理端](https://im.bchongw.com/admin/) 或 [H5](https://im.bchongw.com/app/) 后强制刷新加载新版。如已有会话未刷新到新增权限,可退出后重新登录。
|
||||
|
||||
## 2026-08-31 IM 未读数与时间格式修复(12:47)
|
||||
|
||||
针对 App 给对方发消息后自己的列表出现未读红点、时间显示 `NaN:NaN` 的问题,已发布后端小范围修复。
|
||||
|
||||
- 原先使用 `last_seq - read_seq`,把自己发出的消息也计入未读。现按会话成员实际收到的消息统计:发送者不是本人、序号超过已读/清空/加入位置,且消息未撤回或被管理端下架。发送消息不会自动清除之前尚未阅读的对方消息。
|
||||
- `lastMessageAt` 由直接返回 `sql.NullTime` 对象改成 RFC3339 时间字符串;没有消息时返回 `null`。
|
||||
- HTTP 读取消息、更新已读状态会通过 WebSocket 通知当前用户的其他连接;已读位置不会超过实际消息序号,失败不会假装成功。
|
||||
- 发布前只读检查发现 2 个只有自己发信、却被旧逻辑标为未读的会话。没有为修复清空聊天、修改 read_seq 或创建测试会话,旧记录由新计数逻辑自动正确展示。
|
||||
|
||||
本次基于 12:11 实际生产源码,只修改 `backend/internal/app/im.go` 并加入其回归测试;发布前逐文件核对归档差异恰为这两项。保留 App OAuth、管理员新增用户和密码处理等已上线功能,001–029 迁移未改动或重跑,管理端和 H5 发布目录未切换。
|
||||
|
||||
- 后端发布目录:`/www/server/xingyu-im/releases/im-unread-20260831-124713`。
|
||||
- 后端 SHA-256:`812ceedad7a7714ad9d04558946370d5665b0a2a9231b0e1282cb65def9f03ab`。
|
||||
- 发布包 SHA-256:`230a4755988c2dc4c90a10f00955445e655e11dd6719ece5985707d45f010017`。
|
||||
- 回滚备份:`/www/backup/xingyu-im-unread-20260831-124713/xingyu-api-original`,其摘要为上一版 `54e699a73fd6d3cec7baae3b1224a03cca6f2ddfdcb91c23f05e1fa258514b56`;目录 0700,另有 `before.json`、`result.json`。
|
||||
- 经宝塔原生 Go 项目重启后,唯一服务进程 PID 为 733915,运行映像摘要与发布文件一致;`/healthz` 正常,未登录的会话接口、管理接口、WebSocket 均返回 401。
|
||||
- 发布脚本:`deploy/baota_publish_im_unread.py`,包含生产版本检查、源码差异白名单、迁移一致性检查、二进制备份及失败自动回滚。回滚只替换应用二进制,不恢复数据库。
|
||||
|
||||
本地验证通过:后端完整测试;隔离 MySQL 中 8 个 HTTP/WebSocket 收发、重复发送、已读、撤回、下架等场景;客户端 6 个回归用例(含实际聊天页隐藏后不再标已读、HTTP/WS 回显去重、陈旧请求不恢复红点、旧时间格式兼容);加上图标、原生组件和测试标签共 19 个客户端用例;Vue 类型检查及 App/H5 生产构建。
|
||||
|
||||
客户端代码还修复了重复回显、隐藏聊天页误标已读、返回列表及多连接未读同步。这部分在本地 `mobile`,App 资源位于 `mobile/dist/build/app`,**没有生成或安装签名 APK,也没有把这批客户端改动发布到线上 H5**。已安装 App 重新进入消息页即可取得后端修正后的未读数和时间;要包含全部客户端修复,需重新同步运行或打包安装。未进行生产账号登录后的真机验收。
|
||||
|
||||
## 2026-08-31 头像缩略图上线(18:00)
|
||||
|
||||
用户授权“部署上线”后,已发布头像处理后端和新版 H5。后端以 12:47 的实际生产源码为基础,只有头像处理、对应测试、文档及依赖共 9 个文件变化;聊天未读修复、密码规则、管理员新增用户和 App OAuth 等现有功能保持不变。没有执行数据库迁移,也没有修改 Nginx、存储配置、原有头像或聊天记录。
|
||||
|
||||
- 新版 H5 头像上传发送 `purpose=avatar`,服务端生成最长边 640px 展示图、256px 缩略图,并保留实际上传的原文件。小头像使用缩略图,推荐卡片使用展示图;加载缩略图失败时回退一次到展示图。
|
||||
- 普通图片、封面、语音和证据上传保留原逻辑。历史头像及第三方头像没有批量下载或替换,不会因本次发布自动变小。
|
||||
- H5 从本次冻结的 `mobile` 源码构建,包含此前已在本地完成的聊天同步、图标和原生组件兼容修复;这更新了上文“尚未发布客户端改动到 H5”的状态。管理端静态目录没有切换。
|
||||
- 当前采用 `tencent_cos`,生成文件使用原有存储配置,不启用云端图片处理或调整对象 ACL。
|
||||
|
||||
### 产物及回滚
|
||||
|
||||
- 后端发布目录:`/www/server/xingyu-im/releases/avatars-20260831-180014`。
|
||||
- 后端 SHA-256:`b7eeb926d063855e4271815872ba8c90e226554a3824d48e0995479a671e546e`。
|
||||
- 发布包 SHA-256:`28901eeaa88355886cf74899b4e3390cb0baeb5275c1126024f884b34731b404`。
|
||||
- 后端源码归档 SHA-256:`bc6c1bafc57d3b7e772e7823d89485d6dbce6cc11ff33fc74a01878665a73f10`。
|
||||
- H5 目录:`/www/wwwroot/xingyu-h5/releases/avatars-20260831-180014`;H5 ZIP SHA-256:`00facb91404f06147e9d1f85d872fcc8019878e3a09e45dee8c156db74665214`。
|
||||
- 备份目录:`/www/backup/xingyu-avatars-20260831-180014`,权限 0700;包括旧二进制、权限 0600 的完整数据库 gzip 备份,以及发布前后状态 JSON。
|
||||
- 回滚目标:旧二进制摘要 `812ceedad7a7714ad9d04558946370d5665b0a2a9231b0e1282cb65def9f03ab`,旧 H5 目录 `/www/wwwroot/xingyu-h5/releases/application-20260831-121140`。旧前端资源已兼容保留,切换通过软链接完成。若回滚仅替换程序和前端入口,不恢复数据库覆盖发布后的业务数据。
|
||||
- 发布脚本:`deploy/baota_publish_avatars.py`。发布目录保存 `backend-source.zip`、`mobile-source.zip`、构建产物、校验清单和脚本;本地对应 `.deploy/avatars-20260831-175508`。
|
||||
|
||||
### 验证结果
|
||||
|
||||
- 隔离后端源码完整测试通过;冻结的前端源码类型检查、49 项回归测试和 H5 构建通过。
|
||||
- 服务器执行与发布源码一致的 Linux 测试二进制,11 个选定测试及其子用例全部通过,覆盖头像生成、方向校正、GIF/WebP、尺寸限制、实际 HTTP 上传/读取、失败清理和普通媒体兼容。这些测试仅使用临时目录、内存数据库/存储,不接触生产账号及 COS 对象。
|
||||
- 通过宝塔 Go 项目重启;验证唯一运行进程 PID 9373,其 `/proc` 运行映像摘要与新后端一致。
|
||||
- 公网 HTTPS 证书校验通过,H5 的全部 84 个文件内容摘要与本次发布包一致;健康检查、管理端访问正常,上传接口、会话接口及 WebSocket 的未登录请求均返回 401。
|
||||
- 发布前后配置值与 100 个测试用户头像指纹一致。复核用户 100、资料 100、管理员 1、媒体记录 0、聊天消息 5、迁移记录 29;未为验收创建账户、修改头像或写入媒体记录。
|
||||
- 完整数据库 gzip 备份校验通过;没有实际执行生产回滚,也没有进行生产用户登录后的 COS 上传或真机验收。
|
||||
|
||||
访问 [H5](https://im.bchongw.com/app/) 后强制刷新即可使用新上传流程。已安装的 App 不会随网页发布自动升级,需要重新打包安装;本次未生成或安装签名 APK。
|
||||
|
||||
## 2026-09-01 测试头像缩略图补齐(11:06)
|
||||
|
||||
排查 App“附近”列表头像加载慢时,确认 10 个测试头像的 `-thumb.jpg` 对象全部返回 404。客户端因此先等待缩略图失败,再回退下载约 1.8–2.0MB 的 PNG 原图,每张头像产生两次请求。
|
||||
|
||||
- 已在原 COS 前缀 `media/test-users/cn-adults-20260831-v1/` 下新增 10 个确定名称的 256px JPEG 缩略图,原 10 个 PNG 对象未覆盖。
|
||||
- 外网独立 HEAD 复核 10/10 均为 HTTP 200、`image/jpeg`,单张 8,630–13,355 字节;10 张合计由原图 19,859,686 字节降至 110,178 字节,减少 99.45%。
|
||||
- 生产数据库中 100 条测试用户头像链接前后指纹一致,更新行数为 0;未修改 COS 配置、用户资料或其他媒体。
|
||||
- 备份与验证记录位于 `/www/backup/xingyu-cos-avatars-thumbnails-20260901-110619`,目录仅 root 可读。迁移二进制 SHA-256 为 `9516326bb0cd9b3e5090ee0a567de164bbfa8644545b5c7021918ea56ff92695`。
|
||||
- 此操作只新增静态对象,无需重启后端。客户端重新进入“附近”页后即可直接请求缩略图。
|
||||
@@ -52,6 +52,11 @@ server {
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
location = /_app.config.js {
|
||||
expires -1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Offline regression tests for release validation; never connects to production."""
|
||||
import importlib.util
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
import urllib.error
|
||||
from email.message import Message
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'publish_test_users', Path(__file__).with_name('baota_publish_test_users.py'))
|
||||
release = importlib.util.module_from_spec(spec)
|
||||
with patch.dict(sys.modules, {
|
||||
'pymysql': types.ModuleType('pymysql'),
|
||||
'pwd': types.ModuleType('pwd'),
|
||||
}):
|
||||
spec.loader.exec_module(release)
|
||||
|
||||
|
||||
class CacheHeaderValidationTest(unittest.TestCase):
|
||||
def validate(self, cache_values):
|
||||
def fake_query(conn, sql, args=()):
|
||||
if 'GROUP BY p.gender' in sql:
|
||||
return ((1, 50), (2, 50))
|
||||
if 'DISTINCT p.avatar_url' in sql:
|
||||
return tuple((release.DOMAIN + '/uploads/%d-1.png' % i,) for i in range(10))
|
||||
if 'password_hash' in sql:
|
||||
return ((100,),)
|
||||
self.fail('Unexpected database query')
|
||||
|
||||
def fake_fetch(path):
|
||||
headers = Message()
|
||||
if path.startswith('/uploads/'):
|
||||
headers['Content-Type'] = 'image/png'
|
||||
return 200, headers, b'\x89PNG\r\n\x1a\n'
|
||||
if path in ['/admin/', '/app/']:
|
||||
headers['Content-Type'] = 'text/html'
|
||||
for value in cache_values:
|
||||
headers['Cache-Control'] = value
|
||||
return 200, headers, b'<!doctype html><html></html>'
|
||||
raise urllib.error.HTTPError(path, 401, 'Unauthorized', headers, None)
|
||||
|
||||
with patch.object(release, 'query', fake_query), patch.object(release, 'fetch', fake_fetch), patch.object(release, 'health'):
|
||||
return release.verify(object())
|
||||
|
||||
def test_accepts_no_store_in_second_cache_header(self):
|
||||
result = self.validate(['no-cache', 'no-store, no-cache, must-revalidate'])
|
||||
self.assertEqual(result['total'], 100)
|
||||
self.assertEqual(result['avatarsHttp200'], 10)
|
||||
|
||||
def test_accepts_one_combined_header(self):
|
||||
self.validate(['no-store, no-cache, must-revalidate'])
|
||||
|
||||
def test_rejects_missing_no_store(self):
|
||||
with self.assertRaises(AssertionError):
|
||||
self.validate(['no-cache'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,98 @@
|
||||
# xim.bchongw.com 部署记录
|
||||
|
||||
部署日期:2026-09-02
|
||||
目标服务器:`8.219.70.152`
|
||||
运行方式:既有宝塔 Linux 面板 + 宝塔 Go 项目 + 既有 MySQL 5.7(非 Docker)
|
||||
|
||||
## 对外地址
|
||||
|
||||
- 管理端:`https://xim.bchongw.com/admin/`
|
||||
- API:`https://xim.bchongw.com`
|
||||
- 健康检查:`https://xim.bchongw.com/healthz`
|
||||
- WebSocket:`wss://xim.bchongw.com/ws`
|
||||
- 管理 API:`https://xim.bchongw.com/admin/v1`
|
||||
|
||||
HTTP 已强制 301 跳转到 HTTPS。Let's Encrypt 证书由宝塔托管,证书到期时间为 2026-12-01,宝塔中的“续签 Let's Encrypt 证书”计划任务处于启用状态。
|
||||
|
||||
## 宝塔与服务
|
||||
|
||||
目标机原本已经安装并运行宝塔、Nginx 1.26.1 和 MySQL 5.7.40,因此没有重装面板或替换现有 Web/数据库环境。原有网站和数据库均未修改。
|
||||
|
||||
| 项目 | 值 |
|
||||
| --- | --- |
|
||||
| 宝塔 Go 项目 | `xim_im` |
|
||||
| Go 运行用户 | `www` |
|
||||
| Go 监听地址 | `127.0.0.1:18888` |
|
||||
| Go 当前版本 | `/www/server/xim-im/releases/20260902-100344` |
|
||||
| Go 当前入口 | `/www/server/xim-im/current` |
|
||||
| Go 环境文件 | `/etc/xim-im.env`(`root:www 0640`) |
|
||||
| Go 日志 | `/www/wwwlogs/go/xim_im.log` |
|
||||
| 上传目录 | `/www/wwwroot/xim-data/uploads` |
|
||||
| 管理端当前版本 | `/www/wwwroot/xim-admin/releases/20260902-100344` |
|
||||
| 管理端入口 | `/www/wwwroot/xim.bchongw.com/admin` |
|
||||
| Nginx 主配置 | `/www/server/panel/vhost/nginx/go_xim_im.conf` |
|
||||
| Nginx 扩展路由 | `/www/server/panel/vhost/nginx/extension/xim_im/xim_routes.conf` |
|
||||
| 运维脚本 | `/www/server/xim-im/ops`(仅 root 可访问) |
|
||||
| 初始管理员凭据 | `/root/.xim-initial-credentials`(`root:root 0600`) |
|
||||
|
||||
后端只监听回环地址,公网不开放 18888;MySQL 继续使用服务器既有实例,没有新增公网端口。
|
||||
|
||||
## 数据库
|
||||
|
||||
- 宝塔数据库名:`xim`
|
||||
- 应用账号:`xim_app`,仅授予 `xim` 库权限
|
||||
- 字符集:`utf8mb4`
|
||||
- 已执行迁移:`001_users.sql` 至 `029_admin_create_users.sql`,共 29 条
|
||||
- 当前业务表:66 张
|
||||
- 演示数据:关闭
|
||||
- 初始有效管理员:1 个
|
||||
|
||||
数据库密码、JWT 密钥和配置加密密钥均在目标服务器上随机生成,没有写入工作区或本记录。
|
||||
|
||||
## 发布产物
|
||||
|
||||
- 后端 Linux/amd64 静态二进制 SHA-256:`76ee90fc9ddf4ff5472d20e7595c4e9380b0fee4a4b972aa30c089a03903abe8`
|
||||
- 完整部署包 SHA-256:`49814e881cc2e1776dd768316a37509269ab13a78d8960a9e1c278bcb15f4e87`
|
||||
- 服务器归档:`/www/server/xim-im/releases/20260902-100344/deployment-bundle.zip`
|
||||
- 面板数据库部署前备份:`/www/backup/xim-initial-20260902-100344`
|
||||
- 管理 API 路由修复前备份:`/www/backup/xim-initial-20260902-100344/xim_routes.before-api-fix.conf`
|
||||
|
||||
本地构建前执行了后端 `go test ./...`、管理端类型检查和管理端生产构建,全部通过。
|
||||
|
||||
## 安全处理
|
||||
|
||||
- `IM_ALLOWED_ORIGINS` 仅允许 `https://xim.bchongw.com`。
|
||||
- 管理端运行时接口地址使用同域 `/admin/v1`。
|
||||
- 初始管理员创建后,`IM_BOOTSTRAP_ADMIN_PASSWORD` 已从运行环境清空;凭据只保存在 root 专用文件。
|
||||
- 管理端入口 HTML 和 `_app.config.js` 禁止缓存;散列静态资源使用长期缓存。
|
||||
- 网关传递 `X-Forwarded-Proto`,上传文件生成的公开地址使用 HTTPS。
|
||||
- 未认证管理接口和 WebSocket 握手均返回 401。
|
||||
|
||||
## 验收结果
|
||||
|
||||
- DNS 公网 A 记录解析为 `8.219.70.152`。
|
||||
- Nginx 配置检查通过。
|
||||
- TLS 1.3 握手和证书域名校验通过。
|
||||
- `http://xim.bchongw.com/healthz` 返回 301,并跳转到 HTTPS。
|
||||
- `https://xim.bchongw.com/healthz` 返回 200 和 `status=ok`。
|
||||
- `https://xim.bchongw.com/admin/` 返回 200。
|
||||
- 管理端运行时配置指向 `/admin/v1`。
|
||||
- 使用初始管理员完成真实登录、用户信息、17 项权限码、仪表盘及退出登录验收。
|
||||
- 宝塔 `xim_im` 项目重启后 PID 更新,服务和公网 HTTPS 健康检查恢复正常。
|
||||
- 宝塔数据库列表存在 `xim`,Go 项目已设置开机启动和守护。
|
||||
- 测试产生的未退出管理会话已撤销。
|
||||
|
||||
## 运维入口
|
||||
|
||||
在宝塔中进入“网站 → Go 项目 → `xim_im`”进行启动、停止、重启和日志查看;在“数据库 → MySQL → `xim`”管理项目数据库。
|
||||
|
||||
常用检查:
|
||||
|
||||
```bash
|
||||
curl -fsS http://127.0.0.1:18888/healthz
|
||||
curl -fsS https://xim.bchongw.com/healthz
|
||||
/www/server/nginx/sbin/nginx -t
|
||||
tail -n 200 /www/wwwlogs/go/xim_im.log
|
||||
```
|
||||
|
||||
首次登录后应在管理端修改管理员密码。短信、对象存储、第三方登录和正式支付渠道仍需在管理端填入实际厂商参数并分别完成联调;本次没有写入任何真实第三方密钥。
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Request, install, and verify BaoTa-managed HTTPS for xim.bchongw.com."""
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PANEL = Path('/www/server/panel')
|
||||
DOMAIN = 'xim.bchongw.com'
|
||||
PROJECT = 'xim_im'
|
||||
EXPECTED_IP = '8.219.70.152'
|
||||
GO_CONF = PANEL / ('vhost/nginx/go_' + PROJECT + '.conf')
|
||||
|
||||
|
||||
def request(**values):
|
||||
result = public.dict_obj()
|
||||
for key, value in values.items():
|
||||
setattr(result, key, value)
|
||||
return result
|
||||
|
||||
|
||||
def command(*args):
|
||||
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError('{} failed: {}'.format(args[0], result.stderr.strip()))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def fetch(url, expected):
|
||||
last_error = None
|
||||
for _ in range(40):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=8) as response:
|
||||
body = response.read().decode('utf-8')
|
||||
if response.status == 200 and expected in body:
|
||||
return body
|
||||
except Exception as error:
|
||||
last_error = error
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('Public verification failed for {}: {}'.format(url, last_error))
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() != 0 or not PANEL.is_dir():
|
||||
raise SystemExit('Run as root on the BaoTa host')
|
||||
os.chdir(str(PANEL))
|
||||
sys.path.insert(0, str(PANEL))
|
||||
sys.path.insert(0, str(PANEL / 'class'))
|
||||
global public
|
||||
import public
|
||||
import panelSite
|
||||
from acme_v2 import acme_v2
|
||||
from projectModel.goModel import main as GoProject
|
||||
|
||||
addresses = sorted(set(socket.gethostbyname_ex(DOMAIN)[2]))
|
||||
if EXPECTED_IP not in addresses:
|
||||
raise RuntimeError('DNS does not point to this server: ' + json.dumps(addresses))
|
||||
go = GoProject()
|
||||
project = go.get_project_find(PROJECT)
|
||||
if not project or not go.get_project_run_state(project_name=PROJECT):
|
||||
raise RuntimeError('BaoTa Go project is not running')
|
||||
if DOMAIN + ':80' not in project['project_config']['domains']:
|
||||
raise RuntimeError('Expected domain is not bound to the project')
|
||||
fetch('http://' + DOMAIN + '/healthz', '"status":"ok"')
|
||||
|
||||
site_id = str(project['id'])
|
||||
args = request(id=site_id, auth_to=site_id, auth_type='http',
|
||||
auto_wildcard='0', domains=json.dumps([DOMAIN]),
|
||||
siteName=PROJECT, ca='letsencrypt')
|
||||
certificate = acme_v2().apply_cert_api(args)
|
||||
if not certificate.get('status'):
|
||||
raise RuntimeError('Certificate request failed: ' + str(certificate.get('msg')))
|
||||
if 'private_key' not in certificate or 'cert' not in certificate:
|
||||
raise RuntimeError('Certificate authority returned an incomplete result')
|
||||
|
||||
install = panelSite.panelSite().SetSSL(request(
|
||||
siteName=PROJECT,
|
||||
key=certificate['private_key'],
|
||||
csr=certificate['cert'] + certificate.get('root', ''),
|
||||
))
|
||||
if not install.get('status'):
|
||||
raise RuntimeError('Certificate install failed: ' + str(install.get('msg')))
|
||||
redirect = panelSite.panelSite().HttpToHttps(request(siteName=PROJECT))
|
||||
if not redirect.get('status'):
|
||||
raise RuntimeError('HTTPS redirect enablement failed: ' + str(redirect.get('msg')))
|
||||
command('/www/server/nginx/sbin/nginx', '-t')
|
||||
command('/etc/init.d/nginx', 'reload')
|
||||
|
||||
fetch('https://' + DOMAIN + '/healthz', '"status":"ok"')
|
||||
fetch('https://' + DOMAIN + '/admin/', '星遇社交运营中心')
|
||||
connection = http.client.HTTPConnection(DOMAIN, 80, timeout=8)
|
||||
connection.request('GET', '/healthz')
|
||||
response = connection.getresponse()
|
||||
response.read()
|
||||
if response.status not in (301, 308):
|
||||
raise RuntimeError('HTTP is not redirected to HTTPS: ' + str(response.status))
|
||||
if not (response.getheader('Location') or '').startswith('https://' + DOMAIN):
|
||||
raise RuntimeError('HTTP redirect target is incorrect')
|
||||
|
||||
context = ssl.create_default_context()
|
||||
with socket.create_connection((DOMAIN, 443), timeout=8) as raw:
|
||||
with context.wrap_socket(raw, server_hostname=DOMAIN) as secure:
|
||||
peer = secure.getpeercert()
|
||||
protocol = secure.version()
|
||||
ssl_state = panelSite.panelSite().GetSSL(request(siteName=PROJECT))
|
||||
if not ssl_state.get('status') or not ssl_state.get('httpTohttps'):
|
||||
raise RuntimeError('BaoTa does not report SSL and forced HTTPS as enabled')
|
||||
result = {
|
||||
'status': 'HTTPS_DEPLOYMENT_OK',
|
||||
'domain': DOMAIN,
|
||||
'project': PROJECT,
|
||||
'dns': addresses,
|
||||
'tls_protocol': protocol,
|
||||
'certificate_not_after': peer.get('notAfter'),
|
||||
'http_redirect': response.status,
|
||||
'nginx_config': str(GO_CONF),
|
||||
}
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
umask 077
|
||||
|
||||
readonly stage_dir="/www/server/xim-generated-users-20260902"
|
||||
readonly avatar_dir="${stage_dir}/avatars"
|
||||
readonly manifest_file="${stage_dir}/manifest.json"
|
||||
readonly importer="${stage_dir}/import-generated-test-users"
|
||||
readonly environment_file="/etc/xim-im.env"
|
||||
readonly lock_file="/www/server/xim-generated-users-20260902.lock"
|
||||
|
||||
[[ "$(id -u)" == "0" ]] || { echo "Run as root" >&2; exit 1; }
|
||||
[[ -d "${stage_dir}" && -d "${avatar_dir}" ]] || { echo "Staging directory is incomplete" >&2; exit 1; }
|
||||
[[ -f "${manifest_file}" && -f "${importer}" && -f "${environment_file}" ]] || { echo "Required file is missing" >&2; exit 1; }
|
||||
[[ "$(find "${avatar_dir}" -maxdepth 1 -type f -name 'avatar-*.png' | wc -l)" == "100" ]] || { echo "Expected exactly 100 PNG avatars" >&2; exit 1; }
|
||||
|
||||
exec 9>"${lock_file}"
|
||||
flock -n 9 || { echo "Another generated-user import is running" >&2; exit 1; }
|
||||
|
||||
chmod 0755 "${importer}"
|
||||
# shellcheck disable=SC1091
|
||||
source "${environment_file}"
|
||||
|
||||
"${importer}" \
|
||||
--confirm-database xim \
|
||||
--confirm-bucket gz-1349751149 \
|
||||
--manifest "${manifest_file}" \
|
||||
--avatars-dir "${avatar_dir}"
|
||||
|
||||
readonly backup_dir="/www/backup/xim-generated-users-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
"${importer}" \
|
||||
--apply \
|
||||
--confirm-database xim \
|
||||
--confirm-bucket gz-1349751149 \
|
||||
--manifest "${manifest_file}" \
|
||||
--avatars-dir "${avatar_dir}" \
|
||||
--backup-dir "${backup_dir}"
|
||||
|
||||
echo "Generated test-user import completed. Backup: ${backup_dir}"
|
||||
@@ -0,0 +1,406 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initial, isolated BaoTa deployment for xim.bchongw.com.
|
||||
|
||||
Run with BaoTa's bundled Python as root. Secrets are generated on the target
|
||||
host, stored in root-only files, and never printed by this script.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PANEL = Path('/www/server/panel')
|
||||
DOMAIN = 'xim.bchongw.com'
|
||||
PROJECT = 'xim_im'
|
||||
DATABASE = 'xim'
|
||||
DATABASE_USER = 'xim_app'
|
||||
PORT = 18888
|
||||
SERVER_ROOT = Path('/www/server/xim-im')
|
||||
WEB_ROOT = Path('/www/wwwroot') / DOMAIN
|
||||
ADMIN_ROOT = Path('/www/wwwroot/xim-admin')
|
||||
MEDIA_ROOT = Path('/www/wwwroot/xim-data/uploads')
|
||||
ENV_FILE = Path('/etc/xim-im.env')
|
||||
CREDENTIALS_FILE = Path('/root/.xim-initial-credentials')
|
||||
GO_CONF = PANEL / ('vhost/nginx/go_' + PROJECT + '.conf')
|
||||
ROUTES = PANEL / ('vhost/nginx/extension/' + PROJECT + '/xim_routes.conf')
|
||||
|
||||
|
||||
def atomic_write(path, content, mode=0o600):
|
||||
temporary = path.with_name(path.name + '.new-' + secrets.token_hex(4))
|
||||
descriptor = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as target:
|
||||
target.write(content)
|
||||
os.replace(str(temporary), str(path))
|
||||
os.chmod(str(path), mode)
|
||||
|
||||
|
||||
def digest(path):
|
||||
result = hashlib.sha256()
|
||||
with path.open('rb') as source:
|
||||
while True:
|
||||
block = source.read(1024 * 1024)
|
||||
if not block:
|
||||
return result.hexdigest()
|
||||
result.update(block)
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise RuntimeError('{} failed: {}'.format(args[0], result.stderr.strip()))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def request(**values):
|
||||
result = public.dict_obj()
|
||||
for key, value in values.items():
|
||||
setattr(result, key, value)
|
||||
return result
|
||||
|
||||
|
||||
def extract_safe(package, destination):
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
with zipfile.ZipFile(str(package)) as archive:
|
||||
for item in archive.infolist():
|
||||
name = item.filename.replace('\\', '/')
|
||||
candidate = (destination / name).resolve()
|
||||
if os.path.commonpath([str(candidate), str(destination.resolve())]) != str(destination.resolve()):
|
||||
raise RuntimeError('Unsafe archive member: ' + item.filename)
|
||||
if item.is_dir() or item.filename.endswith(('/', '\\')):
|
||||
candidate.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
candidate.parent.mkdir(parents=True, exist_ok=True)
|
||||
with archive.open(item) as source, candidate.open('wb') as target:
|
||||
shutil.copyfileobj(source, target)
|
||||
|
||||
|
||||
def backup_panel_databases(backup):
|
||||
backup.mkdir(parents=True, mode=0o700, exist_ok=False)
|
||||
os.chmod(str(backup), 0o700)
|
||||
for source in (PANEL / 'data/db/site.db', PANEL / 'data/db/database.db'):
|
||||
with sqlite3.connect(str(source)) as connection:
|
||||
with sqlite3.connect(str(backup / source.name)) as target:
|
||||
connection.backup(target)
|
||||
|
||||
|
||||
def mysql_args(database_password, include_database=True):
|
||||
executable = Path('/www/server/mysql/bin/mysql')
|
||||
if not executable.is_file():
|
||||
executable = Path(shutil.which('mysql') or '')
|
||||
if not executable.is_file():
|
||||
raise RuntimeError('MySQL client is unavailable')
|
||||
args = [str(executable), '--protocol=TCP', '--host=127.0.0.1', '--port=3306',
|
||||
'--user=' + DATABASE_USER, '--default-character-set=utf8mb4',
|
||||
'--batch', '--skip-column-names']
|
||||
if include_database:
|
||||
args.append('--database=' + DATABASE)
|
||||
environment = os.environ.copy()
|
||||
environment['MYSQL_PWD'] = database_password
|
||||
return args, environment
|
||||
|
||||
|
||||
def mysql_query(database_password, statement):
|
||||
args, environment = mysql_args(database_password)
|
||||
result = subprocess.run(args + ['--execute', statement], env=environment,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError('MySQL query failed: ' + result.stderr.strip())
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def migrate(database_password, migration_root):
|
||||
mysql_query(database_password, '''
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(255) NOT NULL PRIMARY KEY,
|
||||
checksum CHAR(64) NOT NULL,
|
||||
applied_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
''')
|
||||
migrations = sorted(migration_root.glob('*.sql'))
|
||||
if len(migrations) != 29 or migrations[0].name != '001_users.sql' or migrations[-1].name != '029_admin_create_users.sql':
|
||||
raise RuntimeError('Expected the complete 001-029 migration set')
|
||||
args, environment = mysql_args(database_password)
|
||||
for migration in migrations:
|
||||
checksum = digest(migration)
|
||||
stored = mysql_query(database_password,
|
||||
"SELECT checksum FROM schema_migrations WHERE version='{}'".format(migration.name))
|
||||
if stored:
|
||||
if stored != checksum:
|
||||
raise RuntimeError('Migration checksum mismatch: ' + migration.name)
|
||||
continue
|
||||
result = subprocess.run(args, env=environment, stdin=migration.open('r', encoding='utf-8'),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError('Migration {} failed: {}'.format(migration.name, result.stderr.strip()))
|
||||
mysql_query(database_password,
|
||||
"INSERT INTO schema_migrations(version, checksum) VALUES('{}','{}')".format(
|
||||
migration.name, checksum))
|
||||
applied = int(mysql_query(database_password, 'SELECT COUNT(*) FROM schema_migrations'))
|
||||
if applied != 29:
|
||||
raise RuntimeError('Unexpected migration count: ' + str(applied))
|
||||
|
||||
|
||||
def environment_text(values):
|
||||
return '# BaoTa Go project environment for xim.bchongw.com. Keep private.\n' + ''.join(
|
||||
'export {}={}\n'.format(key, shlex.quote(value)) for key, value in values.items())
|
||||
|
||||
|
||||
def health(url, host=None, expected='"status":"ok"'):
|
||||
last_error = None
|
||||
for _ in range(120):
|
||||
try:
|
||||
headers = {'Host': host} if host else {}
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=4) as response:
|
||||
body = response.read().decode('utf-8')
|
||||
if response.status == 200 and expected in body:
|
||||
return body
|
||||
except Exception as error:
|
||||
last_error = error
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError('Health check failed for {}: {}'.format(url, last_error))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('bundle')
|
||||
parser.add_argument('sha256')
|
||||
args = parser.parse_args()
|
||||
bundle = Path(args.bundle).resolve()
|
||||
if os.geteuid() != 0 or not PANEL.is_dir():
|
||||
raise SystemExit('Run as root on the BaoTa host')
|
||||
if bundle.parent != Path('/tmp') or not bundle.is_file():
|
||||
raise SystemExit('Bundle must be a regular file directly under /tmp')
|
||||
if digest(bundle) != args.sha256.lower():
|
||||
raise SystemExit('Bundle SHA-256 mismatch')
|
||||
|
||||
os.chdir(str(PANEL))
|
||||
sys.path.insert(0, str(PANEL))
|
||||
sys.path.insert(0, str(PANEL / 'class'))
|
||||
global public
|
||||
import public
|
||||
import database
|
||||
from projectModel.goModel import main as GoProject
|
||||
|
||||
go = GoProject()
|
||||
conflicts = {
|
||||
'project': bool(go.get_project_find(PROJECT)),
|
||||
'domain': bool(public.M('domain').where('name=?', (DOMAIN,)).count()),
|
||||
'database': bool(public.M('databases').where('name=?', (DATABASE,)).count()),
|
||||
'server_root': SERVER_ROOT.exists(),
|
||||
'web_root': WEB_ROOT.exists(),
|
||||
'admin_root': ADMIN_ROOT.exists(),
|
||||
'media_root': MEDIA_ROOT.exists(),
|
||||
'environment': ENV_FILE.exists(),
|
||||
'credentials': CREDENTIALS_FILE.exists(),
|
||||
'nginx': GO_CONF.exists(),
|
||||
}
|
||||
if any(conflicts.values()):
|
||||
raise RuntimeError('Refusing to overwrite an existing target: ' + json.dumps(conflicts, ensure_ascii=False))
|
||||
run(['/www/server/nginx/sbin/nginx', '-t'])
|
||||
if run(['bash', '-lc', "ss -H -ltn 'sport = :{}' | wc -l".format(PORT)]) != '0':
|
||||
raise RuntimeError('Port {} is already in use'.format(PORT))
|
||||
|
||||
stamp = time.strftime('%Y%m%d-%H%M%S')
|
||||
backup = Path('/www/backup/xim-initial-' + stamp)
|
||||
backup_panel_databases(backup)
|
||||
stage = Path('/tmp/xim-stage-' + stamp)
|
||||
extract_safe(bundle, stage)
|
||||
binary = stage / 'xim-api'
|
||||
admin_archive = stage / 'admin.zip'
|
||||
migrations = stage / 'migrations'
|
||||
if not binary.is_file() or not admin_archive.is_file() or not migrations.is_dir():
|
||||
raise RuntimeError('Bundle layout is incomplete')
|
||||
|
||||
database_password = secrets.token_hex(32)
|
||||
jwt_secret = secrets.token_hex(48)
|
||||
encryption_key = secrets.token_hex(48)
|
||||
admin_password = 'Xa9!' + secrets.token_urlsafe(20)
|
||||
add_database = database.database().AddDatabase(request(
|
||||
name=DATABASE, db_user=DATABASE_USER, password=database_password,
|
||||
address='127.0.0.1', codeing='utf8mb4', ps='星遇 IM · xim.bchongw.com',
|
||||
sid=0, pid=0,
|
||||
))
|
||||
if not add_database.get('status'):
|
||||
raise RuntimeError('BaoTa database creation failed: ' + str(add_database.get('msg')))
|
||||
migrate(database_password, migrations)
|
||||
|
||||
release = SERVER_ROOT / 'releases' / stamp
|
||||
admin_release = ADMIN_ROOT / 'releases' / stamp
|
||||
release.mkdir(parents=True, mode=0o755)
|
||||
shutil.copy2(str(binary), str(release / 'xim-api'))
|
||||
os.chmod(str(release / 'xim-api'), 0o755)
|
||||
shutil.copytree(str(migrations), str(release / 'migrations'))
|
||||
launcher = '''#!/bin/bash
|
||||
set -euo pipefail
|
||||
umask 0027
|
||||
for attempt in $(seq 1 120); do
|
||||
if ! /usr/sbin/ss -H -ltn 'sport = :18888' | /usr/bin/grep -q .; then
|
||||
exec /www/server/xim-im/current/xim-api
|
||||
fi
|
||||
sleep 0.25
|
||||
done
|
||||
printf '%s\\n' 'Cannot start xim_im: port 18888 is still occupied.' >&2
|
||||
exit 1
|
||||
'''
|
||||
atomic_write(release / 'start.sh', launcher, 0o750)
|
||||
current = SERVER_ROOT / 'current'
|
||||
current.symlink_to(release)
|
||||
|
||||
ADMIN_ROOT.mkdir(parents=True, mode=0o755)
|
||||
extract_safe(admin_archive, admin_release)
|
||||
if not (admin_release / 'index.html').is_file() or not (admin_release / '_app.config.js').is_file():
|
||||
raise RuntimeError('Admin build is incomplete')
|
||||
if '/admin/' not in (admin_release / 'index.html').read_text(encoding='utf-8'):
|
||||
raise RuntimeError('Admin build does not use the /admin/ base')
|
||||
if '"/admin/v1"' not in (admin_release / '_app.config.js').read_text(encoding='utf-8'):
|
||||
raise RuntimeError('Admin runtime API path is incorrect')
|
||||
www = pwd.getpwnam('www')
|
||||
for parent, directories, files in os.walk(str(admin_release)):
|
||||
os.chown(parent, www.pw_uid, www.pw_gid)
|
||||
os.chmod(parent, 0o755)
|
||||
for filename in files:
|
||||
path = os.path.join(parent, filename)
|
||||
os.chown(path, www.pw_uid, www.pw_gid)
|
||||
os.chmod(path, 0o644)
|
||||
|
||||
WEB_ROOT.mkdir(parents=True, mode=0o755)
|
||||
(WEB_ROOT / 'admin').symlink_to(admin_release)
|
||||
MEDIA_ROOT.mkdir(parents=True, mode=0o750)
|
||||
os.chown(str(MEDIA_ROOT), www.pw_uid, www.pw_gid)
|
||||
|
||||
values = {
|
||||
'IM_ENV': 'production',
|
||||
'IM_HOST': '127.0.0.1',
|
||||
'IM_PORT': str(PORT),
|
||||
'IM_DB_DSN': '{}:{}@tcp(127.0.0.1:3306)/{}?charset=utf8mb4&parseTime=True&loc=Local'.format(
|
||||
DATABASE_USER, database_password, DATABASE),
|
||||
'IM_JWT_SECRET': jwt_secret,
|
||||
'IM_CONFIG_ENCRYPTION_KEY': encryption_key,
|
||||
'IM_ALLOWED_ORIGINS': 'https://' + DOMAIN,
|
||||
'IM_SEED_DEMO': 'false',
|
||||
'IM_MEDIA_DIR': str(MEDIA_ROOT),
|
||||
'IM_BOOTSTRAP_ADMIN_USERNAME': 'admin',
|
||||
'IM_BOOTSTRAP_ADMIN_PASSWORD': admin_password,
|
||||
'IM_BOOTSTRAP_ADMIN_REAL_NAME': '平台管理员',
|
||||
'TZ': 'Asia/Shanghai',
|
||||
}
|
||||
atomic_write(ENV_FILE, environment_text(values), 0o640)
|
||||
os.chown(str(ENV_FILE), 0, www.pw_gid)
|
||||
atomic_write(CREDENTIALS_FILE,
|
||||
'URL=https://{}/admin/\nusername=admin\npassword={}\n'.format(DOMAIN, admin_password), 0o600)
|
||||
|
||||
routes = '''# xim.bchongw.com admin routes. API and WebSocket use the BaoTa Go proxy.
|
||||
server_tokens off;
|
||||
client_max_body_size 16m;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
|
||||
location ^~ /admin/v1/ {
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
location = /admin { return 301 /admin/; }
|
||||
location = /admin/ {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files /admin/index.html =404;
|
||||
}
|
||||
location = /admin/index.html {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location = /admin/_app.config.js {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /admin/ {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri $uri/ /admin/index.html;
|
||||
}
|
||||
'''
|
||||
ROUTES.parent.mkdir(parents=True, mode=0o755)
|
||||
atomic_write(ROUTES, routes, 0o644)
|
||||
|
||||
create = go.create_project(request(
|
||||
project_name=PROJECT, project_exe=str(current / 'xim-api'),
|
||||
project_ps='星遇 IM · xim.bchongw.com · 管理端 /admin/',
|
||||
bind_extranet=1, domains=[DOMAIN + ':80'], is_power_on=1,
|
||||
run_user='www', project_cmd=str(current / 'start.sh'), port=PORT,
|
||||
env_file=str(ENV_FILE), env_list=[], release_firewall=0,
|
||||
))
|
||||
if not create.get('status'):
|
||||
raise RuntimeError('BaoTa Go project creation failed: ' + str(create.get('msg')))
|
||||
health('http://127.0.0.1:{}/healthz'.format(PORT))
|
||||
|
||||
if not GO_CONF.is_file():
|
||||
raise RuntimeError('BaoTa did not generate the Go Nginx config')
|
||||
nginx_text = GO_CONF.read_text(encoding='utf-8')
|
||||
if 'proxy_set_header X-Forwarded-Proto $scheme;' not in nginx_text:
|
||||
marker = 'proxy_set_header X-Scheme $scheme;'
|
||||
if nginx_text.count(marker) != 1:
|
||||
raise RuntimeError('Cannot safely add X-Forwarded-Proto to the Go gateway')
|
||||
nginx_text = nginx_text.replace(marker, marker + '\n proxy_set_header X-Forwarded-Proto $scheme;')
|
||||
atomic_write(GO_CONF, nginx_text, 0o644)
|
||||
run(['/www/server/nginx/sbin/nginx', '-t'])
|
||||
run(['/etc/init.d/nginx', 'reload'])
|
||||
health('http://127.0.0.1/healthz', host=DOMAIN)
|
||||
health('http://127.0.0.1/admin/', host=DOMAIN, expected='星遇社交运营中心')
|
||||
|
||||
if int(mysql_query(database_password, "SELECT COUNT(*) FROM admin_users WHERE username='admin' AND status=1")) != 1:
|
||||
raise RuntimeError('Bootstrap administrator was not created')
|
||||
values['IM_BOOTSTRAP_ADMIN_PASSWORD'] = ''
|
||||
atomic_write(ENV_FILE, environment_text(values), 0o640)
|
||||
os.chown(str(ENV_FILE), 0, www.pw_gid)
|
||||
restart = go.restart_project(request(project_name=PROJECT))
|
||||
if not restart.get('status'):
|
||||
raise RuntimeError('BaoTa project restart failed: ' + str(restart.get('msg')))
|
||||
health('http://127.0.0.1:{}/healthz'.format(PORT))
|
||||
|
||||
result = {
|
||||
'status': 'HTTP_DEPLOYMENT_OK',
|
||||
'domain': DOMAIN,
|
||||
'project': PROJECT,
|
||||
'port': PORT,
|
||||
'database': DATABASE,
|
||||
'migrations': 29,
|
||||
'tables': int(mysql_query(database_password,
|
||||
'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE()')),
|
||||
'backend_sha256': digest(release / 'xim-api'),
|
||||
'admin_release': str(admin_release),
|
||||
'server_release': str(release),
|
||||
'credentials_file': str(CREDENTIALS_FILE),
|
||||
'backup': str(backup),
|
||||
}
|
||||
atomic_write(backup / 'result.json', json.dumps(result, ensure_ascii=False, indent=2) + '\n', 0o600)
|
||||
shutil.rmtree(str(stage))
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
# xim.bchongw.com admin routes. API and WebSocket use the BaoTa Go proxy.
|
||||
server_tokens off;
|
||||
client_max_body_size 16m;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
|
||||
location ^~ /admin/v1/ {
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
location = /admin { return 301 /admin/; }
|
||||
location = /admin/ {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files /admin/index.html =404;
|
||||
}
|
||||
location = /admin/index.html {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location = /admin/_app.config.js {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /admin/ {
|
||||
root /www/wwwroot/xim.bchongw.com;
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri $uri/ /admin/index.html;
|
||||
}
|
||||
@@ -0,0 +1,788 @@
|
||||
# 星遇社交平台:宝塔非 Docker 生产环境搭建说明
|
||||
|
||||
本文适用于在宝塔 Linux 面板中,以原生进程方式部署本项目,不使用 Docker。
|
||||
|
||||
部署后的结构如下:
|
||||
|
||||
```text
|
||||
app.example.com
|
||||
-> 宝塔 Nginx
|
||||
-> uni-app H5 静态文件
|
||||
|
||||
admin.example.com
|
||||
-> 宝塔 Nginx
|
||||
-> Vben Admin 静态文件
|
||||
-> /admin/v1/* 反向代理到 127.0.0.1:18888
|
||||
|
||||
api.example.com
|
||||
-> 宝塔 Nginx
|
||||
-> HTTP API、上传文件及 WebSocket
|
||||
-> 反向代理到 127.0.0.1:18888
|
||||
|
||||
127.0.0.1:18888
|
||||
-> Go 后端 systemd 服务
|
||||
-> 宝塔 MySQL
|
||||
```
|
||||
|
||||
> 为什么使用 `18888`:宝塔面板常使用 `8888`,原生部署时后端不能再占用同一个宿主机端口。后端只监听 `127.0.0.1`,不向公网开放。
|
||||
|
||||
## 1. 部署前准备
|
||||
|
||||
### 1.1 推荐配置
|
||||
|
||||
- Ubuntu 24.04 或 Debian 12
|
||||
- 最低 2 核 4 GB,建议 4 核 8 GB
|
||||
- 50 GB 以上磁盘
|
||||
- 宝塔 Linux 面板
|
||||
- Nginx 1.24 或更高版本
|
||||
- MySQL 8.0/8.4
|
||||
- Go 1.27
|
||||
- Node.js 22.18 或更高版本(推荐 Node.js 22 LTS)
|
||||
- pnpm 10.33.4
|
||||
|
||||
项目后端的 `go.mod` 要求 Go 1.27;管理端要求 Node.js `^22.18.0 || ^24.0.0` 和 pnpm 10 或更高版本。不要使用宝塔中较旧的 Node.js 18/20 构建管理端。
|
||||
|
||||
### 1.2 域名
|
||||
|
||||
准备三个域名并添加 A 记录:
|
||||
|
||||
```text
|
||||
app.example.com -> 服务器公网 IP
|
||||
admin.example.com -> 服务器公网 IP
|
||||
api.example.com -> 服务器公网 IP
|
||||
```
|
||||
|
||||
云服务器安全组和宝塔防火墙只需要放行:
|
||||
|
||||
```text
|
||||
22 SSH
|
||||
80 HTTP/证书验证
|
||||
443 HTTPS/WSS
|
||||
```
|
||||
|
||||
不要向公网开放 MySQL `3306` 和后端 `18888`。
|
||||
|
||||
### 1.3 规划目录
|
||||
|
||||
```text
|
||||
/www/wwwroot/xingyu-source/ 项目源代码
|
||||
/www/wwwroot/xingyu-app/ uni-app H5 发布目录
|
||||
/www/wwwroot/xingyu-admin/ 管理端发布目录
|
||||
/www/wwwroot/xingyu-api-empty/ API 域名空站点目录
|
||||
/www/wwwroot/xingyu-data/uploads/ 本地文件存储目录
|
||||
/www/server/xingyu-im/ 后端二进制和迁移脚本
|
||||
/etc/xingyu-im.env 后端生产环境变量
|
||||
```
|
||||
|
||||
## 2. 在宝塔安装基础环境
|
||||
|
||||
在“软件商店”安装:
|
||||
|
||||
1. Nginx。
|
||||
2. MySQL 8.0 或 8.4。
|
||||
3. Node 版本管理器。
|
||||
|
||||
不需要安装 PHP、PM2、Docker、Redis。Go 后端由 systemd 守护,两个前端都是静态文件。
|
||||
|
||||
进入:
|
||||
|
||||
```text
|
||||
网站 -> Node 项目 -> Node 版本管理器
|
||||
```
|
||||
|
||||
安装 Node.js 22.18 以上版本,并设为“命令行版本”。然后在宝塔终端验证:
|
||||
|
||||
```bash
|
||||
node --version
|
||||
npm --version
|
||||
npm install --global pnpm@10.33.4
|
||||
pnpm --version
|
||||
```
|
||||
|
||||
Node.js 必须满足项目声明的版本要求,建议使用当前 Node.js 22 LTS。
|
||||
|
||||
## 3. 安装 Go 1.27
|
||||
|
||||
先检查:
|
||||
|
||||
```bash
|
||||
go version
|
||||
uname -m
|
||||
```
|
||||
|
||||
如果已经是 Go 1.27,可跳过本节。以下命令适用于 `x86_64` 服务器:
|
||||
|
||||
```bash
|
||||
cd /tmp
|
||||
curl -fLO https://go.dev/dl/go1.27.0.linux-amd64.tar.gz
|
||||
echo '675c26c449cbb18fc24b74650de1eabbae6e16f64326fd85a283fb3b58280685 go1.27.0.linux-amd64.tar.gz' | sha256sum -c -
|
||||
install -d /opt/go1.27.0
|
||||
tar -C /opt/go1.27.0 --strip-components=1 -xzf go1.27.0.linux-amd64.tar.gz
|
||||
ln -s /opt/go1.27.0/bin/go /usr/local/bin/go
|
||||
ln -s /opt/go1.27.0/bin/gofmt /usr/local/bin/gofmt
|
||||
go version
|
||||
```
|
||||
|
||||
如果 `/usr/local/bin/go` 已存在,不要直接覆盖;先确认现有 Go 的安装方式和用途。ARM64 服务器应从 Go 官方下载页选择 `linux-arm64` 文件并校验对应 SHA256。
|
||||
|
||||
## 4. 上传源代码
|
||||
|
||||
在宝塔“文件”中将项目上传并解压为:
|
||||
|
||||
```text
|
||||
/www/wwwroot/xingyu-source/
|
||||
├── admin/
|
||||
├── backend/
|
||||
├── mobile/
|
||||
├── deploy/
|
||||
└── README.md
|
||||
```
|
||||
|
||||
确认不是下面这种双层目录:
|
||||
|
||||
```text
|
||||
/www/wwwroot/xingyu-source/im/backend/
|
||||
```
|
||||
|
||||
创建运行目录:
|
||||
|
||||
```bash
|
||||
install -d -o www -g www -m 0755 /www/wwwroot/xingyu-app
|
||||
install -d -o www -g www -m 0755 /www/wwwroot/xingyu-admin
|
||||
install -d -o www -g www -m 0755 /www/wwwroot/xingyu-api-empty
|
||||
install -d -o www -g www -m 0750 /www/wwwroot/xingyu-data/uploads
|
||||
install -d -o root -g root -m 0755 /www/server/xingyu-im
|
||||
```
|
||||
|
||||
## 5. 创建 MySQL 数据库
|
||||
|
||||
进入宝塔“数据库”,创建:
|
||||
|
||||
```text
|
||||
数据库名:im
|
||||
用户名:xingyu_app
|
||||
密码:使用 openssl rand -hex 32 生成
|
||||
字符集:utf8mb4
|
||||
访问权限:本地服务器
|
||||
```
|
||||
|
||||
不要让后端使用 MySQL `root` 账号。生产配置会主动拒绝 `root` DSN。
|
||||
|
||||
生成数据库密码:
|
||||
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
数据库密码建议使用十六进制随机字符串,避免 `@`、`:` 等字符破坏 MySQL DSN 格式。
|
||||
|
||||
## 6. 执行数据库迁移
|
||||
|
||||
本项目包含 `001` 到 `026` 的顺序迁移。非 Docker 环境可以创建下面的迁移脚本:
|
||||
|
||||
```bash
|
||||
nano /www/server/xingyu-im/migrate.sh
|
||||
```
|
||||
|
||||
脚本内容:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
mysql_cli=/www/server/mysql/bin/mysql
|
||||
database_host=127.0.0.1
|
||||
database_name=im
|
||||
database_user=xingyu_app
|
||||
migration_dir=/www/wwwroot/xingyu-source/backend/migrations
|
||||
|
||||
if [ ! -x "$mysql_cli" ]; then
|
||||
mysql_cli="$(command -v mysql)"
|
||||
fi
|
||||
|
||||
if [ -z "${MYSQL_PWD:-}" ]; then
|
||||
echo '请先通过 MYSQL_PWD 环境变量提供数据库密码' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mysql_args=(
|
||||
--host="$database_host"
|
||||
--user="$database_user"
|
||||
--database="$database_name"
|
||||
--default-character-set=utf8mb4
|
||||
--batch
|
||||
--skip-column-names
|
||||
)
|
||||
|
||||
"$mysql_cli" "${mysql_args[@]}" --execute "
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(255) NOT NULL PRIMARY KEY,
|
||||
checksum CHAR(64) NOT NULL,
|
||||
applied_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
"
|
||||
|
||||
for migration_file in "$migration_dir"/*.sql; do
|
||||
migration_name="$(basename "$migration_file")"
|
||||
migration_checksum="$(sha256sum "$migration_file" | awk '{print $1}')"
|
||||
stored_checksum="$("$mysql_cli" "${mysql_args[@]}" --execute "SELECT checksum FROM schema_migrations WHERE version='${migration_name}'" || true)"
|
||||
|
||||
if [ -n "$stored_checksum" ]; then
|
||||
if [ "$stored_checksum" != "$migration_checksum" ]; then
|
||||
echo "迁移校验和不一致:$migration_name" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "已执行:$migration_name"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "正在执行:$migration_name"
|
||||
"$mysql_cli" "${mysql_args[@]}" < "$migration_file"
|
||||
"$mysql_cli" "${mysql_args[@]}" --execute "INSERT INTO schema_migrations(version, checksum) VALUES('${migration_name}', '${migration_checksum}')"
|
||||
done
|
||||
```
|
||||
|
||||
设置权限并执行:
|
||||
|
||||
```bash
|
||||
chmod 0750 /www/server/xingyu-im/migrate.sh
|
||||
export MYSQL_PWD='替换为数据库密码'
|
||||
/www/server/xingyu-im/migrate.sh
|
||||
unset MYSQL_PWD
|
||||
```
|
||||
|
||||
正常情况下会依次显示 `001_users.sql` 到 `026_report_operations.sql`。已经登记过且校验和一致的迁移会跳过。
|
||||
|
||||
不要修改已经在生产数据库执行过的迁移文件;后续数据库变更应该新增编号更大的迁移。
|
||||
|
||||
## 7. 构建 uni-app H5
|
||||
|
||||
客户端 API 域名和 WSS 域名会在构建时写入产物。必须使用正式域名构建:
|
||||
|
||||
```bash
|
||||
cd /www/wwwroot/xingyu-source/mobile
|
||||
corepack enable
|
||||
pnpm install --frozen-lockfile
|
||||
VITE_API_ORIGIN=https://api.example.com \
|
||||
VITE_WS_ORIGIN=wss://api.example.com \
|
||||
VITE_APP_VERSION=1.0.0 \
|
||||
pnpm build:h5
|
||||
```
|
||||
|
||||
发布静态文件:
|
||||
|
||||
```bash
|
||||
rsync -a --delete \
|
||||
/www/wwwroot/xingyu-source/mobile/dist/build/h5/ \
|
||||
/www/wwwroot/xingyu-app/
|
||||
chown -R www:www /www/wwwroot/xingyu-app
|
||||
```
|
||||
|
||||
`rsync --delete` 只会清理 `/www/wwwroot/xingyu-app/` 中上一版本遗留的静态文件,不会操作源代码和用户上传目录。
|
||||
|
||||
域名修改后必须重新构建 H5,单纯修改 Nginx 不会更新已经写入 JavaScript 的 API/WSS 地址。
|
||||
|
||||
## 8. 构建 Vben 管理端
|
||||
|
||||
管理端生产配置使用同域名 `/admin/v1`,由宝塔 Nginx 转发到后端。
|
||||
|
||||
管理端 build 接口地址位于 `admin/.env.production`。如需使用独立 API 域名,编辑:
|
||||
|
||||
```bash
|
||||
nano /www/wwwroot/xingyu-source/admin/.env.production
|
||||
```
|
||||
|
||||
然后将接口地址设为:
|
||||
|
||||
```dotenv
|
||||
VITE_GLOB_API_URL=https://api.example.com/admin/v1
|
||||
```
|
||||
|
||||
保持同域名反向代理时无需修改,默认值就是 `/admin/v1`。开发接口地址位于 `admin/.env.development`,不会影响生产构建。
|
||||
|
||||
先将 `admin/apps/web-ele/.env` 中的下面一项改为独立随机值:
|
||||
|
||||
```dotenv
|
||||
VITE_APP_STORE_SECURE_KEY=替换为独立随机字符串
|
||||
```
|
||||
|
||||
该值可以使用 `openssl rand -hex 32` 生成。它会进入前端产物,不能替代服务端密钥,但不应继续使用示例值。
|
||||
|
||||
执行构建:
|
||||
|
||||
```bash
|
||||
cd /www/wwwroot/xingyu-source/admin
|
||||
pnpm install --frozen-lockfile
|
||||
NODE_OPTIONS=--max-old-space-size=4096 pnpm --filter @vben/web-ele build
|
||||
```
|
||||
|
||||
发布静态文件:
|
||||
|
||||
```bash
|
||||
rsync -a --delete \
|
||||
/www/wwwroot/xingyu-source/admin/apps/web-ele/dist/ \
|
||||
/www/wwwroot/xingyu-admin/
|
||||
chown -R www:www /www/wwwroot/xingyu-admin
|
||||
```
|
||||
|
||||
## 9. 构建和安装 Go 后端
|
||||
|
||||
先运行测试:
|
||||
|
||||
```bash
|
||||
cd /www/wwwroot/xingyu-source/backend
|
||||
go mod download
|
||||
go test ./...
|
||||
```
|
||||
|
||||
测试通过后构建静态二进制:
|
||||
|
||||
```bash
|
||||
CGO_ENABLED=0 go build \
|
||||
-trimpath \
|
||||
-ldflags='-s -w' \
|
||||
-o /tmp/xingyu-api \
|
||||
./cmd/server
|
||||
|
||||
install -o root -g root -m 0755 \
|
||||
/tmp/xingyu-api \
|
||||
/www/server/xingyu-im/xingyu-api
|
||||
```
|
||||
|
||||
生产运行不依赖 Go、Node.js 或 pnpm;它们只在构建和更新时使用。
|
||||
|
||||
## 10. 配置后端生产环境变量
|
||||
|
||||
生成三组不同的密钥:
|
||||
|
||||
```bash
|
||||
openssl rand -hex 48
|
||||
openssl rand -hex 48
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
前两个分别用于 JWT 和平台配置加密,第三个可作为初始管理员密码随机部分。`IM_CONFIG_ENCRYPTION_KEY` 上线后必须永久、安全保存,不能随意更换。
|
||||
|
||||
创建配置文件:
|
||||
|
||||
```bash
|
||||
nano /etc/xingyu-im.env
|
||||
```
|
||||
|
||||
内容如下:
|
||||
|
||||
```dotenv
|
||||
IM_ENV=production
|
||||
IM_HOST=127.0.0.1
|
||||
IM_PORT=18888
|
||||
|
||||
IM_DB_DSN=xingyu_app:替换为数据库密码@tcp(127.0.0.1:3306)/im?charset=utf8mb4&parseTime=True&loc=Local
|
||||
IM_JWT_SECRET=替换为至少32字节的独立随机密钥
|
||||
IM_CONFIG_ENCRYPTION_KEY=替换为另一个至少32字节的独立随机密钥
|
||||
|
||||
IM_ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
|
||||
IM_SEED_DEMO=false
|
||||
IM_MEDIA_DIR=/www/wwwroot/xingyu-data/uploads
|
||||
|
||||
IM_BOOTSTRAP_ADMIN_USERNAME=admin
|
||||
IM_BOOTSTRAP_ADMIN_PASSWORD=替换为至少12位且包含大小写字母数字和特殊字符的密码
|
||||
IM_BOOTSTRAP_ADMIN_REAL_NAME=平台管理员
|
||||
|
||||
TZ=Asia/Shanghai
|
||||
```
|
||||
|
||||
保护配置文件:
|
||||
|
||||
```bash
|
||||
chown root:root /etc/xingyu-im.env
|
||||
chmod 0600 /etc/xingyu-im.env
|
||||
```
|
||||
|
||||
生产环境要求:
|
||||
|
||||
- JWT 密钥至少 32 字节。
|
||||
- 配置加密密钥至少 32 字节。
|
||||
- CORS 来源必须是明确的 HTTPS 地址,不能使用 `*`。
|
||||
- 数据库账号不能是 `root`。
|
||||
- 初始管理员密码至少 12 位,且包含大小写字母、数字和特殊字符。
|
||||
- 禁止开启演示数据。
|
||||
|
||||
## 11. 创建 systemd 服务
|
||||
|
||||
创建:
|
||||
|
||||
```bash
|
||||
nano /etc/systemd/system/xingyu-im.service
|
||||
```
|
||||
|
||||
内容如下:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Xingyu Social Platform API
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=www
|
||||
Group=www
|
||||
WorkingDirectory=/www/server/xingyu-im
|
||||
EnvironmentFile=/etc/xingyu-im.env
|
||||
ExecStart=/www/server/xingyu-im/xingyu-api
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
TimeoutStopSec=30
|
||||
LimitNOFILE=65535
|
||||
UMask=0027
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
PrivateDevices=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/www/wwwroot/xingyu-data/uploads
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
启动服务:
|
||||
|
||||
```bash
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now xingyu-im
|
||||
systemctl status xingyu-im --no-pager
|
||||
```
|
||||
|
||||
查看日志:
|
||||
|
||||
```bash
|
||||
journalctl -u xingyu-im -n 200 --no-pager
|
||||
journalctl -u xingyu-im -f
|
||||
```
|
||||
|
||||
本机验证:
|
||||
|
||||
```bash
|
||||
curl -fsS http://127.0.0.1:18888/healthz
|
||||
ss -lntp | grep 18888
|
||||
```
|
||||
|
||||
应该只能看到 `127.0.0.1:18888`,不能看到 `0.0.0.0:18888`。
|
||||
|
||||
首次启动成功并登录管理端修改密码后,可以清空 `/etc/xingyu-im.env` 中的:
|
||||
|
||||
```dotenv
|
||||
IM_BOOTSTRAP_ADMIN_PASSWORD=
|
||||
```
|
||||
|
||||
然后执行:
|
||||
|
||||
```bash
|
||||
systemctl restart xingyu-im
|
||||
```
|
||||
|
||||
## 12. 在宝塔创建三个网站
|
||||
|
||||
### 12.1 H5 网站
|
||||
|
||||
进入“网站”,新增 HTML 静态网站:
|
||||
|
||||
```text
|
||||
域名:app.example.com
|
||||
根目录:/www/wwwroot/xingyu-app
|
||||
PHP:纯静态
|
||||
```
|
||||
|
||||
在站点 Nginx 配置的 `server` 内确保包含:
|
||||
|
||||
```nginx
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-store";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~* \.(?:js|css|png|jpg|jpeg|gif|webp|svg|ico|woff2?)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
```
|
||||
|
||||
### 12.2 管理端网站
|
||||
|
||||
新增 HTML 静态网站:
|
||||
|
||||
```text
|
||||
域名:admin.example.com
|
||||
根目录:/www/wwwroot/xingyu-admin
|
||||
PHP:纯静态
|
||||
```
|
||||
|
||||
在该站点 `server` 内加入或替换相应 `location`:
|
||||
|
||||
```nginx
|
||||
location ^~ /admin/v1/ {
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
location = /_app.config.js {
|
||||
expires -1;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-store";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location ~* \.(?:js|css|png|jpg|jpeg|gif|webp|svg|ico|woff2?)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
```
|
||||
|
||||
`/_app.config.js` 保存管理端运行时接口地址,必须禁止浏览器和 CDN 缓存;否则修改接口域名后客户端可能继续请求旧地址。
|
||||
|
||||
### 12.3 API 和 WebSocket 网站
|
||||
|
||||
新增网站:
|
||||
|
||||
```text
|
||||
域名:api.example.com
|
||||
根目录:/www/wwwroot/xingyu-api-empty
|
||||
PHP:纯静态
|
||||
```
|
||||
|
||||
在该站点 `server` 内加入:
|
||||
|
||||
```nginx
|
||||
client_max_body_size 16m;
|
||||
|
||||
location ^~ /ws {
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 70s;
|
||||
proxy_send_timeout 70s;
|
||||
proxy_buffering off;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
```
|
||||
|
||||
保存配置前点击宝塔的配置检查,或在终端执行:
|
||||
|
||||
```bash
|
||||
nginx -t
|
||||
```
|
||||
|
||||
检查成功后重载:
|
||||
|
||||
```bash
|
||||
/etc/init.d/nginx reload
|
||||
```
|
||||
|
||||
不要在宝塔中再为 API 域名创建另一条普通“反向代理”,避免宝塔生成的 `location /` 与上面的 WebSocket 配置冲突。
|
||||
|
||||
## 13. 配置 HTTPS
|
||||
|
||||
依次打开三个网站:
|
||||
|
||||
```text
|
||||
网站设置 -> SSL -> Let's Encrypt
|
||||
```
|
||||
|
||||
分别申请证书并开启强制 HTTPS。宝塔负责证书文件和自动续签。
|
||||
|
||||
证书完成后验证:
|
||||
|
||||
```bash
|
||||
curl -fsS https://api.example.com/healthz
|
||||
```
|
||||
|
||||
客户端必须使用:
|
||||
|
||||
```text
|
||||
https://api.example.com
|
||||
wss://api.example.com/ws
|
||||
```
|
||||
|
||||
不能在生产页面中连接 `http://` 或 `ws://`,否则浏览器会拦截混合内容,消息传输也没有 TLS 保护。
|
||||
|
||||
## 14. 上线验收
|
||||
|
||||
### 14.1 服务状态
|
||||
|
||||
```bash
|
||||
systemctl is-active xingyu-im
|
||||
curl -fsS http://127.0.0.1:18888/healthz
|
||||
curl -fsS https://api.example.com/healthz
|
||||
```
|
||||
|
||||
### 14.2 页面
|
||||
|
||||
- `https://app.example.com`
|
||||
- `https://admin.example.com`
|
||||
- `https://api.example.com/healthz`
|
||||
|
||||
### 14.3 核心功能
|
||||
|
||||
至少完成以下测试:
|
||||
|
||||
1. 用户注册、密码登录、验证码登录和找回密码。
|
||||
2. H5 图片上传、头像修改和动态发布。
|
||||
3. WebSocket 连接、消息发送、接收、历史消息和未读数。
|
||||
4. 管理端登录与管理员密码修改。
|
||||
5. 管理端用户、会员、订单、认证、违规、动态和消息记录查询。
|
||||
6. 短信厂商配置保存、切换和发送测试。
|
||||
7. 文件存储厂商配置保存、切换和上传测试。
|
||||
8. 第三方登录授权、回调和账号绑定。
|
||||
9. 支付下单、异步通知、订单状态和退款流程。
|
||||
|
||||
生产环境不能继续使用 debug 短信或 sandbox 支付。第三方厂商的回调地址必须填写正式 HTTPS 域名。
|
||||
|
||||
## 15. 日常更新流程
|
||||
|
||||
每次发布前先备份数据库、上传目录和 `/etc/xingyu-im.env`。
|
||||
|
||||
推荐顺序:
|
||||
|
||||
```bash
|
||||
export MYSQL_PWD='替换为数据库密码'
|
||||
/www/server/xingyu-im/migrate.sh
|
||||
unset MYSQL_PWD
|
||||
|
||||
cd /www/wwwroot/xingyu-source/backend
|
||||
go test ./...
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /tmp/xingyu-api ./cmd/server
|
||||
install -o root -g root -m 0755 /tmp/xingyu-api /www/server/xingyu-im/xingyu-api
|
||||
systemctl restart xingyu-im
|
||||
systemctl status xingyu-im --no-pager
|
||||
```
|
||||
|
||||
然后按第 7、8 节重新构建并发布两个前端。
|
||||
|
||||
如后端启动失败,立即查看:
|
||||
|
||||
```bash
|
||||
journalctl -u xingyu-im -n 200 --no-pager
|
||||
```
|
||||
|
||||
不要在未确认数据库迁移兼容性的情况下直接覆盖生产版本。
|
||||
|
||||
## 16. 备份要求
|
||||
|
||||
至少备份:
|
||||
|
||||
```text
|
||||
MySQL 数据库 im
|
||||
/www/wwwroot/xingyu-data/uploads
|
||||
/etc/xingyu-im.env
|
||||
/www/server/xingyu-im/xingyu-api
|
||||
宝塔三个站点的 Nginx 配置和 SSL 证书
|
||||
```
|
||||
|
||||
建议:
|
||||
|
||||
- MySQL 每天备份,保留 7~30 天。
|
||||
- 上传目录每天增量备份。
|
||||
- 备份复制到另一台服务器或对象存储,不能只留在本机。
|
||||
- 定期执行恢复演练,而不是只检查“备份任务成功”。
|
||||
- `/etc/xingyu-im.env` 包含敏感密钥,备份文件必须加密并限制访问。
|
||||
|
||||
## 17. 常见故障
|
||||
|
||||
### 后端启动失败
|
||||
|
||||
```bash
|
||||
systemctl status xingyu-im --no-pager
|
||||
journalctl -u xingyu-im -n 200 --no-pager
|
||||
```
|
||||
|
||||
常见原因:数据库未迁移、密钥不足 32 字节、管理员密码强度不足、使用 root DSN、CORS 使用 HTTP 或 `*`。
|
||||
|
||||
### 管理端接口返回 404
|
||||
|
||||
检查管理端站点是否存在 `/admin/v1/` 反向代理,以及 `proxy_pass` 是否为:
|
||||
|
||||
```nginx
|
||||
proxy_pass http://127.0.0.1:18888;
|
||||
```
|
||||
|
||||
### H5 仍然连接本机地址
|
||||
|
||||
说明 H5 构建时没有设置生产变量。按第 7 节重新构建,不能只修改 Nginx。
|
||||
|
||||
### WebSocket 连接失败
|
||||
|
||||
检查:
|
||||
|
||||
- API 域名证书是否有效。
|
||||
- H5 是否使用 `wss://api.example.com`。
|
||||
- `/ws` 是否设置 Upgrade/Connection 请求头。
|
||||
- `/etc/xingyu-im.env` 是否允许 H5 域名来源。
|
||||
- 服务器时间是否准确。
|
||||
|
||||
### 上传失败
|
||||
|
||||
检查:
|
||||
|
||||
```bash
|
||||
ls -ld /www/wwwroot/xingyu-data/uploads
|
||||
sudo -u www test -w /www/wwwroot/xingyu-data/uploads
|
||||
```
|
||||
|
||||
同时确认 API 站点配置了:
|
||||
|
||||
```nginx
|
||||
client_max_body_size 16m;
|
||||
```
|
||||
|
||||
### Node 构建内存不足
|
||||
|
||||
管理端构建建议至少提供 4 GB 可用内存。可以设置:
|
||||
|
||||
```bash
|
||||
NODE_OPTIONS=--max-old-space-size=4096 pnpm --filter @vben/web-ele build
|
||||
```
|
||||
|
||||
如果仍然被系统杀死,应增加内存或临时交换空间,不要不断重试导致服务器失去响应。
|
||||
|
||||
## 18. 官方资料
|
||||
|
||||
- [宝塔安装基础环境](https://docs.bt.cn/getting-started/install-basic-environment)
|
||||
- [宝塔安装 Web 服务器](https://docs.bt.cn/user-guide/site/install-webserver)
|
||||
- [宝塔网站 SSL 配置](https://docs.bt.cn/user-guide/site/php/site-config/ssl)
|
||||
- [Go 官方下载](https://go.dev/dl/)
|
||||
- [Node.js 22 官方下载](https://nodejs.org/en/download/archive/v22)
|
||||
- [pnpm 官方安装说明](https://pnpm.io/installation)
|
||||
Reference in New Issue
Block a user