l3io-wordpress-backup 1.0.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.
Files changed (98) hide show
  1. l3io/wp/backup/__init__.py +22 -0
  2. l3io/wp/backup/_version.py +31 -0
  3. l3io/wp/backup/adapters/__init__.py +9 -0
  4. l3io/wp/backup/adapters/clock.py +22 -0
  5. l3io/wp/backup/adapters/config_writer.py +702 -0
  6. l3io/wp/backup/adapters/credential_providers.py +236 -0
  7. l3io/wp/backup/adapters/crypto.py +237 -0
  8. l3io/wp/backup/adapters/database.py +1555 -0
  9. l3io/wp/backup/adapters/database_load.py +1263 -0
  10. l3io/wp/backup/adapters/exclusions.py +83 -0
  11. l3io/wp/backup/adapters/journal.py +507 -0
  12. l3io/wp/backup/adapters/lock.py +372 -0
  13. l3io/wp/backup/adapters/noop.py +666 -0
  14. l3io/wp/backup/adapters/phase.py +218 -0
  15. l3io/wp/backup/adapters/preflight.py +869 -0
  16. l3io/wp/backup/adapters/redaction.py +237 -0
  17. l3io/wp/backup/adapters/restore_extension.py +341 -0
  18. l3io/wp/backup/adapters/restore_runner.py +1030 -0
  19. l3io/wp/backup/adapters/site_files.py +191 -0
  20. l3io/wp/backup/adapters/store.py +227 -0
  21. l3io/wp/backup/adapters/tar.py +1648 -0
  22. l3io/wp/backup/adapters/tracing.py +235 -0
  23. l3io/wp/backup/adapters/workspace.py +299 -0
  24. l3io/wp/backup/adapters/wpcli.py +584 -0
  25. l3io/wp/backup/adapters/wpcli_child.py +135 -0
  26. l3io/wp/backup/api/__init__.py +104 -0
  27. l3io/wp/backup/api/errors.py +344 -0
  28. l3io/wp/backup/api/operations.py +427 -0
  29. l3io/wp/backup/cli/__init__.py +228 -0
  30. l3io/wp/backup/cli/adapter_sets.py +255 -0
  31. l3io/wp/backup/cli/backup.py +1118 -0
  32. l3io/wp/backup/cli/context.py +382 -0
  33. l3io/wp/backup/cli/credentials.py +310 -0
  34. l3io/wp/backup/cli/doctor.py +171 -0
  35. l3io/wp/backup/cli/exit.py +171 -0
  36. l3io/wp/backup/cli/logging.py +147 -0
  37. l3io/wp/backup/cli/output.py +111 -0
  38. l3io/wp/backup/cli/parser.py +853 -0
  39. l3io/wp/backup/cli/passphrase.py +301 -0
  40. l3io/wp/backup/cli/preflight.py +227 -0
  41. l3io/wp/backup/cli/privileges.py +327 -0
  42. l3io/wp/backup/cli/restore.py +1571 -0
  43. l3io/wp/backup/cli/restore_report.py +396 -0
  44. l3io/wp/backup/cli/restore_request.py +560 -0
  45. l3io/wp/backup/cli/scope.py +31 -0
  46. l3io/wp/backup/cli/settings.py +524 -0
  47. l3io/wp/backup/cli/verify.py +286 -0
  48. l3io/wp/backup/core/__init__.py +9 -0
  49. l3io/wp/backup/core/archive_choice.py +156 -0
  50. l3io/wp/backup/core/backup.py +105 -0
  51. l3io/wp/backup/core/config_location.py +257 -0
  52. l3io/wp/backup/core/exclusions.py +189 -0
  53. l3io/wp/backup/core/relocation.py +437 -0
  54. l3io/wp/backup/core/restore.py +1246 -0
  55. l3io/wp/backup/core/restore_journal.py +541 -0
  56. l3io/wp/backup/core/restore_space.py +224 -0
  57. l3io/wp/backup/core/verify.py +198 -0
  58. l3io/wp/backup/domain/__init__.py +9 -0
  59. l3io/wp/backup/domain/archive_format.py +1072 -0
  60. l3io/wp/backup/domain/backup_scope.py +21 -0
  61. l3io/wp/backup/domain/config.py +27 -0
  62. l3io/wp/backup/domain/credentials.py +125 -0
  63. l3io/wp/backup/domain/database.py +113 -0
  64. l3io/wp/backup/domain/errors.py +1434 -0
  65. l3io/wp/backup/domain/exclusion.py +74 -0
  66. l3io/wp/backup/domain/exit_codes.py +87 -0
  67. l3io/wp/backup/domain/flag_map.py +246 -0
  68. l3io/wp/backup/domain/journal.py +142 -0
  69. l3io/wp/backup/domain/lock.py +61 -0
  70. l3io/wp/backup/domain/preflight.py +126 -0
  71. l3io/wp/backup/domain/restore.py +181 -0
  72. l3io/wp/backup/domain/search_replace.py +59 -0
  73. l3io/wp/backup/domain/secret.py +61 -0
  74. l3io/wp/backup/domain/site.py +60 -0
  75. l3io/wp/backup/domain/storage_target.py +60 -0
  76. l3io/wp/backup/ports/__init__.py +33 -0
  77. l3io/wp/backup/ports/adapter_set.py +66 -0
  78. l3io/wp/backup/ports/archive.py +136 -0
  79. l3io/wp/backup/ports/clock.py +23 -0
  80. l3io/wp/backup/ports/config.py +71 -0
  81. l3io/wp/backup/ports/crypto.py +30 -0
  82. l3io/wp/backup/ports/database.py +129 -0
  83. l3io/wp/backup/ports/exclusion.py +33 -0
  84. l3io/wp/backup/ports/journal.py +53 -0
  85. l3io/wp/backup/ports/lock.py +48 -0
  86. l3io/wp/backup/ports/preflight.py +23 -0
  87. l3io/wp/backup/ports/restore.py +59 -0
  88. l3io/wp/backup/ports/search_replace.py +40 -0
  89. l3io/wp/backup/ports/site_files.py +95 -0
  90. l3io/wp/backup/ports/tracing.py +80 -0
  91. l3io/wp/backup/py.typed +0 -0
  92. l3io_wordpress_backup-1.0.0.dist-info/METADATA +593 -0
  93. l3io_wordpress_backup-1.0.0.dist-info/RECORD +98 -0
  94. l3io_wordpress_backup-1.0.0.dist-info/WHEEL +4 -0
  95. l3io_wordpress_backup-1.0.0.dist-info/entry_points.txt +2 -0
  96. l3io_wordpress_backup-1.0.0.dist-info/licenses/LICENSE +21 -0
  97. wpbackup2/__init__.py +7 -0
  98. wpbackup2/__main__.py +8 -0
