Exemple #1
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]
Exemple #2
0
def doCall(method, *args, **kwargs):
    log = rhnLog.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 rhnErrors.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 rhnErrors.CommunicationError(e.args[1])
                else:
                    raise rhnErrors.CommunicationError(e.args[0])
            else:
                failure = 1
        except httplib.IncompleteRead:
            print "httplib.IncompleteRead"
            raise rhnErrors.CommunicationError("httplib.IncompleteRead")
Exemple #3
0
    def __init__(self):
        UserDict.UserDict.__init__(self)
        self.missingCaps = {}
        #self.populate()
#        self.validate()
        self.neededCaps = neededCaps
        self.cfg = config.initUp2dateConfig()
def printVerboseList(availUpdates):
    cfg = config.initUp2dateConfig()
    if cfg['showChannels']:
        print """
Name                          Version        Rel             Channel     
----------------------------------------------------------------------"""
        for pkg in availUpdates:
            print "%-30s%-15s%-15s%-20s" % (pkg[0], pkg[1], pkg[2], pkg[6])
            if cfg["debug"]:
                time.sleep(.25)
                advisories = rhnErrata.getAdvisoryInfo(pkg)
                if advisories:
                    for a in advisories:
                        topic = string.join(string.split(a['topic']), ' ')
                        print "[%s] %s\n" % (a['advisory'], topic)
                else:
                    print "No advisory information available\n"
        print
        return
    print """
Name                                    Version        Rel     
----------------------------------------------------------"""
    for pkg in availUpdates:
        print "%-40s%-15s%-18s%-6s" % (pkg[0], pkg[1], pkg[2], pkg[4])
        if cfg["debug"]:
            time.sleep(.25)
            advisories = rhnErrata.getAdvisoryInfo(pkg)
            if advisories:
                for a in advisories:
                    topic = string.join(string.split(a['topic']), ' ')
                    print "[%s] %s\n" % (a['advisory'], topic)
            else:
                print "No advisory information available\n"
    print
Exemple #5
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
Exemple #6
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)
Exemple #7
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)
Exemple #8
0
    def __init__(self):
        UserDict.UserDict.__init__(self)
        self.missingCaps = {}
        #self.populate()
#        self.validate()
        self.neededCaps = neededCaps
        self.cfg = config.initUp2dateConfig()
Exemple #9
0
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 label_whitelist.has_key(chan['label']):
                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
Exemple #10
0
def getChannels(force=None, label_whitelist=None):
    cfg = config.initUp2dateConfig()
    global selected_channels
    if not selected_channels and not force:
        selected_channels = rhnChannelList()
        s = rhnserver.RhnServer()

        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 label_whitelist.has_key(chan['label']):
                continue
                
            channel = rhnChannel(type = 'up2date', url = cfg["serverURL"])
            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
Exemple #11
0
def printVerboseList(availUpdates):
    cfg = config.initUp2dateConfig()
    if cfg['showChannels']:
        print """
Name                          Version        Rel             Channel     
----------------------------------------------------------------------"""
        for pkg in availUpdates:
            print "%-30s%-15s%-15s%-20s" % (pkg[0], pkg[1], pkg[2], pkg[6])
            if cfg["debug"]:
                time.sleep(.25)
                advisories = rhnErrata.getAdvisoryInfo(pkg)
                if advisories:
                    for a in advisories:
                        topic = string.join(string.split(a['topic']), ' ')
                        print "[%s] %s\n" % (a['advisory'], topic)
                else:
                    print "No advisory information available\n"
        print
        return
    print """
Name                                    Version        Rel     
----------------------------------------------------------"""
    for pkg in availUpdates:
        print "%-40s%-15s%-18s%-6s" % (pkg[0], pkg[1], pkg[2], pkg[4])
        if cfg["debug"]:
            time.sleep(.25)
            advisories = rhnErrata.getAdvisoryInfo(pkg)
            if advisories:
                for a in advisories:
                    topic = string.join(string.split(a['topic']), ' ')
                    print "[%s] %s\n" % (a['advisory'], topic)
            else:
                print "No advisory information available\n"
    print
