def search_button_clicked(self, widget=None): """ Reload the subscriptions from the server when the Search button is clicked. """ if not self.date_picker.date_entry_validate(): return try: pb_title = _("Searching") pb_label = _("Searching for subscriptions. Please wait.") if self.pb: self.pb.set_title(pb_title) self.pb.set_label(pb_label) else: # show pulsating progress bar while we wait for results self.pb = progress.Progress(pb_title, pb_label) self.timer = ga_GObject.timeout_add(100, self.pb.pulse) self.pb.set_transient_for(self.parent_win) # fire off async refresh async_stash = async_utils.AsyncPool(self.pool_stash) async_stash.refresh(self.date_picker.date, self._update_display) except Exception as e: handle_gui_exception(e, _("Error fetching subscriptions from server: %s"), self.parent_win)
def __init__(self, update_callback=None): super(SystemFactsDialog, self).__init__() #self.consumer = consumer self.update_callback = update_callback self.identity = inj.require(inj.IDENTITY) self.cp_provider = inj.require(inj.CP_PROVIDER) self.facts = inj.require(inj.FACTS) self.connect_signals({ "on_system_facts_dialog_delete_event": self._hide_callback, "on_close_button_clicked": self._hide_callback, "on_facts_update_button_clicked": self._update_facts_callback }) # Set up the model self.facts_store = ga_Gtk.TreeStore(str, str) self.facts_view.set_model(self.facts_store) # Set up columns on the view self._add_column(_("Fact"), 0) self._add_column(_("Value"), 1) # set up the signals from the view self.facts_view.connect("row_activated", widgets.expand_collapse_on_row_activated_callback)
def get_environment(self, owner_key): environment_list = [] try: if self.cp.supports_resource('environments'): environment_list = self.cp.getEnvironmentList(owner_key) elif self.options.environment: system_exit(os.EX_UNAVAILABLE, _("Environments are not supported by this server.")) except Exception as e: log.exception(e) system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e) environment = None if len(environment_list) > 0: if self.options.environment: env_input = self.options.environment elif len(environment_list) == 1: env_input = environment_list[0]['name'] else: env_input = six.moves.input(_("Environment: ")).strip() readline.clear_history() for env_data in environment_list: # See BZ #978001 if (env_data['name'] == env_input or ('label' in env_data and env_data['label'] == env_input) or ('displayName' in env_data and env_data['displayName'] == env_input)): environment = env_data['name'] break if not environment: system_exit(os.EX_DATAERR, _("Couldn't find environment '%s'.") % env_input) return environment
def get_org(self, username): try: owner_list = self.cp.getOwnerList(username) except Exception as e: log.exception(e) system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e) if len(owner_list) == 0: system_exit(1, _("%s cannot register with any organizations.") % username) else: if self.options.org: org_input = self.options.org elif len(owner_list) == 1: org_input = owner_list[0]['key'] else: org_input = six.moves.input(_("Org: ")).strip() readline.clear_history() org = None for owner_data in owner_list: if owner_data['key'] == org_input or owner_data['displayName'] == org_input: org = owner_data['key'] break if not org: system_exit(os.EX_DATAERR, _("Couldn't find organization '%s'.") % org_input) return org
def legacy_purge(self, rpc_session, session_key): system_id_path = self.rhncfg["systemIdPath"] log.info("Deleting system %s from legacy server...", self.system_id) try: result = rpc_session.system.deleteSystems(session_key, self.system_id) except Exception: log.exception("Could not delete system %s from legacy server" % self.system_id) # If we time out or get a network error, log it and keep going. shutil.move(system_id_path, system_id_path + ".save") print(_("Did not receive a completed unregistration message from legacy server for system %s.") % self.system_id) if self.is_hosted: print(_("Please investigate on the Customer Portal at https://access.redhat.com.")) return if result: log.info("System %s deleted. Removing system id file and disabling rhnplugin.conf", self.system_id) os.remove(system_id_path) try: self.disable_yum_rhn_plugin() except Exception: pass print(_("System successfully unregistered from legacy server.")) else: # If the legacy server reports that deletion just failed, then quit. system_exit(1, _("Unable to unregister system from legacy server. ") + SEE_LOG_FILE)
def _button_clicked(self, button): self._calendar_window = ga_Gtk.Window(ga_Gtk.WindowType.TOPLEVEL) self._calendar_window.set_type_hint(ga_Gdk.WindowTypeHint.DIALOG) self._calendar_window.set_modal(True) self._calendar_window.set_title(_("Date Selection")) self._calendar.select_month(self._date.month - 1, self._date.year) self._calendar.select_day(self._date.day) vbox = ga_Gtk.VBox(spacing=3) vbox.set_border_width(2) vbox.pack_start(self._calendar, True, True, 0) button_box = ga_Gtk.HButtonBox() button_box.set_layout(ga_Gtk.ButtonBoxStyle.END) vbox.pack_start(button_box, True, True, 0) button = ga_Gtk.Button(_("Today")) button.connect("clicked", self._today_clicked) button_box.pack_start(button, True, True, 0) frame = ga_Gtk.Frame() frame.add(vbox) self._calendar_window.add(frame) self._calendar_window.set_position(ga_Gtk.WindowPosition.MOUSE) self._calendar_window.show_all() self._calendar.connect("day-selected-double-click", self._calendar_clicked)
def __init__(self, table_widget, product_dir, yes_id=ga_Gtk.STOCK_APPLY, no_id=ga_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. """ table_widget.get_selection().set_mode(ga_Gtk.SelectionMode.NONE) self.table_widget = table_widget self.product_store = ga_Gtk.ListStore(str, ga_GdkPixbuf.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 = product_dir name_column = ga_Gtk.TreeViewColumn(_("Product"), ga_Gtk.CellRendererText(), markup=0) name_column.set_expand(True) installed_column = ga_Gtk.TreeViewColumn(_("Installed"), ga_Gtk.CellRendererPixbuf(), pixbuf=1) table_widget.append_column(name_column) table_widget.append_column(installed_column)
def select_service_level(self, org, servicelevel): not_supported = _("Error: The service-level command is not supported by the server.") try: levels = self.cp.getServiceLevelList(org) except RemoteServerException as e: system_exit(-1, not_supported) except RestlibException as e: if e.code == 404: # no need to die, just skip it print(not_supported) return None else: # server supports it but something went wrong, die. raise e # Create the sla tuple before appending the empty string to the list of # valid slas. slas = [(sla, sla) for sla in levels] # Display an actual message for the empty string level. slas.append((_("No service level preference"), "")) # The empty string is a valid level so append it to the list. levels.append("") if servicelevel is None or \ servicelevel.upper() not in (level.upper() for level in levels): if servicelevel is not None: print(_("\nService level \"%s\" is not available.") % servicelevel) menu = Menu(slas, _("Please select a service level agreement for this system.")) servicelevel = menu.choose() return servicelevel
def _add_group(self, group): tree_iter = None if group.name and len(group.entitlements) > 1: unique = self.find_unique_name_count(group.entitlements) if unique - 1 > 1: name_string = _("Stack of %s and %s others") % \ (group.name, str(unique - 1)) elif unique - 1 == 1: name_string = _("Stack of %s and 1 other") % (group.name) else: name_string = _("Stack of %s") % (group.name) tree_iter = self.store.add_map(tree_iter, self._create_stacking_header_entry(name_string)) new_parent_image = None for i, cert in enumerate(group.entitlements): image = self._get_entry_image(cert) self.store.add_map(tree_iter, self._create_entry_map(cert, image)) # Determine if we need to change the parent's image. We # will match the parent's image with the children if any of # the children have an image. if self.image_ranks_higher(new_parent_image, image): new_parent_image = image # Update the parent image if required. if new_parent_image and tree_iter: self.store.set_value(tree_iter, self.store['image'], ga_GdkPixbuf.Pixbuf.new_from_file_at_size(new_parent_image, 13, 13))
def _validate_options(self): manifest_file = self._get_file_from_args() if not manifest_file: raise InvalidCLIOptionError(_("You must specify a manifest file.")) if not os.path.isfile(manifest_file): raise InvalidCLIOptionError(_("The specified manifest file does not exist."))
def __init__(self): RCTManifestCommand.__init__(self, name="cat-manifest", aliases=['cm'], shortdesc=_("Print manifest information"), primary=True) self.parser.add_option("--no-content", action="store_true", default=False, help=_("skip printing Content Sets"))
def _validate_options(self): cert_file = self._get_file_from_args() if not cert_file: raise InvalidCLIOptionError(_("You must specify a certificate file.")) if not os.path.isfile(cert_file): raise InvalidCLIOptionError(_("The specified certificate file does not exist."))
def __str__(self): s = ["Container content cert updates\n"] s.append(_("Added:")) s.append(self._format_file_list(self.added)) s.append(_("Removed:")) s.append(self._format_file_list(self.removed)) return '\n'.join(s)
def __init__(self, name="system", shortdesc=_("Assemble system information as a tar file or directory"), primary=True): CliCommand.__init__(self, name=name, shortdesc=shortdesc, primary=primary) self.parser.add_option("--destination", dest="destination", default="/tmp", help=_("the destination location of the result; default is /tmp")) # default is to build an archive, this skips the archive and clean up, # just leaving the directory of debug info for sosreport to report self.parser.add_option("--no-archive", action='store_false', default=True, dest="archive", help=_("data will be in an uncompressed directory")) self.parser.add_option("--sos", action='store_true', default=False, dest="sos", help=_("only data not already included in sos report will be collected")) # These options don't do anything anymore, since current versions of # RHSM api doesn't support it, and previously they failed silently. # So now they are hidden, and they are not hooked up to anything. This # avoids breaking existing scripts, since it also didn't do anything # before. See rhbz #1246680 self.parser.add_option("--no-subscriptions", action='store_true', dest="placeholder_for_subscriptions_option", default=False, help=optparse.SUPPRESS_HELP) self.parser.add_option("--subscriptions", action='store_true', dest="placeholder_for_subscriptions_option", default=False, help=optparse.SUPPRESS_HELP) self.assemble_path = ASSEMBLE_DIR # so we can track the path of the archive for tests. self.final_destination_path = None
def _display_progress_bar(self): if self.progress_bar: self.progress_bar.set_title(_("Testing Connection")) self.progress_bar.set_label(_("Please wait")) else: self.progress_bar = progress.Progress(_("Testing Connection"), _("Please wait")) self.timer = ga_GObject.timeout_add(100, self.progress_bar.pulse) self.progress_bar.set_transient_for(self.networkConfigDialog)
def __str__(self): """__str__ of report. Used in rhsm and rhsmcertd logging.""" s = [] s.append(_('Total updates: %d') % self.updates()) s.append(_('Found (local) serial# %s') % self.valid) s.append(_('Expected (UEP) serial# %s') % self.expected) self.write(s, _('Added (new)'), self.added) self.write(s, _('Deleted (rogue):'), self.rogue) return '\n'.join(s)
def type_to_string(cert): if isinstance(cert, EntitlementCertificate): return _("Entitlement Certificate") elif isinstance(cert, ProductCertificate): return _("Product Certificate") elif isinstance(cert, IdentityCertificate): return _("Identity Certificate") else: return _("Unknown Certificate Type")
def __str__(self): s = ["Ostree repo updates\n"] s.append(_("Updates:")) s.append(self._format_remotes(self.remote_updates)) s.append(_("Added:")) s.append(self._format_remotes(self.remote_added)) s.append(_("Deleted:")) s.append(self._format_remotes(self.remote_deleted)) return '\n'.join(s)
def __init__(self, table_widget): table_widget.get_selection().set_mode(ga_Gtk.SelectionMode.NONE) self.override_store = ga_Gtk.ListStore(str, str) table_widget.set_model(self.override_store) for idx, colname in enumerate([_("Name"), _("Value")]): column = ga_Gtk.TreeViewColumn(colname, ga_Gtk.CellRendererText(), markup=0, text=idx) column.set_expand(True) table_widget.append_column(column)
def __init__(self): RCTCliCommand.__init__(self, name="cat-cert", aliases=['cc'], shortdesc=_("Print certificate information"), primary=True) self.parser.add_option("--no-products", dest="no_products", action="store_true", help=_("do not show the cert's product information")) self.parser.add_option("--no-content", dest="no_content", action="store_true", help=_("do not show the cert's content info"))
def __init__(self): """ Create a new firstboot Module for the 'register' screen. """ super(moduleClass, self).__init__() dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) GLib.threads_init() dbus.mainloop.glib.threads_init() self.mode = constants.MODE_REGULAR self.title = _("Subscription Management Registration") self.sidebarTitle = _("Subscription Registration") self.priority = 200.1 # NOTE: all of this is copied form former firstboot_base module # and may no longer be needed # set this so subclasses can override behaviour if needed self._is_compat = False reg_info = registergui.RegisterInfo() self.backend = managergui.Backend() self.plugin_manager = inj.require(inj.PLUGIN_MANAGER) self.register_widget = registergui.FirstbootWidget(self.backend, reg_info) self.register_widget.connect("notify::screen-ready", self._on_screen_ready_change) # Will be False if we are on an older RHEL version where # rhn-client-tools already does some things so we don't have to. self.standalone = True distribution = HardwareCollector().get_distribution() log.debug("Distribution: %s" % str(distribution)) try: dist_version = float(distribution[1]) # We run this for Fedora as well, but all we really care about here # is if this is prior to RHEL 7, so this comparison should be safe. if dist_version < 7: self.standalone = False except Exception as e: log.error("Unable to parse a distribution version.") log.exception(e) log.debug("Running standalone firstboot: %s" % self.standalone) self.manual_message = None self._skip_apply_for_page_jump = False self._cached_credentials = None self._registration_finished = False self.interface = None self.finished = False self.proxies_were_enabled_from_gui = None self._apply_result = constants.RESULT_FAILURE self.page_status = constants.RESULT_FAILURE
def _on_close(self, button, event=None): override_mapping = self._get_changed_overrides() if (len(override_mapping["to_add"]) == 0 and len(override_mapping["to_remove"]) == 0): self.close_dialog() return True # There are changes pending, check if the user would like to save changes. confirm = YesNoDialog(_("Repositories have changes. Save changes?"), self._get_dialog_widget(), _("Save Changes")) confirm.connect("response", self._on_apply_changes_on_close_response, override_mapping)
def _print_general(self, zip_archive): # Print out general data part = zip_archive._read_file(os.path.join("export", "meta.json")) data = json.loads(part) to_print = [] to_print.append((_("Server"), get_value(data, "webAppPrefix"))) to_print.append((_("Server Version"), get_value(data, "version"))) to_print.append((_("Date Created"), get_value(data, "created"))) to_print.append((_("Creator"), get_value(data, "principalName"))) self._print_section(_("General:"), to_print)
def __init__(self): RCTManifestCommand.__init__(self, name="dump-manifest", aliases=['dm'], shortdesc=_("Dump the contents of a manifest"), primary=True) self.parser.add_option("--destination", dest="destination", help=_("directory to extract the manifest to")) self.parser.add_option("-f", "--force", action="store_true", dest="overwrite_files", default=False, help=_("overwrite files which may exist"))
def _do_command(self): """ Does the work that this command intends. """ if self.options.destination: if self._extract(self.options.destination, self.options.overwrite_files): print(_("The manifest has been dumped to the %s directory") % self.options.destination) else: if self._extract(os.getcwd(), self.options.overwrite_files): print(_("The manifest has been dumped to the current directory"))
def _on_reset_repo(self, button): selection = SelectionWrapper(self.overrides_treeview.get_selection(), self.overrides_store) if not selection.is_valid(): return confirm = YesNoDialog(_("Are you sure you want to remove all overrides for <b>%s</b>?") % selection['repo_id'], self._get_dialog_widget(), _("Confirm Remove All Overrides")) confirm.connect("response", self._on_reset_repo_response)
def _is_secure(self, base, new_file): base_path = os.path.abspath(base) new_path = os.path.abspath(new_file) if not new_path.startswith(base_path): raise Exception(_('Manifest zip attempted to extract outside of the base directory.')) #traces symlink to source, and checks that it is valid real_new_path = os.path.realpath(new_path) if real_new_path != new_path: self._is_secure(base, real_new_path) elif os.path.islink(new_path): raise Exception(_('Unable to trace symbolic link. Possibly circular linkage.'))
def __str__(self): s = [_('Repo updates') + '\n'] s.append(_('Total repo updates: %d') % self.updates()) s.append(_('Updated')) s.append(self.format_repos(self.repo_updates)) s.append(_('Added (new)')) s.append(self.format_repos(self.repo_added)) s.append(_('Deleted')) # deleted are former repo sections, but they are the same type s.append(self.format_sections(self.repo_deleted)) return u'\n'.join(s)
def main(self, args=None): self.get_auth() self.transfer_http_proxy_settings() self.cp = self.get_candlepin_connection(self.destination_creds.username, self.destination_creds.password) self.check_ok_to_proceed() (rpc_session, session_key) = self.connect_to_rhn(self.legacy_creds) if self.options.five_to_six: self.load_transition_data(rpc_session) org = None environment = None else: if self.options.activation_keys: environment = None org = self.options.org else: org = self.get_org(self.destination_creds.username) environment = self.get_environment(org) if self.options.registration_state != "keep": self.check_has_access(rpc_session, session_key) print() print(_("Retrieving existing legacy subscription information...")) subscribed_channels = self.get_subscribed_channels_list(rpc_session, session_key) self.print_banner(_("System is currently subscribed to these legacy channels:")) for channel in subscribed_channels: print(channel) self.check_for_conflicting_channels(subscribed_channels) self.deploy_prod_certificates(subscribed_channels) self.clean_up(subscribed_channels) self.write_migration_facts() if self.options.registration_state == "purge": print() print(_("Preparing to unregister system from legacy server...")) self.legacy_purge(rpc_session, session_key) elif self.options.registration_state == "unentitle": self.legacy_unentitle(rpc_session) else: # For the "keep" case, we just leave everything alone. pass using_systemd = self.is_using_systemd() self.handle_legacy_daemons(using_systemd) if self.options.remove_legacy_packages: self.remove_legacy_packages() identity = self.register(self.destination_creds, org, environment) if identity: self.enable_extra_channels(subscribed_channels)
def write_values(self, widget=None, dummy=None): proxy = self.proxyEntry.get_text() or "" # don't save these values if they are disabled in the gui # settings of HTTP Proxy if proxy and self.enableProxyButton.get_active(): # Remove any URI scheme provided proxy = remove_scheme(proxy) # Update the proxy entry field to show we removed any scheme self.proxyEntry.set_text(proxy) try: proxy_hostname, proxy_port = proxy.split(':') self.cfg.set("server", "proxy_hostname", proxy_hostname) self.cfg.set("server", "proxy_port", proxy_port) except ValueError: # no port? just write out the hostname and assume default self.cfg.set("server", "proxy_hostname", proxy) self.cfg.set("server", "proxy_port", rhsm.config.DEFAULT_PROXY_PORT) else: # delete config options if we disable it in the ui self.cfg.set("server", "proxy_hostname", "") self.cfg.set("server", "proxy_port", "") # settings of HTTP proxy authentication if self.enableProxyAuthButton.get_active(): if self.proxyUserEntry.get_text() is not None: self.cfg.set("server", "proxy_user", str(self.proxyUserEntry.get_text())) if self.proxyPasswordEntry.get_text() is not None: self.cfg.set("server", "proxy_password", str(self.proxyPasswordEntry.get_text())) else: self.cfg.set("server", "proxy_user", "") self.cfg.set("server", "proxy_password", "") # settings of bypass the HTTP proxy for specific host/domain if self.enableProxyBypassButton.get_active(): if self.noProxyEntry.get_text() is not None: self.cfg.set("server", "no_proxy", str(self.noProxyEntry.get_text())) else: self.cfg.set("server", "no_proxy", "") try: self.cfg.save() self.cp_provider.set_connection_info() except Exception: show_error_window(_("There was an error saving your configuration.") + _("Make sure that you own %s.") % self.cfg.fileName, parent=self.networkConfigDialog)
def _read_file(self, file_path, is_inner=False): try: output = BytesIO(self.read(file_path)) result = output.getvalue() output.close() except KeyError: try: if is_inner: raise KeyError result = self._get_inner_zip()._read_file(file_path, True) except KeyError: raise Exception( _('Unable to find file "%s" in manifest.') % file_path) return result
def __init__(self): super(RemoveCommand, self).__init__(self._command_name(), self._short_description(), self._primary()) self.parser.add_argument( "--serial", action="append", dest="serials", metavar="SERIAL", help=_("certificate serial number to remove (can be specified more than once)"), ) self.parser.add_argument( "--pool", action="append", dest="pool_ids", metavar="POOL_ID", help=_("the ID of the pool to remove (can be specified more than once)"), ) self.parser.add_argument( "--all", dest="all", action="store_true", help=_("remove all subscriptions from this system"), )
def legacy_unentitle(self, rpc_session): try: rpc_session.system.unentitle(self.system_id_contents) except Exception as e: log.exception( "Could not remove system entitlement on Satellite 5.", e) system_exit( os.EX_SOFTWARE, _("Could not remove system entitlement on legacy server. ") + SEE_LOG_FILE) try: self.disable_yum_rhn_plugin() except Exception: pass
def resolve_base_channel(self, label, rpc_session, session_key): try: details = rpc_session.channel.software.getDetails( session_key, label) except Exception as e: log.exception(e) system_exit( os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels. " ) + SEE_LOG_FILE) if details['clone_original']: return self.resolve_base_channel(details['clone_original'], rpc_session, session_key) return details
def set(self): """ Try to set new syspurpose attribute """ self._set(self.options.set) self._is_provided_value_valid(self.options.set) success_msg = _('{attr} set to "{val}".').format(attr=self.attr, val=self.options.set) self._check_result( expectation=lambda res: res.get(self.attr) == self.options.set, success_msg=success_msg, command='subscription-manager {name} --set "{val}"'.format( name=self.name, val=self.options.set), attr=self.attr)
def main(self): managerlib.check_identity_cert_perms() ret = CLI.main(self) # Try to enable all yum plugins (subscription-manager and plugin-id) enabled_yum_plugins = YumPluginManager.enable_pkg_plugins() if len(enabled_yum_plugins) > 0: print("\n" + _("WARNING") + "\n\n" + YumPluginManager.warning_message(enabled_yum_plugins) + "\n") # Try to flush all outputs, see BZ: 1350402 try: sys.stdout.flush() sys.stderr.flush() except IOError as io_err: log.error("Error: Unable to print data to stdout/stderr output during exit process: %s" % io_err) return ret
def _perform_unregister(self): try: reset_resolver() unregister.UnregisterService( self.backend.cp_provider.get_consumer_auth_cp()).unregister() except Exception as e: log.error("Error unregistering system with entitlement platform.") handle_gui_exception( e, _("<b>Errors were encountered during unregister.</b>") + "\n%s\n" + _("Please see /var/log/rhsm/rhsm.log for more information."), self.main_window, log_msg="Consumer may need to be manually cleaned up: %s" % self.identity.uuid) # managerlib.unregister removes product and entitlement directories self.backend.product_dir.__init__() self.backend.entitlement_dir.__init__() # We have new credentials, restart virt-who restart_virt_who() self.backend.cs.force_cert_check()
def _contract_selected(self, pool, quantity=1): if not valid_quantity(quantity): show_error_window(_("Quantity must be a positive number."), parent=self.parent_win) return self._contract_selection_cancelled() # Start the progress bar self.pb = progress.Progress(_("Attaching"), _("Attaching subscription. Please wait.")) self.timer = ga_GObject.timeout_add(100, self.pb.pulse) self.pb.set_transient_for(self.parent_win) # Spin off a thread to handle binding the selected pool. # After it has completed the actual bind call, available # subs will be refreshed, but we won't re-run compliance # until we have serialized the certificates self.async_bind.bind( pool, quantity, bind_callback=self._async_bind_callback, cert_callback=self.backend.cs.force_cert_check, except_callback=self._async_bind_exception_callback)
def _get_valid_fields(self): """ Try to get valid fields from server :return: Dictionary with valid fields """ valid_fields = {} if self.is_registered(): # When system is registered, then try to get valid fields from cache file try: valid_fields = get_syspurpose_valid_fields( uep=self.cp, identity=self.identity) except ProxyException: system_exit( os.EX_UNAVAILABLE, _("Proxy connection failed, please check your settings.")) elif self.options.username and self.options.password and self.cp is not None: # Try to get current organization key. It is property of OrgCommand. # Every Syspurpose command has to be subclass of OrgCommand too # must have used credentials in command if not registered to proceed try: org_key = self.org server_response = self.cp.getOwnerSyspurposeValidFields( org_key) except connection.RestlibException as rest_err: log.warning( "Unable to get list of valid fields using REST API: {rest_err}" .format(rest_err=rest_err)) except ProxyException: system_exit( os.EX_UNAVAILABLE, _("Proxy connection failed, please check your settings.")) else: if 'systemPurposeAttributes' in server_response: server_response = post_process_received_data( server_response) valid_fields = server_response['systemPurposeAttributes'] return valid_fields
def _validate_options(self): if self.options.additions: self._additions_colon_split() if self.options.additions or self.options.removals: if not self.options.repos: system_exit( os.EX_USAGE, _("Error: You must specify a repository to modify")) if self.options.remove_all or self.options.list: system_exit( os.EX_USAGE, _("Error: You may not use --add or --remove with --remove-all and --list" )) if self.options.list and self.options.remove_all: system_exit(os.EX_USAGE, _("Error: You may not use --list with --remove-all")) if self.options.repos and not ( self.options.list or self.options.additions or self.options.removals or self.options.remove_all): system_exit( os.EX_USAGE, _("Error: The --repo option must be used with --list or --add or --remove." )) if self.options.removals: stripped_removals = [ removal.strip() for removal in self.options.removals ] if "" in stripped_removals: system_exit( os.EX_USAGE, _("Error: You must specify an override name with --remove." )) # If no relevant options were given, just show a list if not (self.options.repos or self.options.additions or self.options.removals or self.options.remove_all or self.options.list): self.options.list = True
def show_autosubscribe_output(uep, identity): """ Try to show auto-attach output :param uep: object with connection to candlepin :param identity: object with identity :return: return 1, when all installed products are subscribed, otherwise return 0 """ if is_simple_content_access(uep=uep, identity=identity): return 0 installed_products = products.InstalledProducts(uep).list() if not installed_products: # Returning an error code here breaks registering when no products are installed, and the # AttachCommand already performs this check before calling. print(_("No products installed.")) return 0 log.debug("Attempted to auto-attach/heal the system.") print(_("Installed Product Current Status:")) subscribed = 1 all_subscribed = True for product in installed_products: if product[4] == SUBSCRIBED: subscribed = 0 status = STATUS_MAP[product[4]] if product[4] == NOT_SUBSCRIBED: all_subscribed = False print( columnize(PRODUCT_STATUS, echo_columnize_callback, product[0], status) + "\n") if not all_subscribed: print( _("Unable to find available subscriptions for all your installed products." )) return subscribed
def _do_command(self): if not self.is_registered(): # TODO: Should this use the standard NOT_REGISTERED message? system_exit(ERR_NOT_REGISTERED_CODE, _("This system is currently not registered.")) print( _("Unregistering from: {hostname}:{port}{prefix}").format( hostname=conf["server"]["hostname"], port=conf["server"]["port"], prefix=conf["server"]["prefix"], )) try: unregister.UnregisterService(self.cp).unregister() except Exception as e: handle_exception("Unregister failed", e) # managerlib.unregister reloads the now None provided identity # so cp_provider provided auth_cp's should fail, like the below # This block is simply to ensure that the yum repos got updated. If it fails, # there is no issue since it will most likely be cleaned up elsewhere (most # likely by the yum plugin) try: # there is no consumer cert at this point, a uep object # is not useful cleanup_certmgr = UnregisterActionClient() cleanup_certmgr.update() except Exception: pass self._request_validity_check() # We have new credentials, restart virt-who restart_virt_who() print(_("System has been unregistered."))
def __init__(self): self.CLI_REGISTER = _("Register the system to the server") self.CLI_UNREGISTER = _("Unregister the system from the server") self.RHSMD_REGISTERED_TO_OTHER = \ _("This system is registered to spacewalk") self.REGISTERED_TO_OTHER_WARNING = _("WARNING") + \ "\n" + \ _("You have already registered with spacewalk.") self.GUI_REGISTRATION_HEADER = \ _("Please enter your account information:") self.GUI_FORGOT_LOGIN_TIP = \ _("Contact your system administrator if you have forgotten your login or password")
def date_entry_validate(self): """ validate the date and pop up a box if not valid """ try: self._date_validate(self._date_entry.get_text()) self.emit('date-picked-text') return True except ValueError: today = datetime.date.today() messageWindow.ErrorDialog( messageWindow.wrap_text("%s %s" % (_( "Invalid date format. Please re-enter a valid date. Example: " ), today.isoformat()))) return False
def get_subscribed_channels_list(self, rpc_session, session_key): try: channels = getChannels().channels() except Exception as e: log.exception(e) system_exit( os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels. " ) + SEE_LOG_FILE) if self.options.five_to_six: channels = [ self.resolve_base_channel(c['label'], rpc_session, session_key) for c in channels ] return [x['label'] for x in channels]
def get_environment(self, owner_key): environment_list = [] try: if self.cp.supports_resource('environments'): environment_list = self.cp.getEnvironmentList(owner_key) elif self.options.environment: system_exit( os.EX_UNAVAILABLE, _("Environments are not supported by this server.")) except Exception as e: log.exception(e) system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e) environment = None if len(environment_list) > 0: if self.options.environment: env_input = self.options.environment elif len(environment_list) == 1: env_input = environment_list[0]['name'] else: env_input = six.moves.input(_("Environment: ")).strip() readline.clear_history() for env_data in environment_list: # See BZ #978001 if (env_data['name'] == env_input or ('label' in env_data and env_data['label'] == env_input) or ('displayName' in env_data and env_data['displayName'] == env_input)): environment = env_data['name'] break if not environment: system_exit(os.EX_DATAERR, _("Couldn't find environment '%s'.") % env_input) return environment
def _print_ignore_auto_attach_mesage(self): """ This message is shared by attach command and register command, because both commands can do auto-attach. :return: None """ owner = get_current_owner(self.cp, self.identity) # We displayed Owner name: `owner_name = owner['displayName']`, but such behavior # was not consistent with rest of subscription-manager # Look at this comment: https://bugzilla.redhat.com/show_bug.cgi?id=1826300#c8 owner_id = owner['key'] print( _('Ignoring request to auto-attach. ' 'It is disabled for org "{owner_id}" because of the content access mode setting.' ).format(owner_id=owner_id))
def list(self): valid_fields = self._get_valid_fields() if self.attr in valid_fields: if len(valid_fields[self.attr]) > 0: line = '+-------------------------------------------+' print(line) translated_string = _('Available {syspurpose_attr}').format( syspurpose_attr=self.attr) # Print translated string (the length could be different) in the center of the line line_len = len(line) trans_str_len = len(translated_string) empty_space_len = int((line_len - trans_str_len) / 2) print(empty_space_len * ' ' + translated_string) print(line) # Print values self._print_valid_values(valid_fields) else: print( _('This org does not have any subscriptions with an available "{syspurpose_attr}"' ).format(syspurpose_attr=self.attr)) else: print( _('This org does not have any subscriptions with an available "{syspurpose_attr}"' ).format(syspurpose_attr=self.attr))
def add(self): self._add(self.options.to_add) self._are_provided_values_valid(self.options.to_add) success_msg = _("{attr} updated.").format(attr=self.name) # When there is several options to add, then format of command is following # subscription-manager command --add opt1 --add opt2 options = ['"' + option + '"' for option in self.options.to_add] to_add = "--add " + " --add ".join(options) command = "subscription-manager syspurpose {name} ".format(name=self.name) + to_add self._check_result( expectation=lambda res: all(x in res.get("addons", []) for x in self.options.to_add), success_msg=success_msg, command=command, attr=self.attr, )
def _check_key_value_validity(self, key, value): """ Check validity of provided key and value of it is included in valid fields :param key: provided key :param value: provided value :return: None """ # FIXME: it is not good idea to print something in this package if self.valid_fields is not None: if key in self.valid_fields: if value not in self.valid_fields[key]: print( _('Warning: Provided value "{val}" is not included in the list ' 'of valid values for attribute {attr}:').format( val=value, attr=key)) for valid_value in self.valid_fields[key]: if len(valid_value) > 0: print(" - %s" % valid_value) else: print( _('Warning: Provided key "{key}" is not included in the list of valid keys:' ).format(key=key)) for valid_key in self.valid_fields.keys(): print(" - %s" % valid_key)
def remove(self): self._remove(self.options.to_remove) success_msg = _("{attr} updated.").format(attr=self.name.capitalize()) options = ['"' + option + '"' for option in self.options.to_remove] # When there is several options to remove, then format of command is following # subscription-manager command --remove opt1 --remove opt2 to_remove = "--remove " + " --remove ".join(options) command = "subscription-manager {name} ".format( name=self.name) + to_remove self._check_result( expectation=lambda res: all(x not in res.get('addons', []) for x in self.options.to_remove), success_msg=success_msg, command=command, attr=self.attr)
def enable_extra_channels(self, subscribed_channels): # Check if system was subscribed to extra channels like supplementary, optional, fastrack etc. # If so, enable them in the redhat.repo file extra_channels = {'supplementary': False, 'productivity': False, 'optional': False} for subscribedChannel in subscribed_channels: if 'supplementary' in subscribedChannel: extra_channels['supplementary'] = True elif 'optional' in subscribedChannel: extra_channels['optional'] = True elif 'productivity' in subscribedChannel: extra_channels['productivity'] = True if True not in list(extra_channels.values()): return # create and populate the redhat.repo file # use the injection cp_providers consumer auth repolib.RepoActionInvoker().update() # read in the redhat.repo file repofile = repolib.YumRepoFile() repofile.read() # enable any extra channels we are using and write out redhat.repo try: for rhsmChannel in repofile.sections(): if ((extra_channels['supplementary'] and re.search('supplementary$', rhsmChannel)) or (extra_channels['optional'] and re.search('optional-rpms$', rhsmChannel)) or (extra_channels['productivity'] and re.search('productivity-rpms$', rhsmChannel))): log.debug("Enabling extra channel '%s'" % rhsmChannel) repofile.set(rhsmChannel, 'enabled', '1') repofile.write() except Exception: print(_("\nCouldn't enable extra repositories.")) command = "subscription-manager repos --help" print(_("Please ensure system has subscriptions attached, and see '%s' to enable additional repositories") % command)
def _do_command(self): self.assert_should_be_registered() try: # remove content_access cache, ensuring we get it fresh content_access = inj.require(inj.CONTENT_ACCESS_CACHE) if content_access.exists(): content_access.remove() # Also remove the content access mode cache to be sure we display # SCA or regular mode correctly content_access_mode = inj.require(inj.CONTENT_ACCESS_MODE_CACHE) if content_access_mode.exists(): content_access_mode.delete_cache() if self.options.force is True: # get current consumer identity consumer_identity = inj.require(inj.IDENTITY) # Force a regen of the entitlement certs for this consumer if not self.cp.regenEntitlementCertificates( consumer_identity.uuid, True): log.debug( "Warning: Unable to refresh entitlement certificates; service likely unavailable" ) self.entcertlib.update() log.debug("Refreshed local data") print(_("All local data refreshed")) except connection.RestlibException as re: log.error(re) system_exit(os.EX_SOFTWARE, str(re)) except Exception as e: handle_exception( _("Unable to perform refresh due to the following exception: {e}" ).format(e=e), e) self._request_validity_check()
def get_client_versions(): # It's possible (though unlikely, and kind of broken) to have more # than one version of subscription-manager installed. # This will return whatever version we are using. sm_version = _("Unknown") try: sm_version = subscription_manager.version.rpm_version if sm_version is None or sm_version == "None": sm_version = pkg_resources.require("subscription-manager")[0].version except Exception as e: log.debug("Client Versions: Unable to check client versions") log.exception(e) return {"subscription-manager": sm_version}
def __init__(self, subparser=None): shortdesc = _( "Show or modify the system purpose service-level setting") super(ServiceLevelCommand, self).__init__( "service-level", subparser, shortdesc, False, attr="service_level_agreement", commands=["set", "unset", "show", "list"], ) self._add_url_options() self.identity = inj.require(inj.IDENTITY)
def _set_validity_status(self): """ Updates the entitlement validity status portion of the UI. """ if ClassicCheck().is_registered_with_classic(): self._set_status_icons(VALID_STATUS) self.subscription_status_label.set_text( get_branding().RHSMD_REGISTERED_TO_OTHER) return is_registered = self.identity.is_valid() self.set_registered(is_registered) warn_count = len(self.backend.cs.unentitled_products) if self.backend.cs.system_status == 'valid': self._set_status_icons(VALID_STATUS) if len(list(self.backend.cs.installed_products.keys())) == 0: # No product certs installed, thus no compliant until date: self.subscription_status_label.set_text( # I18N: Please add newlines if translation is longer: _("No installed products detected.")) elif self.backend.cs.compliant_until: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("System is properly subscribed through %s.") % managerlib.format_date(self.backend.cs.compliant_until)) else: log.warn("Server did not provide a compliant until date.") self.subscription_status_label.set_text( _("System is properly subscribed.")) elif self.backend.cs.system_status == 'partial': self._set_status_icons(PARTIAL_STATUS) self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("This system does not match subscription limits.")) elif self.backend.cs.system_status == 'invalid': self._set_status_icons(INVALID_STATUS) if warn_count > 1: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("%s installed products do not have valid subscriptions.") % warn_count) else: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("1 installed product does not have a valid subscription." )) elif self.backend.cs.system_status == 'unknown': self._set_status_icons(UNKNOWN_STATUS) self.subscription_status_label.set_text( # I18N: Please add newlines if translation is longer: _("Keep your system up to date by registering."))
def _do_command(self): cert = self._create_cert() pem = self._get_pem(self._get_file_from_args()) print( _("Type: {certificate_type}").format( certificate_type=type_to_string(cert))) print( _("Version: {certificate_version}").format( certificate_version=cert.version)) print(_("DER size: {size}b").format(size=self._get_der_size(pem))) subject_key_id = self._get_subject_key_id(pem) if subject_key_id is not None: print( _("Subject Key ID size: {len_subject_key_id}b").format( len_subject_key_id=len(subject_key_id))) if isinstance(cert, EntitlementCertificate): content_len = 0 if cert.content: content_len = len(cert.content) print( _("Content sets: {content_length}").format( content_length=content_len))
def _do_command(self): try: # get a UEP if self.options.token: self.cp = self.cp_provider.get_keycloak_auth_cp( self.options.token) else: self.cp_provider.set_user_pass(self.username, self.password) self.cp = self.cp_provider.get_basic_auth_cp() owners = self.cp.getOwnerList(self.username) log.debug("Successfully retrieved org list from server.") if len(owners): print("+-------------------------------------------+") print(" {name} {label}".format( name=self.username, label=_('Organizations'))) print("+-------------------------------------------+") print("") for owner in owners: print( columnize(ORG_LIST, echo_columnize_callback, owner['displayName'], owner['key']) + "\n") else: print( _("{username} cannot register with any organizations."). format(username=self.username)) except connection.RestlibException as re: log.exception(re) log.error( "Error: Unable to retrieve org list from server: {re}".format( re=re)) system_exit(os.EX_SOFTWARE, str(re)) except Exception as e: handle_exception( _("Error: Unable to retrieve org list from server"), e)
def run(self): try: init_dep_injection() except ImportError as e: logger.error(str(e)) return command = packageprofilelib.PackageProfileActionCommand() report = command.perform(force_upload=self.opts.force_upload) if report._status == 0: print( _("No updates performed. See /var/log/rhsm/rhsm.log for more information." )) else: print(report)
def _check_result(self, expectation, success_msg, command, attr): if self.store: self.store.sync() result = self.store.get_cached_contents() else: result = {} if result and not expectation(result): advice = SP_ADVICE.format(command=command) value = result[attr] msg = _( SP_CONFLICT_MESSAGE.format(attr=attr, download_value=value, advice=advice)) system_exit(os.EX_SOFTWARE, msgs=msg) else: print(success_msg)