mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 04:03:13 +00:00
内置 PostgreSQL 的四条取舍:agentlab.env 模板末尾追加注释掉的「内置 PostgreSQL(可选)」一段(POSTGRES_IMAGE、POSTGRES_CONTAINER、DOCKER_NETWORK、POSTGRES_VOLUME、BACKUP_KEEP,缺省值写在注释里,已有的行一行没动);升级前的备份收紧权限——backups/ 起每一层目录 0700、备份文件 0600,属主同数据目录(SQLite 的在 umask 077 下先以 0600 建空文件再交给备份接口写,pg_dump 在 umask 077 下写、目录由 app.ops backup-dir 建和收紧),恢复步骤里写清哪一步要 sudo、内置库的恢复改成在以 10001 运行的临时容器里读备份(不用 sudo);restart 缺省只重启服务(库停着时先把库起来),restart --postgres 连库一起重启,没用内置库时加 --postgres 照实报错;离线包缺省带 PostgreSQL 镜像不变,deploy/README 写清多出约 160 MB、导入后约 0.7 GB;deploy/README 加「首次在 Linux 上切换前的检查」(docker 版本、属主、权限、磁盘空间、整目录备份)。单测核对权限位、restart 两种用法、模板里的注释和 deploy.sh 的缺省值一致
This commit is contained in:
+47
-5
@@ -10,12 +10,17 @@
|
||||
用的仍是 SQLite,只是让下一次 migrate-to-postgres 认得出数据卷里那半份是自己上次留下的
|
||||
backup-sqlite 拷一份 agentlab.db、checkpoints.db 到 <数据目录>/backups/sqlite/<时间>/(SQLite 的备份接口,一致的一份),
|
||||
只留最近 --keep 份
|
||||
backup-dir 建(或收紧)备份目录:从 backups/ 起每一层 0700(pg_dump 写进去之前用)
|
||||
prune 目录里按名字排序只留最近 --keep 个(pg_dump 的备份用)
|
||||
|
||||
备份里是整个库(含加密存的密钥、业务数据),目录一律 0700、文件 0600,属主是容器里的用户(同数据目录);宿主机上要读用 sudo。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import sys
|
||||
@@ -28,6 +33,10 @@ from app.core import atomic
|
||||
POSTGRES_DIR = ".postgres"
|
||||
STATE_FILE = "state"
|
||||
MODES = ("sqlite", "builtin", "migrating")
|
||||
BACKUPS_DIR = "backups"
|
||||
#: 备份的目录、文件的权限:只有属主(容器里的用户)能读
|
||||
BACKUP_DIR_MODE = 0o700
|
||||
BACKUP_FILE_MODE = 0o600
|
||||
|
||||
|
||||
def _stamp() -> str:
|
||||
@@ -77,16 +86,42 @@ def write_state(data: Path, mode: str) -> None:
|
||||
atomic.write_text(root / STATE_FILE, f"mode={mode}\nsince={datetime.now(timezone.utc).isoformat()}\n", mode=0o644)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _private_umask():
|
||||
"""这一段里新建的文件、目录别人读不到(SQLite 备份时建的 -journal 也一样),出来恢复原来的 umask。"""
|
||||
old = os.umask(0o077)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.umask(old)
|
||||
|
||||
|
||||
def backup_dir(data: Path, *parts: str) -> Path:
|
||||
"""<数据目录>/backups/<parts…>:从 backups/ 起每一层建出来(已有的收紧)成 0700,交回最里面那层。"""
|
||||
folder = data / BACKUPS_DIR
|
||||
levels = [folder]
|
||||
for part in parts:
|
||||
folder = folder / part
|
||||
levels.append(folder)
|
||||
for level in levels:
|
||||
level.mkdir(exist_ok=True)
|
||||
level.chmod(BACKUP_DIR_MODE)
|
||||
return folder
|
||||
|
||||
|
||||
def _copy_sqlite(src: Path, dst: Path) -> None:
|
||||
# 读写打开、只许读:WAL 模式的库用 mode=ro 打开,关掉时会留下它自己建的 -wal(同 db/to_postgres.snapshot)
|
||||
conn = sqlite3.connect(src)
|
||||
conn.execute("PRAGMA query_only = 1")
|
||||
try:
|
||||
# 先以 0600 建出空文件再交给 SQLite 写:从有这个文件起就只有属主读得到
|
||||
os.close(os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, BACKUP_FILE_MODE))
|
||||
out = sqlite3.connect(dst)
|
||||
try:
|
||||
conn.backup(out)
|
||||
finally:
|
||||
out.close()
|
||||
dst.chmod(BACKUP_FILE_MODE)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -112,11 +147,13 @@ def backup_sqlite(data: Path, *, keep: int) -> Path | None:
|
||||
sources = [p for p in (data / "agentlab.db", data / "checkpoints.db") if p.is_file()]
|
||||
if not sources:
|
||||
return None
|
||||
root = data / "backups" / "sqlite"
|
||||
target = root / _stamp()
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for src in sources:
|
||||
_copy_sqlite(src, target / src.name)
|
||||
with _private_umask():
|
||||
root = backup_dir(data, "sqlite")
|
||||
target = root / _stamp()
|
||||
target.mkdir(exist_ok=True)
|
||||
target.chmod(BACKUP_DIR_MODE)
|
||||
for src in sources:
|
||||
_copy_sqlite(src, target / src.name)
|
||||
prune(root, keep)
|
||||
return target
|
||||
|
||||
@@ -137,6 +174,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
b = sub.add_parser("backup-sqlite")
|
||||
b.add_argument("--data", default="/data")
|
||||
b.add_argument("--keep", type=int, default=5)
|
||||
d = sub.add_parser("backup-dir")
|
||||
d.add_argument("--data", default="/data")
|
||||
d.add_argument("parts", nargs="*", help="backups/ 下面的几层,比如 postgres")
|
||||
r = sub.add_parser("prune")
|
||||
r.add_argument("--dir", required=True)
|
||||
r.add_argument("--keep", type=int, default=5)
|
||||
@@ -153,6 +193,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
elif args.command == "backup-sqlite":
|
||||
target = backup_sqlite(Path(args.data), keep=args.keep)
|
||||
print(target if target is not None else "没有 SQLite 库,不用备份")
|
||||
elif args.command == "backup-dir":
|
||||
print(backup_dir(Path(args.data), *args.parts))
|
||||
elif args.command == "prune":
|
||||
for gone in prune(Path(args.dir), args.keep):
|
||||
print(f"删掉旧备份 {gone.name}")
|
||||
|
||||
@@ -154,7 +154,7 @@ def run_oneoff(state: dict, opts: dict, image: str, command: list[str]) -> int:
|
||||
from app import ops
|
||||
|
||||
rest = [to_host(a, data) for a in command[2:]]
|
||||
if rest and rest[0] in ("postgres-secrets", "state", "backup-sqlite") and "--data" not in rest:
|
||||
if rest and rest[0] in ("postgres-secrets", "state", "backup-sqlite", "backup-dir") and "--data" not in rest:
|
||||
rest[1:1] = ["--data", data or "/data"]
|
||||
return ops.main(rest)
|
||||
if entry == "python" and command[:3] == ["-m", "app.db", "copy-to-postgres"]:
|
||||
@@ -171,12 +171,17 @@ def run_oneoff(state: dict, opts: dict, image: str, command: list[str]) -> int:
|
||||
if not a.startswith("-"):
|
||||
Path(to_host(a, data)).mkdir(parents=True, exist_ok=True)
|
||||
return 0
|
||||
if entry == "pg_dump":
|
||||
if entry == "sh" and command[:1] == ["-c"] and 'pg_dump "$@"' in command[1]:
|
||||
# sh -c '<脚本>' pg_dump <参数…>:照脚本里的 umask 建文件
|
||||
umask = 0o077 if "umask 077" in command[1] else 0o022
|
||||
if os.environ.get("FAKE_PGDUMP_FAIL"):
|
||||
print("pg_dump: fake 的失败", file=sys.stderr)
|
||||
return 1
|
||||
out = command[command.index("-f") + 1]
|
||||
Path(to_host(out, data)).write_bytes(b"PGDMP fake")
|
||||
args = command[3:]
|
||||
out = Path(to_host(args[args.index("-f") + 1], data))
|
||||
fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o666 & ~umask)
|
||||
with os.fdopen(fd, "wb") as fh:
|
||||
fh.write(b"PGDMP fake")
|
||||
return 0
|
||||
unknown(["run", "--rm", image, *command])
|
||||
return 99
|
||||
|
||||
@@ -127,7 +127,8 @@ def deploy(tmp_path):
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [["bogus"], ["start", "--postgres"], ["upgrade", "--postgres"],
|
||||
@pytest.mark.parametrize("args", [["bogus"], ["start", "--postgres"], ["upgrade", "--postgres"], ["status", "--postgres"],
|
||||
["restart", "--all"],
|
||||
["install", "--purge-image"], ["migrate-to-postgres", "-f"], ["status", "--tail", "3"]])
|
||||
def test_unknown_arguments_are_refused_before_doing_anything(deploy, args):
|
||||
out = deploy(*args, ok=False)
|
||||
@@ -138,7 +139,8 @@ def test_unknown_arguments_are_refused_before_doing_anything(deploy, args):
|
||||
|
||||
def test_help_lists_the_postgres_commands(deploy):
|
||||
out = deploy("--help")
|
||||
for word in ("install [--postgres]", "migrate-to-postgres", "logs [-f] [--tail N] [--postgres]", "DEPLOY_<名字>"):
|
||||
for word in ("install [--postgres]", "migrate-to-postgres", "restart [--postgres]", "logs [-f] [--tail N] [--postgres]",
|
||||
"DEPLOY_<名字>"):
|
||||
assert word in out.stdout
|
||||
|
||||
|
||||
@@ -282,14 +284,39 @@ def test_start_stop_restart_order_the_two_containers(deploy):
|
||||
pg_ready = index_of(calls, lambda a: a[:1] == ["inspect"] and a[-1] == PG and ".State.Health" in a[2])
|
||||
assert pg_start < pg_ready < index_of(calls, is_cmd("start", APP)), "先起库、等就绪,再起服务"
|
||||
|
||||
deploy("restart")
|
||||
deploy("restart", "--postgres")
|
||||
calls = deploy.calls()
|
||||
order = [index_of(calls, is_cmd("stop", APP)), index_of(calls, is_cmd("stop", PG)),
|
||||
index_of(calls, is_cmd("start", PG)), index_of(calls, is_cmd("start", APP))]
|
||||
assert order == sorted(order)
|
||||
assert order == sorted(order), "--postgres:先停服务、再停库,先起库、再起服务"
|
||||
assert {c["state"] for c in deploy.containers().values()} == {"running"}
|
||||
|
||||
|
||||
def test_restart_by_default_leaves_the_database_alone(deploy):
|
||||
deploy("install", "--postgres")
|
||||
out = deploy("restart")
|
||||
calls = deploy.calls()
|
||||
assert ["restart", APP] in calls
|
||||
assert not any(a[:1] in (["stop"], ["start"], ["restart"]) and a[-1] == PG for a in calls), "库不跟着重启"
|
||||
assert "已重启" in out.stdout
|
||||
# 库停着时先把库起来,服务才连得上
|
||||
state = deploy.state()
|
||||
state["containers"][PG]["state"] = "exited"
|
||||
deploy.state_file.write_text(json.dumps(state))
|
||||
deploy("restart")
|
||||
calls = deploy.calls()
|
||||
assert index_of(calls, is_cmd("start", PG)) < index_of(calls, lambda a: a == ["restart", APP])
|
||||
assert not any(is_cmd("stop", PG)(a) for a in calls)
|
||||
assert deploy.containers()[PG]["state"] == "running"
|
||||
|
||||
|
||||
def test_restart_postgres_needs_the_builtin_database(deploy):
|
||||
deploy("install")
|
||||
out = deploy("restart", "--postgres", ok=False)
|
||||
assert "没用内置 PostgreSQL" in out.stderr
|
||||
assert not any(a[:1] in (["stop"], ["restart"]) for a in deploy.calls()), "什么都没动"
|
||||
|
||||
|
||||
def test_status_and_logs_show_the_database(deploy):
|
||||
deploy("install", "--postgres")
|
||||
out = deploy("status").stdout
|
||||
@@ -346,14 +373,19 @@ def test_upgrade_builtin_dumps_after_stopping_the_app_and_keeps_the_last_n(deplo
|
||||
deploy("upgrade", DEPLOY_BACKUP_KEEP="3")
|
||||
calls = deploy.calls()
|
||||
stop = index_of(calls, is_cmd("stop", APP))
|
||||
dump = index_of(calls, oneoff("pg_dump"))
|
||||
dump = index_of(calls, oneoff("sh", "pg_dump"))
|
||||
new_app = index_of(calls, runs_named(APP))
|
||||
assert stop < dump < new_app, "停了旧服务再备份,备份完才起新的"
|
||||
dump_args = calls[dump]
|
||||
assert dump_args[dump_args.index("--network") + 1] == NET and "PGPASSFILE=/data/.postgres/pgpass" in dump_args
|
||||
assert dump_args[dump_args.index("-c") + 1].startswith("umask 077 && "), "备份文件从建出来就是 0600"
|
||||
assert dump_args[dump_args.index("--user") + 1] == "10001:10001", "属主照数据目录:容器里的用户"
|
||||
kept = sorted(p.name for p in folder.iterdir())
|
||||
assert len(kept) == 3 and kept[-1].startswith("agentlab-") and kept[-1] > "agentlab-20260103", kept
|
||||
assert (folder / kept[-1]).read_bytes() == b"PGDMP fake"
|
||||
assert stat.S_IMODE((folder / kept[-1]).stat().st_mode) == 0o600
|
||||
for level in (deploy.data / "backups", folder):
|
||||
assert stat.S_IMODE(level.stat().st_mode) == 0o700, level
|
||||
|
||||
|
||||
def test_upgrade_sqlite_backs_up_the_database_files(deploy):
|
||||
@@ -367,6 +399,9 @@ def test_upgrade_sqlite_backs_up_the_database_files(deploy):
|
||||
copy = sqlite3.connect(stamp / "agentlab.db")
|
||||
assert copy.execute("SELECT v FROM t").fetchall() == [("一",)]
|
||||
copy.close()
|
||||
for level in (deploy.data / "backups", deploy.data / "backups" / "sqlite", stamp):
|
||||
assert stat.S_IMODE(level.stat().st_mode) == 0o700, level
|
||||
assert stat.S_IMODE((stamp / "agentlab.db").stat().st_mode) == 0o600
|
||||
|
||||
|
||||
def test_failed_backup_aborts_the_upgrade_and_restarts_the_old_service(deploy):
|
||||
@@ -515,6 +550,28 @@ def test_package_script_takes_the_postgres_image_from_deploy_sh():
|
||||
assert out.stdout.strip() == PG_IMAGE
|
||||
|
||||
|
||||
def test_env_template_lists_the_postgres_settings_commented_out_with_the_defaults():
|
||||
"""agentlab.env 模板末尾的「内置 PostgreSQL(可选)」:几项都注释着(不改任何人的部署),缺省值和 deploy.sh 里的一致。"""
|
||||
template = (REPO / "deploy" / "agentlab.env").read_text(encoding="utf-8")
|
||||
section = template[template.index("# ---- 内置 PostgreSQL(可选)----"):]
|
||||
assert template.rstrip().endswith(section.rstrip()), "追加在文件末尾"
|
||||
commented = dict(line[2:].split("=", 1) for line in section.splitlines()
|
||||
if line.startswith("# ") and "=" in line and line[2:3].isupper())
|
||||
assert commented == {"POSTGRES_IMAGE": PG_IMAGE, "POSTGRES_CONTAINER": "agentlab-postgres",
|
||||
"DOCKER_NETWORK": "agentlab-net", "POSTGRES_VOLUME": "agentlab-pgdata", "BACKUP_KEEP": "5"}
|
||||
assert not any(line.split("=", 1)[0] in commented for line in template.splitlines() if not line.startswith("#")), \
|
||||
"都是注释"
|
||||
|
||||
|
||||
def test_settings_written_in_agentlab_env_take_effect(tmp_path):
|
||||
deploy = Deploy(tmp_path, env_lines=["POSTGRES_CONTAINER=agl-db", "DOCKER_NETWORK=agl-n", "POSTGRES_VOLUME=agl-v",
|
||||
"BACKUP_KEEP=1"])
|
||||
deploy("install", "--postgres")
|
||||
assert set(deploy.containers()) == {APP, "agl-db"}
|
||||
assert deploy.containers()["agl-db"]["mounts"]["/var/lib/postgresql/data"] == "agl-v"
|
||||
assert deploy.containers()[APP]["network"] == "agl-n"
|
||||
|
||||
|
||||
def test_dev_script_refuses_unknown_arguments_and_documents_postgres():
|
||||
env = {**os.environ, "PATH": "/usr/bin:/bin"}
|
||||
out = subprocess.run(["bash", str(REPO / "scripts" / "dev.sh"), "--bogus"], capture_output=True, text=True, env=env)
|
||||
|
||||
@@ -95,6 +95,11 @@ def test_backup_sqlite_copies_a_consistent_snapshot_including_the_wal(tmp_path,
|
||||
assert copy.execute("SELECT v FROM t").fetchall() == [("还在 WAL 里",)]
|
||||
copy.close()
|
||||
assert (stamp / "checkpoints.db").exists()
|
||||
# 备份里是整个库:目录只有属主进得去,文件只有属主读得到
|
||||
for level in (tmp_path / "backups", target, stamp):
|
||||
assert _mode(level) == 0o700, level
|
||||
assert _mode(stamp / "agentlab.db") == 0o600 and _mode(stamp / "checkpoints.db") == 0o600
|
||||
assert sorted(p.name for p in stamp.iterdir()) == ["agentlab.db", "checkpoints.db"], "没留下 -journal 之类的"
|
||||
# 只留最近 keep 份
|
||||
for name in ("20200101T000000Z", "20200102T000000Z"):
|
||||
(target / name).mkdir()
|
||||
@@ -102,6 +107,15 @@ def test_backup_sqlite_copies_a_consistent_snapshot_including_the_wal(tmp_path,
|
||||
assert len(list(target.iterdir())) == 2 and not (target / "20200101T000000Z").exists()
|
||||
|
||||
|
||||
def test_backup_dir_creates_and_tightens_every_level(tmp_path, capsys):
|
||||
(tmp_path / "backups").mkdir(mode=0o755)
|
||||
(tmp_path / "backups").chmod(0o755)
|
||||
assert ops.main(["backup-dir", "--data", str(tmp_path), "postgres"]) == 0
|
||||
assert capsys.readouterr().out.strip() == str(tmp_path / "backups" / "postgres")
|
||||
assert _mode(tmp_path / "backups") == 0o700, "已有的收紧"
|
||||
assert _mode(tmp_path / "backups" / "postgres") == 0o700
|
||||
|
||||
|
||||
def test_backup_sqlite_without_databases_does_nothing(tmp_path, capsys):
|
||||
assert ops.main(["backup-sqlite", "--data", str(tmp_path)]) == 0
|
||||
assert "没有 SQLite 库" in capsys.readouterr().out
|
||||
|
||||
Reference in New Issue
Block a user