Skip to content

Commit

Permalink
Add workaround for get_avail_subs
Browse files Browse the repository at this point in the history
We had to do a workaround around the get_avail_subs function to place a
releasever file in /etc/dnf/vars for it to work again.

Signed-off-by: Rodolfo Olivieri <[email protected]>
  • Loading branch information
hosekadam authored and r0x0d committed Nov 25, 2022
1 parent e683f85 commit cc7cc06
Show file tree
Hide file tree
Showing 4 changed files with 147 additions and 11 deletions.
55 changes: 48 additions & 7 deletions convert2rhel/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@

_SUBMGR_PKG_REMOVED_IN_CL_85 = "subscription-manager-initial-setup-addon"

# Path to the releasever variable file for dnf.
DNF_RELEASEVER_FILE = "/etc/yum/vars/releasever"


class UnregisterError(Exception):
"""Raised with problems unregistering a system."""
Expand Down Expand Up @@ -455,7 +458,8 @@ def __call__(self):
register_server = system_bus.get_object("com.redhat.RHSM1", "/com/redhat/RHSM1/RegisterServer")
loggerinst.debug("Starting a private DBus to talk to subscription-manager")
address = register_server.Start(
i18n.SUBSCRIPTION_MANAGER_LOCALE, dbus_interface="com.redhat.RHSM1.RegisterServer"
i18n.SUBSCRIPTION_MANAGER_LOCALE,
dbus_interface="com.redhat.RHSM1.RegisterServer",
)

try:
Expand Down Expand Up @@ -525,7 +529,10 @@ def __call__(self):
finally:
# Always shut down the private bus
loggerinst.debug("Shutting down private DBus instance")
register_server.Stop(i18n.SUBSCRIPTION_MANAGER_LOCALE, dbus_interface="com.redhat.RHSM1.RegisterServer")
register_server.Stop(
i18n.SUBSCRIPTION_MANAGER_LOCALE,
dbus_interface="com.redhat.RHSM1.RegisterServer",
)

