コード例 #1
0
def upload_tracer_profile(conduit=False):
    data = json.dumps({"traces": get_apps(conduit)})
    headers = {"Content-type": "application/json"}

    conn = httplib.HTTPSConnection(
        RhsmConfigParser.get(initConfig(), "server", "hostname"),
        RhsmConfigParser.get(initConfig(), "server", "port"),
        key_file=ConsumerIdentity.keypath(),
        cert_file=ConsumerIdentity.certpath(),
    )
    conn.request("PUT", "/rhsm/consumers/%s/tracer" % (ConsumerIdentity.read().getConsumerId()), data, headers=headers)
    response = conn.getresponse()
コード例 #2
0
def upload_tracer_profile(conduit=False):
    data =  json.dumps({ "traces": get_apps(conduit) })
    headers = { "Content-type": "application/json" }

    conn = httplib.HTTPSConnection(
            RhsmConfigParser.get(initConfig() ,'server', 'hostname'),
            RhsmConfigParser.get(initConfig() ,'server', 'port'),
            key_file = ConsumerIdentity.keypath(),
            cert_file = ConsumerIdentity.certpath()
           )
    conn.request('PUT', '/rhsm/consumers/%s/tracer' % (ConsumerIdentity.read().getConsumerId()), data, headers=headers)
    response = conn.getresponse()
コード例 #3
0
    def __init__(self, options):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = config.Config(initConfig())

        # 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()
コード例 #4
0
def postconfig_hook(conduit):
    """ update """
    # register rpm name for yum history recording"
    # yum on 5.7 doesn't have this method, so check for it

    from subscription_manager import logutil
    logutil.init_logger_for_yum()

    from subscription_manager.injectioninit import init_dep_injection
    init_dep_injection()

    # If a tool (it's, e.g., Mock) manages a chroot via 'yum --installroot',
    # we must update entitlements in that directory.
    chroot(conduit.getConf().installroot)

    cfg = config.initConfig()
    cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum'))

    if hasattr(conduit, 'registerPackageName'):
        conduit.registerPackageName("subscription-manager")
    try:
        update(conduit, cache_only)
        warnOrGiveUsageMessage(conduit)
        warnExpired(conduit)
    except Exception, e:
        conduit.error(2, str(e))
コード例 #5
0
    def __init__(self, options):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = config.Config(initConfig())

        # 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()
コード例 #6
0
def _try_satellite6_configuration():
    """
    Try to autoconfigure for Satellite 6
    """
    try:
        from rhsm.config import initConfig
        rhsm_config = initConfig()

        logger.debug('Trying to autoconfigure...')
        cert = open(rhsmCertificate.certpath(), 'r').read()
        key = open(rhsmCertificate.keypath(), 'r').read()
        rhsm = rhsmCertificate(key, cert)

        # This will throw an exception if we are not registered
        logger.debug('Checking if system is subscription-manager registered')
        rhsm.getConsumerId()
        logger.debug('System is subscription-manager registered')

        rhsm_hostname = rhsm_config.get('server', 'hostname')
        rhsm_hostport = rhsm_config.get('server', 'port')
        rhsm_proxy_hostname = rhsm_config.get('server',
                                              'proxy_hostname').strip()
        rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip()
        rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip()
        rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip()
        proxy = None
        if rhsm_proxy_hostname != "":
            logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname)
            proxy = "http://"
            if rhsm_proxy_user != "" and rhsm_proxy_pass != "":
                logger.debug("Found user and password for rhsm_proxy")
                proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@"
            proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port
            logger.debug("RHSM Proxy: %s", proxy)
        logger.debug(
            "Found %sHost: %s, Port: %s",
            ('' if _is_rhn_or_rhsm(rhsm_hostname) else 'Satellite 6 Server '),
            rhsm_hostname, rhsm_hostport)
        rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert')
        logger.debug("Found CA: %s", rhsm_ca)
        logger.debug("Setting authmethod to CERT")
        config['authmethod'] = 'CERT'

        # Directly connected to Red Hat, use cert auth directly with the api
        if _is_rhn_or_rhsm(rhsm_hostname):
            logger.debug("Connected to Red Hat Directly, using cert-api")
            rhsm_hostname = 'cert-api.access.redhat.com'
            rhsm_ca = None
        else:
            # Set the host path
            # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url'
            rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access'

        logger.debug("Trying to set auto_configuration")
        set_auto_configuration(rhsm_hostname, rhsm_ca, proxy)
        return True
    except Exception as e:
        logger.debug(e)
        logger.debug('System is NOT subscription-manager registered')
        return False