def printRetrieveHash(amount, total, speed=0, secs=0):
    cfg = config.initUp2dateConfig()
    hashesTotal = 26

    if total:
        percent = int(100 * (float(amount) / total))
        hashesNeeded = int(hashesTotal * (float(amount) / total))
    else:
        percent = 100
        hashesNeeded = hashesTotal

    if cfg["isatty"]:
        for i in range(hashesNeeded):
            sys.stdout.write('#')

        for i in range(hashesNeeded, hashesTotal):
            sys.stdout.write(' ')

    if cfg["isatty"]:
        if amount == total:
            print "%-25s" % " Done."
        else:
            print "%4d k/sec, %02d:%02d:%02d rem." % \
                  (speed / 1024, secs / (60*60), (secs % 3600) / 60,
                   secs % 60),
            for i in range(hashesTotal + 25):
                sys.stdout.write("\b")
    elif amount == total:
        print "Retrieved."
Exemple #13
0
def printRetrieveHash(amount, total, speed = 0, secs = 0):
    cfg = config.initUp2dateConfig()
    hashesTotal = 26
    
    if total:
        percent = int(100 * (float(amount) / total))
        hashesNeeded = int(hashesTotal * (float(amount) / total))
    else:
        percent = 100
        hashesNeeded = hashesTotal

    if cfg["isatty"]:
        for i in range(hashesNeeded):
            sys.stdout.write('#')

        for i in range(hashesNeeded, hashesTotal):
            sys.stdout.write(' ')

    if cfg["isatty"]:
        if amount == total:
            print "%-25s" % " Done."
        else:
            print "%4d k/sec, %02d:%02d:%02d rem." % \
                  (speed / 1024, secs / (60*60), (secs % 3600) / 60,
                   secs % 60),
            for i in range(hashesTotal + 25):
                sys.stdout.write("\b")
    elif amount == total:
        print "Retrieved."
Exemple #14
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)
Exemple #15
0
 def __init__(self):
     self.cfg = config.initUp2dateConfig()
     # how many headers to cache in ram
     if self.cfg["headerCacheSize"]:
         self.cache_size = self.cfg["headerCacheSize"]
     else:
         self.cache_size = 30
     self.__cache = {}
     self.__cacheLite = {}
    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
Exemple #17
0
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
Exemple #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()
Exemple #19
0
 def __init__(self):
     self.fd = 0
     self.hashesPrinted = None
     self.progressCurrent = None
     self.progressTotal = None
     self.hashesPrinted = None
     self.lastPercent = None
     self.packagesTotal = None
     self.cfg = config.initUp2dateConfig()
 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()
Exemple #21
0
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 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
Exemple #23
0
 def __init__(self):
     self.cfg = config.initUp2dateConfig()
     # how many headers to cache in ram
     if self.cfg["headerCacheSize"]:
         self.cache_size = self.cfg["headerCacheSize"]
     else:
         self.cache_size = 30
     self.__cache = {}
     self.__cacheLite = {}
Exemple #24
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)
 def __init__(self):
     self.fd = 0
     self.hashesPrinted = None
     self.progressCurrent = None
     self.progressTotal = None
     self.hashesPrinted = None
     self.lastPercent = None
     self.packagesTotal = None
     self.cfg = config.initUp2dateConfig()
Exemple #26
0
def getOSVersionAndRelease():
    cfg = config.initUp2dateConfig()
    if cfg["versionOverride"]:
        version = cfg["versionOverride"]
    else:
        version = os.uname()[2]

    release = os.uname()[0]
    releaseVersion = (release, version)
    return releaseVersion
Exemple #27
0
def getOSVersionAndRelease():
    cfg = config.initUp2dateConfig()
    if cfg["versionOverride"]:
        version = cfg["versionOverride"]
    else:
        version = os.uname()[2]

    release = os.uname()[0]
    releaseVersion = (release, version)
    return releaseVersion
Exemple #28
0
def addGPGKeys():
    cfg = config.initUp2dateConfig()
    if os.access(cfg["gpgKeyRing"], os.R_OK):
        # if they have a keyring like 7.3 used, import the keys off
        # of it
        importGpgKeyring()

    # the red hat keys still arent there
    if not checkGPGInstallation():
        importRedHatGpgKeys()
