def set_connection_info(
        self,
        host=None,
        ssl_port=None,
        handler=None,
        cert_file=None,
        key_file=None,
        proxy_hostname_arg=None,
        proxy_port_arg=None,
        proxy_user_arg=None,
        proxy_password_arg=None,
    ):

        self.cert_file = ConsumerIdentity.certpath()
        self.key_file = ConsumerIdentity.keypath()

        # only use what was passed in, let the lowest level deal with
        # no values and look elsewhere for them.
        self.server_hostname = host
        self.server_port = ssl_port
        self.server_prefix = handler
        self.proxy_hostname = proxy_hostname_arg
        self.proxy_port = proxy_port_arg
        self.proxy_user = proxy_user_arg
        self.proxy_password = proxy_password_arg
        self.clean()
Esempio n. 2
0
    def _update(self, cache_only):
        """ update entitlement certificates """
        logger.info(_('Updating Subscription Management repositories.'))

        # XXX: Importing inline as you must be root to read the config file
        from subscription_manager.identity import ConsumerIdentity

        cert_file = str(ConsumerIdentity.certpath())
        key_file = str(ConsumerIdentity.keypath())

        identity = inj.require(inj.IDENTITY)

        # In containers we have no identity, but we may have entitlements inherited
        # from the host, which need to generate a redhat.repo.
        if identity.is_valid():
            try:
                connection.UEPConnection(cert_file=cert_file,
                                         key_file=key_file)
            # FIXME: catchall exception
            except Exception:
                # log
                logger.info(
                    _("Unable to connect to Subscription Management Service"))
                return
        else:
            logger.info(_("Unable to read consumer identity"))

        if config.in_container():
            logger.info(
                _("Subscription Manager is operating in container mode."))

        rl = RepoActionInvoker(cache_only=cache_only)
        rl.update()
Esempio n. 3
0
def update(conduit, cache_only):
    """ update entitlement certificates """
    if os.getuid() != 0:
        conduit.info(3, 'Not root, Subscription Management repositories not updated')
        return
    conduit.info(3, 'Updating Subscription Management repositories.')

    # XXX: Importing inline as you must be root to read the config file
    from subscription_manager.identity import ConsumerIdentity

    cert_file = ConsumerIdentity.certpath()
    key_file = ConsumerIdentity.keypath()

    identity = inj.require(inj.IDENTITY)

    # In containers we have no identity, but we may have entitlements inherited
    # from the host, which need to generate a redhat.repo.
    if identity.is_valid():
        try:
            connection.UEPConnection(cert_file=cert_file, key_file=key_file)
        #FIXME: catchall exception
        except Exception:
            # log
            conduit.info(2, "Unable to connect to Subscription Management Service")
            return
    else:
        conduit.info(3, "Unable to read consumer identity")

    if config.in_container():
        conduit.info(3, "Subscription Manager is operating in container mode.")

    rl = RepoActionInvoker(cache_only=cache_only, locker=YumRepoLocker(conduit=conduit))
    rl.update()
Esempio n. 4
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        # Delete backup dir if it exists:
        shutil.rmtree(consumer_dir_backup, ignore_errors=True)

        # Copy current consumer dir:
        log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup)
        shutil.copytree(consumer_dir, consumer_dir_backup)


# FIXME FIXME
# Delete current consumer certs:
    for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]:
        if (os.path.exists(path)):
            log.debug("Removing identity cert: %s" % path)
            os.remove(path)

    require(IDENTITY).reload()

    # Delete all entitlement certs rather than the directory itself:
    ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir')
    if os.path.exists(ent_cert_dir):

        for f in glob.glob("%s/*.pem" % ent_cert_dir):
            certpath = os.path.join(ent_cert_dir, f)
            log.debug("Removing entitlement cert: %s" % f)
            os.remove(certpath)
    else:
        log.warn("Entitlement cert directory does not exist: %s" %
                 ent_cert_dir)

    # Subclasses of cache.CacheManager have a @classmethod delete_cache
    # for deleting persistent caches
    cache.ProfileManager.delete_cache()
    cache.InstalledProductsManager.delete_cache()
    cache.SyspurposeCache.delete_cache()

    # FIXME: implement as dbus client to facts service DeleteCache() once implemented
    #Facts.delete_cache()

    # WrittenOverridesCache is also a subclass of cache.CacheManager, but
    # it is deleted in RepoActionInvoker.delete_repo_file() below.

    # StatusCache subclasses have a a per instance cache varable
    # and delete_cache is an instance method, so we need to call
    # the delete_cache on the instances created in injectioninit.
    require(ENTITLEMENT_STATUS_CACHE).delete_cache()
    require(PROD_STATUS_CACHE).delete_cache()
    require(POOL_STATUS_CACHE).delete_cache()
    require(OVERRIDE_STATUS_CACHE).delete_cache()
    require(RELEASE_STATUS_CACHE).delete_cache()

    RepoActionInvoker.delete_repo_file()
    log.info("Cleaned local data")
