def doCommand(self, base, basecmd, extcmds):
        opts = base.plugins.cmdline[0]
        pkgs = base.rpmdb
        product_dir = ProductDirectory()
        product = {}
        for p in product_dir.list():
            for p in p.products:
                product[p.id] = p.name

        product_db = ProductDatabase()
        product_db.read()
        # convert IDs to names in the mapping
        product_repo_mapping = dict((product[k], v) for k, v in product_db.content.iteritems())

        for product in extcmds:
            for ipkg in sorted(pkgs):
                if "from_repo" in ipkg.yumdb_info and ipkg.yumdb_info.from_repo in product_repo_mapping.get(product):
                    # add the package to the erasure transaction
                    base.remove(ipkg)

        if len(base.tsInfo) == 0:
            return 0, ["No packages found for selected products"]

        if base.doTransaction() == 0:
            return 0, ["Removed packages for selected products"]
        else:
            return 0, ["Error occured while removing packages. Please see yum.log for more details."]
    def __init__(self,
                 table_widget,
                 yes_id=gtk.STOCK_APPLY,
                 no_id=gtk.STOCK_REMOVE):
        """
        Create a new products table, populating the gtk.TreeView.

        yes_id and no_id are GTK constants that specify the icon to
        use for representing if a product is installed.
        """

        self.table_widget = table_widget
        self.product_store = gtk.ListStore(str, gtk.gdk.Pixbuf)
        table_widget.set_model(self.product_store)

        self.yes_icon = self._render_icon(yes_id)
        self.no_icon = self._render_icon(no_id)
        self.product_dir = ProductDirectory()

        name_column = gtk.TreeViewColumn(_("Product"),
                                         gtk.CellRendererText(),
                                         markup=0)
        name_column.set_expand(True)
        installed_column = gtk.TreeViewColumn(_("Installed"),
                                              gtk.CellRendererPixbuf(),
                                              pixbuf=1)

        table_widget.append_column(name_column)
        table_widget.append_column(installed_column)
Exemple #3
0
 def test_get_installed_products(self, MockExists):
     MockExists.return_value = True
     pd = ProductDirectory()
     top_product = StubProduct("top")
     provided_products = [StubProduct("provided")]
     pd.list = lambda: [StubProductCertificate(top_product, provided_products)]
     installed_products = pd.get_installed_products()
     self.assertTrue("top" in installed_products)
Exemple #4
0
    def __init__(self, product_dir=None):

        if not product_dir:
            product_dir = ProductDirectory()

        self.installed = {}
        for prod_cert in product_dir.list():
            prod = prod_cert.products[0]
            self.installed[prod.id] = prod.name
Exemple #5
0
    def __init__(self, product_dir=None):

        if not product_dir:
            product_dir = ProductDirectory()

        self.installed = {}
        for prod_cert in product_dir.list():
            prod = prod_cert.getProduct()
            self.installed[prod.getHash()] = prod.getName()
Exemple #6
0
 def test_default_products_matching_ids(self, MockExists):
     MockExists.return_value = True
     pd = ProductDirectory()
     top_product = StubProduct("top")
     default_product = StubProduct("top")
     pd.installed_prod_dir.list = lambda: [StubProductCertificate(top_product, [])]
     pd.default_prod_dir.list = lambda: [StubProductCertificate(default_product, [])]
     results = pd.list()
     self.assertEquals(1, len(results))
     resulting_ids = [cert.products[0].id for cert in results]
     self.assertTrue("top" in resulting_ids)
    def __init__(self, table_widget, yes_id=gtk.STOCK_APPLY,
                 no_id=gtk.STOCK_REMOVE):
        """
        Create a new products table, populating the gtk.TreeView.

        yes_id and no_id are GTK constants that specify the icon to
        use for representing if a product is installed.
        """

        self.table_widget = table_widget
        self.product_store = gtk.ListStore(str, gtk.gdk.Pixbuf)
        table_widget.set_model(self.product_store)

        self.yes_icon = self._render_icon(yes_id)
        self.no_icon = self._render_icon(no_id)
        self.product_dir = ProductDirectory()

        name_column = gtk.TreeViewColumn(_("Product"),
                                         gtk.CellRendererText(),
                                         markup=0)
        name_column.set_expand(True)
        installed_column = gtk.TreeViewColumn(_("Installed"),
                                              gtk.CellRendererPixbuf(),
                                              pixbuf=1)

        table_widget.append_column(name_column)
        table_widget.append_column(installed_column)
Exemple #8
0
    def __init__(self,
                 lock=ActionLock(),
                 uep=None,
                 facts_dict=None,
                 product_dir=None):
        self.facts_dict = facts_dict
        DataLib.__init__(self, lock, uep)

        self._product_dir = product_dir or ProductDirectory()
