Merge ~jfguedez/charm-ubuntu-advantage:bug/1962335 into charm-ubuntu-advantage:master
- Git
- lp:~jfguedez/charm-ubuntu-advantage
- bug/1962335
- Merge into master
Proposed by
Jose Guedez
Status: | Merged |
---|---|
Approved by: | Tom Haddon |
Approved revision: | 08fa05cc05ecd33ea145f6c453ea19a3ace7ce51 |
Merged at revision: | 05a3802c0fa7c349544c5d29fe11175eb694ac65 |
Proposed branch: | ~jfguedez/charm-ubuntu-advantage:bug/1962335 |
Merge into: | charm-ubuntu-advantage:master |
Diff against target: |
1548 lines (+1363/-45) 4 files modified
lib/charms/operator_libs_linux/v0/apt.py (+1329/-0) run_tests (+4/-3) src/charm.py (+3/-13) tests/test_charm.py (+27/-29) |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Tom Haddon | Approve | ||
Canonical IS Reviewers | Pending | ||
Review via email: mp+416293@code.launchpad.net |
Commit message
Use the operator apt library to install/remove packages
Description of the change
To post a comment you must log in.
Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote : | # |
Revision history for this message
Jose Guedez (jfguedez) wrote : | # |
Updated just to reflect that the operator apt library fixes [0] have been released (only the library patch version was updated)
[0] https:/
Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote : | # |
Change successfully merged at revision 05a3802c0fa7c34
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | diff --git a/lib/charms/operator_libs_linux/v0/apt.py b/lib/charms/operator_libs_linux/v0/apt.py | |||
2 | 0 | new file mode 100644 | 0 | new file mode 100644 |
3 | index 0000000..2b5c8f2 | |||
4 | --- /dev/null | |||
5 | +++ b/lib/charms/operator_libs_linux/v0/apt.py | |||
6 | @@ -0,0 +1,1329 @@ | |||
7 | 1 | # Copyright 2021 Canonical Ltd. | ||
8 | 2 | # | ||
9 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
10 | 4 | # you may not use this file except in compliance with the License. | ||
11 | 5 | # You may obtain a copy of the License at | ||
12 | 6 | # | ||
13 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
14 | 8 | # | ||
15 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
16 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
17 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
18 | 12 | # See the License for the specific language governing permissions and | ||
19 | 13 | # limitations under the License. | ||
20 | 14 | |||
21 | 15 | """Abstractions for the system's Debian/Ubuntu package information and repositories. | ||
22 | 16 | |||
23 | 17 | This module contains abstractions and wrappers around Debian/Ubuntu-style repositories and | ||
24 | 18 | packages, in order to easily provide an idiomatic and Pythonic mechanism for adding packages and/or | ||
25 | 19 | repositories to systems for use in machine charms. | ||
26 | 20 | |||
27 | 21 | A sane default configuration is attainable through nothing more than instantiation of the | ||
28 | 22 | appropriate classes. `DebianPackage` objects provide information about the architecture, version, | ||
29 | 23 | name, and status of a package. | ||
30 | 24 | |||
31 | 25 | `DebianPackage` will try to look up a package either from `dpkg -L` or from `apt-cache` when | ||
32 | 26 | provided with a string indicating the package name. If it cannot be located, `PackageNotFoundError` | ||
33 | 27 | will be returned, as `apt` and `dpkg` otherwise return `100` for all errors, and a meaningful error | ||
34 | 28 | message if the package is not known is desirable. | ||
35 | 29 | |||
36 | 30 | To install packages with convenience methods: | ||
37 | 31 | |||
38 | 32 | ```python | ||
39 | 33 | try: | ||
40 | 34 | # Run `apt-get update` | ||
41 | 35 | apt.update() | ||
42 | 36 | apt.add_package("zsh") | ||
43 | 37 | apt.add_package(["vim", "htop", "wget"]) | ||
44 | 38 | except PackageNotFoundError: | ||
45 | 39 | logger.error("a specified package not found in package cache or on system") | ||
46 | 40 | except PackageError as e: | ||
47 | 41 | logger.error("could not install package. Reason: %s", e.message) | ||
48 | 42 | ```` | ||
49 | 43 | |||
50 | 44 | To find details of a specific package: | ||
51 | 45 | |||
52 | 46 | ```python | ||
53 | 47 | try: | ||
54 | 48 | vim = apt.DebianPackage.from_system("vim") | ||
55 | 49 | |||
56 | 50 | # To find from the apt cache only | ||
57 | 51 | # apt.DebianPackage.from_apt_cache("vim") | ||
58 | 52 | |||
59 | 53 | # To find from installed packages only | ||
60 | 54 | # apt.DebianPackage.from_installed_package("vim") | ||
61 | 55 | |||
62 | 56 | vim.ensure(PackageState.Latest) | ||
63 | 57 | logger.info("updated vim to version: %s", vim.fullversion) | ||
64 | 58 | except PackageNotFoundError: | ||
65 | 59 | logger.error("a specified package not found in package cache or on system") | ||
66 | 60 | except PackageError as e: | ||
67 | 61 | logger.error("could not install package. Reason: %s", e.message) | ||
68 | 62 | ``` | ||
69 | 63 | |||
70 | 64 | |||
71 | 65 | `RepositoryMapping` will return a dict-like object containing enabled system repositories | ||
72 | 66 | and their properties (available groups, baseuri. gpg key). This class can add, disable, or | ||
73 | 67 | manipulate repositories. Items can be retrieved as `DebianRepository` objects. | ||
74 | 68 | |||
75 | 69 | In order add a new repository with explicit details for fields, a new `DebianRepository` can | ||
76 | 70 | be added to `RepositoryMapping` | ||
77 | 71 | |||
78 | 72 | `RepositoryMapping` provides an abstraction around the existing repositories on the system, | ||
79 | 73 | and can be accessed and iterated over like any `Mapping` object, to retrieve values by key, | ||
80 | 74 | iterate, or perform other operations. | ||
81 | 75 | |||
82 | 76 | Keys are constructed as `{repo_type}-{}-{release}` in order to uniquely identify a repository. | ||
83 | 77 | |||
84 | 78 | Repositories can be added with explicit values through a Python constructor. | ||
85 | 79 | |||
86 | 80 | Example: | ||
87 | 81 | |||
88 | 82 | ```python | ||
89 | 83 | repositories = apt.RepositoryMapping() | ||
90 | 84 | |||
91 | 85 | if "deb-example.com-focal" not in repositories: | ||
92 | 86 | repositories.add(DebianRepository(enabled=True, repotype="deb", | ||
93 | 87 | uri="https://example.com", release="focal", groups=["universe"])) | ||
94 | 88 | ``` | ||
95 | 89 | |||
96 | 90 | Alternatively, any valid `sources.list` line may be used to construct a new | ||
97 | 91 | `DebianRepository`. | ||
98 | 92 | |||
99 | 93 | Example: | ||
100 | 94 | |||
101 | 95 | ```python | ||
102 | 96 | repositories = apt.RepositoryMapping() | ||
103 | 97 | |||
104 | 98 | if "deb-us.archive.ubuntu.com-xenial" not in repositories: | ||
105 | 99 | line = "deb http://us.archive.ubuntu.com/ubuntu xenial main restricted" | ||
106 | 100 | repo = DebianRepository.from_repo_line(line) | ||
107 | 101 | repositories.add(repo) | ||
108 | 102 | ``` | ||
109 | 103 | """ | ||
110 | 104 | |||
111 | 105 | import fileinput | ||
112 | 106 | import glob | ||
113 | 107 | import logging | ||
114 | 108 | import os | ||
115 | 109 | import re | ||
116 | 110 | import subprocess | ||
117 | 111 | from collections.abc import Mapping | ||
118 | 112 | from enum import Enum | ||
119 | 113 | from subprocess import PIPE, CalledProcessError, check_call, check_output | ||
120 | 114 | from typing import Iterable, List, Optional, Tuple, Union | ||
121 | 115 | from urllib.parse import urlparse | ||
122 | 116 | |||
123 | 117 | logger = logging.getLogger(__name__) | ||
124 | 118 | |||
125 | 119 | # The unique Charmhub library identifier, never change it | ||
126 | 120 | LIBID = "7c3dbc9c2ad44a47bd6fcb25caa270e5" | ||
127 | 121 | |||
128 | 122 | # Increment this major API version when introducing breaking changes | ||
129 | 123 | LIBAPI = 0 | ||
130 | 124 | |||
131 | 125 | # Increment this PATCH version before using `charmcraft publish-lib` or reset | ||
132 | 126 | # to 0 if you are raising the major API version | ||
133 | 127 | LIBPATCH = 7 | ||
134 | 128 | |||
135 | 129 | |||
136 | 130 | VALID_SOURCE_TYPES = ("deb", "deb-src") | ||
137 | 131 | OPTIONS_MATCHER = re.compile(r"\[.*?\]") | ||
138 | 132 | |||
139 | 133 | |||
140 | 134 | class Error(Exception): | ||
141 | 135 | """Base class of most errors raised by this library.""" | ||
142 | 136 | |||
143 | 137 | def __repr__(self): | ||
144 | 138 | """String representation of Error.""" | ||
145 | 139 | return "<{}.{} {}>".format(type(self).__module__, type(self).__name__, self.args) | ||
146 | 140 | |||
147 | 141 | @property | ||
148 | 142 | def name(self): | ||
149 | 143 | """Return a string representation of the model plus class.""" | ||
150 | 144 | return "<{}.{}>".format(type(self).__module__, type(self).__name__) | ||
151 | 145 | |||
152 | 146 | @property | ||
153 | 147 | def message(self): | ||
154 | 148 | """Return the message passed as an argument.""" | ||
155 | 149 | return self.args[0] | ||
156 | 150 | |||
157 | 151 | |||
158 | 152 | class PackageError(Error): | ||
159 | 153 | """Raised when there's an error installing or removing a package.""" | ||
160 | 154 | |||
161 | 155 | |||
162 | 156 | class PackageNotFoundError(Error): | ||
163 | 157 | """Raised when a requested package is not known to the system.""" | ||
164 | 158 | |||
165 | 159 | |||
166 | 160 | class PackageState(Enum): | ||
167 | 161 | """A class to represent possible package states.""" | ||
168 | 162 | |||
169 | 163 | Present = "present" | ||
170 | 164 | Absent = "absent" | ||
171 | 165 | Latest = "latest" | ||
172 | 166 | Available = "available" | ||
173 | 167 | |||
174 | 168 | |||
175 | 169 | class DebianPackage: | ||
176 | 170 | """Represents a traditional Debian package and its utility functions. | ||
177 | 171 | |||
178 | 172 | `DebianPackage` wraps information and functionality around a known package, whether installed | ||
179 | 173 | or available. The version, epoch, name, and architecture can be easily queried and compared | ||
180 | 174 | against other `DebianPackage` objects to determine the latest version or to install a specific | ||
181 | 175 | version. | ||
182 | 176 | |||
183 | 177 | The representation of this object as a string mimics the output from `dpkg` for familiarity. | ||
184 | 178 | |||
185 | 179 | Installation and removal of packages is handled through the `state` property or `ensure` | ||
186 | 180 | method, with the following options: | ||
187 | 181 | |||
188 | 182 | apt.PackageState.Absent | ||
189 | 183 | apt.PackageState.Available | ||
190 | 184 | apt.PackageState.Present | ||
191 | 185 | apt.PackageState.Latest | ||
192 | 186 | |||
193 | 187 | When `DebianPackage` is initialized, the state of a given `DebianPackage` object will be set to | ||
194 | 188 | `Available`, `Present`, or `Latest`, with `Absent` implemented as a convenience for removal | ||
195 | 189 | (though it operates essentially the same as `Available`). | ||
196 | 190 | """ | ||
197 | 191 | |||
198 | 192 | def __init__( | ||
199 | 193 | self, name: str, version: str, epoch: str, arch: str, state: PackageState | ||
200 | 194 | ) -> None: | ||
201 | 195 | self._name = name | ||
202 | 196 | self._arch = arch | ||
203 | 197 | self._state = state | ||
204 | 198 | self._version = Version(version, epoch) | ||
205 | 199 | |||
206 | 200 | def __eq__(self, other) -> bool: | ||
207 | 201 | """Equality for comparison. | ||
208 | 202 | |||
209 | 203 | Args: | ||
210 | 204 | other: a `DebianPackage` object for comparison | ||
211 | 205 | |||
212 | 206 | Returns: | ||
213 | 207 | A boolean reflecting equality | ||
214 | 208 | """ | ||
215 | 209 | return isinstance(other, self.__class__) and ( | ||
216 | 210 | self._name, | ||
217 | 211 | self._version.number, | ||
218 | 212 | ) == (other._name, other._version.number) | ||
219 | 213 | |||
220 | 214 | def __hash__(self): | ||
221 | 215 | """A basic hash so this class can be used in Mappings and dicts.""" | ||
222 | 216 | return hash((self._name, self._version.number)) | ||
223 | 217 | |||
224 | 218 | def __repr__(self): | ||
225 | 219 | """A representation of the package.""" | ||
226 | 220 | return "<{}.{}: {}>".format(self.__module__, self.__class__.__name__, self.__dict__) | ||
227 | 221 | |||
228 | 222 | def __str__(self): | ||
229 | 223 | """A human-readable representation of the package.""" | ||
230 | 224 | return "<{}: {}-{}.{} -- {}>".format( | ||
231 | 225 | self.__class__.__name__, | ||
232 | 226 | self._name, | ||
233 | 227 | self._version, | ||
234 | 228 | self._arch, | ||
235 | 229 | str(self._state), | ||
236 | 230 | ) | ||
237 | 231 | |||
238 | 232 | @staticmethod | ||
239 | 233 | def _apt( | ||
240 | 234 | command: str, | ||
241 | 235 | package_names: Union[str, List], | ||
242 | 236 | optargs: Optional[List[str]] = None, | ||
243 | 237 | ) -> None: | ||
244 | 238 | """Wrap package management commands for Debian/Ubuntu systems. | ||
245 | 239 | |||
246 | 240 | Args: | ||
247 | 241 | command: the command given to `apt-get` | ||
248 | 242 | package_names: a package name or list of package names to operate on | ||
249 | 243 | optargs: an (Optional) list of additioanl arguments | ||
250 | 244 | |||
251 | 245 | Raises: | ||
252 | 246 | PackageError if an error is encountered | ||
253 | 247 | """ | ||
254 | 248 | optargs = optargs if optargs is not None else [] | ||
255 | 249 | if isinstance(package_names, str): | ||
256 | 250 | package_names = [package_names] | ||
257 | 251 | _cmd = ["apt-get", "-y", *optargs, command, *package_names] | ||
258 | 252 | try: | ||
259 | 253 | check_call(_cmd, stderr=PIPE, stdout=PIPE) | ||
260 | 254 | except CalledProcessError as e: | ||
261 | 255 | raise PackageError( | ||
262 | 256 | "Could not {} package(s) [{}]: {}".format(command, [*package_names], e.output) | ||
263 | 257 | ) from None | ||
264 | 258 | |||
265 | 259 | def _add(self) -> None: | ||
266 | 260 | """Add a package to the system.""" | ||
267 | 261 | self._apt( | ||
268 | 262 | "install", | ||
269 | 263 | "{}={}".format(self.name, self.version), | ||
270 | 264 | optargs=["--option=Dpkg::Options::=--force-confold"], | ||
271 | 265 | ) | ||
272 | 266 | |||
273 | 267 | def _remove(self) -> None: | ||
274 | 268 | """Removes a package from the system. Implementation-specific.""" | ||
275 | 269 | return self._apt("remove", "{}={}".format(self.name, self.version)) | ||
276 | 270 | |||
277 | 271 | @property | ||
278 | 272 | def name(self) -> str: | ||
279 | 273 | """Returns the name of the package.""" | ||
280 | 274 | return self._name | ||
281 | 275 | |||
282 | 276 | def ensure(self, state: PackageState): | ||
283 | 277 | """Ensures that a package is in a given state. | ||
284 | 278 | |||
285 | 279 | Args: | ||
286 | 280 | state: a `PackageState` to reconcile the package to | ||
287 | 281 | |||
288 | 282 | Raises: | ||
289 | 283 | PackageError from the underlying call to apt | ||
290 | 284 | """ | ||
291 | 285 | if self._state is not state: | ||
292 | 286 | if state not in (PackageState.Present, PackageState.Latest): | ||
293 | 287 | self._remove() | ||
294 | 288 | else: | ||
295 | 289 | self._add() | ||
296 | 290 | self._state = state | ||
297 | 291 | |||
298 | 292 | @property | ||
299 | 293 | def present(self) -> bool: | ||
300 | 294 | """Returns whether or not a package is present.""" | ||
301 | 295 | return self._state in (PackageState.Present, PackageState.Latest) | ||
302 | 296 | |||
303 | 297 | @property | ||
304 | 298 | def latest(self) -> bool: | ||
305 | 299 | """Returns whether the package is the most recent version.""" | ||
306 | 300 | return self._state is PackageState.Latest | ||
307 | 301 | |||
308 | 302 | @property | ||
309 | 303 | def state(self) -> PackageState: | ||
310 | 304 | """Returns the current package state.""" | ||
311 | 305 | return self._state | ||
312 | 306 | |||
313 | 307 | @state.setter | ||
314 | 308 | def state(self, state: PackageState) -> None: | ||
315 | 309 | """Sets the package state to a given value. | ||
316 | 310 | |||
317 | 311 | Args: | ||
318 | 312 | state: a `PackageState` to reconcile the package to | ||
319 | 313 | |||
320 | 314 | Raises: | ||
321 | 315 | PackageError from the underlying call to apt | ||
322 | 316 | """ | ||
323 | 317 | if state in (PackageState.Latest, PackageState.Present): | ||
324 | 318 | self._add() | ||
325 | 319 | else: | ||
326 | 320 | self._remove() | ||
327 | 321 | self._state = state | ||
328 | 322 | |||
329 | 323 | @property | ||
330 | 324 | def version(self) -> "Version": | ||
331 | 325 | """Returns the version for a package.""" | ||
332 | 326 | return self._version | ||
333 | 327 | |||
334 | 328 | @property | ||
335 | 329 | def epoch(self) -> str: | ||
336 | 330 | """Returns the epoch for a package. May be unset.""" | ||
337 | 331 | return self._version.epoch | ||
338 | 332 | |||
339 | 333 | @property | ||
340 | 334 | def arch(self) -> str: | ||
341 | 335 | """Returns the architecture for a package.""" | ||
342 | 336 | return self._arch | ||
343 | 337 | |||
344 | 338 | @property | ||
345 | 339 | def fullversion(self) -> str: | ||
346 | 340 | """Returns the name+epoch for a package.""" | ||
347 | 341 | return "{}.{}".format(self._version, self._arch) | ||
348 | 342 | |||
349 | 343 | @staticmethod | ||
350 | 344 | def _get_epoch_from_version(version: str) -> Tuple[str, str]: | ||
351 | 345 | """Pull the epoch, if any, out of a version string.""" | ||
352 | 346 | epoch_matcher = re.compile(r"^((?P<epoch>\d+):)?(?P<version>.*)") | ||
353 | 347 | matches = epoch_matcher.search(version).groupdict() | ||
354 | 348 | return matches.get("epoch", ""), matches.get("version") | ||
355 | 349 | |||
356 | 350 | @classmethod | ||
357 | 351 | def from_system( | ||
358 | 352 | cls, package: str, version: Optional[str] = "", arch: Optional[str] = "" | ||
359 | 353 | ) -> "DebianPackage": | ||
360 | 354 | """Locates a package, either on the system or known to apt, and serializes the information. | ||
361 | 355 | |||
362 | 356 | Args: | ||
363 | 357 | package: a string representing the package | ||
364 | 358 | version: an optional string if a specific version isr equested | ||
365 | 359 | arch: an optional architecture, defaulting to `dpkg --print-architecture`. If an | ||
366 | 360 | architecture is not specified, this will be used for selection. | ||
367 | 361 | |||
368 | 362 | """ | ||
369 | 363 | try: | ||
370 | 364 | return DebianPackage.from_installed_package(package, version, arch) | ||
371 | 365 | except PackageNotFoundError: | ||
372 | 366 | logger.debug( | ||
373 | 367 | "package '%s' is not currently installed or has the wrong architecture.", package | ||
374 | 368 | ) | ||
375 | 369 | |||
376 | 370 | # Ok, try `apt-cache ...` | ||
377 | 371 | try: | ||
378 | 372 | return DebianPackage.from_apt_cache(package, version, arch) | ||
379 | 373 | except (PackageNotFoundError, PackageError): | ||
380 | 374 | # If we get here, it's not known to the systems. | ||
381 | 375 | # This seems unnecessary, but virtually all `apt` commands have a return code of `100`, | ||
382 | 376 | # and providing meaningful error messages without this is ugly. | ||
383 | 377 | raise PackageNotFoundError( | ||
384 | 378 | "Package '{}{}' could not be found on the system or in the apt cache!".format( | ||
385 | 379 | package, ".{}".format(arch) if arch else "" | ||
386 | 380 | ) | ||
387 | 381 | ) from None | ||
388 | 382 | |||
389 | 383 | @classmethod | ||
390 | 384 | def from_installed_package( | ||
391 | 385 | cls, package: str, version: Optional[str] = "", arch: Optional[str] = "" | ||
392 | 386 | ) -> "DebianPackage": | ||
393 | 387 | """Check whether the package is already installed and return an instance. | ||
394 | 388 | |||
395 | 389 | Args: | ||
396 | 390 | package: a string representing the package | ||
397 | 391 | version: an optional string if a specific version isr equested | ||
398 | 392 | arch: an optional architecture, defaulting to `dpkg --print-architecture`. | ||
399 | 393 | If an architecture is not specified, this will be used for selection. | ||
400 | 394 | """ | ||
401 | 395 | system_arch = check_output( | ||
402 | 396 | ["dpkg", "--print-architecture"], universal_newlines=True | ||
403 | 397 | ).strip() | ||
404 | 398 | arch = arch if arch else system_arch | ||
405 | 399 | |||
406 | 400 | # Regexps are a really terrible way to do this. Thanks dpkg | ||
407 | 401 | output = "" | ||
408 | 402 | try: | ||
409 | 403 | output = check_output(["dpkg", "-l", package], stderr=PIPE, universal_newlines=True) | ||
410 | 404 | except CalledProcessError: | ||
411 | 405 | raise PackageNotFoundError("Package is not installed: {}".format(package)) from None | ||
412 | 406 | |||
413 | 407 | # Pop off the output from `dpkg -l' because there's no flag to | ||
414 | 408 | # omit it` | ||
415 | 409 | lines = str(output).splitlines()[5:] | ||
416 | 410 | |||
417 | 411 | dpkg_matcher = re.compile( | ||
418 | 412 | r""" | ||
419 | 413 | ^(?P<package_status>\w+?)\s+ | ||
420 | 414 | (?P<package_name>.*?)(?P<throwaway_arch>:\w+?)?\s+ | ||
421 | 415 | (?P<version>.*?)\s+ | ||
422 | 416 | (?P<arch>\w+?)\s+ | ||
423 | 417 | (?P<description>.*) | ||
424 | 418 | """, | ||
425 | 419 | re.VERBOSE, | ||
426 | 420 | ) | ||
427 | 421 | |||
428 | 422 | for line in lines: | ||
429 | 423 | try: | ||
430 | 424 | matches = dpkg_matcher.search(line).groupdict() | ||
431 | 425 | package_status = matches["package_status"] | ||
432 | 426 | |||
433 | 427 | if not package_status.endswith("i"): | ||
434 | 428 | logger.debug( | ||
435 | 429 | "package '%s' in dpkg output but not installed, status: '%s'", | ||
436 | 430 | package, | ||
437 | 431 | package_status, | ||
438 | 432 | ) | ||
439 | 433 | break | ||
440 | 434 | |||
441 | 435 | epoch, split_version = DebianPackage._get_epoch_from_version(matches["version"]) | ||
442 | 436 | pkg = DebianPackage( | ||
443 | 437 | matches["package_name"], | ||
444 | 438 | split_version, | ||
445 | 439 | epoch, | ||
446 | 440 | matches["arch"], | ||
447 | 441 | PackageState.Present, | ||
448 | 442 | ) | ||
449 | 443 | if (pkg.arch == "all" or pkg.arch == arch) and ( | ||
450 | 444 | version == "" or str(pkg.version) == version | ||
451 | 445 | ): | ||
452 | 446 | return pkg | ||
453 | 447 | except AttributeError: | ||
454 | 448 | logger.warning("dpkg matcher could not parse line: %s", line) | ||
455 | 449 | |||
456 | 450 | # If we didn't find it, fail through | ||
457 | 451 | raise PackageNotFoundError("Package {}.{} is not installed!".format(package, arch)) | ||
458 | 452 | |||
459 | 453 | @classmethod | ||
460 | 454 | def from_apt_cache( | ||
461 | 455 | cls, package: str, version: Optional[str] = "", arch: Optional[str] = "" | ||
462 | 456 | ) -> "DebianPackage": | ||
463 | 457 | """Check whether the package is already installed and return an instance. | ||
464 | 458 | |||
465 | 459 | Args: | ||
466 | 460 | package: a string representing the package | ||
467 | 461 | version: an optional string if a specific version isr equested | ||
468 | 462 | arch: an optional architecture, defaulting to `dpkg --print-architecture`. | ||
469 | 463 | If an architecture is not specified, this will be used for selection. | ||
470 | 464 | """ | ||
471 | 465 | system_arch = check_output( | ||
472 | 466 | ["dpkg", "--print-architecture"], universal_newlines=True | ||
473 | 467 | ).strip() | ||
474 | 468 | arch = arch if arch else system_arch | ||
475 | 469 | |||
476 | 470 | # Regexps are a really terrible way to do this. Thanks dpkg | ||
477 | 471 | keys = ("Package", "Architecture", "Version") | ||
478 | 472 | |||
479 | 473 | try: | ||
480 | 474 | output = check_output( | ||
481 | 475 | ["apt-cache", "show", package], stderr=PIPE, universal_newlines=True | ||
482 | 476 | ) | ||
483 | 477 | except CalledProcessError as e: | ||
484 | 478 | raise PackageError( | ||
485 | 479 | "Could not list packages in apt-cache: {}".format(e.output) | ||
486 | 480 | ) from None | ||
487 | 481 | |||
488 | 482 | pkg_groups = output.strip().split("\n\n") | ||
489 | 483 | keys = ("Package", "Architecture", "Version") | ||
490 | 484 | |||
491 | 485 | for pkg_raw in pkg_groups: | ||
492 | 486 | lines = str(pkg_raw).splitlines() | ||
493 | 487 | vals = {} | ||
494 | 488 | for line in lines: | ||
495 | 489 | if line.startswith(keys): | ||
496 | 490 | items = line.split(":", 1) | ||
497 | 491 | vals[items[0]] = items[1].strip() | ||
498 | 492 | else: | ||
499 | 493 | continue | ||
500 | 494 | |||
501 | 495 | epoch, split_version = DebianPackage._get_epoch_from_version(vals["Version"]) | ||
502 | 496 | pkg = DebianPackage( | ||
503 | 497 | vals["Package"], | ||
504 | 498 | split_version, | ||
505 | 499 | epoch, | ||
506 | 500 | vals["Architecture"], | ||
507 | 501 | PackageState.Available, | ||
508 | 502 | ) | ||
509 | 503 | |||
510 | 504 | if (pkg.arch == "all" or pkg.arch == arch) and ( | ||
511 | 505 | version == "" or str(pkg.version) == version | ||
512 | 506 | ): | ||
513 | 507 | return pkg | ||
514 | 508 | |||
515 | 509 | # If we didn't find it, fail through | ||
516 | 510 | raise PackageNotFoundError("Package {}.{} is not in the apt cache!".format(package, arch)) | ||
517 | 511 | |||
518 | 512 | |||
519 | 513 | class Version: | ||
520 | 514 | """An abstraction around package versions. | ||
521 | 515 | |||
522 | 516 | This seems like it should be strictly unnecessary, except that `apt_pkg` is not usable inside a | ||
523 | 517 | venv, and wedging version comparisions into `DebianPackage` would overcomplicate it. | ||
524 | 518 | |||
525 | 519 | This class implements the algorithm found here: | ||
526 | 520 | https://www.debian.org/doc/debian-policy/ch-controlfields.html#version | ||
527 | 521 | """ | ||
528 | 522 | |||
529 | 523 | def __init__(self, version: str, epoch: str): | ||
530 | 524 | self._version = version | ||
531 | 525 | self._epoch = epoch or "" | ||
532 | 526 | |||
533 | 527 | def __repr__(self): | ||
534 | 528 | """A representation of the package.""" | ||
535 | 529 | return "<{}.{}: {}>".format(self.__module__, self.__class__.__name__, self.__dict__) | ||
536 | 530 | |||
537 | 531 | def __str__(self): | ||
538 | 532 | """A human-readable representation of the package.""" | ||
539 | 533 | return "{}{}".format("{}:".format(self._epoch) if self._epoch else "", self._version) | ||
540 | 534 | |||
541 | 535 | @property | ||
542 | 536 | def epoch(self): | ||
543 | 537 | """Returns the epoch for a package. May be empty.""" | ||
544 | 538 | return self._epoch | ||
545 | 539 | |||
546 | 540 | @property | ||
547 | 541 | def number(self) -> str: | ||
548 | 542 | """Returns the version number for a package.""" | ||
549 | 543 | return self._version | ||
550 | 544 | |||
551 | 545 | def _get_parts(self, version: str) -> Tuple[str, str]: | ||
552 | 546 | """Separate the version into component upstream and Debian pieces.""" | ||
553 | 547 | try: | ||
554 | 548 | version.rindex("-") | ||
555 | 549 | except ValueError: | ||
556 | 550 | # No hyphens means no Debian version | ||
557 | 551 | return version, "0" | ||
558 | 552 | |||
559 | 553 | upstream, debian = version.rsplit("-", 1) | ||
560 | 554 | return upstream, debian | ||
561 | 555 | |||
562 | 556 | def _listify(self, revision: str) -> List[str]: | ||
563 | 557 | """Split a revision string into a listself. | ||
564 | 558 | |||
565 | 559 | This list is comprised of alternating between strings and numbers, | ||
566 | 560 | padded on either end to always be "str, int, str, int..." and | ||
567 | 561 | always be of even length. This allows us to trivially implement the | ||
568 | 562 | comparison algorithm described. | ||
569 | 563 | """ | ||
570 | 564 | result = [] | ||
571 | 565 | while revision: | ||
572 | 566 | rev_1, remains = self._get_alphas(revision) | ||
573 | 567 | rev_2, remains = self._get_digits(remains) | ||
574 | 568 | result.extend([rev_1, rev_2]) | ||
575 | 569 | revision = remains | ||
576 | 570 | return result | ||
577 | 571 | |||
578 | 572 | def _get_alphas(self, revision: str) -> Tuple[str, str]: | ||
579 | 573 | """Return a tuple of the first non-digit characters of a revision.""" | ||
580 | 574 | # get the index of the first digit | ||
581 | 575 | for i, char in enumerate(revision): | ||
582 | 576 | if char.isdigit(): | ||
583 | 577 | if i == 0: | ||
584 | 578 | return "", revision | ||
585 | 579 | return revision[0:i], revision[i:] | ||
586 | 580 | # string is entirely alphas | ||
587 | 581 | return revision, "" | ||
588 | 582 | |||
589 | 583 | def _get_digits(self, revision: str) -> Tuple[int, str]: | ||
590 | 584 | """Return a tuple of the first integer characters of a revision.""" | ||
591 | 585 | # If the string is empty, return (0,'') | ||
592 | 586 | if not revision: | ||
593 | 587 | return 0, "" | ||
594 | 588 | # get the index of the first non-digit | ||
595 | 589 | for i, char in enumerate(revision): | ||
596 | 590 | if not char.isdigit(): | ||
597 | 591 | if i == 0: | ||
598 | 592 | return 0, revision | ||
599 | 593 | return int(revision[0:i]), revision[i:] | ||
600 | 594 | # string is entirely digits | ||
601 | 595 | return int(revision), "" | ||
602 | 596 | |||
603 | 597 | def _dstringcmp(self, a, b): # noqa: C901 | ||
604 | 598 | """Debian package version string section lexical sort algorithm. | ||
605 | 599 | |||
606 | 600 | The lexical comparison is a comparison of ASCII values modified so | ||
607 | 601 | that all the letters sort earlier than all the non-letters and so that | ||
608 | 602 | a tilde sorts before anything, even the end of a part. | ||
609 | 603 | """ | ||
610 | 604 | if a == b: | ||
611 | 605 | return 0 | ||
612 | 606 | try: | ||
613 | 607 | for i, char in enumerate(a): | ||
614 | 608 | if char == b[i]: | ||
615 | 609 | continue | ||
616 | 610 | # "a tilde sorts before anything, even the end of a part" | ||
617 | 611 | # (emptyness) | ||
618 | 612 | if char == "~": | ||
619 | 613 | return -1 | ||
620 | 614 | if b[i] == "~": | ||
621 | 615 | return 1 | ||
622 | 616 | # "all the letters sort earlier than all the non-letters" | ||
623 | 617 | if char.isalpha() and not b[i].isalpha(): | ||
624 | 618 | return -1 | ||
625 | 619 | if not char.isalpha() and b[i].isalpha(): | ||
626 | 620 | return 1 | ||
627 | 621 | # otherwise lexical sort | ||
628 | 622 | if ord(char) > ord(b[i]): | ||
629 | 623 | return 1 | ||
630 | 624 | if ord(char) < ord(b[i]): | ||
631 | 625 | return -1 | ||
632 | 626 | except IndexError: | ||
633 | 627 | # a is longer than b but otherwise equal, greater unless there are tildes | ||
634 | 628 | if char == "~": | ||
635 | 629 | return -1 | ||
636 | 630 | return 1 | ||
637 | 631 | # if we get here, a is shorter than b but otherwise equal, so check for tildes... | ||
638 | 632 | if b[len(a)] == "~": | ||
639 | 633 | return 1 | ||
640 | 634 | return -1 | ||
641 | 635 | |||
642 | 636 | def _compare_revision_strings(self, first: str, second: str): # noqa: C901 | ||
643 | 637 | """Compare two debian revision strings.""" | ||
644 | 638 | if first == second: | ||
645 | 639 | return 0 | ||
646 | 640 | |||
647 | 641 | # listify pads results so that we will always be comparing ints to ints | ||
648 | 642 | # and strings to strings (at least until we fall off the end of a list) | ||
649 | 643 | first_list = self._listify(first) | ||
650 | 644 | second_list = self._listify(second) | ||
651 | 645 | if first_list == second_list: | ||
652 | 646 | return 0 | ||
653 | 647 | try: | ||
654 | 648 | for i, item in enumerate(first_list): | ||
655 | 649 | # explicitly raise IndexError if we've fallen off the edge of list2 | ||
656 | 650 | if i >= len(second_list): | ||
657 | 651 | raise IndexError | ||
658 | 652 | # if the items are equal, next | ||
659 | 653 | if item == second_list[i]: | ||
660 | 654 | continue | ||
661 | 655 | # numeric comparison | ||
662 | 656 | if isinstance(item, int): | ||
663 | 657 | if item > second_list[i]: | ||
664 | 658 | return 1 | ||
665 | 659 | if item < second_list[i]: | ||
666 | 660 | return -1 | ||
667 | 661 | else: | ||
668 | 662 | # string comparison | ||
669 | 663 | return self._dstringcmp(item, second_list[i]) | ||
670 | 664 | except IndexError: | ||
671 | 665 | # rev1 is longer than rev2 but otherwise equal, hence greater | ||
672 | 666 | # ...except for goddamn tildes | ||
673 | 667 | if first_list[len(second_list)][0][0] == "~": | ||
674 | 668 | return 1 | ||
675 | 669 | return 1 | ||
676 | 670 | # rev1 is shorter than rev2 but otherwise equal, hence lesser | ||
677 | 671 | # ...except for goddamn tildes | ||
678 | 672 | if second_list[len(first_list)][0][0] == "~": | ||
679 | 673 | return -1 | ||
680 | 674 | return -1 | ||
681 | 675 | |||
682 | 676 | def _compare_version(self, other) -> int: | ||
683 | 677 | if (self.number, self.epoch) == (other.number, other.epoch): | ||
684 | 678 | return 0 | ||
685 | 679 | |||
686 | 680 | if self.epoch < other.epoch: | ||
687 | 681 | return -1 | ||
688 | 682 | if self.epoch > other.epoch: | ||
689 | 683 | return 1 | ||
690 | 684 | |||
691 | 685 | # If none of these are true, follow the algorithm | ||
692 | 686 | upstream_version, debian_version = self._get_parts(self.number) | ||
693 | 687 | other_upstream_version, other_debian_version = self._get_parts(other.number) | ||
694 | 688 | |||
695 | 689 | upstream_cmp = self._compare_revision_strings(upstream_version, other_upstream_version) | ||
696 | 690 | if upstream_cmp != 0: | ||
697 | 691 | return upstream_cmp | ||
698 | 692 | |||
699 | 693 | debian_cmp = self._compare_revision_strings(debian_version, other_debian_version) | ||
700 | 694 | if debian_cmp != 0: | ||
701 | 695 | return debian_cmp | ||
702 | 696 | |||
703 | 697 | return 0 | ||
704 | 698 | |||
705 | 699 | def __lt__(self, other) -> bool: | ||
706 | 700 | """Less than magic method impl.""" | ||
707 | 701 | return self._compare_version(other) < 0 | ||
708 | 702 | |||
709 | 703 | def __eq__(self, other) -> bool: | ||
710 | 704 | """Equality magic method impl.""" | ||
711 | 705 | return self._compare_version(other) == 0 | ||
712 | 706 | |||
713 | 707 | def __gt__(self, other) -> bool: | ||
714 | 708 | """Greater than magic method impl.""" | ||
715 | 709 | return self._compare_version(other) > 0 | ||
716 | 710 | |||
717 | 711 | def __le__(self, other) -> bool: | ||
718 | 712 | """Less than or equal to magic method impl.""" | ||
719 | 713 | return self.__eq__(other) or self.__lt__(other) | ||
720 | 714 | |||
721 | 715 | def __ge__(self, other) -> bool: | ||
722 | 716 | """Greater than or equal to magic method impl.""" | ||
723 | 717 | return self.__gt__(other) or self.__eq__(other) | ||
724 | 718 | |||
725 | 719 | def __ne__(self, other) -> bool: | ||
726 | 720 | """Not equal to magic method impl.""" | ||
727 | 721 | return not self.__eq__(other) | ||
728 | 722 | |||
729 | 723 | |||
730 | 724 | def add_package( | ||
731 | 725 | package_names: Union[str, List[str]], | ||
732 | 726 | version: Optional[str] = "", | ||
733 | 727 | arch: Optional[str] = "", | ||
734 | 728 | update_cache: Optional[bool] = False, | ||
735 | 729 | ) -> Union[DebianPackage, List[DebianPackage]]: | ||
736 | 730 | """Add a package or list of packages to the system. | ||
737 | 731 | |||
738 | 732 | Args: | ||
739 | 733 | name: the name(s) of the package(s) | ||
740 | 734 | version: an (Optional) version as a string. Defaults to the latest known | ||
741 | 735 | arch: an optional architecture for the package | ||
742 | 736 | update_cache: whether or not to run `apt-get update` prior to operating | ||
743 | 737 | |||
744 | 738 | Raises: | ||
745 | 739 | PackageNotFoundError if the package is not in the cache. | ||
746 | 740 | """ | ||
747 | 741 | cache_refreshed = False | ||
748 | 742 | if update_cache: | ||
749 | 743 | update() | ||
750 | 744 | cache_refreshed = True | ||
751 | 745 | |||
752 | 746 | packages = {"success": [], "retry": [], "failed": []} | ||
753 | 747 | |||
754 | 748 | package_names = [package_names] if type(package_names) is str else package_names | ||
755 | 749 | if not package_names: | ||
756 | 750 | raise TypeError("Expected at least one package name to add, received zero!") | ||
757 | 751 | |||
758 | 752 | if len(package_names) != 1 and version: | ||
759 | 753 | raise TypeError( | ||
760 | 754 | "Explicit version should not be set if more than one package is being added!" | ||
761 | 755 | ) | ||
762 | 756 | |||
763 | 757 | for p in package_names: | ||
764 | 758 | pkg, success = _add(p, version, arch) | ||
765 | 759 | if success: | ||
766 | 760 | packages["success"].append(pkg) | ||
767 | 761 | else: | ||
768 | 762 | logger.warning("failed to locate and install/update '%s'", pkg) | ||
769 | 763 | packages["retry"].append(p) | ||
770 | 764 | |||
771 | 765 | if packages["retry"] and not cache_refreshed: | ||
772 | 766 | logger.info("updating the apt-cache and retrying installation of failed packages.") | ||
773 | 767 | update() | ||
774 | 768 | |||
775 | 769 | for p in packages["retry"]: | ||
776 | 770 | pkg, success = _add(p, version, arch) | ||
777 | 771 | if success: | ||
778 | 772 | packages["success"].append(pkg) | ||
779 | 773 | else: | ||
780 | 774 | packages["failed"].append(p) | ||
781 | 775 | |||
782 | 776 | if packages["failed"]: | ||
783 | 777 | raise PackageError("Failed to install packages: {}".format(", ".join(packages["failed"]))) | ||
784 | 778 | |||
785 | 779 | return packages["success"] if len(packages["success"]) > 1 else packages["success"][0] | ||
786 | 780 | |||
787 | 781 | |||
788 | 782 | def _add( | ||
789 | 783 | name: str, | ||
790 | 784 | version: Optional[str] = "", | ||
791 | 785 | arch: Optional[str] = "", | ||
792 | 786 | ) -> Tuple[Union[DebianPackage, str], bool]: | ||
793 | 787 | """Adds a package. | ||
794 | 788 | |||
795 | 789 | Args: | ||
796 | 790 | name: the name(s) of the package(s) | ||
797 | 791 | version: an (Optional) version as a string. Defaults to the latest known | ||
798 | 792 | arch: an optional architecture for the package | ||
799 | 793 | |||
800 | 794 | Returns: a tuple of `DebianPackage` if found, or a :str: if it is not, and | ||
801 | 795 | a boolean indicating success | ||
802 | 796 | """ | ||
803 | 797 | try: | ||
804 | 798 | pkg = DebianPackage.from_system(name, version, arch) | ||
805 | 799 | pkg.ensure(state=PackageState.Present) | ||
806 | 800 | return pkg, True | ||
807 | 801 | except PackageNotFoundError: | ||
808 | 802 | return name, False | ||
809 | 803 | |||
810 | 804 | |||
811 | 805 | def remove_package( | ||
812 | 806 | package_names: Union[str, List[str]] | ||
813 | 807 | ) -> Union[DebianPackage, List[DebianPackage]]: | ||
814 | 808 | """Removes a package from the system. | ||
815 | 809 | |||
816 | 810 | Args: | ||
817 | 811 | package_names: the name of a package | ||
818 | 812 | |||
819 | 813 | Raises: | ||
820 | 814 | PackageNotFoundError if the package is not found. | ||
821 | 815 | """ | ||
822 | 816 | packages = [] | ||
823 | 817 | |||
824 | 818 | package_names = [package_names] if type(package_names) is str else package_names | ||
825 | 819 | if not package_names: | ||
826 | 820 | raise TypeError("Expected at least one package name to add, received zero!") | ||
827 | 821 | |||
828 | 822 | for p in package_names: | ||
829 | 823 | try: | ||
830 | 824 | pkg = DebianPackage.from_installed_package(p) | ||
831 | 825 | pkg.ensure(state=PackageState.Absent) | ||
832 | 826 | packages.append(pkg) | ||
833 | 827 | except PackageNotFoundError: | ||
834 | 828 | logger.info("package '%s' was requested for removal, but it was not installed.", p) | ||
835 | 829 | |||
836 | 830 | # the list of packages will be empty when no package is removed | ||
837 | 831 | logger.debug("packages: '%s'", packages) | ||
838 | 832 | return packages[0] if len(packages) == 1 else packages | ||
839 | 833 | |||
840 | 834 | |||
841 | 835 | def update() -> None: | ||
842 | 836 | """Updates the apt cache via `apt-get update`.""" | ||
843 | 837 | check_call(["apt-get", "update"], stderr=PIPE, stdout=PIPE) | ||
844 | 838 | |||
845 | 839 | |||
846 | 840 | class InvalidSourceError(Error): | ||
847 | 841 | """Exceptions for invalid source entries.""" | ||
848 | 842 | |||
849 | 843 | |||
850 | 844 | class GPGKeyError(Error): | ||
851 | 845 | """Exceptions for GPG keys.""" | ||
852 | 846 | |||
853 | 847 | |||
854 | 848 | class DebianRepository: | ||
855 | 849 | """An abstraction to represent a repository.""" | ||
856 | 850 | |||
857 | 851 | def __init__( | ||
858 | 852 | self, | ||
859 | 853 | enabled: bool, | ||
860 | 854 | repotype: str, | ||
861 | 855 | uri: str, | ||
862 | 856 | release: str, | ||
863 | 857 | groups: List[str], | ||
864 | 858 | filename: Optional[str] = "", | ||
865 | 859 | gpg_key_filename: Optional[str] = "", | ||
866 | 860 | options: Optional[dict] = None, | ||
867 | 861 | ): | ||
868 | 862 | self._enabled = enabled | ||
869 | 863 | self._repotype = repotype | ||
870 | 864 | self._uri = uri | ||
871 | 865 | self._release = release | ||
872 | 866 | self._groups = groups | ||
873 | 867 | self._filename = filename | ||
874 | 868 | self._gpg_key_filename = gpg_key_filename | ||
875 | 869 | self._options = options | ||
876 | 870 | |||
877 | 871 | @property | ||
878 | 872 | def enabled(self): | ||
879 | 873 | """Return whether or not the repository is enabled.""" | ||
880 | 874 | return self._enabled | ||
881 | 875 | |||
882 | 876 | @property | ||
883 | 877 | def repotype(self): | ||
884 | 878 | """Return whether it is binary or source.""" | ||
885 | 879 | return self._repotype | ||
886 | 880 | |||
887 | 881 | @property | ||
888 | 882 | def uri(self): | ||
889 | 883 | """Return the URI.""" | ||
890 | 884 | return self._uri | ||
891 | 885 | |||
892 | 886 | @property | ||
893 | 887 | def release(self): | ||
894 | 888 | """Return which Debian/Ubuntu releases it is valid for.""" | ||
895 | 889 | return self._release | ||
896 | 890 | |||
897 | 891 | @property | ||
898 | 892 | def groups(self): | ||
899 | 893 | """Return the enabled package groups.""" | ||
900 | 894 | return self._groups | ||
901 | 895 | |||
902 | 896 | @property | ||
903 | 897 | def filename(self): | ||
904 | 898 | """Returns the filename for a repository.""" | ||
905 | 899 | return self._filename | ||
906 | 900 | |||
907 | 901 | @filename.setter | ||
908 | 902 | def filename(self, fname: str) -> None: | ||
909 | 903 | """Sets the filename used when a repo is written back to diskself. | ||
910 | 904 | |||
911 | 905 | Args: | ||
912 | 906 | fname: a filename to write the repository information to. | ||
913 | 907 | """ | ||
914 | 908 | if not fname.endswith(".list"): | ||
915 | 909 | raise InvalidSourceError("apt source filenames should end in .list!") | ||
916 | 910 | |||
917 | 911 | self._filename = fname | ||
918 | 912 | |||
919 | 913 | @property | ||
920 | 914 | def gpg_key(self): | ||
921 | 915 | """Returns the path to the GPG key for this repository.""" | ||
922 | 916 | return self._gpg_key_filename | ||
923 | 917 | |||
924 | 918 | @property | ||
925 | 919 | def options(self): | ||
926 | 920 | """Returns any additional repo options which are set.""" | ||
927 | 921 | return self._options | ||
928 | 922 | |||
929 | 923 | def make_options_string(self) -> str: | ||
930 | 924 | """Generate the complete options string for a a repository. | ||
931 | 925 | |||
932 | 926 | Combining `gpg_key`, if set, and the rest of the options to find | ||
933 | 927 | a complex repo string. | ||
934 | 928 | """ | ||
935 | 929 | options = self._options if self._options else {} | ||
936 | 930 | if self._gpg_key_filename: | ||
937 | 931 | options["signed-by"] = self._gpg_key_filename | ||
938 | 932 | |||
939 | 933 | return ( | ||
940 | 934 | "[{}] ".format(" ".join(["{}={}".format(k, v) for k, v in options.items()])) | ||
941 | 935 | if options | ||
942 | 936 | else "" | ||
943 | 937 | ) | ||
944 | 938 | |||
945 | 939 | @staticmethod | ||
946 | 940 | def prefix_from_uri(uri: str) -> str: | ||
947 | 941 | """Get a repo list prefix from the uri, depending on whether a path is set.""" | ||
948 | 942 | uridetails = urlparse(uri) | ||
949 | 943 | path = ( | ||
950 | 944 | uridetails.path.lstrip("/").replace("/", "-") if uridetails.path else uridetails.netloc | ||
951 | 945 | ) | ||
952 | 946 | return "/etc/apt/sources.list.d/{}".format(path) | ||
953 | 947 | |||
954 | 948 | @staticmethod | ||
955 | 949 | def from_repo_line(repo_line: str, write_file: Optional[bool] = True) -> "DebianRepository": | ||
956 | 950 | """Instantiate a new `DebianRepository` a `sources.list` entry line. | ||
957 | 951 | |||
958 | 952 | Args: | ||
959 | 953 | repo_line: a string representing a repository entry | ||
960 | 954 | write_file: boolean to enable writing the new repo to disk | ||
961 | 955 | """ | ||
962 | 956 | repo = RepositoryMapping._parse(repo_line, "UserInput") | ||
963 | 957 | fname = "{}-{}.list".format( | ||
964 | 958 | DebianRepository.prefix_from_uri(repo.uri), repo.release.replace("/", "-") | ||
965 | 959 | ) | ||
966 | 960 | repo.filename = fname | ||
967 | 961 | |||
968 | 962 | options = repo.options if repo.options else {} | ||
969 | 963 | if repo.gpg_key: | ||
970 | 964 | options["signed-by"] = repo.gpg_key | ||
971 | 965 | |||
972 | 966 | # For Python 3.5 it's required to use sorted in the options dict in order to not have | ||
973 | 967 | # different results in the order of the options between executions. | ||
974 | 968 | options_str = ( | ||
975 | 969 | "[{}] ".format(" ".join(["{}={}".format(k, v) for k, v in sorted(options.items())])) | ||
976 | 970 | if options | ||
977 | 971 | else "" | ||
978 | 972 | ) | ||
979 | 973 | |||
980 | 974 | if write_file: | ||
981 | 975 | with open(fname, "wb") as f: | ||
982 | 976 | f.write( | ||
983 | 977 | ( | ||
984 | 978 | "{}".format("#" if not repo.enabled else "") | ||
985 | 979 | + "{} {}{} ".format(repo.repotype, options_str, repo.uri) | ||
986 | 980 | + "{} {}\n".format(repo.release, " ".join(repo.groups)) | ||
987 | 981 | ).encode("utf-8") | ||
988 | 982 | ) | ||
989 | 983 | |||
990 | 984 | return repo | ||
991 | 985 | |||
992 | 986 | def disable(self) -> None: | ||
993 | 987 | """Remove this repository from consideration. | ||
994 | 988 | |||
995 | 989 | Disable it instead of removing from the repository file. | ||
996 | 990 | """ | ||
997 | 991 | searcher = "{} {}{} {}".format( | ||
998 | 992 | self.repotype, self.make_options_string(), self.uri, self.release | ||
999 | 993 | ) | ||
1000 | 994 | for line in fileinput.input(self._filename, inplace=True): | ||
1001 | 995 | if re.match(r"^{}\s".format(re.escape(searcher)), line): | ||
1002 | 996 | print("# {}".format(line), end="") | ||
1003 | 997 | else: | ||
1004 | 998 | print(line, end="") | ||
1005 | 999 | |||
1006 | 1000 | def import_key(self, key: str) -> None: | ||
1007 | 1001 | """Import an ASCII Armor key. | ||
1008 | 1002 | |||
1009 | 1003 | A Radix64 format keyid is also supported for backwards | ||
1010 | 1004 | compatibility. In this case Ubuntu keyserver will be | ||
1011 | 1005 | queried for a key via HTTPS by its keyid. This method | ||
1012 | 1006 | is less preferrable because https proxy servers may | ||
1013 | 1007 | require traffic decryption which is equivalent to a | ||
1014 | 1008 | man-in-the-middle attack (a proxy server impersonates | ||
1015 | 1009 | keyserver TLS certificates and has to be explicitly | ||
1016 | 1010 | trusted by the system). | ||
1017 | 1011 | |||
1018 | 1012 | Args: | ||
1019 | 1013 | key: A GPG key in ASCII armor format, | ||
1020 | 1014 | including BEGIN and END markers or a keyid. | ||
1021 | 1015 | |||
1022 | 1016 | Raises: | ||
1023 | 1017 | GPGKeyError if the key could not be imported | ||
1024 | 1018 | """ | ||
1025 | 1019 | key = key.strip() | ||
1026 | 1020 | if "-" in key or "\n" in key: | ||
1027 | 1021 | # Send everything not obviously a keyid to GPG to import, as | ||
1028 | 1022 | # we trust its validation better than our own. eg. handling | ||
1029 | 1023 | # comments before the key. | ||
1030 | 1024 | logger.debug("PGP key found (looks like ASCII Armor format)") | ||
1031 | 1025 | if ( | ||
1032 | 1026 | "-----BEGIN PGP PUBLIC KEY BLOCK-----" in key | ||
1033 | 1027 | and "-----END PGP PUBLIC KEY BLOCK-----" in key | ||
1034 | 1028 | ): | ||
1035 | 1029 | logger.debug("Writing provided PGP key in the binary format") | ||
1036 | 1030 | key_bytes = key.encode("utf-8") | ||
1037 | 1031 | key_name = self._get_keyid_by_gpg_key(key_bytes) | ||
1038 | 1032 | key_gpg = self._dearmor_gpg_key(key_bytes) | ||
1039 | 1033 | self._gpg_key_filename = "/etc/apt/trusted.gpg.d/{}.gpg".format(key_name) | ||
1040 | 1034 | self._write_apt_gpg_keyfile(key_name=self._gpg_key_filename, key_material=key_gpg) | ||
1041 | 1035 | else: | ||
1042 | 1036 | raise GPGKeyError("ASCII armor markers missing from GPG key") | ||
1043 | 1037 | else: | ||
1044 | 1038 | logger.warning( | ||
1045 | 1039 | "PGP key found (looks like Radix64 format). " | ||
1046 | 1040 | "SECURELY importing PGP key from keyserver; " | ||
1047 | 1041 | "full key not provided." | ||
1048 | 1042 | ) | ||
1049 | 1043 | # as of bionic add-apt-repository uses curl with an HTTPS keyserver URL | ||
1050 | 1044 | # to retrieve GPG keys. `apt-key adv` command is deprecated as is | ||
1051 | 1045 | # apt-key in general as noted in its manpage. See lp:1433761 for more | ||
1052 | 1046 | # history. Instead, /etc/apt/trusted.gpg.d is used directly to drop | ||
1053 | 1047 | # gpg | ||
1054 | 1048 | key_asc = self._get_key_by_keyid(key) | ||
1055 | 1049 | # write the key in GPG format so that apt-key list shows it | ||
1056 | 1050 | key_gpg = self._dearmor_gpg_key(key_asc.encode("utf-8")) | ||
1057 | 1051 | self._gpg_key_filename = "/etc/apt/trusted.gpg.d/{}.gpg".format(key) | ||
1058 | 1052 | self._write_apt_gpg_keyfile(key_name=key, key_material=key_gpg) | ||
1059 | 1053 | |||
1060 | 1054 | @staticmethod | ||
1061 | 1055 | def _get_keyid_by_gpg_key(key_material: bytes) -> str: | ||
1062 | 1056 | """Get a GPG key fingerprint by GPG key material. | ||
1063 | 1057 | |||
1064 | 1058 | Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded | ||
1065 | 1059 | or binary GPG key material. Can be used, for example, to generate file | ||
1066 | 1060 | names for keys passed via charm options. | ||
1067 | 1061 | """ | ||
1068 | 1062 | # Use the same gpg command for both Xenial and Bionic | ||
1069 | 1063 | cmd = ["gpg", "--with-colons", "--with-fingerprint"] | ||
1070 | 1064 | ps = subprocess.run( | ||
1071 | 1065 | cmd, | ||
1072 | 1066 | stdout=PIPE, | ||
1073 | 1067 | stderr=PIPE, | ||
1074 | 1068 | input=key_material, | ||
1075 | 1069 | ) | ||
1076 | 1070 | out, err = ps.stdout.decode(), ps.stderr.decode() | ||
1077 | 1071 | if "gpg: no valid OpenPGP data found." in err: | ||
1078 | 1072 | raise GPGKeyError("Invalid GPG key material provided") | ||
1079 | 1073 | # from gnupg2 docs: fpr :: Fingerprint (fingerprint is in field 10) | ||
1080 | 1074 | return re.search(r"^fpr:{9}([0-9A-F]{40}):$", out, re.MULTILINE).group(1) | ||
1081 | 1075 | |||
1082 | 1076 | @staticmethod | ||
1083 | 1077 | def _get_key_by_keyid(keyid: str) -> str: | ||
1084 | 1078 | """Get a key via HTTPS from the Ubuntu keyserver. | ||
1085 | 1079 | |||
1086 | 1080 | Different key ID formats are supported by SKS keyservers (the longer ones | ||
1087 | 1081 | are more secure, see "dead beef attack" and https://evil32.com/). Since | ||
1088 | 1082 | HTTPS is used, if SSLBump-like HTTPS proxies are in place, they will | ||
1089 | 1083 | impersonate keyserver.ubuntu.com and generate a certificate with | ||
1090 | 1084 | keyserver.ubuntu.com in the CN field or in SubjAltName fields of a | ||
1091 | 1085 | certificate. If such proxy behavior is expected it is necessary to add the | ||
1092 | 1086 | CA certificate chain containing the intermediate CA of the SSLBump proxy to | ||
1093 | 1087 | every machine that this code runs on via ca-certs cloud-init directive (via | ||
1094 | 1088 | cloudinit-userdata model-config) or via other means (such as through a | ||
1095 | 1089 | custom charm option). Also note that DNS resolution for the hostname in a | ||
1096 | 1090 | URL is done at a proxy server - not at the client side. | ||
1097 | 1091 | 8-digit (32 bit) key ID | ||
1098 | 1092 | https://keyserver.ubuntu.com/pks/lookup?search=0x4652B4E6 | ||
1099 | 1093 | 16-digit (64 bit) key ID | ||
1100 | 1094 | https://keyserver.ubuntu.com/pks/lookup?search=0x6E85A86E4652B4E6 | ||
1101 | 1095 | 40-digit key ID: | ||
1102 | 1096 | https://keyserver.ubuntu.com/pks/lookup?search=0x35F77D63B5CEC106C577ED856E85A86E4652B4E6 | ||
1103 | 1097 | |||
1104 | 1098 | Args: | ||
1105 | 1099 | keyid: An 8, 16 or 40 hex digit keyid to find a key for | ||
1106 | 1100 | |||
1107 | 1101 | Returns: | ||
1108 | 1102 | A string contining key material for the specified GPG key id | ||
1109 | 1103 | |||
1110 | 1104 | |||
1111 | 1105 | Raises: | ||
1112 | 1106 | subprocess.CalledProcessError | ||
1113 | 1107 | """ | ||
1114 | 1108 | # options=mr - machine-readable output (disables html wrappers) | ||
1115 | 1109 | keyserver_url = ( | ||
1116 | 1110 | "https://keyserver.ubuntu.com" "/pks/lookup?op=get&options=mr&exact=on&search=0x{}" | ||
1117 | 1111 | ) | ||
1118 | 1112 | curl_cmd = ["curl", keyserver_url.format(keyid)] | ||
1119 | 1113 | # use proxy server settings in order to retrieve the key | ||
1120 | 1114 | return check_output(curl_cmd).decode() | ||
1121 | 1115 | |||
1122 | 1116 | @staticmethod | ||
1123 | 1117 | def _dearmor_gpg_key(key_asc: bytes) -> bytes: | ||
1124 | 1118 | """Converts a GPG key in the ASCII armor format to the binary format. | ||
1125 | 1119 | |||
1126 | 1120 | Args: | ||
1127 | 1121 | key_asc: A GPG key in ASCII armor format. | ||
1128 | 1122 | |||
1129 | 1123 | Returns: | ||
1130 | 1124 | A GPG key in binary format as a string | ||
1131 | 1125 | |||
1132 | 1126 | Raises: | ||
1133 | 1127 | GPGKeyError | ||
1134 | 1128 | """ | ||
1135 | 1129 | ps = subprocess.run(["gpg", "--dearmor"], stdout=PIPE, stderr=PIPE, input=key_asc) | ||
1136 | 1130 | out, err = ps.stdout, ps.stderr.decode() | ||
1137 | 1131 | if "gpg: no valid OpenPGP data found." in err: | ||
1138 | 1132 | raise GPGKeyError( | ||
1139 | 1133 | "Invalid GPG key material. Check your network setup" | ||
1140 | 1134 | " (MTU, routing, DNS) and/or proxy server settings" | ||
1141 | 1135 | " as well as destination keyserver status." | ||
1142 | 1136 | ) | ||
1143 | 1137 | else: | ||
1144 | 1138 | return out | ||
1145 | 1139 | |||
1146 | 1140 | @staticmethod | ||
1147 | 1141 | def _write_apt_gpg_keyfile(key_name: str, key_material: bytes) -> None: | ||
1148 | 1142 | """Writes GPG key material into a file at a provided path. | ||
1149 | 1143 | |||
1150 | 1144 | Args: | ||
1151 | 1145 | key_name: A key name to use for a key file (could be a fingerprint) | ||
1152 | 1146 | key_material: A GPG key material (binary) | ||
1153 | 1147 | """ | ||
1154 | 1148 | with open(key_name, "wb") as keyf: | ||
1155 | 1149 | keyf.write(key_material) | ||
1156 | 1150 | |||
1157 | 1151 | |||
1158 | 1152 | class RepositoryMapping(Mapping): | ||
1159 | 1153 | """An representation of known repositories. | ||
1160 | 1154 | |||
1161 | 1155 | Instantiation of `RepositoryMapping` will iterate through the | ||
1162 | 1156 | filesystem, parse out repository files in `/etc/apt/...`, and create | ||
1163 | 1157 | `DebianRepository` objects in this list. | ||
1164 | 1158 | |||
1165 | 1159 | Typical usage: | ||
1166 | 1160 | |||
1167 | 1161 | repositories = apt.RepositoryMapping() | ||
1168 | 1162 | repositories.add(DebianRepository( | ||
1169 | 1163 | enabled=True, repotype="deb", uri="https://example.com", release="focal", | ||
1170 | 1164 | groups=["universe"] | ||
1171 | 1165 | )) | ||
1172 | 1166 | """ | ||
1173 | 1167 | |||
1174 | 1168 | def __init__(self): | ||
1175 | 1169 | self._repository_map = {} | ||
1176 | 1170 | # Repositories that we're adding -- used to implement mode param | ||
1177 | 1171 | self.default_file = "/etc/apt/sources.list" | ||
1178 | 1172 | |||
1179 | 1173 | # read sources.list if it exists | ||
1180 | 1174 | if os.path.isfile(self.default_file): | ||
1181 | 1175 | self.load(self.default_file) | ||
1182 | 1176 | |||
1183 | 1177 | # read sources.list.d | ||
1184 | 1178 | for file in glob.iglob("/etc/apt/sources.list.d/*.list"): | ||
1185 | 1179 | self.load(file) | ||
1186 | 1180 | |||
1187 | 1181 | def __contains__(self, key: str) -> bool: | ||
1188 | 1182 | """Magic method for checking presence of repo in mapping.""" | ||
1189 | 1183 | return key in self._repository_map | ||
1190 | 1184 | |||
1191 | 1185 | def __len__(self) -> int: | ||
1192 | 1186 | """Return number of repositories in map.""" | ||
1193 | 1187 | return len(self._repository_map) | ||
1194 | 1188 | |||
1195 | 1189 | def __iter__(self) -> Iterable[DebianRepository]: | ||
1196 | 1190 | """Iterator magic method for RepositoryMapping.""" | ||
1197 | 1191 | return iter(self._repository_map.values()) | ||
1198 | 1192 | |||
1199 | 1193 | def __getitem__(self, repository_uri: str) -> DebianRepository: | ||
1200 | 1194 | """Return a given `DebianRepository`.""" | ||
1201 | 1195 | return self._repository_map[repository_uri] | ||
1202 | 1196 | |||
1203 | 1197 | def __setitem__(self, repository_uri: str, repository: DebianRepository) -> None: | ||
1204 | 1198 | """Add a `DebianRepository` to the cache.""" | ||
1205 | 1199 | self._repository_map[repository_uri] = repository | ||
1206 | 1200 | |||
1207 | 1201 | def load(self, filename: str): | ||
1208 | 1202 | """Load a repository source file into the cache. | ||
1209 | 1203 | |||
1210 | 1204 | Args: | ||
1211 | 1205 | filename: the path to the repository file | ||
1212 | 1206 | """ | ||
1213 | 1207 | parsed = [] | ||
1214 | 1208 | skipped = [] | ||
1215 | 1209 | with open(filename, "r") as f: | ||
1216 | 1210 | for n, line in enumerate(f): | ||
1217 | 1211 | try: | ||
1218 | 1212 | repo = self._parse(line, filename) | ||
1219 | 1213 | except InvalidSourceError: | ||
1220 | 1214 | skipped.append(n) | ||
1221 | 1215 | else: | ||
1222 | 1216 | repo_identifier = "{}-{}-{}".format(repo.repotype, repo.uri, repo.release) | ||
1223 | 1217 | self._repository_map[repo_identifier] = repo | ||
1224 | 1218 | parsed.append(n) | ||
1225 | 1219 | logger.debug("parsed repo: '%s'", repo_identifier) | ||
1226 | 1220 | |||
1227 | 1221 | if skipped: | ||
1228 | 1222 | skip_list = ", ".join(str(s) for s in skipped) | ||
1229 | 1223 | logger.debug("skipped the following lines in file '%s': %s", filename, skip_list) | ||
1230 | 1224 | |||
1231 | 1225 | if parsed: | ||
1232 | 1226 | logger.info("parsed %d apt package repositories", len(parsed)) | ||
1233 | 1227 | else: | ||
1234 | 1228 | raise InvalidSourceError("all repository lines in '{}' were invalid!".format(filename)) | ||
1235 | 1229 | |||
1236 | 1230 | @staticmethod | ||
1237 | 1231 | def _parse(line: str, filename: str) -> DebianRepository: | ||
1238 | 1232 | """Parse a line in a sources.list file. | ||
1239 | 1233 | |||
1240 | 1234 | Args: | ||
1241 | 1235 | line: a single line from `load` to parse | ||
1242 | 1236 | filename: the filename being read | ||
1243 | 1237 | |||
1244 | 1238 | Raises: | ||
1245 | 1239 | InvalidSourceError if the source type is unknown | ||
1246 | 1240 | """ | ||
1247 | 1241 | enabled = True | ||
1248 | 1242 | repotype = uri = release = gpg_key = "" | ||
1249 | 1243 | options = {} | ||
1250 | 1244 | groups = [] | ||
1251 | 1245 | |||
1252 | 1246 | line = line.strip() | ||
1253 | 1247 | if line.startswith("#"): | ||
1254 | 1248 | enabled = False | ||
1255 | 1249 | line = line[1:] | ||
1256 | 1250 | |||
1257 | 1251 | # Check for "#" in the line and treat a part after it as a comment then strip it off. | ||
1258 | 1252 | i = line.find("#") | ||
1259 | 1253 | if i > 0: | ||
1260 | 1254 | line = line[:i] | ||
1261 | 1255 | |||
1262 | 1256 | # Split a source into substrings to initialize a new repo. | ||
1263 | 1257 | source = line.strip() | ||
1264 | 1258 | if source: | ||
1265 | 1259 | # Match any repo options, and get a dict representation. | ||
1266 | 1260 | for v in re.findall(OPTIONS_MATCHER, source): | ||
1267 | 1261 | opts = dict(o.split("=") for o in v.strip("[]").split()) | ||
1268 | 1262 | # Extract the 'signed-by' option for the gpg_key | ||
1269 | 1263 | gpg_key = opts.pop("signed-by", "") | ||
1270 | 1264 | options = opts | ||
1271 | 1265 | |||
1272 | 1266 | # Remove any options from the source string and split the string into chunks | ||
1273 | 1267 | source = re.sub(OPTIONS_MATCHER, "", source) | ||
1274 | 1268 | chunks = source.split() | ||
1275 | 1269 | |||
1276 | 1270 | # Check we've got a valid list of chunks | ||
1277 | 1271 | if len(chunks) < 3 or chunks[0] not in VALID_SOURCE_TYPES: | ||
1278 | 1272 | raise InvalidSourceError("An invalid sources line was found in %s!", filename) | ||
1279 | 1273 | |||
1280 | 1274 | repotype = chunks[0] | ||
1281 | 1275 | uri = chunks[1] | ||
1282 | 1276 | release = chunks[2] | ||
1283 | 1277 | groups = chunks[3:] | ||
1284 | 1278 | |||
1285 | 1279 | return DebianRepository( | ||
1286 | 1280 | enabled, repotype, uri, release, groups, filename, gpg_key, options | ||
1287 | 1281 | ) | ||
1288 | 1282 | else: | ||
1289 | 1283 | raise InvalidSourceError("An invalid sources line was found in %s!", filename) | ||
1290 | 1284 | |||
1291 | 1285 | def add(self, repo: DebianRepository, default_filename: Optional[bool] = False) -> None: | ||
1292 | 1286 | """Add a new repository to the system. | ||
1293 | 1287 | |||
1294 | 1288 | Args: | ||
1295 | 1289 | repo: a `DebianRepository` object | ||
1296 | 1290 | default_filename: an (Optional) filename if the default is not desirable | ||
1297 | 1291 | """ | ||
1298 | 1292 | new_filename = "{}-{}.list".format( | ||
1299 | 1293 | DebianRepository.prefix_from_uri(repo.uri), repo.release.replace("/", "-") | ||
1300 | 1294 | ) | ||
1301 | 1295 | |||
1302 | 1296 | fname = repo.filename or new_filename | ||
1303 | 1297 | |||
1304 | 1298 | options = repo.options if repo.options else {} | ||
1305 | 1299 | if repo.gpg_key: | ||
1306 | 1300 | options["signed-by"] = repo.gpg_key | ||
1307 | 1301 | |||
1308 | 1302 | with open(fname, "wb") as f: | ||
1309 | 1303 | f.write( | ||
1310 | 1304 | ( | ||
1311 | 1305 | "{}".format("#" if not repo.enabled else "") | ||
1312 | 1306 | + "{} {}{} ".format(repo.repotype, repo.make_options_string(), repo.uri) | ||
1313 | 1307 | + "{} {}\n".format(repo.release, " ".join(repo.groups)) | ||
1314 | 1308 | ).encode("utf-8") | ||
1315 | 1309 | ) | ||
1316 | 1310 | |||
1317 | 1311 | self._repository_map["{}-{}-{}".format(repo.repotype, repo.uri, repo.release)] = repo | ||
1318 | 1312 | |||
1319 | 1313 | def disable(self, repo: DebianRepository) -> None: | ||
1320 | 1314 | """Remove a repository. Disable by default. | ||
1321 | 1315 | |||
1322 | 1316 | Args: | ||
1323 | 1317 | repo: a `DebianRepository` to disable | ||
1324 | 1318 | """ | ||
1325 | 1319 | searcher = "{} {}{} {}".format( | ||
1326 | 1320 | repo.repotype, repo.make_options_string(), repo.uri, repo.release | ||
1327 | 1321 | ) | ||
1328 | 1322 | |||
1329 | 1323 | for line in fileinput.input(repo.filename, inplace=True): | ||
1330 | 1324 | if re.match(r"^{}\s".format(re.escape(searcher)), line): | ||
1331 | 1325 | print("# {}".format(line), end="") | ||
1332 | 1326 | else: | ||
1333 | 1327 | print(line, end="") | ||
1334 | 1328 | |||
1335 | 1329 | self._repository_map["{}-{}-{}".format(repo.repotype, repo.uri, repo.release)] = repo | ||
1336 | diff --git a/run_tests b/run_tests | |||
1337 | index 362a995..ef9f058 100755 | |||
1338 | --- a/run_tests | |||
1339 | +++ b/run_tests | |||
1340 | @@ -1,17 +1,18 @@ | |||
1341 | 1 | #!/bin/sh -e | 1 | #!/bin/sh -e |
1342 | 2 | # Copyright 2021 Canonical Ltd. | 2 | # Copyright 2021 Canonical Ltd. |
1343 | 3 | # See LICENSE file for licensing details. | 3 | # See LICENSE file for licensing details. |
1344 | 4 | PYTHONPATH_INCLUDES="src:lib" | ||
1345 | 4 | 5 | ||
1346 | 5 | if [ -z "$VIRTUAL_ENV" -a -d venv/ ]; then | 6 | if [ -z "$VIRTUAL_ENV" -a -d venv/ ]; then |
1347 | 6 | . venv/bin/activate | 7 | . venv/bin/activate |
1348 | 7 | fi | 8 | fi |
1349 | 8 | 9 | ||
1350 | 9 | if [ -z "$PYTHONPATH" ]; then | 10 | if [ -z "$PYTHONPATH" ]; then |
1352 | 10 | export PYTHONPATH=src | 11 | export PYTHONPATH="$PYTHONPATH_INCLUDES" |
1353 | 11 | else | 12 | else |
1355 | 12 | export PYTHONPATH="src:$PYTHONPATH" | 13 | export PYTHONPATH="$PYTHONPATH_INCLUDES:$PYTHONPATH" |
1356 | 13 | fi | 14 | fi |
1357 | 14 | 15 | ||
1359 | 15 | flake8 | 16 | flake8 --extend-exclude operator_libs_linux |
1360 | 16 | coverage run --source=src -m unittest -v "$@" | 17 | coverage run --source=src -m unittest -v "$@" |
1361 | 17 | coverage report -m | 18 | coverage report -m |
1362 | diff --git a/src/charm.py b/src/charm.py | |||
1363 | index 34878c0..84362d3 100755 | |||
1364 | --- a/src/charm.py | |||
1365 | +++ b/src/charm.py | |||
1366 | @@ -10,6 +10,7 @@ import os | |||
1367 | 10 | import subprocess | 10 | import subprocess |
1368 | 11 | import yaml | 11 | import yaml |
1369 | 12 | 12 | ||
1370 | 13 | from charms.operator_libs_linux.v0 import apt | ||
1371 | 13 | from ops.charm import CharmBase | 14 | from ops.charm import CharmBase |
1372 | 14 | from ops.framework import StoredState | 15 | from ops.framework import StoredState |
1373 | 15 | from ops.main import main | 16 | from ops.main import main |
1374 | @@ -29,17 +30,6 @@ def remove_ppa(ppa, env): | |||
1375 | 29 | subprocess.check_call(["add-apt-repository", "--remove", "--yes", ppa], env=env) | 30 | subprocess.check_call(["add-apt-repository", "--remove", "--yes", ppa], env=env) |
1376 | 30 | 31 | ||
1377 | 31 | 32 | ||
1378 | 32 | def install_package(package): | ||
1379 | 33 | """Install specified apt package (after performing an apt update)""" | ||
1380 | 34 | subprocess.check_call(["apt", "update"]) | ||
1381 | 35 | subprocess.check_call(["apt", "install", "--yes", "--quiet", package]) | ||
1382 | 36 | |||
1383 | 37 | |||
1384 | 38 | def remove_package(package): | ||
1385 | 39 | """Remove specified apt package""" | ||
1386 | 40 | subprocess.check_call(["apt", "remove", "--yes", "--quiet", package]) | ||
1387 | 41 | |||
1388 | 42 | |||
1389 | 43 | def update_configuration(contract_url): | 33 | def update_configuration(contract_url): |
1390 | 44 | """Write the contract_url to the uaclient configuration file""" | 34 | """Write the contract_url to the uaclient configuration file""" |
1391 | 45 | with open("/etc/ubuntu-advantage/uaclient.conf", "r+") as f: | 35 | with open("/etc/ubuntu-advantage/uaclient.conf", "r+") as f: |
1392 | @@ -137,9 +127,9 @@ class UbuntuAdvantageCharm(CharmBase): | |||
1393 | 137 | """Install apt package if necessary""" | 127 | """Install apt package if necessary""" |
1394 | 138 | if self._state.package_needs_installing: | 128 | if self._state.package_needs_installing: |
1395 | 139 | logger.info("Removing package ubuntu-advantage-tools") | 129 | logger.info("Removing package ubuntu-advantage-tools") |
1397 | 140 | remove_package("ubuntu-advantage-tools") | 130 | apt.remove_package("ubuntu-advantage-tools") |
1398 | 141 | logger.info("Installing package ubuntu-advantage-tools") | 131 | logger.info("Installing package ubuntu-advantage-tools") |
1400 | 142 | install_package("ubuntu-advantage-tools") | 132 | apt.add_package("ubuntu-advantage-tools", update_cache=True) |
1401 | 143 | self._state.package_needs_installing = False | 133 | self._state.package_needs_installing = False |
1402 | 144 | 134 | ||
1403 | 145 | def _handle_subscription_state(self): | 135 | def _handle_subscription_state(self): |
1404 | diff --git a/tests/test_charm.py b/tests/test_charm.py | |||
1405 | index f55d844..37da2a7 100644 | |||
1406 | --- a/tests/test_charm.py | |||
1407 | +++ b/tests/test_charm.py | |||
1408 | @@ -80,7 +80,8 @@ class TestCharm(TestCase): | |||
1409 | 80 | "check_call": patch("subprocess.check_call").start(), | 80 | "check_call": patch("subprocess.check_call").start(), |
1410 | 81 | "check_output": patch("subprocess.check_output").start(), | 81 | "check_output": patch("subprocess.check_output").start(), |
1411 | 82 | "open": patch("builtins.open").start(), | 82 | "open": patch("builtins.open").start(), |
1413 | 83 | "environ": patch.dict("os.environ", clear=True).start() | 83 | "environ": patch.dict("os.environ", clear=True).start(), |
1414 | 84 | "apt": patch("charm.apt").start() | ||
1415 | 84 | } | 85 | } |
1416 | 85 | self.mocks["check_output"].side_effect = [ | 86 | self.mocks["check_output"].side_effect = [ |
1417 | 86 | STATUS_DETACHED | 87 | STATUS_DETACHED |
1418 | @@ -100,25 +101,21 @@ class TestCharm(TestCase): | |||
1419 | 100 | 101 | ||
1420 | 101 | def test_config_changed_ppa_new(self): | 102 | def test_config_changed_ppa_new(self): |
1421 | 102 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) | 103 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) |
1423 | 103 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 104 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1424 | 104 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 105 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1425 | 105 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), | 106 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), |
1426 | 106 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1427 | 107 | call(["apt", "update"]), | ||
1428 | 108 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1429 | 109 | ])) | 107 | ])) |
1430 | 108 | self._assert_apt_calls() | ||
1431 | 110 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") | 109 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") |
1432 | 111 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 110 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1433 | 112 | 111 | ||
1434 | 113 | def test_config_changed_ppa_updated(self): | 112 | def test_config_changed_ppa_updated(self): |
1435 | 114 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) | 113 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) |
1437 | 115 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 114 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1438 | 116 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 115 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1439 | 117 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), | 116 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), |
1440 | 118 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1441 | 119 | call(["apt", "update"]), | ||
1442 | 120 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1443 | 121 | ])) | 117 | ])) |
1444 | 118 | self._assert_apt_calls() | ||
1445 | 122 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") | 119 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") |
1446 | 123 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 120 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1447 | 124 | 121 | ||
1448 | @@ -126,29 +123,26 @@ class TestCharm(TestCase): | |||
1449 | 126 | STATUS_DETACHED | 123 | STATUS_DETACHED |
1450 | 127 | ] | 124 | ] |
1451 | 128 | self.mocks["check_call"].reset_mock() | 125 | self.mocks["check_call"].reset_mock() |
1452 | 126 | self.mocks["apt"].reset_mock() | ||
1453 | 129 | self.harness.update_config({"ppa": "ppa:different-client/unstable"}) | 127 | self.harness.update_config({"ppa": "ppa:different-client/unstable"}) |
1455 | 130 | self.assertEqual(self.mocks["check_call"].call_count, 7) | 128 | self.assertEqual(self.mocks["check_call"].call_count, 4) |
1456 | 131 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 129 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1457 | 132 | call(["add-apt-repository", "--remove", "--yes", "ppa:ua-client/stable"], | 130 | call(["add-apt-repository", "--remove", "--yes", "ppa:ua-client/stable"], |
1458 | 133 | env=self.env), | 131 | env=self.env), |
1459 | 134 | call(["add-apt-repository", "--yes", "ppa:different-client/unstable"], | 132 | call(["add-apt-repository", "--yes", "ppa:different-client/unstable"], |
1460 | 135 | env=self.env), | 133 | env=self.env), |
1461 | 136 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1462 | 137 | call(["apt", "update"]), | ||
1463 | 138 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1464 | 139 | ])) | 134 | ])) |
1465 | 135 | self._assert_apt_calls() | ||
1466 | 140 | self.assertEqual(self.harness.charm._state.ppa, "ppa:different-client/unstable") | 136 | self.assertEqual(self.harness.charm._state.ppa, "ppa:different-client/unstable") |
1467 | 141 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 137 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1468 | 142 | 138 | ||
1469 | 143 | def test_config_changed_ppa_unmodified(self): | 139 | def test_config_changed_ppa_unmodified(self): |
1470 | 144 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) | 140 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) |
1472 | 145 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 141 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1473 | 146 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 142 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1474 | 147 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), | 143 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), |
1475 | 148 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1476 | 149 | call(["apt", "update"]), | ||
1477 | 150 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1478 | 151 | ])) | 144 | ])) |
1479 | 145 | self._assert_apt_calls() | ||
1480 | 152 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") | 146 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") |
1481 | 153 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 147 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1482 | 154 | 148 | ||
1483 | @@ -165,30 +159,27 @@ class TestCharm(TestCase): | |||
1484 | 165 | 159 | ||
1485 | 166 | def test_config_changed_ppa_unset(self): | 160 | def test_config_changed_ppa_unset(self): |
1486 | 167 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) | 161 | self.harness.update_config({"ppa": "ppa:ua-client/stable"}) |
1488 | 168 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 162 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1489 | 169 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 163 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1490 | 170 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), | 164 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), |
1491 | 171 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1492 | 172 | call(["apt", "update"]), | ||
1493 | 173 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1494 | 174 | ])) | 165 | ])) |
1495 | 166 | self._assert_apt_calls() | ||
1496 | 175 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") | 167 | self.assertEqual(self.harness.charm._state.ppa, "ppa:ua-client/stable") |
1497 | 176 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 168 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1498 | 177 | 169 | ||
1499 | 178 | self.mocks["check_call"].reset_mock() | 170 | self.mocks["check_call"].reset_mock() |
1500 | 179 | self.mocks["check_output"].reset_mock() | 171 | self.mocks["check_output"].reset_mock() |
1501 | 172 | self.mocks["apt"].reset_mock() | ||
1502 | 180 | self.mocks["check_output"].side_effect = [ | 173 | self.mocks["check_output"].side_effect = [ |
1503 | 181 | STATUS_DETACHED | 174 | STATUS_DETACHED |
1504 | 182 | ] | 175 | ] |
1505 | 183 | self.harness.update_config({"ppa": ""}) | 176 | self.harness.update_config({"ppa": ""}) |
1507 | 184 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 177 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1508 | 185 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 178 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1509 | 186 | call(["add-apt-repository", "--remove", "--yes", "ppa:ua-client/stable"], | 179 | call(["add-apt-repository", "--remove", "--yes", "ppa:ua-client/stable"], |
1510 | 187 | env=self.env), | 180 | env=self.env), |
1511 | 188 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1512 | 189 | call(["apt", "update"]), | ||
1513 | 190 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1514 | 191 | ])) | 181 | ])) |
1515 | 182 | self._assert_apt_calls() | ||
1516 | 192 | self.assertIsNone(self.harness.charm._state.ppa) | 183 | self.assertIsNone(self.harness.charm._state.ppa) |
1517 | 193 | self.assertFalse(self.harness.charm._state.package_needs_installing) | 184 | self.assertFalse(self.harness.charm._state.package_needs_installing) |
1518 | 194 | 185 | ||
1519 | @@ -232,14 +223,12 @@ class TestCharm(TestCase): | |||
1520 | 232 | STATUS_ATTACHED | 223 | STATUS_ATTACHED |
1521 | 233 | ] | 224 | ] |
1522 | 234 | self.harness.update_config({"token": "test-token"}) | 225 | self.harness.update_config({"token": "test-token"}) |
1524 | 235 | self.assertEqual(self.mocks["check_call"].call_count, 6) | 226 | self.assertEqual(self.mocks["check_call"].call_count, 3) |
1525 | 236 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ | 227 | self.mocks["check_call"].assert_has_calls(self._add_ua_proxy_setup_calls([ |
1526 | 237 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), | 228 | call(["add-apt-repository", "--yes", "ppa:ua-client/stable"], env=self.env), |
1527 | 238 | call(["apt", "remove", "--yes", "--quiet", "ubuntu-advantage-tools"]), | ||
1528 | 239 | call(["apt", "update"]), | ||
1529 | 240 | call(["apt", "install", "--yes", "--quiet", "ubuntu-advantage-tools"]) | ||
1530 | 241 | ])) | 229 | ])) |
1531 | 242 | self.mocks["open"].assert_called_with("/etc/ubuntu-advantage/uaclient.conf", "r+") | 230 | self.mocks["open"].assert_called_with("/etc/ubuntu-advantage/uaclient.conf", "r+") |
1532 | 231 | self._assert_apt_calls() | ||
1533 | 243 | handle = self.mocks["open"]() | 232 | handle = self.mocks["open"]() |
1534 | 244 | expected = dedent("""\ | 233 | expected = dedent("""\ |
1535 | 245 | contract_url: https://contracts.canonical.com | 234 | contract_url: https://contracts.canonical.com |
1536 | @@ -505,3 +494,12 @@ class TestCharm(TestCase): | |||
1537 | 505 | ), | 494 | ), |
1538 | 506 | ] | 495 | ] |
1539 | 507 | return call_list + proxy_calls if append else proxy_calls + call_list | 496 | return call_list + proxy_calls if append else proxy_calls + call_list |
1540 | 497 | |||
1541 | 498 | def _assert_apt_calls(self): | ||
1542 | 499 | """Helper to run the assertions for apt install/remove""" | ||
1543 | 500 | self.mocks["apt"].remove_package.assert_called_once_with( | ||
1544 | 501 | "ubuntu-advantage-tools" | ||
1545 | 502 | ) | ||
1546 | 503 | self.mocks["apt"].add_package.assert_called_once_with( | ||
1547 | 504 | "ubuntu-advantage-tools", update_cache=True | ||
1548 | 505 | ) |
This merge proposal is being monitored by mergebot. Change the status to Approved to merge.