コード例 #7
0
    def __init__(self, logger, options):
        self.logger = logger
        self.options = options
        self.cert_uuid = None

        self.rhsm_config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()
コード例 #8
0
def _try_satellite6_configuration(config):
    """
    Try to autoconfigure for Satellite 6
    """
    try:
        from rhsm.config import initConfig
        rhsm_config = initConfig()

        logger.debug('Trying to autoconf Satellite 6')
        cert = file(rhsmCertificate.certpath(), 'r').read()
        key = file(rhsmCertificate.keypath(), 'r').read()
        rhsm = rhsmCertificate(key, cert)

        # This will throw an exception if we are not registered
        logger.debug('Checking if system is subscription-manager registered')
        rhsm.getConsumerId()
        logger.debug('System is subscription-manager registered')

        rhsm_hostname = rhsm_config.get('server', 'hostname')
        rhsm_hostport = rhsm_config.get('server', 'port')
        rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip()
        rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip()
        rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip()
        rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip()
        proxy = None
        if rhsm_proxy_hostname != "":
            logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname)
            proxy = "http://"
            if rhsm_proxy_user != "" and rhsm_proxy_pass != "":
                logger.debug("Found user and password for rhsm_proxy")
                proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@"
                proxy = proxy + rhsm_proxy_hostname + rhsm_proxy_port
            else:
                proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port
                logger.debug("RHSM Proxy: %s", proxy)
        logger.debug("Found Satellite Server Host: %s, Port: %s",
                     rhsm_hostname, rhsm_hostport)
        rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert')
        logger.debug("Found CA: %s", rhsm_ca)
        logger.debug("Setting authmethod to CERT")
        config.set(APP_NAME, 'authmethod', 'CERT')

        # Directly connected to Red Hat, use cert auth directly with the api
        if rhsm_hostname == 'subscription.rhn.redhat.com':
            logger.debug("Connected to Red Hat Directly, using cert-api")
            rhsm_hostname = 'cert-api.access.redhat.com'
            rhsm_ca = None
        else:
            # Set the host path
            # 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url'
            rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access'

        logger.debug("Trying to set auto_configuration")
        set_auto_configuration(config, rhsm_hostname, rhsm_ca, proxy)
        return True
    except Exception as e:
        logger.debug(e)
        logger.debug('System is NOT subscription-manager registered')
        return False
コード例 #9
0
    def __init__(self, logger, options, addJob=None):
        self.logger = logger
        self.options = options
        self.cert_uuid = None
        self.addJob = addJob

        self.rhsm_config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()
コード例 #10
0
    def __init__(self, logger):
        self.logger = logger
        self.cert_uuid = None

        self.config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()

        # Consumer ID obtained from consumer certificate
        self.cert_uuid = self.uuid()
コード例 #11
0
    def __init__(self, logger):
        self.logger = logger
        self.cert_uuid = None

        self.config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()

        # Consumer ID obtained from consumer certificate
        self.cert_uuid = self.uuid()
コード例 #12
0
 def readConfig(self):
     """ Parse rhsm.conf in order to obtain consumer
         certificate and key paths. """
     self.rhsm_config = rhsm_config.initConfig(
         rhsm_config.DEFAULT_CONFIG_PATH)
     consumer_cert_dir = self.rhsm_config.get("rhsm", "consumerCertDir")
     cert = 'cert.pem'
     key = 'key.pem'
     self.cert_file = os.path.join(consumer_cert_dir, cert)
     self.key_file = os.path.join(consumer_cert_dir, key)
