Example #1
0
def _initialize_dmi_data():
    """ Initialize _dmi_data unless it already exist and returns it """
    global _dmi_data, _dmi_not_available
    if _dmi_data is None:
        if _dmi_not_available:
            # do not try to initialize it again and again if not available
            return None
        else:
            dmixml = dmidecode.dmidecodeXML()
            dmixml.SetResultType(dmidecode.DMIXML_DOC)
            # Get all the DMI data and prepare a XPath context
            try:
                data = dmixml.QuerySection('all')
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                    log = up2dateLog.initLog()
                    log.log_debug("dmidecode warnings: " % dmi_warn)
            except:
                # DMI decode FAIL, this can happend e.g in PV guest
                _dmi_not_available = 1
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                return None
            _dmi_data = data.xpathNewContext()
    return _dmi_data
Example #2
0
def writeCachedLogin():
    """
    Pickle loginInfo to a file
    Returns:
    True    -- wrote loginInfo to a pickle file
    False   -- did _not_ write loginInfo to a pickle file
    """
    log = up2dateLog.initLog()
    log.log_debug("writeCachedLogin() invoked")
    if not loginInfo:
        log.log_debug("writeCachedLogin() loginInfo is None, so bailing.")
        return False
    data = {'time': time.time(),
            'loginInfo': loginInfo}

    pcklDir = os.path.dirname(pcklAuthFileName)
    if not os.access(pcklDir, os.W_OK):
        try:
            os.mkdir(pcklDir)
            os.chmod(pcklDir, 0700)
        except:
            log.log_me("Unable to write pickled loginInfo to %s" % pcklDir)
            return False
    pcklAuth = open(pcklAuthFileName, 'wb')
    os.chmod(pcklAuthFileName, 0600)
    pickle.dump(data, pcklAuth)
    pcklAuth.close()
    expireTime = data['time'] + float(loginInfo['X-RHN-Auth-Expire-Offset'])
    log.log_debug("Wrote pickled loginInfo at ", data['time'], " with expiration of ",
            expireTime, " seconds.")
    return True
Example #3
0
def readCachedLogin():
    """
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    """
    log = up2dateLog.initLog()
    log.log_debug("readCachedLogin invoked")
    if not os.access(pcklAuthFileName, os.R_OK):
        log.log_debug("Unable to read pickled loginInfo at: %s" % pcklAuthFileName)
        return False
    pcklAuth = open(pcklAuthFileName, 'rb')
    try:
        data = pickle.load(pcklAuth)
    except EOFError:
        log.log_debug("Unexpected EOF. Probably an empty file, \
                       regenerate auth file")
        pcklAuth.close()
        return False
    pcklAuth.close()
    createdTime = data['time']
    li = data['loginInfo']
    currentTime = time.time()
    expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset'])
    #Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset"
    log.log_debug("Checking pickled loginInfo, currentTime=", currentTime,
            ", createTime=", createdTime, ", expire-offset=",
            float(li['X-RHN-Auth-Expire-Offset']))
    if (currentTime > expireTime):
        log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \
                %(createdTime, expireTime))
        return False
    _updateLoginInfo(li)
    log.log_debug("readCachedLogin(): using pickled loginInfo set to expire at ", expireTime)
    return True
Example #4
0
 def __init__(self, cacheObject = None):
     # this is the cache, stuff here is only in storageDir
     self.cfg = config.initUp2dateConfig()
     self.log = up2dateLog.initLog()
     self.dir_list = [self.cfg["storageDir"]]
     self.ts =  transaction.initReadOnlyTransaction()
     PackageSource.__init__(self, cacheObject = cacheObject)