def _set_connection_opts_in_config(self):
"""
Expand Down Expand Up @@ -776,10 +783,33 @@ def attach_subscription():
def get_avail_subs():
"""Get list of all the subscriptions available to the user so they are
accessible by index once the user chooses one.
.. note::
Get multiline string holding all the subscriptions available to the
logged-in user
"""
# Get multiline string holding all the subscriptions available to the
# logged-in user
# With the current changes introduced in PR#627, we needed to remove the
# non-RHEL packages that contain repofiles before we do any call to
# subscription-manager, and since we are doing that, this function starts to
# fail because it doesn't have the package that sets the releasever anymore.
# For some reason, subscription-manager needs to call libdnf internally to
# read the repositories on the system, and since libdnf needs to do
# substitutions on those repofiles, mainly the releasever and any other file
# placed in /etc/dnf/vars, this command call fails as it cannot replace the
# releasever variable anymore.
releaver_created = False
if system_info.version.major >= 8:
if not os.path.exists(DNF_RELEASEVER_FILE):
with open(DNF_RELEASEVER_FILE, "w") as handler:
handler.write(system_info.original_releasever)

releaver_created = True

subs_raw, ret_code = utils.run_subprocess(["subscription-manager", "list", "--available"], print_output=False)

if releaver_created:
os.remove(DNF_RELEASEVER_FILE)

if ret_code != 0:
loggerinst.critical("Unable to get list of available subscriptions:\n%s" % subs_raw)
return list(get_sub(subs_raw))
Expand Down Expand Up @@ -1005,7 +1035,12 @@ def _log_rhsm_download_directory_contents(directory, when_message):
pkgs = ["<download directory does not exist>"]
if os.path.isdir(SUBMGR_RPMS_DIR):
pkgs = os.listdir(SUBMGR_RPMS_DIR)
loggerinst.debug("Contents of %s directory %s:\n%s", SUBMGR_RPMS_DIR, when_message, "\n".join(pkgs))
loggerinst.debug(
"Contents of %s directory %s:\n%s",
SUBMGR_RPMS_DIR,
when_message,
"\n".join(pkgs),
)


def exit_on_failed_download(paths):
Expand Down Expand Up @@ -1036,7 +1071,11 @@ def lock_releasever_in_rhel_repositories():
"Updating /etc/yum.repos.d/rehat.repo to point to RHEL %s instead of the default latest minor version."
% system_info.releasever
)
cmd = ["subscription-manager", "release", "--set=%s" % system_info.releasever]
cmd = [
"subscription-manager",
"release",
"--set=%s" % system_info.releasever,
]

output, ret_code = utils.run_subprocess(cmd, print_output=False)
if ret_code != 0:
Expand Down Expand Up @@ -1065,7 +1104,9 @@ def update_rhsm_custom_facts():

if ret_code != 0:
loggerinst.warning(
"Failed to update the RHSM custom facts with return code '%s' and output '%s'.", ret_code, output
"Failed to update the RHSM custom facts with return code '%s' and output '%s'.",
ret_code,
output,
)
else:
loggerinst.info("RHSM custom facts uploaded successfully.")
Expand Down
17 changes: 16 additions & 1 deletion convert2rhel/systeminfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from six.moves import configparser, urllib

from convert2rhel import logger, utils
from convert2rhel import logger, pkgmanager, utils
from convert2rhel.toolopts import tool_opts
from convert2rhel.utils import run_subprocess

Expand Down Expand Up @@ -103,6 +103,7 @@ def __init__(self):
self.kmods_to_ignore = []
# Booted kernel VRA (version, release, architecture), e.g. "4.18.0-240.22.1.el8_3.x86_64"
self.booted_kernel = ""
self.original_releasever = ""

def resolve_system_info(self):
self.logger = logging.getLogger(__name__)
Expand All @@ -125,6 +126,7 @@ def resolve_system_info(self):
self.booted_kernel = self._get_booted_kernel()
self.has_internet_access = self._check_internet_access()
self.dbus_running = self._is_dbus_running()
self.original_releasever = _get_original_releasever()

def print_system_information(self):
"""Print system related information."""
Expand Down Expand Up @@ -468,6 +470,19 @@ def get_system_release_info(self, system_release_content=None):
return release_info


def _get_original_releasever():
"""Get the original value for releasever using either YUM or DNF."""
original_releasever = ""
if pkgmanager.TYPE == "yum":
yb = pkgmanager.YumBase()
original_releasever = yb.conf.yumvar["releasever"]
else:
db = pkgmanager.Base()
original_releasever = db.conf.releasever

return str(original_releasever)


def _is_sysv_managed_dbus_running():
"""Get DBus status from SysVinit compatible systems."""
# None means the status should be retried because we weren't sure if it is turned off.
Expand Down
82 changes: 81 additions & 1 deletion convert2rhel/unit_tests/subscription_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import dbus
import dbus.connection
import dbus.exceptions
import pexpect
import pytest
import six

Expand Down Expand Up @@ -1573,3 +1572,84 @@ def test_update_rhsm_custom_facts_no_rhsm(global_tool_opts, caplog, monkeypatch)

subscription.update_rhsm_custom_facts()
assert "Skipping updating RHSM custom facts." in caplog.records[-1].message


MOCK_LIST_AVAILABLE_SUBS_OUTPUT = """\
Subscription Name: Red Hat\n
Provides: Test\n
SKU: RHTEST\n
Contract: 123456\n
Pool ID: 096fbb526ce611ed-97076c9466263bdf\n
Provides Management: No\n
Available: Unlimited\n
Suggested: 1\n
Service Type: L1-L3\n
Roles: \n
Service Level: Self-Support\n
Usage: \n
Add-ons: \n
Subscription Type: Standard\n
Starts: 03/29/2000\n
Ends: 03/29/2003\n
Entitlement Type: Physical\n
"""


@centos8
def test_get_avail_subs(pretend_os, tmpdir, monkeypatch):
return_value = (MOCK_LIST_AVAILABLE_SUBS_OUTPUT, 0)
cmd = ["subscription-manager", "list", "--available"]
tmpdir.join("releasever").write("8")
dnf_releasever_file = str(tmpdir)
run_subprocess_mock = mock.Mock(
side_effect=unit_tests.run_subprocess_side_effect((cmd, return_value)),
)
monkeypatch.setattr(
utils,
"run_subprocess",
value=run_subprocess_mock,
)
monkeypatch.setattr(subscription, "DNF_RELEASEVER_FILE", dnf_releasever_file)

result = subscription.get_avail_subs()
assert result[0].pool_id == "096fbb526ce611ed-97076c9466263bdf"


@centos8
def test_get_avail_subs_failed_command(pretend_os, tmpdir, monkeypatch, caplog):
return_value = (MOCK_LIST_AVAILABLE_SUBS_OUTPUT, 1)
cmd = ["subscription-manager", "list", "--available"]
tmpdir.join("releasever").write("8")
dnf_releasever_file = str(tmpdir)
run_subprocess_mock = mock.Mock(
side_effect=unit_tests.run_subprocess_side_effect((cmd, return_value)),
)
monkeypatch.setattr(
utils,
"run_subprocess",
value=run_subprocess_mock,
)
monkeypatch.setattr(subscription, "DNF_RELEASEVER_FILE", dnf_releasever_file)

with pytest.raises(SystemExit):
subscription.get_avail_subs()
assert "Unable to get list of available subscriptions:" in caplog.records[-1].message


@centos8
def test_get_avail_subs_no_releasever_file(pretend_os, tmpdir, monkeypatch):
return_value = (MOCK_LIST_AVAILABLE_SUBS_OUTPUT, 0)
cmd = ["subscription-manager", "list", "--available"]
dnf_releasever_file = str(tmpdir.join("releasever"))
run_subprocess_mock = mock.Mock(
side_effect=unit_tests.run_subprocess_side_effect((cmd, return_value)),
)
monkeypatch.setattr(
utils,
"run_subprocess",
value=run_subprocess_mock,
)
monkeypatch.setattr(subscription, "DNF_RELEASEVER_FILE", dnf_releasever_file)

result = subscription.get_avail_subs()
assert result[0].pool_id == "096fbb526ce611ed-97076c9466263bdf"
4 changes: 2 additions & 2 deletions convert2rhel/unit_tests/systeminfo_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
import pytest
import six

from convert2rhel import logger, systeminfo, unit_tests, utils # Imports unit_tests/__init__.py
from convert2rhel import logger, pkgmanager, systeminfo, unit_tests, utils # Imports unit_tests/__init__.py
from convert2rhel.systeminfo import RELEASE_VER_MAPPING, Version, system_info
from convert2rhel.toolopts import tool_opts
from convert2rhel.unit_tests import is_rpm_based_os
from convert2rhel.unit_tests.conftest import all_systems, centos8
from convert2rhel.unit_tests.conftest import all_systems, centos7, centos8


six.add_move(six.MovedModule("mock", "mock", "unittest.mock"))
Expand Down

0 comments on commit cc7cc06

Please sign in to comment.