class ProductsTable(object):
    def __init__(self,
                 table_widget,
                 yes_id=gtk.STOCK_APPLY,
                 no_id=gtk.STOCK_REMOVE):
        """
        Create a new products table, populating the gtk.TreeView.

        yes_id and no_id are GTK constants that specify the icon to
        use for representing if a product is installed.
        """

        self.table_widget = table_widget
        self.product_store = gtk.ListStore(str, gtk.gdk.Pixbuf)
        table_widget.set_model(self.product_store)

        self.yes_icon = self._render_icon(yes_id)
        self.no_icon = self._render_icon(no_id)
        self.product_dir = ProductDirectory()

        name_column = gtk.TreeViewColumn(_("Product"),
                                         gtk.CellRendererText(),
                                         markup=0)
        name_column.set_expand(True)
        installed_column = gtk.TreeViewColumn(_("Installed"),
                                              gtk.CellRendererPixbuf(),
                                              pixbuf=1)

        table_widget.append_column(name_column)
        table_widget.append_column(installed_column)

    def clear(self):
        """
        Remove all products from the table.
        """
        self.product_store.clear()

    def add_product(self, product_name, product_id):
        """
        Add a product with the given name and id to the table.
        """
        self.product_store.append([product_name, self._get_icon(product_id)])

    def set_accessibility_name(self, accessibility_name):
        self.table_widget.get_accessible().set_name(accessibility_name)

    def _render_icon(self, icon_id):
        return self.table_widget.render_icon(icon_id, gtk.ICON_SIZE_MENU)

    def _get_icon(self, product_id):
        if self.product_dir.findByProduct(product_id):
            return self.yes_icon
        else:
            return self.no_icon
class ProductsTable(object):

    def __init__(self, table_widget, yes_id=gtk.STOCK_APPLY,
                 no_id=gtk.STOCK_REMOVE):
        """
        Create a new products table, populating the gtk.TreeView.

        yes_id and no_id are GTK constants that specify the icon to
        use for representing if a product is installed.
        """

        self.table_widget = table_widget
        self.product_store = gtk.ListStore(str, gtk.gdk.Pixbuf)
        table_widget.set_model(self.product_store)

        self.yes_icon = self._render_icon(yes_id)
        self.no_icon = self._render_icon(no_id)
        self.product_dir = ProductDirectory()

        name_column = gtk.TreeViewColumn(_("Product"),
                                         gtk.CellRendererText(),
                                         markup=0)
        name_column.set_expand(True)
        installed_column = gtk.TreeViewColumn(_("Installed"),
                                              gtk.CellRendererPixbuf(),
                                              pixbuf=1)

        table_widget.append_column(name_column)
        table_widget.append_column(installed_column)

    def clear(self):
        """
        Remove all products from the table.
        """
        self.product_store.clear()

    def add_product(self, product_name, product_id):
        """
        Add a product with the given name and id to the table.
        """
        self.product_store.append([product_name, self._get_icon(product_id)])

    def set_accessibility_name(self, accessibility_name):
        self.table_widget.get_accessible().set_name(accessibility_name)

    def _render_icon(self, icon_id):
        return self.table_widget.render_icon(icon_id, gtk.ICON_SIZE_MENU)

    def _get_icon(self, product_id):
        if self.product_dir.findByProduct(product_id):
            return self.yes_icon
        else:
            return self.no_icon
Exemple #11
0
    def __init__(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(),
                        key_file=ConsumerIdentity.keypath())

        self.create_content_connection()
        # we don't know the user/pass yet, so no point in
        # creating an admin uep till we need it
        self.admin_uep = None

        self.product_dir = ProductDirectory()
        self.entitlement_dir = EntitlementDirectory()
        self.certlib = CertLib(uep=self.uep)

        self.product_monitor = file_monitor.Monitor(self.product_dir.path)
        self.entitlement_monitor = file_monitor.Monitor(
            self.entitlement_dir.path)
        self.identity_monitor = file_monitor.Monitor(ConsumerIdentity.PATH)

        # connect handlers to refresh the cached data when we notice a change.
        # do this before any other handlers might connect
        self.product_monitor.connect(
            "changed", lambda monitor: self.product_dir.refresh())
        self.entitlement_monitor.connect(
            "changed", lambda monitor: self.entitlement_dir.refresh())