コード例 #13
0
 def readConfig(self):
     """ Parse rhsm.conf in order to obtain consumer
         certificate and key paths. """
     self.rhsm_config = rhsm_config.initConfig(
         rhsm_config.DEFAULT_CONFIG_PATH)
     consumer_cert_dir = self.rhsm_config.get("rhsm", "consumerCertDir")
     cert = 'cert.pem'
     key = 'key.pem'
     self.cert_file = os.path.join(consumer_cert_dir, cert)
     self.key_file = os.path.join(consumer_cert_dir, key)
コード例 #14
0
 def transaction(self):
     """
     Call Package Profile
     """
     cfg = config.initConfig()
     if '1' == cfg.get('rhsm', 'package_profile_on_trans'):
         package_profile_client = ProfileActionClient()
         package_profile_client.update()
     else:
         # do nothing
         return
コード例 #15
0
    def __init__(self, logger, username=None, password=None):
        self.logger = logger
        self.cert_uuid = None
        self.username = username
        self.password = password

        self.config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()

        # Consumer ID obtained from consumer certificate
        self.cert_uuid = self.uuid()
コード例 #16
0
def posttrans_hook(conduit):
    """
    Upload package profile after transactions if run as a yum plugin (BZ 1742208)
    :param conduit:
    :return: None
    """
    cfg = config.initConfig()
    if '1' == cfg.get('rhsm', 'package_profile_on_trans'):
        conduit.info(3, "Updating package profile")
        package_profile_client = ProfileActionClient()
        package_profile_client.update()
コード例 #17
0
 def transaction(self):
     """
     Call Package Profile
     """
     cfg = config.initConfig()
     if '1' == cfg.get('rhsm', 'package_profile_on_trans'):
         package_profile_client = ProfileActionClient()
         package_profile_client.update()
     else:
         # do nothing
         return
コード例 #18
0
    def __init__(self, logger, username=None, password=None):
        self.logger = logger
        self.cert_uuid = None
        self.username = username
        self.password = password

        self.config = rhsm_config.initConfig(rhsm_config.DEFAULT_CONFIG_PATH)
        self.readConfig()

        # Consumer ID obtained from consumer certificate
        self.cert_uuid = self.uuid()
コード例 #19
0
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.initConfig()
    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))
コード例 #20
0
ファイル: virt_config.py プロジェクト: hao-yu/virt-who-tui
    def __init__(self):
        self.config_name = None
        self.smType = None
        self.smType_label = None
        self.encrypt_pass = True
        self.sat_encrypt_pass = True
        self.rhsm_encrypt_pass = True
        self._rhsm_config = rhsm_config.initConfig(
            rhsm_config.DEFAULT_CONFIG_PATH)

        self.all_fields = self.VIRT_FIELDS + self.SAT_FIELDS + self.RHSM_FIELDS
        # pre-populate all the fields to empty string
        for field in self.all_fields:
            setattr(self, field, None)

        self.logger = logging.getLogger('virt-who-tui')
        hdlr = logging.FileHandler(self.LOG_FILE)
        self.logger.addHandler(hdlr)
        self.logger.setLevel(logging.DEBUG)
コード例 #21
0
    def config(self):
        """ update """
        logutil.init_logger_for_yum()

        init_dep_injection()

        chroot(self.base.conf.installroot)

        cfg = config.initConfig()
        cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum'))

        try:
            if os.getuid() == 0:
                self._update(cache_only)
                self._warnOrGiveUsageMessage()
            else:
                logger.info(_('Not root, Subscription Management repositories not updated'))
            self._warnExpired()
        except Exception as e:
            logger.error(str(e))
コード例 #22
0
    def config(self):
        """ update """
        logutil.init_logger_for_yum()

        init_dep_injection()

        chroot(self.base.conf.installroot)

        cfg = config.initConfig()
        cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum'))

        try:
            if os.getuid() == 0:
                self._update(cache_only)
                self._warnOrGiveUsageMessage()
            else:
                logger.info(_('Not root, Subscription Management repositories not updated'))
            self._warnExpired()
        except Exception as e:
            logger.error(str(e))