def update(conduit, cache_only):
    """ update entitlement certificates """
    if os.getuid() != 0:
        conduit.info(
            3, 'Not root, Subscription Management repositories not updated')
        return
    conduit.info(3, 'Updating Subscription Management repositories.')

    # XXX: Importing inline as you must be root to read the config file
    from subscription_manager.identity import ConsumerIdentity

    cert_file = ConsumerIdentity.certpath()
    key_file = ConsumerIdentity.keypath()

    identity = inj.require(inj.IDENTITY)

    if not identity.is_valid():
        conduit.info(3, "Unable to read consumer identity")
        return

    try:
        connection.UEPConnection(cert_file=cert_file, key_file=key_file)
    #FIXME: catchall exception
    except Exception:
        # log
        conduit.info(2, "Unable to connect to Subscription Management Service")
        return

    rl = RepoActionInvoker(cache_only=cache_only)
    rl.update()
def update(conduit, cache_only):
    """ update entitlement certificates """
    if os.getuid() != 0:
        conduit.info(3, 'Not root, Subscription Management repositories not updated')
        return
    conduit.info(3, 'Updating Subscription Management repositories.')

    # XXX: Importing inline as you must be root to read the config file
    from subscription_manager.identity import ConsumerIdentity

    cert_file = ConsumerIdentity.certpath()
    key_file = ConsumerIdentity.keypath()

    identity = inj.require(inj.IDENTITY)

    if not identity.is_valid():
        conduit.info(3, "Unable to read consumer identity")
        return

    try:
        uep = connection.UEPConnection(cert_file=cert_file, key_file=key_file)
    #FIXME: catchall exception
    except Exception:
        # log
        conduit.info(2, "Unable to connect to Subscription Management Service")
        return

    rl = RepoActionInvoker(uep=uep, cache_only=cache_only)
    rl.update()
    def _update(self, cache_only):
        """ update entitlement certificates """
        logger.info(_('Updating Subscription Management repositories.'))

        # XXX: Importing inline as you must be root to read the config file
        from subscription_manager.identity import ConsumerIdentity

        cert_file = str(ConsumerIdentity.certpath())
        key_file = str(ConsumerIdentity.keypath())

        identity = inj.require(inj.IDENTITY)

        # In containers we have no identity, but we may have entitlements inherited
        # from the host, which need to generate a redhat.repo.
        if identity.is_valid():
            try:
                connection.UEPConnection(cert_file=cert_file, key_file=key_file)
            # FIXME: catchall exception
            except Exception:
                # log
                logger.info(_("Unable to connect to Subscription Management Service"))
                return
        else:
            logger.info(_("Unable to read consumer identity"))

        if config.in_container():
            logger.info(_("Subscription Manager is operating in container mode."))

        if not cache_only:
            cert_action_invoker = EntCertActionInvoker()
            cert_action_invoker.update()

        repo_action_invoker = RepoActionInvoker(cache_only=cache_only)
        repo_action_invoker.update()
Esempio n. 8
0
def validate_registration():
    """
    Validate consumer registration by making a REST call
    to the server.  Updates the global 'registered' variable.
    """
    global registered
    registered = False

    if ConsumerIdentity.existsAndValid():
        consumer = ConsumerIdentity.read()
        consumer_id = consumer.getConsumerId()
    else:
        return

    try:
        uep = UEP()
        consumer = uep.getConsumer(consumer_id)
        registered = (consumer is not None)
    except GoneException:
        registered = False
    except RemoteServerException as e:
        if e.code not in (http.NOT_FOUND, http.GONE):
            log.warn(str(e))
            raise
    except Exception as e:
        log.exception(str(e))
        raise
    def set_connection_info(self,
                host=None,
                ssl_port=None,
                handler=None,
                cert_file=None,
                key_file=None,
                proxy_hostname_arg=None,
                proxy_port_arg=None,
                proxy_user_arg=None,
                proxy_password_arg=None,
                no_proxy_arg=None,
                restlib_class=connection.Restlib):
        self.cert_file = ConsumerIdentity.certpath()
        self.key_file = ConsumerIdentity.keypath()

        # only use what was passed in, let the lowest level deal with
        # no values and look elsewhere for them.
        self.server_hostname = host
        self.server_port = ssl_port
        self.server_prefix = handler
        self.proxy_hostname = proxy_hostname_arg
        self.proxy_port = proxy_port_arg
        self.proxy_user = proxy_user_arg
        self.proxy_password = proxy_password_arg
        self.no_proxy = no_proxy_arg
        self.restlib_class = restlib_class
        self.clean()