Exemple #12
0
    def __init__(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(),
                        key_file=ConsumerIdentity.keypath())

        self.create_content_connection()
        # we don't know the user/pass yet, so no point in
        # creating an admin uep till we need it
        self.admin_uep = None

        self.product_dir = ProductDirectory()
        self.entitlement_dir = EntitlementDirectory()
        self.certlib = CertLib(uep=self.uep)

        self.product_monitor = file_monitor.Monitor(self.product_dir.path)
        self.entitlement_monitor = file_monitor.Monitor(
            self.entitlement_dir.path)
        self.identity_monitor = file_monitor.Monitor(ConsumerIdentity.PATH)
    def __init__(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(), key_file=ConsumerIdentity.keypath())

        self.create_content_connection()
        # we don't know the user/pass yet, so no point in
        # creating an admin uep till we need it
        self.admin_uep = None

        self.product_dir = ProductDirectory()
        self.entitlement_dir = EntitlementDirectory()
        self.certlib = CertLib(uep=self.uep)

        self.product_monitor = file_monitor.Monitor(self.product_dir.path)
        self.entitlement_monitor = file_monitor.Monitor(self.entitlement_dir.path)
        self.identity_monitor = file_monitor.Monitor(ConsumerIdentity.PATH)

        # connect handlers to refresh the cached data when we notice a change.
        # do this before any other handlers might connect
        self.product_monitor.connect("changed", lambda monitor: self.product_dir.refresh())
        self.entitlement_monitor.connect("changed", lambda monitor: self.entitlement_dir.refresh())
def find_first_invalid_date(ent_dir=None, product_dir=None, facts_dict=None):
    """
    Find the first date when the system is invalid at midnight
    GMT.

    WARNING: This method does *not* return the exact first datetime when
    we're invalid. Due to it's uses in the GUI it needs to
    return a datetime into the first day of being completely invalid, so
    the subscription assistant can search for that time and find expired
    products.

    If there are no products installed, return None, as there technically
    is no first invalid date.
    """
    if not ent_dir:
        ent_dir = EntitlementDirectory()
    if not product_dir:
        product_dir = ProductDirectory()
    if facts_dict is None:
        facts_dict = Facts().get_facts()

    current_date = datetime.now(GMT())

    if not product_dir.list():
        # If there are no products installed, return None, there is no
        # invalid date:
        log.debug("Unable to determine first invalid date, no products "
                  "installed.")
        return None

    # change _scan_entitlement_certs to take product lists,
    # run it for the future to figure this out
    # First check if we have anything installed but not entitled *today*:
    cs = cert_sorter.CertSorter(product_dir,
                                ent_dir,
                                facts_dict,
                                on_date=current_date)
    if not cs.is_valid():
        log.debug("Found unentitled products or partial stacks.")
        return current_date

    # Sort all the ent certs by end date. (ascending)
    all_ent_certs = ent_dir.list()

    def get_date(ent_cert):
        return ent_cert.validRange().end()

    all_ent_certs.sort(key=get_date)

    # Loop through all current and future entitlement certs, check validity
    # status on their end date, and return the first date where we're not
    # valid.
    for ent_cert in all_ent_certs:
        # Adding a timedelta of one day here so we can be sure we get a date
        # the subscription assitant (which does not use time) can use to search
        # for.
        end_date = ent_cert.validRange().end() + timedelta(days=1)
        if end_date < current_date:
            # This cert is expired, ignore it:
            continue
        log.debug("Checking cert: %s, end date: %s" %
                  (ent_cert.serialNumber(), end_date))

        # new cert_sort stuff, use _scan_for_entitled_products, since
        # we just need to know if stuff is expired
        cs = cert_sorter.CertSorter(product_dir,
                                    ent_dir,
                                    facts_dict,
                                    on_date=end_date)
        if not cs.is_valid():
            log.debug("Found non-valid status on %s" % end_date)
            return end_date
        else:
            log.debug("Valid status on %s" % end_date)

    # Should never hit this:
    raise Exception("Unable to determine first invalid date.")
    def __init__(self,
                 backend,
                 consumer,
                 facts,
                 tab_icon,
                 parent,
                 ent_dir=None,
                 prod_dir=None):

        widgets = [
            'product_text', 'product_id_text', 'validity_text',
            'subscription_text', 'subscription_status_label',
            'update_certificates_button', 'register_button'
        ]
        super(InstalledProductsTab, self).__init__('installed.glade', widgets)

        self.tab_icon = tab_icon

        self.product_dir = prod_dir or ProductDirectory()
        self.entitlement_dir = ent_dir or EntitlementDirectory()

        self.facts = facts
        self.cs = cert_sorter.CertSorter(prod_dir, ent_dir,
                                         self.facts.get_facts())

        # Product column
        text_renderer = gtk.CellRendererText()
        image_renderer = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn(_('Product'),
                                    image_renderer,
                                    pixbuf=self.store['image'])

        column.set_expand(True)
        column.pack_end(text_renderer, True)
        column.add_attribute(text_renderer, 'text', self.store['product'])
        column.add_attribute(text_renderer, 'cell-background',
                             self.store['background'])
        self.top_view.append_column(column)
        cols = []
        cols.append((column, 'text', 'product'))

        column = self.add_text_column(_('Version'), 'version')
        cols.append((column, 'text', 'version'))

        column = self.add_text_column(_('Arch'), 'arch')
        column.set_alignment(0.5)
        cols.append((column, 'text', 'arch'))

        column = self.add_text_column(_('Status'), 'status')
        cols.append((column, 'text', 'status'))

        column = self.add_date_column(_('Start Date'), 'start_date')
        cols.append((column, 'date', 'start_date'))

        column = self.add_date_column(_('End Date'), 'expiration_date')
        cols.append((column, 'date', 'expiration_date'))

        self.set_sorts(cols)

        self.glade.signal_autoconnect({
            "on_update_certificates_button_clicked":
            parent._update_certificates_button_clicked,
        })
        self.glade.signal_autoconnect({
            "on_register_button_clicked":
            parent._register_item_clicked,
        })

        self.update_products()

        # Monitor entitlements/products for additions/deletions
        def on_cert_change(filemonitor):
            self.update_products()
            self._set_validity_status()

        backend.monitor_certs(on_cert_change)
 def __init__(self):
     self.pdir = ProductDirectory()
     self.db = ProductDatabase()
     self.db.read()
     self.meta_data_errors = []