Example #5
0
def doCall(method, *args, **kwargs):
    log = up2dateLog.initLog()
    cfg = config.initUp2dateConfig()
    ret = None

    attempt_count = 1
    attempts = cfg["networkRetries"] or 5

    while 1:
        failure = 0
        ret = None        
        try:
            ret = apply(method, args, kwargs)
        except KeyboardInterrupt:
            raise up2dateErrors.CommunicationError(
                "Connection aborted by the user")
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror), e:
            log.log_me("A socket error occurred: %s, attempt #%s" % (
                e, attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise up2dateErrors.CommunicationError(e.args[1])
                else:
                    raise up2dateErrors.CommunicationError(e.args[0])
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead" 
            raise up2dateErrors.CommunicationError("httplib.IncompleteRead")
Example #6
0
def login(systemId=None):
    server = rpcServer.getServer()
    log = up2dateLog.initLog()

    # send up the capabality info
    headerlist = clientCaps.caps.headerFormat()
    for (headerName, value) in headerlist:
        server.add_header(headerName, value)

    if systemId == None:
        systemId = getSystemId()

    if not systemId:
        return None

    maybeUpdateVersion()
    log.log_me("logging into up2date server")

    # the list of caps the client needs
    caps = capabilities.Capabilities()

    global loginInfo
    try:
        li = rpcServer.doCall(server.up2date.login, systemId)
    except rpclib.Fault, f:
        if abs(f.faultCode) == 49:
            #            print f.faultString
            raise up2dateErrors.AbuseError(f.faultString)
        else:
            raise f
Example #7
0
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 up2dateErrors.CommunicationError(_("Connection aborted by the user")), None, sys.exc_info()[2]
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror), e:
            log.log_me("A socket error occurred: %s, attempt #%s" % (e, attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise up2dateErrors.CommunicationError(e.args[1]), None, sys.exc_info()[2]
                else:
                    raise up2dateErrors.CommunicationError(e.args[0]), None, sys.exc_info()[2]
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise up2dateErrors.CommunicationError("httplib.IncompleteRead"), None, sys.exc_info()[2]
Example #8
0
def login(systemId=None):
    server = rpcServer.getServer()
    log = up2dateLog.initLog()

    # send up the capabality info
    headerlist = clientCaps.caps.headerFormat()
    for (headerName, value) in headerlist:
        server.add_header(headerName, value)

    if systemId == None:
        systemId = getSystemId()

    if not systemId:
        return None
        
    maybeUpdateVersion()
    log.log_me("logging into up2date server")

    # the list of caps the client needs
    caps = capabilities.Capabilities()

    global loginInfo
    try:
        li = rpcServer.doCall(server.up2date.login, systemId)
    except rpclib.Fault, f:
        if abs(f.faultCode) == 49:
#            print f.faultString
            raise up2dateErrors.AbuseError(f.faultString)
        else:
            raise f
Example #9
0
def read_all_fqdns():
    def flatten_dict(d):
        def items():
            for key, value in d.items():
                if isinstance(value, dict):
                    for subkey, subvalue in flatten_dict(value).items():
                        yield key + "." + subkey, subvalue
                else:
                    yield key, value
        return dict(items())
    
    fqdns = set()
    ret = {}
    ret["class"] = "FQDN"
    
    interfaces = flatten_dict(read_network_interfaces())
    ips = []
    
    for ipv4 in list(value for key, value in interfaces.iteritems() if key.endswith('ipaddr') and not key.startswith('lo')):
        if ipv4:
            ips.append(ipv4)
    for ipv6 in list(value for key, value in interfaces.iteritems() if key.endswith('ipv6') and not key.startswith('lo')):
        if ipv6:
            ips.append(ipv6[0]['addr'])
    for ip in ips:
        try:
            fqdns.add(socket.gethostbyaddr(ip)[0])
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            log = up2dateLog.initLog()
            msg = "Error resolving address: %s\n" % (e)
            log.log_error(msg)

    ret["name"] = list(fqdns)
    return ret
Example #10
0
 def __init__(self, cacheObject = None):
     # this is the cache, stuff here is only in storageDir
     self.cfg = config.initUp2dateConfig()
     self.log = up2dateLog.initLog()
     self.dir_list = [self.cfg["storageDir"]]
     self.ts =  transaction.initReadOnlyTransaction()
     PackageSource.__init__(self, cacheObject = cacheObject)
Example #11
0
def doCall(method, *args, **kwargs):
    log = up2dateLog.initLog()
    cfg = config.initUp2dateConfig()
    ret = None

    attempt_count = 1
    attempts = cfg["networkRetries"] or 5

    while 1:
        failure = 0
        ret = None
        try:
            ret = apply(method, args, kwargs)
        except KeyboardInterrupt:
            raise up2dateErrors.CommunicationError(
                "Connection aborted by the user")
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror), e:
            log.log_me("A socket error occurred: %s, attempt #%s" %
                       (e, attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise up2dateErrors.CommunicationError(e.args[1])
                else:
                    raise up2dateErrors.CommunicationError(e.args[0])
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise up2dateErrors.CommunicationError("httplib.IncompleteRead")
Example #12
0
def _initialize_dmi_data():
    """ Initialize _dmi_data unless it already exist and returns it """
    global _dmi_data, _dmi_not_available
    if _dmi_data is None:
        if _dmi_not_available:
            # do not try to initialize it again and again if not available
            return None
        else :
            dmixml = dmidecode.dmidecodeXML()
            dmixml.SetResultType(dmidecode.DMIXML_DOC)
            # Get all the DMI data and prepare a XPath context
            try:
                data = dmixml.QuerySection('all')
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                    log = up2dateLog.initLog()
                    log.log_debug("dmidecode warnings: " % dmi_warn)
            except:
                # DMI decode FAIL, this can happend e.g in PV guest
                _dmi_not_available = 1
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                return None
            _dmi_data = data.xpathNewContext()
    return _dmi_data
Example #13
0
def getAdvisoryInfo(pkg, warningCallback=None):
    log = up2dateLog.initLog()
    cfg = config.initUp2dateConfig()
    # no errata for non rhn use
    if not cfg['useRhn']:
        return None

    s = rpcServer.getServer()

    ts = transaction.initReadOnlyTransaction()
    mi = ts.dbMatch('Providename', pkg[0])
    if not mi:
        return None

    # odd,set h to last value in mi. mi has to be iterated
    # to get values from it...
    h = None
    for h in mi:
        break

    info = None

    # in case of package less errata that somehow apply
    if h:
        try:
            pkgName = "%s-%s-%s" % (h['name'], h['version'], h['release'])
            log.log_me("getAdvisoryInfo for %s" % pkgName)
            info = rpcServer.doCall(s.errata.getPackageErratum,
                                    up2dateAuth.getSystemId(), pkg)
        except rpclib.Fault, f:
            if warningCallback:
                warningCallback(f.faultString)
            return None
Example #14
0
def updateLoginInfo():
    log = up2dateLog.initLog()
    log.log_me("updating login info")
    # NOTE: login() updates the loginInfo object
    login()
    if not loginInfo:
        raise up2dateErrors.AuthenticationError("Unable to authenticate")
    return loginInfo
Example #15
0
def updateLoginInfo():
    log = up2dateLog.initLog()
    log.log_me("updating login info")
    # NOTE: login() updates the loginInfo object
    login()
    if not loginInfo:
        raise up2dateErrors.AuthenticationError("Unable to authenticate")
    return loginInfo
Example #16
0
def updateLoginInfo(timeout=None):
    log = up2dateLog.initLog()
    log.log_me("updateLoginInfo() login info")
    # NOTE: login() updates the loginInfo object
    login(forceUpdate=True, timeout=timeout)
    if not loginInfo:
        raise up2dateErrors.AuthenticationError("Unable to authenticate")
    return loginInfo
Example #17
0
    def __init__(self, cacheObject = None, packagePath = None):
        self.cfg = config.initUp2dateConfig()
        self.log = up2dateLog.initLog()
        self.dir_list = up2dateUtils.getPackageSearchPath()
        if packagePath:
            self.dir_list = self.dir_list + packagePath

        self.ts = transaction.initReadOnlyTransaction()
        PackageSource.__init__(self, cacheObject = cacheObject)
Example #18
0
 def __init__(self, filename=None):
     self.repos = []
     self.fileName = filename
     self.log = up2dateLog.initLog()
     self.cfg = config.initUp2dateConfig()
     #just so we dont import repomd info more than onc
     self.setupRepomd = None
     if self.fileName:
         self.load()
Example #19
0
    def __init__(self, cacheObject = None, packagePath = None):
        self.cfg = config.initUp2dateConfig()
        self.log = up2dateLog.initLog()
        self.dir_list = up2dateUtils.getPackageSearchPath()
        if packagePath:
            self.dir_list = self.dir_list + packagePath

        self.ts = transaction.initReadOnlyTransaction()
        PackageSource.__init__(self, cacheObject = cacheObject)
Example #20
0
 def __init__(self, filename = None):
     self.repos = []
     self.fileName = filename
     self.log = up2dateLog.initLog()
     self.cfg = config.initUp2dateConfig()
     #just so we dont import repomd info more than onc
     self.setupRepomd = None
     if self.fileName:
         self.load()
Example #21
0
def updatePackageProfile():
    """ get a list of installed packages and send it to rhnServer """
    log = up2dateLog.initLog()
    log.log_me("Updating package profile")
    packages = pkgUtils.getInstalledPackageList(getArch=1)
    s = rhnserver.RhnServer()
    if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
        # for older satellites and hosted - convert to old format
        packages = convertPackagesFromHashToList(packages)
    s.registration.update_packages(up2dateAuth.getSystemId(), packages)
Example #22
0
def updatePackageProfile(timeout=None):
    """ get a list of installed packages and send it to rhnServer """
    log = up2dateLog.initLog()
    log.log_me("Updating package profile")
    packages = pkgUtils.getInstalledPackageList(getArch=1)
    s = rhnserver.RhnServer(timeout=timeout)
    if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
        # for older satellites and hosted - convert to old format
        packages = convertPackagesFromHashToList(packages)
    s.registration.update_packages(up2dateAuth.getSystemId(), packages)
Example #23
0
    def __init__(self, headerCacheObject = None, metainfolist = None):
        self.log = up2dateLog.initLog()
        self.metainfo = {}
        # lame, need to keep a list to keep the order
        self.source_list = []
        if metainfolist != None:
            for source in metainfolist:
                self.addSourceClass(source)

        self.headerCache = headerCacheObject
Example #24
0
    def __init__(self, headerCacheObject = None, metainfolist = None):
        self.log = up2dateLog.initLog()
        self.metainfo = {}
        # lame, need to keep a list to keep the order
        self.source_list = []
        if metainfolist != None:
            for source in metainfolist:
                self.addSourceClass(source)

        self.headerCache = headerCacheObject
Example #25
0
def get_hal_system_and_smbios():
    try:
        if using_gudev:
            props = get_computer_info()
        else: 
            computer = get_hal_computer()
            props = computer.GetAllProperties()
    except Exception, e:
        log = up2dateLog.initLog()
        msg = "Error reading system and smbios information: %s\n" % (e)
        log.log_debug(msg)
        return {}
Example #26
0
def get_hal_system_and_smbios():
    try:
        if using_gudev:
            props = get_computer_info()
        else:
            computer = get_hal_computer()
            props = computer.GetAllProperties()
    except Exception, e:
        log = up2dateLog.initLog()
        msg = "Error reading system and smbios information: %s\n" % (e)
        log.log_debug(msg)
        return {}
Example #27
0
    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_type, sys.exc_value)
                msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server(
                )
                self.log.log_me(msg)
                # try a different url

                # use the next serverURL
                import urllib
                typ, uri = urllib.splittype(self.serverList.server())
                typ = typ.lower()
                if typ not in ("http", "https"):
                    raise (rpclib.InvalidRedirectionError(
                        "Redirected to unsupported protocol %s" % typ), None,
                           sys.exc_info()[2])

                self._host, self._handler = urllib.splithost(uri)
                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
Example #28
0
    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_type, sys.exc_value)
                msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server()
                self.log.log_me(msg)
                # try a different url

                # use the next serverURL
                import urllib

                typ, uri = urllib.splittype(self.serverList.server())
                typ = typ.lower()
                if typ not in ("http", "https"):
                    raise rpclib.InvalidRedirectionError(
                        "Redirected to unsupported protocol %s" % typ
                    ), None, sys.exc_info()[2]

                self._host, self._handler = urllib.splithost(uri)
                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
Example #29
0
def getChannels(force=None, label_whitelist=None):
    cfg = config.initUp2dateConfig()
    log = up2dateLog.initLog()
    global selected_channels
    #bz:210625 the selected_chs is never filled
    # so it assumes there is no channel although
    # channels are subscribed
    selected_channels = label_whitelist
    if not selected_channels and not force:

        ### mrepo: hardcode sources so we don't depend on /etc/sysconfig/rhn/sources
        # sources = sourcesConfig.getSources()
        sources = [{
            'url': 'https://xmlrpc.rhn.redhat.com/XMLRPC',
            'type': 'up2date'
        }]
        useRhn = 1

        if cfg.has_key('cmdlineChannel'):
            sources.append({'type': 'cmdline', 'label': 'cmdline'})

        selected_channels = rhnChannelList()
        cfg['useRhn'] = useRhn

        li = up2dateAuth.getLoginInfo()
        # login can fail...
        if not li:
            return []

        tmp = li.get('X-RHN-Auth-Channels')
        if tmp == None:
            tmp = []
        for i in tmp:
            if label_whitelist and not label_whitelist.has_key(i[0]):
                continue

            channel = rhnChannel(label=i[0],
                                 version=i[1],
                                 type='up2date',
                                 url=cfg["serverURL"])
            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
Example #30
0
def readCachedLogin():
    """
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    """
    log = up2dateLog.initLog()
    log.log_debug("readCachedLogin invoked")
    if not os.access(pcklAuthFileName, os.R_OK):
        log.log_debug("Unable to read pickled loginInfo at: %s" %
                      pcklAuthFileName)
        return False
    pcklAuth = open(pcklAuthFileName, 'rb')
    try:
        data = pickle.load(pcklAuth)
    except EOFError:
        log.log_debug("Unexpected EOF. Probably an empty file, \
                       regenerate auth file")
        pcklAuth.close()
        return False
    pcklAuth.close()
    # Check if system_id has changed
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['system_id']
        cidVer = "ID-%s" % data['loginInfo']['X-RHN-Server-Id']
        if idVer != cidVer:
            log.log_debug("system id version changed: %s vs %s" %
                          (idVer, cidVer))
            return False
    except:
        pass
    createdTime = data['time']
    li = data['loginInfo']
    currentTime = time.time()
    expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset'])
    #Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset"
    log.log_debug("Checking pickled loginInfo, currentTime=", currentTime,
                  ", createTime=", createdTime, ", expire-offset=",
                  float(li['X-RHN-Auth-Expire-Offset']))
    if (currentTime > expireTime):
        log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \
                %(createdTime, expireTime))
        return False
    _updateLoginInfo(li)
    log.log_debug(
        "readCachedLogin(): using pickled loginInfo set to expire at ",
        expireTime)
    return True
Example #31
0
    def _request1(self, methodname, params):
        self.log = up2dateLog.initLog()
        while 1:
            try:
                ret = self._request(methodname, params)
            except rpclib.InvalidRedirectionError:
                #                print "GOT a InvalidRedirectionError"
                raise
            except rpclib.Fault:
                raise
            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 occured talking to %s:\n" % self._host
                msg = msg + "%s\n%s\n" % (sys.exc_type, sys.exc_value)
                msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server(
                )
                self.log.log_me(msg)
                # try a different url

                # use the next serverURL
                import urllib
                typ, uri = urllib.splittype(self.serverList.server())
                typ = string.lower(typ)
                if typ not in ("http", "https"):
                    raise InvalidRedirectionError(
                        "Redirected to unsupported protocol %s" % typ)

#                print "gha2"
                self._host, self._handler = urllib.splithost(uri)
                self._orig_handler = self._handler
                self._type = typ
                if not self._handler:
                    self._handler = "/RPC2"
                self._allow_redirect = 1
                continue
            # if we get this far, we succedded
            break
        return ret
Example #32
0
    def _request1(self, methodname, params):
        self.log = up2dateLog.initLog()
        while 1:
            try:
                ret = self._request(methodname, params)
            except rpclib.InvalidRedirectionError:
#                print "GOT a InvalidRedirectionError"
                raise
            except rpclib.Fault:
		raise 
            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 occured talking to %s:\n" % self._host
                msg = msg + "%s\n%s\n" % (sys.exc_type, sys.exc_value)
                msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server()
                self.log.log_me(msg)
                # try a different url

                # use the next serverURL
                import urllib
                typ, uri = urllib.splittype(self.serverList.server())
                typ = string.lower(typ)
                if typ not in ("http", "https"):
                    raise InvalidRedirectionError(
                        "Redirected to unsupported protocol %s" % typ)

#                print "gha2"
                self._host, self._handler = urllib.splithost(uri)
                self._orig_handler = self._handler
                self._type = typ
                if not self._handler:
                    self._handler = "/RPC2"
                self._allow_redirect = 1
                continue
            # if we get this far, we succedded
            break
        return ret
Example #33
0
def readCachedLogin():
    """
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    """
    log = up2dateLog.initLog()
    log.log_debug("readCachedLogin invoked")
    if not os.access(pcklAuthFileName, os.R_OK):
        log.log_debug("Unable to read pickled loginInfo at: %s" % pcklAuthFileName)
        return False
    pcklAuth = open(pcklAuthFileName, 'rb')
    try:
        data = pickle.load(pcklAuth)
    except EOFError:
        log.log_debug("Unexpected EOF. Probably an empty file, \
                       regenerate auth file")
        pcklAuth.close()
        return False
    pcklAuth.close()
    # Check if system_id has changed
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['system_id']
        cidVer = "ID-%s" % data['loginInfo']['X-RHN-Server-Id']
        if idVer != cidVer:
            log.log_debug("system id version changed: %s vs %s" % (idVer, cidVer))
	    return False
    except:
	pass
    createdTime = data['time']
    li = data['loginInfo']
    currentTime = time.time()
    expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset'])
    #Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset"
    log.log_debug("Checking pickled loginInfo, currentTime=", currentTime,
            ", createTime=", createdTime, ", expire-offset=",
            float(li['X-RHN-Auth-Expire-Offset']))
    if (currentTime > expireTime):
        log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \
                %(createdTime, expireTime))
        return False
    _updateLoginInfo(li)
    log.log_debug("readCachedLogin(): using pickled loginInfo set to expire at ", expireTime)
    return True