Esempio n. 10
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        # Delete backup dir if it exists:
        shutil.rmtree(consumer_dir_backup, ignore_errors=True)

        # Copy current consumer dir:
        log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup)
        shutil.copytree(consumer_dir, consumer_dir_backup)

# FIXME FIXME
    # Delete current consumer certs:
    for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]:
        if (os.path.exists(path)):
            log.debug("Removing identity cert: %s" % path)
            os.remove(path)

    require(IDENTITY).reload()

    # Delete all entitlement certs rather than the directory itself:
    ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir')
    if os.path.exists(ent_cert_dir):

        for f in glob.glob("%s/*.pem" % ent_cert_dir):
            certpath = os.path.join(ent_cert_dir, f)
            log.debug("Removing entitlement cert: %s" % f)
            os.remove(certpath)
    else:
        log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir)

    # Subclasses of cache.CacheManager have a @classmethod delete_cache
    # for deleting persistent caches
    cache.ProfileManager.delete_cache()
    cache.InstalledProductsManager.delete_cache()
    if SyncedStore is not None:
        SyncedStore(None).update_cache({})
    # FIXME: implement as dbus client to facts service DeleteCache() once implemented
    # Facts.delete_cache()
    # WrittenOverridesCache is also a subclass of cache.CacheManager, but
    # it is deleted in RepoActionInvoker.delete_repo_file() below.
    # StatusCache subclasses have a a per instance cache varable
    # and delete_cache is an instance method, so we need to call
    # the delete_cache on the instances created in injectioninit.
    require(ENTITLEMENT_STATUS_CACHE).delete_cache()
    require(SYSTEMPURPOSE_COMPLIANCE_STATUS_CACHE).delete_cache()
    require(PROD_STATUS_CACHE).delete_cache()
    require(POOL_STATUS_CACHE).delete_cache()
    require(OVERRIDE_STATUS_CACHE).delete_cache()
    require(RELEASE_STATUS_CACHE).delete_cache()

    RepoActionInvoker.delete_repo_file()
    log.debug("Cleaned local data")
Esempio n. 11
0
def get_manager():
    if 'subscription_manager.action_client' in sys.modules:
        mgr = action_client.ActionClient()
    else:
        # for compatability with subscription-manager > =1.13
        uep = connection.UEPConnection(cert_file=ConsumerIdentity.certpath(),
                                        key_file=ConsumerIdentity.keypath())
        mgr = certmgr.CertManager(uep=uep)
    return mgr
Esempio n. 12
0
def get_manager():
    if 'subscription_manager.action_client' in sys.modules:
        mgr = action_client.ActionClient()
    else:
        # for compatability with subscription-manager > =1.13
        uep = connection.UEPConnection(cert_file=ConsumerIdentity.certpath(),
                                        key_file=ConsumerIdentity.keypath())
        mgr = certmgr.CertManager(uep=uep)
    return mgr
    def get_candlepin_consumer_connection(self):
        self.cp_provider = inj.require(inj.CP_PROVIDER)

        connection_info = self._get_connection_info()

        connection_info["cert_file"] = ConsumerIdentity.certpath()
        connection_info["key_file"] = ConsumerIdentity.keypath()

        self.cp_provider.set_connection_info(**connection_info)

        return self.cp_provider.get_consumer_auth_cp()
Esempio n. 14
0
    def get_candlepin_consumer_connection(self):
        self.cp_provider = inj.require(inj.CP_PROVIDER)

        connection_info = self._get_connection_info()

        connection_info['cert_file'] = ConsumerIdentity.certpath()
        connection_info['key_file'] = ConsumerIdentity.keypath()

        self.cp_provider.set_connection_info(**connection_info)

        return self.cp_provider.get_consumer_auth_cp()
Esempio n. 15
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()
Esempio n. 16
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()
Esempio n. 17
0
def setup_plugin():
    """
    Setup the plugin based on registration status using the RHSM configuration.
    """
    if not ConsumerIdentity.existsAndValid():
        # not registered
        return
    cfg = plugin.cfg()
    rhsm_conf = Config(RHSM_CONFIG_PATH)
    certificate = ConsumerIdentity.read()
    cfg.messaging.url = 'ssl://%s:5671' % rhsm_conf['server']['hostname']
    cfg.messaging.uuid = 'pulp.agent.%s' % certificate.getConsumerId()
    bundle(certificate)
Esempio n. 18
0
 def _get_consumer_id(self):
     try:
         cid = ConsumerIdentity.read()
         return cid.getConsumerId()
     except Exception, e:
         log.error(e)
         raise Disconnected()