class ProductManager:

    REPO = 'from_repo'
    PRODUCTID = 'productid'

    def __init__(self):
        self.pdir = ProductDirectory()
        self.db = ProductDatabase()
        self.db.read()
        self.meta_data_errors = []

    def update(self, yb):
        if yb is None:
            yb = yum.YumBase()
        enabled = self.getEnabled(yb)
        active = self.getActive(yb)

        #only execute this on versions of yum that track
        #which repo a package came from
        if yum.__version_info__[2] >= 28:
            # check that we have any repo's enabled
            # and that we have some enabled repo's. Not just
            # that we have packages from repo's that are
            # not active. See #806457
            if enabled and active:
                self.updateRemoved(active)
        self.updateInstalled(enabled, active)

    def _isWorkstation(self, product):
        if product.getName() == "Red Hat Enterprise Linux Workstation" and \
                "rhel-5-client-workstation" in product.getProvidedTags() and \
                product.getVersion()[0] == '5':
            return True
        return False

    def _isDesktop(self, product):
        if product.getName() == "Red Hat Enterprise Linux Desktop" and \
                "rhel-5-client" in product.getProvidedTags() and \
                product.getVersion()[0] == '5':
            return True
        return False

    def updateInstalled(self, enabled, active):
        for cert, repo in enabled:
            #nothing from this repo is installed
            if repo not in active:
                continue

            p = cert.getProduct()
            prod_hash = p.getHash()

            # Are we installing Workstation cert?
            if self._isWorkstation(p):
                # is the Desktop product cert installed?
                for pc in self.pdir.list():
                    if self._isDesktop(pc.getProduct()):
                        # Desktop product cert is installed,
                        # delete the Desktop product cert
                        pc.delete()
                        self.db.delete(prod_hash)
                        self.db.write()

            # no point installing desktop only to delete it
            if self._isDesktop(p):
                for pc in self.pdir.list():
                    if self._isWorkstation(pc.getProduct()):
                        # we are installing Desktop, but we already have workstation
                        return

            if self.pdir.findByProduct(prod_hash):
                continue

            fn = '%s.pem' % prod_hash
            path = self.pdir.abspath(fn)
            cert.write(path)
            self.db.add(prod_hash, repo)
            self.db.write()

    # We should only delete productcerts if there are no
    # packages from that repo installed (not "active")
    # and we have the product cert installed.
    def updateRemoved(self, active):
        for cert in self.pdir.list():
            p = cert.getProduct()
            prod_hash = p.getHash()
            repo = self.db.findRepo(prod_hash)

            # if we had errors with the repo or productid metadata
            # we could be very confused here, so do not
            # delete anything. see bz #736424
            if repo in self.meta_data_errors:
                log.info("%s has meta-data errors.  Not deleting product cert %s." % (repo, prod_hash))
                continue

            # FIXME: not entirely sure why we do this
            #  to avoid a none on cert.delete surely
            # but is there another reason?
            if repo is None:
                continue
            if repo in active:
                continue

            log.info("product cert %s for %s is being deleted" % (prod_hash, p.getName()))
            cert.delete()

            self.db.delete(prod_hash)
            self.db.write()

    # find the list of repo's that provide packages that
    # are actually installed.
    def getActive(self, yb):
        active = set()

        packages = yb.pkgSack.returnPackages()
        for p in packages:
            repo = p.repoid

            # if a pkg is in multiple repo's, this will consider
            # all the repo's with the pkg "active".
            db_pkg = yb.rpmdb.searchNevra(name=p.name, arch=p.arch)

            # that pkg is not actually installed
            if not db_pkg:
                continue

            # yum on 5.7 list everything as "installed" instead
            # of the repo it came from
            if repo in (None, "installed"):
                continue
            active.add(repo)
        return active

    def getEnabled(self, yb):
        lst = []
        enabled = yb.repos.listEnabled()

        for repo in enabled:
            try:
                fn = repo.retrieveMD(self.PRODUCTID)
                cert = self.__getCert(fn)
                if cert is None:
                    continue
                lst.append((cert, repo.id))
            except Exception, e:
                log.warn("Error loading productid metadata for %s." % repo)
                log.exception(e)
                self.meta_data_errors.append(repo.id)
        return lst