Example #34
0
def getChannels(force=None, label_whitelist=None):
    cfg = config.initUp2dateConfig()
    log = up2dateLog.initLog()
    global selected_channels
    # bz:210625 the selected_chs is never filled
    # so it assumes there is no channel although
    # channels are subscribed
    selected_channels = label_whitelist
    if not selected_channels and not force:

        ### mrepo: hardcode sources so we don't depend on /etc/sysconfig/rhn/sources
        # sources = sourcesConfig.getSources()
        sources = [{"url": "https://xmlrpc.rhn.redhat.com/XMLRPC", "type": "up2date"}]
        useRhn = 1

        if cfg.has_key("cmdlineChannel"):
            sources.append({"type": "cmdline", "label": "cmdline"})

        selected_channels = rhnChannelList()
        cfg["useRhn"] = useRhn

        li = up2dateAuth.getLoginInfo()
        # login can fail...
        if not li:
            return []

        tmp = li.get("X-RHN-Auth-Channels")
        if tmp == None:
            tmp = []
        for i in tmp:
            if label_whitelist and not label_whitelist.has_key(i[0]):
                continue

            channel = rhnChannel(label=i[0], version=i[1], type="up2date", url=cfg["serverURL"])
            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
Example #35
0
def get_hal_system_and_smbios():
    try:
        if using_gudev:
            props = get_computer_info()
        else:
            computer = get_hal_computer()
            props = computer.GetAllProperties()
    except Exception:
        log = up2dateLog.initLog()
        msg = "Error reading system and smbios information: %s\n" % (sys.exc_info()[1])
        log.log_debug(msg)
        return {}
    system_and_smbios = {}

    for key in props:
        if key.startswith('system'):
            system_and_smbios[unicode(key)] = unicode(props[key])

    system_and_smbios.update(get_smbios())
    return system_and_smbios