Exemple #29
0
def addGPGKeys():
    cfg = config.initUp2dateConfig()
    if os.access(cfg["gpgKeyRing"], os.R_OK):
        # if they have a keyring like 7.3 used, import the keys off
        # of it
        importGpgKeyring()

    # the red hat keys still arent there
    if not checkGPGInstallation():
        importRedHatGpgKeys()
Exemple #30
0
def findHostByRoute():
    cfg = config.initUp2dateConfig()
    sl = cfg['serverURL']
    if type(sl) == type(""):
        sl  = [sl]

    st = {'https':443, 'http':80}
    hostname = None
    intf = None
    for serverUrl in sl:
        s = socket.socket()
        server = string.split(serverUrl, '/')[2]
        servertype = string.split(serverUrl, ':')[0]
        port = st[servertype]
        
        if cfg['enableProxy']:
            server_port = config.getProxySetting()
            (server, port) = string.split(server_port, ':')
            port = int(port)

        try:
            s.settimeout(5)
            s.connect((server, port))
            (intf, port) = s.getsockname()
            hostname = socket.gethostbyaddr(intf)[0]
        # I dislike generic excepts, but is the above fails
        # for any reason, were not going to be able to
        # find a good hostname....
        except:
            s.close()
            continue
        
    # Override hostname with the one in /etc/sysconfig/network 
    # for bz# 457953
    
    if 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 = string.split(info, '=')
            if len(vals) <= 1:
                continue
            strippedstring = string.strip(vals[0])
            vals[0] = strippedstring
            if vals[0] == "HOSTNAME":
                hostname = string.strip(string.join(vals[1:]))
                break
        
    if hostname == None or hostname == 'localhost.localdomain':
        hostname = "unknown"
        s.close()
    return hostname, intf
Exemple #31
0
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
Exemple #32
0
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
Exemple #33
0
def getGPGflags():
    cfg = config.initUp2dateConfig()
    keyring_relocatable = 0
    rpm_version = getRpmVersion()
    if up2dateUtils.comparePackages(rpm_version, ("rpm", "4.0.4", "0", None)) >= 0:
        keyring_relocatable = 1

    if keyring_relocatable and cfg["gpgKeyRing"]:
        gpg_flags = "--homedir %s --no-default-keyring --keyring %s" % (gpgUtils.gpg_home_dir, cfg["gpgKeyRing"])
    else:
        gpg_flags = "--homedir %s" % gpgUtils.gpg_home_dir
    return gpg_flags
Exemple #34
0
def getPackageSearchPath():
    dir_list = []
    cfg = config.initUp2dateConfig()
    dir_list.append(cfg["storageDir"])

    dir_string = cfg["packageDir"]
    if dir_string:
        paths = string.split(dir_string, ":")
        fullpaths = []
        for path in paths:
            fullpath = os.path.normpath(os.path.abspath(os.path.expanduser(path)))
            fullpaths.append(fullpath)
        dir_list = dir_list + fullpaths
    return dir_list
Exemple #35
0
 def __init__(self):
     # Need to override __init__ because the base class requires a message arg
     # and this exception shouldn't.
     up2dateConfig = config.initUp2dateConfig()
     certFile = up2dateConfig['sslCACert']
     f = open(certFile, "r")
     buf = f.read()
     f.close()
     tempCert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, buf)
     if tempCert.has_expired():
         RepoError.__init__(self ,"The certificate %s is expired. Please ensure you have the correct"
                        " certificate and your system time is correct." % certFile)
     else:
         RepoError.__init__(self, "The SSL certificate failed verification.")
Exemple #36
0
def getGPGflags():
    cfg = config.initUp2dateConfig()
    keyring_relocatable = 0
    rpm_version = getRpmVersion()
    if up2dateUtils.comparePackages(rpm_version,
                                    ("rpm", "4.0.4", "0", None)) >= 0:
        keyring_relocatable = 1

    if keyring_relocatable and cfg["gpgKeyRing"]:
        gpg_flags = "--homedir %s --no-default-keyring --keyring %s" % (
            gpgUtils.gpg_home_dir, cfg["gpgKeyRing"])
    else:
        gpg_flags = "--homedir %s" % gpgUtils.gpg_home_dir
    return gpg_flags