Exemple #18
0
    def __init__(self,
                 backend=None,
                 consumer=None,
                 facts=None,
                 ent_dir=None,
                 prod_dir=None,
                 auto_launch_registration=False):
        super(MainWindow, self).__init__('mainwindow.glade', [
            'main_window', 'notebook', 'system_name_label',
            'next_update_label', 'next_update_title', 'register_menu_item',
            'unregister_menu_item', 'redeem_menu_item'
        ])

        self.backend = backend or Backend()
        self.consumer = consumer or Consumer()
        self.facts = facts or Facts()

        log.debug("Versions: %s " % get_version_dict(self.backend.uep))

        self.product_dir = prod_dir or ProductDirectory()
        self.entitlement_dir = ent_dir or EntitlementDirectory()

        self.system_facts_dialog = factsgui.SystemFactsDialog(
            self.backend, self.consumer, self.facts)

        self.registration_dialog = registergui.RegisterScreen(
            self.backend,
            self.consumer,
            self.facts,
            callbacks=[self.registration_changed])

        self.preferences_dialog = PreferencesDialog(self.backend,
                                                    self.consumer,
                                                    self._get_window())

        self.import_sub_dialog = ImportSubDialog()

        self.network_config_dialog = networkConfig.NetworkConfigDialog()
        self.network_config_dialog.xml.get_widget("closeButton").connect(
            "clicked", self._config_changed)

        self.redeem_dialog = redeem.RedeemDialog(self.backend, self.consumer)

        self.installed_tab_icon = gtk.Image()
        self.installed_tab_icon.set_from_stock(gtk.STOCK_YES,
                                               gtk.ICON_SIZE_MENU)

        self.installed_tab = InstalledProductsTab(self.backend,
                                                  self.consumer,
                                                  self.facts,
                                                  self.installed_tab_icon,
                                                  self,
                                                  ent_dir=self.entitlement_dir,
                                                  prod_dir=self.product_dir)
        self.my_subs_tab = MySubscriptionsTab(self.backend,
                                              self.consumer,
                                              self.facts,
                                              self.main_window,
                                              ent_dir=self.entitlement_dir,
                                              prod_dir=self.product_dir)

        self.all_subs_tab = AllSubscriptionsTab(self.backend, self.consumer,
                                                self.facts, self.main_window)

        hbox = gtk.HBox(spacing=6)
        hbox.pack_start(self.installed_tab_icon, False, False)
        hbox.pack_start(gtk.Label(self.installed_tab.get_label()), False,
                        False)
        self.notebook.append_page(self.installed_tab.get_content(), hbox)
        hbox.show_all()

        self.notebook.append_page(self.my_subs_tab.get_content(),
                                  gtk.Label(self.my_subs_tab.get_label()))

        self.glade.signal_autoconnect({
            "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_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":
            gtk.main_quit,
        })

        def on_identity_change(filemonitor):
            self.refresh()

        self.backend.monitor_identity(on_identity_change)

        self.main_window.show_all()
        self.refresh()

        # Check to see if already registered to old RHN/Spacewalk
        # and show dialog if so
        self._check_rhn_classic()

        if auto_launch_registration and not self.registered():
            self._register_item_clicked(None)