@@ -0,0 +1,1263 @@
1
+ """Owner decisions 49 to 55, ADR-0027, AD-18 — the direct load and its rollback.
2
+
3
+ :func:`load_live` is the real ``load_database`` slot of
4
+ ``adapters/restore_runner.py``'s ``execute_restore`` and :func:`check_live`
5
+ its ``check_database`` slot (the database part of ``PREFLIGHT``). The root
6
+ binds them with
7
+ ``functools.partial`` over the Run's
8
+ :class:`~l3io.wp.backup.ports.restore.RestorePorts`; a Dry Run is the same
9
+ calls over ``dry_run_adapters(...)``, so this module has no branch on it.
10
+
11
+ **The direct load (ADR-0027, decisions 49 and 55).** The Dump loads straight
12
+ into the live database, as the WordPress account, after the Safety Snapshot:
13
+ there is no staging database and no ``DB_NAME`` cutover. ``load_live``
14
+ journals each step through the journal it is handed:
15
+
16
+ 1. when the WordPress account cannot load the database as it stands (the
17
+ database is absent, or the account lacks a right), ``ensure_database``
18
+ as the administrator, the one use an administrator has (decision 55;
19
+ ``"database_created"`` when it created the database);
20
+ 2. ``"load_started"``, then ``load_dump(..., replace=True,
21
+ prune_prefix=<the site's table prefix>)``: database drops every table and
22
+ view carrying the prefix, then loads the Dump, so the database holds the
23
+ Archive's tables and no others with that prefix (decision 53); tables
24
+ without the prefix are never touched;
25
+ 3. the post-load check, ``survey_target`` of the loaded database
26
+ (:class:`LoadCheckFailedError` when it is not WordPress), then
27
+ ``"loaded"``; a not-performed ``LoadResult`` (a Dry Run) surveys nothing;
28
+ 4. a relocation's cutover (``--new-db-*``): one
29
+ ``ConfigCommand.set_constants(config_file, {key: value})`` per key, each
30
+ preceded by ``"cutover_started:<KEY>"`` and followed by
31
+ ``"cutover:<KEY>"``. A restore that relocates nothing writes no key.
32
+
33
+ **The automatic rollback (decision 50).** Any failure inside ``LOAD_DUMP``
34
+ after ``"load_started"`` (the load, its check, or a cutover that wrote no
35
+ key) puts the live database back before the Run exits
36
+ (:func:`roll_back`): the Safety Snapshot's Dump is loaded the same way
37
+ (``"rollback_started"``, ``"rolled_back"``), or, when the database held
38
+ nothing before, the tables loaded are dropped (a database this Run created
39
+ is dropped). The Run's own error is then re-raised, and the failure is
40
+ orderly (``core/restore_journal.is_orderly_failure``). If the rollback
41
+ fails, or nothing can roll back (``--no-safety-snapshot`` over a database
42
+ with content), ``"rollback_failed"`` is journaled, the Run stays recorded as
43
+ interrupted, and :class:`RollbackFailedError` names both failures, the
44
+ snapshot and the recovery command. A SIGTERM (``RunTerminated``) or Ctrl-C
45
+ during the load is not rolled back: the Run stops at once, recorded
46
+ interrupted, and the undo text names the snapshot. A relocation that loads
47
+ another database leaves the live one untouched; a relocated database this
48
+ Run created is dropped again (``"load_target_dropped"``).
49
+
50
+ No SQL is issued and no config byte is written here: database and
51
+ ``adapters/config_writer`` do both. ``l3io.wp.database`` is never imported
52
+ here: the load name is checked through
53
+ ``adapters/database.database_name_is_valid`` (ADR-0015), so this module
54
+ imports even without database installed; it imports nothing from
55
+ ``l3io.wp.config``.
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ from collections.abc import Mapping
61
+ from dataclasses import dataclass
62
+ from pathlib import Path, PurePosixPath
63
+ from typing import Final, NoReturn
64
+
65
+ import structlog
66
+
67
+ from l3io.wp.backup.adapters.clock import SystemClock
68
+ from l3io.wp.backup.adapters.database import (
69
+ ADMIN_SOURCE,
70
+ blocked_dump_error,
71
+ database_location_from_db_host,
72
+ database_name_is_valid,
73
+ )
74
+ from l3io.wp.backup.adapters.journal import CorruptJournalError
75
+ from l3io.wp.backup.adapters.tar import (
76
+ decrypt_payload,
77
+ read_inner_manifest,
78
+ verify_archive_manifest,
79
+ )
80
+ from l3io.wp.backup.core.restore import (
81
+ CUTOVER_KEYS,
82
+ NOT_ENSURED,
83
+ DatabaseRestoreReport,
84
+ RestoreInputs,
85
+ database_report_fields,
86
+ database_restored,
87
+ load_database_name,
88
+ planned_cutover_keys,
89
+ planned_cutover_targets,
90
+ )
91
+ from l3io.wp.backup.core.restore_journal import (
92
+ STEP_CONFIG_RESTORED,
93
+ STEP_CUTOVER,
94
+ STEP_CUTOVER_READBACK_FAILED,
95
+ STEP_CUTOVER_STARTED,
96
+ STEP_DATABASE_CREATED,
97
+ STEP_LOAD_STARTED,
98
+ STEP_LOAD_TARGET_DROPPED,
99
+ STEP_LOADED,
100
+ STEP_RELOCATION_ROLLED_BACK,
101
+ STEP_ROLLBACK_FAILED,
102
+ STEP_ROLLBACK_STARTED,
103
+ STEP_ROLLED_BACK,
104
+ cutover_progress,
105
+ interrupted_phase,
106
+ last_step,
107
+ recovery_command,
108
+ )
109
+ from l3io.wp.backup.domain.archive_format import (
110
+ DUMP_RELATIVE,
111
+ MemberRole,
112
+ check_inner_manifest,
113
+ )
114
+ from l3io.wp.backup.domain.database import (
115
+ DatabaseLocation,
116
+ EnsureOutcome,
117
+ LoadResult,
118
+ Readiness,
119
+ )
120
+ from l3io.wp.backup.domain.errors import (
121
+ AdminCredentialsRequiredError,
122
+ BackupError,
123
+ ConfigWriteFailedError,
124
+ CredentialsError,
125
+ DatabaseRefusedError,
126
+ PayloadDamagedError,
127
+ ProvisioningFailedError,
128
+ RefusedError,
129
+ RunTerminated,
130
+ VerificationFailedError,
131
+ )
132
+ from l3io.wp.backup.domain.exit_codes import ExitCode
133
+ from l3io.wp.backup.domain.journal import (
134
+ JOURNALED_CONSTANTS,
135
+ JournalHeader,
136
+ JournalRecord,
137
+ )
138
+ from l3io.wp.backup.domain.restore import RestorePhase
139
+ from l3io.wp.backup.domain.storage_target import StorageTarget
140
+ from l3io.wp.backup.ports.clock import Clock
141
+ from l3io.wp.backup.ports.config import WHOLE_FILE
142
+ from l3io.wp.backup.ports.crypto import PayloadCipher
143
+ from l3io.wp.backup.ports.journal import RunJournalCommand
144
+ from l3io.wp.backup.ports.restore import RestorePorts
145
+
146
+ __all__ = [
147
+ "ADMINISTRATOR_RESOLVES",
148
+ "CUTOVER_PASSWORD_SOURCE",
149
+ "ConfigCutoverError",
150
+ "CutoverTargetUnusableError",
151
+ "InvalidLoadDatabaseNameError",
152
+ "LoadCheckFailedError",
153
+ "RollbackFailedError",
154
+ "check_live",
155
+ "complete_cutover",
156
+ "load_live",
157
+ "roll_back",
158
+ "roll_back_relocation",
159
+ ]
160
+
161
+ _log = structlog.get_logger(__name__)
162
+ #: The default ``Clock`` of :func:`load_live` when a caller passes none.
163
+ SYSTEM_CLOCK: Final = SystemClock()
164
+
165
+ #: ``check_load``'s blockers an administrator resolves with ``ensure``
166
+ #: (database's ``Code`` values): the database is absent, the account is
167
+ #: absent or cannot log in, or it lacks a right on the database (``ensure``
168
+ #: grants it ALL on the database). Owner decision 55: only these call for an
169
+ #: administrator.
170
+ ADMINISTRATOR_RESOLVES: Final[frozenset[str]] = frozenset(
171
+ {"database_absent", "user_absent", "authentication_failed", "missing_privilege"}
172
+ )
173
+ #: The account a load check answers for when no ``DB_USER`` is known.
174
+ WORDPRESS_ACCOUNT: Final = "the WordPress account"
175
+ #: The label a missing relocated ``DB_PASSWORD`` source is named by.
176
+ CUTOVER_PASSWORD_SOURCE: Final = "relocated WordPress account" # noqa: S105 - a label
177
+ _PASSWORD: Final = "DB_PASSWORD" # noqa: S105 - a key name
178
+ _PHASE: Final = RestorePhase.LOAD_DUMP
179
+ _NS_PER_MS: Final = 1_000_000
180
+ #: Where the Safety Snapshot's Dump is extracted for a rollback, in the Run's
181
+ #: workspace.
182
+ _ROLLBACK_DIR: Final = "rollback"
183
+ _ROLLBACK_PAYLOAD: Final = "rollback-payload"
184
+
185
+
186
+ class LoadCheckFailedError(BackupError):
187
+ """The loaded database is not a WordPress database (the post-load check)."""
188
+
189
+ def __init__(
190
+ self, database: str, *, is_wordpress: bool, schema_version: str | None
191
+ ) -> None:
192
+ self.database = database
193
+ self.is_wordpress = is_wordpress
194
+ self.schema_version = schema_version
195
+ super().__init__(
196
+ f"the loaded database {database!r} failed its check (is_wordpress="
197
+ f"{is_wordpress}, schema_version={schema_version})"
198
+ )
199
+
200
+
201
+ class ConfigCutoverError(BackupError):
202
+ """A cutover write failed; ``key`` is byte-identical, ``written`` landed."""
203
+
204
+ def __init__(
205
+ self, path: str, key: str, *, written: tuple[str, ...], pending: tuple[str, ...]
206
+ ) -> None:
207
+ self.path = path
208
+ self.key = key
209
+ self.written = written
210
+ self.pending = pending
211
+ state = (
212
+ "no key was written"
213
+ if not written
214
+ else f"written: {', '.join(written)}; pending: {', '.join(pending)}"
215
+ )
216
+ super().__init__(f"the cutover could not write {key} to {path!r}; {state}")
217
+
218
+
219
+ class InvalidLoadDatabaseNameError(RefusedError):
220
+ """The load database's name is not a usable database identifier."""
221
+
222
+ def __init__(self, name: str) -> None:
223
+ self.name = name
224
+ super().__init__(
225
+ f"the load database name {name!r} is not a valid database name; "
226
+ "nothing was changed"
227
+ )
228
+
229
+
230
+ def _failure_text(exc: BaseException) -> str:
231
+ """An error's class, never its text, which may quote a dependency (AD-7)."""
232
+ return type(exc).__name__
233
+
234
+
235
+ class RollbackFailedError(BackupError):
236
+ """Decision 50: the load failed, and putting the database back failed too.
237
+
238
+ Decision 72 too: ``SEARCH_REPLACE`` failed after a relocation, and putting
239
+ the database or the original ``wp-config.php`` back failed.
240
+
241
+ ``FAILED``. ``cause`` is the load's failure and ``rollback`` the
242
+ rollback's (``None`` when nothing could roll back: no Safety Snapshot);
243
+ ``database`` the live database, now partly loaded; ``snapshot`` the
244
+ Safety Snapshot's path (``None`` without one) and ``recovery`` the
245
+ commands that restore it. The Run stays recorded as interrupted. Names,
246
+ paths, error classes and this package's own messages only.
247
+ """
248
+
249
+ def __init__(
250
+ self,
251
+ *,
252
+ cause: BaseException,
253
+ rollback: BaseException | None,
254
+ database: str,
255
+ snapshot: str | None,
256
+ recovery: str,
257
+ ) -> None:
258
+ self.cause = cause
259
+ self.rollback = rollback
260
+ self.database = database
261
+ self.snapshot = snapshot
262
+ self.recovery = recovery
263
+ failed = (
264
+ "no Safety Snapshot was taken, so nothing could roll it back"
265
+ if rollback is None
266
+ else f"rolling it back from the Safety Snapshot failed too "
267
+ f"({_failure_text(rollback)})"
268
+ )
269
+ what = (
270
+ f"restore it from the Safety Snapshot {snapshot!r}: {recovery}"
271
+ if snapshot is not None
272
+ else "restore the database from another backup"
273
+ )
274
+ super().__init__(
275
+ f"the restore into the database {database!r} failed "
276
+ f"({_failure_text(cause)}); {failed}. The database is "
277
+ f"partly restored and the run is recorded as interrupted; {what}"
278
+ )
279
+
280
+
281
+ # --------------------------------------------------------------------------
282
+ # Where the Dump loads
283
+ # --------------------------------------------------------------------------
284
+
285
+
286
+ @dataclass(frozen=True, slots=True)
287
+ class _Target:
288
+ live: DatabaseLocation
289
+ load: DatabaseLocation
290
+ #: The WordPress account the Dump loads as: the relocated user, else the
291
+ #: live one (prior ``DB_USER``).
292
+ load_user: str | None
293
+
294
+ @property
295
+ def loads_live(self) -> bool:
296
+ """Owner decision 49: the Dump loads into the live database itself."""
297
+ return self.load == self.live
298
+
299
+
300
+ def _target(inputs: RestoreInputs) -> _Target:
301
+ site, relocation = inputs.site, inputs.relocation
302
+ live = site.database_location()
303
+ base = relocation.load_location or live
304
+ prior = inputs.header.prior_constants.get("DB_USER")
305
+ return _Target(
306
+ live=live,
307
+ load=base.with_name(load_database_name(site.db_name, relocation)),
308
+ load_user=relocation.cutover_user or prior,
309
+ )
310
+
311
+
312
+ def _validate_name(name: str) -> None:
313
+ """Database's ``validate_database_name``, before the first call using ``name``."""
314
+ if not database_name_is_valid(name):
315
+ raise InvalidLoadDatabaseNameError(name)
316
+
317
+
318
+ def _require_password_source(inputs: RestoreInputs, ports: RestorePorts) -> None:
319
+ keys = planned_cutover_keys(inputs.relocation)
320
+ if _PASSWORD in keys and ports.cutover_credentials is None:
321
+ raise CredentialsError(CUTOVER_PASSWORD_SOURCE, missing_key=_PASSWORD)
322
+
323
+
324
+ # --------------------------------------------------------------------------
325
+ # PREFLIGHT — queries only
326
+ # --------------------------------------------------------------------------
327
+
328
+
329
+ def _refuse(
330
+ location: DatabaseLocation, blockers: tuple[str, ...], *, account: str
331
+ ) -> None:
332
+ """Refuse on ``blockers``, naming the database and ``account`` (never a secret)."""
333
+ if not blockers:
334
+ return
335
+ error = blocked_dump_error(location, blockers, credential_source=account)
336
+ if error is not None:
337
+ raise error
338
+ raise DatabaseRefusedError(
339
+ findings=blockers, database=location.name, account=account
340
+ )
341
+
342
+
343
+ def _readiness(
344
+ inputs: RestoreInputs, ports: RestorePorts, target: _Target
345
+ ) -> Readiness:
346
+ return ports.adapters.restore_database_query.check_load(
347
+ target.load,
348
+ source=None,
349
+ replace=True,
350
+ prune_prefix=inputs.site.table_prefix,
351
+ )
352
+
353
+
354
+ def _administrator_needed(readiness: Readiness) -> tuple[str, ...]:
355
+ """The blockers only an administrator resolves (decision 55), in order."""
356
+ return tuple(b for b in readiness.blockers if b in ADMINISTRATOR_RESOLVES)
357
+
358
+
359
+ def check_live(inputs: RestoreInputs, *, ports: RestorePorts) -> None:
360
+ """The database part of ``PREFLIGHT``: database's checks, before any command.
361
+
362
+ ``check_load`` as the WordPress account, with the load's own options
363
+ (``replace``, ``prune_prefix``). Its blockers that only an administrator
364
+ resolves (:data:`ADMINISTRATOR_RESOLVES`) call for ``check_ensure`` as
365
+ the administrator; with none configured, ``AdminCredentialsRequiredError``
366
+ names what is missing (owner decision 55). Any other blocker refuses.
367
+ Nothing is changed, a Dry Run included.
368
+ """
369
+ target = _target(inputs)
370
+ _validate_name(target.load.name)
371
+ _require_password_source(inputs, ports)
372
+ readiness = _readiness(inputs, ports, target)
373
+ account = target.load_user or WORDPRESS_ACCOUNT
374
+ needed = _administrator_needed(readiness)
375
+ others = tuple(b for b in readiness.blockers if b not in ADMINISTRATOR_RESOLVES)
376
+ _refuse(target.load, others, account=account)
377
+ if not needed:
378
+ _log.info(
379
+ "database_load_ready",
380
+ database=target.load.name,
381
+ administrator_needed=False,
382
+ )
383
+ return
384
+ try:
385
+ ensure = ports.adapters.restore_database_query.check_ensure(target.load)
386
+ except AdminCredentialsRequiredError as exc:
387
+ raise AdminCredentialsRequiredError(
388
+ exc.source,
389
+ flags=exc.flags,
390
+ missing=needed,
391
+ database=target.load.name,
392
+ account=account,
393
+ ) from exc
394
+ _refuse(target.load, ensure.blockers, account=ADMIN_SOURCE)
395
+ _log.info(
396
+ "database_load_ready",
397
+ database=target.load.name,
398
+ administrator_needed=True,
399
+ missing=list(needed),
400
+ )
401
+
402
+
403
+ # --------------------------------------------------------------------------
404
+ # LOAD_DUMP
405
+ # --------------------------------------------------------------------------
406
+
407
+
408
+ def _check_header(inputs: RestoreInputs, target: _Target) -> tuple[str, ...]:
409
+ """The cutover keys; ``ValueError`` when the header was built for another load."""
410
+ header = inputs.header
411
+ keys = planned_cutover_keys(inputs.relocation)
412
+ expected = (target.load.name, None, keys)
413
+ found = (header.load_database, header.staging_database, header.cutover_keys)
414
+ if expected != found:
415
+ msg = (
416
+ f"the journal header names load {found[0]!r}, staging {found[1]!r} and "
417
+ f"keys {list(found[2])}; this Run loads {expected[0]!r}, no staging "
418
+ f"database, keys {list(keys)}"
419
+ )
420
+ raise ValueError(msg)
421
+ return keys
422
+
423
+
424
+ def _post_load_check(
425
+ inputs: RestoreInputs,
426
+ target: _Target,
427
+ loaded: LoadResult,
428
+ *,
429
+ ports: RestorePorts,
430
+ ) -> bool:
431
+ """Structural: the loaded database must be WordPress with a schema version.
432
+
433
+ Given a not-performed ``LoadResult`` (a Dry Run's ``NoopDatabase``) it
434
+ surveys nothing, reports "would check" instead (ADR-0022) and returns
435
+ ``False``: nothing was checked. ``True`` only for a check that passed.
436
+ """
437
+ name = target.load.name
438
+ if not loaded.performed:
439
+ _log.info("database_load_checked", database=name, performed=False)
440
+ _log.info("would_check", database=name)
441
+ return False
442
+ state = ports.adapters.restore_database_query.survey_target(
443
+ target.load,
444
+ table_prefix=inputs.site.table_prefix,
445
+ wordpress_user=target.load_user,
446
+ )
447
+ _log.info(
448
+ "database_load_checked",
449
+ database=name,
450
+ is_wordpress=state.is_wordpress,
451
+ schema_version=state.schema_version,
452
+ performed=True,
453
+ )
454
+ if state.is_wordpress is not True or state.schema_version is None:
455
+ raise LoadCheckFailedError(
456
+ name, is_wordpress=state.is_wordpress, schema_version=state.schema_version
457
+ )
458
+ return True
459
+
460
+
461
+ def _cutover_value(
462
+ key: str, inputs: RestoreInputs, ports: RestorePorts, load_name: str
463
+ ) -> str:
464
+ if key == _PASSWORD:
465
+ if ports.cutover_credentials is None:
466
+ raise CredentialsError(CUTOVER_PASSWORD_SOURCE, missing_key=_PASSWORD)
467
+ return ports.cutover_credentials()
468
+ return planned_cutover_targets(load_name, inputs.relocation)[key]
469
+
470
+
471
+ def _read_back(
472
+ ports: RestorePorts, config_file: Path, key: str, value: str
473
+ ) -> bool | None:
474
+ """Whether ``key`` now holds ``value``; ``None`` when it cannot be read.
475
+
476
+ ADV-S02-04: after a write raised something other than
477
+ ``ConfigWriteFailedError`` (whose contract is that the key did not land),
478
+ the file itself says whether the one-key atomic write landed.
479
+ """
480
+ try:
481
+ current = ports.adapters.config_query.read_constants(config_file, (key,))
482
+ except RunTerminated:
483
+ raise # BL-E002-092
484
+ except Exception as exc: # unknown: the caller re-raises the write's error
485
+ _log.error("cutover_read_back_failed", key=key, error_type=type(exc).__name__)
486
+ return None
487
+ return current.get(key) == value
488
+
489
+
490
+ def _cutover(
491
+ inputs: RestoreInputs,
492
+ target: _Target,
493
+ keys: tuple[str, ...],
494
+ *,
495
+ ports: RestorePorts,
496
+ journal: RunJournalCommand,
497
+ clock: Clock,
498
+ ) -> tuple[str, ...]:
499
+ """A relocation's cutover: one atomic, verified ``set_constants`` per key.
500
+
501
+ Its duration is read from ``clock`` (the Run's ``Clock`` port,
502
+ BL-E003-100). Returns the keys written, in order. Each key's value is
503
+ resolved before its ``"cutover_started:<KEY>"`` intent, so a value that
504
+ cannot be had leaves no intent for a write that never began (ADV-S02-04).
505
+ A write that raises is classified: a ``ConfigWriteFailedError`` did not
506
+ land; any other error is read back — not at its target, it did not land,
507
+ and is handled as a ``ConfigWriteFailedError``; at its target, it landed
508
+ and the cutover goes on; unreadable, the error is re-raised and the
509
+ intent stays the last step, because whether it landed is then unknown.
510
+ """
511
+ if not keys:
512
+ return ()
513
+ config_file = Path(inputs.relocation.config_file or inputs.config_path)
514
+ command = ports.adapters.config_command
515
+ started = clock.monotonic_ns()
516
+ landed: list[str] = []
517
+ for key in keys:
518
+ value: str | None = _cutover_value(key, inputs, ports, target.load.name)
519
+ journal.step_completed(_PHASE, STEP_CUTOVER_STARTED + key)
520
+ try:
521
+ command.set_constants(config_file, {key: value or ""})
522
+ except RunTerminated:
523
+ raise # BL-E002-092: never read back and carried on past a SIGTERM
524
+ except Exception as exc:
525
+ arrived = (
526
+ False
527
+ if isinstance(exc, ConfigWriteFailedError)
528
+ else _read_back(ports, config_file, key, value or "")
529
+ )
530
+ if arrived is None:
531
+ raise
532
+ if not arrived:
533
+ if not landed:
534
+ journal.step_completed(_PHASE, STEP_CUTOVER_READBACK_FAILED)
535
+ pending = tuple(k for k in keys if k not in landed)
536
+ raise ConfigCutoverError(
537
+ str(config_file), key, written=tuple(landed), pending=pending
538
+ ) from exc
539
+ _log.warning(
540
+ "cutover_write_error_landed", key=key, error_type=type(exc).__name__
541
+ )
542
+ finally:
543
+ value = None # DB_PASSWORD is held for its one write only
544
+ landed.append(key)
545
+ journal.step_completed(_PHASE, STEP_CUTOVER + key)
546
+ _log.debug("cutover_key_written", key=key, wp_config_path=str(config_file))
547
+ host_fields: dict[str, object] = {}
548
+ if inputs.relocation.cutover_host is not None:
549
+ host_fields = {
550
+ "host_from": target.live.host,
551
+ "host_to": inputs.relocation.cutover_host,
552
+ }
553
+ _log.info(
554
+ "database_cutover",
555
+ keys=list(keys),
556
+ wp_config_path=str(config_file),
557
+ **{"from": target.live.name, "to": target.load.name},
558
+ **host_fields,
559
+ )
560
+ _log.info(
561
+ "phase_completed",
562
+ phase=_PHASE.name,
563
+ step="cutover",
564
+ duration_ms=(clock.monotonic_ns() - started) / _NS_PER_MS,
565
+ bytes=0,
566
+ outcome="ok",
567
+ exit_code=int(ExitCode.OK),
568
+ )
569
+ return tuple(landed)
570
+
571
+
572
+ def _ensure(
573
+ inputs: RestoreInputs,
574
+ target: _Target,
575
+ *,
576
+ ports: RestorePorts,
577
+ journal: RunJournalCommand,
578
+ ) -> EnsureOutcome | None:
579
+ """Decision 55: the administrator's ``ensure``, only where it is needed.
580
+
581
+ ``check_load`` is asked again here, as the WordPress account: the
582
+ preflight's answer is not carried across phases (ADR-0022), and the
583
+ administrator is used only when the account still cannot load.
584
+ """
585
+ needed = _administrator_needed(_readiness(inputs, ports, target))
586
+ if not needed:
587
+ return None
588
+ ensure = ports.adapters.restore_database_command.ensure_database(target.load)
589
+ if ensure.created_database:
590
+ journal.step_completed(_PHASE, STEP_DATABASE_CREATED)
591
+ _log.info(
592
+ "database_ensured_for_load",
593
+ database=target.load.name,
594
+ missing=list(needed),
595
+ created_database=ensure.created_database,
596
+ created_user=ensure.created_user,
597
+ granted=ensure.granted,
598
+ warnings=list(ensure.warnings),
599
+ )
600
+ return ensure
601
+
602
+
603
+ def _extract_dump(
604
+ inputs: RestoreInputs, *, ports: RestorePorts, workspace: Path
605
+ ) -> Path:
606
+ ports.adapters.site_files_command.extract(
607
+ inputs.archive,
608
+ workspace,
609
+ inputs.view,
610
+ roles=frozenset({MemberRole.DUMP}),
611
+ payload=None if inputs.payload is None else Path(inputs.payload),
612
+ )
613
+ return workspace / DUMP_RELATIVE
614
+
615
+
616
+ def load_live(
617
+ inputs: RestoreInputs,
618
+ journal: RunJournalCommand,
619
+ *,
620
+ ports: RestorePorts,
621
+ workspace: Path,
622
+ cipher: PayloadCipher | None = None,
623
+ clock: Clock = SYSTEM_CLOCK,
624
+ ) -> DatabaseRestoreReport:
625
+ """``LOAD_DUMP``: ensure if needed, load, check, a relocation's cutover.
626
+
627
+ ``clock`` times the cutover: the Run's ``Clock`` (the restore root passes
628
+ ``RunContext.clock``), the system clock when none is given. ``cipher``
629
+ decrypts an encrypted Safety Snapshot for the rollback.
630
+
631
+ Raises :class:`LoadCheckFailedError` or :class:`ConfigCutoverError`
632
+ (``FAILED``), the load's own errors, or :class:`RollbackFailedError` when
633
+ the rollback that follows one of them fails (:func:`roll_back`). A
634
+ header built for another load database or key set is a programming error
635
+ (``ValueError``), raised before any call.
636
+
637
+ FR-9: the returned report's ``restored`` is
638
+ ``core/restore.py::database_restored`` of the load's result, the check's
639
+ and the keys the cutover wrote; it is logged as ``database_restore_report``
640
+ (INFO). Any failure is logged as ``database_restore_report`` at ERROR
641
+ with ``restored: false`` and what is known, and re-raised; a failed load
642
+ is never returned as a value.
643
+ """
644
+ target = _target(inputs)
645
+ ensure: EnsureOutcome | None = None
646
+ written: tuple[str, ...] | None = None
647
+ started = cutting = False
648
+ try:
649
+ _validate_name(target.load.name)
650
+ keys = _check_header(inputs, target)
651
+ _require_password_source(inputs, ports)
652
+ ensure = _ensure(inputs, target, ports=ports, journal=journal)
653
+ dump = _extract_dump(inputs, ports=ports, workspace=workspace)
654
+ journal.step_completed(_PHASE, STEP_LOAD_STARTED)
655
+ started = True
656
+ loaded = ports.adapters.restore_database_command.load_dump(
657
+ target.load,
658
+ dump,
659
+ replace=True,
660
+ prune_prefix=inputs.site.table_prefix,
661
+ )
662
+ _log_dropped(target, loaded, inputs.site.table_prefix)
663
+ checked = _post_load_check(inputs, target, loaded, ports=ports)
664
+ journal.step_completed(_PHASE, STEP_LOADED)
665
+ cutting = True
666
+ written = _cutover(
667
+ inputs, target, keys, ports=ports, journal=journal, clock=clock
668
+ )
669
+ except BaseException as exc:
670
+ _report_failure(target, ensure, written, exc)
671
+ if not started and not _interrupt(exc) and not target.loads_live:
672
+ # Owner decision 73: a relocated database this Run created is
673
+ # dropped again, whatever failed after ``ensure``.
674
+ _drop_relocated(target, ensure, ports=ports, journal=journal)
675
+ # A cutover error other than ``ConfigCutoverError`` leaves unknown
676
+ # whether its key landed (ADV-S02-04): resolution decides, not a
677
+ # rollback.
678
+ ambiguous = cutting and not isinstance(exc, ConfigCutoverError)
679
+ if started and not ambiguous:
680
+ _undo_failed_load(
681
+ inputs,
682
+ journal,
683
+ exc,
684
+ ports=ports,
685
+ workspace=workspace,
686
+ cipher=cipher,
687
+ ensure=ensure,
688
+ )
689
+ raise
690
+ report = DatabaseRestoreReport(
691
+ live_database_before=target.live.name,
692
+ live_database_after=target.load.name,
693
+ database=_where(target.load),
694
+ ensure=NOT_ENSURED if ensure is None else ensure,
695
+ administrator=ensure is not None,
696
+ loaded_bytes=loaded.bytes,
697
+ load_duration_ms=loaded.duration_ms,
698
+ dropped_tables=loaded.dropped if loaded.performed else inputs.prefixed_tables,
699
+ restored=database_restored(
700
+ loaded, check_passed=checked, cutover_written=written == keys
701
+ ),
702
+ performed=loaded.performed,
703
+ )
704
+ _log.info("database_restore_report", **database_report_fields(report))
705
+ return report
706
+
707
+
708
+ def _where(location: DatabaseLocation) -> str:
709
+ return f"{location.host}:{location.port}/{location.name}"
710
+
711
+
712
+ def _log_dropped(target: _Target, loaded: LoadResult, prefix: str) -> None:
713
+ """Decision 53: the tables the load removed first, by name, logged."""
714
+ if not loaded.performed:
715
+ return
716
+ _log.info(
717
+ "database_tables_dropped",
718
+ database=target.load.name,
719
+ table_prefix=prefix,
720
+ count=len(loaded.dropped),
721
+ tables=list(loaded.dropped),
722
+ )
723
+
724
+
725
+ def _report_failure(
726
+ target: _Target,
727
+ ensure: EnsureOutcome | None,
728
+ written: tuple[str, ...] | None,
729
+ exc: BaseException,
730
+ ) -> None:
731
+ """``database_restore_report`` at ERROR: what is known, never ``restored``.
732
+
733
+ Fields are names, flags, codes and the error class — never the error's
734
+ text, which may quote the dependency (AD-7). The cutover's progress is
735
+ stated: the keys written (``cutover_written``) and, once every key
736
+ landed, ``cutover_completed``.
737
+ """
738
+ fields: dict[str, object] = {
739
+ "live_database_before": target.live.name,
740
+ "load_database": target.load.name,
741
+ "database": _where(target.load),
742
+ "restored": False,
743
+ "error_type": type(exc).__name__,
744
+ "administrator": ensure is not None,
745
+ }
746
+ if ensure is not None:
747
+ fields.update(
748
+ created_database=ensure.created_database,
749
+ created_user=ensure.created_user,
750
+ password_set=ensure.password_set,
751
+ granted=ensure.granted,
752
+ warnings=list(ensure.warnings),
753
+ performed=ensure.performed,
754
+ )
755
+ if written is not None:
756
+ fields.update(
757
+ cutover_written=list(written),
758
+ cutover_completed=True,
759
+ live_database_after=target.load.name,
760
+ )
761
+ elif isinstance(exc, ConfigCutoverError):
762
+ fields.update(
763
+ cutover_written=list(exc.written),
764
+ cutover_pending=list(exc.pending),
765
+ cutover_completed=False,
766
+ )
767
+ if isinstance(exc, ProvisioningFailedError):
768
+ fields["completed"] = list(exc.completed)
769
+ if isinstance(exc, DatabaseRefusedError):
770
+ fields["findings"] = list(exc.findings)
771
+ _log.error("database_restore_report", **fields)
772
+
773
+
774
+ # --------------------------------------------------------------------------
775
+ # The automatic rollback (owner decision 50)
776
+ # --------------------------------------------------------------------------
777
+
778
+
779
+ def _interrupt(exc: BaseException) -> bool:
780
+ """A SIGTERM or Ctrl-C: the Run stops now, and is not rolled back."""
781
+ return isinstance(exc, RunTerminated | KeyboardInterrupt) or not isinstance(
782
+ exc, Exception
783
+ )
784
+
785
+
786
+ def _undo_failed_load(
787
+ inputs: RestoreInputs,
788
+ journal: RunJournalCommand,
789
+ exc: BaseException,
790
+ *,
791
+ ports: RestorePorts,
792
+ workspace: Path,
793
+ cipher: PayloadCipher | None,
794
+ ensure: EnsureOutcome | None,
795
+ ) -> None:
796
+ """After ``"load_started"``: roll back, or drop a relocated database made here.
797
+
798
+ A cutover that wrote a key is left for ``--resolve-interrupted-run``
799
+ (its keys point the site at the loaded database). An interrupt is not
800
+ rolled back (:func:`_interrupt`). Raises :class:`RollbackFailedError`
801
+ from ``exc`` when the rollback fails; returns when the database is as it
802
+ was, so the caller re-raises ``exc``.
803
+ """
804
+ if _interrupt(exc):
805
+ return
806
+ if isinstance(exc, ConfigCutoverError) and exc.written:
807
+ return
808
+ target = _target(inputs)
809
+ if not target.loads_live:
810
+ _drop_relocated(target, ensure, ports=ports, journal=journal)
811
+ return
812
+ roll_back(
813
+ inputs,
814
+ journal,
815
+ exc,
816
+ ports=ports,
817
+ workspace=workspace,
818
+ cipher=cipher,
819
+ created=ensure is not None and ensure.created_database,
820
+ )
821
+
822
+
823
+ def _drop_relocated(
824
+ target: _Target,
825
+ ensure: EnsureOutcome | None,
826
+ *,
827
+ ports: RestorePorts,
828
+ journal: RunJournalCommand,
829
+ ) -> None:
830
+ """A relocated database this Run created is dropped again; the live is intact.
831
+
832
+ One that existed before is left as the load left it (the undo text says
833
+ so). A failed drop is logged, and the journal stays blocking; the caller
834
+ re-raises the original error.
835
+ """
836
+ if ensure is None or not ensure.created_database:
837
+ return
838
+ name = target.load.name
839
+ try:
840
+ ports.adapters.restore_database_command.drop_database(target.load, confirm=name)
841
+ journal.step_completed(_PHASE, STEP_LOAD_TARGET_DROPPED)
842
+ except RunTerminated:
843
+ raise # BL-E002-092
844
+ except Exception as exc: # the original error is re-raised by the caller
845
+ _log.error(
846
+ "load_database_drop_failed", database=name, error_type=type(exc).__name__
847
+ )
848
+ return
849
+ _log.warning("load_database_dropped", database=name)
850
+
851
+
852
+ def _snapshot_dump(
853
+ snapshot: str,
854
+ *,
855
+ ports: RestorePorts,
856
+ workspace: Path,
857
+ cipher: PayloadCipher | None,
858
+ ) -> Path:
859
+ """The Safety Snapshot's Dump, verified again and extracted into the workspace.
860
+
861
+ The snapshot was verified after it was published (FR-8); it is verified
862
+ again here, as ``VERIFY`` verifies an Archive, and an encrypted one's
863
+ inner Manifest must equal the outer one (ADR-0024 amendment) before its
864
+ Dump is read.
865
+ """
866
+ archive = StorageTarget(scheme="file", path=PurePosixPath(snapshot))
867
+ view, result, text = verify_archive_manifest(Path(snapshot), phase_key=_PHASE)
868
+ if view is None or not result.passed:
869
+ raise VerificationFailedError(result, snapshot)
870
+ payload: Path | None = None
871
+ if view.encrypted:
872
+ if cipher is None or text is None:
873
+ msg = "the Safety Snapshot is encrypted and no passphrase is bound"
874
+ raise ValueError(msg)
875
+ payload = decrypt_payload(
876
+ archive, view, cipher=cipher, destination=workspace / _ROLLBACK_PAYLOAD
877
+ )
878
+ field = check_inner_manifest(
879
+ text, read_inner_manifest(payload, phase_key=_PHASE)
880
+ )
881
+ if field is not None:
882
+ raise PayloadDamagedError(field=field)
883
+ destination = workspace / _ROLLBACK_DIR
884
+ destination.mkdir(mode=0o700, exist_ok=True)
885
+ ports.adapters.site_files_command.extract(
886
+ archive, destination, view, roles=frozenset({MemberRole.DUMP}), payload=payload
887
+ )
888
+ return destination / DUMP_RELATIVE
889
+
890
+
891
+ def roll_back(
892
+ inputs: RestoreInputs,
893
+ journal: RunJournalCommand,
894
+ cause: BaseException,
895
+ *,
896
+ ports: RestorePorts,
897
+ workspace: Path,
898
+ cipher: PayloadCipher | None,
899
+ created: bool = False,
900
+ ) -> None:
901
+ """Put the live database back as it was before the load (decision 50).
902
+
903
+ ``inputs.rollback`` says how (``core/restore.database_rollback``):
904
+ ``"snapshot"`` loads the Safety Snapshot's Dump the same way the load
905
+ did (``replace``, ``prune_prefix``); ``"empty"`` drops the tables the
906
+ load created, or the database itself when this Run created it
907
+ (``created``, as the administrator). ``"not-live"`` changes nothing.
908
+ ``"none"``, or any failure of the rollback, journals
909
+ ``"rollback_failed"`` and raises :class:`RollbackFailedError` naming
910
+ ``cause``, the rollback's failure, the snapshot and the recovery
911
+ command. Success journals ``"rolled_back"`` and logs WARNING
912
+ ``database_rolled_back``; the caller then re-raises ``cause``.
913
+ """
914
+ kind = inputs.rollback
915
+ if kind == "not-live":
916
+ return
917
+ target = _target(inputs)
918
+ header = inputs.header
919
+ prefix = inputs.site.table_prefix
920
+ command = ports.adapters.restore_database_command
921
+ _log.warning(
922
+ "database_rollback_started",
923
+ database=target.load.name,
924
+ rollback=kind,
925
+ snapshot=header.snapshot_path,
926
+ cause=type(cause).__name__,
927
+ )
928
+ snapshot = header.snapshot_path
929
+ if kind == "none" or (kind == "snapshot" and snapshot is None):
930
+ _rollback_failed(inputs, journal, cause, None, target=target)
931
+ try:
932
+ journal.step_completed(_PHASE, STEP_ROLLBACK_STARTED)
933
+ if kind == "snapshot" and snapshot is not None:
934
+ dump = _snapshot_dump(
935
+ snapshot, ports=ports, workspace=workspace, cipher=cipher
936
+ )
937
+ command.load_dump(target.load, dump, replace=True, prune_prefix=prefix)
938
+ elif created:
939
+ command.drop_database(target.load, confirm=target.load.name)
940
+ else:
941
+ command.drop_tables(target.load, prefix=prefix)
942
+ except RunTerminated:
943
+ raise
944
+ except Exception as exc: # named in RollbackFailedError, with the cause
945
+ _rollback_failed(inputs, journal, cause, exc, target=target)
946
+ journal.step_completed(_PHASE, STEP_ROLLED_BACK)
947
+ _log.warning(
948
+ "database_rolled_back",
949
+ database=target.load.name,
950
+ rollback=kind,
951
+ snapshot=header.snapshot_path,
952
+ cause=type(cause).__name__,
953
+ )
954
+
955
+
956
+ def roll_back_relocation(
957
+ inputs: RestoreInputs,
958
+ journal: RunJournalCommand,
959
+ cause: BaseException,
960
+ created: bool,
961
+ config_file: Path | None,
962
+ *,
963
+ ports: RestorePorts,
964
+ workspace: Path,
965
+ cipher: PayloadCipher | None,
966
+ ) -> None:
967
+ """Owner decision 72: a failed ``SEARCH_REPLACE`` puts the site back.
968
+
969
+ The executor's ``undo_relocation`` slot, called when the URL rewrite
970
+ fails after ``LOAD_DUMP`` (an interrupt is never rolled back). The
971
+ database first: the live one is rolled back as a failed load is
972
+ (:func:`roll_back`: the Safety Snapshot, or emptied when it was empty);
973
+ a relocated one this Run ``created`` is dropped again, and one that
974
+ existed (empty, decision 73) has the tables the load created dropped.
975
+ Then ``config_file``, the original ``wp-config.php``, is replaced by its
976
+ saved copy (the journal header's ``saved_config``), undoing
977
+ ``REWRITE_CONFIG`` and the cutover at once; ``None`` when the target had
978
+ none to put back. Journals ``"config_restored"`` and
979
+ ``"relocation_rolled_back"`` (orderly unless files were extracted) and
980
+ logs WARNING ``relocation_rolled_back``. Any failure journals
981
+ ``"rollback_failed"`` and raises :class:`RollbackFailedError` naming
982
+ ``cause`` (decision 50); the caller re-raises ``cause`` otherwise.
983
+ """
984
+ target = _target(inputs)
985
+ saved = inputs.header.saved_config
986
+ _log.warning(
987
+ "relocation_rollback_started",
988
+ database=target.load.name,
989
+ wp_config_path=None if config_file is None else str(config_file),
990
+ saved_config=saved,
991
+ cause=type(cause).__name__,
992
+ )
993
+ if target.loads_live:
994
+ roll_back(
995
+ inputs,
996
+ journal,
997
+ cause,
998
+ ports=ports,
999
+ workspace=workspace,
1000
+ cipher=cipher,
1001
+ created=created,
1002
+ )
1003
+ else:
1004
+ _empty_relocated(
1005
+ inputs, journal, cause, target=target, ports=ports, created=created
1006
+ )
1007
+ if config_file is not None:
1008
+ try:
1009
+ _put_back_config(config_file, saved, ports=ports)
1010
+ journal.step_completed(RestorePhase.SEARCH_REPLACE, STEP_CONFIG_RESTORED)
1011
+ except RunTerminated:
1012
+ raise
1013
+ except Exception as exc: # named in RollbackFailedError, with the cause
1014
+ _rollback_failed(inputs, journal, cause, exc, target=target)
1015
+ journal.step_completed(RestorePhase.SEARCH_REPLACE, STEP_RELOCATION_ROLLED_BACK)
1016
+ _log.warning(
1017
+ "relocation_rolled_back",
1018
+ database=target.load.name,
1019
+ wp_config_path=None if config_file is None else str(config_file),
1020
+ saved_config=saved,
1021
+ cause=type(cause).__name__,
1022
+ )
1023
+
1024
+
1025
+ def _put_back_config(
1026
+ config_file: Path, saved: str | None, *, ports: RestorePorts
1027
+ ) -> None:
1028
+ """The saved copy's bytes over ``config_file``, atomically, nothing carried."""
1029
+ if saved is None:
1030
+ reason = "no saved copy of wp-config.php to put back"
1031
+ raise ConfigWriteFailedError(config_file, WHOLE_FILE, reason)
1032
+ text = Path(saved).read_bytes().decode("utf-8")
1033
+ ports.adapters.config_command.replace_file(config_file, text, keep=())
1034
+
1035
+
1036
+ def _empty_relocated(
1037
+ inputs: RestoreInputs,
1038
+ journal: RunJournalCommand,
1039
+ cause: BaseException,
1040
+ *,
1041
+ target: _Target,
1042
+ ports: RestorePorts,
1043
+ created: bool,
1044
+ ) -> None:
1045
+ """The relocated database as it was: dropped if made here, else emptied."""
1046
+ command = ports.adapters.restore_database_command
1047
+ try:
1048
+ journal.step_completed(_PHASE, STEP_ROLLBACK_STARTED)
1049
+ if created:
1050
+ command.drop_database(target.load, confirm=target.load.name)
1051
+ journal.step_completed(_PHASE, STEP_LOAD_TARGET_DROPPED)
1052
+ else:
1053
+ command.drop_tables(target.load, prefix=inputs.site.table_prefix)
1054
+ except RunTerminated:
1055
+ raise
1056
+ except Exception as exc: # named in RollbackFailedError, with the cause
1057
+ _rollback_failed(inputs, journal, cause, exc, target=target)
1058
+ journal.step_completed(_PHASE, STEP_ROLLED_BACK)
1059
+
1060
+
1061
+ def _rollback_failed(
1062
+ inputs: RestoreInputs,
1063
+ journal: RunJournalCommand,
1064
+ cause: BaseException,
1065
+ failure: BaseException | None,
1066
+ *,
1067
+ target: _Target,
1068
+ ) -> NoReturn:
1069
+ header = inputs.header
1070
+ try:
1071
+ journal.step_completed(_PHASE, STEP_ROLLBACK_FAILED)
1072
+ except RunTerminated:
1073
+ raise
1074
+ except Exception as exc: # the journal stays at rollback_started: blocking
1075
+ _log.error("rollback_failed_not_journaled", error_type=type(exc).__name__)
1076
+ error = RollbackFailedError(
1077
+ cause=cause,
1078
+ rollback=failure,
1079
+ database=_where(target.load),
1080
+ snapshot=header.snapshot_path,
1081
+ recovery=recovery_command(header),
1082
+ )
1083
+ _log.error(
1084
+ "database_rollback_failed",
1085
+ database=target.load.name,
1086
+ cause=type(cause).__name__,
1087
+ rollback_error=None if failure is None else type(failure).__name__,
1088
+ snapshot=header.snapshot_path,
1089
+ recovery=error.recovery,
1090
+ )
1091
+ raise error from cause
1092
+
1093
+
1094
+ # --------------------------------------------------------------------------
1095
+ # Resolution: completing an interrupted cutover set
1096
+ # --------------------------------------------------------------------------
1097
+
1098
+
1099
+ class CutoverTargetUnusableError(RefusedError):
1100
+ """ADV-S02-05: the database an interrupted cutover pointed at is unusable."""
1101
+
1102
+ def __init__(self, database: str, *, run_id: str, exists: bool) -> None:
1103
+ self.database = database
1104
+ self.run_id = run_id
1105
+ self.exists = exists
1106
+ state = "is not a WordPress database" if exists else "no longer exists"
1107
+ super().__init__(
1108
+ f"the interrupted run {run_id} was switching wp-config.php to "
1109
+ f"{database!r}, which {state}; the cutover was not completed and "
1110
+ "nothing was written. Set the keys already written back to the "
1111
+ "journal's prior_constants, or restore from the Safety Snapshot, "
1112
+ f"then run --resolve-interrupted-run {run_id} again"
1113
+ )
1114
+
1115
+
1116
+ def _cutover_target(header: JournalHeader, key: str, *, journal_path: str) -> str:
1117
+ """The header's target for a non-secret ``key``; a missing one is corrupt."""
1118
+ value = header.cutover_targets.get(key)
1119
+ if value is None:
1120
+ raise CorruptJournalError(
1121
+ journal_path, f"its header records no cutover target for {key}"
1122
+ )
1123
+ return value
1124
+
1125
+
1126
+ def _load_location(
1127
+ header: JournalHeader, current: Mapping[str, object]
1128
+ ) -> DatabaseLocation | None:
1129
+ """The server and name the interrupted cutover points ``wp-config.php`` at.
1130
+
1131
+ ``DB_HOST`` is the header's target when the cutover moves it, else the
1132
+ one ``wp-config.php`` holds now; ``None`` when neither is known.
1133
+ """
1134
+ host = header.cutover_targets.get("DB_HOST", current.get("DB_HOST"))
1135
+ if not isinstance(host, str) or not host:
1136
+ return None
1137
+ return database_location_from_db_host(host, header.load_database)
1138
+
1139
+
1140
+ def _back_at_prior(header: JournalHeader, current: Mapping[str, object]) -> bool:
1141
+ """Whether every journaled cutover key holds its pre-Run value again."""
1142
+ return all(
1143
+ current.get(key) == header.prior_constants.get(key)
1144
+ for key in header.cutover_keys
1145
+ if key in JOURNALED_CONSTANTS
1146
+ )
1147
+
1148
+
1149
+ def _require_load_database(
1150
+ header: JournalHeader,
1151
+ current: Mapping[str, object],
1152
+ *,
1153
+ ports: RestorePorts,
1154
+ table_prefix: str,
1155
+ ) -> bool:
1156
+ """Survey the load database before any write; ``False``: write nothing.
1157
+
1158
+ A load database that still exists and passes the post-load check:
1159
+ ``True``. Otherwise, when ``wp-config.php`` is back at its pre-Run values
1160
+ (no key landed, or the operator set them back), there is nothing to roll
1161
+ forward: ``False``, logged ``cutover_abandoned``. Otherwise
1162
+ :class:`CutoverTargetUnusableError`.
1163
+ """
1164
+ location = _load_location(header, current)
1165
+ state = (
1166
+ None
1167
+ if location is None
1168
+ else ports.adapters.restore_database_query.survey_target(
1169
+ location,
1170
+ table_prefix=table_prefix,
1171
+ wordpress_user=header.cutover_targets.get(
1172
+ "DB_USER", header.prior_constants.get("DB_USER")
1173
+ ),
1174
+ )
1175
+ )
1176
+ usable = (
1177
+ state is not None
1178
+ and state.database_exists
1179
+ and state.is_wordpress is True
1180
+ and state.schema_version is not None
1181
+ )
1182
+ if usable:
1183
+ return True
1184
+ exists = state is not None and state.database_exists
1185
+ if _back_at_prior(header, current):
1186
+ _log.warning(
1187
+ "cutover_abandoned",
1188
+ load_database=header.load_database,
1189
+ database_exists=exists,
1190
+ reason="wp-config.php holds its pre-run values",
1191
+ )
1192
+ return False
1193
+ raise CutoverTargetUnusableError(
1194
+ header.load_database, run_id=header.run_id, exists=exists
1195
+ )
1196
+
1197
+
1198
+ def complete_cutover(
1199
+ record: JournalRecord,
1200
+ *,
1201
+ ports: RestorePorts,
1202
+ table_prefix: str,
1203
+ journal_path: str,
1204
+ ) -> tuple[str, ...]:
1205
+ """Complete the cutover set of a Run stopped inside it; the keys written.
1206
+
1207
+ Called by ``--resolve-interrupted-run`` (E003-S02-006) before
1208
+ ``RunJournalCommand.resolve``. Only when the Run stopped at a
1209
+ ``"cutover_started:*"`` or ``"cutover:*"`` step with keys pending: the
1210
+ keys are re-read through ``ConfigQuery.read_constants`` to learn what
1211
+ actually landed, and each pending key not already at its target is
1212
+ written from the header's non-secret targets; ``DB_PASSWORD`` from
1213
+ ``ports.cutover_credentials``, else ``CredentialsError`` naming it and
1214
+ nothing is written. Any other journal: nothing is written (a direct
1215
+ load's interruption is resolved by acknowledging it; its undo text names
1216
+ the Safety Snapshot and the recovery command).
1217
+
1218
+ ADV-S02-05: before the first write the load database is surveyed
1219
+ (``table_prefix`` is the Site's); one that is gone or not WordPress is
1220
+ never written to (:func:`_require_load_database`). A header with no
1221
+ target for a pending key is :class:`CorruptJournalError` naming
1222
+ ``journal_path``, raised before any write.
1223
+ """
1224
+ header, entries = record.header, record.entries
1225
+ phase = interrupted_phase(entries)
1226
+ step = last_step(entries, phase)
1227
+ if phase is not _PHASE or step is None:
1228
+ return ()
1229
+ if not step.startswith((STEP_CUTOVER, STEP_CUTOVER_STARTED)):
1230
+ return ()
1231
+ _, pending = cutover_progress(entries, header)
1232
+ if not pending:
1233
+ return ()
1234
+ credentials = ports.cutover_credentials
1235
+ if _PASSWORD in pending and credentials is None:
1236
+ raise CredentialsError(CUTOVER_PASSWORD_SOURCE, missing_key=_PASSWORD)
1237
+ targets = {
1238
+ key: _cutover_target(header, key, journal_path=journal_path)
1239
+ for key in pending
1240
+ if key != _PASSWORD
1241
+ }
1242
+ config_file = Path(header.wp_config_path)
1243
+ adapters = ports.adapters
1244
+ current = adapters.config_query.read_constants(config_file, CUTOVER_KEYS)
1245
+ if not _require_load_database(
1246
+ header, current, ports=ports, table_prefix=table_prefix
1247
+ ):
1248
+ return ()
1249
+ written: list[str] = []
1250
+ for key in pending:
1251
+ if key == _PASSWORD and credentials is not None:
1252
+ value: str | None = credentials()
1253
+ else:
1254
+ value = targets[key]
1255
+ if current.get(key) == value:
1256
+ continue
1257
+ try:
1258
+ adapters.config_command.set_constants(config_file, {key: value or ""})
1259
+ finally:
1260
+ value = None
1261
+ written.append(key)
1262
+ _log.info("cutover_completed", keys=written, wp_config_path=str(config_file))
1263
+ return tuple(written)