Exemple #37
0
def getPackageSearchPath():
    dir_list = []
    cfg = config.initUp2dateConfig()
    dir_list.append(cfg["storageDir"])

    dir_string = cfg["packageDir"]
    if dir_string:
        paths = string.split(dir_string, ':')
        fullpaths = []
        for path in paths:
            fullpath = os.path.normpath(
                os.path.abspath(os.path.expanduser(path)))
            fullpaths.append(fullpath)
        dir_list = dir_list + fullpaths
    return dir_list
Exemple #38
0
def downloadPackage(channel, pkghash, localfile, serverUrl=None):
    cfg = config.initUp2dateConfig()

    serverSettings = ServerSettings()
    if serverUrl is not None:
        serverSettings.httpServerUrl = serverUrl
    li = rhnAuth.getLoginInfo()
    s = getGETServer(li, serverSettings)

    fd = rpcServer.doCall(s.getPackage, channel, pkghash)
    status = s.get_response_status()

    f2 = _readFD(fd, localfile)
    f2.close()
    fd.close()
Exemple #39
0
def downloadPackage(channel, pkghash, localfile, serverUrl=None):
    cfg = config.initUp2dateConfig()

    serverSettings = ServerSettings()
    if serverUrl is not None:
        serverSettings.httpServerUrl = serverUrl
    li = rhnAuth.getLoginInfo()
    s = getGETServer(li, serverSettings)

    fd = rpcServer.doCall(s.getPackage, channel, pkghash)
    status = s.get_response_status()

    f2 = _readFD(fd, localfile)
    f2.close()
    fd.close()
Exemple #40
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
Exemple #41
0
def getOSVersionAndRelease():
    cfg = config.initUp2dateConfig()
    ts = transaction.initReadOnlyTransaction()
    for h in ts.dbMatch('Providename', "redhat-release"):
        if cfg["versionOverride"]:
            version = cfg["versionOverride"]
        else:
            version = h['version']

        releaseVersion = (h['name'], version)
        return releaseVersion
    else:
       raise up2dateErrors.RpmError(
           "Could not determine what version of Red Hat Linux you "\
           "are running.\nIf you get this error, try running \n\n"\
           "\t\trpm --rebuilddb\n\n")
Exemple #42
0
def saveHeader(hdr):
    #    print hdr
    #    print type(hdr)
    cfg = config.initUp2dateConfig()
    fileName = "%s/%s.%s.hdr" % (cfg["storageDir"],
                                 string.join(
                                     (hdr['name'], hdr['version'],
                                      hdr['release']), "-"), hdr['arch'])

    #    print fileName
    fd = os.open(fileName, os.O_WRONLY | os.O_CREAT, 0600)

    os.write(fd, hdr.unload())
    os.close(fd)

    return 1
Exemple #43
0
def getOSVersionAndRelease():
    cfg = config.initUp2dateConfig()
    ts = transaction.initReadOnlyTransaction()
    for h in ts.dbMatch('Providename', "redhat-release"):
        if cfg["versionOverride"]:
            version = cfg["versionOverride"]
        else:
            version = h['version']

        releaseVersion = (h['name'], version)
        return releaseVersion
    else:
        raise up2dateErrors.RpmError(
            "Could not determine what version of Red Hat Linux you "\
            "are running.\nIf you get this error, try running \n\n"\
            "\t\trpm --rebuilddb\n\n")
Exemple #44
0
def printSkippedPackages(skippedUpdates):
    cfg = config.initUp2dateConfig()
    print "The following Packages were marked to be skipped by your configuration:"
    print """
Name                                    Version        Rel  Reason
-------------------------------------------------------------------------------"""
    for pkg,reason in skippedUpdates:
        print "%-40s%-15s%-5s%s" % (pkg[0], pkg[1], pkg[2], reason)
        if cfg["debug"]:
            time.sleep(.25)
            advisories = rhnErrata.getAdvisoryInfo(pkg)
            if advisories:
                for a in advisories:
                    topic = string.join(string.split(a['topic']), ' ')
                    print "[%s] %s\n" % (a['advisory'], topic)
            else:
                print "No advisory information available\n"
    print
