debkit 0.1.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.
- debkit/__init__.py +7 -0
- debkit/__main__.py +8 -0
- debkit/_env.py +67 -0
- debkit/_escape.py +25 -0
- debkit/_logging.py +98 -0
- debkit/_options.py +177 -0
- debkit/action/__init__.py +325 -0
- debkit/action/action_history.py +191 -0
- debkit/action/action_pkg.py +468 -0
- debkit/action/action_sync.py +495 -0
- debkit/argparser.py +246 -0
- debkit/argtypes.py +140 -0
- debkit/cli.py +130 -0
- debkit/repo/__init__.py +610 -0
- debkit/repo/changes.py +172 -0
- debkit/repo/component.py +335 -0
- debkit/repo/compress.py +266 -0
- debkit/repo/debfile.py +207 -0
- debkit/repo/gnupg.py +215 -0
- debkit/repo/hashes.py +139 -0
- debkit/repo/index_selection.py +224 -0
- debkit/repo/package.py +177 -0
- debkit/repo/packages.py +525 -0
- debkit/repo/params.py +305 -0
- debkit/repo/release.py +881 -0
- debkit/repo/repo_diff.py +114 -0
- debkit/repo/repo_rw.py +444 -0
- debkit/repo/repo_sync.py +433 -0
- debkit/repo/shared_root.py +348 -0
- debkit/repo/sources.py +165 -0
- debkit/repo/stanza.py +47 -0
- debkit-0.1.0.dist-info/METADATA +138 -0
- debkit-0.1.0.dist-info/RECORD +36 -0
- debkit-0.1.0.dist-info/WHEEL +4 -0
- debkit-0.1.0.dist-info/entry_points.txt +2 -0
- debkit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
"""Sync (mirror) a Debian repo from a source to a target storage, and check a repo."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from argparse import BooleanOptionalAction
|
|
7
|
+
from contextlib import nullcontext
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
10
|
+
|
|
11
|
+
from humanize import naturalsize
|
|
12
|
+
from txstore import get_supported_schemes, maybe_transaction, redact_url
|
|
13
|
+
|
|
14
|
+
from debkit.action import (
|
|
15
|
+
Action,
|
|
16
|
+
ActionException,
|
|
17
|
+
OutputType,
|
|
18
|
+
attach_storage_repo,
|
|
19
|
+
dump_json,
|
|
20
|
+
open_target_repo,
|
|
21
|
+
)
|
|
22
|
+
from debkit.repo.component import IndexLoad
|
|
23
|
+
from debkit.repo.hashes import ChecksumException
|
|
24
|
+
from debkit.repo.params import is_valid_arch
|
|
25
|
+
from debkit.repo.release import ReleaseNotFoundException
|
|
26
|
+
from debkit.repo.repo_sync import RepoSync
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from argparse import Namespace
|
|
30
|
+
|
|
31
|
+
from debkit._options import EnvArgumentParser
|
|
32
|
+
from debkit.repo.repo_diff import RepoDiff
|
|
33
|
+
from debkit.repo.repo_rw import RepoRW
|
|
34
|
+
|
|
35
|
+
ARCHITECTURES_DEFAULT = "amd64,arm64"
|
|
36
|
+
INDICES_EXCLUDE_DEFAULT = ""
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
logger.addHandler(logging.NullHandler())
|
|
40
|
+
|
|
41
|
+
# a maximum number of repetitions if the source has changed during synchronization
|
|
42
|
+
MAX_UPDATED_REPO_RETRIES = 4
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _split_csv(value: str) -> list[str]:
|
|
46
|
+
"""Split a comma-separated flag value, dropping empty tokens.
|
|
47
|
+
|
|
48
|
+
A value of commas alone yields an empty list, which callers still apply
|
|
49
|
+
-> [VALIDATION.md](VALIDATION.md#architectures).
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
value: The raw flag value.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
The non-empty tokens, in order.
|
|
56
|
+
"""
|
|
57
|
+
return [token for token in value.split(",") if token]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _selection(pars: Namespace) -> tuple[list[str] | None, list[str] | None]:
|
|
61
|
+
"""Read the `--architectures` and `--indices-exclude` selection `sync` and `check` share.
|
|
62
|
+
|
|
63
|
+
A check builds its index and package sets the way a sync does, so both read one
|
|
64
|
+
selection -> [CONFIG.md](CONFIG.md#check).
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
pars: Command line arguments from argparser.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
ActionException: An `--architectures` token is not an architecture name.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
The selected architectures and the index exclude globs, each None when its flag is
|
|
74
|
+
empty.
|
|
75
|
+
"""
|
|
76
|
+
archs: list[str] | None = None
|
|
77
|
+
if pars.architectures != "":
|
|
78
|
+
archs = _split_csv(pars.architectures)
|
|
79
|
+
for arch in archs:
|
|
80
|
+
if not is_valid_arch(arch):
|
|
81
|
+
raise ActionException(f"Invalid architecture: {arch!r}")
|
|
82
|
+
|
|
83
|
+
# index excludes apply to both repos so --verify-existing agrees with the sync
|
|
84
|
+
excludes = _split_csv(pars.indices_exclude) if pars.indices_exclude != "" else None
|
|
85
|
+
return archs, excludes
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ActionSync(Action):
|
|
89
|
+
"""Sync debian repo from source repository.
|
|
90
|
+
|
|
91
|
+
Attributes:
|
|
92
|
+
source_repo: The repository the sync reads.
|
|
93
|
+
source_url: The source deb source string; logged only through `redact_url`.
|
|
94
|
+
target_url: The target deb source string; logged only through `redact_url`.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
source_repo: RepoSync
|
|
98
|
+
|
|
99
|
+
def __init__(self, pars: Namespace, create_path: bool = False):
|
|
100
|
+
"""Initialize ActionSync.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
pars: Command line arguments from argparser.
|
|
104
|
+
create_path: Create path or bucket if True.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
ActionException: An `--architectures` token is not an architecture name; refused
|
|
108
|
+
before any storage is opened, so no target path or bucket is created.
|
|
109
|
+
"""
|
|
110
|
+
archs, indices_exclude = _selection(pars)
|
|
111
|
+
super().__init__(pars)
|
|
112
|
+
self.verify_existing: bool = pars.verify_existing
|
|
113
|
+
self.indices_only: bool = pars.indices_only
|
|
114
|
+
self.allow_release_rollback: bool = pars.allow_release_rollback
|
|
115
|
+
self.source_url: str = pars.source_url
|
|
116
|
+
self.target_url: str = pars.target_url
|
|
117
|
+
|
|
118
|
+
# the source, then the target, each with the selection applied
|
|
119
|
+
logger.debug("Prepare source URL: %s", redact_url(pars.source_url))
|
|
120
|
+
storage, params = attach_storage_repo(
|
|
121
|
+
pars, pars.source_url, archs=archs, indices_exclude=indices_exclude
|
|
122
|
+
)
|
|
123
|
+
self.source_repo = RepoSync(storage, params, gpg=self.gpg)
|
|
124
|
+
# a sync overwrites the target, so it gets no `GnuPG`: its Release is read
|
|
125
|
+
# unverified and never signed -> [CRYPTO.md](CRYPTO.md#gpg)
|
|
126
|
+
self.target_repo = open_target_repo(
|
|
127
|
+
pars, gpg=None, create_path=create_path, archs=archs, indices_exclude=indices_exclude
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def _print_sync_brief(self, diff: RepoDiff) -> None:
|
|
131
|
+
"""Print sync brief output.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
diff: Repository diff object.
|
|
135
|
+
"""
|
|
136
|
+
print(f"Added {diff.count_pkgs_to_copy()} packages.")
|
|
137
|
+
print(f"Removed {diff.count_pkgs_to_remove()} packages.")
|
|
138
|
+
print(
|
|
139
|
+
f"{self._target_metrics.write_objects_total} objects "
|
|
140
|
+
f"({naturalsize(self._target_metrics.write_bytes)}) transferred."
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def _print_sync_json(self, diff: RepoDiff, source: RepoSync) -> None:
|
|
144
|
+
"""Print sync json output.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
diff: Repository diff object.
|
|
148
|
+
source: The source repository the sync read.
|
|
149
|
+
"""
|
|
150
|
+
json_dict: dict[str, Any] = {
|
|
151
|
+
"packages": diff.dump(),
|
|
152
|
+
"transfer": {"metrics": {}},
|
|
153
|
+
}
|
|
154
|
+
json_dict["transfer"]["metrics"]["source_storage"] = source.storage.metrics.dump()
|
|
155
|
+
json_dict["transfer"]["metrics"]["target_storage"] = self._target_metrics.dump()
|
|
156
|
+
|
|
157
|
+
print(dump_json(json_dict))
|
|
158
|
+
|
|
159
|
+
def sync(self) -> None:
|
|
160
|
+
"""Sync debian repo from source storage to target storage."""
|
|
161
|
+
if self.allow_release_rollback:
|
|
162
|
+
logger.warning("Release freshness checks skipped: --allow-release-rollback is set")
|
|
163
|
+
|
|
164
|
+
with maybe_transaction(self.target_repo.storage, self.history_retention):
|
|
165
|
+
# a peer may commit before `history_lock` is granted, so the target every pass
|
|
166
|
+
# plans and floors against is read under it -> txstore locking rules
|
|
167
|
+
logger.info("---------- Load target repo (%s)...", redact_url(self.target_url))
|
|
168
|
+
run_floor = self._load_target()
|
|
169
|
+
# the report compares against the target as this run found it
|
|
170
|
+
target_before = self.target_repo.snapshot()
|
|
171
|
+
if self.verify_existing:
|
|
172
|
+
self._verify_existing(self.target_repo)
|
|
173
|
+
|
|
174
|
+
logger.info("---------- Load source repo (%s)...", redact_url(self.source_url))
|
|
175
|
+
self.source_repo.load(IndexLoad.STRICT)
|
|
176
|
+
self._check_fresh(run_floor)
|
|
177
|
+
self._sync_until_settled(run_floor)
|
|
178
|
+
|
|
179
|
+
ret_diff = self.source_repo.diff(target_before)
|
|
180
|
+
if self.output == OutputType.json:
|
|
181
|
+
self._print_sync_json(ret_diff, self.source_repo)
|
|
182
|
+
else:
|
|
183
|
+
self._print_sync_brief(ret_diff)
|
|
184
|
+
|
|
185
|
+
def _sync_until_settled(self, run_floor: str | None) -> None:
|
|
186
|
+
"""Run sync passes until the source Release holds across one.
|
|
187
|
+
|
|
188
|
+
A source that changed during a pass is read again with the target the pass staged,
|
|
189
|
+
and checked against both that target and the Release the run found. After
|
|
190
|
+
`MAX_UPDATED_REPO_RETRIES` passes the source is not read again
|
|
191
|
+
-> [VALIDATION.md](VALIDATION.md#index-selection).
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
run_floor: The target Release `Date` as the run found it.
|
|
195
|
+
"""
|
|
196
|
+
for _ in range(MAX_UPDATED_REPO_RETRIES - 1):
|
|
197
|
+
if not self._sync_pass():
|
|
198
|
+
return
|
|
199
|
+
synced_sha256 = self.source_repo.release.content_sha256
|
|
200
|
+
logger.info("---------- Retrieve load to verify source repo changes...")
|
|
201
|
+
self.source_repo.load(IndexLoad.STRICT)
|
|
202
|
+
if self.source_repo.release.content_sha256 == synced_sha256:
|
|
203
|
+
return
|
|
204
|
+
logger.info("Source repo modified during synchronisation! Repeat sync...")
|
|
205
|
+
# reads go through the transaction, so the target now describes the bytes the
|
|
206
|
+
# previous pass staged -> txstore footmark rules; the run never goes below the
|
|
207
|
+
# Release it found -> [CRYPTO.md](CRYPTO.md#release-freshness)
|
|
208
|
+
self._check_fresh(self._load_target(), run_floor)
|
|
209
|
+
if self._sync_pass():
|
|
210
|
+
logger.warning(
|
|
211
|
+
"Source repo still changing after %d passes; committing the last pass",
|
|
212
|
+
MAX_UPDATED_REPO_RETRIES,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def _sync_pass(self) -> bool:
|
|
216
|
+
"""Plan one pass from the loaded source and target, and sync it.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
False when the plan was empty, so nothing was synced.
|
|
220
|
+
"""
|
|
221
|
+
logger.info("Building filelists...")
|
|
222
|
+
plan = self.source_repo.build_sync_lists(self.target_repo, indices_only=self.indices_only)
|
|
223
|
+
if plan.is_empty():
|
|
224
|
+
logger.info("Nothing to sync.")
|
|
225
|
+
return False
|
|
226
|
+
# a ChecksumException propagates to discard the transaction; cli.py logs it
|
|
227
|
+
self.source_repo.sync(self.target_repo, plan)
|
|
228
|
+
return True
|
|
229
|
+
|
|
230
|
+
def _check_fresh(self, *floors: str | None) -> None:
|
|
231
|
+
"""Check the loaded source Release against each floor, in order.
|
|
232
|
+
|
|
233
|
+
Skipped without GPG verification or with `--allow-release-rollback`
|
|
234
|
+
-> [CRYPTO.md](CRYPTO.md#release-freshness).
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
floors: Target Release `Date` values the source must not undercut; None floors
|
|
238
|
+
nothing.
|
|
239
|
+
"""
|
|
240
|
+
if not self.source_repo.params.verify_gpg or self.allow_release_rollback:
|
|
241
|
+
return
|
|
242
|
+
now = datetime.now(UTC)
|
|
243
|
+
for floor in floors:
|
|
244
|
+
self.source_repo.release.check_fresh_against(floor, now)
|
|
245
|
+
|
|
246
|
+
def _load_target(self) -> str | None:
|
|
247
|
+
"""Load the target repo, treating a missing or corrupt one as empty.
|
|
248
|
+
|
|
249
|
+
A target that fails a checksum is reset, so nothing it recorded settles an
|
|
250
|
+
index -> [VALIDATION.md](VALIDATION.md#index-selection). Its Release still
|
|
251
|
+
floors the source, so the `Date` it carried is returned
|
|
252
|
+
-> [CRYPTO.md](CRYPTO.md#release-freshness).
|
|
253
|
+
|
|
254
|
+
Returns:
|
|
255
|
+
The target Release `Date` as read, taken before any reset; None without one.
|
|
256
|
+
"""
|
|
257
|
+
try:
|
|
258
|
+
# the sync plans from the source and only copies indices, never writing one from
|
|
259
|
+
# this load, so an unreadable target index is skipped
|
|
260
|
+
# -> [VALIDATION.md](VALIDATION.md#index-loading)
|
|
261
|
+
self.target_repo.load(IndexLoad.READ_ONLY)
|
|
262
|
+
except ReleaseNotFoundException as exc:
|
|
263
|
+
logger.warning("Target repo is empty: %s", exc)
|
|
264
|
+
except ChecksumException as exc:
|
|
265
|
+
logger.warning("Target repo corrupted: %s indices IGNORED", exc)
|
|
266
|
+
floor = self.target_repo.release.fields.get("Date")
|
|
267
|
+
self.target_repo.reset()
|
|
268
|
+
return floor
|
|
269
|
+
return self.target_repo.release.fields.get("Date")
|
|
270
|
+
|
|
271
|
+
@staticmethod
|
|
272
|
+
def _verify_existing(target: RepoRW) -> None:
|
|
273
|
+
"""Verify the loaded target's payloads, deleting each that fails.
|
|
274
|
+
|
|
275
|
+
Runs inside the sync transaction, so the deletions are staged and recorded
|
|
276
|
+
with the sync, whose repair pass copies each deleted payload again
|
|
277
|
+
-> [STORAGE.md](STORAGE.md#transactions).
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
target: The loaded target repository.
|
|
281
|
+
"""
|
|
282
|
+
logger.info("---------- Verify target repo packages...")
|
|
283
|
+
# orphans are left to the sync's own purge
|
|
284
|
+
report = target.verify_payloads(fix=True)
|
|
285
|
+
if report.failed > report.fixed:
|
|
286
|
+
logger.warning(
|
|
287
|
+
"%d target files failed verification and were not deleted",
|
|
288
|
+
report.failed - report.fixed,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
@staticmethod
|
|
292
|
+
def add_selection_cli_args(parser: EnvArgumentParser) -> None:
|
|
293
|
+
"""Register the selection flags shared by the sync and check subcommands.
|
|
294
|
+
|
|
295
|
+
A check builds its index and package sets the way a sync does, so both
|
|
296
|
+
subcommands read the same dests, env fallbacks and defaults from one
|
|
297
|
+
registration: a check run with other values reports the difference as
|
|
298
|
+
missing or orphan objects and `--fix` acts on it
|
|
299
|
+
-> [CONFIG.md](CONFIG.md#check).
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
parser: The parser to add arguments to.
|
|
303
|
+
"""
|
|
304
|
+
parser.add_env_argument(
|
|
305
|
+
"--architectures",
|
|
306
|
+
env="DEBKIT_ARCHITECTURES",
|
|
307
|
+
dest="architectures",
|
|
308
|
+
help="comma separated list of architectures to limit the selection",
|
|
309
|
+
default=ARCHITECTURES_DEFAULT,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
parser.add_env_argument(
|
|
313
|
+
"--indices-exclude",
|
|
314
|
+
env="DEBKIT_INDICES_EXCLUDE",
|
|
315
|
+
dest="indices_exclude",
|
|
316
|
+
help="comma separated globs of Release-listed index paths to skip "
|
|
317
|
+
"(Example: '*/i18n/*,*/dep11/icons-*')",
|
|
318
|
+
default=INDICES_EXCLUDE_DEFAULT,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def add_sync_cli_args(parser: EnvArgumentParser) -> None:
|
|
323
|
+
"""Add argparser arguments for sync.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
parser: The parser to add arguments to.
|
|
327
|
+
"""
|
|
328
|
+
parser.add_env_argument(
|
|
329
|
+
"--source-url",
|
|
330
|
+
env="DEBKIT_SOURCE_URL",
|
|
331
|
+
dest="source_url",
|
|
332
|
+
help="source repository 'URL DIST [COMPONENT ...]'; URL is a filesystem path or uses "
|
|
333
|
+
f"one of the schemes {', '.join(get_supported_schemes())} "
|
|
334
|
+
"(example: 'https://deb.debian.org/debian bookworm main')",
|
|
335
|
+
required=True,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
parser.add_env_argument(
|
|
339
|
+
"--allow-release-rollback",
|
|
340
|
+
env="DEBKIT_ALLOW_RELEASE_ROLLBACK",
|
|
341
|
+
dest="allow_release_rollback",
|
|
342
|
+
help="accept a source Release older than the target or past its Valid-Until",
|
|
343
|
+
action=BooleanOptionalAction,
|
|
344
|
+
default=False,
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
parser.add_argument(
|
|
348
|
+
"--verify-existing",
|
|
349
|
+
action="store_true",
|
|
350
|
+
dest="verify_existing",
|
|
351
|
+
help="verify existing packages before sync",
|
|
352
|
+
default=False,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
parser.add_argument(
|
|
356
|
+
"--indices-only",
|
|
357
|
+
action="store_true",
|
|
358
|
+
dest="indices_only",
|
|
359
|
+
help="force sync indices objects, skip deb packages",
|
|
360
|
+
default=False,
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class CheckStatus(NamedTuple):
|
|
365
|
+
"""The totals a check reports; the JSON output prints them under these names.
|
|
366
|
+
|
|
367
|
+
Attributes:
|
|
368
|
+
errors_total: Missing, orphan, and failed files.
|
|
369
|
+
errors_fixed_total: Files `--fix` deleted.
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
errors_total: int
|
|
373
|
+
errors_fixed_total: int
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
class ActionCheck(Action):
|
|
377
|
+
"""Check a repository against its own indices.
|
|
378
|
+
|
|
379
|
+
Attributes:
|
|
380
|
+
fix: Delete corrupt payloads and orphans if True.
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
def __init__(self, pars: Namespace, create_path: bool = False):
|
|
384
|
+
"""Initialize ActionCheck.
|
|
385
|
+
|
|
386
|
+
Args:
|
|
387
|
+
pars: Command line arguments from argparser.
|
|
388
|
+
create_path: Create path or bucket if True.
|
|
389
|
+
|
|
390
|
+
Raises:
|
|
391
|
+
ActionException: An `--architectures` token is not an architecture name; refused
|
|
392
|
+
before any storage is opened.
|
|
393
|
+
"""
|
|
394
|
+
archs, indices_exclude = _selection(pars)
|
|
395
|
+
super().__init__(pars)
|
|
396
|
+
self.fix: bool = pars.fix
|
|
397
|
+
self.target_repo = open_target_repo(
|
|
398
|
+
pars,
|
|
399
|
+
gpg=self.gpg,
|
|
400
|
+
create_path=create_path,
|
|
401
|
+
archs=archs,
|
|
402
|
+
indices_exclude=indices_exclude,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
def check(self) -> bool:
|
|
406
|
+
"""Check debian repo for consistency.
|
|
407
|
+
|
|
408
|
+
Returns:
|
|
409
|
+
True if repo is consistent.
|
|
410
|
+
"""
|
|
411
|
+
# `--fix` writes, so it is recorded as one transaction -> STORAGE.md#transactions
|
|
412
|
+
with (
|
|
413
|
+
maybe_transaction(self.target_repo.storage, self.history_retention)
|
|
414
|
+
if self.fix
|
|
415
|
+
else nullcontext()
|
|
416
|
+
):
|
|
417
|
+
try:
|
|
418
|
+
# `--fix` deletes what no loaded index claims, so it never skips one
|
|
419
|
+
# -> [VALIDATION.md](VALIDATION.md#index-loading)
|
|
420
|
+
self.target_repo.load(IndexLoad.WRITABLE if self.fix else IndexLoad.READ_ONLY)
|
|
421
|
+
except ReleaseNotFoundException as exc:
|
|
422
|
+
logger.error("Target repo is empty: %s", exc)
|
|
423
|
+
return False
|
|
424
|
+
status = self._check_target(self.target_repo)
|
|
425
|
+
|
|
426
|
+
if self.output == OutputType.json:
|
|
427
|
+
self._print_check_json(status)
|
|
428
|
+
else:
|
|
429
|
+
self._print_check_brief(status)
|
|
430
|
+
|
|
431
|
+
return status.errors_total == status.errors_fixed_total
|
|
432
|
+
|
|
433
|
+
def _check_target(self, target: RepoRW) -> CheckStatus:
|
|
434
|
+
"""Check the loaded target against its own indices, fixing it with `--fix`.
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
target: The loaded target repository.
|
|
438
|
+
|
|
439
|
+
Returns:
|
|
440
|
+
The error and fixed-error totals.
|
|
441
|
+
"""
|
|
442
|
+
report = target.check(fix=self.fix)
|
|
443
|
+
|
|
444
|
+
if report.missing:
|
|
445
|
+
logger.warning(
|
|
446
|
+
"Files is not in sync with indices... %s files missing.", len(report.missing)
|
|
447
|
+
)
|
|
448
|
+
logger.debug("Missing files: %s", report.missing)
|
|
449
|
+
|
|
450
|
+
if report.orphans:
|
|
451
|
+
logger.warning("Found %s orphan files in storage.", len(report.orphans))
|
|
452
|
+
logger.info("Orphan files: %s", report.orphans)
|
|
453
|
+
|
|
454
|
+
return CheckStatus(
|
|
455
|
+
errors_total=len(report.missing) + len(report.orphans) + report.failed,
|
|
456
|
+
errors_fixed_total=report.fixed,
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
def _print_check_brief(self, status: CheckStatus) -> None:
|
|
460
|
+
"""Print check brief output.
|
|
461
|
+
|
|
462
|
+
Args:
|
|
463
|
+
status: The error and fixed-error totals.
|
|
464
|
+
"""
|
|
465
|
+
print(f"Errors total: {status.errors_total} files")
|
|
466
|
+
print(f"Errors fixed: {status.errors_fixed_total} files")
|
|
467
|
+
|
|
468
|
+
def _print_check_json(self, status: CheckStatus) -> None:
|
|
469
|
+
"""Print check json output.
|
|
470
|
+
|
|
471
|
+
Args:
|
|
472
|
+
status: The error and fixed-error totals.
|
|
473
|
+
"""
|
|
474
|
+
json_dict: dict[str, dict[str, Any]] = {"status": status._asdict(), "metrics": {}}
|
|
475
|
+
json_dict["metrics"]["target_storage"] = self._target_metrics.dump()
|
|
476
|
+
|
|
477
|
+
print(dump_json(json_dict))
|
|
478
|
+
|
|
479
|
+
@staticmethod
|
|
480
|
+
def add_check_cli_args(parser: EnvArgumentParser) -> None:
|
|
481
|
+
"""Add argparser arguments for check.
|
|
482
|
+
|
|
483
|
+
The selection flags come from `add_selection_cli_args`, which sync registers
|
|
484
|
+
too.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
parser: The parser to add arguments to.
|
|
488
|
+
"""
|
|
489
|
+
parser.add_argument(
|
|
490
|
+
"--fix",
|
|
491
|
+
action="store_true",
|
|
492
|
+
dest="fix",
|
|
493
|
+
help="delete corrupted files from storage",
|
|
494
|
+
default=False,
|
|
495
|
+
)
|