Esempio n. 19
0
def send_enabled_report(path=REPOSITORY_PATH):
    """
    Send the enabled repository report.
    :param path: The path to a repository file.
    :type path: str
    """
    if not ConsumerIdentity.existsAndValid():
        # not registered
        return
    try:
        uep = UEP()
        certificate = ConsumerIdentity.read()
        report = EnabledReport(path)
        uep.report_enabled(certificate.getConsumerId(), report.content)
    except Exception, e:
        log.error('send enabled report failed: %s', str(e))
Esempio n. 20
0
def update_settings():
    """
    Setup the plugin based on the RHSM configuration.
    """
    rhsm_conf = Config(RHSM_CONFIG_PATH)
    certificate = ConsumerIdentity.read()
    if 'ca_cert_dir' in rhsm_conf['rhsm']:
        ca_cert_dir = rhsm_conf['rhsm']['ca_cert_dir']
    else:
        #handle old subscription-manager configurations
        ca_cert_dir = rhsm_conf['server']['ca_cert_dir']

    # the 'katello-default-ca.pem' is the ca used for generating the CA certs.
    # the 'candlepin-local.pem' is there for compatibility reasons (the old path where the
    # legacy installer was putting this file. If none of them is present, there is still
    # a chance the rhsm_conf['rhsm']['repo_ca_cert'] is serving as the CA for issuing
    # the client certs
    ca_candidates = [os.path.join(ca_cert_dir, 'katello-default-ca.pem'),
                     os.path.join(ca_cert_dir, 'candlepin-local.pem'),
                     rhsm_conf['rhsm']['repo_ca_cert'] % {'ca_cert_dir': ca_cert_dir}]
    existing_ca_certs = [cert for cert in ca_candidates if os.path.exists(cert)]
    if not existing_ca_certs:
       log.warn('None of the ca cert files %s found for the qpid connection' % ca_candidates)

       raise
    else:
       log.info('Using %s as the ca cert for qpid connection' % existing_ca_certs[0])

    plugin.cfg.messaging.cacert = existing_ca_certs[0]
    plugin.cfg.messaging.url = 'proton+amqps://%s:5647' % rhsm_conf['server']['hostname']
    plugin.cfg.messaging.uuid = 'pulp.agent.%s' % certificate.getConsumerId()
    bundle(certificate)
Esempio n. 21
0
 def _get_consumer_id(self):
     try:
         cid = ConsumerIdentity.read()
         return cid.getConsumerId()
     except Exception, e:
         log.error(e)
         raise Disconnected()
Esempio n. 22
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        # Delete backup dir if it exists:
        shutil.rmtree(consumer_dir_backup, ignore_errors=True)

        # Copy current consumer dir:
        log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup)
        shutil.copytree(consumer_dir, consumer_dir_backup)


# FIXME FIXME
# Delete current consumer certs:
    for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]:
        if (os.path.exists(path)):
            log.debug("Removing identity cert: %s" % path)
            os.remove(path)

    require(IDENTITY).reload()

    # Delete all entitlement certs rather than the directory itself:
    ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir')
    if os.path.exists(ent_cert_dir):

        for f in glob.glob("%s/*.pem" % ent_cert_dir):
            certpath = os.path.join(ent_cert_dir, f)
            log.debug("Removing entitlement cert: %s" % f)
            os.remove(certpath)
    else:
        log.warn("Entitlement cert directory does not exist: %s" %
                 ent_cert_dir)

    cache.ProfileManager.delete_cache()
    cache.InstalledProductsManager.delete_cache()
    Facts.delete_cache()

    # Must also delete in-memory cache
    require(ENTITLEMENT_STATUS_CACHE).delete_cache()
    require(PROD_STATUS_CACHE).delete_cache()
    require(OVERRIDE_STATUS_CACHE).delete_cache()
    RepoActionInvoker.delete_repo_file()
    log.info("Cleaned local data")
Esempio n. 23
0
    def _do_update(self):
        uuid = ConsumerIdentity.read().getConsumerId()
        consumer = self.uep.getConsumer(uuid)

        if 'autoheal' in consumer and consumer['autoheal']:
            try:
                log.info("Checking if system requires healing.")

                today = datetime.now(GMT())
                tomorrow = today + timedelta(days=1)

                # Check if we're invalid today and heal if so. If we are
                # valid, see if 24h from now is greater than our "valid until"
                # date, and heal for tomorrow if so.

                cs = require(CERT_SORTER)
                cert_updater = CertLib(lock=self.lock, uep=self.uep)
                if not cs.is_valid():
                    log.warn("Found invalid entitlements for today: %s" %
                             today)
                    self.plugin_manager.run("pre_auto_attach",
                                            consumer_uuid=uuid)
                    ents = self.uep.bind(uuid, today)
                    self.plugin_manager.run("post_auto_attach",
                                            consumer_uuid=uuid,
                                            entitlement_data=ents)
                    cert_updater.update()
                else:
                    log.info("Entitlements are valid for today: %s" % today)

                    if cs.compliant_until is None:
                        # Edge case here, not even sure this can happen as we
                        # should have a compliant until date if we're valid
                        # today, but just in case:
                        log.warn(
                            "Got valid status from server but no valid until date."
                        )
                    elif tomorrow > cs.compliant_until:
                        log.warn(
                            "Entitlements will be invalid by tomorrow: %s" %
                            tomorrow)
                        self.plugin_manager.run("pre_auto_attach",
                                                consumer_uuid=uuid)
                        ents = self.uep.bind(uuid, tomorrow)
                        self.plugin_manager.run("post_auto_attach",
                                                consumer_uuid=uuid,
                                                entitlement_data=ents)
                        cert_updater.update()
                    else:
                        log.info("Entitlements are valid for tomorrow: %s" %
                                 tomorrow)

            except Exception, e:
                log.error("Error attempting to auto-heal:")
                log.exception(e)
                return 0
            else:
                log.info("Auto-heal check complete.")
                return 1
