secondkey 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- secondkey/__init__.py +3 -0
- secondkey/__main__.py +3 -0
- secondkey/audit.py +98 -0
- secondkey/classify.py +616 -0
- secondkey/cli.py +651 -0
- secondkey/default_policy.yaml +85 -0
- secondkey/gate.py +192 -0
- secondkey/hooks/__init__.py +0 -0
- secondkey/hooks/claude_code.py +67 -0
- secondkey/hooks/cursor.py +77 -0
- secondkey/notify.py +36 -0
- secondkey/policy.py +165 -0
- secondkey/proxy.py +244 -0
- secondkey/snapshots/__init__.py +155 -0
- secondkey/snapshots/aws.py +109 -0
- secondkey/snapshots/base.py +48 -0
- secondkey/snapshots/docker.py +70 -0
- secondkey/snapshots/files.py +108 -0
- secondkey/snapshots/git.py +216 -0
- secondkey/snapshots/k8s.py +97 -0
- secondkey/snapshots/mysql.py +104 -0
- secondkey/snapshots/postgres.py +388 -0
- secondkey/snapshots/terraform.py +74 -0
- secondkey/sql.py +142 -0
- secondkey/store.py +211 -0
- secondkey/util.py +108 -0
- secondkey-0.2.0.dist-info/METADATA +208 -0
- secondkey-0.2.0.dist-info/RECORD +32 -0
- secondkey-0.2.0.dist-info/WHEEL +5 -0
- secondkey-0.2.0.dist-info/entry_points.txt +2 -0
- secondkey-0.2.0.dist-info/licenses/LICENSE +202 -0
- secondkey-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Postgres snapshots with pg_dump / pg_restore.
|
|
2
|
+
|
|
3
|
+
Before a DROP, TRUNCATE, DELETE, UPDATE or ALTER runs, the affected tables
|
|
4
|
+
are dumped (schema + data), their row counts recorded, and any foreign keys
|
|
5
|
+
from *other* tables that point at them saved, since a CASCADE drop removes
|
|
6
|
+
those. `undo` restores the tables, re-adds those foreign keys and checks the
|
|
7
|
+
row counts match.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from ..classify import Action
|
|
19
|
+
from ..policy import Policy
|
|
20
|
+
from ..store import Snapshot
|
|
21
|
+
from ..util import CommandError, run
|
|
22
|
+
from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def conn_args(conn: dict[str, str]) -> list[str]:
|
|
26
|
+
args = []
|
|
27
|
+
if conn.get("dbname"):
|
|
28
|
+
args += ["--dbname", conn["dbname"]]
|
|
29
|
+
if conn.get("host"):
|
|
30
|
+
args += ["--host", conn["host"]]
|
|
31
|
+
if conn.get("port"):
|
|
32
|
+
args += ["--port", str(conn["port"])]
|
|
33
|
+
if conn.get("user"):
|
|
34
|
+
args += ["--username", conn["user"]]
|
|
35
|
+
return args
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _quote_literal(s: str) -> str:
|
|
39
|
+
return "'" + s.replace("'", "''") + "'"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def psql(conn: dict[str, str], *statements: str, read_only: bool = False, timeout_ms: int = 10000) -> list[list[str]]:
|
|
43
|
+
"""Run statements in one psql session; return rows of the last one (tab-separated)."""
|
|
44
|
+
cmds = ["SET statement_timeout = %d" % timeout_ms]
|
|
45
|
+
if read_only:
|
|
46
|
+
cmds.append("BEGIN READ ONLY")
|
|
47
|
+
cmds.extend(statements)
|
|
48
|
+
if read_only:
|
|
49
|
+
cmds.append("ROLLBACK")
|
|
50
|
+
argv = ["psql", "-X", "-q", "-A", "-t", "-F", "\t", "-v", "ON_ERROR_STOP=1", "-w", *conn_args(conn)]
|
|
51
|
+
for c in cmds:
|
|
52
|
+
argv += ["-c", c]
|
|
53
|
+
try:
|
|
54
|
+
out = run(argv, timeout=timeout_ms / 1000 + 20).stdout
|
|
55
|
+
except CommandError as e:
|
|
56
|
+
raise SnapshotUnavailable(f"can't query Postgres: {e.stderr.strip()[:300]}") from e
|
|
57
|
+
return [line.split("\t") for line in out.splitlines() if line != ""]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _exists(conn: dict[str, str], table: str) -> bool:
|
|
61
|
+
rows = psql(conn, f"SELECT to_regclass({_quote_literal(table)}) IS NOT NULL", read_only=True)
|
|
62
|
+
return bool(rows) and rows[-1][0] == "t"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _count(conn: dict[str, str], table: str, where: str | None = None) -> int:
|
|
66
|
+
if where and ";" in where:
|
|
67
|
+
raise SnapshotUnavailable("WHERE clause too complex to estimate safely")
|
|
68
|
+
q = f"SELECT count(*) FROM {table}" + (f" WHERE {where}" if where else "")
|
|
69
|
+
rows = psql(conn, q, read_only=True)
|
|
70
|
+
return int(rows[-1][0])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _referencing_fks(conn: dict[str, str], table: str) -> list[dict[str, str]]:
|
|
74
|
+
rows = psql(conn, "SELECT conrelid::regclass::text, conname, pg_get_constraintdef(oid) FROM pg_constraint "
|
|
75
|
+
f"WHERE contype = 'f' AND confrelid = to_regclass({_quote_literal(table)}) "
|
|
76
|
+
f"AND conrelid <> to_regclass({_quote_literal(table)})", read_only=True)
|
|
77
|
+
return [{"table": r[0], "name": r[1], "def": r[2]} for r in rows if len(r) == 3]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _size_bytes(conn: dict[str, str], tables: list[str]) -> int:
|
|
81
|
+
if tables == ["*"]:
|
|
82
|
+
rows = psql(conn, "SELECT pg_database_size(current_database())", read_only=True)
|
|
83
|
+
else:
|
|
84
|
+
parts = " + ".join(f"COALESCE(pg_total_relation_size(to_regclass({_quote_literal(t)})), 0)" for t in tables)
|
|
85
|
+
rows = psql(conn, f"SELECT {parts}", read_only=True)
|
|
86
|
+
return int(rows[-1][0]) if rows else 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _neon_bin() -> str:
|
|
90
|
+
import shutil
|
|
91
|
+
for b in ("neonctl", "neon"):
|
|
92
|
+
if shutil.which(b):
|
|
93
|
+
return b
|
|
94
|
+
raise SnapshotUnavailable("postgres_strategy is neon but neonctl isn't installed (npm i -g neonctl)")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _neon_settings(policy: Policy) -> dict[str, str]:
|
|
98
|
+
project = str(policy.snapshots.get("neon_project_id") or os.environ.get("NEON_PROJECT_ID") or "")
|
|
99
|
+
branch = str(policy.snapshots.get("neon_branch") or os.environ.get("NEON_BRANCH") or "")
|
|
100
|
+
if not project or not branch:
|
|
101
|
+
raise SnapshotUnavailable("set snapshots.neon_project_id and snapshots.neon_branch (or NEON_PROJECT_ID / NEON_BRANCH)")
|
|
102
|
+
return {"project": project, "branch": branch}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class PostgresProvider(Provider):
|
|
106
|
+
name = "postgres"
|
|
107
|
+
|
|
108
|
+
def _strategy(self, policy: Policy) -> str:
|
|
109
|
+
return str(policy.snapshots.get("postgres_strategy", "dump"))
|
|
110
|
+
|
|
111
|
+
def _check_size(self, conn: dict[str, str], tables: list[str], policy: Policy) -> int:
|
|
112
|
+
size = _size_bytes(conn, tables)
|
|
113
|
+
limit = int(float(policy.snapshots.get("postgres_max_dump_mb", 2048)) * 1024 * 1024)
|
|
114
|
+
if limit and size > limit:
|
|
115
|
+
from ..util import human_size
|
|
116
|
+
raise SnapshotUnavailable(f"{'database' if tables == ['*'] else 'tables'} are {human_size(size)}, over the "
|
|
117
|
+
f"{human_size(limit)} dump limit. Use postgres_strategy: neon, or raise postgres_max_dump_mb")
|
|
118
|
+
return size
|
|
119
|
+
|
|
120
|
+
def plan(self, action: Action, policy: Policy) -> list[str]:
|
|
121
|
+
t = action.target
|
|
122
|
+
conn, tables, kind = t.get("conn") or {}, t.get("tables") or [], t.get("kind")
|
|
123
|
+
if not tables:
|
|
124
|
+
raise SnapshotUnavailable("no table names found in the statement")
|
|
125
|
+
strategy = self._strategy(policy)
|
|
126
|
+
if strategy == "neon":
|
|
127
|
+
ns = _neon_settings(policy)
|
|
128
|
+
_neon_bin()
|
|
129
|
+
if tables == ["*"]:
|
|
130
|
+
from ..util import human_size
|
|
131
|
+
size = _size_bytes(conn, tables)
|
|
132
|
+
n = psql(conn, "SELECT count(*) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')", read_only=True)
|
|
133
|
+
lines = [f"whole database: {int(n[-1][0])} tables, {human_size(size)}"]
|
|
134
|
+
if strategy == "neon":
|
|
135
|
+
lines.append(f"restore point: Neon branch {ns['branch']} point-in-time")
|
|
136
|
+
else:
|
|
137
|
+
self._check_size(conn, tables, policy)
|
|
138
|
+
return lines
|
|
139
|
+
if strategy != "neon":
|
|
140
|
+
self._check_size(conn, [tb for tb in tables if _exists(conn, tb)] or tables, policy)
|
|
141
|
+
lines = []
|
|
142
|
+
for table in tables:
|
|
143
|
+
if not _exists(conn, table):
|
|
144
|
+
lines.append(f"{table}: does not exist (nothing to lose)")
|
|
145
|
+
continue
|
|
146
|
+
total = _count(conn, table)
|
|
147
|
+
if kind in ("sql.delete", "sql.update") and t.get("where"):
|
|
148
|
+
try:
|
|
149
|
+
hit = _count(conn, table, t["where"])
|
|
150
|
+
lines.append(f"{table}: {hit:,} of {total:,} rows match")
|
|
151
|
+
except SnapshotUnavailable:
|
|
152
|
+
lines.append(f"{table}: {total:,} rows (couldn't evaluate the WHERE clause)")
|
|
153
|
+
elif kind in ("sql.delete", "sql.update"):
|
|
154
|
+
lines.append(f"{table}: all {total:,} rows (no WHERE clause)")
|
|
155
|
+
elif kind == "sql.alter":
|
|
156
|
+
lines.append(f"{table}: {total:,} rows, schema change")
|
|
157
|
+
else:
|
|
158
|
+
lines.append(f"{table}: {total:,} rows")
|
|
159
|
+
return lines
|
|
160
|
+
|
|
161
|
+
def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
|
|
162
|
+
t = action.target
|
|
163
|
+
conn, tables = t.get("conn") or {}, t.get("tables") or []
|
|
164
|
+
if self._strategy(policy) == "neon":
|
|
165
|
+
import datetime as _dt
|
|
166
|
+
ns = _neon_settings(policy)
|
|
167
|
+
_neon_bin()
|
|
168
|
+
ts = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
169
|
+
counts = {tb: _count(conn, tb) for tb in tables if tb != "*" and _exists(conn, tb)}
|
|
170
|
+
return (f"Neon {ns['branch']} @ {ts[:19]}Z", {"strategy": "neon", **ns, "timestamp": ts, "conn": conn,
|
|
171
|
+
"tables": tables, "counts": counts, "statement": t.get("sql")})
|
|
172
|
+
if tables == ["*"]:
|
|
173
|
+
size = self._check_size(conn, tables, policy)
|
|
174
|
+
dump = dest / "dump.pgc"
|
|
175
|
+
try:
|
|
176
|
+
run(["pg_dump", "-Fc", "-w", "-f", str(dump), *conn_args(conn)], timeout=3600)
|
|
177
|
+
except CommandError as e:
|
|
178
|
+
raise SnapshotUnavailable(f"pg_dump failed: {e.stderr.strip()[:300]}") from e
|
|
179
|
+
from ..util import human_size
|
|
180
|
+
return f"whole database ({human_size(size)})", {"conn": conn, "tables": ["*"], "counts": {}, "fks": [],
|
|
181
|
+
"kind": t.get("kind"), "bytes": dump.stat().st_size}
|
|
182
|
+
self._check_size(conn, [tb for tb in tables if _exists(conn, tb)] or tables, policy)
|
|
183
|
+
present = [tb for tb in tables if _exists(conn, tb)]
|
|
184
|
+
if not present:
|
|
185
|
+
raise NothingToProtect("none of the tables exist, so there is nothing to protect")
|
|
186
|
+
counts = {tb: _count(conn, tb) for tb in present}
|
|
187
|
+
fks = [fk for tb in present for fk in _referencing_fks(conn, tb)]
|
|
188
|
+
dump = dest / "dump.pgc"
|
|
189
|
+
argv = ["pg_dump", "-Fc", "-w", "-f", str(dump), *conn_args(conn)]
|
|
190
|
+
for tb in present:
|
|
191
|
+
argv += ["-t", tb]
|
|
192
|
+
try:
|
|
193
|
+
run(argv, timeout=3600)
|
|
194
|
+
except CommandError as e:
|
|
195
|
+
raise SnapshotUnavailable(f"pg_dump failed: {e.stderr.strip()[:300]}") from e
|
|
196
|
+
size = dump.stat().st_size
|
|
197
|
+
label = ", ".join(f"{tb} ({n:,} rows)" for tb, n in counts.items())
|
|
198
|
+
return label, {"conn": conn, "tables": present, "counts": counts, "fks": fks,
|
|
199
|
+
"statement": t.get("sql"), "kind": t.get("kind"), "bytes": size}
|
|
200
|
+
|
|
201
|
+
# ------------------------------------------------------------ restore
|
|
202
|
+
def _mode(self, snap: Snapshot, mode: str | None) -> tuple[str, dict[str, bool]]:
|
|
203
|
+
conn = snap.meta["conn"]
|
|
204
|
+
present = {tb: _exists(conn, tb) for tb in snap.meta["tables"]}
|
|
205
|
+
if mode == "full":
|
|
206
|
+
return "full", present
|
|
207
|
+
if mode in ("data", "exact"):
|
|
208
|
+
return "data", present
|
|
209
|
+
return ("data" if all(present.values()) else "full"), present
|
|
210
|
+
|
|
211
|
+
def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
|
|
212
|
+
m = snap.meta
|
|
213
|
+
if m.get("strategy") == "neon":
|
|
214
|
+
return [f"rewind Neon branch {m['branch']} to {m['timestamp']} (every database on that branch)",
|
|
215
|
+
f"the current state is kept as branch {m['branch']}_before_{snap.id}",
|
|
216
|
+
"everything written to the branch after that moment is rolled back"]
|
|
217
|
+
if m.get("tables") == ["*"]:
|
|
218
|
+
return ["restore the whole database from the snapshot (drop and recreate every object in the dump)",
|
|
219
|
+
"everything written to the database after the snapshot will be lost"]
|
|
220
|
+
try:
|
|
221
|
+
chosen, present = self._mode(snap, mode)
|
|
222
|
+
except SnapshotUnavailable as e:
|
|
223
|
+
return [f"can't reach the database right now: {e}"]
|
|
224
|
+
lines = []
|
|
225
|
+
for tb in m["tables"]:
|
|
226
|
+
n = m["counts"][tb]
|
|
227
|
+
if chosen == "data":
|
|
228
|
+
lines.append(f"{tb}: put back the {n:,} saved rows by primary key (changed rows reverted, deleted rows re-inserted)")
|
|
229
|
+
elif present[tb]:
|
|
230
|
+
lines.append(f"{tb}: drop the current table and recreate it with {n:,} rows")
|
|
231
|
+
else:
|
|
232
|
+
lines.append(f"{tb}: recreate the table with {n:,} rows, indexes and constraints")
|
|
233
|
+
for fk in m.get("fks") or []:
|
|
234
|
+
lines.append(f"re-add foreign key {fk['name']} on {fk['table']} if it's missing")
|
|
235
|
+
if chosen == "data":
|
|
236
|
+
lines.append("rows written after the snapshot are " + ("REMOVED (--mode exact)" if mode == "exact"
|
|
237
|
+
else "kept (use --mode exact to remove them)"))
|
|
238
|
+
elif any(present.values()):
|
|
239
|
+
lines.append("rows written to these tables after the snapshot will be lost")
|
|
240
|
+
return lines
|
|
241
|
+
|
|
242
|
+
def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
|
|
243
|
+
m = snap.meta
|
|
244
|
+
if m.get("strategy") == "neon":
|
|
245
|
+
keep = f"{m['branch']}_before_{snap.id}"
|
|
246
|
+
try:
|
|
247
|
+
run([_neon_bin(), "branches", "restore", m["branch"], f"^self@{m['timestamp']}",
|
|
248
|
+
"--preserve-under-name", keep, "--project-id", m["project"]], timeout=600)
|
|
249
|
+
except CommandError as e:
|
|
250
|
+
raise RestoreError(f"neon restore failed: {e.stderr.strip()[:400]}") from e
|
|
251
|
+
out = [f"Neon branch {m['branch']} rewound to {m['timestamp']}", f"previous state kept as branch {keep}"]
|
|
252
|
+
for tb, n in (m.get("counts") or {}).items():
|
|
253
|
+
got = _count(m["conn"], tb)
|
|
254
|
+
out.append(f"{'verified' if got == n else 'WARNING'} {tb}: {got:,} rows (snapshot had {n:,})")
|
|
255
|
+
return out
|
|
256
|
+
conn, dump = m["conn"], str(Path(snap.path) / "dump.pgc")
|
|
257
|
+
if m.get("tables") == ["*"]:
|
|
258
|
+
try:
|
|
259
|
+
run(["pg_restore", "--single-transaction", "--exit-on-error", "--clean", "--if-exists", "-w",
|
|
260
|
+
*conn_args(conn), dump], timeout=7200)
|
|
261
|
+
except CommandError as e:
|
|
262
|
+
raise RestoreError(f"pg_restore failed, nothing was changed: {e.stderr.strip()[:400]}") from e
|
|
263
|
+
return ["whole database restored from the snapshot"]
|
|
264
|
+
chosen, present = self._mode(snap, mode)
|
|
265
|
+
out = []
|
|
266
|
+
env = dict(os.environ)
|
|
267
|
+
if chosen == "full":
|
|
268
|
+
argv = ["pg_restore", "--single-transaction", "--exit-on-error", "-w", *conn_args(conn)]
|
|
269
|
+
if any(present.values()):
|
|
270
|
+
argv += ["--clean", "--if-exists"]
|
|
271
|
+
argv.append(dump)
|
|
272
|
+
try:
|
|
273
|
+
run(argv, env=env, timeout=3600)
|
|
274
|
+
except CommandError as e:
|
|
275
|
+
raise RestoreError(f"pg_restore failed, nothing was changed: {e.stderr.strip()[:400]}") from e
|
|
276
|
+
out.append("tables recreated from the snapshot: " + ", ".join(m["tables"]))
|
|
277
|
+
else:
|
|
278
|
+
out.extend(self._merge_restore(conn, dump, m["tables"], exact=(mode == "exact")))
|
|
279
|
+
for fk in m.get("fks") or []:
|
|
280
|
+
exists = psql(conn, "SELECT 1 FROM pg_constraint WHERE conname = %s AND conrelid = to_regclass(%s)"
|
|
281
|
+
% (_quote_literal(fk["name"]), _quote_literal(fk["table"])), read_only=True)
|
|
282
|
+
if exists:
|
|
283
|
+
continue
|
|
284
|
+
try:
|
|
285
|
+
psql(conn, f'ALTER TABLE {fk["table"]} ADD CONSTRAINT "{fk["name"]}" {fk["def"]}')
|
|
286
|
+
out.append(f"foreign key {fk['name']} on {fk['table']} re-added")
|
|
287
|
+
except SnapshotUnavailable as e:
|
|
288
|
+
out.append(f"WARNING: couldn't re-add foreign key {fk['name']} on {fk['table']}: {e}")
|
|
289
|
+
|
|
290
|
+
if chosen == "full":
|
|
291
|
+
bad = []
|
|
292
|
+
for tb, expected in m["counts"].items():
|
|
293
|
+
got = _count(conn, tb)
|
|
294
|
+
if got != expected:
|
|
295
|
+
bad.append(f"{tb}: expected {expected:,} rows, found {got:,}")
|
|
296
|
+
else:
|
|
297
|
+
out.append(f"verified {tb}: {got:,} rows")
|
|
298
|
+
if bad:
|
|
299
|
+
raise RestoreError("restore finished but row counts don't match: " + "; ".join(bad))
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
# Merge restore: put back saved rows by primary key, keep rows written since.
|
|
303
|
+
def _merge_restore(self, conn: dict[str, str], dump: str, tables: list[str], exact: bool) -> list[str]:
|
|
304
|
+
try:
|
|
305
|
+
data_sql = run(["pg_restore", "--data-only", "-f", "-", dump], timeout=3600).stdout
|
|
306
|
+
except CommandError as e:
|
|
307
|
+
raise RestoreError(f"couldn't read the snapshot: {e.stderr.strip()[:300]}") from e
|
|
308
|
+
info = {}
|
|
309
|
+
for i, tb in enumerate(tables):
|
|
310
|
+
rows = psql(conn, "SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) FROM pg_class c "
|
|
311
|
+
f"JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = to_regclass({_quote_literal(tb)})",
|
|
312
|
+
read_only=True)
|
|
313
|
+
qual = rows[0][0]
|
|
314
|
+
pk = [r[0] for r in psql(conn, "SELECT quote_ident(a.attname) FROM pg_index i JOIN pg_attribute a "
|
|
315
|
+
"ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) "
|
|
316
|
+
f"WHERE i.indrelid = to_regclass({_quote_literal(tb)}) AND i.indisprimary "
|
|
317
|
+
"ORDER BY array_position(i.indkey, a.attnum)", read_only=True)]
|
|
318
|
+
info[qual] = {"name": tb, "tmp": f"secondkey_restore_{i}", "pk": pk, "cols": None}
|
|
319
|
+
|
|
320
|
+
lines, script = data_sql.splitlines(keepends=True), []
|
|
321
|
+
for ln in lines:
|
|
322
|
+
m = re.match(r"^COPY (\S+) \((.*)\) FROM stdin;", ln)
|
|
323
|
+
if m and m.group(1) in info:
|
|
324
|
+
t = info[m.group(1)]
|
|
325
|
+
t["cols"] = [c.strip() for c in m.group(2).split(",")]
|
|
326
|
+
script.append(f"COPY {t['tmp']} ({m.group(2)}) FROM stdin;\n")
|
|
327
|
+
continue
|
|
328
|
+
sv = re.match(r"^SELECT pg_catalog\.setval\('([^']+)', (\d+), (true|false)\);", ln)
|
|
329
|
+
if sv:
|
|
330
|
+
seq = sv.group(1).replace("'", "''")
|
|
331
|
+
script.append(f"SELECT pg_catalog.setval('{seq}', GREATEST({sv.group(2)}, (SELECT last_value FROM {sv.group(1)})), true);\n")
|
|
332
|
+
continue
|
|
333
|
+
script.append(ln)
|
|
334
|
+
|
|
335
|
+
pre = ["SET statement_timeout = 0;\n"]
|
|
336
|
+
post = []
|
|
337
|
+
for qual, t in info.items():
|
|
338
|
+
pre.append(f"CREATE TEMP TABLE {t['tmp']} (LIKE {qual} INCLUDING DEFAULTS) ON COMMIT DROP;\n")
|
|
339
|
+
cols = t["cols"] or []
|
|
340
|
+
if not cols:
|
|
341
|
+
continue
|
|
342
|
+
col_list = ", ".join(cols)
|
|
343
|
+
s_cols = ", ".join(f"s.{c}" for c in cols)
|
|
344
|
+
d_cols = ", ".join(f"d.{c}" for c in cols)
|
|
345
|
+
if t["pk"]:
|
|
346
|
+
join = " AND ".join(f"d.{k} = s.{k}" for k in t["pk"])
|
|
347
|
+
upd = [c for c in cols if c not in t["pk"]]
|
|
348
|
+
if upd:
|
|
349
|
+
post.append(f"UPDATE {qual} AS d SET ({', '.join(upd)}) = ROW({', '.join('s.' + c for c in upd)}) "
|
|
350
|
+
f"FROM {t['tmp']} s WHERE {join} AND ROW({', '.join('d.' + c for c in upd)}) "
|
|
351
|
+
f"IS DISTINCT FROM ROW({', '.join('s.' + c for c in upd)});\n")
|
|
352
|
+
post.append(f"INSERT INTO {qual} ({col_list}) OVERRIDING SYSTEM VALUE SELECT {s_cols} FROM {t['tmp']} s "
|
|
353
|
+
f"WHERE NOT EXISTS (SELECT 1 FROM {qual} d WHERE {join});\n")
|
|
354
|
+
newer = f"FROM {qual} d WHERE NOT EXISTS (SELECT 1 FROM {t['tmp']} s WHERE {join})"
|
|
355
|
+
if exact:
|
|
356
|
+
post.append(f"DELETE {newer.replace('FROM ' + qual + ' d', 'FROM ' + qual + ' AS d', 1)};\n")
|
|
357
|
+
post.append(f"SELECT 'newer:{t['name']}:' || count(*) {newer};\n")
|
|
358
|
+
else:
|
|
359
|
+
post.append(f"DELETE FROM {qual};\n")
|
|
360
|
+
post.append(f"INSERT INTO {qual} ({col_list}) OVERRIDING SYSTEM VALUE SELECT {col_list} FROM {t['tmp']};\n")
|
|
361
|
+
post.append(
|
|
362
|
+
"DO $sk$ BEGIN IF EXISTS (SELECT 1 FROM " + t["tmp"] + " s WHERE NOT EXISTS (SELECT 1 FROM " + qual
|
|
363
|
+
+ f" d WHERE ROW({d_cols}) IS NOT DISTINCT FROM ROW({s_cols}))) THEN "
|
|
364
|
+
+ f"RAISE EXCEPTION 'secondkey: verification failed for {t['name']}'; END IF; END $sk$;\n")
|
|
365
|
+
post.append(f"SELECT 'saved:{t['name']}:' || count(*) FROM {t['tmp']};\n")
|
|
366
|
+
|
|
367
|
+
full = "".join(pre) + "".join(script) + "".join(post)
|
|
368
|
+
proc = subprocess.run(["psql", "-X", "-q", "-A", "-t", "-w", "-v", "ON_ERROR_STOP=1", "--single-transaction",
|
|
369
|
+
*conn_args(conn), "-f", "-"], input=full, capture_output=True, text=True)
|
|
370
|
+
if proc.returncode != 0:
|
|
371
|
+
raise RestoreError("restore failed and was rolled back, nothing was changed: "
|
|
372
|
+
+ (proc.stderr.strip()[:500] or "unknown error")
|
|
373
|
+
+ ". If the table's columns changed, try `--mode full`.")
|
|
374
|
+
result, saved, newer = [], {}, {}
|
|
375
|
+
for ln in proc.stdout.splitlines():
|
|
376
|
+
parts = ln.strip().split(":")
|
|
377
|
+
if len(parts) == 3 and parts[0] in ("saved", "newer"):
|
|
378
|
+
(saved if parts[0] == "saved" else newer)[parts[1]] = int(parts[2])
|
|
379
|
+
for qual, t in info.items():
|
|
380
|
+
n = t["name"]
|
|
381
|
+
line = f"verified {n}: all {saved.get(n, 0):,} saved rows are back"
|
|
382
|
+
if t["pk"] and newer.get(n):
|
|
383
|
+
line += (f", {newer[n]:,} rows written after the snapshot were removed" if exact
|
|
384
|
+
else f", {newer[n]:,} rows written after the snapshot were kept")
|
|
385
|
+
if not t["pk"]:
|
|
386
|
+
line += " (no primary key: table contents replaced)"
|
|
387
|
+
result.append(line)
|
|
388
|
+
return result
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Terraform / OpenTofu: back up the state file and the config commit.
|
|
2
|
+
|
|
3
|
+
Honest limits: after `terraform destroy` the real resources are gone. Pushing
|
|
4
|
+
the old state back would make Terraform believe they still exist, which is
|
|
5
|
+
worse. So for destroy/apply, undo explains how to recreate the resources from
|
|
6
|
+
the saved config instead of touching state. For state surgery
|
|
7
|
+
(`state rm/mv/push`, import, taint) undo pushes the saved state back.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ..classify import Action
|
|
17
|
+
from ..policy import Policy
|
|
18
|
+
from ..store import Snapshot
|
|
19
|
+
from ..util import CommandError, run
|
|
20
|
+
from .base import Provider, RestoreError, SnapshotUnavailable
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TerraformProvider(Provider):
|
|
24
|
+
name = "terraform"
|
|
25
|
+
|
|
26
|
+
def _pull(self, action: Action) -> str:
|
|
27
|
+
t = action.target
|
|
28
|
+
try:
|
|
29
|
+
return run([t.get("binary", "terraform"), "state", "pull"], cwd=t.get("cwd"), timeout=300).stdout
|
|
30
|
+
except CommandError as e:
|
|
31
|
+
raise SnapshotUnavailable(f"state pull failed: {e.stderr.strip()[:300]}") from e
|
|
32
|
+
|
|
33
|
+
def plan(self, action: Action, policy: Policy) -> list[str]:
|
|
34
|
+
state = self._pull(action)
|
|
35
|
+
try:
|
|
36
|
+
n = len(json.loads(state).get("resources") or []) if state.strip() else 0
|
|
37
|
+
except json.JSONDecodeError:
|
|
38
|
+
n = 0
|
|
39
|
+
note = "" if action.category == "tf.state_write" else " (state backup only; destroyed cloud resources can't be un-destroyed)"
|
|
40
|
+
return [f"state with {n} resource{'s' if n != 1 else ''} will be backed up{note}"]
|
|
41
|
+
|
|
42
|
+
def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
|
|
43
|
+
state = self._pull(action)
|
|
44
|
+
(dest / "terraform.tfstate").write_text(state)
|
|
45
|
+
cwd = action.target.get("cwd")
|
|
46
|
+
commit = run(["git", "-C", cwd or ".", "rev-parse", "--verify", "-q", "HEAD"], check=False).stdout.strip() if cwd else ""
|
|
47
|
+
try:
|
|
48
|
+
n = len(json.loads(state).get("resources") or []) if state.strip() else 0
|
|
49
|
+
except json.JSONDecodeError:
|
|
50
|
+
n = 0
|
|
51
|
+
return f"terraform state ({n} resources)" + (f", config @ {commit[:8]}" if commit else ""), {
|
|
52
|
+
"cwd": cwd, "binary": action.target.get("binary", "terraform"), "category": action.category,
|
|
53
|
+
"commit": commit or None, "resources": n}
|
|
54
|
+
|
|
55
|
+
def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
|
|
56
|
+
m = snap.meta
|
|
57
|
+
if m["category"] == "tf.state_write":
|
|
58
|
+
return [f"push the saved state ({m['resources']} resources) back with `{m['binary']} state push -force`"]
|
|
59
|
+
steps = ["Terraform can't un-destroy cloud resources. To recreate them:"]
|
|
60
|
+
if m.get("commit"):
|
|
61
|
+
steps.append(f" git checkout {m['commit'][:8]} -- . (the config as it was)")
|
|
62
|
+
steps.append(f" {m['binary']} apply")
|
|
63
|
+
steps.append(f"saved state for reference (resource IDs, attributes): {Path(snap.path) / 'terraform.tfstate'}")
|
|
64
|
+
return steps
|
|
65
|
+
|
|
66
|
+
def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
|
|
67
|
+
m = snap.meta
|
|
68
|
+
if m["category"] != "tf.state_write":
|
|
69
|
+
raise RestoreError("\n".join(self.describe_restore(snap)))
|
|
70
|
+
try:
|
|
71
|
+
run([m["binary"], "state", "push", "-force", str(Path(snap.path) / "terraform.tfstate")], cwd=m["cwd"], timeout=300)
|
|
72
|
+
except CommandError as e:
|
|
73
|
+
raise RestoreError(f"state push failed: {e.stderr.strip()[:400]}") from e
|
|
74
|
+
return [f"terraform state restored ({m['resources']} resources)"]
|
secondkey/sql.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Lightweight SQL statement classification.
|
|
2
|
+
|
|
3
|
+
This is deliberately conservative: it only needs to tell reads from writes and
|
|
4
|
+
find which tables a destructive statement touches. Anything it can't
|
|
5
|
+
understand is reported as ``sql.other`` so the policy can still ask.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
_IDENT = r'(?:"[^"]+"|[A-Za-z_][\w$]*)(?:\s*\.\s*(?:"[^"]+"|[A-Za-z_][\w$]*))?'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Statement:
|
|
18
|
+
category: str # sql.read, sql.drop, sql.delete, ...
|
|
19
|
+
text: str
|
|
20
|
+
tables: list[str] = field(default_factory=list)
|
|
21
|
+
where: str | None = None # WHERE clause for DELETE/UPDATE, used to estimate impact
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def split_statements(sql: str) -> list[str]:
|
|
25
|
+
"""Split on semicolons outside quotes, comments and dollar-quoted bodies."""
|
|
26
|
+
out, buf, i, n = [], [], 0, len(sql)
|
|
27
|
+
quote: str | None = None
|
|
28
|
+
while i < n:
|
|
29
|
+
ch = sql[i]
|
|
30
|
+
if quote:
|
|
31
|
+
if quote.startswith("$"):
|
|
32
|
+
if sql.startswith(quote, i):
|
|
33
|
+
buf.append(quote)
|
|
34
|
+
i += len(quote)
|
|
35
|
+
quote = None
|
|
36
|
+
continue
|
|
37
|
+
elif ch == quote:
|
|
38
|
+
if i + 1 < n and sql[i + 1] == quote: # escaped '' or ""
|
|
39
|
+
buf.append(ch * 2)
|
|
40
|
+
i += 2
|
|
41
|
+
continue
|
|
42
|
+
quote = None
|
|
43
|
+
buf.append(ch)
|
|
44
|
+
i += 1
|
|
45
|
+
continue
|
|
46
|
+
if ch in ("'", '"'):
|
|
47
|
+
quote = ch
|
|
48
|
+
elif ch == "$":
|
|
49
|
+
m = re.match(r"\$[A-Za-z_]*\$", sql[i:])
|
|
50
|
+
if m:
|
|
51
|
+
quote = m.group(0)
|
|
52
|
+
buf.append(quote)
|
|
53
|
+
i += len(quote)
|
|
54
|
+
continue
|
|
55
|
+
elif sql.startswith("--", i):
|
|
56
|
+
j = sql.find("\n", i)
|
|
57
|
+
i = n if j < 0 else j
|
|
58
|
+
continue
|
|
59
|
+
elif sql.startswith("/*", i):
|
|
60
|
+
j = sql.find("*/", i + 2)
|
|
61
|
+
i = n if j < 0 else j + 2
|
|
62
|
+
continue
|
|
63
|
+
elif ch == ";":
|
|
64
|
+
stmt = "".join(buf).strip()
|
|
65
|
+
if stmt:
|
|
66
|
+
out.append(stmt)
|
|
67
|
+
buf = []
|
|
68
|
+
i += 1
|
|
69
|
+
continue
|
|
70
|
+
buf.append(ch)
|
|
71
|
+
i += 1
|
|
72
|
+
stmt = "".join(buf).strip()
|
|
73
|
+
if stmt:
|
|
74
|
+
out.append(stmt)
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _clean(name: str) -> str:
|
|
79
|
+
return re.sub(r"\s+", "", name)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _table_list(s: str) -> list[str]:
|
|
83
|
+
return [_clean(m.group(0)) for m in re.finditer(_IDENT, s)]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def classify_statement(stmt: str) -> Statement:
|
|
87
|
+
s = stmt.strip()
|
|
88
|
+
u = s.upper()
|
|
89
|
+
first = u.split(None, 1)[0] if u else ""
|
|
90
|
+
|
|
91
|
+
if first in ("SELECT", "SHOW", "EXPLAIN", "VALUES", "TABLE", "DESCRIBE", "DESC") or s.startswith("\\"):
|
|
92
|
+
if first == "EXPLAIN" and re.search(r"\bANALYZE\b", u) and re.search(r"\b(DELETE|UPDATE|INSERT|DROP)\b", u):
|
|
93
|
+
return Statement("sql.other", s)
|
|
94
|
+
return Statement("sql.read", s)
|
|
95
|
+
if first == "WITH":
|
|
96
|
+
if re.search(r"\b(DELETE|UPDATE|INSERT|MERGE)\b", u):
|
|
97
|
+
return Statement("sql.other", s)
|
|
98
|
+
return Statement("sql.read", s)
|
|
99
|
+
|
|
100
|
+
m = re.match(r"DROP\s+(DATABASE|SCHEMA)\b", u)
|
|
101
|
+
if m:
|
|
102
|
+
return Statement("sql.drop_database", s)
|
|
103
|
+
m = re.match(r"DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(.+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$", s, re.I | re.S)
|
|
104
|
+
if m:
|
|
105
|
+
return Statement("sql.drop", s, _table_list(m.group(1)))
|
|
106
|
+
if first == "DROP":
|
|
107
|
+
return Statement("sql.drop_other", s)
|
|
108
|
+
|
|
109
|
+
m = re.match(r"TRUNCATE\s+(?:TABLE\s+)?(?:ONLY\s+)?(.+?)(?:\s+(?:RESTART|CONTINUE)\s+IDENTITY)?(?:\s+(?:CASCADE|RESTRICT))?\s*$",
|
|
110
|
+
s, re.I | re.S)
|
|
111
|
+
if m:
|
|
112
|
+
return Statement("sql.truncate", s, _table_list(m.group(1)))
|
|
113
|
+
|
|
114
|
+
m = re.match(rf"DELETE\s+FROM\s+(?:ONLY\s+)?({_IDENT})(?:\s+(?:AS\s+)?(?!WHERE\b|USING\b|RETURNING\b)\w+)?(.*)$", s, re.I | re.S)
|
|
115
|
+
if m:
|
|
116
|
+
rest = m.group(2)
|
|
117
|
+
w = re.search(r"\bWHERE\b(.*)$", rest, re.I | re.S)
|
|
118
|
+
simple = not re.search(r"\b(USING|RETURNING)\b", rest, re.I)
|
|
119
|
+
return Statement("sql.delete", s, [_clean(m.group(1))], w.group(1).strip() if (w and simple) else None)
|
|
120
|
+
|
|
121
|
+
m = re.match(rf"UPDATE\s+(?:ONLY\s+)?({_IDENT})(?:\s+(?:AS\s+)?(?!SET\b)\w+)?\s+SET\b(.*)$", s, re.I | re.S)
|
|
122
|
+
if m:
|
|
123
|
+
rest = m.group(2)
|
|
124
|
+
w = re.search(r"\bWHERE\b(.*)$", rest, re.I | re.S)
|
|
125
|
+
simple = not re.search(r"\b(FROM|RETURNING)\b", rest[: w.start()] if w else rest, re.I)
|
|
126
|
+
return Statement("sql.update", s, [_clean(m.group(1))], w.group(1).strip() if (w and simple) else None)
|
|
127
|
+
|
|
128
|
+
m = re.match(rf"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?({_IDENT})", s, re.I)
|
|
129
|
+
if m:
|
|
130
|
+
return Statement("sql.alter", s, [_clean(m.group(1))])
|
|
131
|
+
|
|
132
|
+
if first in ("INSERT", "COPY", "MERGE"):
|
|
133
|
+
return Statement("sql.write", s)
|
|
134
|
+
if first in ("CREATE", "COMMENT", "GRANT", "REVOKE", "REINDEX", "VACUUM", "ANALYZE", "CLUSTER", "REFRESH"):
|
|
135
|
+
return Statement("sql.write", s)
|
|
136
|
+
if first in ("BEGIN", "COMMIT", "ROLLBACK", "SET", "RESET", "START", "END", "SAVEPOINT", "RELEASE"):
|
|
137
|
+
return Statement("sql.read", s)
|
|
138
|
+
return Statement("sql.other", s)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def classify_sql(sql: str) -> list[Statement]:
|
|
142
|
+
return [classify_statement(s) for s in split_statements(sql)]
|