Skip to content
26 changes: 2 additions & 24 deletions library/bootloader_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Copyright: (c) 2023, Sergei Petrosian <spetrosi@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Assisted by goose using model glm-5-3
from __future__ import absolute_import, division, print_function

__metaclass__ = type
Expand Down Expand Up @@ -116,34 +117,11 @@
"""


import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.bootloader_lsr.bootloader_common import get_facts
from ansible.module_utils.bootloader_lsr.grub import check_loader, get_kernels


def get_facts(kernels_info, default_kernel):
"""Get kernel facts"""
kernels_info_lines = kernels_info.strip().split("\n")
kernels = []
index_count = 0

for line in kernels_info_lines:
index = re.search(r"index=(\d+)", line)
if index:
is_default = index.group(1) == default_kernel.strip()
index_count += 1
kernels.append({})
search = re.search(r"(.*?)=(.*)", line)
if search:
key = search.group(1).strip('"')
value = search.group(2).strip('"')
kernels[index_count - 1].update({key: value})
else:
kernels[index_count - 1].update({"kernel": line})
kernels[index_count - 1].update({"default": is_default})
return kernels


def run_module():
# define available arguments/parameters a user can pass to the module
module_args = dict(
Expand Down
125 changes: 90 additions & 35 deletions library/bootloader_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Copyright: (c) 2023, Sergei Petrosian <spetrosi@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Includes code generated by Cursor IDE using the models Composer 2.5, Codex 5.3, and Sonnet 4.6
# Assisted by goose using model glm-5-3
from __future__ import absolute_import, division, print_function

__metaclass__ = type
Expand Down Expand Up @@ -103,36 +104,20 @@
"""

import re
import shlex

from ansible.module_utils.basic import AnsibleModule

# This is a bit of a mystery - bug in pylint?
# pylint: disable=import-error
import ansible.module_utils.six.moves as ansible_six_moves
from ansible.module_utils.bootloader_lsr import pbl


def get_facts(kernels_info, default_kernel_index):
"""Get kernel facts"""
kernels_info_lines = kernels_info.strip().split("\n")
kernels = []
index_count = 0

for line in kernels_info_lines:
index = re.search(r"index=(\d+)", line)
if index:
is_default = index.group(1) == default_kernel_index.strip()
index_count += 1
kernels.append({})
search = re.search(r"(.*?)=(.*)", line)
if search:
key = search.group(1).strip('"')
value = search.group(2).strip('"')
kernels[index_count - 1].update({key: value})
else:
kernels[index_count - 1].update({"kernel": line})
kernels[index_count - 1].update({"default": is_default})
return kernels
from ansible.module_utils.bootloader_lsr.bootloader_common import (
add_extra_boot_prefix,
get_extra_boot_prefix_paths,
get_facts,
strip_extra_boot_prefix,
)


def get_dict_same_keys(dict1, dict2):
Expand Down Expand Up @@ -171,26 +156,43 @@ def get_kernel_to_mod(bootloader_setting_kernel, kernel_mod_keys):
}


def get_single_kernel(bootloader_setting_kernel):
def get_single_kernel(bootloader_setting_kernel, extra_boot_prefix_paths=frozenset()):
"""Get kernel in the format expected by 'grubby --update-kernel=' from a one-element dict"""
kernel_key, kernel_val = list(bootloader_setting_kernel.items())[0]
kernel_key_prefix = ""
if kernel_key == "title":
kernel_key_prefix = "TITLE="
if kernel_key == "path":
# add the extra prefix only when grubby reports the path of this
# kernel with it; grubby cannot match the real paths of the entries
# that it reports with the extra prefix, and it cannot match the
# paths with the extra prefix of the entries that it reports with
# the real paths
kernel_val = add_extra_boot_prefix(
kernel_val, kernel_val in extra_boot_prefix_paths
)
return kernel_key_prefix + escapeval(kernel_val)


def get_create_kernel(bootloader_setting_kernel):
def get_create_kernel(bootloader_setting_kernel, extra_boot_prefix_paths=frozenset()):
"""Get kernel in the format expected by 'grubby --add-kernel=' from a multiple-element dict"""
kernel = ""
# a new kernel has no reported path yet, so it follows the convention of
# the existing entries: apply the extra prefix when grubby reports the
# path of any existing entry with it
extra_boot_prefix = bool(extra_boot_prefix_paths)
for key in sorted(bootloader_setting_kernel.keys()):
value = bootloader_setting_kernel[key]
if key == "path":
kernel += " --add-kernel=" + escapeval(value)
kernel += " --add-kernel=" + escapeval(
add_extra_boot_prefix(value, extra_boot_prefix)
)
elif key == "title":
kernel += " --title=" + escapeval(value)
elif key == "initrd":
kernel += " --initrd=" + escapeval(value)
kernel += " --initrd=" + escapeval(
add_extra_boot_prefix(value, extra_boot_prefix)
)
return kernel.strip()


Expand Down Expand Up @@ -222,7 +224,9 @@ def validate_default_kernel(module, bootloader_settings):
)


def validate_kernels(module, bootloader_setting, bootloader_facts):
def validate_kernels(
module, bootloader_setting, bootloader_facts, extra_boot_prefix_paths=frozenset()
):
"""Validate that user passes bootloader_setting correctly"""
kernel_action = ""
kernel = ""
Expand Down Expand Up @@ -278,10 +282,22 @@ def validate_kernels(module, bootloader_setting, bootloader_facts):
msg="kernel value in '%s: %s' must be of type str or int" % (key, value)
)