Esempio n. 24
0
 def send():
     try:
         uep = UEP()
         certificate = ConsumerIdentity.read()
         report = EnabledReport(path)
         uep.report_enabled(certificate.getConsumerId(), report.content)
     except Exception, e:
         log.error('send enabled report failed: %s', str(e))
Esempio n. 25
0
    def _do_update(self):
        if not ConsumerIdentity.existsAndValid():
            # we could in theory try to update the id in the
            # case of it being bogus/corrupted, ala #844069,
            # but that seems unneeded
            return 0

        from subscription_manager import managerlib

        idcert = ConsumerIdentity.read()
        uuid = idcert.getConsumerId()
        consumer = self.uep.getConsumer(uuid)
        # only write the cert if the serial has changed
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')
            managerlib.persist_consumer_cert(consumer)
        return 1
Esempio n. 26
0
 def consumer_id(self):
     """
     Get the current consumer ID
     :return: The unique consumer ID of the currently running agent
     :rtype:  str
     """
     certificate = ConsumerIdentity.read()
     return certificate.getConsumerId()
Esempio n. 27
0
 def consumer_id(self):
     """
     Get the current consumer ID
     :return: The unique consumer ID of the currently running agent
     :rtype:  str
     """
     certificate = ConsumerIdentity.read()
     return certificate.getConsumerId()
Esempio n. 28
0
    def _do_update(self):
        if not ConsumerIdentity.existsAndValid():
            # we could in theory try to update the id in the
            # case of it being bogus/corrupted, ala #844069,
            # but that seems unneeded
            return 0

        from subscription_manager import managerlib

        idcert = ConsumerIdentity.read()
        uuid = idcert.getConsumerId()
        consumer = self.uep.getConsumer(uuid)
        # only write the cert if the serial has changed
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')
            managerlib.persist_consumer_cert(consumer)
        return 1
Esempio n. 29
0
def clean_all_data(backup=True):
    consumer_dir = cfg.get('rhsm', 'consumerCertDir')
    if backup:
        if consumer_dir[-1] == "/":
            consumer_dir_backup = consumer_dir[0:-1] + ".old"
        else:
            consumer_dir_backup = consumer_dir + ".old"

        # Delete backup dir if it exists:
        shutil.rmtree(consumer_dir_backup, ignore_errors=True)

        # Copy current consumer dir:
        log.info("Backing up %s to %s." % (consumer_dir, consumer_dir_backup))
        shutil.copytree(consumer_dir, consumer_dir_backup)

# FIXME FIXME
    # Delete current consumer certs:
    for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]:
        if (os.path.exists(path)):
            log.debug("Removing identity cert: %s" % path)
            os.remove(path)

    require(IDENTITY).reload()

    # Delete all entitlement certs rather than the directory itself:
    ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir')
    if os.path.exists(ent_cert_dir):

        for f in glob.glob("%s/*.pem" % ent_cert_dir):
            certpath = os.path.join(ent_cert_dir, f)
            log.debug("Removing entitlement cert: %s" % f)
            os.remove(certpath)
    else:
        log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir)

    cache.ProfileManager.delete_cache()
    cache.InstalledProductsManager.delete_cache()
    Facts.delete_cache()

    # Must also delete in-memory cache
    require(ENTITLEMENT_STATUS_CACHE).delete_cache()
    require(PROD_STATUS_CACHE).delete_cache()
    require(OVERRIDE_STATUS_CACHE).delete_cache()
    RepoActionInvoker.delete_repo_file()
    log.info("Cleaned local data")
