| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2020, Silvie Chlupova <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: copr |
| 11 |
short_description: Manage one of the Copr repositories |
| 12 |
version_added: 2.0.0 |
| 13 |
description: This module can enable, disable or remove the specified repository. |
| 14 |
author: Silvie Chlupova (@schlupov) <[email protected]> |
| 15 |
requirements: |
| 16 |
- dnf |
| 17 |
- dnf-plugins-core |
| 18 |
notes: |
| 19 |
- Supports C(check_mode). |
| 20 |
extends_documentation_fragment: |
| 21 |
- community.general._attributes |
| 22 |
attributes: |
| 23 |
check_mode: |
| 24 |
support: full |
| 25 |
diff_mode: |
| 26 |
support: none |
| 27 |
options: |
| 28 |
host: |
| 29 |
description: The Copr host to work with. |
| 30 |
default: copr.fedorainfracloud.org |
| 31 |
type: str |
| 32 |
protocol: |
| 33 |
description: This indicate which protocol to use with the host. |
| 34 |
default: https |
| 35 |
type: str |
| 36 |
name: |
| 37 |
description: Copr directory name, for example C(@copr/copr-dev). |
| 38 |
required: true |
| 39 |
type: str |
| 40 |
state: |
| 41 |
description: |
| 42 |
- Whether to set this project as V(enabled), V(disabled), or V(absent). |
| 43 |
default: enabled |
| 44 |
type: str |
| 45 |
choices: [absent, enabled, disabled] |
| 46 |
chroot: |
| 47 |
description: |
| 48 |
- The name of the chroot that you want to enable/disable/remove in the project, for example V(epel-7-x86_64). Default |
| 49 |
chroot is determined by the operating system, version of the operating system, and architecture on which the module |
| 50 |
is run. |
| 51 |
type: str |
| 52 |
includepkgs: |
| 53 |
description: |
| 54 |
- List of packages to include in all operations. Inverse of O(excludepkgs), DNF will exclude any package in |
| 55 |
the repository that does not match this list. Matches a name or a glob. |
| 56 |
type: list |
| 57 |
elements: str |
| 58 |
version_added: 9.4.0 |
| 59 |
excludepkgs: |
| 60 |
description: List of packages in this repository to exclude from all operations. Matches a name or a glob. |
| 61 |
type: list |
| 62 |
elements: str |
| 63 |
version_added: 9.4.0 |
| 64 |
""" |
| 65 |
|
| 66 |
EXAMPLES = r""" |
| 67 |
- name: Enable project Test of the user schlupov |
| 68 |
community.general.copr: |
| 69 |
host: copr.fedorainfracloud.org |
| 70 |
state: enabled |
| 71 |
name: schlupov/Test |
| 72 |
chroot: fedora-31-x86_64 |
| 73 |
|
| 74 |
- name: Remove project integration_tests of the group copr |
| 75 |
community.general.copr: |
| 76 |
state: absent |
| 77 |
name: '@copr/integration_tests' |
| 78 |
|
| 79 |
- name: Install a repo where only packages starting with "python" that do not have i386 are seen by DNF |
| 80 |
community.general.copr: |
| 81 |
name: '@sample/repo' |
| 82 |
chroot: fedora-rawhide-{{ ansible_facts.architecture }} |
| 83 |
includepkgs: |
| 84 |
- 'python*' |
| 85 |
excludepkgs: |
| 86 |
- '*.i386' |
| 87 |
""" |
| 88 |
|
| 89 |
RETURN = r""" |
| 90 |
repo_filename: |
| 91 |
description: The name of the repo file in which the copr project information is stored. |
| 92 |
returned: success |
| 93 |
type: str |
| 94 |
sample: _copr:copr.fedorainfracloud.org:group_copr:integration_tests.repo |
| 95 |
|
| 96 |
repo: |
| 97 |
description: Path to the project on the host. |
| 98 |
returned: success |
| 99 |
type: str |
| 100 |
sample: copr.fedorainfracloud.org/group_copr/integration_tests |
| 101 |
""" |
| 102 |
|
| 103 |
import os |
| 104 |
import stat |
| 105 |
import traceback |
| 106 |
from urllib.error import HTTPError |
| 107 |
|
| 108 |
try: |
| 109 |
import dnf |
| 110 |
import dnf.cli |
| 111 |
import dnf.repodict |
| 112 |
from dnf.conf import Conf |
| 113 |
|
| 114 |
HAS_DNF_PACKAGES = True |
| 115 |
DNF_IMP_ERR = None |
| 116 |
except ImportError: |
| 117 |
DNF_IMP_ERR = traceback.format_exc() |
| 118 |
HAS_DNF_PACKAGES = False |
| 119 |
|
| 120 |
from ansible.module_utils import distro |
| 121 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 122 |
from ansible.module_utils.common import respawn |
| 123 |
from ansible.module_utils.urls import open_url |
| 124 |
|
| 125 |
|
| 126 |
def _respawn_dnf(): |
| 127 |
if respawn.has_respawned(): |
| 128 |
return |
| 129 |
system_interpreters = ( |
| 130 |
"/usr/libexec/platform-python", |
| 131 |
"/usr/bin/python3", |
| 132 |
"/usr/bin/python", |
| 133 |
) |
| 134 |
interpreter = respawn.probe_interpreters_for_module(system_interpreters, "dnf") |
| 135 |
if interpreter: |
| 136 |
respawn.respawn_module(interpreter) |
| 137 |
|
| 138 |
|
| 139 |
class CoprModule: |
| 140 |
"""The class represents a copr module. |
| 141 |
|
| 142 |
The class contains methods that take care of the repository state of a project, |
| 143 |
whether the project is enabled, disabled or missing. |
| 144 |
""" |
| 145 |
|
| 146 |
ansible_module = None |
| 147 |
|
| 148 |
def __init__(self, host, name, state, protocol, chroot=None, check_mode=False): |
| 149 |
self.host = host |
| 150 |
self.name = name |
| 151 |
self.state = state |
| 152 |
self.chroot = chroot |
| 153 |
self.protocol = protocol |
| 154 |
self.check_mode = check_mode |
| 155 |
if not chroot: |
| 156 |
self.chroot = self.chroot_conf() |
| 157 |
else: |
| 158 |
self.chroot = chroot |
| 159 |
self.get_base() |
| 160 |
|
| 161 |
@property |
| 162 |
def short_chroot(self): |
| 163 |
"""str: Chroot (distribution-version-architecture) shorten to distribution-version.""" |
| 164 |
return self.chroot.rsplit("-", 1)[0] |
| 165 |
|
| 166 |
@property |
| 167 |
def arch(self): |
| 168 |
"""str: Target architecture.""" |
| 169 |
chroot_parts = self.chroot.split("-") |
| 170 |
return chroot_parts[-1] |
| 171 |
|
| 172 |
@property |
| 173 |
def user(self): |
| 174 |
"""str: Copr user (this can also be the name of the group).""" |
| 175 |
return self._sanitize_username(self.name.split("/")[0]) |
| 176 |
|
| 177 |
@property |
| 178 |
def project(self): |
| 179 |
"""str: The name of the copr project.""" |
| 180 |
return self.name.split("/")[1] |
| 181 |
|
| 182 |
@classmethod |
| 183 |
def need_root(cls): |
| 184 |
"""Check if the module was run as root.""" |
| 185 |
if os.geteuid() != 0: |
| 186 |
cls.raise_exception("This command has to be run under the root user.") |
| 187 |
|
| 188 |
@classmethod |
| 189 |
def get_base(cls): |
| 190 |
"""Initialize the configuration from dnf. |
| 191 |
|
| 192 |
Returns: |
| 193 |
An instance of the BaseCli class. |
| 194 |
""" |
| 195 |
cls.base = dnf.cli.cli.BaseCli(Conf()) |
| 196 |
return cls.base |
| 197 |
|
| 198 |
@classmethod |
| 199 |
def raise_exception(cls, msg): |
| 200 |
"""Raise either an ansible exception or a python exception. |
| 201 |
|
| 202 |
Args: |
| 203 |
msg: The message to be displayed when an exception is thrown. |
| 204 |
""" |
| 205 |
if cls.ansible_module: |
| 206 |
raise cls.ansible_module.fail_json(msg=msg, changed=False) |
| 207 |
raise Exception(msg) |
| 208 |
|
| 209 |
def _get(self, chroot): |
| 210 |
"""Send a get request to the server to obtain the necessary data. |
| 211 |
|
| 212 |
Args: |
| 213 |
chroot: Chroot in the form of distribution-version. |
| 214 |
|
| 215 |
Returns: |
| 216 |
Info about a repository and status code of the get request. |
| 217 |
""" |
| 218 |
repo_info = None |
| 219 |
url = f"{self.protocol}://{self.host}/coprs/{self.name}/repo/{chroot}/dnf.repo?arch={self.arch}" |
| 220 |
try: |
| 221 |
r = open_url(url) |
| 222 |
status_code = r.getcode() |
| 223 |
repo_info = r.read().decode("utf-8") |
| 224 |
except HTTPError as e: |
| 225 |
status_code = e.getcode() |
| 226 |
return repo_info, status_code |
| 227 |
|
| 228 |
def _download_repo_info(self): |
| 229 |
"""Download information about the repository. |
| 230 |
|
| 231 |
Returns: |
| 232 |
Information about the repository. |
| 233 |
""" |
| 234 |
distribution, version = self.short_chroot.split("-", 1) |
| 235 |
chroot = self.short_chroot |
| 236 |
while True: |
| 237 |
repo_info, status_code = self._get(chroot) |
| 238 |
if repo_info: |
| 239 |
return repo_info |
| 240 |
if distribution == "rhel": |
| 241 |
chroot = "centos-stream-8" |
| 242 |
distribution = "centos" |
| 243 |
elif distribution == "centos": |
| 244 |
if version == "stream-8": |
| 245 |
version = "8" |
| 246 |
elif version == "stream-9": |
| 247 |
version = "9" |
| 248 |
chroot = f"epel-{version}" |
| 249 |
distribution = "epel" |
| 250 |
else: |
| 251 |
if str(status_code) != "404": |
| 252 |
self.raise_exception("This repository does not have any builds yet so you cannot enable it now.") |
| 253 |
else: |
| 254 |
self.raise_exception(f"Chroot {self.chroot} does not exist in {self.name}") |
| 255 |
|
| 256 |
def _enable_repo(self, repo_filename_path, repo_content=None): |
| 257 |
"""Write information to a repo file. |
| 258 |
|
| 259 |
Args: |
| 260 |
repo_filename_path: Path to repository. |
| 261 |
repo_content: Repository information from the host. |
| 262 |
|
| 263 |
Returns: |
| 264 |
True, if the information in the repo file matches that stored on the host, |
| 265 |
False otherwise. |
| 266 |
""" |
| 267 |
if not repo_content: |
| 268 |
repo_content = self._download_repo_info() |
| 269 |
if self.ansible_module.params["includepkgs"]: |
| 270 |
includepkgs_value = ",".join(self.ansible_module.params["includepkgs"]) |
| 271 |
repo_content_strip = repo_content.rstrip( |
| 272 |
"\n" |
| 273 |
) # Python 3.11 does not allow backslash chars within f-string expressions |
| 274 |
repo_content = f"{repo_content_strip}\nincludepkgs={includepkgs_value}\n" |
| 275 |
if self.ansible_module.params["excludepkgs"]: |
| 276 |
excludepkgs_value = ",".join(self.ansible_module.params["excludepkgs"]) |
| 277 |
repo_content_strip = repo_content.rstrip( |
| 278 |
"\n" |
| 279 |
) # Python 3.11 does not allow backslash chars within f-string expressions |
| 280 |
repo_content = f"{repo_content_strip}\nexcludepkgs={excludepkgs_value}\n" |
| 281 |
if self._compare_repo_content(repo_filename_path, repo_content): |
| 282 |
return False |
| 283 |
if not self.check_mode: |
| 284 |
with open(repo_filename_path, "w+") as file: |
| 285 |
file.write(repo_content) |
| 286 |
os.chmod(repo_filename_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) |
| 287 |
return True |
| 288 |
|
| 289 |
def _get_repo_with_old_id(self): |
| 290 |
"""Try to get a repository with the old name.""" |
| 291 |
repo_id = f"{self.user}-{self.project}" |
| 292 |
if repo_id in self.base.repos and "_copr" in self.base.repos[repo_id].repofile: |
| 293 |
file_name = self.base.repos[repo_id].repofile.split("/")[-1] |
| 294 |
try: |
| 295 |
copr_hostname = file_name.rsplit(":", 2)[0].split(":", 1)[1] |
| 296 |
if copr_hostname != self.host: |
| 297 |
return None |
| 298 |
return file_name |
| 299 |
except IndexError: |
| 300 |
return file_name |
| 301 |
return None |
| 302 |
|
| 303 |
def _read_all_repos(self, repo_id=None): |
| 304 |
"""The method is used to initialize the base variable by |
| 305 |
repositories using the RepoReader class from dnf. |
| 306 |
|
| 307 |
Args: |
| 308 |
repo_id: Repo id of the repository we want to work with. |
| 309 |
""" |
| 310 |
reader = dnf.conf.read.RepoReader(self.base.conf, None) |
| 311 |
for repo in reader: |
| 312 |
try: |
| 313 |
if repo_id: |
| 314 |
if repo.id == repo_id: |
| 315 |
self.base.repos.add(repo) |
| 316 |
break |
| 317 |
else: |
| 318 |
self.base.repos.add(repo) |
| 319 |
except dnf.exceptions.ConfigError as e: |
| 320 |
self.raise_exception(str(e)) |
| 321 |
|
| 322 |
def _get_copr_repo(self): |
| 323 |
"""Return one specific repository from all repositories on the system. |
| 324 |
|
| 325 |
Returns: |
| 326 |
The repository that a user wants to enable, disable, or remove. |
| 327 |
""" |
| 328 |
repo_id = f"copr:{self.host}:{self.user}:{self.project}" |
| 329 |
if repo_id not in self.base.repos: |
| 330 |
if self._get_repo_with_old_id() is None: |
| 331 |
return None |
| 332 |
return self.base.repos[repo_id] |
| 333 |
|
| 334 |
def _disable_repo(self, repo_filename_path): |
| 335 |
"""Disable the repository. |
| 336 |
|
| 337 |
Args: |
| 338 |
repo_filename_path: Path to repository. |
| 339 |
|
| 340 |
Returns: |
| 341 |
False, if the repository is already disabled on the system, |
| 342 |
True otherwise. |
| 343 |
""" |
| 344 |
self._read_all_repos() |
| 345 |
repo = self._get_copr_repo() |
| 346 |
if repo is None: |
| 347 |
if self.check_mode: |
| 348 |
return True |
| 349 |
self._enable_repo(repo_filename_path) |
| 350 |
self._read_all_repos(f"copr:{self.host}:{self.user}:{self.project}") |
| 351 |
repo = self._get_copr_repo() |
| 352 |
for repo_id in repo.cfg.sections(): |
| 353 |
repo_content_api = self._download_repo_info() |
| 354 |
with open(repo_filename_path) as file: |
| 355 |
repo_content_file = file.read() |
| 356 |
if repo_content_file != repo_content_api: |
| 357 |
if not self.resolve_differences(repo_content_file, repo_content_api, repo_filename_path): |
| 358 |
return False |
| 359 |
if not self.check_mode: |
| 360 |
self.base.conf.write_raw_configfile( |
| 361 |
repo.repofile, |
| 362 |
repo_id, |
| 363 |
self.base.conf.substitutions, |
| 364 |
{"enabled": "0"}, |
| 365 |
) |
| 366 |
return True |
| 367 |
|
| 368 |
def resolve_differences(self, repo_content_file, repo_content_api, repo_filename_path): |
| 369 |
"""Detect differences between the contents of the repository stored on the |
| 370 |
system and the information about the repository on the server. |
| 371 |
|
| 372 |
Args: |
| 373 |
repo_content_file: The contents of the repository stored on the system. |
| 374 |
repo_content_api: The information about the repository from the server. |
| 375 |
repo_filename_path: Path to repository. |
| 376 |
|
| 377 |
Returns: |
| 378 |
False, if the contents of the repo file and the information on the server match, |
| 379 |
True otherwise. |
| 380 |
""" |
| 381 |
repo_file_lines = repo_content_file.split("\n") |
| 382 |
repo_api_lines = repo_content_api.split("\n") |
| 383 |
repo_api_lines.remove("enabled=1") |
| 384 |
if "enabled=0" in repo_file_lines: |
| 385 |
repo_file_lines.remove("enabled=0") |
| 386 |
if " ".join(repo_api_lines) == " ".join(repo_file_lines): |
| 387 |
return False |
| 388 |
if not self.check_mode: |
| 389 |
os.remove(repo_filename_path) |
| 390 |
self._enable_repo(repo_filename_path, repo_content_api) |
| 391 |
else: |
| 392 |
repo_file_lines.remove("enabled=1") |
| 393 |
if " ".join(repo_api_lines) != " ".join(repo_file_lines): |
| 394 |
if not self.check_mode: |
| 395 |
os.remove(repo_filename_path) |
| 396 |
self._enable_repo(repo_filename_path, repo_content_api) |
| 397 |
return True |
| 398 |
|
| 399 |
def _remove_repo(self): |
| 400 |
"""Remove the required repository. |
| 401 |
|
| 402 |
Returns: |
| 403 |
True, if the repository has been removed, False otherwise. |
| 404 |
""" |
| 405 |
self._read_all_repos() |
| 406 |
repo = self._get_copr_repo() |
| 407 |
if not repo: |
| 408 |
return False |
| 409 |
if not self.check_mode: |
| 410 |
try: |
| 411 |
os.remove(repo.repofile) |
| 412 |
except OSError as e: |
| 413 |
self.raise_exception(str(e)) |
| 414 |
return True |
| 415 |
|
| 416 |
def run(self): |
| 417 |
"""The method uses methods of the CoprModule class to change the state of the repository. |
| 418 |
|
| 419 |
Returns: |
| 420 |
Dictionary with information that the ansible module displays to the user at the end of the run. |
| 421 |
""" |
| 422 |
self.need_root() |
| 423 |
state = dict() |
| 424 |
repo_filename = f"_copr:{self.host}:{self.user}:{self.project}.repo" |
| 425 |
state["repo"] = f"{self.host}/{self.user}/{self.project}" |
| 426 |
state["repo_filename"] = repo_filename |
| 427 |
repo_filename_path = f"{self.base.conf.get_reposdir}/_copr:{self.host}:{self.user}:{self.project}.repo" |
| 428 |
if self.state == "enabled": |
| 429 |
enabled = self._enable_repo(repo_filename_path) |
| 430 |
state["msg"] = "enabled" |
| 431 |
state["state"] = bool(enabled) |
| 432 |
elif self.state == "disabled": |
| 433 |
disabled = self._disable_repo(repo_filename_path) |
| 434 |
state["msg"] = "disabled" |
| 435 |
state["state"] = bool(disabled) |
| 436 |
elif self.state == "absent": |
| 437 |
removed = self._remove_repo() |
| 438 |
state["msg"] = "absent" |
| 439 |
state["state"] = bool(removed) |
| 440 |
return state |
| 441 |
|
| 442 |
@staticmethod |
| 443 |
def _compare_repo_content(repo_filename_path, repo_content_api): |
| 444 |
"""Compare the contents of the stored repository with the information from the server. |
| 445 |
|
| 446 |
Args: |
| 447 |
repo_filename_path: Path to repository. |
| 448 |
repo_content_api: The information about the repository from the server. |
| 449 |
|
| 450 |
Returns: |
| 451 |
True, if the information matches, False otherwise. |
| 452 |
""" |
| 453 |
if not os.path.isfile(repo_filename_path): |
| 454 |
return False |
| 455 |
with open(repo_filename_path) as file: |
| 456 |
repo_content_file = file.read() |
| 457 |
return repo_content_file == repo_content_api |
| 458 |
|
| 459 |
@staticmethod |
| 460 |
def chroot_conf(): |
| 461 |
"""Obtain information about the distribution, version, and architecture of the target. |
| 462 |
|
| 463 |
Returns: |
| 464 |
Chroot info in the form of distribution-version-architecture. |
| 465 |
""" |
| 466 |
(distribution, version, codename) = distro.linux_distribution(full_distribution_name=False) |
| 467 |
base = CoprModule.get_base() |
| 468 |
return f"{distribution}-{version}-{base.conf.arch}" |
| 469 |
|
| 470 |
@staticmethod |
| 471 |
def _sanitize_username(user): |
| 472 |
"""Modify the group name. |
| 473 |
|
| 474 |
Args: |
| 475 |
user: User name. |
| 476 |
|
| 477 |
Returns: |
| 478 |
Modified user name if it is a group name with @. |
| 479 |
""" |
| 480 |
if user[0] == "@": |
| 481 |
return f"group_{user[1:]}" |
| 482 |
return user |
| 483 |
|
| 484 |
|
| 485 |
def run_module(): |
| 486 |
"""The function takes care of the functioning of the whole ansible copr module.""" |
| 487 |
module_args = dict( |
| 488 |
host=dict(type="str", default="copr.fedorainfracloud.org"), |
| 489 |
protocol=dict(type="str", default="https"), |
| 490 |
name=dict(type="str", required=True), |
| 491 |
state=dict(type="str", choices=["enabled", "disabled", "absent"], default="enabled"), |
| 492 |
chroot=dict(type="str"), |
| 493 |
includepkgs=dict(type="list", elements="str"), |
| 494 |
excludepkgs=dict(type="list", elements="str"), |
| 495 |
) |
| 496 |
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) |
| 497 |
params = module.params |
| 498 |
|
| 499 |
if not HAS_DNF_PACKAGES: |
| 500 |
_respawn_dnf() |
| 501 |
module.fail_json(msg=missing_required_lib("dnf"), exception=DNF_IMP_ERR) |
| 502 |
|
| 503 |
CoprModule.ansible_module = module |
| 504 |
copr_module = CoprModule( |
| 505 |
host=params["host"], |
| 506 |
name=params["name"], |
| 507 |
state=params["state"], |
| 508 |
protocol=params["protocol"], |
| 509 |
chroot=params["chroot"], |
| 510 |
check_mode=module.check_mode, |
| 511 |
) |
| 512 |
state = copr_module.run() |
| 513 |
|
| 514 |
info = "Please note that this repository is not part of the main distribution" |
| 515 |
|
| 516 |
if params["state"] == "enabled" and state["state"]: |
| 517 |
module.exit_json( |
| 518 |
changed=state["state"], |
| 519 |
msg=state["msg"], |
| 520 |
repo=state["repo"], |
| 521 |
repo_filename=state["repo_filename"], |
| 522 |
info=info, |
| 523 |
) |
| 524 |
module.exit_json( |
| 525 |
changed=state["state"], |
| 526 |
msg=state["msg"], |
| 527 |
repo=state["repo"], |
| 528 |
repo_filename=state["repo_filename"], |
| 529 |
) |
| 530 |
|
| 531 |
|
| 532 |
def main(): |
| 533 |
"""Launches ansible Copr module.""" |
| 534 |
run_module() |
| 535 |
|
| 536 |
|
| 537 |
if __name__ == "__main__": |
| 538 |
main() |