コード例 #23
0
def _try_satellite6_configuration(config):
    """
    Try to autoconfigure for Satellite 6
    """
    try:
        from rhsm.config import initConfig
        RHSM_CONFIG = initConfig()

        logger.debug('Trying to autoconf Satellite 6')
        cert = file(rhsmCertificate.certpath(), 'r').read()
        key = file(rhsmCertificate.keypath(), 'r').read()
        rhsm = rhsmCertificate(key, cert)

        # This will throw an exception if we are not registered
        logger.debug('Checking if system is subscription-manager registered')
        rhsm.getConsumerId()
        logger.debug('System is subscription-manager registered')

        rhsm_hostname = RHSM_CONFIG.get('server', 'hostname')
        logger.debug("Found Satellite Server: %s", rhsm_hostname)
        rhsm_ca = RHSM_CONFIG.get('rhsm', 'repo_ca_cert')
        logger.debug("Found CA: %s", rhsm_ca)
        logger.debug("Setting authmethod to CERT")
        config.set(APP_NAME, 'authmethod', 'CERT')

        # Directly connected to Red Hat, use cert auth directly with the api
        if rhsm_hostname == 'subscription.rhn.redhat.com':
            logger.debug("Connected to RH Directly, using cert-api")
            rhsm_hostname = 'cert-api.access.redhat.com'
            rhsm_ca = None
        else:
            # Set the cert verify CA, and path
            rhsm_hostname = rhsm_hostname + '/redhat_access'

        logger.debug("Trying to set auto_configuration")
        set_auto_configuration(config, rhsm_hostname, rhsm_ca)
        return True
    except:
        logger.debug('System is NOT subscription-manager registered')
        return False
コード例 #24
0
def config_hook(conduit):
    """ update """
    # register rpm name for yum history recording"
    # yum on 5.7 doesn't have this method, so check for it

    from subscription_manager import logutil
    logutil.init_logger_for_yum()

    from subscription_manager.injectioninit import init_dep_injection
    init_dep_injection()

    cfg = config.initConfig()
    cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum'))

    if hasattr(conduit, 'registerPackageName'):
        conduit.registerPackageName("subscription-manager")
    try:
        update(conduit, cache_only)
        warnOrGiveUsageMessage(conduit)
        warnExpired(conduit)
    except Exception, e:
        conduit.error(2, str(e))
コード例 #25
0
def config_hook(conduit):
    """ update """
    # register rpm name for yum history recording"
    # yum on 5.7 doesn't have this method, so check for it

    from subscription_manager import logutil
    logutil.init_logger_for_yum()

    from subscription_manager.injectioninit import init_dep_injection
    init_dep_injection()

    cfg = config.initConfig()
    cache_only = not bool(cfg.get_int('rhsm', 'full_refresh_on_yum'))

    if hasattr(conduit, 'registerPackageName'):
        conduit.registerPackageName("subscription-manager")
    try:
        update(conduit, cache_only)
        warnOrGiveUsageMessage(conduit)
        warnExpired(conduit)
    except Exception, e:
        conduit.error(2, str(e))
コード例 #26
0
ファイル: stubs.py プロジェクト: Lorquas/subscription-manager
            return list(items_from_store.items())
        return config.RhsmConfigParser.items(self, section)

    def save(self, config_file=None):
        if self.raise_io:
            raise IOError
        return None


def stubInitConfig():
    return StubConfig()


# create a global CFG object,then replace it with our own that candlepin
# read from a stringio
config.initConfig(config_file="test/rhsm.conf")
config.CFG = StubConfig()

# we are not actually reading test/rhsm.conf, it's just a placeholder
config.CFG.read("test/rhsm.conf")


class MockActionLock(ActionLock):
    PATH = tempfile.mkstemp()[1]