Esempio n. 30
0
def warnOrGiveUsageMessage(conduit):

    # XXX: Importing inline as you must be root to read the config file
    """ either output a warning, or a usage message """
    msg = ""
    # TODO: refactor so there are not two checks for this
    if os.getuid() != 0:
        return
    if ClassicCheck().is_registered_with_classic():
        return
    try:
        identity = inj.require(inj.IDENTITY)
        ent_dir = inj.require(inj.ENT_DIR)
        # Don't warn people to register if we see entitelements, but no identity:
        if not identity.is_valid() and len(ent_dir.list_valid()) == 0:
            msg = not_registered_warning
        elif len(ent_dir.list_valid()) == 0:
            # XXX: Importing inline as you must be root to read the config file
            from subscription_manager.identity import ConsumerIdentity

            cert_file = ConsumerIdentity.certpath()
            key_file = ConsumerIdentity.keypath()

            # In containers we have no identity, but we may have entitlements inherited
            # from the host, which need to generate a redhat.repo.
            if identity.is_valid():
                try:
                    uep = connection.UEPConnection(cert_file=cert_file,
                                                   key_file=key_file)
                # FIXME: catchall exception
                except Exception:
                    pass
                else:
                    owner = uep.getOwner(identity.uuid)
                    if owner['contentAccessMode'] != "org_environment":
                        return

            msg = no_subs_warning
        if config.in_container() and len(ent_dir.list_valid()) == 0:
            msg = no_subs_container_warning

    finally:
        if msg:
            conduit.info(2, msg)
Esempio n. 31
0
 def __init__(self):
     self.correlation_id = None
     self.username = None
     self.password = None
     self.token = None
     self.token_username = None
     self.cdn_hostname = None
     self.cdn_port = None
     self.cert_file = ConsumerIdentity.certpath()
     self.key_file = ConsumerIdentity.keypath()
     self.server_hostname = None
     self.server_port = None
     self.server_prefix = None
     self.proxy_hostname = None
     self.proxy_port = None
     self.proxy_user = None
     self.proxy_password = None
     self.no_proxy = None
     self.restlib_class = None
Esempio n. 32
0
 def __init__(self, oscs, rdb, logger, opts):
     self.oscs = oscs
     self.rdb = rdb
     self.logger = logger
     self.opts = opts
     self.rhsmconfig = rhsm.config.initConfig()
     try:
         self.consumer_key = _read(ConsumerIdentity.keypath())
         self.consumer_cert = _read(ConsumerIdentity.certpath())
     except IOError as ioerr:
         if 2 == ioerr.errno:
             raise SubscriptionManagerNotRegisteredError()
     self.consumer_identity = ConsumerIdentity(self.consumer_key, self.consumer_cert)
     self.consumer_uuid = self.consumer_identity.getConsumerId()
     self.cp_provider = inj.require(inj.CP_PROVIDER)
     self.cp = self.cp_provider.get_consumer_auth_cp()
     # self.ATTR_DEFAULTS = dict([(attr, RepoConf.optionobj(attr).default) for attr in IMPORTANT_ATTRS])
     self._set_attr_defaults()
     self.problem = False
Esempio n. 33
0
def update_settings():
    """
    Setup the plugin based on the RHSM configuration.
    """
    rhsm_conf = Config(RHSM_CONFIG_PATH)
    certificate = ConsumerIdentity.read()
    plugin.cfg.messaging.cacert = rhsm_conf['rhsm']['repo_ca_cert'] % rhsm_conf['rhsm']
    plugin.cfg.messaging.url = 'proton+amqps://%s:5647' % rhsm_conf['server']['hostname']
    plugin.cfg.messaging.uuid = 'pulp.agent.%s' % certificate.getConsumerId()
    bundle(certificate)
Esempio n. 34
0
    def _do_update(self):
        uuid = ConsumerIdentity.read().getConsumerId()
        consumer = self.uep.getConsumer(uuid)

        if 'autoheal' in consumer and consumer['autoheal']:
            try:
                log.info("Checking if system requires healing.")

                today = datetime.now(GMT())
                tomorrow = today + timedelta(days=1)

                # Check if we're invalid today and heal if so. If we are
                # valid, see if 24h from now is greater than our "valid until"
                # date, and heal for tomorrow if so.

                cs = require(CERT_SORTER)
                cert_updater = CertLib(lock=self.lock, uep=self.uep)
                if not cs.is_valid():
                    log.warn("Found invalid entitlements for today: %s" %
                            today)
                    self.plugin_manager.run("pre_auto_attach", consumer_uuid=uuid)
                    ents = self.uep.bind(uuid, today)
                    self.plugin_manager.run("post_auto_attach", consumer_uuid=uuid,
                                            entitlement_data=ents)
                    cert_updater.update()
                else:
                    log.info("Entitlements are valid for today: %s" %
                            today)

                    if cs.compliant_until is None:
                        # Edge case here, not even sure this can happen as we
                        # should have a compliant until date if we're valid
                        # today, but just in case:
                        log.warn("Got valid status from server but no valid until date.")
                    elif tomorrow > cs.compliant_until:
                        log.warn("Entitlements will be invalid by tomorrow: %s" %
                                tomorrow)
                        self.plugin_manager.run("pre_auto_attach", consumer_uuid=uuid)
                        ents = self.uep.bind(uuid, tomorrow)
                        self.plugin_manager.run("post_auto_attach", consumer_uuid=uuid,
                                                entitlement_data=ents)
                        cert_updater.update()
                    else:
                        log.info("Entitlements are valid for tomorrow: %s" %
                                tomorrow)

            except Exception, e:
                log.error("Error attempting to auto-heal:")
                log.exception(e)
                return 0
            else:
                log.info("Auto-heal check complete.")
                return 1
