update
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user