def main(): if OPTIONS.add: need_channel(OPTIONS.channel) result = subscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password) if OPTIONS.verbose: if result == 0: print _("Channel(s): %s successfully added") % ", ".join(OPTIONS.channel) else: sys.stderr.write( rhncli.utf8_encode(_("Error during adding channel(s) %s") % ", ".join(OPTIONS.channel)) ) if result != 0: sys.exit(result) elif OPTIONS.remove: need_channel(OPTIONS.channel) result = unsubscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password) if OPTIONS.verbose: if result == 0: print _("Channel(s): %s successfully removed") % ", ".join(OPTIONS.channel) else: sys.stderr.write( rhncli.utf8_encode(_("Error during removal of channel(s) %s") % ", ".join(OPTIONS.channel)) ) if result != 0: sys.exit(result) elif OPTIONS.list: try: channels = map(lambda x: x["label"], getChannels().channels()) except up2dateErrors.NoChannelsError: systemExit(1, _("This system is not associated with any channel.")) except up2dateErrors.NoSystemIdError: systemExit(1, _("Unable to locate SystemId file. Is this system registered?")) channels.sort() print "\n".join(channels) elif OPTIONS.base: try: for channel in getChannels().channels(): # Base channel has no parent if not channel["parent_channel"]: print channel["label"] except up2dateErrors.NoChannelsError: systemExit(1, "This system is not associated with any channel.") except up2dateErrors.NoSystemIdError: systemExit(1, "Unable to locate SystemId file. Is this system registered?") elif OPTIONS.available_channels: channels = get_available_channels(OPTIONS.user, OPTIONS.password) channels.sort() print "\n".join(channels) else: systemExit(3, _("ERROR: you may want to specify --add, --remove or --list"))
def __check_instance_lock(): lock = None try: lock = rhnLockfile.Lockfile('/var/run/rhn_check.pid') except rhnLockfile.LockfileLockedException, e: sys.stderr.write(rhncli.utf8_encode(_("Attempting to run more than one instance of rhn_check. Exiting.\n"))) sys.exit(0)
def utf8_encode(msg): """ for RHEL6 just pass the function to rhncli for RHEL5 do the same within this module """ if hasattr(rhncli, 'utf8_encode'): return rhncli.utf8_encode(msg) if isinstance(msg, UnicodeType): msg = msg.encode('utf-8') return(msg)
def systemExit(code, msgs=None): "Exit with a code and optional message(s). Saved a few lines of code." if msgs is not None: if type(msgs) not in [type([]), type(())]: msgs = (msgs, ) for msg in msgs: if hasattr(msg, 'value'): msg = msg.value sys.stderr.write(rhncli.utf8_encode(msg) + "\n") sys.exit(code)
def poll_hypervisor(): """ This function polls the hypervisor for information about the currently running set of domains. It returns a dictionary object that looks like the following: { uuid : { 'name' : '...', 'uuid' : '...', 'virt_type' : '...', 'memory_size' : '...', 'vcpus' : '...', 'state' : '...' }, ... } """ if not libvirt: return {} try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError, lve: # virConnectOpen() failed sys.stderr.write(rhncli.utf8_encode(_("Warning: Could not retrieve virtualization information!\n\tlibvirtd service needs to be running.\n"))) conn = None
def main(self): if self.options.serverUrl: rhnreg.cfg.set("serverURL", self.options.serverUrl) if self.options.sslCACert: rhnreg.cfg.set("sslCACert", self.options.sslCACert) if not (self.options.activationkey or (self.options.username and self.options.password)): print _("A username and password are required "\ "to register a system.") sys.exit(-1) if rhnreg.registered() and not self.options.force: print _("This system is already registered. Use --force to override") sys.exit(-1) rhnreg.getCaps() if not self.options.nopackages: getArch = 0 if rhnreg.cfg['supportsExtendedPackageProfile']: getArch = 1 packageList = pkgUtils.getInstalledPackageList(getArch=getArch) else: packageList = [] hardwareList = hardware.Hardware() if self.options.profilename: profilename = self.options.profilename else: profilename = RegisterKsCli.__generateProfileName(hardwareList) other = {} if self.options.systemorgid: other['org_id'] = self.options.systemorgid # Try to get the virt uuid and put it in "other". (virt_uuid, virt_type) = rhnreg.get_virt_info() if not virt_uuid is None: other['virt_uuid'] = virt_uuid other['virt_type'] = virt_type # If specified, send up the EUS channel label for subscription. if self.options.use_eus_channel: if self.options.activationkey: print _("Usage of --use-eus-channel option with --activationkey is not supported. Please use username and password instead.") sys.exit(-1) if not rhnreg.server_supports_eus(): print _("The server you are registering against does not support EUS.") sys.exit(-1) channels = rhnreg.getAvailableChannels(self.options.username, self.options.password) other['channel'] = channels['default_channel'] try: if self.options.activationkey: systemId = rhnreg.registerSystem(token = self.options.activationkey, profileName = profilename, other = other) else: systemId = rhnreg.registerSystem(self.options.username, self.options.password, profilename, other = other) except (up2dateErrors.AuthenticationTicketError, up2dateErrors.RhnUuidUniquenessError, up2dateErrors.CommunicationError, up2dateErrors.AuthenticationOrAccountCreationError): e = sys.exc_info()[1] print "%s" % e.errmsg sys.exit(1) # collect hardware info, inluding hostname if not self.options.nohardware: rhnreg.sendHardware(systemId, hardwareList) if not self.options.nopackages: rhnreg.sendPackages(systemId, packageList) if self.options.contactinfo: print _("Warning: --contactinfo option has been deprecated. Please login to the server web user Interface and update your contactinfo. ") # write out the new id if isinstance(systemId, unicode): rhnreg.writeSystemId(unicode.encode(systemId, 'utf-8')) else: rhnreg.writeSystemId(systemId) # assume successful communication with server # remember to save the config options rhnreg.cfg.save() # Send virtualization information to the server. We must do this # *after* writing out the system id. if not self.options.novirtinfo: rhnreg.sendVirtInfo(systemId) # do this after writing out system id, bug #147513 if not self.options.norhnsd: rhnreg.startRhnsd() try: present, conf_changed = rhnreg.pluginEnable() if not present: sys.stderr.write(rhncli.utf8_encode(_("Warning: %s is not present, could not enable it.") % PM_PLUGIN_NAME)) except IOError: e = sys.exc_info()[1] sys.stderr.write(rhncli.utf8_encode(_("Warning: Could not open %s\n%s is not enabled.\n") % (PM_PLUGIN_CONF, PM_PLUGIN_NAME) + e.errmsg)) RegisterKsCli.__runRhnCheck(self.options.verbose)
def poll_hypervisor(): """ This function polls the hypervisor for information about the currently running set of domains. It returns a dictionary object that looks like the following: { uuid : { 'name' : '...', 'uuid' : '...', 'virt_type' : '...', 'memory_size' : '...', 'vcpus' : '...', 'state' : '...' }, ... } """ if not libvirt: return {} try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError: # virConnectOpen() failed sys.stderr.write(rhncli.utf8_encode(_("Warning: Could not retrieve virtualization information!\n\t" + "libvirtd service needs to be running.\n"))) conn = None if not conn: # No connection to hypervisor made return {} domainIDs = conn.listDomainsID() state = {} for domainID in domainIDs: try: domain = conn.lookupByID(domainID) except libvirt.libvirtError: lve = sys.exc_info()[1] raise_with_tb(VirtualizationException("Failed to obtain handle to domain %d: %s" % (domainID, repr(lve)), sys.exc_info()[2])) uuid = binascii.hexlify(domain.UUID()) # SEE: http://libvirt.org/html/libvirt-libvirt.html#virDomainInfo # for more info. domain_info = domain.info() # Set the virtualization type. We can tell if the domain is fully virt # by checking the domain's OSType() attribute. virt_type = VirtualizationType.PARA if is_fully_virt(domain): virt_type = VirtualizationType.FULLY # we need to filter out the small per/minute KB changes # that occur inside a vm. To do this we divide by 1024 to # drop our precision down to megabytes with an int then # back up to KB memory = int(domain_info[2] / 1024); memory = memory * 1024; properties = { PropertyType.NAME : domain.name(), PropertyType.UUID : uuid, PropertyType.TYPE : virt_type, PropertyType.MEMORY : str(memory), # current memory PropertyType.VCPUS : domain_info[3], PropertyType.STATE : VIRT_STATE_NAME_MAP[domain_info[0]] } state[uuid] = properties if state: _log_debug("Polled state: %s" % repr(state)) return state
svrChannels = rhnChannel.getChannelDetails() except up2dateErrors.NoSystemIdError, e: sys.stderr.write("%s\n" % e) sys.exit(42) except up2dateErrors.Error, e: sys.stderr.write("%s\n" % e) sys.exit(1) except: sys.exit(1) service_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] print "# Channels for service %s" % service_name for channel in svrChannels: print >>sendback if channel['name']: print >>sendback, "# Name: %s" % utf8_encode(channel['name']) if channel['summary']: print >>sendback, "# Summary: %s" % utf8_encode(channel['summary']) if channel['description']: print >>sendback, "# Description:" for line in [line for line in channel['description'].split(os.linesep)]: print >>sendback, "# %s" % utf8_encode(line) print >>sendback, "#" if channel['type']: print >>sendback, "# Type: %s" % utf8_encode(channel['type']) if channel['version']: print >>sendback, "# Version: %s" % utf8_encode(channel['version']) if channel['arch']: print >>sendback, "# Architecture: %s" % utf8_encode(channel['arch']) if channel['gpg_key_url']: print >>sendback, "# Gpg Key: %s" % utf8_encode(channel['gpg_key_url'])
svrChannels = rhnChannel.getChannelDetails() except up2dateErrors.NoSystemIdError as e: sys.stderr.write("%s\n" % e) sys.exit(42) except up2dateErrors.Error as e: sys.stderr.write("%s\n" % e) sys.exit(1) except: sys.exit(1) service_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] print("# Channels for service %s" % service_name) for channel in svrChannels: _sendback("") if channel['name']: _sendback("# Name: %s" % utf8_encode(channel['name'])) if channel['summary']: _sendback("# Summary: %s" % utf8_encode(channel['summary'])) if channel['description']: _sendback("# Description:") for line in [line for line in channel['description'].split(os.linesep)]: _sendback("# %s" % utf8_encode(line)) _sendback("#") if channel['type']: _sendback("# Type: %s" % utf8_encode(channel['type'])) if channel['version']: _sendback("# Version: %s" % utf8_encode(channel['version'])) if channel['arch']: _sendback("# Architecture: %s" % utf8_encode(channel['arch'])) if channel['gpg_key_url']: _sendback("# Gpg Key: %s" % utf8_encode(channel['gpg_key_url']))
class RegisterKsCli(rhncli.RhnCli): def __init__(self): super(RegisterKsCli, self).__init__() self.optparser.add_option("--profilename", action="store", help=_("Specify a profilename")), self.optparser.add_option("--username", action="store", help=_("Specify a username")), self.optparser.add_option("--password", action="store", help=_("Specify a password")), self.optparser.add_option( "--systemorgid", action="store", help=_("Specify an organizational id for this system")), self.optparser.add_option("--serverUrl", action="store", help=_("Specify a url to use as a server")), self.optparser.add_option( "--sslCACert", action="store", help=_("Specify a file to use as the ssl CA cert")), self.optparser.add_option("--activationkey", action="store", help=_("Specify an activation key")), self.optparser.add_option( "--use-eus-channel", action="store_true", help= _("Subscribe this system to the EUS channel tied to the system's redhat-release" )), self.optparser.add_option( "--contactinfo", action="store_true", default=False, help=_("[Deprecated] Read contact info from stdin")), self.optparser.add_option( "--nohardware", action="store_true", default=False, help=_("Do not probe or upload any hardware info")), self.optparser.add_option( "--nopackages", action="store_true", default=False, help=_("Do not profile or upload any package info")), self.optparser.add_option( "--novirtinfo", action="store_true", default=False, help=_("Do not upload any virtualization info")), self.optparser.add_option( "--norhnsd", action="store_true", default=False, help=_("Do not start rhnsd after completion")), self.optparser.add_option( "--force", action="store_true", default=False, help=_("Register the system even if it is already registered")), def main(self): if self.options.serverUrl: rhnreg.cfg.set("serverURL", self.options.serverUrl) if self.options.sslCACert: rhnreg.cfg.set("sslCACert", self.options.sslCACert) if not (self.options.activationkey or (self.options.username and self.options.password)): print _("A username and password are required "\ "to register a system.") sys.exit(-1) if rhnreg.registered() and not self.options.force: print _( "This system is already registered. Use --force to override") sys.exit(-1) rhnreg.getCaps() if not self.options.nopackages: getArch = 0 if rhnreg.cfg['supportsExtendedPackageProfile']: getArch = 1 packageList = pkgUtils.getInstalledPackageList(getArch=getArch) else: packageList = [] hardwareList = hardware.Hardware() if self.options.profilename: profilename = self.options.profilename else: profilename = RegisterKsCli.__generateProfileName(hardwareList) other = {} if self.options.systemorgid: other['org_id'] = self.options.systemorgid # Try to get the virt uuid and put it in "other". (virt_uuid, virt_type) = rhnreg.get_virt_info() if not virt_uuid is None: other['virt_uuid'] = virt_uuid other['virt_type'] = virt_type # If specified, send up the EUS channel label for subscription. if self.options.use_eus_channel: if self.options.activationkey: print _( "Usage of --use-eus-channel option with --activationkey is not supported. Please use username and password instead." ) sys.exit(-1) if not rhnreg.server_supports_eus(): print _( "The server you are registering against does not support EUS." ) sys.exit(-1) channels = rhnreg.getAvailableChannels(self.options.username, self.options.password) other['channel'] = channels['default_channel'] try: if self.options.activationkey: systemId = rhnreg.registerSystem( token=self.options.activationkey, profileName=profilename, other=other) else: systemId = rhnreg.registerSystem(self.options.username, self.options.password, profilename, other=other) except (up2dateErrors.AuthenticationTicketError, up2dateErrors.RhnUuidUniquenessError, up2dateErrors.CommunicationError, up2dateErrors.AuthenticationOrAccountCreationError), e: print "%s" % e.errmsg sys.exit(1) # collect hardware info, inluding hostname if not self.options.nohardware: rhnreg.sendHardware(systemId, hardwareList) if not self.options.nopackages: rhnreg.sendPackages(systemId, packageList) if self.options.contactinfo: print _( "Warning: --contactinfo option has been deprecated. Please login to the server web user Interface and update your contactinfo. " ) # write out the new id if isinstance(systemId, unicode): rhnreg.writeSystemId(unicode.encode(systemId, 'utf-8')) else: rhnreg.writeSystemId(systemId) # assume successful communication with server # remember to save the config options rhnreg.cfg.save() # Send virtualization information to the server. We must do this # *after* writing out the system id. if not self.options.novirtinfo: rhnreg.sendVirtInfo(systemId) # do this after writing out system id, bug #147513 if not self.options.norhnsd: rhnreg.startRhnsd() try: present, conf_changed = rhnreg.pluginEnable() if not present: sys.stderr.write( rhncli.utf8_encode( _("Warning: yum-rhn-plugin is not present, could not enable it." ))) except IOError, e: sys.stderr.write( rhncli.utf8_encode( _("Warning: Could not open /etc/yum/pluginconf.d/rhnplugin.conf\nyum-rhn-plugin is not enabled.\n" ) + e.errmsg))
def poll_hypervisor(): """ This function polls the hypervisor for information about the currently running set of domains. It returns a dictionary object that looks like the following: { uuid : { 'name' : '...', 'uuid' : '...', 'virt_type' : '...', 'memory_size' : '...', 'vcpus' : '...', 'state' : '...' }, ... } """ if not libvirt: return {} try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError: # virConnectOpen() failed sys.stderr.write( rhncli.utf8_encode( _("Warning: Could not retrieve virtualization information!\n\t" + "libvirtd service needs to be running.\n"))) conn = None if not conn: # No connection to hypervisor made return {} domainIDs = conn.listDomainsID() if not domainIDs: domainIDs = [] if len(domainIDs) == 0: domainIDs.extend(conn.listDefinedDomains()) state = {} for domainID in domainIDs: if type(domainID) == int: try: domain = conn.lookupByID(domainID) except libvirt.libvirtError: lve = sys.exc_info()[1] raise_with_tb( VirtualizationException( "Failed to obtain handle to domain %d: %s" % (domainID, repr(lve)), sys.exc_info()[2])) else: try: domain = conn.lookupByName(domainID) except libvirt.libvirtError: lve = sys.exc_info()[1] raise_with_tb( VirtualizationException( "Failed to obtain handle to domain %d: %s" % (domainID, repr(lve)), sys.exc_info()[2])) uuid = binascii.hexlify(domain.UUID()) # SEE: http://libvirt.org/html/libvirt-libvirt.html#virDomainInfo # for more info. domain_info = domain.info() # Set the virtualization type. We can tell if the domain is fully virt # by checking the domain's OSType() attribute. virt_type = VirtualizationType.PARA if is_fully_virt(domain): virt_type = VirtualizationType.FULLY # we need to filter out the small per/minute KB changes # that occur inside a vm. To do this we divide by 1024 to # drop our precision down to megabytes with an int then # back up to KB memory = int(domain_info[2] / 1024) memory = memory * 1024 properties = { PropertyType.NAME: domain.name(), PropertyType.UUID: uuid, PropertyType.TYPE: virt_type, PropertyType.MEMORY: str(memory), # current memory PropertyType.VCPUS: domain_info[3], PropertyType.STATE: VIRT_STATE_NAME_MAP[domain_info[0]] } state[uuid] = properties if state: _log_debug("Polled state: %s" % repr(state)) return state
svrChannels = rhnChannel.getChannelDetails() except up2dateErrors.NoSystemIdError as e: sys.stderr.write("%s\n" % e) sys.exit(42) except up2dateErrors.Error as e: sys.stderr.write("%s\n" % e) sys.exit(1) except: sys.exit(1) service_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] print("# Channels for service %s" % service_name) for channel in svrChannels: _sendback("") if channel['name']: _sendback("# Name: %s" % utf8_encode(channel['name'])) if channel['summary']: _sendback("# Summary: %s" % utf8_encode(channel['summary'])) if channel['description']: _sendback("# Description:") for line in [ line for line in channel['description'].split(os.linesep) ]: _sendback("# %s" % utf8_encode(line)) _sendback("#") if channel['type']: _sendback("# Type: %s" % utf8_encode(channel['type'])) if channel['version']: _sendback("# Version: %s" % utf8_encode(channel['version'])) if channel['arch']: _sendback("# Architecture: %s" % utf8_encode(channel['arch']))
def main(self): if self.options.serverUrl: rhnreg.cfg.set("serverURL", self.options.serverUrl) if self.options.sslCACert: rhnreg.cfg.set("sslCACert", self.options.sslCACert) if not (self.options.activationkey or (self.options.username and self.options.password)): print _("A username and password are required "\ "to register a system.") sys.exit(-1) if rhnreg.registered() and not self.options.force: print _( "This system is already registered. Use --force to override") sys.exit(-1) rhnreg.getCaps() if not self.options.nopackages: getArch = 0 if rhnreg.cfg['supportsExtendedPackageProfile']: getArch = 1 packageList = pkgUtils.getInstalledPackageList(getArch=getArch) else: packageList = [] hardwareList = hardware.Hardware() if self.options.profilename: profilename = self.options.profilename else: profilename = RegisterKsCli.__generateProfileName(hardwareList) other = {} if self.options.systemorgid: other['org_id'] = self.options.systemorgid # Try to get the virt uuid and put it in "other". (virt_uuid, virt_type) = rhnreg.get_virt_info() if not virt_uuid is None: other['virt_uuid'] = virt_uuid other['virt_type'] = virt_type # If specified, send up the EUS channel label for subscription. if self.options.use_eus_channel: if self.options.activationkey: print _( "Usage of --use-eus-channel option with --activationkey is not supported. Please use username and password instead." ) sys.exit(-1) if not rhnreg.server_supports_eus(): print _( "The server you are registering against does not support EUS." ) sys.exit(-1) channels = rhnreg.getAvailableChannels(self.options.username, self.options.password) other['channel'] = channels['default_channel'] try: systemId = rhnreg.registerSystem(self.options.username, self.options.password, profilename, self.options.activationkey, other) except (up2dateErrors.AuthenticationTicketError, up2dateErrors.RhnUuidUniquenessError, up2dateErrors.CommunicationError, up2dateErrors.AuthenticationOrAccountCreationError): e = sys.exc_info()[1] print "%s" % e.errmsg sys.exit(1) # collect hardware info, inluding hostname if not self.options.nohardware: rhnreg.sendHardware(systemId, hardwareList) if not self.options.nopackages: rhnreg.sendPackages(systemId, packageList) if self.options.contactinfo: print _( "Warning: --contactinfo option has been deprecated. Please login to the server web user Interface and update your contactinfo. " ) # write out the new id if isinstance(systemId, unicode): rhnreg.writeSystemId(unicode.encode(systemId, 'utf-8')) else: rhnreg.writeSystemId(systemId) # assume successful communication with server # remember to save the config options rhnreg.cfg.save() # Send virtualization information to the server. We must do this # *after* writing out the system id. if not self.options.novirtinfo: rhnreg.sendVirtInfo(systemId) # do this after writing out system id, bug #147513 if not self.options.norhnsd: rhnreg.startRhnsd() try: present, conf_changed = rhnreg.pluginEnable() if not present: sys.stderr.write( rhncli.utf8_encode( _("Warning: %s is not present, could not enable it.") % PM_PLUGIN_NAME)) except IOError: e = sys.exc_info()[1] sys.stderr.write( rhncli.utf8_encode( _("Warning: Could not open %s\n%s is not enabled.\n") % (PM_PLUGIN_CONF, PM_PLUGIN_NAME) + e.errmsg)) RegisterKsCli.__runRhnCheck(self.options.verbose)