class StubProduct(Product):

    def __init__(self, product_id, name=None, version=None,
                 architectures=None, provided_tags=None,
                 os=None, brand_name=None):
コード例 #27
0
import os
import string
import logging
from urllib import basejoin
from iniparse import ConfigParser

from rhsm.config import initConfig
from rhsm.connection import RemoteServerException, RestlibException

from certlib import ActionLock, DataLib, ConsumerIdentity
from certdirectory import Path, EntitlementDirectory, ProductDirectory

log = logging.getLogger('rhsm-app.' + __name__)

CFG = initConfig()


class RepoLib(DataLib):

    def __init__(self, lock=ActionLock(), uep=None):
        DataLib.__init__(self, lock, uep)

    def _do_update(self):
        action = UpdateAction(uep=self.uep)
        return action.perform()

    def get_repos(self):
        print "get_repos"
        current = set()
        action = UpdateAction(uep=self.uep)
コード例 #28
0
    def save(self, config_file=None):
        if self.raise_io:
            raise IOError
        return None

    # replace read with readfp on stringio


def stubInitConfig():
    return StubConfig()


# create a global CFG object,then replace it with out own that candlepin
# read from a stringio
config.initConfig(config_file="test/rhsm.conf")
config.CFG = StubConfig()

# we are not actually reading test/rhsm.conf, it's just a placeholder
config.CFG.read("test/rhsm.conf")

from datetime import datetime, timedelta

from subscription_manager.certdirectory import EntitlementDirectory, ProductDirectory

from rhsm.certificate import parse_tags
from rhsm.certificate2 import EntitlementCertificate, ProductCertificate, \
        Product, Content, Order
from rhsm import profile

コード例 #29
0
    def __init__(self,
                 backend=None,
                 ent_dir=None,
                 prod_dir=None,
                 auto_launch_registration=False):
        super(MainWindow, self).__init__()

        rhsm_cfg = config.initConfig()
        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()

        if proxy_server:
            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 as err:
                # See https://tools.ietf.org/html/rfc7235#section-4.3
                if "407 Proxy Authentication Required" in 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 rhsmdd for example, or manually provisioned).
        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"
                  ))
コード例 #30
0
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.overrides import Overrides

_ = gettext.gettext

gettext.textdomain("rhsm")

#Gtk.glade.bindtextdomain("rhsm")
#Gtk.Window.set_default_icon_name("subscription-manager")

log = logging.getLogger('rhsm-app.' + __name__)

cfg = config.initConfig()

ONLINE_DOC_URL_TEMPLATE = "https://access.redhat.com/knowledge/docs/Red_Hat_Subscription_Management/?locale=%s"
ONLINE_DOC_FALLBACK_URL = "https://access.redhat.com/knowledge/docs/Red_Hat_Subscription_Management/"


