| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2015-2023, Vlad Glagolev <[email protected]> |
| 4 |
# |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: sorcery |
| 12 |
short_description: Package manager for Source Mage GNU/Linux |
| 13 |
description: |
| 14 |
- Manages "spells" on Source Mage GNU/Linux using I(sorcery) toolchain. |
| 15 |
author: "Vlad Glagolev (@vaygr)" |
| 16 |
notes: |
| 17 |
- When all three components are selected, the update goes by the sequence -- Sorcery -> Grimoire(s) -> Spell(s); you cannot |
| 18 |
override it. |
| 19 |
- Grimoire handling is supported since community.general 7.3.0. |
| 20 |
requirements: |
| 21 |
- bash |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.general._attributes |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: full |
| 27 |
diff_mode: |
| 28 |
support: none |
| 29 |
options: |
| 30 |
name: |
| 31 |
description: |
| 32 |
- Name of the spell or grimoire. |
| 33 |
- Multiple names can be given, separated by commas. |
| 34 |
- Special value V(*) in conjunction with states V(latest) or V(rebuild) updates or rebuilds the whole system respectively. |
| 35 |
- The alias O(grimoire) was added in community.general 7.3.0. |
| 36 |
aliases: ["spell", "grimoire"] |
| 37 |
type: list |
| 38 |
elements: str |
| 39 |
|
| 40 |
repository: |
| 41 |
description: |
| 42 |
- Repository location. |
| 43 |
- If specified, O(name) represents grimoire(s) instead of spell(s). |
| 44 |
- Special value V(*) pulls grimoire from the official location. |
| 45 |
- Only single item in O(name) in conjunction with V(*) can be used. |
| 46 |
- O(state=absent) must be used with a special value V(*). |
| 47 |
type: str |
| 48 |
version_added: 7.3.0 |
| 49 |
|
| 50 |
state: |
| 51 |
description: |
| 52 |
- Whether to cast, dispel or rebuild a package. |
| 53 |
- State V(cast) is an equivalent of V(present), not V(latest). |
| 54 |
- State V(rebuild) implies cast of all specified spells, not only those existed before. |
| 55 |
choices: ["present", "latest", "absent", "cast", "dispelled", "rebuild"] |
| 56 |
default: "present" |
| 57 |
type: str |
| 58 |
|
| 59 |
depends: |
| 60 |
description: |
| 61 |
- Comma-separated list of _optional_ dependencies to build a spell (or make sure it is built) with; use V(+)/V(-) in |
| 62 |
front of dependency to turn it on/off (V(+) is optional though). |
| 63 |
- This option is ignored if O(name) parameter is equal to V(*) or contains more than one spell. |
| 64 |
- Providers must be supplied in the form recognized by Sorcery, for example 'V(openssl(SSL\))'. |
| 65 |
type: str |
| 66 |
|
| 67 |
update: |
| 68 |
description: |
| 69 |
- Whether or not to update sorcery scripts at the very first stage. |
| 70 |
type: bool |
| 71 |
default: false |
| 72 |
|
| 73 |
update_cache: |
| 74 |
description: |
| 75 |
- Whether or not to update grimoire collection before casting spells. |
| 76 |
type: bool |
| 77 |
default: false |
| 78 |
aliases: ["update_codex"] |
| 79 |
|
| 80 |
cache_valid_time: |
| 81 |
description: |
| 82 |
- Time in seconds to invalidate grimoire collection on update. |
| 83 |
- Especially useful for SCM and rsync grimoires. |
| 84 |
- Makes sense only in pair with O(update_cache). |
| 85 |
type: int |
| 86 |
default: 0 |
| 87 |
""" |
| 88 |
|
| 89 |
|
| 90 |
EXAMPLES = r""" |
| 91 |
- name: Make sure spell foo is installed |
| 92 |
community.general.sorcery: |
| 93 |
spell: foo |
| 94 |
state: present |
| 95 |
|
| 96 |
- name: Make sure spells foo, bar and baz are removed |
| 97 |
community.general.sorcery: |
| 98 |
spell: foo,bar,baz |
| 99 |
state: absent |
| 100 |
|
| 101 |
- name: Make sure spell foo with dependencies bar and baz is installed |
| 102 |
community.general.sorcery: |
| 103 |
spell: foo |
| 104 |
depends: bar,baz |
| 105 |
state: present |
| 106 |
|
| 107 |
- name: Make sure spell foo with bar and without baz dependencies is installed |
| 108 |
community.general.sorcery: |
| 109 |
spell: foo |
| 110 |
depends: +bar,-baz |
| 111 |
state: present |
| 112 |
|
| 113 |
- name: Make sure spell foo with libressl (providing SSL) dependency is installed |
| 114 |
community.general.sorcery: |
| 115 |
spell: foo |
| 116 |
depends: libressl(SSL) |
| 117 |
state: present |
| 118 |
|
| 119 |
- name: Make sure spells with/without required dependencies (if any) are installed |
| 120 |
community.general.sorcery: |
| 121 |
name: "{{ item.spell }}" |
| 122 |
depends: "{{ item.depends | default(None) }}" |
| 123 |
state: present |
| 124 |
loop: |
| 125 |
- {spell: 'vifm', depends: '+file,-gtk+2'} |
| 126 |
- {spell: 'fwknop', depends: 'gpgme'} |
| 127 |
- {spell: 'pv,tnftp,tor'} |
| 128 |
|
| 129 |
- name: Install the latest version of spell foo using regular glossary |
| 130 |
community.general.sorcery: |
| 131 |
name: foo |
| 132 |
state: latest |
| 133 |
|
| 134 |
- name: Rebuild spell foo |
| 135 |
community.general.sorcery: |
| 136 |
spell: foo |
| 137 |
state: rebuild |
| 138 |
|
| 139 |
- name: Rebuild the whole system, but update Sorcery and Codex first |
| 140 |
community.general.sorcery: |
| 141 |
spell: '*' |
| 142 |
state: rebuild |
| 143 |
update: true |
| 144 |
update_cache: true |
| 145 |
|
| 146 |
- name: Refresh the grimoire collection if it is 1 day old using native sorcerous alias |
| 147 |
community.general.sorcery: |
| 148 |
update_codex: true |
| 149 |
cache_valid_time: 86400 |
| 150 |
|
| 151 |
- name: Make sure stable grimoire is present |
| 152 |
community.general.sorcery: |
| 153 |
name: stable |
| 154 |
repository: '*' |
| 155 |
state: present |
| 156 |
|
| 157 |
- name: Make sure binary and stable-rc grimoires are removed |
| 158 |
community.general.sorcery: |
| 159 |
grimoire: binary,stable-rc |
| 160 |
repository: '*' |
| 161 |
state: absent |
| 162 |
|
| 163 |
- name: Make sure games grimoire is pulled from rsync |
| 164 |
community.general.sorcery: |
| 165 |
grimoire: games |
| 166 |
repository: "rsync://download.sourcemage.org::codex/games" |
| 167 |
state: present |
| 168 |
|
| 169 |
- name: Make sure a specific branch of stable grimoire is pulled from git |
| 170 |
community.general.sorcery: |
| 171 |
grimoire: stable.git |
| 172 |
repository: "git://download.sourcemage.org/smgl/grimoire.git:stable.git:stable-0.62" |
| 173 |
state: present |
| 174 |
|
| 175 |
- name: Update only Sorcery itself |
| 176 |
community.general.sorcery: |
| 177 |
update: true |
| 178 |
""" |
| 179 |
|
| 180 |
|
| 181 |
RETURN = r""" |
| 182 |
""" |
| 183 |
|
| 184 |
|
| 185 |
import datetime |
| 186 |
import fileinput |
| 187 |
import os |
| 188 |
import re |
| 189 |
import shutil |
| 190 |
import sys |
| 191 |
|
| 192 |
from ansible.module_utils.basic import AnsibleModule |
| 193 |
|
| 194 |
# auto-filled at module init |
| 195 |
SORCERY = {"sorcery": None, "scribe": None, "cast": None, "dispel": None, "gaze": None} |
| 196 |
|
| 197 |
SORCERY_LOG_DIR = "/var/log/sorcery" |
| 198 |
SORCERY_STATE_DIR = "/var/state/sorcery" |
| 199 |
|
| 200 |
NA = "N/A" |
| 201 |
|
| 202 |
|
| 203 |
def get_sorcery_ver(module): |
| 204 |
"""Get Sorcery version.""" |
| 205 |
|
| 206 |
cmd_sorcery = f"{SORCERY['sorcery']} --version" |
| 207 |
|
| 208 |
rc, stdout, stderr = module.run_command(cmd_sorcery) |
| 209 |
|
| 210 |
if rc != 0 or not stdout: |
| 211 |
module.fail_json(msg="unable to get Sorcery version") |
| 212 |
|
| 213 |
return stdout.strip() |
| 214 |
|
| 215 |
|
| 216 |
def codex_fresh(codex, module): |
| 217 |
"""Check if grimoire collection is fresh enough.""" |
| 218 |
|
| 219 |
if not module.params["cache_valid_time"]: |
| 220 |
return False |
| 221 |
|
| 222 |
timedelta = datetime.timedelta(seconds=module.params["cache_valid_time"]) |
| 223 |
|
| 224 |
for grimoire in codex: |
| 225 |
lastupdate_path = os.path.join(SORCERY_STATE_DIR, f"{grimoire}.lastupdate") |
| 226 |
|
| 227 |
try: |
| 228 |
mtime = os.stat(lastupdate_path).st_mtime |
| 229 |
except Exception: |
| 230 |
return False |
| 231 |
|
| 232 |
lastupdate_ts = datetime.datetime.fromtimestamp(mtime) |
| 233 |
|
| 234 |
# if any grimoire is not fresh, we invalidate the Codex |
| 235 |
if lastupdate_ts + timedelta < datetime.datetime.now(): |
| 236 |
return False |
| 237 |
|
| 238 |
return True |
| 239 |
|
| 240 |
|
| 241 |
def codex_list(module, skip_new=False): |
| 242 |
"""List valid grimoire collection.""" |
| 243 |
|
| 244 |
params = module.params |
| 245 |
|
| 246 |
codex = {} |
| 247 |
|
| 248 |
cmd_scribe = f"{SORCERY['scribe']} index" |
| 249 |
|
| 250 |
rc, stdout, stderr = module.run_command(cmd_scribe) |
| 251 |
|
| 252 |
if rc != 0: |
| 253 |
module.fail_json(msg="unable to list grimoire collection, fix your Codex") |
| 254 |
|
| 255 |
rex = re.compile(r"^\s*\[\d+\] : (?P<grim>[\w\-+.]+) : [\w\-+./]+(?: : (?P<ver>[\w\-+.]+))?\s*$") |
| 256 |
|
| 257 |
# drop 4-line header and empty trailing line |
| 258 |
for line in stdout.splitlines()[4:-1]: |
| 259 |
match = rex.match(line) |
| 260 |
|
| 261 |
if match: |
| 262 |
codex[match.group("grim")] = match.group("ver") |
| 263 |
|
| 264 |
# return only specified grimoires unless requested to skip new |
| 265 |
if params["repository"] and not skip_new: |
| 266 |
codex = {x: codex.get(x, NA) for x in params["name"]} |
| 267 |
|
| 268 |
if not codex: |
| 269 |
module.fail_json(msg="no grimoires to operate on; add at least one") |
| 270 |
|
| 271 |
return codex |
| 272 |
|
| 273 |
|
| 274 |
def update_sorcery(module): |
| 275 |
"""Update sorcery scripts. |
| 276 |
|
| 277 |
This runs 'sorcery update' ('sorcery -u'). Check mode always returns a |
| 278 |
positive change value. |
| 279 |
|
| 280 |
""" |
| 281 |
|
| 282 |
changed = False |
| 283 |
|
| 284 |
if module.check_mode: |
| 285 |
return (True, "would have updated Sorcery") |
| 286 |
else: |
| 287 |
sorcery_ver = get_sorcery_ver(module) |
| 288 |
|
| 289 |
cmd_sorcery = f"{SORCERY['sorcery']} update" |
| 290 |
|
| 291 |
rc, stdout, stderr = module.run_command(cmd_sorcery) |
| 292 |
|
| 293 |
if rc != 0: |
| 294 |
module.fail_json(msg=f"unable to update Sorcery: {stdout}") |
| 295 |
|
| 296 |
if sorcery_ver != get_sorcery_ver(module): |
| 297 |
changed = True |
| 298 |
|
| 299 |
return (changed, "successfully updated Sorcery") |
| 300 |
|
| 301 |
|
| 302 |
def update_codex(module): |
| 303 |
"""Update grimoire collections. |
| 304 |
|
| 305 |
This runs 'scribe update'. Check mode always returns a positive change |
| 306 |
value when 'cache_valid_time' is used. |
| 307 |
|
| 308 |
""" |
| 309 |
|
| 310 |
params = module.params |
| 311 |
|
| 312 |
changed = False |
| 313 |
|
| 314 |
codex = codex_list(module) |
| 315 |
fresh = codex_fresh(codex, module) |
| 316 |
|
| 317 |
if module.check_mode: |
| 318 |
if not fresh: |
| 319 |
changed = True |
| 320 |
|
| 321 |
return (changed, "would have updated Codex") |
| 322 |
else: |
| 323 |
if not fresh: |
| 324 |
# SILENT is required as a workaround for query() in libgpg |
| 325 |
module.run_command_environ_update.update(dict(SILENT="1")) |
| 326 |
|
| 327 |
cmd_scribe = f"{SORCERY['scribe']} update" |
| 328 |
|
| 329 |
if params["repository"]: |
| 330 |
cmd_scribe += f" {' '.join(codex.keys())}" |
| 331 |
|
| 332 |
rc, stdout, stderr = module.run_command(cmd_scribe) |
| 333 |
|
| 334 |
if rc != 0: |
| 335 |
module.fail_json(msg=f"unable to update Codex: {stdout}") |
| 336 |
|
| 337 |
if codex != codex_list(module): |
| 338 |
changed = True |
| 339 |
|
| 340 |
return (changed, "successfully updated Codex") |
| 341 |
|
| 342 |
|
| 343 |
def match_depends(module): |
| 344 |
"""Check for matching dependencies. |
| 345 |
|
| 346 |
This inspects spell's dependencies with the desired states and returns |
| 347 |
'False' if a recast is needed to match them. It also adds required lines |
| 348 |
to the system-wide depends file for proper recast procedure. |
| 349 |
|
| 350 |
""" |
| 351 |
|
| 352 |
params = module.params |
| 353 |
spells = params["name"] |
| 354 |
|
| 355 |
depends = {} |
| 356 |
|
| 357 |
depends_ok = True |
| 358 |
|
| 359 |
if len(spells) > 1 or not params["depends"]: |
| 360 |
return depends_ok |
| 361 |
|
| 362 |
spell = spells[0] |
| 363 |
|
| 364 |
if module.check_mode: |
| 365 |
sorcery_depends_orig = os.path.join(SORCERY_STATE_DIR, "depends") |
| 366 |
sorcery_depends = os.path.join(SORCERY_STATE_DIR, "depends.check") |
| 367 |
|
| 368 |
try: |
| 369 |
shutil.copy2(sorcery_depends_orig, sorcery_depends) |
| 370 |
except OSError: |
| 371 |
module.fail_json(msg="failed to copy depends.check file") |
| 372 |
else: |
| 373 |
sorcery_depends = os.path.join(SORCERY_STATE_DIR, "depends") |
| 374 |
|
| 375 |
rex = re.compile(r"^(?P<status>\+?|\-){1}(?P<depend>[a-z0-9]+[a-z0-9_\-\+\.]*(\([A-Z0-9_\-\+\.]+\))*)$") |
| 376 |
|
| 377 |
for d in params["depends"].split(","): |
| 378 |
match = rex.match(d) |
| 379 |
|
| 380 |
if not match: |
| 381 |
module.fail_json(msg=f"wrong depends line for spell '{spell}'") |
| 382 |
|
| 383 |
# normalize status |
| 384 |
if not match.group("status") or match.group("status") == "+": |
| 385 |
status = "on" |
| 386 |
else: |
| 387 |
status = "off" |
| 388 |
|
| 389 |
depends[match.group("depend")] = status |
| 390 |
|
| 391 |
# drop providers spec |
| 392 |
depends_list = [s.split("(")[0] for s in depends] |
| 393 |
|
| 394 |
cmd_gaze = f"{SORCERY['gaze']} -q version {' '.join(depends_list)}" |
| 395 |
|
| 396 |
rc, stdout, stderr = module.run_command(cmd_gaze) |
| 397 |
|
| 398 |
if rc != 0: |
| 399 |
module.fail_json(msg=f"wrong dependencies for spell '{spell}'") |
| 400 |
|
| 401 |
fi = fileinput.input(sorcery_depends, inplace=True) |
| 402 |
|
| 403 |
try: |
| 404 |
try: |
| 405 |
for line in fi: |
| 406 |
if line.startswith(f"{spell}:"): |
| 407 |
match = None |
| 408 |
|
| 409 |
for d in depends: |
| 410 |
# when local status is 'off' and dependency is provider, |
| 411 |
# use only provider value |
| 412 |
d_offset = d.find("(") |
| 413 |
|
| 414 |
if d_offset == -1: |
| 415 |
d_p = "" |
| 416 |
else: |
| 417 |
d_p = re.escape(d[d_offset:]) |
| 418 |
|
| 419 |
# .escape() is needed mostly for the spells like 'libsigc++' |
| 420 |
rex = re.compile(f"{re.escape(spell)}:(?:{re.escape(d)}|{d_p}):(?P<lstatus>on|off):optional:") |
| 421 |
|
| 422 |
match = rex.match(line) |
| 423 |
|
| 424 |
# we matched the line "spell:dependency:on|off:optional:" |
| 425 |
if match: |
| 426 |
# if we also matched the local status, mark dependency |
| 427 |
# as empty and put it back into depends file |
| 428 |
if match.group("lstatus") == depends[d]: |
| 429 |
depends[d] = None |
| 430 |
|
| 431 |
sys.stdout.write(line) |
| 432 |
|
| 433 |
# status is not that we need, so keep this dependency |
| 434 |
# in the list for further reverse switching; |
| 435 |
# stop and process the next line in both cases |
| 436 |
break |
| 437 |
|
| 438 |
if not match: |
| 439 |
sys.stdout.write(line) |
| 440 |
else: |
| 441 |
sys.stdout.write(line) |
| 442 |
except OSError: |
| 443 |
module.fail_json(msg="I/O error on the depends file") |
| 444 |
finally: |
| 445 |
fi.close() |
| 446 |
|
| 447 |
depends_new = [v for v in depends if depends[v]] |
| 448 |
|
| 449 |
if depends_new: |
| 450 |
try: |
| 451 |
with open(sorcery_depends, "a") as fl: |
| 452 |
for k in depends_new: |
| 453 |
fl.write(f"{spell}:{k}:{depends[k]}:optional::\n") |
| 454 |
except OSError: |
| 455 |
module.fail_json(msg="I/O error on the depends file") |
| 456 |
|
| 457 |
depends_ok = False |
| 458 |
|
| 459 |
if module.check_mode: |
| 460 |
try: |
| 461 |
os.remove(sorcery_depends) |
| 462 |
except OSError: |
| 463 |
module.fail_json(msg="failed to clean up depends.backup file") |
| 464 |
|
| 465 |
return depends_ok |
| 466 |
|
| 467 |
|
| 468 |
def manage_grimoires(module): |
| 469 |
"""Add or remove grimoires.""" |
| 470 |
|
| 471 |
params = module.params |
| 472 |
grimoires = params["name"] |
| 473 |
url = params["repository"] |
| 474 |
|
| 475 |
codex = codex_list(module, True) |
| 476 |
|
| 477 |
if url == "*": |
| 478 |
if params["state"] in ("present", "latest", "absent"): |
| 479 |
if params["state"] == "absent": |
| 480 |
action = "remove" |
| 481 |
todo = set(grimoires) & set(codex) |
| 482 |
else: |
| 483 |
action = "add" |
| 484 |
todo = set(grimoires) - set(codex) |
| 485 |
|
| 486 |
if not todo: |
| 487 |
return (False, f"all grimoire(s) are already {action[:5]}ed") |
| 488 |
|
| 489 |
if module.check_mode: |
| 490 |
return (True, f"would have {action[:5]}ed grimoire(s)") |
| 491 |
|
| 492 |
cmd_scribe = f"{SORCERY['scribe']} {action} {' '.join(todo)}" |
| 493 |
|
| 494 |
rc, stdout, stderr = module.run_command(cmd_scribe) |
| 495 |
|
| 496 |
if rc != 0: |
| 497 |
module.fail_json(msg=f"failed to {action} one or more grimoire(s): {stdout}") |
| 498 |
|
| 499 |
return (True, f"successfully {action[:5]}ed one or more grimoire(s)") |
| 500 |
else: |
| 501 |
module.fail_json(msg="unsupported operation on '*' repository value") |
| 502 |
else: |
| 503 |
if params["state"] in ("present", "latest"): |
| 504 |
if len(grimoires) > 1: |
| 505 |
module.fail_json(msg="using multiple items with repository is invalid") |
| 506 |
|
| 507 |
grimoire = grimoires[0] |
| 508 |
|
| 509 |
if grimoire in codex: |
| 510 |
return (False, f"grimoire {grimoire} already exists") |
| 511 |
|
| 512 |
if module.check_mode: |
| 513 |
return (True, f"would have added grimoire {grimoire} from {url}") |
| 514 |
|
| 515 |
cmd_scribe = f"{SORCERY['scribe']} add {grimoire} from {url}" |
| 516 |
|
| 517 |
rc, stdout, stderr = module.run_command(cmd_scribe) |
| 518 |
|
| 519 |
if rc != 0: |
| 520 |
module.fail_json(msg=f"failed to add grimoire {grimoire} from {url}: {stdout}") |
| 521 |
|
| 522 |
return (True, f"successfully added grimoire {grimoire} from {url}") |
| 523 |
else: |
| 524 |
module.fail_json(msg="unsupported operation on repository value") |
| 525 |
|
| 526 |
|
| 527 |
def manage_spells(module): |
| 528 |
"""Cast or dispel spells. |
| 529 |
|
| 530 |
This manages the whole system ('*'), list or a single spell. Command 'cast' |
| 531 |
is used to install or rebuild spells, while 'dispel' takes care of theirs |
| 532 |
removal from the system. |
| 533 |
|
| 534 |
""" |
| 535 |
|
| 536 |
params = module.params |
| 537 |
spells = params["name"] |
| 538 |
|
| 539 |
sorcery_queue = os.path.join(SORCERY_LOG_DIR, "queue/install") |
| 540 |
|
| 541 |
if spells == "*": |
| 542 |
if params["state"] == "latest": |
| 543 |
# back up original queue |
| 544 |
try: |
| 545 |
os.rename(sorcery_queue, f"{sorcery_queue}.backup") |
| 546 |
except OSError: |
| 547 |
module.fail_json(msg="failed to backup the update queue") |
| 548 |
|
| 549 |
# see update_codex() |
| 550 |
module.run_command_environ_update.update(dict(SILENT="1")) |
| 551 |
|
| 552 |
cmd_sorcery = f"{SORCERY['sorcery']} queue" |
| 553 |
|
| 554 |
rc, stdout, stderr = module.run_command(cmd_sorcery) |
| 555 |
|
| 556 |
if rc != 0: |
| 557 |
module.fail_json(msg="failed to generate the update queue") |
| 558 |
|
| 559 |
try: |
| 560 |
queue_size = os.stat(sorcery_queue).st_size |
| 561 |
except Exception: |
| 562 |
module.fail_json(msg="failed to read the update queue") |
| 563 |
|
| 564 |
if queue_size != 0: |
| 565 |
if module.check_mode: |
| 566 |
try: |
| 567 |
os.rename(f"{sorcery_queue}.backup", sorcery_queue) |
| 568 |
except OSError: |
| 569 |
module.fail_json(msg="failed to restore the update queue") |
| 570 |
|
| 571 |
return (True, "would have updated the system") |
| 572 |
|
| 573 |
cmd_cast = f"{SORCERY['cast']} --queue" |
| 574 |
|
| 575 |
rc, stdout, stderr = module.run_command(cmd_cast) |
| 576 |
|
| 577 |
if rc != 0: |
| 578 |
module.fail_json(msg="failed to update the system") |
| 579 |
|
| 580 |
return (True, "successfully updated the system") |
| 581 |
else: |
| 582 |
return (False, "the system is already up to date") |
| 583 |
elif params["state"] == "rebuild": |
| 584 |
if module.check_mode: |
| 585 |
return (True, "would have rebuilt the system") |
| 586 |
|
| 587 |
cmd_sorcery = f"{SORCERY['sorcery']} rebuild" |
| 588 |
|
| 589 |
rc, stdout, stderr = module.run_command(cmd_sorcery) |
| 590 |
|
| 591 |
if rc != 0: |
| 592 |
module.fail_json(msg=f"failed to rebuild the system: {stdout}") |
| 593 |
|
| 594 |
return (True, "successfully rebuilt the system") |
| 595 |
else: |
| 596 |
module.fail_json(msg="unsupported operation on '*' name value") |
| 597 |
else: |
| 598 |
if params["state"] in ("present", "latest", "rebuild", "absent"): |
| 599 |
# extract versions from the 'gaze' command |
| 600 |
cmd_gaze = f"{SORCERY['gaze']} -q version {' '.join(spells)}" |
| 601 |
|
| 602 |
rc, stdout, stderr = module.run_command(cmd_gaze) |
| 603 |
|
| 604 |
# fail if any of spells cannot be found |
| 605 |
if rc != 0: |
| 606 |
module.fail_json(msg=f"failed to locate spell(s) in the list ({', '.join(spells)})") |
| 607 |
|
| 608 |
cast_queue = [] |
| 609 |
dispel_queue = [] |
| 610 |
|
| 611 |
rex = re.compile(r"[^|]+\|[^|]+\|(?P<spell>[^|]+)\|(?P<grim_ver>[^|]+)\|(?P<inst_ver>[^$]+)") |
| 612 |
|
| 613 |
# drop 2-line header and empty trailing line |
| 614 |
for line in stdout.splitlines()[2:-1]: |
| 615 |
match = rex.match(line) |
| 616 |
|
| 617 |
cast = False |
| 618 |
|
| 619 |
if params["state"] == "present": |
| 620 |
# spell is not installed.. |
| 621 |
if match.group("inst_ver") == "-": |
| 622 |
# ..so set up depends reqs for it |
| 623 |
match_depends(module) |
| 624 |
|
| 625 |
cast = True |
| 626 |
# spell is installed.. |
| 627 |
else: |
| 628 |
# ..but does not conform depends reqs |
| 629 |
if not match_depends(module): |
| 630 |
cast = True |
| 631 |
elif params["state"] == "latest": |
| 632 |
# grimoire and installed versions do not match.. |
| 633 |
if match.group("grim_ver") != match.group("inst_ver"): |
| 634 |
# ..so check for depends reqs first and set them up |
| 635 |
match_depends(module) |
| 636 |
|
| 637 |
cast = True |
| 638 |
# grimoire and installed versions match.. |
| 639 |
else: |
| 640 |
# ..but the spell does not conform depends reqs |
| 641 |
if not match_depends(module): |
| 642 |
cast = True |
| 643 |
elif params["state"] == "rebuild": |
| 644 |
cast = True |
| 645 |
# 'absent' |
| 646 |
else: |
| 647 |
if match.group("inst_ver") != "-": |
| 648 |
dispel_queue.append(match.group("spell")) |
| 649 |
|
| 650 |
if cast: |
| 651 |
cast_queue.append(match.group("spell")) |
| 652 |
|
| 653 |
if cast_queue: |
| 654 |
if module.check_mode: |
| 655 |
return (True, "would have cast spell(s)") |
| 656 |
|
| 657 |
cmd_cast = f"{SORCERY['cast']} -c {' '.join(cast_queue)}" |
| 658 |
|
| 659 |
rc, stdout, stderr = module.run_command(cmd_cast) |
| 660 |
|
| 661 |
if rc != 0: |
| 662 |
module.fail_json(msg=f"failed to cast spell(s): {stdout}") |
| 663 |
|
| 664 |
return (True, "successfully cast spell(s)") |
| 665 |
elif params["state"] != "absent": |
| 666 |
return (False, "spell(s) are already cast") |
| 667 |
|
| 668 |
if dispel_queue: |
| 669 |
if module.check_mode: |
| 670 |
return (True, "would have dispelled spell(s)") |
| 671 |
|
| 672 |
cmd_dispel = f"{SORCERY['dispel']} {' '.join(dispel_queue)}" |
| 673 |
|
| 674 |
rc, stdout, stderr = module.run_command(cmd_dispel) |
| 675 |
|
| 676 |
if rc != 0: |
| 677 |
module.fail_json(msg=f"failed to dispel spell(s): {stdout}") |
| 678 |
|
| 679 |
return (True, "successfully dispelled spell(s)") |
| 680 |
else: |
| 681 |
return (False, "spell(s) are already dispelled") |
| 682 |
|
| 683 |
|
| 684 |
def main(): |
| 685 |
module = AnsibleModule( |
| 686 |
argument_spec=dict( |
| 687 |
name=dict(aliases=["spell", "grimoire"], type="list", elements="str"), |
| 688 |
repository=dict(type="str"), |
| 689 |
state=dict(default="present", choices=["present", "latest", "absent", "cast", "dispelled", "rebuild"]), |
| 690 |
depends=dict(), |
| 691 |
update=dict(default=False, type="bool"), |
| 692 |
update_cache=dict(default=False, aliases=["update_codex"], type="bool"), |
| 693 |
cache_valid_time=dict(default=0, type="int"), |
| 694 |
), |
| 695 |
required_one_of=[["name", "update", "update_cache"]], |
| 696 |
supports_check_mode=True, |
| 697 |
) |
| 698 |
|
| 699 |
if os.geteuid() != 0: |
| 700 |
module.fail_json(msg="root privileges are required for this operation") |
| 701 |
|
| 702 |
for c in SORCERY: |
| 703 |
SORCERY[c] = module.get_bin_path(c, True) |
| 704 |
|
| 705 |
# prepare environment: run sorcery commands without asking questions |
| 706 |
module.run_command_environ_update = dict(PROMPT_DELAY="0", VOYEUR="0", LANGUAGE="C", LC_ALL="C") |
| 707 |
|
| 708 |
params = module.params |
| 709 |
|
| 710 |
# normalize 'state' parameter |
| 711 |
if params["state"] in ("present", "cast"): |
| 712 |
params["state"] = "present" |
| 713 |
elif params["state"] in ("absent", "dispelled"): |
| 714 |
params["state"] = "absent" |
| 715 |
|
| 716 |
changed = {"sorcery": (False, NA), "grimoires": (False, NA), "codex": (False, NA), "spells": (False, NA)} |
| 717 |
|
| 718 |
if params["update"]: |
| 719 |
changed["sorcery"] = update_sorcery(module) |
| 720 |
|
| 721 |
if params["name"] and params["repository"]: |
| 722 |
changed["grimoires"] = manage_grimoires(module) |
| 723 |
|
| 724 |
if params["update_cache"]: |
| 725 |
changed["codex"] = update_codex(module) |
| 726 |
|
| 727 |
if params["name"] and not params["repository"]: |
| 728 |
changed["spells"] = manage_spells(module) |
| 729 |
|
| 730 |
if any(x[0] for x in changed.values()): |
| 731 |
state_msg = "state changed" |
| 732 |
state_changed = True |
| 733 |
else: |
| 734 |
state_msg = "no change in state" |
| 735 |
state_changed = False |
| 736 |
|
| 737 |
module.exit_json(changed=state_changed, msg=f"{state_msg}: {'; '.join(x[1] for x in changed.values())}") |
| 738 |
|
| 739 |
|
| 740 |
if __name__ == "__main__": |
| 741 |
main() |