def find_first_invalid_date(ent_dir=None, product_dir=None,
        facts_dict=None):
    """
    Find the first date when the system is invalid at midnight
    GMT.

    WARNING: This method does *not* return the exact first datetime when
    we're invalid. Due to it's uses in the GUI it needs to
    return a datetime into the first day of being completely invalid, so
    the subscription assistant can search for that time and find expired
    products.

    If there are no products installed, return None, as there technically
    is no first invalid date.
    """
    if not ent_dir:
        ent_dir = EntitlementDirectory()
    if not product_dir:
        product_dir = ProductDirectory()
    if facts_dict is None:
        facts_dict = Facts().get_facts()

    current_date = datetime.now(GMT())

    if not product_dir.list():
        # If there are no products installed, return None, there is no
        # invalid date:
        log.debug("Unable to determine first invalid date, no products "
                "installed.")
        return None

    # change _scan_entitlement_certs to take product lists,
    # run it for the future to figure this out
    # First check if we have anything installed but not entitled *today*:
    cs = cert_sorter.CertSorter(product_dir, ent_dir, facts_dict,
            on_date=current_date)
    if not cs.is_valid():
        log.debug("Found unentitled products or partial stacks.")
        return current_date

    # Sort all the ent certs by end date. (ascending)
    all_ent_certs = ent_dir.list()

    def get_date(ent_cert):
        return ent_cert.validRange().end()

    all_ent_certs.sort(key=get_date)

    # Loop through all current and future entitlement certs, check validity
    # status on their end date, and return the first date where we're not
    # valid.
    for ent_cert in all_ent_certs:
        # Adding a timedelta of one day here so we can be sure we get a date
        # the subscription assitant (which does not use time) can use to search
        # for.
        end_date = ent_cert.validRange().end() + timedelta(days=1)
        if end_date < current_date:
            # This cert is expired, ignore it:
            continue
        log.debug("Checking cert: %s, end date: %s" % (ent_cert.serialNumber(),
            end_date))

        # new cert_sort stuff, use _scan_for_entitled_products, since
        # we just need to know if stuff is expired
        cs = cert_sorter.CertSorter(product_dir, ent_dir, facts_dict,
                on_date=end_date)
        if not cs.is_valid():
            log.debug("Found non-valid status on %s" % end_date)
            return end_date
        else:
            log.debug("Valid status on %s" % end_date)

    # Should never hit this:
    raise Exception("Unable to determine first invalid date.")
 def __init__(self):
     self.pdir = ProductDirectory()
     self.db = ProductDatabase()
     self.db.read()
     self.meta_data_errors = []
