def __query_future_actions(self, time_window): try: actions = self.server.queue.get_future_actions(up2dateAuth.getSystemId(), time_window) return actions except xmlrpclib.Fault: f = sys.exc_info()[1] if f.faultCode == -31: raise_with_tb(up2dateErrors.InsuffMgmntEntsError(f.faultString)) else: print("Could not retrieve action item from server %s" % self.server) print("Error code: %d%s" % (f.faultCode, f.faultString)) sys.exit(-1) # XXX: what if no SSL in socket? except SSL.socket_error: print("ERROR: SSL handshake to %s failed" % self.server) print(""" This could signal that you are *NOT* talking to a server whose certificate was signed by a Certificate Authority listed in the %s file or that the RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert) sys.exit(-1) except socket.error: print("Could not retrieve action from %s.\n"\ "Possible networking problem?" % str(self.server)) sys.exit(-1) except up2dateErrors.ServerCapabilityError: print(sys.exc_info()[1]) sys.exit(1) except SSL.Error: print("ERROR: SSL errors detected") print("%s" % sys.exc_info()[1]) sys.exit(-1)
def __query_future_actions(self, time_window): try: actions = self.server.queue.get_future_actions( up2dateAuth.getSystemId(), time_window) return actions except xmlrpclib.Fault: f = sys.exc_info()[1] if f.faultCode == -31: raise_with_tb(up2dateErrors.InsuffMgmntEntsError( f.faultString)) else: print("Could not retrieve action item from server %s" % self.server) print("Error code: %d%s" % (f.faultCode, f.faultString)) sys.exit(-1) # XXX: what if no SSL in socket? except SSL.socket_error: print("ERROR: SSL handshake to %s failed" % self.server) print(""" This could signal that you are *NOT* talking to a server whose certificate was signed by a Certificate Authority listed in the %s file or that the RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert) sys.exit(-1) except socket.error: print("Could not retrieve action from %s.\n"\ "Possible networking problem?" % str(self.server)) sys.exit(-1) except up2dateErrors.ServerCapabilityError: print(sys.exc_info()[1]) sys.exit(1) except SSL.Error: print("ERROR: SSL errors detected") print("%s" % sys.exc_info()[1]) sys.exit(-1)
def getMethod(methodName, baseClass): #""" #Retreive method given methodName, path to base of tree, and class/module #route/label. #""" # First split the method name methodNameComps = baseClass.split('.') + methodName.split('.') # Sanity checks sanity(methodNameComps) # Look for the module, start with the most specific for index in range(len(methodNameComps), 0, -1): modulename = '.'.join(methodNameComps[:index]) try: actions = __import__(modulename) except ImportError: # does not exist, try next one continue except Exception: raise_with_tb(GetMethodException("Could not import module %s" % modulename)) # found one, skip the rest break else: # no module found. die raise GetMethodException("Action %s could not be imported" % methodName) # The position of the file fIndex = index className = actions # Iterate through the list of components and try to load that specific # module/method for index in range(1, len(methodNameComps)): comp = methodNameComps[index] if index < fIndex: # This is a directory or a file we have to load if not hasattr(className, comp): # Hmmm... Not there raise GetMethodException("Class %s has no attribute %s" % ( '.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) #print(type(className)) continue # A file or method # We look for the special __rhnexport__ array if not hasattr(className, '__rhnexport__'): raise GetMethodException("Class %s is not RHN-compliant" % \ '.'.join(methodNameComps[:index])) export = getattr(className, '__rhnexport__') if comp not in export: raise GetMethodException("Class %s does not export '%s'" % ( '.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) if type(className) is ClassType: # Try to instantiate it className = className() #print(type(className)) return className
def _request1(self, methodname, params): self.log = up2dateLog.initLog() while 1: try: ret = self._request(methodname, params) except rpclib.InvalidRedirectionError: raise except xmlrpclib.Fault: raise except httplib.BadStatusLine: self.log.log_me("Error: Server Unavailable. Please try later.") stdoutMsgCallback( _("Error: Server Unavailable. Please try later.")) sys.exit(-1) except: server = self.serverList.next() if server == None: # since just because we failed, the server list could # change (aka, firstboot, they get an option to reset the # the server configuration) so reset the serverList self.serverList.resetServerIndex() raise msg = "An error occurred talking to %s:\n" % self._host msg = msg + "%s\n%s\n" % (sys.exc_info()[0], sys.exc_info()[1]) msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server( ) self.log.log_me(msg) # try a different url # use the next serverURL parse_res = urlparse.urlsplit(self.serverList.server()) typ = parse_res[0] # scheme self._host = parse_res[1] # netloc self._handler = parse_res[2] # path typ = typ.lower() if typ not in ("http", "https"): raise_with_tb( rpclib.InvalidRedirectionError( "Redirected to unsupported protocol %s" % typ)) self._orig_handler = self._handler self._type = typ self._uri = self.serverList.server() if not self._handler: self._handler = "/RPC2" self._allow_redirect = 1 continue # if we get this far, we succedded break return ret
def _request1(self, methodname, params): self.log = up2dateLog.initLog() while 1: try: ret = self._request(methodname, params) except rpclib.InvalidRedirectionError: raise except xmlrpclib.Fault: raise except httplib.BadStatusLine: self.log.log_me("Error: Server Unavailable. Please try later.") stdoutMsgCallback( _("Error: Server Unavailable. Please try later.")) sys.exit(-1) except: server = self.serverList.next() if server == None: # since just because we failed, the server list could # change (aka, firstboot, they get an option to reset the # the server configuration) so reset the serverList self.serverList.resetServerIndex() raise msg = "An error occurred talking to %s:\n" % self._host msg = msg + "%s\n%s\n" % (sys.exc_info()[0], sys.exc_info()[1]) msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server() self.log.log_me(msg) # try a different url # use the next serverURL parse_res = urlparse.urlsplit(self.serverList.server()) typ = parse_res.scheme self._host = parse_res.netloc self._handler = parse_res.path typ = typ.lower() if typ not in ("http", "https"): raise_with_tb(rpclib.InvalidRedirectionError( "Redirected to unsupported protocol %s" % typ)) self._orig_handler = self._handler self._type = typ self._uri = self.serverList.server() if not self._handler: self._handler = "/RPC2" self._allow_redirect = 1 continue # if we get this far, we succedded break return ret
def getAvailableChannels(username, password): s = rhnserver.RhnServer() server_arch = up2dateUtils.getArch() server_version = up2dateUtils.getVersion() server_release = up2dateUtils.getRelease() availableChannels = None try: availableChannels = s.registration.available_eus_channels( username, password, server_arch, server_version, server_release) except xmlrpclib.Fault: f = sys.exc_info()[1] if f.faultCode == 99: raise_with_tb(up2dateErrors.DelayError(f.faultString)) else: raise return availableChannels
def getAvailableChannels(username, password): s = rhnserver.RhnServer() server_arch = up2dateUtils.getArch() server_version = up2dateUtils.getVersion() server_release = up2dateUtils.getRelease() availableChannels = None try: availableChannels = s.registration.available_eus_channels( username, password, server_arch, server_version, server_release ) except xmlrpclib.Fault: f = sys.exc_info()[1] if f.faultCode == 99: raise_with_tb(up2dateErrors.DelayError(f.faultString)) else: raise return availableChannels
def __call__(self, *args, **kwargs): """ Call the method. Catch faults and translate them. """ method = getattr(self._server, self._method_name) try: return rpcServer.doCall(method, *args, **kwargs) except xmlrpclib.Fault: raise_with_tb(self.__exception_from_fault(sys.exc_info()[1])) except OpenSSL.SSL.Error: # TODO This should probably be moved to rhnlib and raise an # exception that subclasses OpenSSL.SSL.Error # TODO Is there a better way to detect cert failures? error = str(sys.exc_info()[1]) error = error.strip("[()]") pieces = error.split(',') message = "" if len(pieces) > 2: message = pieces[2] elif len(pieces) == 2: message = pieces[1] message = message.strip(" '") if message == 'certificate verify failed': raise_with_tb(up2dateErrors.SSLCertificateVerifyFailedError()) else: raise_with_tb(up2dateErrors.NetworkError(message))
def getOemInfo(): configFile = cfg["oemInfoFile"] or "/etc/sysconfig/rhn/oeminfo" if not os.access(configFile, os.R_OK): return {} fd = open(configFile, "r") L = fd.readlines() info = {} for i in L: i = i.strip() if i == "": continue try: (key, value) = i.split(':') except ValueError: raise_with_tb(up2dateErrors.OemInfoFileError(i)) info[key] = value.strip() return info
def getMethod(methodName, abspath, baseClass): #""" #Retreive method given methodName, path to base of tree, and class/module #route/label. #""" # First split the method name methodNameComps = baseClass.split('.') + methodName.split('.') # Sanity checks sanity(methodNameComps) # Build the path to the file path = abspath for index in range(len(methodNameComps)): comp = methodNameComps[index] path = "%s/%s" % (path, comp) # If this is a directory, fine... if os.path.isdir(path): # Okay, go on continue # Try to load this as a file for extension in ['py', 'pyc', 'pyo']: if os.path.isfile("%s.%s" % (path, extension)): # Yes, this is a file break else: # No dir and no file. Die raise GetMethodException("Action %s could not be found" % methodName) break else: # Only directories. This can't happen raise GetMethodException("Very wrong") # The position of the file fIndex = index + 1 # Now build the module name modulename = '.'.join(methodNameComps[:fIndex]) # And try to import it try: actions = __import__(modulename) except ImportError: raise_with_tb(GetMethodException("Could not import module %s" % modulename)) className = actions # Iterate through the list of components and try to load that specific # module/method for index in range(1, len(methodNameComps)): comp = methodNameComps[index] if index < fIndex: # This is a directory or a file we have to load if not hasattr(className, comp): # Hmmm... Not there raise GetMethodException("Class %s has no attribute %s" % ( '.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) #print(type(className)) continue # A file or method # We look for the special __rhnexport__ array if not hasattr(className, '__rhnexport__'): raise GetMethodException("Class %s is not RHN-compliant" % \ '.'.join(methodNameComps[:index])) export = getattr(className, '__rhnexport__') if comp not in export: raise GetMethodException("Class %s does not export '%s'" % ( '.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) if type(className) is ClassType: # Try to instantiate it className = className() #print(type(className)) return className
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 getMethod(methodName, abspath, baseClass): #""" #Retreive method given methodName, path to base of tree, and class/module #route/label. #""" # First split the method name methodNameComps = baseClass.split('.') + methodName.split('.') # Sanity checks sanity(methodNameComps) # Build the path to the file path = abspath for index in range(len(methodNameComps)): comp = methodNameComps[index] path = "%s/%s" % (path, comp) # If this is a directory, fine... if os.path.isdir(path): # Okay, go on continue # Try to load this as a file for extension in ['py', 'pyc', 'pyo']: if os.path.isfile("%s.%s" % (path, extension)): # Yes, this is a file break else: # No dir and no file. Die raise GetMethodException("Action %s could not be found" % methodName) break else: # Only directories. This can't happen raise GetMethodException("Very wrong") # The position of the file fIndex = index + 1 # Now build the module name modulename = '.'.join(methodNameComps[:fIndex]) # And try to import it try: actions = __import__(modulename) except ImportError: raise_with_tb( GetMethodException("Could not import module %s" % modulename)) className = actions # Iterate through the list of components and try to load that specific # module/method for index in range(1, len(methodNameComps)): comp = methodNameComps[index] if index < fIndex: # This is a directory or a file we have to load if not hasattr(className, comp): # Hmmm... Not there raise GetMethodException( "Class %s has no attribute %s" % ('.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) #print(type(className)) continue # A file or method # We look for the special __rhnexport__ array if not hasattr(className, '__rhnexport__'): raise GetMethodException("Class %s is not RHN-compliant" % \ '.'.join(methodNameComps[:index])) export = getattr(className, '__rhnexport__') if comp not in export: raise GetMethodException("Class %s does not export '%s'" % ('.'.join(methodNameComps[:index]), comp)) className = getattr(className, comp) if type(className) is ClassType: # Try to instantiate it className = className() #print(type(className)) return className
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