This commit is contained in:
zyp
2026-11-27 21:27:14 +08:00
parent b18c6efe92
commit 5f204764c9
12 changed files with 563 additions and 28 deletions
+19
View File
@@ -40,6 +40,25 @@
默认 8000。如需其他端口,可修改 compose.yml 的 ports 映射。
需允许 Java 所在服务器访问该端口。
保留人员分析、清理其他测试运行数据后重新部署(不要用于普通更新)
1. 先停止连接此实例的所有 Java 服务,避免旧任务再次写入。
2. 在本部署目录执行 bash reset-runtime.sh --check;只检查,不停服、不修改数据。
3. 确认要重新分析后执行 bash reset-runtime.sh --apply。
如需使用开发机已经备份的人员缓存,在命令后加:
--personnel-source /实际解压目录/personnel-retention/python-jobs
--check和--apply均支持此参数;不传则保留服务器现有人员缓存。
脚本停止 assistant,将 data/jobs、data/checkpoints 原目录移入
backups/runtime-before-reset-时间戳,再创建运行目录,并从备份提取人员分析任务/结果/断点及人员历史缓存;其他任务和会话清空。
旧数据完整保留,可回退。
assistant.env、同机模型、PostgreSQL、Redis、Java 业务库和附件不受影响。
4. 执行 bash deploy.sh 部署新版,健康检查通过后再启动 Java。
仅清理 Python 不会清空 Java 库内已发布画像和审核结果。
若要从正式库基线重新演练且保留已完成人员画像,须先导出MySQL中personnel_profile的完整结果链,
覆盖测试库后执行升级SQL,再恢复人员画像SQL,最后才启动Java。只保留Python缓存不能保住页面上的画像。
5. 回退运行数据时先停 assistant,将新 data/jobs、data/checkpoints 另行备份,
再将同一个备份目录内的 jobs、checkpoints 移回原处;同时核对数据库与代码版本。
不要混用两个不同备份或把测试运行数据带入正式环境。
回退
每次构建保留 company-ai-assistant:版本号 镜像。查看可用版本:
docker image ls company-ai-assistant
+58
View File
@@ -0,0 +1,58 @@
"""Retain personnel review checkpoints/results, excluding other assistant workloads."""
import json
from pathlib import Path
import sqlite3
from contextlib import closing
def is_personnel(checkpoint, result):
for raw in (checkpoint, result):
try:
value = json.loads(raw) if raw else {}
except (ValueError, TypeError):
continue
if not isinstance(value, dict):
continue
if str(value.get('analysis_version', '')).startswith('personnel-'):
return True
if str(value.get('rule', '')).startswith('personnel-'):
return True
if isinstance(value.get('talent'), dict):
return True
return False
def retain_personnel(source, target):
source, target = Path(source).resolve(), Path(target).resolve()
if source == target or source in target.parents or target in source.parents:
raise ValueError('Source and destination must be separate runtime directories')
target.mkdir(parents=True, exist_ok=True)
stats = {'personnel_jobs': 0, 'ready': 0, 'history_pages': 0}
old = source / 'review-jobs.sqlite3'
if old.exists():
new = target / old.name
if new.exists():
raise FileExistsError('Destination review database already exists')
with closing(sqlite3.connect(old.as_uri() + '?mode=ro', uri=True, timeout=10)) as src:
schema = src.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='review_job'").fetchone()
if schema:
src.row_factory = sqlite3.Row
with closing(sqlite3.connect(new)) as dst:
dst.execute(schema[0])
for row in src.execute('SELECT * FROM review_job'):
if not is_personnel(row['checkpoint'], row['result']):
continue
dst.execute('INSERT INTO review_job VALUES(' + ','.join('?' for _ in row) + ')', tuple(row))
stats['personnel_jobs'] += 1
stats['ready'] += row['status'] == 'ready'
dst.commit()
old_cache = source / 'personnel-history.sqlite3'
if old_cache.exists():
new_cache = target / old_cache.name
if new_cache.exists():
raise FileExistsError('Destination personnel cache already exists')
with closing(sqlite3.connect(old_cache.as_uri() + '?mode=ro', uri=True, timeout=10)) as src:
with closing(sqlite3.connect(new_cache)) as dst:
src.backup(dst)
stats['history_pages'] = dst.execute('SELECT COUNT(*) FROM history_page').fetchone()[0]
return stats
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
mode=${1:---check}
[[ "$mode" == --check || "$mode" == --apply ]] || { echo 'Usage: bash reset-runtime.sh [--check|--apply]' >&2; exit 2; }
if [[ $# -gt 1 ]]; then
[[ $# -eq 3 && "$2" == --personnel-source ]] || { echo 'Optional: --personnel-source /absolute/path/to/python-jobs' >&2; exit 2; }
fi
command -v docker >/dev/null
command -v python3 >/dev/null
python3 - "$mode" "${3:-}" <<'PY'
import datetime
import json
import os
from pathlib import Path
import subprocess
import sys
import sqlite3
from contextlib import closing
from personnel_runtime import retain_personnel
apply = sys.argv[1] == '--apply'
root = Path.cwd().resolve()
compose = ['docker', 'compose', '--env-file', '/dev/null', '-f', 'compose.yml']
if not (root / 'compose.yml').is_file() or not (root / 'assistant.env').is_file():
raise SystemExit('Run this script from the deployed assistant package directory; compose.yml and assistant.env are required.')
config = json.loads(subprocess.check_output(compose + ['config', '--format', 'json']))
service = config.get('services', {}).get('assistant', {})
if service.get('environment', {}).get('APP_MODE') != 'work-assistant':
raise SystemExit('Refusing reset: this is not the standalone work-assistant service.')
if not str(service.get('image', '')).startswith('company-ai-assistant:'):
raise SystemExit('Refusing reset: unexpected assistant image.')
targets = [root / 'data' / 'jobs', root / 'data' / 'checkpoints']
personnel_source = Path(sys.argv[2]).resolve() if len(sys.argv) > 2 and sys.argv[2] else None
if personnel_source:
if not personnel_source.is_dir() or any(personnel_source == t or t in personnel_source.parents or personnel_source in t.parents for t in targets):
raise SystemExit('Personnel snapshot must be a separate existing directory outside runtime targets.')
snapshot = personnel_source / 'review-jobs.sqlite3'
if not snapshot.is_file() or snapshot.is_symlink():
raise SystemExit('Personnel snapshot review-jobs.sqlite3 is missing or a symlink.')
with closing(sqlite3.connect(snapshot.as_uri() + '?mode=ro', uri=True)) as connection:
if connection.execute('PRAGMA quick_check').fetchone()[0] != 'ok':
raise SystemExit('Personnel snapshot failed SQLite integrity verification.')
connection.execute('SELECT checkpoint,result FROM review_job LIMIT 1').fetchall()
mounts = {v.get('target'): v for v in service.get('volumes', [])}
for target, container_path in zip(targets, ['/app/.private', '/app/data']):
if (root / 'data').is_symlink() or target.is_symlink() or target.resolve() != target:
raise SystemExit('Refusing reset: runtime path is a symlink or outside the deployment directory.')
mount = mounts.get(container_path, {})
if mount.get('type') != 'bind' or Path(mount.get('source', '')).resolve() != target:
raise SystemExit('Refusing reset: Compose bind mounts differ from data/jobs and data/checkpoints.')
if target.exists() and not target.is_dir():
raise SystemExit('Refusing reset: runtime target is not a directory.')
ids = subprocess.check_output(compose + ['ps', '--all', '--quiet', 'assistant'], text=True).split()
all_ids = subprocess.check_output(['docker', 'ps', '--all', '--quiet'], text=True).split()
if all_ids:
for container in json.loads(subprocess.check_output(['docker', 'inspect'] + all_ids)):
if container['Id'] in ids:
continue
for mount in container.get('Mounts', []):
source = Path(mount['Source']).resolve()
if any(source == target or source in target.parents or target in source.parents for target in targets):
raise SystemExit('Refusing reset: another container mounts these runtime paths: ' + container.get('Name', 'unknown'))
backup_root = root / 'backups'
if backup_root.is_symlink() or backup_root.resolve() != backup_root:
raise SystemExit('Refusing reset: backups directory is a symlink.')
print('Deployment:', root)
print('Reset scope: non-personnel jobs and conversation checkpoints; personnel analyses and history cache are retained.')
print('Preserved: assistant.env, model services, PostgreSQL, Redis, Java files and business database.')
print('Personnel source:', personnel_source or 'existing server runtime')
print('Stop all Java instances connected to this assistant before --apply; otherwise jobs may be recreated.')
if not apply:
print('CHECK PASSED. No service stopped and no data changed. Use --apply only when ready to reset.')
raise SystemExit(0)
subprocess.run(compose + ['stop', '--timeout', '60', 'assistant'], check=True)
if ids:
for container in json.loads(subprocess.check_output(['docker', 'inspect'] + ids)):
if container['State']['Running']:
raise SystemExit('Assistant is still running; runtime data was not moved.')
backup = backup_root / ('runtime-before-reset-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
backup.mkdir(parents=True, mode=0o700)
os.chmod(backup, 0o700)
manifest = {'deployment': str(root), 'moved': [], 'state': 'moving'}
manifest_path = backup / 'manifest.json'
def record():
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
os.chmod(manifest_path, 0o600)
record()
for target in targets:
if target.exists():
target.rename(backup / target.name)
manifest['moved'].append(target.name)
record()
target.mkdir(parents=True, exist_ok=True)
manifest['personnel_retained'] = retain_personnel(personnel_source or backup / 'jobs', root / 'data' / 'jobs')
manifest['state'] = 'complete'
record()
print('RESET COMPLETE. Old data retained at:', backup)
print('Personnel retained:', manifest['personnel_retained'])
print('Assistant remains STOPPED. Deploy the new package with: bash deploy.sh')
print('After the database upgrade and assistant health check, start Java to regenerate analyses.')
PY