Exemple #21
0
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.
    """
    def __init__(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(),
                        key_file=ConsumerIdentity.keypath())

        self.create_content_connection()
        # we don't know the user/pass yet, so no point in
        # creating an admin uep till we need it
        self.admin_uep = None

        self.product_dir = ProductDirectory()
        self.entitlement_dir = EntitlementDirectory()
        self.certlib = CertLib(uep=self.uep)

        self.product_monitor = file_monitor.Monitor(self.product_dir.path)
        self.entitlement_monitor = file_monitor.Monitor(
            self.entitlement_dir.path)
        self.identity_monitor = file_monitor.Monitor(ConsumerIdentity.PATH)

        # connect handlers to refresh the cached data when we notice a change.
        # do this before any other handlers might connect
        self.product_monitor.connect(
            "changed", lambda monitor: self.product_dir.refresh())
        self.entitlement_monitor.connect(
            "changed", lambda monitor: self.entitlement_dir.refresh())

    # make a create that does the init
    # and a update() for a name

    def update(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(),
                        key_file=ConsumerIdentity.keypath())
        self.content_connection = self._create_content_connection()

    def create_uep(self, cert_file=None, key_file=None):
        # Re-initialize our connection:
        self.uep = self._create_uep(cert_file=cert_file, key_file=key_file)
        # Holds a reference to the old uep:
        self.certlib = CertLib(uep=self.uep)

    def _create_uep(self,
                    username=None,
                    password=None,
                    cert_file=None,
                    key_file=None):
        return connection.UEPConnection(
            host=cfg.get('server', 'hostname'),
            ssl_port=int(cfg.get('server', 'port')),
            handler=cfg.get('server', 'prefix'),
            proxy_hostname=cfg.get('server', 'proxy_hostname'),
            proxy_port=cfg.get('server', 'proxy_port'),
            proxy_user=cfg.get('server', 'proxy_user'),
            proxy_password=cfg.get('server', 'proxy_password'),
            username=username,
            password=password,
            cert_file=cert_file,
            key_file=key_file)

    def create_content_connection(self):
        self.content_connection = self._create_content_connection()

    def _create_content_connection(self):
        return connection.ContentConnection(
            host=urlparse.urlparse(cfg.get('rhsm', 'baseurl'))[1],
            ssl_port=443,
            proxy_hostname=cfg.get('server', 'proxy_hostname'),
            proxy_port=cfg.get('server', 'proxy_port'),
            proxy_user=cfg.get('server', 'proxy_user'),
            proxy_password=cfg.get('server', 'proxy_password'))

    def is_registered(self):
        return self.consumer.is_valid()

    def create_admin_uep(self, username=None, password=None):
        self.admin_uep = self._create_uep(username=username, password=password)

    def monitor_certs(self, callback):
        self.product_monitor.connect('changed', callback)
        self.entitlement_monitor.connect('changed', callback)

    def monitor_identity(self, callback):
        self.identity_monitor.connect('changed', callback)
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.
    """

    def __init__(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(), key_file=ConsumerIdentity.keypath())

        self.create_content_connection()
        # we don't know the user/pass yet, so no point in
        # creating an admin uep till we need it
        self.admin_uep = None

        self.product_dir = ProductDirectory()
        self.entitlement_dir = EntitlementDirectory()
        self.certlib = CertLib(uep=self.uep)

        self.product_monitor = file_monitor.Monitor(self.product_dir.path)
        self.entitlement_monitor = file_monitor.Monitor(self.entitlement_dir.path)
        self.identity_monitor = file_monitor.Monitor(ConsumerIdentity.PATH)

        # connect handlers to refresh the cached data when we notice a change.
        # do this before any other handlers might connect
        self.product_monitor.connect("changed", lambda monitor: self.product_dir.refresh())
        self.entitlement_monitor.connect("changed", lambda monitor: self.entitlement_dir.refresh())

    # make a create that does the init
    # and a update() for a name

    def update(self):
        self.create_uep(cert_file=ConsumerIdentity.certpath(), key_file=ConsumerIdentity.keypath())
        self.content_connection = self._create_content_connection()

    def create_uep(self, cert_file=None, key_file=None):
        # Re-initialize our connection:
        self.uep = self._create_uep(cert_file=cert_file, key_file=key_file)
        # Holds a reference to the old uep:
        self.certlib = CertLib(uep=self.uep)

    def _create_uep(self, username=None, password=None, cert_file=None, key_file=None):
        return connection.UEPConnection(
            host=cfg.get("server", "hostname"),
            ssl_port=int(cfg.get("server", "port")),
            handler=cfg.get("server", "prefix"),
            proxy_hostname=cfg.get("server", "proxy_hostname"),
            proxy_port=cfg.get("server", "proxy_port"),
            proxy_user=cfg.get("server", "proxy_user"),
            proxy_password=cfg.get("server", "proxy_password"),
            username=username,
            password=password,
            cert_file=cert_file,
            key_file=key_file,
        )

    def create_content_connection(self):
        self.content_connection = self._create_content_connection()

    def _create_content_connection(self):
        return connection.ContentConnection(
            host=urlparse.urlparse(cfg.get("rhsm", "baseurl"))[1],
            ssl_port=443,
            proxy_hostname=cfg.get("server", "proxy_hostname"),
            proxy_port=cfg.get("server", "proxy_port"),
            proxy_user=cfg.get("server", "proxy_user"),
            proxy_password=cfg.get("server", "proxy_password"),
        )

    def is_registered(self):
        return self.consumer.is_valid()

    def create_admin_uep(self, username=None, password=None):
        self.admin_uep = self._create_uep(username=username, password=password)

    def monitor_certs(self, callback):
        self.product_monitor.connect("changed", callback)
        self.entitlement_monitor.connect("changed", callback)

    def monitor_identity(self, callback):
        self.identity_monitor.connect("changed", callback)
