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.
@@ -0,0 +1,468 @@
1
+ """Debian repo operations commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from humanize import naturalsize
10
+ from txstore import compare_digests, maybe_transaction
11
+
12
+ from debkit._escape import escape_control
13
+ from debkit.action import (
14
+ Action,
15
+ ActionException,
16
+ OutputType,
17
+ dump_json,
18
+ open_storage,
19
+ open_target_repo,
20
+ )
21
+ from debkit.argtypes import component_type, pkg_pattern_type
22
+ from debkit.repo.changes import Changes
23
+ from debkit.repo.component import IndexLoad
24
+ from debkit.repo.debfile import DebFile
25
+ from debkit.repo.hashes import ChecksumException
26
+ from debkit.repo.params import ARCH_ANY, SOURCE_ARCH, is_valid_arch
27
+ from debkit.repo.release import ReleaseNotFoundException
28
+
29
+ if TYPE_CHECKING:
30
+ from argparse import Namespace
31
+
32
+ from txstore import Storage
33
+
34
+ from debkit._options import EnvArgumentParser
35
+ from debkit.repo import RepoSnapshot
36
+ from debkit.repo.package import Package
37
+ from debkit.repo.repo_diff import RepoDiff
38
+
39
+
40
+ logger = logging.getLogger(__name__)
41
+ logger.addHandler(logging.NullHandler())
42
+
43
+ # the component an insert targets without `--component` → [CONFIG.md](CONFIG.md#insert)
44
+ DEFAULT_COMPONENT = "main"
45
+ DEFAULT_REPO_FIELDS = {"Architectures": "amd64 arm64 all", "Components": DEFAULT_COMPONENT}
46
+
47
+
48
+ class ActionPkg(Action):
49
+ """Actions with debian packages in repository."""
50
+
51
+ def __init__(self, pars: Namespace, create_path: bool = False):
52
+ """Initialize ActionPkg.
53
+
54
+ Args:
55
+ pars: Command line arguments from argparser.
56
+ create_path: Create path or bucket if True.
57
+
58
+ Raises:
59
+ ActionException: An `insert` names neither or both of `--changes-filename` and
60
+ `--deb-filename`, or a `.deb` file name without the suffix; refused before
61
+ any storage is opened, so no target path or bucket is created.
62
+ """
63
+ # one action serves five subcommands, each registering only its own flags
64
+ self.pkg_pattern: dict[str, re.Pattern[str]] | None = getattr(pars, "pkg_pattern", None)
65
+ self.changes_filename: str | None = getattr(pars, "changes_filename", None)
66
+ self.changes_sha256: str | None = getattr(pars, "changes_sha256", None)
67
+ self.deb_filename: str | None = getattr(pars, "deb_filename", None)
68
+ self.component: str = getattr(pars, "component", DEFAULT_COMPONENT)
69
+ is_insert = pars.command == "insert"
70
+ if is_insert:
71
+ self._check_insert_source()
72
+
73
+ super().__init__(pars)
74
+ self.target_repo = open_target_repo(pars, gpg=self.gpg, create_path=create_path)
75
+ self.incoming_storage: Storage | None = (
76
+ open_storage(pars, pars.incoming_url) if is_insert else None
77
+ )
78
+
79
+ def _check_insert_source(self) -> None:
80
+ """Check the `insert` upload flags -> [CONFIG.md](CONFIG.md#insert).
81
+
82
+ Raises:
83
+ ActionException: Neither or both of `--changes-filename` and `--deb-filename`.
84
+ ActionException: A `--deb-filename` that does not end with `.deb`.
85
+ """
86
+ if (self.changes_filename is None) == (self.deb_filename is None):
87
+ raise ActionException(
88
+ "insert needs exactly one of --changes-filename or --deb-filename"
89
+ )
90
+ if self.deb_filename is not None and not self.deb_filename.endswith(".deb"):
91
+ raise ActionException(f"Invalid .deb filename: {self.deb_filename}")
92
+
93
+ def dump(self) -> None:
94
+ """Dump repository to stdout."""
95
+ self.target_repo.load(IndexLoad.READ_ONLY)
96
+ logger.debug("%s", str(self._target_metrics))
97
+ if self.output == OutputType.brief:
98
+ self._print_brief_dump()
99
+ else:
100
+ print(dump_json(self.target_repo.dump()))
101
+
102
+ def _print_brief_dump(self) -> None:
103
+ """Print the target's Release fields and each arch's Release and package count."""
104
+ # Release fields are remote text, so a control character is escaped as a log line
105
+ # escapes it -> [CONFIG.md](CONFIG.md#output-flag)
106
+ print("Release:")
107
+ for key, value in self.target_repo.release.fields.items():
108
+ print(escape_control(f" {key}: {value}"))
109
+
110
+ print("Components:")
111
+ for component_name, component in self.target_repo.components.items():
112
+ print(f" {component_name}:")
113
+ for arch_name, packages in component.packages.items():
114
+ # a per-arch Release is optional, so an empty one is reported as absent
115
+ if packages.release.is_empty():
116
+ release = "<No release data>"
117
+ else:
118
+ release = escape_control(
119
+ ", ".join(f"{k}: {v}" for k, v in packages.release.fields.items())
120
+ )
121
+ print(f" {arch_name}: {release}")
122
+ print(f" {len(component.slot_packages(arch_name))} packages")
123
+
124
+ def stats(self) -> None:
125
+ """Print repository statistics to stdout."""
126
+ self.target_repo.load(IndexLoad.READ_ONLY)
127
+ stats = self.target_repo.stats()
128
+
129
+ if self.output == OutputType.brief:
130
+ self._print_brief_stats(stats)
131
+ else:
132
+ self._print_json_stats(stats)
133
+
134
+ def _print_brief_stats(self, stats: dict[str, dict[str, dict[str, int]]]) -> None:
135
+ """Print brief naturalized statistics to stdout.
136
+
137
+ Args:
138
+ stats: A dictionary containing the stats data.
139
+ """
140
+ print("Packages:")
141
+ for component, arch in stats.items():
142
+ print(f" {component}:")
143
+ for arch_name, arch_data in arch.items():
144
+ print(
145
+ f" {arch_name}: {naturalsize(arch_data['packages_bytes'])}, "
146
+ f"{arch_data['packages_total']} packages"
147
+ )
148
+ print("Indices read:")
149
+ print(
150
+ f" {naturalsize(self._target_metrics.read_bytes)}, "
151
+ f"{self._target_metrics.read_objects_total} files"
152
+ )
153
+
154
+ def _print_json_stats(self, stats: dict[str, dict[str, dict[str, int]]]) -> None:
155
+ """Print JSON statistics to stdout.
156
+
157
+ Args:
158
+ stats: A dictionary containing the stats data.
159
+ """
160
+ ret = {
161
+ "packages": stats,
162
+ "indices": {
163
+ "files_total": self._target_metrics.read_objects_total,
164
+ "files_bytes": self._target_metrics.read_bytes,
165
+ },
166
+ }
167
+
168
+ json_formatted_str = dump_json(ret)
169
+ print(json_formatted_str)
170
+
171
+ def list_packages(self) -> None:
172
+ """List packages in repository to stdout."""
173
+ self.target_repo.load(IndexLoad.READ_ONLY)
174
+
175
+ if self.output == OutputType.brief:
176
+ print("\n".join(str(package) for package in self.target_repo.get_packages()))
177
+ else:
178
+ json_formatted_str = dump_json(list(self.target_repo.get_packages()))
179
+ print(json_formatted_str)
180
+
181
+ def _load_target_or_setup(self) -> RepoSnapshot:
182
+ """Load the target, or set up a new one where it has no Release.
183
+
184
+ Called inside the command's transaction: a peer may commit before `history_lock`
185
+ is granted, so a target read before it would save over the peer's indices
186
+ -> [STORAGE.md](STORAGE.md#transactions).
187
+
188
+ Returns:
189
+ A snapshot of the target as loaded, for the command's diff.
190
+ """
191
+ try:
192
+ self.target_repo.load()
193
+ except ReleaseNotFoundException as exc:
194
+ # no repository - create new one; any other read failure must not reset an
195
+ # existing one
196
+ logger.debug("Target repository not found... (%s)", exc)
197
+
198
+ self.target_repo.setup(fields=DEFAULT_REPO_FIELDS)
199
+ return self.target_repo.snapshot()
200
+
201
+ def _load_changes(self, incoming_storage: Storage, changes_filename: str) -> Changes:
202
+ """Load and check a `.changes` upload, whose digests each listed `.deb` must match.
203
+
204
+ Args:
205
+ incoming_storage: The storage holding the upload.
206
+ changes_filename: The `.changes` file in it.
207
+
208
+ Raises:
209
+ ActionException: An architecture token is not an architecture name.
210
+ ActionException: An architecture token names the source one.
211
+
212
+ Returns:
213
+ The upload; `get_deb_files()` lists its `.deb` files.
214
+ """
215
+ changes = Changes(incoming_storage)
216
+ changes.load(changes_filename, digest_expected=self.changes_sha256)
217
+ for arch in changes.get_archs():
218
+ if not is_valid_arch(arch):
219
+ raise ActionException(f"Invalid architecture in {changes_filename}: {arch!r}")
220
+
221
+ # `Architecture` lists every arch the upload built, so a source plus binary
222
+ # build names `source` beside the binary one; reading the first token alone
223
+ # let the field order decide the upload
224
+ if changes.names_source_arch():
225
+ raise ActionException("Source packages are not supported yet")
226
+
227
+ return changes
228
+
229
+ def insert(self) -> None:
230
+ """Insert packages into repository.
231
+
232
+ The upload flags were checked when the action was built
233
+ -> `_check_insert_source`.
234
+
235
+ Raises:
236
+ ActionException: If the .changes architecture names the source one.
237
+ ActionException: If an architecture token is not an architecture name.
238
+ ActionException: If the package control field names the source architecture.
239
+ ActionException: If an `all` or arch-less package finds no binary architecture
240
+ in the target.
241
+ ChecksumException: If a transferred `.deb` does not match its `.changes` digest.
242
+ """
243
+ # `--incoming-url` is required for `insert`, so argparse already refused a missing one
244
+ assert self.incoming_storage is not None, "insert without --incoming-url"
245
+
246
+ # process deb files
247
+ changes: Changes | None = None
248
+ if self.changes_filename is not None:
249
+ changes = self._load_changes(self.incoming_storage, self.changes_filename)
250
+ filenames = changes.get_deb_files()
251
+ else:
252
+ # exactly one of the two filenames is set -> `_check_insert_source`
253
+ assert self.deb_filename is not None
254
+ filenames = [self.deb_filename]
255
+
256
+ with maybe_transaction(self.target_repo.storage, self.history_retention):
257
+ target_before = self._load_target_or_setup()
258
+ binary_archs = self.target_repo.binary_archs()
259
+ for filename in filenames:
260
+ debfile_obj = DebFile(self.incoming_storage, filename, comp=self.component)
261
+ package = debfile_obj.get_package()
262
+ archs = self._target_archs(filename, package, binary_archs)
263
+
264
+ pool_key = package.get_filename()
265
+ held = self.target_repo.held_digests(pool_key)
266
+ digests = self.target_repo.transfer_from(
267
+ self.incoming_storage, filename, path_dst=pool_key
268
+ )
269
+ # the pinned `.changes` lists each payload's digest, so a payload swapped in
270
+ # the incoming storage is refused before any other check can misname it;
271
+ # raising discards the staged transfer
272
+ # -> [CRYPTO.md](CRYPTO.md#verification-failures)
273
+ if (
274
+ changes is not None
275
+ and self.target_repo.params.verify_digests
276
+ and not changes.verify_digests(filename, digests)
277
+ ):
278
+ raise ChecksumException(
279
+ f"{filename} does not match its digest in {self.changes_filename}"
280
+ )
281
+ # other dists and arch indices may list this pool key with the digests of the
282
+ # bytes it holds, so replacing those bytes would break their records
283
+ # -> [VALIDATION.md](VALIDATION.md#filename-safety)
284
+ if held is not None and not compare_digests(held, digests):
285
+ raise ActionException(
286
+ f"{pool_key} already holds other bytes than {filename}; "
287
+ "upload them under another file name or version"
288
+ )
289
+ package.set_digests(digests)
290
+
291
+ for arch in archs:
292
+ self.target_repo.insert_pkg(self.component, arch, package)
293
+
294
+ ret_diff = self._save_if_changed(target_before)
295
+
296
+ self._print_pkg(ret_diff)
297
+
298
+ @staticmethod
299
+ def _target_archs(filename: str, package: Package, binary_archs: list[str]) -> list[str]:
300
+ """Get the repository architectures one uploaded package is inserted into.
301
+
302
+ Each package goes by its own control field, so neither the upload's field order
303
+ nor its file order picks the arches -> [VALIDATION.md](VALIDATION.md#architectures).
304
+
305
+ Args:
306
+ filename: The `.deb` file, for messages.
307
+ package: Its control data.
308
+ binary_archs: The target's binary architectures, for `all` or an arch-less package.
309
+
310
+ Raises:
311
+ ActionException: If the control `Architecture` is not an architecture name.
312
+ ActionException: If it names the source architecture.
313
+ ActionException: If an `all` or arch-less package finds no binary architecture.
314
+
315
+ Returns:
316
+ The architectures to insert into.
317
+ """
318
+ pkg_arch = package.get_arch()
319
+ if pkg_arch is not None and not is_valid_arch(pkg_arch):
320
+ raise ActionException(f"Invalid architecture in {filename}: {pkg_arch!r}")
321
+ # the control field is read straight out of the uploaded .deb, so it can name the
322
+ # source arch; the mirrored source index is read-only, so refuse before the
323
+ # transfer as the changes path already does
324
+ if pkg_arch == SOURCE_ARCH:
325
+ raise ActionException("Source packages are not supported yet")
326
+
327
+ archs = [pkg_arch] if pkg_arch is not None and pkg_arch != ARCH_ANY else binary_archs
328
+ if not archs:
329
+ raise ActionException(
330
+ f"Cannot insert {filename} (Architecture: {pkg_arch or 'none'}): "
331
+ "the target Release lists no binary architecture"
332
+ )
333
+ return archs
334
+
335
+ def _save_if_changed(self, target_before: RepoSnapshot) -> RepoDiff:
336
+ """Diff the target against its state before the command and save it if it changed.
337
+
338
+ Called inside the command's transaction, so the save is staged with the payloads.
339
+
340
+ Args:
341
+ target_before: The target as loaded before the command, as `snapshot` took it.
342
+
343
+ Returns:
344
+ The diff, for the command's output.
345
+ """
346
+ ret_diff = self.target_repo.diff(target_before)
347
+ if not ret_diff.is_empty():
348
+ self.target_repo.save()
349
+ return ret_diff
350
+
351
+ def _print_pkg(self, diff: RepoDiff) -> None:
352
+ """Print an insert or remove diff in the selected output format.
353
+
354
+ Args:
355
+ diff: Repository diff object.
356
+ """
357
+ if self.output == OutputType.brief:
358
+ self._print_pkg_brief(diff)
359
+ else:
360
+ self._print_pkg_json(diff)
361
+
362
+ def remove(self) -> None:
363
+ """Remove the packages matching the parsed ``--pkg-pattern`` from the repository.
364
+
365
+ Raises:
366
+ ActionException: If no package matched.
367
+ """
368
+ # `--pkg-pattern` is required for `remove`, so argparse already refused a missing one
369
+ assert self.pkg_pattern is not None, "remove without --pkg-pattern"
370
+
371
+ with maybe_transaction(self.target_repo.storage, self.history_retention):
372
+ # a peer may commit before `history_lock` is granted, so the target is read
373
+ # under it -> [STORAGE.md](STORAGE.md#transactions)
374
+ self.target_repo.load()
375
+ target_before = self.target_repo.snapshot()
376
+ if not self.target_repo.remove_pkg(self.pkg_pattern):
377
+ raise ActionException("No removable packages matched the pattern.")
378
+ ret_diff = self._save_if_changed(target_before)
379
+
380
+ self._print_pkg(ret_diff)
381
+
382
+ def _print_pkg_brief(self, diff: RepoDiff) -> None:
383
+ """Print package operation brief output.
384
+
385
+ Args:
386
+ diff: Repository diff object.
387
+ """
388
+ if diff.count_pkgs_to_copy() > 0:
389
+ print(f"Inserted {diff.count_pkgs_to_copy()} packages.")
390
+ if diff.count_pkgs_to_remove() > 0:
391
+ print(f"Removed {diff.count_pkgs_to_remove()} packages.")
392
+ if diff.count_pkgs_to_copy() > 0:
393
+ print(
394
+ f"{self._target_metrics.write_objects_total} objects "
395
+ f"({naturalsize(self._target_metrics.write_bytes)}) transferred."
396
+ )
397
+
398
+ def _print_pkg_json(self, diff: RepoDiff) -> None:
399
+ """Print package operation json output.
400
+
401
+ Args:
402
+ diff: Repository diff object.
403
+ """
404
+ json_dict: dict[str, Any] = {
405
+ "packages": diff.dump(),
406
+ "transfer": {"metrics": {}, "errors": {}},
407
+ }
408
+ json_dict["transfer"]["metrics"]["target_storage"] = self._target_metrics.dump()
409
+
410
+ print(dump_json(json_dict))
411
+
412
+ @staticmethod
413
+ def add_insert_cli_args(parser: EnvArgumentParser) -> None:
414
+ """Add arguments for insert.
415
+
416
+ Args:
417
+ parser: The argument parser to which the arguments should be added.
418
+ """
419
+ parser.add_env_argument(
420
+ "--changes-filename",
421
+ env="DEBKIT_CHANGES_FILENAME",
422
+ dest="changes_filename",
423
+ help=".changes filename of incoming packages",
424
+ )
425
+ parser.add_env_argument(
426
+ "--changes-sha256",
427
+ env="DEBKIT_CHANGES_SHA256",
428
+ dest="changes_sha256",
429
+ help="validate .changes file SHA256 checksum",
430
+ )
431
+ parser.add_env_argument(
432
+ "--deb-filename",
433
+ env="DEBKIT_DEB_FILENAME",
434
+ dest="deb_filename",
435
+ help=".deb filename of incoming package",
436
+ )
437
+ parser.add_env_argument(
438
+ "--incoming-url",
439
+ env="DEBKIT_INCOMING_URL",
440
+ dest="incoming_url",
441
+ help="url for incoming files",
442
+ required=True,
443
+ )
444
+ parser.add_env_argument(
445
+ "--component",
446
+ env="DEBKIT_COMPONENT",
447
+ dest="component",
448
+ help="component of Debian repo for incoming packages",
449
+ default=DEFAULT_COMPONENT,
450
+ type=component_type,
451
+ )
452
+
453
+ @staticmethod
454
+ def add_remove_cli_args(parser: EnvArgumentParser) -> None:
455
+ """Add arguments for delete.
456
+
457
+ Args:
458
+ parser: The argument parser to which the arguments should be added.
459
+ """
460
+ parser.add_env_argument(
461
+ "--pkg-pattern",
462
+ env="DEBKIT_PKG_PATTERN",
463
+ dest="pkg_pattern",
464
+ type=pkg_pattern_type,
465
+ help="JSON format of regexp patterns of package fields. "
466
+ 'Example: {"Filename":"filename_1.deb|filename_2.deb"}',
467
+ required=True,
468
+ )