# Normalize the path and initrd values of the user setting with the same
# rules used for the paths that grubby reports, so that a value with the
# extra /boot prefix that grubby adds on some platforms matches the
# normalized path of the corresponding fact; the extra prefix is added
# back to the grubby commands, where needed, by add_extra_boot_prefix
for key in ["path", "initrd"]:
value = bootloader_setting["kernel"].get(key)
if isinstance(value, str):
bootloader_setting["kernel"][key] = strip_extra_boot_prefix(value)

# Validate with len(bootloader_setting["kernel"]) == 1
if len(bootloader_setting["kernel"]) == 1:
validate_kernel_initrd(module, bootloader_setting["kernel"], kernel_mod_keys)
kernel = get_single_kernel(bootloader_setting["kernel"])
kernel = get_single_kernel(
bootloader_setting["kernel"], extra_boot_prefix_paths
)
kernel_action = "modify" if state == "present" else "remove"
return kernel_action, kernel

Expand Down Expand Up @@ -313,13 +329,15 @@ def validate_kernels(module, bootloader_setting, bootloader_facts):
kernel_action = "create" if state == "present" else "remove"

if kernel_action == "create":
kernel = get_create_kernel(bootloader_setting["kernel"])
kernel = get_create_kernel(
bootloader_setting["kernel"], extra_boot_prefix_paths
)

validate_kernel_initrd(module, bootloader_setting["kernel"], kernel_mod_keys)

if kernel_action in ["remove", "modify"]:
kernel_to_mod = get_kernel_to_mod(bootloader_setting["kernel"], kernel_mod_keys)
kernel = get_single_kernel(kernel_to_mod)
kernel = get_single_kernel(kernel_to_mod, extra_boot_prefix_paths)
return kernel_action, kernel


Expand Down Expand Up @@ -483,11 +501,15 @@ def mod_default_kernel(module, result, bootloader_setting, kernel_info):
if not kernel_match:
return

kernel = kernel_match.group(1)
kernel = strip_extra_boot_prefix(kernel_match.group(1))
current_default = get_default_kernel(module, "kernel")
if current_default == kernel:
return

# grubby does not strip the extra /boot prefix from the --set-default
# value, so it needs the real kernel path, unlike the commands handled
# by remove_var_prefix() (--add-kernel, --initrd, --update-kernel,
# --remove-kernel), which do need the extra prefix on affected platforms
cmd = "grubby --set-default=" + kernel
apply_command(module, result, cmd)

Expand All @@ -503,9 +525,29 @@ def get_default_kernel(module, type):
module.fail_json(msg="Type must be one of 'kernel', 'title', or 'index'")
cmd = "grubby --default-" + type
_unused, stdout, _unused = module.run_command(cmd)
if type == "kernel":
# grubby may report the kernel path with an extra /boot prefix
return strip_extra_boot_prefix(stdout.strip())
return stdout.strip()


def get_info_kernel(kernel):
"""Get the kernel selector in the format expected by 'grubby --info='

grubby does not strip the extra /boot prefix from the --info value, so
the extra prefix is stripped from the path selectors, to pass the real
kernel path; the title, index and other selectors are not paths, so
they are used as is, to keep matching the corresponding entries. The
selector for a path is quoted, so the extra prefix is stripped from
the raw, unquoted path, and the result is quoted again.
"""
if not kernel.startswith("/") and not kernel.startswith("'"):
return kernel
# the selector is a path, which escapeval may have quoted
raw_kernel = shlex.split(kernel)[0]
return escapeval(strip_extra_boot_prefix(raw_kernel))


def get_replaced_args(bootloader_setting_options):
"""Get the sorted list of desired arg tokens for a replacement check."""
tokens = []
Expand Down Expand Up @@ -582,17 +624,28 @@ def run_module():

default_kernel_index = get_default_kernel(module, "index")
bootloader_facts = get_facts(kernels_info, default_kernel_index)
# grubby may report the paths of only some of the kernel entries
# with an extra /boot prefix; the grubby commands whose values
# grubby strips the prefix from (--add-kernel, --initrd,
# --update-kernel, --remove-kernel) need the extra prefix for those
# entries, while the other commands (--info, --set-default) always
# need the real kernel path
extra_boot_prefix_paths = get_extra_boot_prefix_paths(kernels_info)

kernel_action, kernel = validate_kernels(
module, bootloader_setting, bootloader_facts
module, bootloader_setting, bootloader_facts, extra_boot_prefix_paths
)

# Remove all existing boot settings
if (
"options" in bootloader_setting
and {"previous": "replaced"} in bootloader_setting["options"]
) and (kernel_action != "remove"):
rc, kernel_info, stderr = module.run_command("grubby --info=" + kernel)
# grubby does not strip the extra /boot prefix from the --info
# value, so it needs the real kernel path
rc, kernel_info, stderr = module.run_command(
"grubby --info=" + get_info_kernel(kernel)
)
if needs_replacement(bootloader_setting.get("options", []), kernel_info):
rm_boot_args(module, result, kernel_info, kernel)

Expand All @@ -602,8 +655,10 @@ def run_module():

# Modify boot settings
if kernel_action == "modify":
# grubby does not strip the extra /boot prefix from the --info
# value, so it needs the real kernel path
_unused, kernel_info, _unused = module.run_command(
"grubby --info=" + kernel
"grubby --info=" + get_info_kernel(kernel)
)
mod_boot_args(module, result, bootloader_setting, kernel, kernel_info)

Expand Down
Loading