class ProductManager:

    REPO = 'from_repo'
    PRODUCTID = 'productid'

    def __init__(self):
        self.pdir = ProductDirectory()
        self.db = ProductDatabase()
        self.db.read()
        self.meta_data_errors = []

    def update(self, yb):
        if yb is None:
            yb = yum.YumBase()
        enabled = self.getEnabled(yb)
        active = self.getActive(yb)

        #only execute this on versions of yum that track
        #which repo a package came from
        if yum.__version_info__[2] >= 28:
            # check that we have any repo's enabled
            # and that we have some enabled repo's. Not just
            # that we have packages from repo's that are
            # not active. See #806457
            if enabled and active:
                self.updateRemoved(active)
        self.updateInstalled(enabled, active)

    def _isWorkstation(self, product):
        if product.getName() == "Red Hat Enterprise Linux Workstation" and \
                "rhel-5-client-workstation" in product.getProvidedTags() and \
                product.getVersion()[0] == '5':
            return True
        return False

    def _isDesktop(self, product):
        if product.getName() == "Red Hat Enterprise Linux Desktop" and \
                "rhel-5-client" in product.getProvidedTags() and \
                product.getVersion()[0] == '5':
            return True
        return False

    def updateInstalled(self, enabled, active):
        for cert, repo in enabled:
            #nothing from this repo is installed
            if repo not in active:
                continue

            p = cert.getProduct()
            prod_hash = p.getHash()

            # Are we installing Workstation cert?
            if self._isWorkstation(p):
                # is the Desktop product cert installed?
                for pc in self.pdir.list():
                    if self._isDesktop(pc.getProduct()):
                        # Desktop product cert is installed,
                        # delete the Desktop product cert
                        pc.delete()
                        self.db.delete(prod_hash)
                        self.db.write()

            # no point installing desktop only to delete it
            if self._isDesktop(p):
                for pc in self.pdir.list():
                    if self._isWorkstation(pc.getProduct()):
                        # we are installing Desktop, but we already have workstation
                        return

            if self.pdir.findByProduct(prod_hash):
                continue

            fn = '%s.pem' % prod_hash
            path = self.pdir.abspath(fn)
            cert.write(path)
            self.db.add(prod_hash, repo)
            self.db.write()

    # We should only delete productcerts if there are no
    # packages from that repo installed (not "active")
    # and we have the product cert installed.
    def updateRemoved(self, active):
        for cert in self.pdir.list():
            p = cert.getProduct()
            prod_hash = p.getHash()
            repo = self.db.findRepo(prod_hash)

            # if we had errors with the repo or productid metadata
            # we could be very confused here, so do not
            # delete anything. see bz #736424
            if repo in self.meta_data_errors:
                log.info(
                    "%s has meta-data errors.  Not deleting product cert %s." %
                    (repo, prod_hash))
                continue

            # FIXME: not entirely sure why we do this
            #  to avoid a none on cert.delete surely
            # but is there another reason?
            if repo is None:
                continue
            if repo in active:
                continue

            log.info("product cert %s for %s is being deleted" %
                     (prod_hash, p.getName()))
            cert.delete()

            self.db.delete(prod_hash)
            self.db.write()

    # find the list of repo's that provide packages that
    # are actually installed.
    def getActive(self, yb):
        active = set()

        packages = yb.pkgSack.returnPackages()
        for p in packages:
            repo = p.repoid

            # if a pkg is in multiple repo's, this will consider
            # all the repo's with the pkg "active".
            db_pkg = yb.rpmdb.searchNevra(name=p.name, arch=p.arch)

            # that pkg is not actually installed
            if not db_pkg:
                continue

            # yum on 5.7 list everything as "installed" instead
            # of the repo it came from
            if repo in (None, "installed"):
                continue
            active.add(repo)
        return active

    def getEnabled(self, yb):
        lst = []
        enabled = yb.repos.listEnabled()

        for repo in enabled:
            try:
                fn = repo.retrieveMD(self.PRODUCTID)
                cert = self.__getCert(fn)
                if cert is None:
                    continue
                lst.append((cert, repo.id))
            except Exception, e:
                log.warn("Error loading productid metadata for %s." % repo)
                log.exception(e)
                self.meta_data_errors.append(repo.id)
        return lst
Exemple #24
0
    def __init__(self,
                 backend,
                 consumer,
                 facts,
                 parent_win,
                 ent_dir=None,
                 prod_dir=None):
        """
        Create a new 'My Subscriptions' tab.
        """
        super(MySubscriptionsTab,
              self).__init__('mysubs.glade',
                             ['details_box', 'unsubscribe_button'])
        self.backend = backend
        self.consumer = consumer
        self.facts = facts
        self.parent_win = parent_win
        self.entitlement_dir = ent_dir or EntitlementDirectory()
        self.product_dir = prod_dir or ProductDirectory()

        self.sub_details = widgets.SubDetailsWidget()

        # Put the details widget in the middle
        details = self.sub_details.get_widget()
        self.details_box.pack_start(details)

        # Set up columns on the view
        column = self.add_text_column(_("Subscription"), 'subscription', True)
        cols = []
        cols.append((column, 'text', 'subscription'))

        progress_renderer = gtk.CellRendererProgress()
        products_column = gtk.TreeViewColumn(
            _("Installed Products"),
            progress_renderer,
            value=self.store['installed_value'],
            text=self.store['installed_text'])
        self.empty_progress_renderer = gtk.CellRendererText()
        products_column.pack_end(self.empty_progress_renderer, True)
        products_column.set_cell_data_func(progress_renderer,
                                           self._update_progress_renderer)
        self.top_view.append_column(products_column)

        column = self.add_date_column(_("End Date"), 'expiration_date')
        cols.append((column, 'date', 'expiration_date'))

        # Disable row striping on the tree view as we are overriding the behavior
        # to display stacking groups as one color.
        self.top_view.set_rules_hint(False)

        column = self.add_text_column(_("Quantity"), 'quantity')
        cols.append((column, 'text', 'quantity'))

        self.set_sorts(cols)

        self.top_view.connect(
            "row_activated", widgets.expand_collapse_on_row_activated_callback)

        self.update_subscriptions()

        self.glade.signal_autoconnect(
            {'on_unsubscribe_button_clicked': self.unsubscribe_button_clicked})

        # Monitor entitlements/products for additions/deletions
        def on_cert_change(filemonitor):
            self.update_subscriptions()

        self.backend.monitor_certs(on_cert_change)