Exemple #45
0
def getProxySetting():
    cfg = config.initUp2dateConfig()
    proxy = None
    proxyHost = cfg["httpProxy"]
    # legacy for backwards compat
    if proxyHost == "":
        try:
            proxyHost = cfg["pkgProxy"]
        except:
            proxyHost = None

    if proxyHost:
        if proxyHost[:7] == "http://":
            proxy = proxyHost[7:]
        else:
            proxy = proxyHost

    return proxy
Exemple #46
0
def saveHeader(hdr):
#    print hdr
#    print type(hdr)
    cfg = config.initUp2dateConfig()
    fileName = "%s/%s.%s.hdr" % (cfg["storageDir"],
                                 string.join( (hdr['name'],
                                               hdr['version'],
                                               hdr['release']),
                                              "-"),
                                 hdr['arch'])

#    print fileName
    fd = os.open(fileName, os.O_WRONLY|os.O_CREAT, 0600)

    os.write(fd, hdr.unload())
    os.close(fd)

    return 1
Exemple #47
0
    def __init__(self):
        self.cfg = config.initUp2dateConfig()
        self.xmlrpcServerUrl = self.cfg["serverURL"]
        if self.cfg["useNoSSLForPackages"]:
            self.httpServerUrl = self.cfg["noSSLServerURL"]
        else:
            self.httpServerUrl = self.cfg["serverURL"]

        self.proxyUrl = None
        self.proxyUser = None
        self.proxyPassword = None

        if self.cfg["enableProxy"] and rhnUtils.getProxySetting():
            self.proxyUrl = rhnUtils.getProxySetting()
            if self.cfg["enableProxyAuth"]:
                if self.cfg["proxyUser"] and self.cfg["proxyPassword"]:
                    self.proxyPassword = self.cfg["proxyPassword"]
                    self.proxyUser = self.cfg["proxyUser"]
def printSkippedPackages(skippedUpdates):
    cfg = config.initUp2dateConfig()
    print "The following Packages were marked to be skipped by your configuration:"
    print """
Name                                    Version        Rel  Reason
-------------------------------------------------------------------------------"""
    for pkg, reason in skippedUpdates:
        print "%-40s%-15s%-5s%s" % (pkg[0], pkg[1], pkg[2], reason)
        if cfg["debug"]:
            time.sleep(.25)
            advisories = rhnErrata.getAdvisoryInfo(pkg)
            if advisories:
                for a in advisories:
                    topic = string.join(string.split(a['topic']), ' ')
                    print "[%s] %s\n" % (a['advisory'], topic)
            else:
                print "No advisory information available\n"
    print
Exemple #49
0
    def __init__(self):
        self.cfg = config.initUp2dateConfig()
        self.xmlrpcServerUrl = self.cfg["serverURL"]
        if self.cfg["useNoSSLForPackages"]:
            self.httpServerUrl = self.cfg["noSSLServerURL"]
        else:
            self.httpServerUrl = self.cfg["serverURL"]

        self.proxyUrl = None
        self.proxyUser = None
        self.proxyPassword = None

        if self.cfg["enableProxy"] and rhnUtils.getProxySetting():
            self.proxyUrl = rhnUtils.getProxySetting()
            if self.cfg["enableProxyAuth"]:
                if self.cfg["proxyUser"] and self.cfg["proxyPassword"]:
                    self.proxyPassword = self.cfg["proxyPassword"]
                    self.proxyUser = self.cfg["proxyUser"]
Exemple #50
0
def getProxySetting():
    cfg = config.initUp2dateConfig()
    proxy = None
    proxyHost = cfg["httpProxy"]
    # legacy for backwards compat
    if proxyHost == "":
        try:
            proxyHost = cfg["pkgProxy"]
        except:
            proxyHost = None

    if proxyHost:
        if proxyHost[:7] == "http://":
            proxy = proxyHost[7:]
        else:
            proxy = proxyHost

    return proxy
