charmlibs-apt 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.
@@ -0,0 +1,1804 @@
1
+ # Copyright 2021 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Abstractions for the system's Debian/Ubuntu package information and repositories.
16
+
17
+ This module contains abstractions and wrappers around Debian/Ubuntu-style repositories and
18
+ packages, in order to easily provide an idiomatic and Pythonic mechanism for adding packages and/or
19
+ repositories to systems for use in machine charms.
20
+
21
+ A sane default configuration is attainable through nothing more than instantiation of the
22
+ appropriate classes. :class:`DebianPackage` objects provide information about the architecture,
23
+ version, name, and status of a package.
24
+
25
+ :class:`DebianPackage` will try to look up a package either from ``dpkg -L`` or from ``apt-cache``
26
+ when provided with a string indicating the package name. If it cannot be located,
27
+ :class:`PackageNotFoundError` will be raised, as ``apt`` and ``dpkg`` otherwise return ``100`` for
28
+ all errors, and a meaningful error message if the package is not known is desirable.
29
+
30
+ To install packages with convenience methods::
31
+
32
+ try:
33
+ # Run `apt-get update`
34
+ apt.update()
35
+ apt.add_package("zsh")
36
+ apt.add_package(["vim", "htop", "wget"])
37
+ except PackageError as e:
38
+ logger.error("could not install package. Reason: %s", e.message)
39
+
40
+ The convenience methods don't raise :class:`PackageNotFoundError`. If any packages aren't found in
41
+ the cache, :func:`apt.add_package` raises :class:`PackageError` with a message 'Failed to install
42
+ packages: foo, bar'.
43
+
44
+ To find details of a specific package::
45
+
46
+ try:
47
+ vim = apt.DebianPackage.from_system("vim")
48
+
49
+ # To find from the apt cache only
50
+ # apt.DebianPackage.from_apt_cache("vim")
51
+
52
+ # To find from installed packages only
53
+ # apt.DebianPackage.from_installed_package("vim")
54
+
55
+ vim.ensure(PackageState.Latest)
56
+ logger.info("updated vim to version: %s", vim.fullversion)
57
+ except PackageNotFoundError:
58
+ logger.error("a specified package not found in package cache or on system")
59
+ except PackageError as e:
60
+ logger.error("could not install package. Reason: %s", e.message)
61
+
62
+ :class:`RepositoryMapping` will return a dict-like object containing enabled system repositories
63
+ and their properties (available groups, URI, GPG key). This class can add, disable, or
64
+ manipulate repositories. Items can be retrieved as :class:`DebianRepository` objects.
65
+
66
+ In order to add a new repository with explicit details for fields, a new :class:`DebianRepository`
67
+ can be added to :class:`RepositoryMapping`
68
+
69
+ :class:`RepositoryMapping` provides an abstraction around the existing repositories on the system,
70
+ and can be accessed and iterated over like any :class:`Mapping` object, to retrieve values by key,
71
+ iterate, or perform other operations.
72
+
73
+ Keys are constructed as ``{repo_type}-{}-{release}`` in order to uniquely identify a repository.
74
+
75
+ Repositories can be added with explicit values through a Python constructor.
76
+
77
+ Example::
78
+
79
+ repositories = apt.RepositoryMapping()
80
+ if "deb-example.com-focal" not in repositories:
81
+ repositories.add(
82
+ DebianRepository(
83
+ enabled=True,
84
+ repotype="deb",
85
+ uri="https://example.com",
86
+ release="focal",
87
+ groups=["universe"],
88
+ )
89
+ )
90
+
91
+ Alternatively, any valid ``sources.list`` line may be used to construct a new
92
+ :class:`DebianRepository`.
93
+
94
+ Example::
95
+
96
+ repositories = apt.RepositoryMapping()
97
+ if "deb-us.archive.ubuntu.com-xenial" not in repositories:
98
+ line = "deb http://us.archive.ubuntu.com/ubuntu xenial main restricted"
99
+ repo = DebianRepository.from_repo_line(line)
100
+ repositories.add(repo)
101
+ """
102
+
103
+ from __future__ import annotations
104
+
105
+ import fileinput
106
+ import glob
107
+ import logging
108
+ import os
109
+ import re
110
+ import subprocess
111
+ import typing
112
+ from collections.abc import Iterable, Iterator, Mapping
113
+ from enum import Enum
114
+ from subprocess import PIPE, CalledProcessError, check_output
115
+ from typing import Any, Literal
116
+ from urllib.parse import urlparse
117
+
118
+ import opentelemetry.trace
119
+
120
+ __version__ = '1.0.0'
121
+
122
+ logger = logging.getLogger(__name__)
123
+ tracer = opentelemetry.trace.get_tracer(__name__)
124
+
125
+
126
+ VALID_SOURCE_TYPES = ('deb', 'deb-src')
127
+ OPTIONS_MATCHER = re.compile(r'\[.*?\]')
128
+ _GPG_KEY_DIR = '/etc/apt/trusted.gpg.d/'
129
+
130
+
131
+ class Error(Exception):
132
+ """Base class of most errors raised by this library."""
133
+
134
+ def __repr__(self):
135
+ """Represent the Error."""
136
+ return f'<{type(self).__module__}.{type(self).__name__} {self.args}>'
137
+
138
+ @property
139
+ def name(self):
140
+ """Return a string representation of the model plus class."""
141
+ return f'<{type(self).__module__}.{type(self).__name__}>'
142
+
143
+ @property
144
+ def message(self):
145
+ """Return the message passed as an argument."""
146
+ return self.args[0]
147
+
148
+
149
+ class PackageError(Error):
150
+ """Raised when there's an error installing or removing a package.
151
+
152
+ Additionally, :func:`apt.add_package` raises ``PackageError`` if any packages aren't found in
153
+ the cache.
154
+ """
155
+
156
+
157
+ class PackageNotFoundError(Error):
158
+ """Raised by :class:`DebianPackage` methods if a requested package is not found."""
159
+
160
+
161
+ class PackageState(Enum):
162
+ """A class to represent possible package states."""
163
+
164
+ Present = 'present'
165
+ Absent = 'absent'
166
+ Latest = 'latest'
167
+ Available = 'available'
168
+
169
+
170
+ class DebianPackage:
171
+ """Represents a traditional Debian package and its utility functions.
172
+
173
+ :class:`DebianPackage` wraps information and functionality around a known package, whether
174
+ installed or available. The version, epoch, name, and architecture can be easily queried and
175
+ compared against other :class:`DebianPackage` objects to determine the latest version or to
176
+ install a specific version.
177
+
178
+ The representation of this object as a string mimics the output from ``dpkg`` for familiarity.
179
+
180
+ Installation and removal of packages is handled through the ``state`` property or ``ensure``
181
+ method, with the following options:
182
+
183
+ :attr:`apt.PackageState.Absent`
184
+ :attr:`apt.PackageState.Available`
185
+ :attr:`apt.PackageState.Present`
186
+ :attr:`apt.PackageState.Latest`
187
+
188
+ When :class:`DebianPackage` is initialised, the state of a given :class:`DebianPackage` object
189
+ will be set to ``Available``, ``Present``, or ``Latest``, with ``Absent`` implemented as a
190
+ convenience for removal (though it operates essentially the same as ``Available``).
191
+ """
192
+
193
+ def __init__(
194
+ self, name: str, version: str, epoch: str, arch: str, state: PackageState
195
+ ) -> None:
196
+ self._name = name
197
+ self._arch = arch
198
+ self._state = state
199
+ self._version = Version(version, epoch)
200
+
201
+ def __eq__(self, other: object) -> bool:
202
+ """Equality for comparison.
203
+
204
+ Args:
205
+ other: a :class:`DebianPackage` object for comparison
206
+
207
+ Returns:
208
+ A Boolean reflecting equality
209
+ """
210
+ return isinstance(other, self.__class__) and (
211
+ self._name,
212
+ self._version.number,
213
+ ) == (other._name, other._version.number)
214
+
215
+ def __hash__(self):
216
+ """Return a hash of this package."""
217
+ return hash((self._name, self._version.number))
218
+
219
+ def __repr__(self):
220
+ """Represent the package."""
221
+ return f'<{self.__module__}.{type(self).__name__}: {self.__dict__}>'
222
+
223
+ def __str__(self):
224
+ """Return a human-readable representation of the package."""
225
+ return (
226
+ f'<{type(self).__name__}: {self._name}-{self._version}.{self._arch} -- {self._state}>'
227
+ )
228
+
229
+ @staticmethod
230
+ def _apt(
231
+ command: str,
232
+ package_names: str | list[str],
233
+ optargs: list[str] | None = None,
234
+ ) -> None:
235
+ """Wrap package management commands for Debian/Ubuntu systems.
236
+
237
+ Args:
238
+ command: the command given to ``apt-get``
239
+ package_names: a package name or list of package names to operate on
240
+ optargs: an (optional) list of additional arguments
241
+
242
+ Raises:
243
+ PackageError: if an error is encountered
244
+ """
245
+ optargs = optargs if optargs is not None else []
246
+ if isinstance(package_names, str):
247
+ package_names = [package_names]
248
+ cmd = ['apt-get', '-y', *optargs, command, *package_names]
249
+ try:
250
+ env = os.environ.copy()
251
+ env['DEBIAN_FRONTEND'] = 'noninteractive'
252
+ with tracer.start_as_current_span(cmd[0]) as span:
253
+ span.set_attribute('argv', cmd)
254
+ subprocess.run(cmd, capture_output=True, check=True, text=True, env=env)
255
+ except CalledProcessError as e:
256
+ raise PackageError(
257
+ f'Could not {command} package(s) {package_names}: {e.stderr}'
258
+ ) from None
259
+
260
+ def _add(self) -> None:
261
+ """Add a package to the system."""
262
+ self._apt(
263
+ 'install',
264
+ f'{self.name}={self.version}',
265
+ optargs=['--option=Dpkg::Options::=--force-confold'],
266
+ )
267
+
268
+ def _remove(self) -> None:
269
+ """Remove a package from the system. Implementation-specific."""
270
+ return self._apt('remove', f'{self.name}={self.version}')
271
+
272
+ @property
273
+ def name(self) -> str:
274
+ """Returns the name of the package."""
275
+ return self._name
276
+
277
+ def ensure(self, state: PackageState):
278
+ """Ensure that a package is in a given state.
279
+
280
+ Args:
281
+ state: a :class:`PackageState` to reconcile the package to
282
+
283
+ Raises:
284
+ PackageError: from the underlying call to ``apt``
285
+ """
286
+ if self._state is not state:
287
+ if state not in (PackageState.Present, PackageState.Latest):
288
+ self._remove()
289
+ else:
290
+ self._add()
291
+ self._state = state
292
+
293
+ @property
294
+ def present(self) -> bool:
295
+ """Return whether or not a package is present."""
296
+ return self._state in (PackageState.Present, PackageState.Latest)
297
+
298
+ @property
299
+ def latest(self) -> bool:
300
+ """Return whether the package is the most recent version."""
301
+ return self._state is PackageState.Latest
302
+
303
+ @property
304
+ def state(self) -> PackageState:
305
+ """Return the current package state."""
306
+ return self._state
307
+
308
+ @state.setter
309
+ def state(self, state: PackageState) -> None:
310
+ """Set the package state to a given value.
311
+
312
+ Args:
313
+ state: a :class:`PackageState` to reconcile the package to
314
+
315
+ Raises:
316
+ PackageError: from the underlying call to ``apt``
317
+ """
318
+ if state in (PackageState.Latest, PackageState.Present):
319
+ self._add()
320
+ else:
321
+ self._remove()
322
+ self._state = state
323
+
324
+ @property
325
+ def version(self) -> Version:
326
+ """Return the version for a package."""
327
+ return self._version
328
+
329
+ @property
330
+ def epoch(self) -> str:
331
+ """Return the epoch for a package. May be unset."""
332
+ return self._version.epoch
333
+
334
+ @property
335
+ def arch(self) -> str:
336
+ """Return the architecture for a package."""
337
+ return self._arch
338
+
339
+ @property
340
+ def fullversion(self) -> str:
341
+ """Return the name+epoch for a package."""
342
+ return f'{self._version}.{self._arch}'
343
+
344
+ @staticmethod
345
+ def _get_epoch_from_version(version: str) -> tuple[str, str]:
346
+ """Pull the epoch, if any, out of a version string."""
347
+ epoch_matcher = re.compile(r'^((?P<epoch>\d+):)?(?P<version>.*)')
348
+ result = epoch_matcher.search(version)
349
+ assert result is not None
350
+ matches = result.groupdict()
351
+ return matches.get('epoch', ''), matches['version']
352
+
353
+ @classmethod
354
+ def from_system(
355
+ cls, package: str, version: str | None = '', arch: str | None = ''
356
+ ) -> DebianPackage:
357
+ """Locate a package, either on the system or known to apt, and serialises the information.
358
+
359
+ Args:
360
+ package: a string representing the package
361
+ version: an optional string if a specific version is requested
362
+ arch: an optional architecture, defaulting to ``dpkg --print-architecture``.
363
+ If an architecture is not specified, this will be used for selection.
364
+
365
+ """
366
+ try:
367
+ return DebianPackage.from_installed_package(package, version, arch)
368
+ except PackageNotFoundError:
369
+ logger.debug(
370
+ "package '%s' is not currently installed or has the wrong architecture.", package
371
+ )
372
+
373
+ # Ok, try `apt-cache ...`
374
+ try:
375
+ return DebianPackage.from_apt_cache(package, version, arch)
376
+ except (PackageNotFoundError, PackageError):
377
+ # If we get here, it's not known to the systems.
378
+ # This seems unnecessary, but virtually all `apt` commands have a return code of `100`,
379
+ # and providing meaningful error messages without this is ugly.
380
+ arch_str = f'.{arch}' if arch else ''
381
+ raise PackageNotFoundError(
382
+ f"Package '{package}{arch_str}' "
383
+ 'could not be found on the system or in the apt cache!'
384
+ ) from None
385
+
386
+ @classmethod
387
+ def from_installed_package(
388
+ cls, package: str, version: str | None = '', arch: str | None = ''
389
+ ) -> DebianPackage:
390
+ """Check whether the package is already installed and return an instance.
391
+
392
+ Args:
393
+ package: a string representing the package
394
+ version: an optional string if a specific version is requested
395
+ arch: an optional architecture, defaulting to ``dpkg --print-architecture``.
396
+ If an architecture is not specified, this will be used for selection.
397
+ """
398
+ system_arch = check_output(
399
+ ['dpkg', '--print-architecture'], universal_newlines=True
400
+ ).strip()
401
+ arch = arch if arch else system_arch
402
+
403
+ # Regexps are a really terrible way to do this. Thanks dpkg
404
+ output = ''
405
+ try:
406
+ output = check_output(['dpkg', '-l', package], stderr=PIPE, universal_newlines=True)
407
+ except CalledProcessError:
408
+ raise PackageNotFoundError(f'Package is not installed: {package}') from None
409
+
410
+ # Pop off the output from `dpkg -l' because there's no flag to
411
+ # omit it`
412
+ lines = str(output).splitlines()[5:]
413
+
414
+ dpkg_matcher = re.compile(
415
+ r"""
416
+ ^(?P<package_status>\w+?)\s+
417
+ (?P<package_name>.*?)(?P<throwaway_arch>:\w+?)?\s+
418
+ (?P<version>.*?)\s+
419
+ (?P<arch>\w+?)\s+
420
+ (?P<description>.*)
421
+ """,
422
+ re.VERBOSE,
423
+ )
424
+
425
+ for line in lines:
426
+ result = dpkg_matcher.search(line)
427
+ if result is None:
428
+ logger.warning('dpkg matcher could not parse line: %s', line)
429
+ continue
430
+ matches = result.groupdict()
431
+ package_status = matches['package_status']
432
+
433
+ if not package_status.endswith('i'):
434
+ logger.debug(
435
+ "package '%s' in dpkg output but not installed, status: '%s'",
436
+ package,
437
+ package_status,
438
+ )
439
+ break
440
+
441
+ epoch, split_version = DebianPackage._get_epoch_from_version(matches['version'])
442
+ pkg = DebianPackage(
443
+ name=matches['package_name'],
444
+ version=split_version,
445
+ epoch=epoch,
446
+ arch=matches['arch'],
447
+ state=PackageState.Present,
448
+ )
449
+ if (pkg.arch == 'all' or pkg.arch == arch) and (
450
+ version == '' or str(pkg.version) == version
451
+ ):
452
+ return pkg
453
+
454
+ # If we didn't find it, fail through
455
+ raise PackageNotFoundError(f'Package {package}.{arch} is not installed!')
456
+
457
+ @classmethod
458
+ def from_apt_cache(
459
+ cls, package: str, version: str | None = '', arch: str | None = ''
460
+ ) -> DebianPackage:
461
+ """Check whether the package is already installed and return an instance.
462
+
463
+ Args:
464
+ package: a string representing the package
465
+ version: an optional string if a specific version is requested
466
+ arch: an optional architecture, defaulting to ``dpkg --print-architecture``.
467
+ If an architecture is not specified, this will be used for selection.
468
+ """
469
+ cmd = ['dpkg', '--print-architecture']
470
+ with tracer.start_as_current_span(cmd[0]) as span:
471
+ span.set_attribute('argv', cmd)
472
+ system_arch = check_output(cmd, universal_newlines=True).strip()
473
+ arch = arch if arch else system_arch
474
+
475
+ # Regexps are a really terrible way to do this. Thanks dpkg
476
+ keys = ('Package', 'Architecture', 'Version')
477
+
478
+ cmd = ['apt-cache', 'show', package]
479
+ try:
480
+ with tracer.start_as_current_span(cmd[0]) as span:
481
+ span.set_attribute('argv', cmd)
482
+ output = check_output(cmd, stderr=PIPE, universal_newlines=True)
483
+ except CalledProcessError as e:
484
+ raise PackageError(f'Could not list packages in apt-cache: {e.stderr}') from None
485
+
486
+ pkg_groups = output.strip().split('\n\n')
487
+ keys = ('Package', 'Architecture', 'Version')
488
+
489
+ for pkg_raw in pkg_groups:
490
+ lines = str(pkg_raw).splitlines()
491
+ vals: dict[str, str] = {}
492
+ for line in lines:
493
+ if line.startswith(keys):
494
+ items = line.split(':', 1)
495
+ vals[items[0]] = items[1].strip()
496
+ else:
497
+ continue
498
+
499
+ epoch, split_version = DebianPackage._get_epoch_from_version(vals['Version'])
500
+ pkg = DebianPackage(
501
+ name=vals['Package'],
502
+ version=split_version,
503
+ epoch=epoch,
504
+ arch=vals['Architecture'],
505
+ state=PackageState.Available,
506
+ )
507
+
508
+ if (pkg.arch == 'all' or pkg.arch == arch) and (
509
+ version == '' or str(pkg.version) == version
510
+ ):
511
+ return pkg
512
+
513
+ # If we didn't find it, fail through
514
+ raise PackageNotFoundError(f'Package {package}.{arch} is not in the apt cache!')
515
+
516
+
517
+ class Version:
518
+ """An abstraction around package versions.
519
+
520
+ This seems like it should be strictly unnecessary, except that ``apt_pkg`` is not usable inside
521
+ a ``venv``, and wedging version comparisons into :class:`DebianPackage` would over complicate
522
+ it.
523
+
524
+ This class implements the algorithm found here:
525
+ https://www.debian.org/doc/debian-policy/ch-controlfields.html#version
526
+ """
527
+
528
+ def __init__(self, version: str, epoch: str):
529
+ self._version = version
530
+ self._epoch = epoch or ''
531
+
532
+ def __repr__(self):
533
+ """Represent the package."""
534
+ return f'<{self.__module__}.{type(self).__name__}: {self.__dict__}>'
535
+
536
+ def __str__(self):
537
+ """Return human-readable representation of the package."""
538
+ epoch = f'{self._epoch}:' if self._epoch else ''
539
+ return f'{epoch}{self._version}'
540
+
541
+ @property
542
+ def epoch(self):
543
+ """Return the epoch for a package. May be empty."""
544
+ return self._epoch
545
+
546
+ @property
547
+ def number(self) -> str:
548
+ """Return the version number for a package."""
549
+ return self._version
550
+
551
+ def _get_parts(self, version: str) -> tuple[str, str]:
552
+ """Separate the version into component upstream and Debian pieces."""
553
+ try:
554
+ version.rindex('-')
555
+ except ValueError:
556
+ # No hyphens means no Debian version
557
+ return version, '0'
558
+
559
+ upstream, debian = version.rsplit('-', 1)
560
+ return upstream, debian
561
+
562
+ def _listify(self, revision: str) -> list[str | int]:
563
+ """Split a revision string into a list.
564
+
565
+ This list is comprised of alternating between strings and numbers,
566
+ padded on either end to always be ``"str, int, str, int..."`` and
567
+ always be of even length. This allows us to trivially implement the
568
+ comparison algorithm described.
569
+ """
570
+ result: list[str | int] = []
571
+ while revision:
572
+ rev_1, remains = self._get_alphas(revision)
573
+ rev_2, remains = self._get_digits(remains)
574
+ result.extend([rev_1, rev_2])
575
+ revision = remains
576
+ return result
577
+
578
+ def _get_alphas(self, revision: str) -> tuple[str, str]:
579
+ """Return a tuple of the first non-digit characters of a revision."""
580
+ # get the index of the first digit
581
+ for i, char in enumerate(revision):
582
+ if char.isdigit():
583
+ if i == 0:
584
+ return '', revision
585
+ return revision[0:i], revision[i:]
586
+ # string is entirely alphas
587
+ return revision, ''
588
+
589
+ def _get_digits(self, revision: str) -> tuple[int, str]:
590
+ """Return a tuple of the first integer characters of a revision."""
591
+ # If the string is empty, return (0,'')
592
+ if not revision:
593
+ return 0, ''
594
+ # get the index of the first non-digit
595
+ for i, char in enumerate(revision):
596
+ if not char.isdigit():
597
+ if i == 0:
598
+ return 0, revision
599
+ return int(revision[0:i]), revision[i:]
600
+ # string is entirely digits
601
+ return int(revision), ''
602
+
603
+ def _dstringcmp(self, a: str, b: str) -> Literal[-1, 0, 1]:
604
+ """Debian package version string section lexical sort algorithm.
605
+
606
+ The lexical comparison is a comparison of ASCII values modified so
607
+ that all the letters sort earlier than all the non-letters and so that
608
+ a tilde sorts before anything, even the end of a part.
609
+ """
610
+ if a == b:
611
+ return 0
612
+ try:
613
+ for i, char in enumerate(a):
614
+ if char == b[i]:
615
+ continue
616
+ # "a tilde sorts before anything, even the end of a part"
617
+ # (emptyness)
618
+ if char == '~':
619
+ return -1
620
+ if b[i] == '~':
621
+ return 1
622
+ # "all the letters sort earlier than all the non-letters"
623
+ if char.isalpha() and not b[i].isalpha():
624
+ return -1
625
+ if not char.isalpha() and b[i].isalpha():
626
+ return 1
627
+ # otherwise lexical sort
628
+ if ord(char) > ord(b[i]):
629
+ return 1
630
+ if ord(char) < ord(b[i]):
631
+ return -1
632
+ except IndexError:
633
+ # a is longer than b but otherwise equal, greater unless there are tildes
634
+ # Note: type checker thinks "char" is possibly unbound as it's a loop variable
635
+ # but it won't be since the IndexError can only occur inside the loop
636
+ # -- I'd like to refactor away this `try ... except` anyway
637
+ if char == '~': # pyright: ignore[reportPossiblyUnboundVariable]
638
+ return -1
639
+ return 1
640
+ # if we get here, a is shorter than b but otherwise equal, so check for tildes...
641
+ if b[len(a)] == '~':
642
+ return 1
643
+ return -1
644
+
645
+ def _compare_revision_strings(self, first: str, second: str) -> Literal[-1, 0, 1]:
646
+ """Compare two debian revision strings."""
647
+ if first == second:
648
+ return 0
649
+
650
+ # listify pads results so that we will always be comparing ints to ints
651
+ # and strings to strings (at least until we fall off the end of a list)
652
+ first_list = self._listify(first)
653
+ second_list = self._listify(second)
654
+ if first_list == second_list:
655
+ return 0
656
+ try:
657
+ for i, item in enumerate(first_list):
658
+ # explicitly raise IndexError if we've fallen off the edge of list2
659
+ if i >= len(second_list):
660
+ raise IndexError
661
+ other = second_list[i]
662
+ # if the items are equal, next
663
+ if item == other:
664
+ continue
665
+ # numeric comparison
666
+ if isinstance(item, int):
667
+ assert isinstance(other, int)
668
+ if item > other:
669
+ return 1
670
+ if item < other:
671
+ return -1
672
+ else:
673
+ # string comparison
674
+ assert isinstance(other, str)
675
+ return self._dstringcmp(item, other)
676
+ except IndexError:
677
+ # rev1 is longer than rev2 but otherwise equal, hence greater
678
+ # ...except for goddamn tildes
679
+ # bug??: we return 1 in both cases
680
+ # also: first_list[len(second_list)] should be a string
681
+ # why are we indexing to 0 twice?
682
+ if first_list[len(second_list)][0][0] == '~': # type: ignore
683
+ return 1
684
+ return 1
685
+ # rev1 is shorter than rev2 but otherwise equal, hence lesser
686
+ # ...except for goddamn tildes
687
+ # bug??: we return -1 in both cases
688
+ # also: first_list[len(second_list)] should be a string, why are we indexing to 0 twice?
689
+ if second_list[len(first_list)][0][0] == '~': # type: ignore
690
+ return -1
691
+ return -1
692
+
693
+ def _compare_version(self, other: Version) -> Literal[-1, 0, 1]:
694
+ if (self.number, self.epoch) == (other.number, other.epoch):
695
+ return 0
696
+
697
+ if self.epoch < other.epoch:
698
+ return -1
699
+ if self.epoch > other.epoch:
700
+ return 1
701
+
702
+ # If none of these are true, follow the algorithm
703
+ upstream_version, debian_version = self._get_parts(self.number)
704
+ other_upstream_version, other_debian_version = self._get_parts(other.number)
705
+
706
+ upstream_cmp = self._compare_revision_strings(upstream_version, other_upstream_version)
707
+ if upstream_cmp != 0:
708
+ return upstream_cmp
709
+
710
+ debian_cmp = self._compare_revision_strings(debian_version, other_debian_version)
711
+ if debian_cmp != 0:
712
+ return debian_cmp
713
+
714
+ return 0
715
+
716
+ def __lt__(self, other: Version) -> bool:
717
+ """Less than magic method implementation."""
718
+ return self._compare_version(other) < 0
719
+
720
+ def __eq__(self, other: object) -> bool:
721
+ """Equality magic method implementation."""
722
+ if not isinstance(other, Version):
723
+ return False
724
+ return self._compare_version(other) == 0
725
+
726
+ def __gt__(self, other: Version) -> bool:
727
+ """Greater than magic method implementation."""
728
+ return self._compare_version(other) > 0
729
+
730
+ def __le__(self, other: Version) -> bool:
731
+ """Less than or equal to magic method implementation."""
732
+ return self.__eq__(other) or self.__lt__(other)
733
+
734
+ def __ge__(self, other: Version) -> bool:
735
+ """Greater than or equal to magic method implementation."""
736
+ return self.__gt__(other) or self.__eq__(other)
737
+
738
+ def __ne__(self, other: object) -> bool:
739
+ """Not equal to magic method implementation."""
740
+ return not self.__eq__(other)
741
+
742
+
743
+ @typing.overload
744
+ def add_package(
745
+ package_names: str,
746
+ version: str | None = '',
747
+ arch: str | None = '',
748
+ update_cache: bool = False,
749
+ ) -> DebianPackage: ...
750
+ @typing.overload
751
+ def add_package(
752
+ package_names: list[str],
753
+ version: str | None = '',
754
+ arch: str | None = '',
755
+ update_cache: bool = False,
756
+ ) -> DebianPackage | list[DebianPackage]: ...
757
+ def add_package(
758
+ package_names: str | list[str],
759
+ version: str | None = '',
760
+ arch: str | None = '',
761
+ update_cache: bool = False,
762
+ ) -> DebianPackage | list[DebianPackage]:
763
+ """Add a package or list of packages to the system.
764
+
765
+ Args:
766
+ package_names: single package name, or list of package names
767
+ name: the name(s) of the package(s)
768
+ version: an (optional) version as a string. Defaults to the latest known
769
+ arch: an optional architecture for the package
770
+ update_cache: whether or not to run `apt-get update` prior to operating
771
+
772
+ Raises:
773
+ TypeError: if no package name is given, or explicit version is set for multiple packages
774
+ PackageError: if packages fail to install, including if any packages aren't found in the
775
+ cache
776
+ """
777
+ cache_refreshed = False
778
+ if update_cache:
779
+ update()
780
+ cache_refreshed = True
781
+
782
+ package_names = [package_names] if isinstance(package_names, str) else package_names
783
+ if not package_names:
784
+ raise TypeError('Expected at least one package name to add, received zero!')
785
+
786
+ if len(package_names) != 1 and version:
787
+ raise TypeError(
788
+ 'Explicit version should not be set if more than one package is being added!'
789
+ )
790
+
791
+ succeeded: list[DebianPackage] = []
792
+ retry: list[str] = []
793
+ failed: list[str] = []
794
+
795
+ for p in package_names:
796
+ pkg, _ = _add(p, version, arch)
797
+ if isinstance(pkg, DebianPackage):
798
+ succeeded.append(pkg)
799
+ elif cache_refreshed:
800
+ logger.warning("failed to locate and install/update '%s'", pkg)
801
+ failed.append(p)
802
+ else:
803
+ logger.warning("failed to locate and install/update '%s', will retry later", pkg)
804
+ retry.append(p)
805
+
806
+ if retry:
807
+ logger.info('updating the apt-cache and retrying installation of failed packages.')
808
+ update()
809
+
810
+ for p in retry:
811
+ pkg, _ = _add(p, version, arch)
812
+ if isinstance(pkg, DebianPackage):
813
+ succeeded.append(pkg)
814
+ else:
815
+ failed.append(p)
816
+
817
+ if failed:
818
+ raise PackageError(f'Failed to install packages: {", ".join(failed)}')
819
+
820
+ return succeeded[0] if len(succeeded) == 1 else succeeded
821
+
822
+
823
+ def _add(
824
+ name: str,
825
+ version: str | None = '',
826
+ arch: str | None = '',
827
+ ) -> tuple[DebianPackage, Literal[True]] | tuple[str, Literal[False]]:
828
+ """Add a package to the system.
829
+
830
+ Args:
831
+ name: the name(s) of the package(s)
832
+ version: an (Optional) version as a string. Defaults to the latest known
833
+ arch: an optional architecture for the package
834
+
835
+ Returns: a tuple of :class:`DebianPackage` if found, or a ``str`` if it is not, and
836
+ a Boolean indicating success
837
+ """
838
+ try:
839
+ pkg = DebianPackage.from_system(name, version, arch)
840
+ pkg.ensure(state=PackageState.Present)
841
+ return pkg, True
842
+ except PackageNotFoundError:
843
+ return name, False
844
+
845
+
846
+ @typing.overload
847
+ def remove_package(
848
+ package_names: str,
849
+ ) -> DebianPackage: ...
850
+ @typing.overload
851
+ def remove_package(
852
+ package_names: list[str],
853
+ ) -> DebianPackage | list[DebianPackage]: ...
854
+ def remove_package(
855
+ package_names: str | list[str],
856
+ ) -> DebianPackage | list[DebianPackage]:
857
+ """Remove package(s) from the system.
858
+
859
+ Args:
860
+ package_names: the name of a package
861
+
862
+ Raises:
863
+ TypeError: if no packages are provided
864
+ """
865
+ packages: list[DebianPackage] = []
866
+
867
+ package_names = [package_names] if isinstance(package_names, str) else package_names
868
+ if not package_names:
869
+ raise TypeError('Expected at least one package name to add, received zero!')
870
+
871
+ for p in package_names:
872
+ try:
873
+ pkg = DebianPackage.from_installed_package(p)
874
+ pkg.ensure(state=PackageState.Absent)
875
+ packages.append(pkg)
876
+ except PackageNotFoundError: # noqa: PERF203
877
+ logger.info("package '%s' was requested for removal, but it was not installed.", p)
878
+
879
+ # the list of packages will be empty when no package is removed
880
+ logger.debug("packages: '%s'", packages)
881
+ return packages[0] if len(packages) == 1 else packages
882
+
883
+
884
+ def update() -> None:
885
+ """Update the apt cache via ``apt-get update``."""
886
+ cmd = ['apt-get', 'update', '--error-on=any']
887
+ try:
888
+ with tracer.start_as_current_span(cmd[0]) as span:
889
+ span.set_attribute('argv', cmd)
890
+ subprocess.run(cmd, capture_output=True, check=True)
891
+ except CalledProcessError as e:
892
+ logger.error(
893
+ '%s:\nstdout:\n%s\nstderr:\n%s',
894
+ ' '.join(cmd),
895
+ e.stdout.decode(),
896
+ e.stderr.decode(),
897
+ )
898
+ raise
899
+
900
+
901
+ def import_key(key: str) -> str:
902
+ """Import an ASCII Armor key.
903
+
904
+ A Radix64 format key ID is also supported for backwards
905
+ compatibility. In this case Ubuntu key server will be
906
+ queried for a key via HTTPS by its key ID. This method
907
+ is less preferable because HTTPS proxy servers may
908
+ require traffic decryption which is equivalent to a
909
+ man-in-the-middle attack (a proxy server impersonates
910
+ key server TLS certificates and has to be explicitly
911
+ trusted by the system).
912
+
913
+ Args:
914
+ key: A GPG key in ASCII armor format, including BEGIN
915
+ and END markers or a key ID.
916
+
917
+ Returns:
918
+ The GPG key filename written.
919
+
920
+ Raises:
921
+ GPGKeyError: if the key could not be imported
922
+ """
923
+ key = key.strip()
924
+ if '-' in key or '\n' in key:
925
+ # Send everything not obviously a keyid to GPG to import, as
926
+ # we trust its validation better than our own. eg. handling
927
+ # comments before the key.
928
+ logger.debug('PGP key found (looks like ASCII Armor format)')
929
+ if (
930
+ '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key
931
+ and '-----END PGP PUBLIC KEY BLOCK-----' in key
932
+ ):
933
+ logger.debug('Writing provided PGP key in the binary format')
934
+ key_bytes = key.encode('utf-8')
935
+ key_name = DebianRepository._get_keyid_by_gpg_key(key_bytes)
936
+ key_gpg = DebianRepository._dearmor_gpg_key(key_bytes)
937
+ gpg_key_filename = os.path.join(_GPG_KEY_DIR, f'{key_name}.gpg')
938
+ DebianRepository._write_apt_gpg_keyfile(
939
+ key_name=gpg_key_filename, key_material=key_gpg
940
+ )
941
+ return gpg_key_filename
942
+ else:
943
+ raise GPGKeyError('ASCII armor markers missing from GPG key')
944
+ else:
945
+ logger.warning(
946
+ 'PGP key found (looks like Radix64 format). '
947
+ 'SECURELY importing PGP key from key server; '
948
+ 'full key not provided.'
949
+ )
950
+ # as of bionic add-apt-repository uses curl with an HTTPS key server URL
951
+ # to retrieve GPG keys. `apt-key adv` command is deprecated as is
952
+ # apt-key in general as noted in its manpage. See lp:1433761 for more
953
+ # history. Instead, /etc/apt/trusted.gpg.d is used directly to drop
954
+ # gpg
955
+ key_asc = DebianRepository._get_key_by_keyid(key)
956
+ # write the key in GPG format so that apt-key list shows it
957
+ key_gpg = DebianRepository._dearmor_gpg_key(key_asc.encode('utf-8'))
958
+ gpg_key_filename = os.path.join(_GPG_KEY_DIR, f'{key}.gpg')
959
+ DebianRepository._write_apt_gpg_keyfile(key_name=gpg_key_filename, key_material=key_gpg)
960
+ return gpg_key_filename
961
+
962
+
963
+ class InvalidSourceError(Error):
964
+ """Exception for invalid source entries."""
965
+
966
+
967
+ class GPGKeyError(Error):
968
+ """Exception for GPG keys."""
969
+
970
+
971
+ class DebianRepository:
972
+ """An abstraction to represent a repository."""
973
+
974
+ _deb822_stanza: _Deb822Stanza | None = None
975
+ """set by :class:`Deb822Stanza` after creating a :class:`DebianRepository`"""
976
+
977
+ def __init__(
978
+ self,
979
+ enabled: bool,
980
+ repotype: str,
981
+ uri: str,
982
+ release: str,
983
+ groups: list[str],
984
+ filename: str = '',
985
+ gpg_key_filename: str = '',
986
+ options: dict[str, str] | None = None,
987
+ ):
988
+ self._enabled = enabled
989
+ self._repotype = repotype
990
+ self._uri = uri
991
+ self._release = release
992
+ self._groups = groups
993
+ self._filename = filename
994
+ self._gpg_key_filename = gpg_key_filename
995
+ self._options = options
996
+
997
+ @property
998
+ def enabled(self):
999
+ """Return whether or not the repository is enabled."""
1000
+ return self._enabled
1001
+
1002
+ @property
1003
+ def repotype(self):
1004
+ """Return whether it is binary or source."""
1005
+ return self._repotype
1006
+
1007
+ @property
1008
+ def uri(self):
1009
+ """Return the URI."""
1010
+ return self._uri
1011
+
1012
+ @property
1013
+ def release(self):
1014
+ """Return which Debian/Ubuntu releases it is valid for."""
1015
+ return self._release
1016
+
1017
+ @property
1018
+ def groups(self):
1019
+ """Return the enabled package groups."""
1020
+ return self._groups
1021
+
1022
+ @property
1023
+ def filename(self):
1024
+ """Returns the filename for a repository."""
1025
+ return self._filename
1026
+
1027
+ @filename.setter
1028
+ def filename(self, fname: str) -> None:
1029
+ """Set the filename used when a repo is written back to disk.
1030
+
1031
+ Args:
1032
+ fname: a filename to write the repository information to.
1033
+ """
1034
+ if not fname.endswith(('.list', '.sources')):
1035
+ raise InvalidSourceError('apt source filenames should end in .list or .sources!')
1036
+ self._filename = fname
1037
+
1038
+ @property
1039
+ def gpg_key(self):
1040
+ """Returns the path to the GPG key for this repository."""
1041
+ if not self._gpg_key_filename and self._deb822_stanza is not None:
1042
+ self._gpg_key_filename = self._deb822_stanza.get_gpg_key_filename()
1043
+ return self._gpg_key_filename
1044
+
1045
+ @property
1046
+ def options(self):
1047
+ """Returns any additional repo options which are set."""
1048
+ return self._options
1049
+
1050
+ def make_options_string(self, include_signed_by: bool = True) -> str:
1051
+ """Generate the complete one-line-style options string for a repository.
1052
+
1053
+ Combining ``gpg_key``, if set (and ``include_signed_by`` is ``True``), with any other
1054
+ provided options to form the options section of a one-line-style definition.
1055
+ """
1056
+ options = self._options if self._options else {}
1057
+ if include_signed_by and self.gpg_key:
1058
+ options['signed-by'] = self.gpg_key
1059
+ if not options:
1060
+ return ''
1061
+ pairs = (f'{k}={v}' for k, v in sorted(options.items()))
1062
+ return '[{}] '.format(' '.join(pairs))
1063
+
1064
+ @staticmethod
1065
+ def prefix_from_uri(uri: str) -> str:
1066
+ """Get a repo list prefix from the URI, depending on whether a path is set."""
1067
+ uridetails = urlparse(uri)
1068
+ path = (
1069
+ uridetails.path.lstrip('/').replace('/', '-') if uridetails.path else uridetails.netloc
1070
+ )
1071
+ return f'/etc/apt/sources.list.d/{path}'
1072
+
1073
+ @staticmethod
1074
+ def from_repo_line(repo_line: str, write_file: bool | None = True) -> DebianRepository:
1075
+ """Instantiate a new :class:`DebianRepository` from a ``sources.list`` entry line.
1076
+
1077
+ Args:
1078
+ repo_line: a string representing a repository entry
1079
+ write_file: Boolean to enable writing the new repo to disk. True by default.
1080
+ Expect it to result in an add-apt-repository call under the hood, like
1081
+ ``add-apt-repository --no-update --sourceslist="$repo_line"``
1082
+ """
1083
+ repo = RepositoryMapping._parse(
1084
+ repo_line,
1085
+ filename='UserInput', # temp filename
1086
+ )
1087
+ repo.filename = repo._make_filename()
1088
+ if write_file:
1089
+ _add_repository(repo)
1090
+ return repo
1091
+
1092
+ def _make_filename(self) -> str:
1093
+ """Construct a filename from uri and release.
1094
+
1095
+ For internal use when a filename isn't set.
1096
+ Should match the filename written to by add-apt-repository.
1097
+ """
1098
+ return '{}-{}.list'.format(
1099
+ DebianRepository.prefix_from_uri(self.uri),
1100
+ self.release.replace('/', '-'),
1101
+ )
1102
+
1103
+ def disable(self) -> None:
1104
+ """Remove this repository by disabling it in the source file.
1105
+
1106
+ WARNING: This method does NOT alter the :attr:`DebianRepository.enabled` flag.
1107
+
1108
+ WARNING: disable is currently not implemented for repositories defined
1109
+ by a ``deb822`` stanza. Raises a :class:`NotImplementedError` in this case.
1110
+ """
1111
+ if self._deb822_stanza is not None:
1112
+ raise NotImplementedError(
1113
+ 'Disabling a repository defined by a deb822 format source is not implemented.'
1114
+ ' Please raise an issue if you require this feature.'
1115
+ )
1116
+ searcher = f'{self.repotype} {self.make_options_string()}{self.uri} {self.release}'
1117
+ with tracer.start_as_current_span('disable source') as span:
1118
+ span.set_attribute('filename', self._filename)
1119
+ with fileinput.input(self._filename, inplace=True) as lines:
1120
+ for line in lines:
1121
+ if re.match(rf'^{re.escape(searcher)}\s', line):
1122
+ print(f'# {line}', end='')
1123
+ else:
1124
+ print(line, end='')
1125
+
1126
+ def import_key(self, key: str) -> None:
1127
+ """Import an ASCII Armor key.
1128
+
1129
+ A Radix64 format key ID is also supported for backwards
1130
+ compatibility. In this case Ubuntu key server will be
1131
+ queried for a key via HTTPS by its key ID. This method
1132
+ is less preferable because HTTPS proxy servers may
1133
+ require traffic decryption which is equivalent to a
1134
+ man-in-the-middle attack (a proxy server impersonates
1135
+ key server TLS certificates and has to be explicitly
1136
+ trusted by the system).
1137
+
1138
+ Args:
1139
+ key: A GPG key in ASCII armor format,
1140
+ including BEGIN and END markers or a key ID.
1141
+
1142
+ Raises:
1143
+ GPGKeyError: if the key could not be imported
1144
+ """
1145
+ self._gpg_key_filename = import_key(key)
1146
+
1147
+ @staticmethod
1148
+ def _get_keyid_by_gpg_key(key_material: bytes) -> str:
1149
+ """Get a GPG key fingerprint by GPG key material.
1150
+
1151
+ Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded
1152
+ or binary GPG key material. Can be used, for example, to generate file
1153
+ names for keys passed via charm options.
1154
+ """
1155
+ # Use the same gpg command for both Xenial and Bionic
1156
+ cmd = ['gpg', '--with-colons', '--with-fingerprint']
1157
+ with tracer.start_as_current_span(cmd[0]) as span:
1158
+ span.set_attribute('argv', cmd)
1159
+ ps = subprocess.run(cmd, capture_output=True, input=key_material)
1160
+ out, err = ps.stdout.decode(), ps.stderr.decode()
1161
+ if 'gpg: no valid OpenPGP data found.' in err:
1162
+ raise GPGKeyError('Invalid GPG key material provided')
1163
+ # from gnupg2 docs: fpr :: Fingerprint (fingerprint is in field 10) # codespell:ignore fpr
1164
+ result = re.search(r'^fpr:{9}([0-9A-F]{40}):$', out, re.MULTILINE) # codespell:ignore fpr
1165
+ assert result is not None
1166
+ return result.group(1)
1167
+
1168
+ @staticmethod
1169
+ def _get_key_by_keyid(keyid: str) -> str:
1170
+ """Get a key via HTTPS from the Ubuntu key server.
1171
+
1172
+ Different key ID formats are supported by SKS key servers (the longer ones
1173
+ are more secure, see "dead beef attack" and https://evil32.com/). Since
1174
+ HTTPS is used, if SSLBump-like HTTPS proxies are in place, they will
1175
+ impersonate key server.ubuntu.com and generate a certificate with
1176
+ key server.ubuntu.com in the CN field or in SubjAltName fields of a
1177
+ certificate. If such proxy behavior is expected it is necessary to add the
1178
+ CA certificate chain containing the intermediate CA of the SSLBump proxy to
1179
+ every machine that this code runs on via ca-certs cloud-init directive (via
1180
+ cloudinit-userdata model-config) or via other means (such as through a
1181
+ custom charm option). Also note that DNS resolution for the hostname in a
1182
+ URL is done at a proxy server - not at the client side.
1183
+ 8-digit (32 bit) key ID
1184
+ https://keyserver.ubuntu.com/pks/lookup?search=0x4652B4E6
1185
+ 16-digit (64 bit) key ID
1186
+ https://keyserver.ubuntu.com/pks/lookup?search=0x6E85A86E4652B4E6
1187
+ 40-digit key ID:
1188
+ https://keyserver.ubuntu.com/pks/lookup?search=0x35F77D63B5CEC106C577ED856E85A86E4652B4E6
1189
+
1190
+ Args:
1191
+ keyid: An 8, 16 or 40 hex digit key ID to find a key for
1192
+
1193
+ Returns:
1194
+ A string containing key material for the specified GPG key ID
1195
+
1196
+
1197
+ Raises:
1198
+ CalledProcessError
1199
+ """
1200
+ # options=mr - machine-readable output (disables html wrappers)
1201
+ keyserver_url = (
1202
+ 'https://keyserver.ubuntu.com/pks/lookup?op=get&options=mr&exact=on&search=0x{}'
1203
+ )
1204
+ curl_cmd = ['curl', keyserver_url.format(keyid)]
1205
+ with tracer.start_as_current_span(curl_cmd[0]) as span:
1206
+ span.set_attribute('argv', curl_cmd)
1207
+ # use proxy server settings in order to retrieve the key
1208
+ return check_output(curl_cmd).decode()
1209
+
1210
+ @staticmethod
1211
+ def _dearmor_gpg_key(key_asc: bytes) -> bytes:
1212
+ """Convert a GPG key in the ASCII armor format to the binary format.
1213
+
1214
+ Args:
1215
+ key_asc: A GPG key in ASCII armor format.
1216
+
1217
+ Returns:
1218
+ A GPG key in binary format as a string
1219
+
1220
+ Raises:
1221
+ GPGKeyError
1222
+ """
1223
+ cmd = ['gpg', '--dearmor']
1224
+ with tracer.start_as_current_span(cmd[0]) as span:
1225
+ span.set_attribute('argv', cmd)
1226
+ ps = subprocess.run(cmd, capture_output=True, input=key_asc)
1227
+ out, err = ps.stdout, ps.stderr.decode()
1228
+ if 'gpg: no valid OpenPGP data found.' in err:
1229
+ raise GPGKeyError(
1230
+ 'Invalid GPG key material. Check your network setup'
1231
+ ' (MTU, routing, DNS) and/or proxy server settings'
1232
+ ' as well as destination key server status.'
1233
+ )
1234
+ else:
1235
+ return out
1236
+
1237
+ @staticmethod
1238
+ def _write_apt_gpg_keyfile(key_name: str, key_material: bytes) -> None:
1239
+ """Write GPG key material into a file at a provided path.
1240
+
1241
+ Args:
1242
+ key_name: A key name to use for a key file (could be a fingerprint)
1243
+ key_material: A GPG key material (binary)
1244
+ """
1245
+ with open(key_name, 'wb') as keyf:
1246
+ keyf.write(key_material)
1247
+
1248
+
1249
+ def _repo_to_identifier(repo: DebianRepository) -> str:
1250
+ """Return str identifier derived from repotype, uri, and release.
1251
+
1252
+ Private method used to produce the identifiers used by :class:`RepositoryMapping`.
1253
+ """
1254
+ return f'{repo.repotype}-{repo.uri}-{repo.release}'
1255
+
1256
+
1257
+ def _repo_to_line(repo: DebianRepository, include_signed_by: bool = True) -> str:
1258
+ """Return the one-per-line format repository definition."""
1259
+ return '{prefix}{repotype} {options}{uri} {release} {groups}'.format(
1260
+ prefix='' if repo.enabled else '#',
1261
+ repotype=repo.repotype,
1262
+ options=repo.make_options_string(include_signed_by=include_signed_by),
1263
+ uri=repo.uri,
1264
+ release=repo.release,
1265
+ groups=' '.join(repo.groups),
1266
+ )
1267
+
1268
+
1269
+ class RepositoryMapping(Mapping[str, DebianRepository]):
1270
+ """An representation of known repositories.
1271
+
1272
+ Instantiation of :class:`RepositoryMapping` will iterate through the
1273
+ filesystem, parse out repository files in `/etc/apt/...`, and create
1274
+ :class:`DebianRepository` objects in this list.
1275
+
1276
+ Typical usage::
1277
+
1278
+ repositories = apt.RepositoryMapping()
1279
+ repositories.add(
1280
+ DebianRepository(
1281
+ enabled=True,
1282
+ repotype="deb",
1283
+ uri="https://example.com",
1284
+ release="focal",
1285
+ groups=["universe"],
1286
+ )
1287
+ )
1288
+ """
1289
+
1290
+ _apt_dir = '/etc/apt'
1291
+ _sources_subdir = 'sources.list.d'
1292
+ _default_list_name = 'sources.list'
1293
+ _default_sources_name = 'ubuntu.sources'
1294
+ _last_errors: tuple[Error, ...] = ()
1295
+
1296
+ def __init__(self):
1297
+ self._repository_map: dict[str, DebianRepository] = {}
1298
+ self.default_file = os.path.join(self._apt_dir, self._default_list_name)
1299
+ # ^ public attribute for backwards compatibility only
1300
+ sources_dir = os.path.join(self._apt_dir, self._sources_subdir)
1301
+ default_sources = os.path.join(sources_dir, self._default_sources_name)
1302
+
1303
+ # read sources.list if it exists
1304
+ # ignore InvalidSourceError if ubuntu.sources also exists
1305
+ # -- in this case, sources.list just contains a comment
1306
+ if os.path.isfile(self.default_file):
1307
+ try:
1308
+ self.load(self.default_file)
1309
+ except InvalidSourceError:
1310
+ if not os.path.isfile(default_sources):
1311
+ raise
1312
+
1313
+ with tracer.start_as_current_span('load sources'):
1314
+ # read sources.list.d
1315
+ for file in glob.iglob(os.path.join(sources_dir, '*.list')):
1316
+ self.load(file)
1317
+ for file in glob.iglob(os.path.join(sources_dir, '*.sources')):
1318
+ self.load_deb822(file)
1319
+
1320
+ def __contains__(self, key: Any) -> bool:
1321
+ """Magic method for checking presence of repo in mapping.
1322
+
1323
+ Checks against the string names used to identify repositories.
1324
+ """
1325
+ return key in self._repository_map
1326
+
1327
+ def __len__(self) -> int:
1328
+ """Return number of repositories in map."""
1329
+ return len(self._repository_map)
1330
+
1331
+ def __iter__(self) -> Iterator[DebianRepository]: # pyright: ignore[reportIncompatibleMethodOverride]
1332
+ """Return iterator for :class:`RepositoryMapping`.
1333
+
1334
+ Iterates over the :class:`DebianRepository` values rather than the string names.
1335
+
1336
+ Note: this breaks the expectations of the :class:`Mapping` abstract base class
1337
+ for example when it provides methods like keys and items
1338
+ """
1339
+ return iter(self._repository_map.values())
1340
+
1341
+ def __getitem__(self, repository_uri: str) -> DebianRepository:
1342
+ """Return a given :class:`DebianRepository`."""
1343
+ return self._repository_map[repository_uri]
1344
+
1345
+ def __setitem__(self, repository_uri: str, repository: DebianRepository) -> None:
1346
+ """Add a :class:`DebianRepository` to the cache."""
1347
+ self._repository_map[repository_uri] = repository
1348
+
1349
+ def load_deb822(self, filename: str) -> None:
1350
+ """Load a ``deb822`` format repository source file into the cache.
1351
+
1352
+ In contrast to one-line-style, the ``deb822`` format specifies a repository
1353
+ using a multi-line stanza. Stanzas are separated by white space,
1354
+ and each definition consists of lines that are either key: value pairs,
1355
+ or continuations of the previous value.
1356
+
1357
+ Read more about the ``deb822`` format here:
1358
+ https://manpages.ubuntu.com/manpages/noble/en/man5/sources.list.5.html
1359
+ For instance, Ubuntu 24.04 (noble) lists its sources using ``deb822`` style in:
1360
+ ``/etc/apt/sources.list.d/ubuntu.sources``
1361
+ """
1362
+ with open(filename) as f:
1363
+ repos, errors = self._parse_deb822_lines(f, filename=filename)
1364
+ for repo in repos:
1365
+ self._repository_map[_repo_to_identifier(repo)] = repo
1366
+ if errors:
1367
+ self._last_errors = tuple(errors)
1368
+ logger.debug(
1369
+ 'the following %d error(s) were encountered when reading deb822 sources:\n%s',
1370
+ len(errors),
1371
+ '\n'.join(str(e) for e in errors),
1372
+ )
1373
+ if repos:
1374
+ logger.info('parsed %d apt package repositories from %s', len(repos), filename)
1375
+ else:
1376
+ raise InvalidSourceError(f"all repository lines in '{filename}' were invalid!")
1377
+
1378
+ @classmethod
1379
+ def _parse_deb822_lines(
1380
+ cls,
1381
+ lines: Iterable[str],
1382
+ filename: str = '',
1383
+ ) -> tuple[list[DebianRepository], list[InvalidSourceError]]:
1384
+ """Parse lines from a ``deb822`` file into a list of repos and a list of errors.
1385
+
1386
+ The semantics of ``_parse_deb822_lines`` slightly different to :meth:`_parse`:
1387
+ ``_parse`` reads a commented out line as an entry that is not enabled
1388
+ ``_parse_deb822_lines`` strips out comments entirely when parsing a file into stanzas,
1389
+ instead only reading the 'Enabled' key to determine if an entry is enabled
1390
+ """
1391
+ repos: list[DebianRepository] = []
1392
+ errors: list[InvalidSourceError] = []
1393
+ for numbered_lines in _iter_deb822_stanzas(lines):
1394
+ try:
1395
+ stanza = _Deb822Stanza(numbered_lines=numbered_lines, filename=filename)
1396
+ except InvalidSourceError as e: # noqa: PERF203
1397
+ errors.append(e)
1398
+ else:
1399
+ repos.extend(stanza.repos)
1400
+ return repos, errors
1401
+
1402
+ def load(self, filename: str):
1403
+ """Load a one-line-style format repository source file into the cache.
1404
+
1405
+ Args:
1406
+ filename: the path to the repository file
1407
+ """
1408
+ parsed: list[int] = []
1409
+ skipped: list[int] = []
1410
+ with open(filename) as f:
1411
+ for n, line in enumerate(f, start=1): # 1 indexed line numbers
1412
+ try:
1413
+ repo = self._parse(line, filename)
1414
+ except InvalidSourceError: # noqa: PERF203
1415
+ skipped.append(n)
1416
+ else:
1417
+ repo_identifier = _repo_to_identifier(repo)
1418
+ self._repository_map[repo_identifier] = repo
1419
+ parsed.append(n)
1420
+ logger.debug("parsed repo: '%s'", repo_identifier)
1421
+
1422
+ if skipped:
1423
+ skip_list = ', '.join(str(s) for s in skipped)
1424
+ logger.debug("skipped the following lines in file '%s': %s", filename, skip_list)
1425
+
1426
+ if parsed:
1427
+ logger.info('parsed %d apt package repositories from %s', len(parsed), filename)
1428
+ else:
1429
+ raise InvalidSourceError(f"all repository lines in '{filename}' were invalid!")
1430
+
1431
+ @staticmethod
1432
+ def _parse(line: str, filename: str) -> DebianRepository:
1433
+ """Parse a line in a sources.list file.
1434
+
1435
+ Args:
1436
+ line: a single line from `load` to parse
1437
+ filename: the filename being read
1438
+
1439
+ Raises:
1440
+ InvalidSourceError: if the source type is unknown
1441
+ """
1442
+ enabled = True
1443
+ repotype = uri = release = gpg_key = ''
1444
+ options = {}
1445
+ groups = []
1446
+
1447
+ line = line.strip()
1448
+ if line.startswith('#'):
1449
+ enabled = False
1450
+ line = line[1:]
1451
+
1452
+ # Check for "#" in the line and treat a part after it as a comment then strip it off.
1453
+ i = line.find('#')
1454
+ if i > 0:
1455
+ line = line[:i]
1456
+
1457
+ # Split a source into substrings to initialise a new repo.
1458
+ source = line.strip()
1459
+ if source:
1460
+ # Match any repo options, and get a dict representation.
1461
+ for v in re.findall(OPTIONS_MATCHER, source):
1462
+ opts = dict(o.split('=') for o in v.strip('[]').split())
1463
+ # Extract the 'signed-by' option for the gpg_key
1464
+ gpg_key = opts.pop('signed-by', '')
1465
+ options = opts
1466
+
1467
+ # Remove any options from the source string and split the string into chunks
1468
+ source = re.sub(OPTIONS_MATCHER, '', source)
1469
+ chunks = source.split()
1470
+
1471
+ # Check we've got a valid list of chunks
1472
+ if len(chunks) < 3 or chunks[0] not in VALID_SOURCE_TYPES:
1473
+ raise InvalidSourceError('An invalid sources line was found in %s!', filename)
1474
+
1475
+ repotype = chunks[0]
1476
+ uri = chunks[1]
1477
+ release = chunks[2]
1478
+ groups = chunks[3:]
1479
+
1480
+ return DebianRepository(
1481
+ enabled, repotype, uri, release, groups, filename, gpg_key, options
1482
+ )
1483
+ else:
1484
+ raise InvalidSourceError('An invalid sources line was found in %s!', filename)
1485
+
1486
+ def add( # noqa: D417 # undocumented-param: default_filename intentionally undocumented
1487
+ self, repo: DebianRepository, default_filename: bool | None = False
1488
+ ) -> None:
1489
+ """Add a new repository to the system using add-apt-repository.
1490
+
1491
+ Args:
1492
+ repo: a :class:`DebianRepository` object
1493
+ if :attr:`DebianRepository.enabled` is false, will return without adding the repo
1494
+ Raises:
1495
+ CalledProcessError: if there's an error running apt-add-repository
1496
+
1497
+ WARNING: Does not associate the repository with a signing key.
1498
+ Use ``import_key`` to add a signing key globally.
1499
+
1500
+ WARNING: if :attr:`DebianRepository.enabled` is false, will return without adding the repo
1501
+
1502
+ WARNING: Don't forget to call :meth:`update` before installing any packages!
1503
+ Or call :meth:`add_package` with ``update_cache=True``.
1504
+
1505
+ WARNING: the ``default_filename`` keyword argument is provided for backwards compatibility
1506
+ only. It is not used, and was not used in the previous revision of this library.
1507
+ """
1508
+ if not repo.enabled:
1509
+ logger.warning(
1510
+ (
1511
+ 'Returning from RepositoryMapping.add(repo=%s) without adding the repo'
1512
+ ' because repo.enabled is %s'
1513
+ ),
1514
+ repo,
1515
+ repo.enabled,
1516
+ )
1517
+ return
1518
+ _add_repository(repo)
1519
+ self._repository_map[_repo_to_identifier(repo)] = repo
1520
+
1521
+ def disable(self, repo: DebianRepository) -> None:
1522
+ """Remove a repository by disabling it in the source file.
1523
+
1524
+ WARNING: disable is currently not implemented for repositories defined
1525
+ by a ``deb822`` stanza, and will raise a :class:`NotImplementedError` if called on one.
1526
+
1527
+ WARNING: This method does NOT alter the :attr:`DebianRepository.enabled` flag.
1528
+ """
1529
+ repo.disable()
1530
+ self._repository_map[_repo_to_identifier(repo)] = repo
1531
+ # ^ adding to map on disable seems like a bug, but this is the previous behaviour
1532
+
1533
+
1534
+ def _add_repository(
1535
+ repo: DebianRepository,
1536
+ remove: bool = False,
1537
+ update_cache: bool = False,
1538
+ ) -> None:
1539
+ line = _repo_to_line(repo, include_signed_by=False)
1540
+ key_file = repo.gpg_key
1541
+ if key_file and not remove and not os.path.exists(key_file):
1542
+ msg = (
1543
+ "Adding repository '%s' with add-apt-repository."
1544
+ " Key file '%s' does not exist."
1545
+ ' Ensure it is imported correctly to use this repository.'
1546
+ )
1547
+ logger.warning(msg, line, key_file)
1548
+ cmd = [
1549
+ 'add-apt-repository',
1550
+ '--yes',
1551
+ '--sourceslist=' + line,
1552
+ ]
1553
+ if remove:
1554
+ cmd.append('--remove')
1555
+ if not update_cache:
1556
+ cmd.append('--no-update')
1557
+ logger.info('%s', cmd)
1558
+ try:
1559
+ with tracer.start_as_current_span(cmd[0]) as span:
1560
+ span.set_attribute('argv', cmd)
1561
+ subprocess.run(cmd, check=True, capture_output=True)
1562
+ except CalledProcessError as e:
1563
+ logger.error(
1564
+ 'subprocess.run(%s):\nstdout:\n%s\nstderr:\n%s',
1565
+ cmd,
1566
+ e.stdout.decode(),
1567
+ e.stderr.decode(),
1568
+ )
1569
+ raise
1570
+
1571
+
1572
+ class _Deb822Stanza:
1573
+ """Representation of a stanza from a ``deb822`` source file.
1574
+
1575
+ May define multiple :class:`DebianRepository` objects.
1576
+ """
1577
+
1578
+ def __init__(self, numbered_lines: list[tuple[int, str]], filename: str = ''):
1579
+ self._filename = filename
1580
+ self._numbered_lines = numbered_lines
1581
+ if not numbered_lines:
1582
+ self._repos = ()
1583
+ self._gpg_key_filename = ''
1584
+ self._gpg_key_from_stanza = None
1585
+ return
1586
+ options, line_numbers = _deb822_stanza_to_options(numbered_lines)
1587
+ repos, gpg_key_info = _deb822_options_to_repos(
1588
+ options, line_numbers=line_numbers, filename=filename
1589
+ )
1590
+ for repo in repos:
1591
+ repo._deb822_stanza = self
1592
+ self._repos = repos
1593
+ self._gpg_key_filename, self._gpg_key_from_stanza = gpg_key_info
1594
+
1595
+ @property
1596
+ def repos(self) -> tuple[DebianRepository, ...]:
1597
+ """The repositories defined by this ``deb822`` stanza."""
1598
+ return self._repos
1599
+
1600
+ def get_gpg_key_filename(self) -> str:
1601
+ """Return the path to the GPG key for this stanza.
1602
+
1603
+ Import the key first, if the key itself was provided in the stanza.
1604
+ Return an empty string if no filename or key was provided.
1605
+ """
1606
+ if self._gpg_key_filename:
1607
+ return self._gpg_key_filename
1608
+ if self._gpg_key_from_stanza is None:
1609
+ return ''
1610
+ # a gpg key was provided in the stanza
1611
+ # and we haven't already imported it
1612
+ self._gpg_key_filename = import_key(self._gpg_key_from_stanza)
1613
+ return self._gpg_key_filename
1614
+
1615
+
1616
+ class MissingRequiredKeyError(InvalidSourceError):
1617
+ """Missing a required value in a source file."""
1618
+
1619
+ def __init__(self, message: str = '', *, file: str, line: int | None, key: str) -> None:
1620
+ super().__init__(message, file, line, key)
1621
+ self.file = file
1622
+ self.line = line
1623
+ self.key = key
1624
+
1625
+
1626
+ class BadValueError(InvalidSourceError):
1627
+ """Bad value for an entry in a source file."""
1628
+
1629
+ def __init__(
1630
+ self,
1631
+ message: str = '',
1632
+ *,
1633
+ file: str,
1634
+ line: int | None,
1635
+ key: str,
1636
+ value: str,
1637
+ ) -> None:
1638
+ super().__init__(message, file, line, key, value)
1639
+ self.file = file
1640
+ self.line = line
1641
+ self.key = key
1642
+ self.value = value
1643
+
1644
+
1645
+ def _iter_deb822_stanzas(lines: Iterable[str]) -> Iterator[list[tuple[int, str]]]:
1646
+ """Given lines from a ``deb822`` format file, yield a stanza of lines.
1647
+
1648
+ Args:
1649
+ lines: an iterable of lines from a ``deb822`` sources file
1650
+
1651
+ Yields:
1652
+ lists of numbered lines (a tuple of line number and line) that make up
1653
+ a ``deb822`` stanza, with comments stripped out (but accounted for in line numbering)
1654
+ """
1655
+ current_stanza: list[tuple[int, str]] = []
1656
+ for n, line in enumerate(lines, start=1): # 1 indexed line numbers
1657
+ if not line.strip(): # blank lines separate stanzas
1658
+ if current_stanza:
1659
+ yield current_stanza
1660
+ current_stanza = []
1661
+ continue
1662
+ content, _delim, _comment = line.partition('#')
1663
+ if content.strip(): # skip (potentially indented) comment line
1664
+ current_stanza.append((n, content.rstrip())) # preserve indent
1665
+ if current_stanza:
1666
+ yield current_stanza
1667
+
1668
+
1669
+ def _deb822_stanza_to_options(
1670
+ lines: Iterable[tuple[int, str]],
1671
+ ) -> tuple[dict[str, str], dict[str, int]]:
1672
+ """Turn numbered lines into a dict of options and a dict of line numbers.
1673
+
1674
+ Args:
1675
+ lines: an iterable of numbered lines (a tuple of line number and line)
1676
+
1677
+ Returns:
1678
+ A dictionary of option names to (potentially multiline) values, and
1679
+ a dictionary of option names to starting line number.
1680
+ """
1681
+ parts: dict[str, list[str]] = {}
1682
+ line_numbers: dict[str, int] = {}
1683
+ current = None
1684
+ for n, line in lines:
1685
+ assert '#' not in line # comments should be stripped out
1686
+ if line.startswith(' '): # continuation of previous key's value
1687
+ assert current is not None
1688
+ parts[current].append(line.rstrip()) # preserve indent
1689
+ continue
1690
+ raw_key, _, raw_value = line.partition(':')
1691
+ current = raw_key.strip()
1692
+ parts[current] = [raw_value.strip()]
1693
+ line_numbers[current] = n
1694
+ options = {k: '\n'.join(v) for k, v in parts.items()}
1695
+ return options, line_numbers
1696
+
1697
+
1698
+ def _deb822_options_to_repos(
1699
+ options: dict[str, str], line_numbers: Mapping[str, int] = {}, filename: str = ''
1700
+ ) -> tuple[tuple[DebianRepository, ...], tuple[str, str | None]]:
1701
+ """Return a collections of :class:`DebianRepository` objects defined by this ``deb822`` stanza.
1702
+
1703
+ Args:
1704
+ options: a dictionary of ``deb822`` field names to string options
1705
+ line_numbers: a dictionary of field names to line numbers (for error messages)
1706
+ filename: the file the options were read from (for repository object and errors)
1707
+
1708
+ Returns:
1709
+ A tuple of :class:`DebianRepository`s, and
1710
+ a tuple of the gpg key filename and optional in-stanza provided key itself.
1711
+
1712
+ Raises:
1713
+ InvalidSourceError: if any options are malformed or required options are missing
1714
+ """
1715
+ # Enabled
1716
+ enabled_field = options.pop('Enabled', 'yes')
1717
+ if enabled_field == 'yes':
1718
+ enabled = True
1719
+ elif enabled_field == 'no':
1720
+ enabled = False
1721
+ else:
1722
+ raise BadValueError(
1723
+ 'Must be one of yes or no (default: yes).',
1724
+ file=filename,
1725
+ line=line_numbers.get('Enabled'),
1726
+ key='Enabled',
1727
+ value=enabled_field,
1728
+ )
1729
+ # Signed-By
1730
+ gpg_key_file = options.pop('Signed-By', '')
1731
+ gpg_key_from_stanza: str | None = None
1732
+ if '\n' in gpg_key_file:
1733
+ # actually a literal multi-line gpg-key rather than a filename
1734
+ gpg_key_from_stanza = gpg_key_file
1735
+ gpg_key_file = ''
1736
+ # Types
1737
+ try:
1738
+ repotypes = options.pop('Types').split()
1739
+ uris = options.pop('URIs').split()
1740
+ suites = options.pop('Suites').split()
1741
+ except KeyError as e:
1742
+ [key] = e.args
1743
+ raise MissingRequiredKeyError(
1744
+ key=key,
1745
+ line=min(line_numbers.values()) if line_numbers else None,
1746
+ file=filename,
1747
+ ) from e
1748
+ # Components
1749
+ # suite can specify an exact path, in which case the components must be omitted
1750
+ # and suite must end with a slash (/).
1751
+ # If suite does not specify an exact path, at least one component must be present.
1752
+ # https://manpages.ubuntu.com/manpages/noble/man5/sources.list.5.html
1753
+ components: list[str]
1754
+ if len(suites) == 1 and suites[0].endswith('/'):
1755
+ if 'Components' in options:
1756
+ msg = (
1757
+ "Since 'Suites' (line {suites_line}) specifies"
1758
+ " a path relative to 'URIs' (line {uris_line}),"
1759
+ " 'Components' must be omitted."
1760
+ ).format(
1761
+ suites_line=line_numbers.get('Suites'),
1762
+ uris_line=line_numbers.get('URIs'),
1763
+ )
1764
+ raise BadValueError(
1765
+ msg,
1766
+ file=filename,
1767
+ line=line_numbers.get('Components'),
1768
+ key='Components',
1769
+ value=options['Components'],
1770
+ )
1771
+ components = []
1772
+ else:
1773
+ if 'Components' not in options:
1774
+ msg = (
1775
+ "Since 'Suites' (line {suites_line}) does not specify"
1776
+ " a path relative to 'URIs' (line {uris_line}),"
1777
+ " 'Components' must be present in this stanza."
1778
+ ).format(
1779
+ suites_line=line_numbers.get('Suites'),
1780
+ uris_line=line_numbers.get('URIs'),
1781
+ )
1782
+ raise MissingRequiredKeyError(
1783
+ msg,
1784
+ file=filename,
1785
+ line=min(line_numbers.values()) if line_numbers else None,
1786
+ key='Components',
1787
+ )
1788
+ components = options.pop('Components').split()
1789
+ repos = tuple(
1790
+ DebianRepository(
1791
+ enabled=enabled,
1792
+ repotype=repotype,
1793
+ uri=uri,
1794
+ release=suite,
1795
+ groups=components,
1796
+ filename=filename,
1797
+ gpg_key_filename=gpg_key_file,
1798
+ options=options,
1799
+ )
1800
+ for repotype in repotypes
1801
+ for uri in uris
1802
+ for suite in suites
1803
+ )
1804
+ return repos, (gpg_key_file, gpg_key_from_stanza)