Example #36
0
def get_hal_system_and_smbios():
    try:
        if using_gudev:
            props = get_computer_info()
        else:
            computer = get_hal_computer()
            props = computer.GetAllProperties()
    except Exception:
        log = up2dateLog.initLog()
        msg = "Error reading system and smbios information: %s\n" % (
            sys.exc_info()[1])
        log.log_debug(msg)
        return {}
    system_and_smbios = {}

    for key in props:
        if key.startswith('system'):
            system_and_smbios[unicode(key)] = unicode(props[key])

    system_and_smbios.update(get_smbios())
    return system_and_smbios
Example #37
0
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 up2dateErrors.CommunicationError(
                _("Connection aborted by the user")), None, sys.exc_info()[2]
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror), e:
            log.log_me("A socket error occurred: %s, attempt #%s" %
                       (e, attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise up2dateErrors.CommunicationError(
                        e.args[1]), None, sys.exc_info()[2]
                else:
                    raise up2dateErrors.CommunicationError(
                        e.args[0]), None, sys.exc_info()[2]
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise up2dateErrors.CommunicationError(
                "httplib.IncompleteRead"), None, sys.exc_info()[2]
Example #38
0
def getAdvisoryInfo(pkg, warningCallback=None):
    log = up2dateLog.initLog()
    cfg = config.initUp2dateConfig()
    # no errata for non rhn use
    if not cfg['useRhn']:
        return None
        
    s = rpcServer.getServer()

    ts = transaction.initReadOnlyTransaction()
    mi = ts.dbMatch('Providename', pkg[0])
    if not mi:
	return None

    # odd,set h to last value in mi. mi has to be iterated
    # to get values from it...
    h = None
    for h in mi:
        break

    info = None

    # in case of package less errata that somehow apply
    if h:
        try:
            pkgName = "%s-%s-%s" % (h['name'],
                                h['version'],
                                h['release'])
            log.log_me("getAdvisoryInfo for %s" % pkgName)
            info = rpcServer.doCall(s.errata.getPackageErratum,
                                    up2dateAuth.getSystemId(),
                                    pkg)
        except rpclib.Fault, f:
            if warningCallback:
                warningCallback(f.faultString)
            return None
Example #39
0
def login(systemId=None, forceUpdate=False, timeout=None):
    log = up2dateLog.initLog()
    log.log_debug("login(forceUpdate=%s) invoked" % (forceUpdate))
    if not forceUpdate and not loginInfo:
        if readCachedLogin():
            return loginInfo

    server = rhnserver.RhnServer(timeout=timeout)

    # send up the capabality info
    headerlist = clientCaps.caps.headerFormat()
    for (headerName, value) in headerlist:
        server.add_header(headerName, value)

    if systemId == None:
        systemId = getSystemId()

    if not systemId:
        return None

    maybeUpdateVersion()
    log.log_me("logging into up2date server")

    li = server.up2date.login(systemId)

    # figure out if were missing any needed caps
    server.capabilities.validate()
    _updateLoginInfo(li) #update global var, loginInfo
    writeCachedLogin() #pickle global loginInfo

    if loginInfo:
        log.log_me("successfully retrieved authentication token "
                   "from up2date server")

    log.log_debug("logininfo:", loginInfo)
    return loginInfo
Example #40
0
 def __repr__(self):
     log = up2dateLog.initLog()
     msg = "Password error. The message was:\n" + self.errmsg
     log.log_me(msg)
     return msg
Example #41
0
 def __repr__(self):
     msg = "RPM file conflict error. The message was:\n" + self.errmsg
     log = up2dateLog.initLog()
     log.log_me(msg)
     return msg
Example #42
0
 def __repr__(self):
     msg = "RPM dependency error. The message was:\n" + self.errmsg
     log = up2dateLog.initLog()
     log.log_me(msg)
     return msg
Example #43
0
def getServer(refreshCallback=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 type(ca) == type(""):
        ca = [ca]

    rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"]
    if cfg["enableProxy"]:
        proxyHost = up2dateUtils.getProxySetting()
    else:
        proxyHost = None

    if hasSSL():
        serverUrls = cfg["serverURL"]
    else:
        serverUrls = cfg["noSSLServerURL"]

    # the standard is to be a string, so list-a-fy in that case
    if type(serverUrls) == type(""):
        serverUrls = [serverUrls]

    serverList = initServerList(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 os.environ.has_key(env):
            if not os.environ[env]:
                # sometimes unset
                continue
            lang = string.split(os.environ[env], ':')[0]
            lang = string.split(lang, '.')[0]
            break

    s = RetryServer(serverList.server(),
                    refreshCallback=refreshCallback,
                    proxy=proxyHost,
                    username=proxyUser,
                    password=proxyPassword)
    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
    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)
            print msg
            sys.exit(-1)

        # 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
Example #44
0
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 (up2dateErrors.CommunicationError(
                _("Connection aborted by the user")), None, sys.exc_info()[2])
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror):
            log.log_me("A socket error occurred: %s, attempt #%s" %
                       (sys.exc_info()[1], attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise (up2dateErrors.CommunicationError(e.args[1]), None,
                           sys.exc_info()[2])
                else:
                    raise (up2dateErrors.CommunicationError(e.args[0]), None,
                           sys.exc_info()[2])
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise (up2dateErrors.CommunicationError("httplib.IncompleteRead"),
                   None, sys.exc_info()[2])

        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 (up2dateErrors.CommunicationError(msg), None,
                   sys.exc_info()[2])

        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

                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 (up2dateErrors.CommunicationError(e.errmsg), None,
                       sys.exc_info()[2])
            # 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 (up2dateErrors.FileNotFoundError(msg), None,
                       sys.exc_info()[2])

            if not reset:
                if attempt_count >= attempts:
                    raise (up2dateErrors.CommunicationError(e.errmsg), None,
                           sys.exc_info()[2])
                else:
                    failure = 1

        except xmlrpclib.ResponseError:
            raise (up2dateErrors.CommunicationError(
                "Broken response from the server."), None, sys.exc_info()[2])

        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
Example #45
0
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 isinstance(ca, basestring):
        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 os.environ.has_key(env):
            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
Example #46
0
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_type)
                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_type

    # memory size info
    try:
        ret = read_memory()
        if ret: allhw.append(ret)
    except:
        print _("Error reading system memory information:"), sys.exc_type

    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_type
    # 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_type)
        log.log_me(msg)

    try:
        ret = read_installinfo()
        if ret:
            allhw.append(ret)
    except:
        print _("Error reading install method information:"), sys.exc_type

    if not cfg["skipNetwork"]:
        try:
            ret = read_network_interfaces()
            if ret:
                allhw.append(ret)
        except:
            print _("Error reading network interface information:"), sys.exc_type

    # all Done.
    return allhw
Example #47
0
def getServer(refreshCallback=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 isinstance(ca, basestring):
        ca = [ca]

    rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"]
    if cfg["enableProxy"]:
        proxyHost = config.getProxySetting()
    else:
        proxyHost = None

    serverUrls = config.getServerlURL()
    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 os.environ.has_key(env):
            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)
    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
    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
Example #48
0
import signal

import rhnreg, hardware
import up2dateErrors
import up2dateUtils
import pkgUtils
import up2dateLog
import config
from config import convert_url_from_puny
import up2dateAuth
from rhn import rpclib
from rhn.connections import idn_puny_to_unicode
from pmPlugin import PM_PLUGIN_NAME, PM_PLUGIN_CONF
from rhnreg_constants import *

log = up2dateLog.initLog()
cfg = config.initUp2dateConfig()

def ErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, ERROR.encode('utf-8'), (u"%s" % errmsg).encode('utf-8'),
                             [BACK.encode('utf-8')])

def FatalErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, FATAL_ERROR.encode('utf-8'), (u"%s" % errmsg).encode('utf-8'),
                             [OK.encode('utf-8')])
    screen.finish()
    sys.exit(1)

def WarningWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, WARNING.encode('utf-8'), ("%s" % errmsg).encode('utf-8'),
                             [OK.encode('utf-8')])
Example #49
0
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_type)
                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_type

    # memory size info
    try:
        ret = read_memory()
        if ret: allhw.append(ret)
    except:
        print _("Error reading system memory information:"), sys.exc_type

    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_type
    # 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_type)
        log.log_me(msg)

    try:
        ret = read_installinfo()
        if ret:
            allhw.append(ret)
    except:
        print _("Error reading install method information:"), sys.exc_type

    if not cfg["skipNetwork"]:
        try:
            ret = read_network_interfaces()
            if ret:
                allhw.append(ret)
        except:
            print _(
                "Error reading network interface information:"), sys.exc_type

    # all Done.
    return allhw
Example #50
0
def logDeltaPackages(pkgs):
    log = up2dateLog.initLog()
    log.log_me("Adding packages to package profile: %s" %
               pprint_pkglist(pkgs['added']))
    log.log_me("Removing packages from package profile: %s" %
               pprint_pkglist(pkgs['removed']))
Example #51
0
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 (up2dateErrors.CommunicationError(_(
                "Connection aborted by the user")), None, sys.exc_info()[2])
        # if we get a socket error, keep tryingx2
        except (socket.error, socket.sslerror):
            log.log_me("A socket error occurred: %s, attempt #%s" % (
                sys.exc_info()[1], attempt_count))
            if attempt_count >= attempts:
                if len(e.args) > 1:
                    raise (up2dateErrors.CommunicationError(e.args[1]), None, sys.exc_info()[2])
                else:
                    raise (up2dateErrors.CommunicationError(e.args[0]), None, sys.exc_info()[2])
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise (up2dateErrors.CommunicationError("httplib.IncompleteRead"), None, sys.exc_info()[2])

        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 (up2dateErrors.CommunicationError(msg), None, sys.exc_info()[2])

        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

                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 (up2dateErrors.CommunicationError(e.errmsg), None, sys.exc_info()[2])
            # 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 (up2dateErrors.FileNotFoundError(msg), None, sys.exc_info()[2])

            if not reset:
                if attempt_count >= attempts:
                    raise (up2dateErrors.CommunicationError(e.errmsg), None, sys.exc_info()[2])
                else:
                    failure = 1

        except xmlrpclib.ResponseError:
            raise (up2dateErrors.CommunicationError(
                "Broken response from the server."), None, sys.exc_info()[2])

        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