Esempio n. 35
0
def update_settings():
    """
    Setup the plugin based on the RHSM configuration.
    """
    rhsm_conf = Config(RHSM_CONFIG_PATH)
    certificate = ConsumerIdentity.read()
    plugin.cfg.messaging.cacert = rhsm_conf['rhsm'][
        'repo_ca_cert'] % rhsm_conf['rhsm']
    plugin.cfg.messaging.url = 'proton+amqps://%s:5647' % rhsm_conf['server'][
        'hostname']
    plugin.cfg.messaging.uuid = 'pulp.agent.%s' % certificate.getConsumerId()
    bundle(certificate)
Esempio n. 36
0
def registration_changed(path):
    """
    Notification that a change in registration has been detected.
    On registration: setup the plugin; attach to the message broker.
    On un-registration: detach from the message broker.
    :param path: The path to the file that changed.
    :type path: str
    """
    log.info('changed: %s', path)
    if ConsumerIdentity.existsAndValid():
        setup_plugin()
        plugin.attach()
    else:
        plugin.detach()
Esempio n. 37
0
def init_plugin():
    """
    Initialize the plugin.
    Called (once) immediately after the plugin is loaded.
     - setup plugin configuration.
     - send an initial repository enabled report.
     - setup path monitoring.
    """
    setup_plugin()
    send_enabled_report()
    path = ConsumerIdentity.certpath()
    path_monitor.add(path, registration_changed)
    path_monitor.add(REPOSITORY_PATH, send_enabled_report)
    path_monitor.start()
Esempio n. 38
0
def send_enabled_report(path=REPOSITORY_PATH):
    """
    Send the enabled repository report.
    :param path: The path to a repository file.
    :type path: str
    """
    if not registered:
        return
    try:
        uep = UEP()
        certificate = ConsumerIdentity.read()
        report = EnabledReport(path)
        uep.report_enabled(certificate.getConsumerId(), report.content)
    except Exception, e:
        log.error('send enabled report failed: %s', str(e))
Esempio n. 39
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)

    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, e:
        log.critical(_("Your identity certificate has expired"))
        raise e
Esempio n. 40
0
def init_plugin():
    """
    Initialize the plugin.
    Called (once) immediately after the plugin is loaded.
     - setup path monitoring.
     - validate registration.  If registered:
       - setup plugin configuration.
    """
    path = ConsumerIdentity.certpath()
    path_monitor.add(path, certificate_changed)
    path_monitor.add(REPOSITORY_PATH, send_enabled_report)
    path_monitor.start()
    while True:
        try:
            validate_registration()
            if registered:
                update_settings()
            # DONE
            break
        except Exception, e:
            log.warn(str(e))
            sleep(60)
Esempio n. 41
0
def main(options, 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')

    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, e:
        log.critical(_("Your identity certificate has expired"))
        raise e
def main(options, 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')

    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, e:
        log.critical(_("Your identity certificate has expired"))
        raise e
Esempio n. 43
0
def plugin_loaded():
    """
    Initialize the plugin.
    Called (once) immediately after the plugin is loaded.
     - setup path monitoring.
     - validate registration.  If registered:
       - setup plugin configuration.
    """
    global path_monitor
    path = ConsumerIdentity.certpath()
    path_monitor = PathMonitor()
    path_monitor.add(path, certificate_changed)
    path_monitor.start()
    while True:
        try:
            validate_registration()
            if registered:
                update_settings()
            # DONE
            break
        except Exception as e:
            log.warn(str(e))
            sleep(60)
Esempio n. 44
0
def init_plugin():
    """
    Initialize the plugin.
    Called (once) immediately after the plugin is loaded.
     - setup path monitoring.
     - validate registration.  If registered:
       - setup plugin configuration.
       - send an initial repository enabled report.
    """
    path = ConsumerIdentity.certpath()
    path_monitor.add(path, certificate_changed)
    path_monitor.add(REPOSITORY_PATH, send_enabled_report)
    path_monitor.start()
    while True:
        try:
            validate_registration()
            if registered:
                update_settings()
                send_enabled_report()
            # DONE
            break
        except Exception, e:
            log.warn(str(e))
            sleep(60)
Esempio n. 45
0
def main(options, log):
    # Set default mainloop
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    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)

    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, e:
        log.critical(_("Your identity certificate has expired"))
        raise e
            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, e:
        log.critical(_("Your identity certificate has expired"))
        raise e
    except connection.GoneException, 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
Esempio n. 47
0
 def __init__(self):
     key = ConsumerIdentity.keypath()
     cert = ConsumerIdentity.certpath()
     UEPConnection.__init__(self, key_file=key, cert_file=cert)
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)

    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
