def testConfigRuntimeStore(self): "Verify that values Config['value'] are set for runtime only and not saved" cfg = config.initUp2dateConfig(test_up2date) cfg['blippy12345'] = "wantafreehat?" cfg.save() # cfg is a fairly persistent singleton, blow it awy to get a new referece del config.cfg cfg2 = config.initUp2dateConfig(test_up2date) # if this returns a value, it means we saved the config file... assert cfg2['blippy12345'] == None
def get_config(): """send back a cross platform structure containing cfg info""" global _config if not _config: _config = config.initUp2dateConfig() return _config
def _rpc_call(self, function_name, params): get_server_obj = self.login() # Try a couple of times cfg = config.initUp2dateConfig() for i in range(cfg["networkRetries"]): try: ret = apply(getattr(get_server_obj, function_name), params) except rpclib.ProtocolError, e: # We have two codes to check: the HTTP error code, and the # combination (failtCode, faultString) encoded in the headers # of the request. http_error_code = e.errcode fault_code, fault_string = rpclib.reportError(e.headers) if http_error_code == 401 and fault_code == -34: # Login token expired get_server_obj = self.login(force=1) continue if http_error_code == 404 and fault_code == -17: # File not found self.extinctErrorYN = 1 return None log(-1, "ERROR: http error code :%s; fault code: %s; %s" % (http_error_code, fault_code, fault_string)) # XXX raise else: return ret
def get_up2date_config(self): if self._up2date_config is None: self._up2date_config = initUp2dateConfig() if not hasattr(self._up2date_config, '__getitem__'): # Old interface self._up2date_config = OldUp2dateConfig(self._up2date_config) return self._up2date_config
def _openSocketStream(self, method, params): """Wraps the gzipstream.GzipStream instantiation in a test block so we can open normally if stream is not gzipped.""" stream = None retryYN = 0 wait = 0.33 lastErrorMsg = '' cfg = config.initUp2dateConfig() for i in range(cfg['networkRetries']): server = self.getServer(retryYN) if server is None: log2(-1, 2, 'ERROR: server unable to initialize, attempt %s' % i, stream=sys.stderr) retryYN = 1 time.sleep(wait) continue func = getattr(server, method) try: stream = func(*params) return stream except rpclib.xmlrpclib.ProtocolError, e: p = tuple(['<the systemid>'] + list(params[1:])) lastErrorMsg = 'ERROR: server.%s%s: %s' % (method, p, e) log2(-1, 2, lastErrorMsg, stream=sys.stderr) retryYN = 1 time.sleep(wait) # do not reraise this exception! except (KeyboardInterrupt, SystemExit): raise
def _rpc_call(self, function_name, params): get_server_obj = self.login() # Try a couple of times fault_count = 0 expired_token = 0 cfg = config.initUp2dateConfig() while fault_count - expired_token < cfg['networkRetries']: try: ret = getattr(get_server_obj, function_name)(*params) except rpclib.xmlrpclib.ProtocolError: e = sys.exc_info()[1] # We have two codes to check: the HTTP error code, and the # combination (failtCode, faultString) encoded in the headers # of the request. http_error_code = e.errcode fault_code, fault_string = rpclib.reportError(e.headers) fault_count += 1 if http_error_code == 401 and fault_code == -34: # Login token expired get_server_obj = self.login(force=1) # allow exactly one respin for expired token expired_token = 1 continue if http_error_code == 404 and fault_code == -17: # File not found self.extinctErrorYN = 1 return None log(-1, 'ERROR: http error code :%s; fault code: %s; %s' % (http_error_code, fault_code, fault_string)) # XXX raise else: return ret raise Exception("Failed after multiple attempts!")
def __init__(self): UserDict.UserDict.__init__(self) self.missingCaps = {} #self.populate() # self.validate() self.neededCaps = neededCaps self.cfg = config.initUp2dateConfig()
def _read_rhn_proxy_settings(self): # Read and store rhn-setup's proxy settings, as they have been set # on the prior screen (which is owned by rhn-setup) up2date_cfg = config.initUp2dateConfig() cfg = rhsm.config.initConfig() if up2date_cfg['enableProxy']: proxy = up2date_cfg['httpProxy'] if proxy: # Remove any URI scheme provided proxy = remove_scheme(proxy) try: host, port = proxy.split(':') cfg.set('server', 'proxy_hostname', host) cfg.set('server', 'proxy_port', port) except ValueError: cfg.set('server', 'proxy_hostname', proxy) cfg.set('server', 'proxy_port', rhsm.config.DEFAULT_PROXY_PORT) if up2date_cfg['enableProxyAuth']: cfg.set('server', 'proxy_user', up2date_cfg['proxyUser']) cfg.set('server', 'proxy_password', up2date_cfg['proxyPassword']) else: cfg.set('server', 'proxy_hostname', '') cfg.set('server', 'proxy_port', '') cfg.set('server', 'proxy_user', '') cfg.set('server', 'proxy_password', '') cfg.save() self.backend.cp_provider.set_connection_info()
def getChannels(force=None, label_whitelist=None, timeout=None): """ return rhnChannelList containing list of channel we are subscribed to """ cfg = config.initUp2dateConfig() global selected_channels if not selected_channels and not force: selected_channels = rhnChannelList() s = rhnserver.RhnServer(timeout=timeout) if not up2dateAuth.getSystemId(): raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId")) up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId()) for chan in up2dateChannels: if label_whitelist and not chan['label'] in label_whitelist: continue channel = rhnChannel(type = 'up2date', url = config.getServerlURL()) for key in chan.keys(): if key == "last_modified": channel['version'] = chan['last_modified'] else: channel[key] = chan[key] selected_channels.addChannel(channel) if len(selected_channels.list) == 0: raise up2dateErrors.NoChannelsError(_("This system may not be updated until it is associated with a channel.")) return selected_channels
def __init__(self): self.cfg = config.initUp2dateConfig() self.xmlrpcServerUrl = self.cfg["serverURL"] refreshServerList = 0 if self.cfg["useNoSSLForPackages"]: self.httpServerUrls = self.cfg["noSSLServerURL"] refreshServerList = 1 else: self.httpServerUrls = self.cfg["serverURL"] if type(self.httpServerUrls) == type(""): self.httpServerUrls = [self.httpServerUrls] self.serverList = rpcServer.initServerList(self.httpServerUrls) # if the list of servers for packages and stuff is different, # refresh if refreshServerList: self.serverList.resetServerList(self.httpServerUrls) self.proxyUrl = None self.proxyUser = None self.proxyPassword = None if self.cfg["enableProxy"] and up2dateUtils.getProxySetting(): self.proxyUrl = up2dateUtils.getProxySetting() if self.cfg["enableProxyAuth"]: if self.cfg["proxyUser"] and self.cfg["proxyPassword"]: self.proxyPassword = self.cfg["proxyPassword"] self.proxyUser = self.cfg["proxyUser"]
def setUp(self): self.__setupData() import testutils testutils.setupConfig("8.0-workstation-i386-1") self.cfg = config.initUp2dateConfig(test_up2date) self.origversion = self.cfg["versionOverride"]
def __init__(self, options): self.rhncfg = initUp2dateConfig() self.rhsmcfg = config.Config(initConfig()) # Sometimes we need to send up the entire contents of the system id file # which is referred to in Satellite 5 nomenclature as a "certificate" # although it is not an X509 certificate. try: self.system_id_contents = open(self.rhncfg["systemIdPath"], 'r').read() except IOError: system_exit(os.EX_IOERR, _("Could not read legacy system id at %s") % self.rhncfg["systemIdPath"]) self.system_id = self.get_system_id(self.system_id_contents) self.proxy_host = None self.proxy_port = None self.proxy_user = None self.proxy_pass = None self.cp = None self.db = ProductDatabase() self.consumer_id = None self.options = options self.is_hosted = is_hosted()
def apply(self, interface, testing=False): if testing: return RESULT_SUCCESS up2DateConfig = config.initUp2dateConfig() up2DateConfig.save() return RESULT_SUCCESS
def _read_rhn_proxy_settings(self): if not rhn_config: return # Read and store rhn-setup's proxy settings, as they have been set # on the prior screen (which is owned by rhn-setup) up2date_cfg = rhn_config.initUp2dateConfig() cfg = rhsm.config.initConfig() if up2date_cfg["enableProxy"]: proxy = up2date_cfg["httpProxy"] if proxy: # Remove any URI scheme provided proxy = remove_scheme(proxy) try: host, port = proxy.split(":") cfg.set("server", "proxy_hostname", host) cfg.set("server", "proxy_port", port) except ValueError: cfg.set("server", "proxy_hostname", proxy) cfg.set("server", "proxy_port", rhsm.config.DEFAULT_PROXY_PORT) if up2date_cfg["enableProxyAuth"]: cfg.set("server", "proxy_user", up2date_cfg["proxyUser"]) cfg.set("server", "proxy_password", up2date_cfg["proxyPassword"]) else: cfg.set("server", "proxy_hostname", "") cfg.set("server", "proxy_port", "") cfg.set("server", "proxy_user", "") cfg.set("server", "proxy_password", "") cfg.save() self.backend.cp_provider.set_connection_info()
def apply(self, interface, testing=False): if testing: return RESULT_SUCCESS up2DateConfig = config.initUp2dateConfig() up2DateConfig.save() interface.moveToPage(pageNum = len(interface.moduleList)) return RESULT_JUMP
def __init__(self, proxyHost=None, loginInfo=None, cacheObject=None, register=None): self.cfg = config.initUp2dateConfig() rpmSource.PackageSource.__init__(self, cacheObject = cacheObject) self._loginInfo=loginInfo self.headerCache = cacheObject self.pkglists = {}
def rhn_username(self): try: cfg = config.initUp2dateConfig() return rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['username'] except: # ignore any exception and return an empty username return ""
def apply(self, *args): """Returns None to stay on the same page. Anything else will cause firstboot to advance but True is generally used. This is different from the gnome druid in rhn_register. """ up2DateConfig = config.initUp2dateConfig() up2DateConfig.save() return True
def setUp(self): self.defaultServer = testConfig.brokenServer500error import testutils testutils.setupConfig("fc1-at-pepsi") # cant import config until we put the right stuff in place self.cfg = config.initUp2dateConfig(test_up2date) self.cfg['serverURL'] = self.defaultServer
def getVersion(): ''' Returns the version of redhat-release rpm ''' cfg = config.initUp2dateConfig() if cfg["versionOverride"]: return str(cfg["versionOverride"]) os_release, version, release = _getOSVersionAndRelease() return version
def __setDebugLevel(level): cfg = config.initUp2dateConfig() # figure out the debug level cfg["debug"] = cfg["debug"] + level if cfg["debug"] > 2: # Set rpm's verbosity mode try: rpm.setVerbosity(rpm.RPMLOG_DEBUG) except AttributeError: print "extra verbosity not supported in this version of rpm"
def _init(): cfg = config.initUp2dateConfig() cfg_dict = dict(cfg.items()) server_url = config.getServerlURL() cfg_dict['proto'], cfg_dict['server_name'] = utils.parse_url(server_url[0], scheme="https")[:2] if len(server_url) > 1: cfg_dict['server_list'] = server_url local_config.init('rhncfg-client', defaults=cfg_dict) set_debug_level(int(local_config.get('debug_level') or 0)) set_logfile("/var/log/rhncfg-actions")
def __init__(self): yum.YumBase.__init__(self) self.cfg = config.initUp2dateConfig() self.doConfigSetup(debuglevel=self.cfg["debug"]) self.cache_only = None self.doTsSetup() self.doRpmDBSetup() self.doRepoSetup() self.doSackSetup()
def getSystemId(): cfg = config.initUp2dateConfig() path = cfg["systemIdPath"] if not os.access(path, os.R_OK): return None f = open(path, "r") ret = f.read() f.close() return ret
def get_available_channels(user, password): """ return list of available child channels """ cfg = config.initUp2dateConfig() satellite_url = config.getServerlURL()[0] scheme, netloc, path, query, fragment = urlparse.urlsplit(satellite_url) satellite_url = urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment)) client = xmlrpclib.Server(satellite_url, verbose=0) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def __init__(self, config, source, buildroot='', nc=None): JointDB.__init__(self, config, source, buildroot) self.comps = None self.reponame = "rhnrepo" if not use_rhn: return up2date_cfg = rhnconfig.initUp2dateConfig() try: login_info = up2dateAuth.getLoginInfo() except up2dateErrors.RhnServerException, e: raise IOError, "Failed to get login info from RHN Server."
def __init__(self, proxyHost=None, loginInfo=None, cacheObject=None): self.cfg = config.initUp2dateConfig() rpmSource.PackageSource.__init__(self, cacheObject = cacheObject) self.headerCache = cacheObject self.obsList = [] try: cmd = os.popen('uname -m') self._arch = cmd.read().strip('\n') except IOError: self._arch = 'unknown'
def _openSocketStream(self, method, params): """Wraps the gzipstream.GzipStream instantiation in a test block so we can open normally if stream is not gzipped.""" stream = None retryYN = 0 wait = 0.33 lastErrorMsg = '' cfg = config.initUp2dateConfig() for i in range(cfg['networkRetries']): server = self.getServer(retryYN) if server is None: log2(-1, 2, 'ERROR: server unable to initialize, attempt %s' % i, stream=sys.stderr) retryYN = 1 time.sleep(wait) continue func = getattr(server, method) try: stream = func(*params) if CFG.SYNC_TO_TEMP: import tempfile cached = tempfile.NamedTemporaryFile() stream.read_to_file(cached) cached.seek(0) return cached else: return stream except rpclib.xmlrpclib.ProtocolError: e = sys.exc_info()[1] p = tuple(['<the systemid>'] + list(params[1:])) lastErrorMsg = 'ERROR: server.%s%s: %s' % (method, p, e) log2(-1, 2, lastErrorMsg, stream=sys.stderr) retryYN = 1 time.sleep(wait) # do not reraise this exception! except (KeyboardInterrupt, SystemExit): raise except rpclib.xmlrpclib.Fault: e = sys.exc_info()[1] lastErrorMsg = e.faultString break except Exception: # pylint: disable=E0012, W0703 e = sys.exc_info()[1] p = tuple(['<the systemid>'] + list(params[1:])) lastErrorMsg = 'ERROR: server.%s%s: %s' % (method, p, e) log2(-1, 2, lastErrorMsg, stream=sys.stderr) break # do not reraise this exception! if lastErrorMsg: raise_with_tb(RhnSyncException(lastErrorMsg), sys.exc_info()[2]) # Returns a stream # Should never be reached return stream
def get_available_channels(user, password): """ return list of available child channels """ cfg = config.initUp2dateConfig() modified_servers = [] servers = config.getServerlURL() for server in servers: scheme, netloc, path, query, fragment = urlparse.urlsplit(server) modified_servers.append(urlparse.urlunsplit((scheme, netloc, "/rpc/api", query, fragment))) client = rhnserver.RhnServer(serverOverride=modified_servers) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def __init__(self, download_only=False): self.download_only = bool(download_only) self.cfg = config.initUp2dateConfig() if self.cfg['retrieveOnly']: log.log_me('Configured to "retrieveOnly"') self.download_only = True # dup_version == 2 support # * dup --no-allow-vendor-change # * patch --updatestack-only self.dup_version = 1 if 'distupgrade.upgrade' in clientCaps.caps.data: self.dup_version = int(clientCaps.caps.data['distupgrade.upgrade']['version'])
def testConfigRuntimeStoreNoDir(self): "Verify that saving a file into a non existent dir works" # bugzilla: 125179 cfg = config.initUp2dateConfig(test_up2date) cfg['blippy321'] = "blumblim" cfg.save()
def __init__(self): self.cfg = config.initUp2dateConfig() gladeFile = "/usr/share/rhn/up2date_client/gui.glade" self.xml = gtk.glade.XML(gladeFile, "mainWin", domain="rhn-client-tools") self.xml.signal_autoconnect({ "onMainWinCancel": self.onMainWinCancel, "onMainWinPrepare": self.onMainWinPrepare, "onMainWinApply": self.onMainWinApply, }) rhnregGui.StartPage.__init__(self) rhnregGui.ChooseServerPage.__init__(self) rhnregGui.LoginPage.__init__(self) rhnregGui.ChooseChannelPage.__init__(self) rhnregGui.CreateProfilePage.__init__(self) rhnregGui.ReviewSubscriptionPage.__init__(self) rhnregGui.ProvideCertificatePage.__init__(self) rhnregGui.FinishPage.__init__(self) # Pack all the pages into the empty druid screens contents = self.startPageVbox() container = self.xml.get_widget("startPageVbox") container.pack_start(contents, True, True, 0) contents = self.chooseServerPageVbox() container = self.xml.get_widget("chooseServerPageVbox") container.pack_start(contents, True, True, 0) contents = self.loginPageVbox() container = self.xml.get_widget("loginPageVbox") container.pack_start(contents, True, True, 0) contents = self.chooseChannelPageVbox() container = self.xml.get_widget("chooseChannelPageVbox") container.pack_start(contents, True, True, 0) self.chooseChannelPageVbox = container contents = self.createProfilePageVbox() container = self.xml.get_widget("createProfilePageVbox") container.pack_start(contents, True, True, 0) contents = self.reviewSubscriptionPageVbox() container = self.xml.get_widget("reviewSubscriptionPageVbox") container.pack_start(contents, True, True, 0) contents = self.provideCertificatePageVbox() container = self.xml.get_widget("provideCertificatePageVbox") container.pack_start(contents, True, True, 0) self.provideCertificatePageVbox = container contents = self.finishPageVbox() container = self.xml.get_widget("finishPageVbox") container.pack_start(contents, True, True, 0) self.initProfile = False self.oemInfo = {} self.productInfo = {} self.already_registered_already_shown = False self.rhsm_already_registered_already_shown = False self.mainWin = self.xml.get_widget("mainWin") self.mainWin.connect("delete-event", gtk.main_quit) self.mainWin.connect("hide", gtk.main_quit) self.mainWin.connect("close", gtk.main_quit) self.pages = dict([(getWidgetName(self.mainWin.get_nth_page(n)), n) for n in range(self.mainWin.get_n_pages())]) # Set up cursor changing functions. Overriding functions that aren't in # classes like this could be called a hack, but I think it's the best # we can do with the current overall setup and isn't too bad. def mySetBusyCursor(): setCursor(self.mainWin, gtk.CURSOR_WATCH) def mySetArrowCursor(): setCursor(self.mainWin, gtk.CURSOR_LEFT_PTR) rhnregGui.setBusyCursor = mySetBusyCursor rhnregGui.setArrowCursor = mySetArrowCursor self.mainWin.show_all() # GtkAssistant doesn't signal prepare to the first page when starting up self.onStartPagePrepare(None, None, manualPrepare=True)
def run(action_id, params, cache_only=None): cfg = config.initUp2dateConfig() local_config.init('rhncfg-client', defaults=dict(cfg.items())) tempfile.tempdir = local_config.get('script_tmp_dir') logfile_name = local_config.get('script_log_file') log_output = local_config.get('script_log_file_enable') if log_output: # If we're going to log, make sure we can create the logfile _create_path(logfile_name) if cache_only: return (0, "no-ops for caching", {}) action_type = 'script.run' if not _local_permission_check(action_type): return _perm_error(action_type) extras = {'output':''} script = params.get('script') if not script: return (1, "No script to execute", {}) username = params.get('username') groupname = params.get('groupname') if not username: return (1, "No username given to execute script as", {}) if not groupname: return (1, "No groupname given to execute script as", {}) timeout = params.get('timeout') if timeout: try: timeout = int(timeout) except ValueError: return (1, "Invalid timeout value", {}) else: timeout = None db_now = params.get('now') if not db_now: return (1, "'now' argument missing", {}) db_now = time.mktime(time.strptime(db_now, "%Y-%m-%d %H:%M:%S")) now = time.time() process_start = None process_end = None child_pid = None # determine uid/ugid for script ownership, uid also used for setuid... try: user_record = pwd.getpwnam(username) except KeyError: return 1, "No such user %s" % username, extras uid = user_record[2] ugid = user_record[3] # create the script on disk try: script_path = _create_script_file(script, uid=uid, gid=ugid) except OSError: e = sys.exc_info()[1] return 1, "Problem creating script file: %s" % e, extras # determine gid to run script as try: group_record = grp.getgrnam(groupname) except KeyError: return 1, "No such group %s" % groupname, extras run_as_gid = group_record[2] # create some pipes to communicate w/ the child process (pipe_read, pipe_write) = os.pipe() process_start = time.time() child_pid = os.fork() if not child_pid: # Parent doesn't write to child, so close that part os.close(pipe_read) # Redirect both stdout and stderr to the pipe os.dup2(pipe_write, sys.stdout.fileno()) os.dup2(pipe_write, sys.stderr.fileno()) # Close unnecessary file descriptors (including pipe since it's duped) for i in range(3, MAXFD): try: os.close(i) except: pass # all scripts initial working directory will be / # puts burden on script writer to ensure cwd is correct within the # script os.chdir('/') # the child process gets the desired uid/gid os.setgid(run_as_gid) groups=[g.gr_gid for g in grp.getgrall() if username in g.gr_mem or username in g.gr_name] os.setgroups(groups) os.setuid(uid) # give this its own process group (which happens to be equal to its # pid) os.setpgrp() # Finally, exec the script try: os.umask(int("022", 8)) os.execv(script_path, [script_path, ]) finally: # This code can be reached only when script_path can not be # executed as otherwise execv never returns. # (The umask syscall always succeeds.) os._exit(1) # Parent doesn't write to child, so close that part os.close(pipe_write) output = None timed_out = None out_stream = tempfile.TemporaryFile() while 1: select_wait = None if timeout: elapsed = time.time() - process_start if elapsed >= timeout: timed_out = 1 # Send TERM to all processes in the child's process group # Send KILL after that, just to make sure the child died os.kill(-child_pid, signal.SIGTERM) time.sleep(2) os.kill(-child_pid, signal.SIGKILL) break select_wait = timeout - elapsed # XXX try-except here for interrupted system calls input_fds, output_fds, error_fds = select.select([pipe_read], [], [], select_wait) if error_fds: # when would this happen? os.close(pipe_read) return 1, "Fatal exceptional case", extras if not (pipe_read in input_fds): # Read timed out, should be caught in the next loop continue output = os.read(pipe_read, 4096) if not output: # End of file from the child break out_stream.write(output) os.close(pipe_read) # wait for the child to complete (somepid, exit_status) = os.waitpid(child_pid, 0) process_end = time.time() # Copy the output from the temporary file out_stream.seek(0, 0) extras['output'] = out_stream.read() out_stream.close() # Log script-output locally, unless we're asked not to if log_output : set_logfile(logfile_name) log_to_file(0, extras['output']) # since output can contain chars that won't make xmlrpc very happy, # base64 encode it... extras['base64enc'] = 1 extras['output'] = base64.encodestring(extras['output']) extras['return_code'] = exit_status # calculate start and end times in db's timespace extras['process_start'] = db_now + (process_start - now) extras['process_end'] = db_now + (process_end - now) for key in ('process_start', 'process_end'): extras[key] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(extras[key])) # clean up the script os.unlink(script_path) if timed_out: return 1, "Script killed, timeout of %s seconds exceeded" % timeout, extras if exit_status == 0: return 0, "Script executed", extras return 1, "Script failed", extras
def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https':443, 'http':80} hostname = None intf = None intf6 = None etchostname = False sockethostname = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp sockethostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() # Warn if /etc/hostname contains more than one entry (bsc#929979) if len(hostnameinfo) > 1: log = up2dateLog.initLog() log.log_me("/etc/hostname contains more than one entry! Using first one.") if len(hostnameinfo): info = hostnameinfo[0] else: info = "" # ".site" is now an allowed TLD. Catch local installations by checking # for pseudo TLD ".suse" and require more than the domainname for ".site" # so "local.site" still can be identified as local installation (bsc#923990) if len(info): tmpval = info.strip().split('.') if not info.strip().endswith(".suse"): if not info.strip().endswith(".site") or len(tmpval) > 2: hostname = info.strip() etchostname = True # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access("/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue if vals[0].strip() == "HOSTNAME": # /etc/sysconfig/network is of shell syntax, # so values can be quoted hostname = ''.join(vals[1:]).strip('"\' \t\n') etchostname = False break # /etc/hostname doesn't contain a fully qualified hostname # try to find out the domain if etchostname and "." not in hostname: fqdn = socket.getfqdn(hostname) if "." in fqdn: domain = fqdn.split('.', 1)[1] aliasfqdn = "{0}.{1}".format(hostname, domain) try: socket.gethostbyname(aliasfqdn) hostname = aliasfqdn except socket.error: hostname = fqdn log = up2dateLog.initLog() log.log_me("Could not resolve /etc/hostname alias to {0}. Falling back to {1}".format(aliasfqdn, fqdn)) else: log = up2dateLog.initLog() log.log_me("Got an invalid FQDN {0} for /etc/hostname. Falling back to {1}".format(fqdn, sockethostname)) hostname = sockethostname if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6
class BaseMain: modes = [] repository_class_name = "Repository" plugins_dir = 'config_common' mode_prefix = None config_section = None def usage(self, exit_code): print "Usage: %s MODE [ --server-name name ] [ params ]" % sys.argv[0] print "Valid modes are:" for mode in self.modes: print "\t%s" % mode sys.exit(exit_code) def main(self): args = [] show_help = None debug_level = 3 mode = None dict_name_opt={'--server-name': None,'--password': None,'--username': None,} for index in range(1,len(sys.argv)): arg=sys.argv[index] param = filter(lambda x: x[1] == 0,dict_name_opt.iteritems()) if param: if arg.startswith('-') or arg in self.modes: # not perfect, but at least a little bit better print "Option %s requires an argument" % dict_name_opt[param[0][0]] return 1 dict_name_opt[param[0][0]] = arg continue if arg in ('--help', '-h'): show_help = 1 continue param = [s for s in dict_name_opt.keys() if arg.startswith(s)] if param: rarg = arg[len(param[0]):] if not rarg: dict_name_opt[param[0]] = 0 if index == len(sys.argv) - 1: print "Option %s requires an argument" % param[0] return 1 continue if rarg[0] == '=': if len(rarg) == 1: print "Option %s requires an argument" % param[0] return 1 dict_name_opt[param[0]] = rarg[1:] continue print "Unknown option %s" % arg return 1 if mode is None: # This should be the mode mode = arg if mode == '': # Bad self.usage(1) if mode[0] == '-': # Mode can't be an option self.usage(1) if mode not in self.modes: print "Unknown mode %s" % mode self.usage(1) continue args.append(arg) server_name = dict_name_opt['--server-name'] password = dict_name_opt['--password'] username = dict_name_opt['--username'] rhn_log.set_debug_level(debug_level) if mode is None: # No args were specified self.usage(0) execname = os.path.basename(sys.argv[0]) # Class names cannot have dot in them, so strip the extension execname = string.split(execname, '.', 1)[0] mode_module = string.replace(mode, '-', '_') module_name = "%s_%s" % (self.mode_prefix, mode_module) full_module_name = "%s.%s" % (self.plugins_dir, module_name) try: module = __import__(full_module_name) except ImportError, e: rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e)) module = getattr(module, module_name) if show_help: # Display the per-module help handler = module.Handler(args, None, mode=mode, exec_name=execname) handler.usage() return 0 cfg = config.initUp2dateConfig() up2date_cfg = dict(cfg.items()) if server_name: local_config.init(self.config_section, defaults=up2date_cfg, server_url="https://" + server_name) else: local_config.init(self.config_section, defaults=up2date_cfg) try: server_name = local_config.get('server_url') except InterpolationError, e: if e.option == 'server_url': server_name = config.getServerlURL() up2date_cfg['proto'] = urlsplit(server_name[0])[0] if up2date_cfg['proto'] == '': up2date_cfg['proto'] = 'https' up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[2], server_name) else: up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[1], server_name) server_name = (up2date_cfg['server_list'])[0] local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)
def setUp(self): from up2date_client import config self.cfg = config.initUp2dateConfig(test_up2date) self.function = up2dateUtils.getVersion
def setUp(self): self.cfg = config.initUp2dateConfig(test_up2date) self.defaultServer = self.cfg['serverURL']
def _get_config(): """send back a cross platform structure containing cfg info""" return config.initUp2dateConfig()
def run(action_id, params, cache_only=None): cfg = config.initUp2dateConfig() local_config.init('rhncfg-client', defaults=dict(cfg.items())) tempfile.tempdir = local_config.get('script_tmp_dir') logfile_name = local_config.get('script_log_file') log_output = local_config.get('script_log_file_enable') if log_output: # If we're going to log, make sure we can create the logfile _create_path(logfile_name) if cache_only: return (0, "no-ops for caching", {}) action_type = 'script.run' if not _local_permission_check(action_type): return _perm_error(action_type) extras = {'output': ''} script = params.get('script') if not script: return (1, "No script to execute", {}) username = params.get('username') groupname = params.get('groupname') if not username: return (1, "No username given to execute script as", {}) if not groupname: return (1, "No groupname given to execute script as", {}) timeout = params.get('timeout') if timeout: try: timeout = int(timeout) except ValueError: return (1, "Invalid timeout value", {}) else: timeout = None db_now = params.get('now') if not db_now: return (1, "'now' argument missing", {}) db_now = time.mktime(time.strptime(db_now, "%Y-%m-%d %H:%M:%S")) now = time.time() process_start = None process_end = None child_pid = None # determine uid/ugid for script ownership, uid also used for setuid... try: user_record = pwd.getpwnam(username) except KeyError: return 1, "No such user %s" % username, extras uid = user_record[2] ugid = user_record[3] # create the script on disk try: script_path = _create_script_file(script, uid=uid, gid=ugid) except OSError, e: return 1, "Problem creating script file: %s" % e, extras
def setUp(self): self.cfg = config.initUp2dateConfig(test_up2date) self.origssl = self.cfg['sslCACert']
def __init__(self): self.app = "up2date" self.cfg = config.initUp2dateConfig() self.log_info = ''
def doCall(method, *args, **kwargs): log = up2dateLog.initLog() log.log_debug("rpcServer: Calling XMLRPC %s" % method.__dict__['_Method__name']) cfg = config.initUp2dateConfig() ret = None attempt_count = 1 try: attempts = int(cfg["networkRetries"]) except ValueError: attempts = 1 if attempts <= 0: attempts = 1 while 1: failure = 0 ret = None try: ret = method(*args, **kwargs) except KeyboardInterrupt: raise_with_tb( up2dateErrors.CommunicationError( _("Connection aborted by the user"))) # if we get a socket error, keep tryingx2 except (socket.error, SSL.socket_error): log.log_me("A socket error occurred: %s, attempt #%s" % (sys.exc_info()[1], attempt_count)) if attempt_count >= attempts: e = sys.exc_info()[1] if len(e.args) > 1: raise_with_tb(up2dateErrors.CommunicationError(e.args[1])) else: raise_with_tb(up2dateErrors.CommunicationError(e.args[0])) else: failure = 1 except httplib.IncompleteRead: print("httplib.IncompleteRead") raise_with_tb( up2dateErrors.CommunicationError("httplib.IncompleteRead")) except urllib2.HTTPError: e = sys.exc_info()[1] msg = "\nAn HTTP error occurred:\n" msg = msg + "URL: %s\n" % e.filename msg = msg + "Status Code: %s\n" % e.code msg = msg + "Error Message: %s\n" % e.msg log.log_me(msg) raise_with_tb(up2dateErrors.CommunicationError(msg)) except xmlrpclib.ProtocolError: e = sys.exc_info()[1] log.log_me("A protocol error occurred: %s , attempt #%s," % (e.errmsg, attempt_count)) if e.errcode == 404: log.log_me("Could not find URL, %s" % (e.url)) log.log_me("Check server name and/or URL, then retry\n") (errCode, errMsg) = rpclib.reportError(e.headers) reset = 0 if abs(errCode) == 34: log.log_me("Auth token timeout occurred\n errmsg: %s" % errMsg) # this calls login, which in tern calls doCall (ie, # this function) but login should never get a 34, so # should be safe from recursion from up2date_client import up2dateAuth up2dateAuth.updateLoginInfo() # the servers are being throttle to pay users only, catch the # exceptions and display a nice error message if abs(errCode) == 51: log.log_me(_("Server has refused connection due to high load")) raise_with_tb(up2dateErrors.CommunicationError(e.errmsg)) # if we get a 404 from our server, thats pretty # fatal... no point in retrying over and over. Note that # errCode == 17 is specific to our servers, if the # serverURL is just pointing somewhere random they will # get a 0 for errcode and will raise a CommunicationError if abs(errCode) == 17: #in this case, the args are the package string, so lets try to # build a useful error message if type(args[0]) == type([]): pkg = args[0] else: pkg = args[1] if type(pkg) == type([]): pkgName = "%s-%s-%s.%s" % (pkg[0], pkg[1], pkg[2], pkg[4]) else: pkgName = pkg msg = "File Not Found: %s\n%s" % (pkgName, errMsg) log.log_me(msg) raise_with_tb(up2dateErrors.FileNotFoundError(msg)) if not reset: if attempt_count >= attempts: raise_with_tb(up2dateErrors.CommunicationError(e.errmsg)) else: failure = 1 except xmlrpclib.ResponseError: raise_with_tb( up2dateErrors.CommunicationError( "Broken response from the server.")) if ret != None: break else: failure = 1 if failure: # rest for five seconds before trying again time.sleep(5) attempt_count = attempt_count + 1 if attempt_count > attempts: raise up2dateErrors.CommunicationError( "The data returned from the server was incomplete") return ret
def __init__(self): self.cfg = config.initUp2dateConfig() gladeFile = "/usr/share/rhn/up2date_client/gui.glade" self.xml = gtk.glade.XML(gladeFile, "mainWin", domain="rhn-client-tools") self.xml.signal_autoconnect({ "onMainWinCancel": self.onMainWinCancel, "onMainWinPrepare": self.onMainWinPrepare, "onMainWinApply": self.onMainWinApply, }) rhnregGui.StartPage.__init__(self) rhnregGui.ChooseServerPage.__init__(self) rhnregGui.LoginPage.__init__(self) rhnregGui.ChooseChannelPage.__init__(self) rhnregGui.CreateProfilePage.__init__(self) rhnregGui.ReviewSubscriptionPage.__init__(self) rhnregGui.ProvideCertificatePage.__init__(self) rhnregGui.FinishPage.__init__(self) # Pack all the pages into the empty druid screens contents = self.startPageVbox() container = self.xml.get_widget("startPageVbox") container.pack_start(contents, True) contents = self.chooseServerPageVbox() container = self.xml.get_widget("chooseServerPageVbox") container.pack_start(contents, True) contents = self.loginPageVbox() container = self.xml.get_widget("loginPageVbox") container.pack_start(contents, True) contents = self.chooseChannelPageVbox() container = self.xml.get_widget("chooseChannelPageVbox") container.pack_start(contents, True) self.chooseChannelPageVbox = container contents = self.createProfilePageVbox() container = self.xml.get_widget("createProfilePageVbox") container.pack_start(contents, True) contents = self.reviewSubscriptionPageVbox() container = self.xml.get_widget("reviewSubscriptionPageVbox") container.pack_start(contents, True) contents = self.provideCertificatePageVbox() container = self.xml.get_widget("provideCertificatePageVbox") container.pack_start(contents, True) self.provideCertificatePageVbox = container contents = self.finishPageVbox() container = self.xml.get_widget("finishPageVbox") container.pack_start(contents, True) self.initProfile = False self.oemInfo = {} self.productInfo = {} self.already_registered_already_shown = False self.rhsm_already_registered_already_shown = False # self.druid = self.xml.get_widget("druid") self.mainWin = self.xml.get_widget("mainWin") self.mainWin.connect("delete-event", gtk.main_quit) self.mainWin.connect("hide", gtk.main_quit) self.mainWin.connect("close", gtk.main_quit) # # It's better to get widgets in advance so bugs don't hide in get_widget # # calls that only get executed periodically. # self.startPage = self.xml.get_widget("startPage") # self.chooseServerPage = self.xml.get_widget("chooseServerPage") # self.provideCertificatePage = self.xml.get_widget("provideCertificatePage") # self.loginPage = self.xml.get_widget("loginPage") # self.chooseChannelPage = self.xml.get_widget("chooseChannelPage") # self.createProfilePage = self.xml.get_widget("createProfilePage") # self.reviewSubscriptionPage = \ # self.xml.get_widget("reviewSubscriptionPage") # self.finishPage = self.xml.get_widget("finishPage") self.pages = { page.name: n for n, page in enumerate(self.mainWin.get_children()) } # Set up cursor changing functions. Overriding functions that aren't in # classes like this could be called a hack, but I think it's the best # we can do with the current overall setup and isn't too bad. def mySetBusyCursor(): cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.mainWin.window.set_cursor(cursor) while gtk.events_pending(): gtk.main_iteration(False) def mySetArrowCursor(): cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR) self.mainWin.window.set_cursor(cursor) while gtk.events_pending(): gtk.main_iteration(False) rhnregGui.setBusyCursor = mySetBusyCursor rhnregGui.setArrowCursor = mySetArrowCursor self.mainWin.show_all() # Druid doesn't signal prepare to the first page when starting up self.onStartPagePrepare(None, None, manualPrepare=True)
def getServer(refreshCallback=None, serverOverride=None, timeout=None): log = up2dateLog.initLog() cfg = config.initUp2dateConfig() # Where do we keep the CA certificate for RHNS? # The servers we're talking to need to have their certs # signed by one of these CA. ca = cfg["sslCACert"] if not isinstance(ca, list): ca = [ca] rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] if cfg["enableProxy"]: proxyHost = config.getProxySetting() else: proxyHost = None if not serverOverride: serverUrls = config.getServerlURL() else: serverUrls = serverOverride serverList = ServerList(serverUrls) proxyUser = None proxyPassword = None if cfg["enableProxyAuth"]: proxyUser = cfg["proxyUser"] or None proxyPassword = cfg["proxyPassword"] or None lang = None for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG': if env in os.environ: if not os.environ[env]: # sometimes unset continue lang = os.environ[env].split(':')[0] lang = lang.split('.')[0] break s = RetryServer(serverList.server(), refreshCallback=refreshCallback, proxy=proxyHost, username=proxyUser, password=proxyPassword, timeout=timeout) s.addServerList(serverList) s.add_header("X-Up2date-Version", up2dateUtils.version()) if lang: s.setlang(lang) # require RHNS-CA-CERT file to be able to authenticate the SSL connections need_ca = [ True for i in s.serverList.serverList if urlparse.urlparse(i)[0] == 'https' ] if need_ca: for rhns_ca_cert in rhns_ca_certs: if not os.access(rhns_ca_cert, os.R_OK): msg = "%s: %s" % (_("ERROR: can not find RHNS CA file"), rhns_ca_cert) log.log_me("%s" % msg) raise up2dateErrors.SSLCertificateFileNotFound(msg) # force the validation of the SSL cert s.add_trusted_cert(rhns_ca_cert) clientCaps.loadLocalCaps() # send up the capabality info headerlist = clientCaps.caps.headerFormat() for (headerName, value) in headerlist: s.add_header(headerName, value) return s
def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https': 443, 'http': 80} hostname = None intf = None intf6 = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() for info in hostnameinfo: if not len(info): continue hostname = info.strip() # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access( "/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue strippedstring = vals[0].strip() vals[0] = strippedstring if vals[0] == "HOSTNAME": hostname = ''.join(vals[1:]).strip() break if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6
def setUp(self): self.__setupData() self.cfg = config.initUp2dateConfig(test_up2date) self.sysid = self.cfg['systemIdPath']
def Hardware(): if using_gudev: allhw = get_devices() else: hal_status, dbus_status = check_hal_dbus_status() hwdaemon = 1 if hal_status or dbus_status: # if status != 0 haldaemon or messagebus service not running. # set flag and dont try probing hardware and DMI info # and warn the user. log = up2dateLog.initLog() msg = "Warning: haldaemon or messagebus service not running. Cannot probe hardware and DMI information.\n" log.log_me(msg) hwdaemon = 0 allhw = [] if hwdaemon: try: ret = read_hal() if ret: allhw = ret except: # bz253596 : Logging Dbus Error messages instead of printing on stdout log = up2dateLog.initLog() msg = "Error reading hardware information: %s\n" % (sys.exc_info()[0]) log.log_me(msg) # all others return individual arrays # cpu info try: ret = read_cpuinfo() if ret: allhw.append(ret) except: print(_("Error reading cpu information:"), sys.exc_info()[0]) # memory size info try: ret = read_memory() if ret: allhw.append(ret) except: print(_("Error reading system memory information:"), sys.exc_info()[0]) cfg = config.initUp2dateConfig() if not cfg["skipNetwork"]: # minimal networking info try: ret = read_network() if ret: allhw.append(ret) except: print(_("Error reading networking information:"), sys.exc_info()[0]) # dont like catchall exceptions but theres not # really anything useful we could do at this point # and its been trouble prone enough # minimal DMI info try: ret = read_dmi() if ret: allhw.append(ret) except: # bz253596 : Logging Dbus Error messages instead of printing on stdout log = up2dateLog.initLog() msg = "Error reading DMI information: %s\n" % (sys.exc_info()[0]) log.log_me(msg) try: ret = read_installinfo() if ret: allhw.append(ret) except: print(_("Error reading install method information:"), sys.exc_info()[0]) if not cfg["skipNetwork"]: try: ret = read_network_interfaces() if ret: allhw.append(ret) except: print(_("Error reading network interface information:"), sys.exc_info()[0]) if not cfg["skipNetwork"]: try: ret = read_all_fqdns() if ret: allhw.append(ret) except: print(_("Error reading network FQDNs information:"), sys.exc_info()[0]) try: ret = get_sysinfo() if ret: allhw.append(ret) except: print(_("Error reading system info:"), sys.exc_info()[0]) try: ret = read_machineinfo() if ret: allhw.append(ret) except: print(_("Error reading machine info:"), sys.exc_info()[0]) # all Done. return allhw
def setUp(self): self.__setupData() import testutils testutils.setupConfig("8.0-workstation-i386-1") self.cfg = config.initUp2dateConfig(test_up2date) self.origversion = self.cfg['versionOverride']
def main(): """ 0 success 1 general 2 proxy_invalid_systemid 4 proxy_no_management_entitlements 5 proxy_no_enterprise_entitlements 6 proxy_no_channel_entitlements 7 proxy_no_proxy_child_channel 8 proxy_not_activated 10 connection issues? 11 hostname unresolvable 12 connection refused 13 SSL connection failed 44 host not found 47 http proxy authentication failure """ cfg = config.initUp2dateConfig() options = processCommandline(cfg) if options.list_available_versions: resolveHostnamePort(options.http_proxy) if not options.http_proxy: resolveHostnamePort(options.server) listAvailableProxyChannels(options, cfg) sys.exit(0) noSslString = 'false' if options.no_ssl: noSslString = 'true' if not options.non_interactive: print("\n" "--server (RHN parent): %s\n" "--http-proxy: %s\n" "--http-proxy-username: %s\n" "--http-proxy-password: %s\n" "--ca-cert: %s\n" "--no-ssl: %s\n" "--version: %s\n" % (options.server, options.http_proxy, options.http_proxy_username, options.http_proxy_password, options.ca_cert, noSslString, options.version)) if not yn("Are you sure about these options? y/n: "): return 0 # early checks resolveHostnamePort(options.http_proxy) if not options.http_proxy: resolveHostnamePort(options.server) if options.deactivate: _deactivateProxy_api_v3_x(options, cfg) else: # ACTIVATE!!!!!!!! activateProxy(options, cfg) return 0
def get_server_url(self): cfg = initUp2dateConfig() return cfg['serverURL']
def testConfigKeys(self): "Verify that Config.keys() returns a list with the right stuff" cfg = config.initUp2dateConfig(test_up2date) blip = cfg.keys() assert "enableProxy" in blip
def __init__(self, cacheObject=None): self.cfg = config.initUp2dateConfig() rpmSource.PackageSource.__init__(self, cacheObject=cacheObject)
def testConfigKeysReturnsAList(self): "Verify that Config.keys() returns a list" cfg = config.initUp2dateConfig(test_up2date) blip = cfg.keys() assert type(blip) == type([])
def saveConfig(self): """ Saves the current up2date configuration being used to disk. """ cfg = config.initUp2dateConfig() cfg.save()
def testConfigInfo(self): "Verify that Config.into() runs without error" cfg = config.initUp2dateConfig(test_up2date) blargh = cfg.info('enableProxy')
def __setDebugLevel(level): cfg = config.initUp2dateConfig() # figure out the debug level cfg["debug"] = cfg["debug"] + level if cfg["debug"] > 2: pkgUtils.setDebugVerbosity()
def testConfigSetItem(self): "Verify that Config.__setitem__ works" cfg = config.initUp2dateConfig(test_up2date) cfg['blippyfoobarbazblargh'] = 1 assert cfg['blippyfoobarbazblargh'] == 1
from rhn import SSL from rhn import rhnLockfile from rhn.i18n import bstr, sstr from rhn.tb import raise_with_tb try: # python2 import xmlrpclib except ImportError: # python3 import xmlrpc.client as xmlrpclib long = int if 'sgmlop' in sys.modules: del sys.modules['sgmlop'] cfg = config.initUp2dateConfig() log = up2dateLog.initLog() # action version we understand ACTION_VERSION = 2 # lock file to check if we're disabled at the server's request DISABLE_FILE = "/etc/sysconfig/rhn/disable" # Actions that will run each time we execute. LOCAL_ACTIONS = [("packages.checkNeedUpdate", ("rhnsd=1", ))] class CheckCli(rhncli.RhnCli): def __init__(self): super(CheckCli, self).__init__()
def get_up2date_config(self): if self._up2date_config is None: self._up2date_config = initUp2dateConfig() return self._up2date_config
def main(self): args = [] show_help = None debug_level = 3 mode = None dict_name_opt = { '--server-name': None, '--password': None, '--username': None, '--config': None, } for index in range(1, len(sys.argv)): arg = sys.argv[index] param = [x for x in dict_name_opt.items() if x[1] == 0] if param: if arg.startswith('-') or arg in self.modes: # not perfect, but at least a little bit better print("Option %s requires an argument" % dict_name_opt[param[0][0]]) return 1 dict_name_opt[param[0][0]] = arg continue if arg in ('--help', '-h'): show_help = 1 continue param = [s for s in dict_name_opt.keys() if arg.startswith(s)] if param: rarg = arg[len(param[0]):] if not rarg: dict_name_opt[param[0]] = 0 if index == len(sys.argv) - 1: print("Option %s requires an argument" % param[0]) return 1 continue if rarg[0] == '=': if len(rarg) == 1: print("Option %s requires an argument" % param[0]) return 1 dict_name_opt[param[0]] = rarg[1:] continue print("Unknown option %s" % arg) return 1 if mode is None: # This should be the mode mode = arg if mode == '': # Bad self.usage(1) if mode[0] == '-': # Mode can't be an option self.usage(1) if mode not in self.modes: print("Unknown mode %s" % mode) self.usage(1) continue args.append(arg) server_name = dict_name_opt['--server-name'] password = dict_name_opt['--password'] username = dict_name_opt['--username'] config_file_override = dict_name_opt['--config'] if config_file_override and not os.path.isfile(config_file_override): rhn_log.die(1, "Config file %s does not exist.", config_file_override) rhn_log.set_debug_level(debug_level) if mode is None: # No args were specified self.usage(0) execname = os.path.basename(sys.argv[0]) # Class names cannot have dot in them, so strip the extension execname = execname.split('.', 1)[0] mode_module = mode.replace('-', '_') module_name = "%s_%s" % (self.mode_prefix, mode_module) full_module_name = "%s.%s" % (self.plugins_dir, module_name) try: module = __import__(full_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e)) module = getattr(module, module_name) if show_help: # Display the per-module help handler = module.Handler(args, None, mode=mode, exec_name=execname) handler.usage() return 0 cfg = config.initUp2dateConfig() up2date_cfg = dict(cfg.items()) if server_name: local_config.init(self.config_section, defaults=up2date_cfg, config_file_override=config_file_override, server_url="https://" + server_name) else: local_config.init(self.config_section, defaults=up2date_cfg, config_file_override=config_file_override) try: server_name = local_config.get('server_url') except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': server_name = config.getServerlURL() up2date_cfg['proto'] = urlsplit(server_name[0])[0] if up2date_cfg['proto'] == '': up2date_cfg['proto'] = 'https' up2date_cfg['server_list'] = [ urlsplit(x)[2] for x in server_name ] else: up2date_cfg['server_list'] = [ urlsplit(x)[1] for x in server_name ] server_name = (up2date_cfg['server_list'])[0] local_config.init( self.config_section, defaults=up2date_cfg, config_file_override=config_file_override, server_name=server_name) print("Using server name %s" % server_name) # set the debug level through the config rhn_log.set_debug_level(int(local_config.get('debug_level') or 0)) rhn_log.set_logfile(local_config.get('logfile') or "/var/log/rhncfg") # Multi-level import - __import__("foo.bar") does not return the bar # module, but the foo module with bar loaded # XXX Error checking repo_class = local_config.get('repository_type') if repo_class is None: rhn_log.die( 1, "repository_type not set (missing configuration file?)") repo_module_name = "%s.%s" % (self.plugins_dir, repo_class) try: repo_module = __import__(repo_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load repository module: %s" % e) try: repo_module = getattr(repo_module, repo_class) except AttributeError: rhn_log.die(1, "Malformed repository module") try: repo = getattr(repo_module, self.repository_class_name)() except AttributeError: rhn_log.die(1, "Missing repository class") except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': #pkilambi: bug#179367# backtic is replaced with single quote rhn_log.die( 1, "Missing 'server_url' configuration variable; please refer to the config file" ) raise except cfg_exceptions.ConfigurationError: e = sys.exc_info()[1] rhn_log.die(e) except gaierror: e = sys.exc_info()[1] print("Socket Error: %s" % (e.args[1], )) sys.exit(1) handler = module.Handler(args, repo, mode=mode, exec_name=execname) try: try: handler.authenticate(username, password) handler.run() except cfg_exceptions.AuthenticationError: e = sys.exc_info()[1] rhn_log.die(1, "Authentication failed: %s" % e) except Exception: raise finally: repo.cleanup() return 0