class Backend(object):
    """
    Wrapper for sharing UEP connections to Candlepin.

    Reference to a Backend object will be passed around UI components, so
    the UEP connection it contains can be modified/recreated and all
    components will have the updated connection.

    This also serves as a common wrapper for certifcate directories and methods
    to monitor those directories for changes.
コード例 #31
0
        POOLTYPE_CACHE, RELEASE_STATUS_CACHE, FACTS, POOL_STATUS_CACHE
from subscription_manager import isodate
from subscription_manager.jsonwrapper import PoolWrapper
from subscription_manager.repolib import RepoActionInvoker
from subscription_manager.syspurposelib import SyncedStore
from subscription_manager import utils

# FIXME FIXME
from subscription_manager.identity import ConsumerIdentity
from dateutil.tz import tzlocal

from subscription_manager.i18n import ugettext as _

log = logging.getLogger(__name__)

cfg = initConfig()
ENT_CONFIG_DIR = cfg.get('rhsm', 'entitlementCertDir')

# Expected permissions for identity certificates:
ID_CERT_PERMS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP


def system_log(message, priority=syslog.LOG_NOTICE):
    utils.system_log(message, priority)


# FIXME: move me to identity.py
def persist_consumer_cert(consumerinfo):
    """
     Calls the consumerIdentity, persists and gets consumer info
    """
コード例 #32
0
def _importInitConfig():
    from rhsm.config import initConfig
    return initConfig()
コード例 #33
0
        PROD_STATUS_CACHE, ENT_DIR, PROD_DIR, CP_PROVIDER, OVERRIDE_STATUS_CACHE, \
        POOLTYPE_CACHE
from subscription_manager import isodate
from subscription_manager.jsonwrapper import PoolWrapper
from subscription_manager.repolib import RepoActionInvoker
from subscription_manager import utils

# FIXME FIXME
from subscription_manager.identity import ConsumerIdentity
from dateutil.tz import tzlocal

log = logging.getLogger('rhsm-app.' + __name__)

_ = gettext.gettext

cfg = initConfig()
ENT_CONFIG_DIR = cfg.get('rhsm', 'entitlementCertDir')

# Expected permissions for identity certificates:
ID_CERT_PERMS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP


def system_log(message, priority=syslog.LOG_NOTICE):
    utils.system_log(message, priority)


# FIXME: move me to identity.py
def persist_consumer_cert(consumerinfo):
    """
     Calls the consumerIdentity, persists and gets consumer info
    """
コード例 #34
0
def is_hosted():
    rhsmcfg = config.Config(initConfig())
    hostname = rhsmcfg['server']['hostname']
    return bool(re.search('subscription\.rhn\.(.*\.)*redhat\.com', hostname) or
                re.search('subscription\.rhsm\.(.*\.)*redhat\.com', hostname))
コード例 #35
0
    def __init__(self):
        super(CallbackModule, self).__init__()
        self.items = defaultdict(list)
        self.insights_system_ids = defaultdict(list)
        self.start_time = int(time.time())

        possible_conf_paths = [
            "/etc/redhat-access-insights/redhat-access-insights.conf",
            "/etc/insights-client/insights-client.conf",
            os.path.expanduser('~/.insights.conf'),
        ]

        possible_conf_sections = [
            "insights-client",
            "redhat-access-insights",
            "redhat_access_insights",
        ]

        path = os.getenv('INSIGHTS_CONF')
        if path:
            possible_conf_paths.append(path)

        self.insights_config = self.parse_config_file(possible_conf_paths)
        self.base_url = "https://cert-api.access.redhat.com/r/insights"

        self.v3("Searching for Insights config sections from: %s" %
                possible_conf_sections)
        self.insights_config_section = None
        for each in possible_conf_sections:
            if self.insights_config.has_section(each):
                self.insights_config_section = each
                break
        self.v3("Using Insights config section: %s" %
                self.insights_config_section)

        username = None
        password = None
        cert = None

        if self.insights_config_section:
            username = self.insights_config.get(self.insights_config_section,
                                                "username")
            password = self.insights_config.get(self.insights_config_section,
                                                "password")

        if username:
            self.v3(
                "Found 'username' in configuration, using BASIC AUTH to login to Insights"
            )
            if password == None:
                password = ""
                self.warning(
                    "Found NO 'password' in configuration, using BASIC AUTH with empty password"
                )
        else:
            self.v3(
                "Not using BASIC AUTH to login to Insights, could not find 'username' in configuration"
            )
            try:
                from rhsm.config import initConfig
                rhsm_config = initConfig()
                rhsm_consumerCertDir = rhsm_config.get('rhsm',
                                                       'consumerCertDir')

                cert_filename = os.path.join(rhsm_consumerCertDir, "cert.pem")
                rhsm_key_filename = os.path.join(rhsm_consumerCertDir,
                                                 "key.pem")

                def try_open(file, file_kind):
                    try:
                        self.v3("Found %s: %s" % (file_kind, file))
                        open(file).close()
                    except Exception as ex:
                        self.v3("Could not open %s %s: %s" %
                                (file_kind, file, ex))
                        raise ex

                try_open(cert_filename, "RHSM CERT")
                try_open(rhsm_key_filename, "RHSM KEY")

                cert = (cert_filename, rhsm_key_filename)

            except Exception as ex:
                self.v3(
                    "Not using CERT AUTH to login to Insights, could not load RHSM CERT or KEY: %s"
                    % ex)

        self.session = None
        if username or cert:
            self.v3("Setting up HTTP Session")
            self.session = requests.Session()
            self.session.auth = (username, password)
            self.session.cert = cert

            possible_CA_VERIFY_files = [
                "/etc/rhsm/ca/redhat-uep.pem",
                "/etc/redhat-access-insights/cert-api.access.redhat.com.pem",
                "/etc/insights-client/cert-api.access.redhat.com.pem",
            ]

            self.session.verify = False
            for filename in possible_CA_VERIFY_files:
                try:
                    with open(filename):
                        self.session.verify = filename
                        break
                except:
                    pass
            self.v3("HTTP Session VERIFY %s" % self.session.verify)

            self.session.headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'notify_insights',
                'Accept': 'application/json',
            }

            if not self.get(self.base_url + "/v1/branch_info", [200]):
                self.session = None

        else:
            self.error(
                "Not sending results to Insights, not registered and username/password not available"
            )
コード例 #36
0
ファイル: utils.py プロジェクト: cnsnyder/katello-host-tools
def subman_profile_enabled():
    cfg = rhsmConfig.initConfig()
    try:
        return cfg.get('rhsm', 'package_profile_on_trans') == '1'
    except NoOptionError:
        return False
コード例 #37
0
"""
Module to interact with Satellite Based Certificates
"""
from __future__ import print_function
import os
import logging

logger = logging.getLogger(__name__)

# RHSM and Subscription Manager
RHSM_CONFIG = None
try:
    from rhsm.config import initConfig
    from rhsm.certificate import create_from_pem
    RHSM_CONFIG = initConfig()
except ImportError:
    logger.debug("Could not load RHSM modules")


# Class for dealing with rhsmCertificates
class rhsmCertificate:

    try:
        PATH = RHSM_CONFIG.get('rhsm', 'consumerCertDir')
    except:
        pass

    KEY = 'key.pem'
    CERT = 'cert.pem'

    @classmethod
コード例 #38
0
        ServiceLevelNotSupportedException, AllProductsCoveredException, \
        NoProductsException
from subscription_manager.gui.messageWindow import InfoDialog, OkDialog
from subscription_manager.jsonwrapper import PoolWrapper

_ = lambda x: gettext.ldgettext("rhsm", x)

gettext.textdomain("rhsm")

gtk.glade.bindtextdomain("rhsm")

gtk.glade.textdomain("rhsm")

log = logging.getLogger('rhsm-app.' + __name__)

CFG = config.initConfig()

REGISTERING = 0
SUBSCRIBING = 1
state = REGISTERING


def get_state():
    global state
    return state


def set_state(new_state):
    global state
    state = new_state
コード例 #39
0
"""
Module to interact with Satellite Based Certificates
"""
import os
import logging
from constants import InsightsConstants as constants

logger = logging.getLogger(constants.app_name)

# RHSM and Subscription Manager
RHSM_CONFIG = None
try:
    from rhsm.config import initConfig
    from rhsm.certificate import create_from_pem
    RHSM_CONFIG = initConfig()
except ImportError:
    logger.debug("Could not load RHSM modules")


# Class for dealing with rhsmCertificates
class rhsmCertificate:

    try:
        PATH = RHSM_CONFIG.get('rhsm', 'consumerCertDir')
    except:
        pass

    KEY = 'key.pem'
    CERT = 'cert.pem'

    @classmethod
コード例 #40
0
import subscription_manager.injection as inj
from subscription_manager.cache import OverrideStatusCache, WrittenOverrideCache
from subscription_manager import utils
from subscription_manager import model
from subscription_manager.model import ent_cert

from rhsm.config import initConfig

# FIXME: local imports

from subscription_manager.certlib import ActionReport, BaseActionInvoker
from subscription_manager.certdirectory import Path

log = logging.getLogger('rhsm-app.' + __name__)

CFG = initConfig()

ALLOWED_CONTENT_TYPES = ["yum"]

_ = gettext.gettext


def manage_repos_enabled():
    manage_repos = True
    try:
        manage_repos = CFG.get_int('rhsm', 'manage_repos')
    except ValueError, e:
        log.exception(e)
        return True
    except ConfigParserError, e:
        log.exception(e)
コード例 #41
0
except ImportError as e:
    HAS_DEB822 = False

from subscription_manager import utils
from subscription_manager.certdirectory import Path
from six.moves import configparser
from six.moves.urllib.parse import parse_qs, urlparse, urlunparse, urlencode

from rhsm.config import initConfig

from rhsmlib.services import config


log = logging.getLogger(__name__)

conf = config.Config(initConfig())

repo_files = []


class Repo(dict):
    # (name, mutable, default) - The mutability information is only used in disconnected cases
    PROPERTIES = {
            'name': (0, None),
            'baseurl': (0, None),
            'enabled': (1, '1'),
            'gpgcheck': (1, '1'),
            'gpgkey': (0, None),
            'sslverify': (1, '1'),
            'sslcacert': (0, None),
            'sslclientkey': (0, None),
コード例 #42
0
def is_hosted():
    rhsmcfg = config.Config(initConfig())
    hostname = rhsmcfg['server']['hostname']
    return bool(
        re.search('subscription\.rhn\.(.*\.)*redhat\.com', hostname)
        or re.search('subscription\.rhsm\.(.*\.)*redhat\.com', hostname))
コード例 #43
0
import rhsm.connection as connection
from rhsm.profile import get_profile
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 rhsmlib.services import config, syspurpose

from subscription_manager.i18n import ugettext as _

log = logging.getLogger(__name__)

PACKAGES_RESOURCE = "packages"

conf = config.Config(initConfig())


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):
        """
