def __init__(self, options): self.rhncfg = initUp2dateConfig() self.rhsmcfg = config.Config(get_config_parser()) # Sometimes we need to send up the entire contents of the system id file # which is referred to in Satellite 5 nomenclature as a "certificate" # although it is not an X509 certificate. try: self.system_id_contents = open(self.rhncfg["systemIdPath"], 'r').read() except IOError: system_exit( os.EX_IOERR, _("Could not read legacy system id at %s") % self.rhncfg["systemIdPath"]) self.system_id = self.get_system_id(self.system_id_contents) self.proxy_host = None self.proxy_port = None self.proxy_user = None self.proxy_pass = None self.cp = None self.db = ProductDatabase() self.consumer_id = None self.options = options self.is_hosted = is_hosted()
def posttrans_hook(conduit): """ Upload package profile after transactions if run as a yum plugin (BZ 1742208) :param conduit: :return: None """ cfg = config.get_config_parser() if '1' == cfg.get('rhsm', 'package_profile_on_trans'): conduit.info(3, "Updating package profile") package_profile_client = ProfileActionClient() package_profile_client.update()
def transaction(self): """ Call Package Profile """ cfg = config.get_config_parser() if '1' == cfg.get('rhsm', 'package_profile_on_trans'): log.debug('Uploading package profile') package_profile_client = ProfileActionClient() package_profile_client.update() else: log.debug('Uploading package profile disabled in configuration file')
def transaction(self): """ Call Package Profile """ cfg = config.get_config_parser() if "1" == cfg.get("rhsm", "package_profile_on_trans"): log.debug("Uploading package profile") package_profile_client = ProfileActionClient() package_profile_client.update() else: log.debug("Uploading package profile disabled in configuration file")
def prereposetup_hook(conduit): """ Try to update configuration of redhat.repo, before yum tries to load configuration of repositories. :param conduit: Reference on conduit object used by yum plugin API :return: None """ cfg = config.get_config_parser() cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum')) try: update(conduit, cache_only) except Exception as e: conduit.error(2, str(e))
def setup(self): # rhsm config and logs self.add_copy_spec([ "/etc/rhsm/", "/var/lib/rhsm/", "/var/log/rhsm/rhsm.log", "/var/log/rhsm/rhsmcertd.log"]) self.add_cmd_output([ "subscription-manager list --installed", "subscription-manager list --available", "subscription-manager list --all --available", "subscription-manager list --consumed", "subscription-manager identity", "subscription-manager release --show", "subscription-manager release --list", "syspurpose show", "subscription-manager syspurpose --show", ], cmd_as_tag=True) self.add_cmd_output("rhsm-debug system --sos --no-archive " "--no-subscriptions --destination %s" % self.get_cmd_output_path()) certs = glob.glob('/etc/pki/product-default/*.pem') self.add_cmd_output(["rct cat-cert %s" % cert for cert in certs], tags='subscription_manager_installed_product_ids') # try curl to the RHSM server for potential certificate/proxy issue curlcmd = "curl -vv --cacert /etc/rhsm/ca/redhat-uep.pem " \ "https://subscription.rhsm.redhat.com:443/subscription" env = None # for no_proxy try: from rhsm.config import get_config_parser config = get_config_parser() proxy = self.get_proxy_string(config) server_url = self.get_server_url(config) curlcmd = "curl -vv %s --cacert %s %s" % \ (server_url, config.get('rhsm', 'repo_ca_cert'), proxy) # honour os.environ no_proxy, if set no_proxy = config.get('server', 'no_proxy') if no_proxy: env = {'NO_PROXY': no_proxy} except (ModuleNotFoundError, ImportError, NoOptionError, NoSectionError): pass self.add_cmd_output(curlcmd, env=env, timeout=30)
def _config(self): """ update """ logutil.init_logger_for_yum() init_dep_injection() chroot(self.base.conf.installroot) cfg = config.get_config_parser() cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum')) try: if os.getuid() == 0: # Try to update entitlement certificates and redhat.repo file self._update(cache_only) else: logger.info(_('Not root, Subscription Management repositories not updated')) self._warn_or_give_usage_message() self._warn_expired() except Exception as e: log.error(str(e))
import subscription_manager.injection as inj from subscription_manager.jsonwrapper import PoolWrapper from rhsm import ourjson as json from subscription_manager.isodate import parse_date from subscription_manager.utils import get_supported_resources from subscription_manager.syspurposelib import post_process_received_data from rhsmlib.services import config, syspurpose from subscription_manager.i18n import ugettext as _ log = logging.getLogger(__name__) PACKAGES_RESOURCE = "packages" conf = config.Config(get_config_parser()) class CacheManager(object): """ Parent class used for common logic in a number of collections where we need to push some consumer JSON up to the server, maintain a local cache of that data, and check if anything has changed on subsequent runs. """ # Fields the subclass must override: CACHE_FILE = None def to_dict(self): """
import logging import shutil import tarfile import tempfile from datetime import datetime from . import fixture from .test_managercli import TestCliCommand from rhsm_debug import debug_commands from rhsm_debug import cli from rhsm.config import get_config_parser from subscription_manager.cli import InvalidCLIOptionError cfg = get_config_parser() log = logging.getLogger(__name__) def path_join(first, second): if os.path.isabs(second): second = second[1:] return os.path.join(first, second) class TestRhsmDebugCLI(fixture.SubManFixture): def test_init(self): cli_obj = cli.RhsmDebugCLI() # we populated cli_commands self.assertTrue(cli_obj.cli_commands)
def is_hosted(): rhsmcfg = config.Config(get_config_parser()) hostname = rhsmcfg['server']['hostname'] return bool( re.search('subscription\.rhn\.(.*\.)*redhat\.com', hostname) or re.search('subscription\.rhsm\.(.*\.)*redhat\.com', hostname))
def __init__(self, backend=None, ent_dir=None, prod_dir=None, auto_launch_registration=False): super(MainWindow, self).__init__() rhsm_cfg = config.get_config_parser() proxy_server = rhsm_cfg.get("server", "proxy_hostname") proxy_port = int( rhsm_cfg.get("server", "proxy_port") or config.DEFAULT_PROXY_PORT) def show_proxy_error_dialog(proxy_auth_required=False): """ When proxy server is set in configuration and it is not possible to connect to proxy server, then open dialog for setting proxy server. """ if proxy_auth_required: proxy_user = rhsm_cfg.get("server", "proxy_user") proxy_password = rhsm_cfg.get("server", "proxy_password") if proxy_user or proxy_password: err_msg = _( "Wrong proxy username or password, please check your settings." ) else: err_msg = _( "Proxy authentication required, please check your settings." ) else: err_msg = _( "Proxy connection failed, please check your settings.") print_error(err_msg) error_dialog = messageWindow.ContinueDialog( err_msg, self._get_window()) error_dialog.connect("response", self._on_proxy_error_dialog_response) self.network_config_dialog = networkConfig.NetworkConfigDialog() # Sub-man gui will be terminated after saving settings and it is # necessary to start it once again. self.network_config_dialog.saveButton.connect( "clicked", self._exit) self.network_config_dialog.cancelButton.connect( "clicked", self._exit) self.backend = backend or Backend() cp = self.backend.cp_provider.get_consumer_auth_cp() # allow specifying no_proxy via api or config no_proxy = rhsm_cfg.get('server', 'no_proxy') if no_proxy: os.environ['no_proxy'] = no_proxy rhsm_utils.fix_no_proxy() log.debug('Environment variable NO_PROXY=%s will be used' % no_proxy) # Don't check the proxy server if the hostname we aim to connect to is covered by no_proxy if proxy_server and not urllib.request.proxy_bypass( rhsm_cfg.get('server', 'hostname')): if not utils.test_proxy_reachability(proxy_server, proxy_port): show_proxy_error_dialog() return try: # Try to send to the simplest Rest API call to Candlepin server. # This result will be used for getting version of Candlepin server. # See self.log_server_version. cp.supports_resource("status") except (socket.error, connection.ProxyException) as err: # See https://tools.ietf.org/html/rfc7235#section-4.3 if "407 Proxy Authentication Required" in str(err.message): show_proxy_error_dialog(proxy_auth_required=True) return self.identity = require(IDENTITY) log.debug("Client Versions: %s " % get_client_versions()) ga_GLib.idle_add(self.log_server_version, cp) settings = self.main_window.get_settings() # prevent gtk from trying to save a list of recently used files, which # as root, causes gtk warning: # "Attempting to set the permissions of `/root/.local/share/recently-used.xbel' # The __name__ use is just for the 'origin' value gtk uses to store # where a Gtk.Settings value was set. settings.set_long_property('gtk-recent-files-max-age', 0, "%s:%s" % (__name__, type(self).__name__)) ga_Gtk.Window.set_default_icon_name("subscription-manager") self.product_dir = prod_dir or self.backend.product_dir self.entitlement_dir = ent_dir or self.backend.entitlement_dir self.system_facts_dialog = factsgui.SystemFactsDialog( update_callback=self._handle_facts_updated) self.preferences_dialog = PreferencesDialog(self.backend, self._get_window()) self.repos_dialog = RepositoriesDialog(self.backend, self._get_window()) self.import_sub_dialog = ImportSubDialog() self.network_config_dialog = networkConfig.NetworkConfigDialog() self.network_config_dialog.saveButton.connect("clicked", self._config_changed) self.redeem_dialog = redeem.RedeemDialog(self.backend) self.installed_tab_icon = ga_Gtk.Image() self.installed_tab_icon.set_from_stock(ga_Gtk.STOCK_YES, ga_Gtk.IconSize.MENU) self.installed_tab = InstalledProductsTab(self.backend, self.installed_tab_icon, self, ent_dir=self.entitlement_dir, prod_dir=self.product_dir) self.my_subs_tab = MySubscriptionsTab(self.backend, self.main_window, ent_dir=self.entitlement_dir, prod_dir=self.product_dir) self.all_subs_tab = AllSubscriptionsTab(self.backend, self.main_window) hbox = ga_Gtk.HBox(spacing=6) hbox.pack_start(self.installed_tab_icon, False, False, 0) hbox.pack_start(ga_Gtk.Label(self.installed_tab.get_label()), False, False, 0) self.notebook.append_page(self.installed_tab.get_content(), hbox) hbox.show_all() self.notebook.append_page(self.my_subs_tab.get_content(), ga_Gtk.Label(self.my_subs_tab.get_label())) self.connect_signals({ "on_register_menu_item_activate": self._register_item_clicked, "on_unregister_menu_item_activate": self._unregister_item_clicked, "on_import_cert_menu_item_activate": self._import_cert_item_clicked, "on_view_facts_menu_item_activate": self._facts_item_clicked, "on_proxy_config_menu_item_activate": self._proxy_config_item_clicked, "on_redeem_menu_item_activate": self._redeem_item_clicked, "on_preferences_menu_item_activate": self._preferences_item_clicked, "on_repos_menu_item_activate": self._repos_item_clicked, "on_about_menu_item_activate": self._about_item_clicked, "on_getting_started_menu_item_activate": self._getting_started_item_clicked, "on_online_docs_menu_item_activate": self._online_docs_item_clicked, "on_quit_menu_item_activate": ga_Gtk.main_quit, }) # various state tracking for async operations self._show_overrides = False self._can_redeem = False self.backend.cs.add_callback(self.on_cert_sorter_cert_change) self.main_window.show_all() # Check to see if already registered to old RHN/Spacewalk # and show dialog if so self._check_rhn_classic() # Update everything with compliance data self.backend.cs.notify() # managergui needs cert_sort.cert_monitor.run_check() to run # on a timer to detect cert changes from outside the gui # (via manual provisioning). cert_monitor_thread = threading.Thread(target=self._cert_check_timer, name="CertMonitorThread") cert_monitor_thread.daemon = True cert_monitor_thread.start() if auto_launch_registration and not self.registered(): self._register_item_clicked(None) enabled_yum_plugins = YumPluginManager.enable_pkg_plugins() if len(enabled_yum_plugins) > 0: messageWindow.InfoDialog( YumPluginManager.warning_message(enabled_yum_plugins), self._get_window(), _("Warning - subscription-manager plugins were automatically enabled" ))
from subscription_manager.gui.allsubs import AllSubscriptionsTab from subscription_manager.gui.importsub import ImportSubDialog from subscription_manager.gui.installedtab import InstalledProductsTab from subscription_manager.gui.mysubstab import MySubscriptionsTab from subscription_manager.gui.preferences import PreferencesDialog from subscription_manager.gui.utils import handle_gui_exception, linkify from subscription_manager.gui.reposgui import RepositoriesDialog from subscription_manager.gui.networkConfig import reset_resolver from subscription_manager.overrides import Overrides from subscription_manager.cli import system_exit from subscription_manager.i18n import ugettext as _ log = logging.getLogger(__name__) cfg = config.get_config_parser() ONLINE_DOC_URL_TEMPLATE = "https://access.redhat.com/documentation/%s/red_hat_subscription_management/" ONLINE_DOC_FALLBACK_URL = "https://access.redhat.com/documentation/en-us/red_hat_subscription_management/" # every GUI browser from https://docs.python.org/2/library/webbrowser.html with updates within last 2 years of writing PREFERRED_BROWSERS = [ "mozilla", "firefox", "epiphany", "konqueror", "opera", "google-chrome", "chrome", "chromium", "chromium-browser",
def _main(options, log): # Set default mainloop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # exit on SIGTERM, otherwise finally statements don't run (one explanation: http://stackoverflow.com/a/41840796) # SIGTERM happens for example when systemd wants the service to stop # without finally statements, we get confusing behavior (ex. see bz#1431659) signal.signal(signal.SIGTERM, exit_on_signal) cp_provider = inj.require(inj.CP_PROVIDER) correlation_id = generate_correlation_id() log.debug("X-Correlation-ID: %s", correlation_id) cp_provider.set_correlation_id(correlation_id) cfg = config.get_config_parser() log.debug("check for rhsmcertd disable") if "1" == cfg.get("rhsmcertd", "disable") and not options.force: log.warning("The rhsmcertd process has been disabled by configuration.") sys.exit(-1) # Was script executed with --auto-register option if options.auto_register is True: _auto_register(cp_provider, log) if not ConsumerIdentity.existsAndValid(): log.error( "Either the consumer is not registered or the certificates" + " are corrupted. Certificate update using daemon failed." ) sys.exit(-1) print(_("Updating entitlement certificates & repositories")) cp = cp_provider.get_consumer_auth_cp() # pre-load supported resources; serves as a way of failing before locking the repos cp.supports_resource(None) try: if options.autoheal: action_client = HealingActionClient() else: action_client = ActionClient() action_client.update(options.autoheal) for update_report in action_client.update_reports: # FIXME: make sure we don't get None reports if update_report: print(update_report) except connection.ExpiredIdentityCertException as e: log.critical(_("Your identity certificate has expired")) raise e except connection.GoneException as ge: uuid = ConsumerIdentity.read().getConsumerId() # This code is to prevent an errant 410 response causing consumer cert deletion. # # If a server responds with a 410, we want to very that it's not just a 410 http status, but # also that the response is from candlepin, and include the right info about the consumer. # # A connection to the entitlement server could get an unintentional 410 response. A common # cause for that kind of error would be a bug or crash or misconfiguration of a reverse proxy # in front of candlepin. Most error codes we treat as temporary and transient, and they don't # cause any action to be taken (aside from error handling). But since consumer deletion is tied # to the 410 status code, and that is difficult to recover from, we try to be a little bit # more paranoid about that case. # # So we look for both the 410 status, and the expected response body. If we get those # then python-rhsm will create a GoneException that includes the deleted_id. If we get # A GoneException and the deleted_id matches, then we actually delete the consumer. # # However... If we get a GoneException and it's deleted_id does not match the current # consumer uuid, we do not delete the consumer. That would require using a valid consumer # cert, but making a request for a different consumer uuid, so unlikely. Could register # with --consumerid get there? if ge.deleted_id == uuid: log.critical( 'Consumer profile "%s" has been deleted from the server. Its local certificates will now be archived', uuid, ) managerlib.clean_all_data() log.critical( "Certificates archived to '/etc/pki/consumer.old'. Contact your system administrator if you need more information." ) raise ge
from subscription_manager import ga_loader ga_loader.init_ga() from subscription_manager.ga import GLib from functools import partial from rhsmlib.services import config from rhsm.config import get_config_parser from rhsmlib.file_monitor import create_filesystem_watcher, DirectoryWatch from rhsmlib.file_monitor import CONSUMER_WATCHER, ENTITLEMENT_WATCHER, CONFIG_WATCHER, PRODUCT_WATCHER, \ SYSPURPOSE_WATCHER from subscription_manager import injection as inj from rhsm.logutil import init_logger log = logging.getLogger(__name__) parser = get_config_parser() conf = config.Config(parser) init_logger(parser) class Server(object): """ Class used for rhsm.service providing D-Bus API """ INSTANCE = None def __new__(cls, *args, **kwargs): """ Function called, when new instance of Server is requested