class ReconciliationEngine(object):
    def __init__(self, oscs, rdb, logger, opts):
        self.oscs = oscs
        self.rdb = rdb
        self.logger = logger
        self.opts = opts
        self.rhsmconfig = rhsm.config.initConfig()
        try:
            self.consumer_key = _read(ConsumerIdentity.keypath())
            self.consumer_cert = _read(ConsumerIdentity.certpath())
        except IOError as ioerr:
            if 2 == ioerr.errno:
                raise SubscriptionManagerNotRegisteredError()
        self.consumer_identity = ConsumerIdentity(self.consumer_key, self.consumer_cert)
        self.consumer_uuid = self.consumer_identity.getConsumerId()
        self.cp_provider = inj.require(inj.CP_PROVIDER)
        self.cp = self.cp_provider.get_consumer_auth_cp()
        # self.ATTR_DEFAULTS = dict([(attr, RepoConf.optionobj(attr).default) for attr in IMPORTANT_ATTRS])
        self._set_attr_defaults()
        self.problem = False

    def _set_attr_defaults(self):
        self.ATTR_DEFAULTS = dict()
        for attr in IMPORTANT_ATTRS:
            try:
                self.ATTR_DEFAULTS[attr] = RepoConf.optionobj(attr).default
            except KeyError:
                IMPORTANT_ATTRS.remove(attr)

    def get_overrides_and_repos(self):
        overrides = self.cp.getContentOverrides(self.consumer_uuid)
        override_repos = list(set([ovrd['contentLabel'] for ovrd in overrides]))
        ovrdict = defaultdict(lambda: defaultdict(lambda: None))
        for ovrd in overrides:
            ovrdict[ovrd['contentLabel']][ovrd['name']] = ovrd['value']
        return ovrdict, override_repos

    def set_override(self, repo, attr):
        if not self.problem:
            self.logger.error(SET_OVERRIDE_MSG)
            if self.opts.fix:
                self.logger.error(SET_OVERRIDE_FIX_MSG)
            else:
                self.logger.error(SET_OVERRIDE_REPORT_MSG)
        self.problem = True
        value = repo.getAttribute(attr)
        option = RepoConf.optionobj(attr)
        if self.opts.fix:
            if isinstance(option, config.ListOption):
                v_str = ' '.join(value)
            else:
                v_str = option.tostring(value)
            if self.current_repoid != repo.id:
                self.current_repoid = repo.id
                self.logger.error("Updating repository %s" % repo.id)
            self.logger.error("    %s: %s" % (attr, v_str))
            self.oscs.set_save_repo_attr(repo.id, attr, value)
        else:
            self.logger.error(
                "# %s" %
                self.oscs.get_update_override_cmd(
                    repo, attr, repo.getAttribute(attr), for_output=True))

    def fix_overrides_for_repo(self, repoid, overrides):
        self.current_repoid=""
        try:
            repo = self.oscs.repo_for_repoid(repoid)
        except KeyError:
            if self.opts.fix:
                self.logger.warning('Cannot modify content overrides for '
                                    'non-existent repo %s' % repoid)
            return # don't operate on nonexistant repos
        for attr in IMPORTANT_ATTRS:
            if repo.getAttribute(attr) != self.ATTR_DEFAULTS[attr]:
                if not overrides[repoid] or not overrides[repoid][attr]:
                    self.set_override(repo, attr)

    def reconcile_overrides(self):
        (overrides, override_repos) = self.get_overrides_and_repos()
        rhsm_repoids = self.rdb.find_repoids(subscription = 'rhsm')
        for repoid in rhsm_repoids:
            self.fix_overrides_for_repo(repoid, overrides)
        return self.problem
Esempio n. 50
0
def upload_package_profile():
    uep = connection.UEPConnection(cert_file=ConsumerIdentity.certpath(),
                                   key_file=ConsumerIdentity.keypath())
    get_manager().profilelib._do_update()
Esempio n. 51
0
def lookup_consumer_id():
    try:
        certificate = ConsumerIdentity.read()
        return certificate.getConsumerId()
    except IOError:
        return None
Esempio n. 52
0
def get_uep():
    key = ConsumerIdentity.keypath()
    cert = ConsumerIdentity.certpath()
    uep = UEPConnection(key_file=key, cert_file=cert)
    return uep