Exemple #51
0
def maybeUpdateVersion():
    cfg = config.initUp2dateConfig()
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['os_release']
    except:
        # they may not even have a system id yet.
        return 0

    systemVer = up2dateUtils.getVersion()

    if idVer != systemVer:
        s = rpcServer.getServer()

        try:
            newSystemId = rpcServer.doCall(s.registration.upgrade_version,
                                           getSystemId(), systemVer)
        except rpclib.Fault, f:
            raise up2dateErrors.CommunicationError(f.faultString)

        path = cfg["systemIdPath"]
        dir = path[:string.rfind(path, "/")]
        if not os.access(dir, os.W_OK):
            try:
                os.mkdir(dir)
            except:
                return 0
        if not os.access(dir, os.W_OK):
            return 0

        if os.access(path, os.F_OK):
            # already have systemid file there; let's back it up
            savePath = path + ".save"
            try:
                os.rename(path, savePath)
            except:
                return 0

        f = open(path, "w")
        f.write(newSystemId)
        f.close()
        try:
            os.chmod(path, 0600)
        except:
            pass
Exemple #52
0
def maybeUpdateVersion():
    cfg = config.initUp2dateConfig()
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['os_release']
    except:
        # they may not even have a system id yet.
        return 0

    systemVer = up2dateUtils.getVersion()
    
    if idVer != systemVer:
      s = rpcServer.getServer()
    
      try:
          newSystemId = rpcServer.doCall(s.registration.upgrade_version,
                                         getSystemId(), systemVer)
      except rpclib.Fault, f:
          raise up2dateErrors.CommunicationError(f.faultString)

      path = cfg["systemIdPath"]
      dir = path[:string.rfind(path, "/")]
      if not os.access(dir, os.W_OK):
          try:
              os.mkdir(dir)
          except:
              return 0
      if not os.access(dir, os.W_OK):
          return 0

      if os.access(path, os.F_OK):
          # already have systemid file there; let's back it up
          savePath = path + ".save"
          try:
              os.rename(path, savePath)
          except:
              return 0

      f = open(path, "w")
      f.write(newSystemId)
      f.close()
      try:
          os.chmod(path, 0600)
      except:
          pass
Exemple #53
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
Exemple #54
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]
Exemple #55
0
def initServerList(servers):
    global server_list
    try:
        server_list = server_list
    except NameError:
        server_list = None

    if server_list == None:
        server_list = ServerList(servers)

    # if we've changed the config, we need need to
    # update the server_list as well. Not really needed
    # in the app, but makes testing cleaner
    cfg = config.initUp2dateConfig()
    sl = cfg['serverURL']
    if type(sl) == type(""):
        sl = [sl]

    if sl != server_list.serverList:
        server_list = ServerList(servers)

    return server_list
Exemple #56
0
def initServerList(servers):
    global server_list
    try:
        server_list = server_list
    except NameError:
        server_list = None

    if server_list == None:
        server_list = ServerList(servers)

    # if we've changed the config, we need need to
    # update the server_list as well. Not really needed
    # in the app, but makes testing cleaner
    cfg = config.initUp2dateConfig()
    sl = cfg['serverURL']
    if type(sl) == type(""):
        sl  = [sl]
        
    if sl != server_list.serverList:
        server_list = ServerList(servers)

    return server_list
Exemple #57
0
def findHostByRoute():
    cfg = config.initUp2dateConfig()
    s = socket.socket()
    serverUrl = cfg['serverURL']
    server = string.split(serverUrl, '/')[2]
    port = 80
    if cfg['enableProxy']:
        server_port = rhnUtils.getProxySetting()
        (server, port) = string.split(server_port, ':')
        port = int(port)

    s.connect((server, port))
    (intf, port) = s.getsockname()
    try:
        hostname = socket.gethostbyaddr(intf)[0]
    # I dislike generic excepts, but is the above fails
    # for any reason, were not going to be able to
    # find a good hostname....
    except:
        hostname = "unknown"
    s.close()
    return hostname, intf
Exemple #58
0
def findHostByRoute():
    cfg = config.initUp2dateConfig()
    s = socket.socket()
    serverUrl = cfg['serverURL']
    server = string.split(serverUrl, '/')[2]
    port = 80
    if cfg['enableProxy']:
        server_port = rhnUtils.getProxySetting()
        (server, port) = string.split(server_port, ':')
        port = int(port)

    s.connect((server, port))
    (intf, port) = s.getsockname()
    try:
        hostname = socket.gethostbyaddr(intf)[0]
    # I dislike generic excepts, but is the above fails
    # for any reason, were not going to be able to
    # find a good hostname....
    except:
        hostname = "unknown"
    s.close()
    return hostname, intf