コード例 #44
0
import re

# iniparse.utils isn't in old versions
# but it's always there if ostree is
iniparse_tidy = None
try:
    from iniparse.utils import tidy as iniparse_tidy
except ImportError:
    pass

from rhsm import config
from subscription_manager import utils

log = logging.getLogger("rhsm-app." + __name__)

CFG = config.initConfig()
"""Ostree has two config files, both based on the freedesktop.org
Desktop Entry spec. This defines a file format based on "ini" style
config files. Ostree refers to these as "key files".

One config file is the "repo" config, that defines some
core config options, and the ostree "remotes".

The other is an "origin" file that includes a refspec
for a given ostree sha.

We base the config parser on rhsm.config.RhsmConfigParser,
except with "defaults" support removed.

We has a KeyFileConfigParser, and two subclasses of it
for RepoFileConfigParser and OriginFileConfigParser.
コード例 #45
0
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.initConfig()

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",
コード例 #46
0
    def __init__(self, backend=None,
                 ent_dir=None, prod_dir=None,
                 auto_launch_registration=False):
        super(MainWindow, self).__init__()

        rhsm_cfg = config.initConfig()
        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()

        if proxy_server:
            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 as err:
                # See https://tools.ietf.org/html/rfc7235#section-4.3
                if "407 Proxy Authentication Required" in 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 rhsmdd for example, or manually provisioned).
        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")
            )
コード例 #47
0
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.info('X-Correlation-ID: %s', correlation_id)
    cp_provider.set_correlation_id(correlation_id)
    cfg = config.initConfig()

    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)

    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()
    cp.supports_resource(None)  # pre-load supported resources; serves as a way of failing before locking the repos

    try:
        if options.autoheal:
            actionclient = action_client.HealingActionClient()
        else:
            actionclient = action_client.ActionClient()

        actionclient.update(options.autoheal)

        for update_report in actionclient.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
コード例 #48
0
ファイル: utils.py プロジェクト: Katello/katello-agent
def subman_profile_enabled():
    cfg = rhsmConfig.initConfig()
    try:
        return cfg.get('rhsm', 'package_profile_on_trans') == '1'
    except NoOptionError:
        return False