Example #52
0
def logDeltaPackages(pkgs):
    log = up2dateLog.initLog()
    log.log_me("Adding packages to package profile: %s" %
               pprint_pkglist(pkgs['added']))
    log.log_me("Removing packages from package profile: %s" %
               pprint_pkglist(pkgs['removed']))
Example #53
0
import signal

import rhnreg, hardware
import up2dateErrors
import up2dateUtils
import pkgUtils
import up2dateLog
import config
from config import convert_url_from_pune
import up2dateAuth
from rhn import rpclib
from rhn.connections import idn_pune_to_unicode

from rhnreg_constants import *

log = up2dateLog.initLog()
cfg = config.initUp2dateConfig()


def ErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, ERROR.encode('utf-8'),
                             (u"%s" % errmsg).encode('utf-8'),
                             [BACK.encode('utf-8')])


def FatalErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, FATAL_ERROR.encode('utf-8'),
                             (u"%s" % errmsg).encode('utf-8'),
                             [OK.encode('utf-8')])
    screen.finish()
    sys.exit(1)
Example #54
0
 def __init__(self, errmsg):
     if not isinstance(errmsg, unicode):
         errmsg = unicode(errmsg, 'utf-8')
     YumBaseError.__init__(self, errmsg)
     self.value = self.premsg + errmsg
     self.log = up2dateLog.initLog()