コード例 #1
0
ファイル: spacewalk.py プロジェクト: BlackSmith/spacewalk
    def __init__(self, channel, opts):
        super(SpacewalkRepo, self).__init__(ustr(channel['label']),
                                            opts.get('cachedir'))
        # dnf stuff
        self.name = ustr(channel['name'])
        self.baseurl = [ url + '/GET-REQ/' + self.id for url in channel['url']]
        self.sslcacert = opts.get('sslcacert')
        self.proxy = opts.get('proxy')
        try:
            self.gpgkey = get_gpg_key_urls(channel['gpg_key_url'])
        except InvalidGpgKeyLocation as e:
            logger.warn(GPG_KEY_REJECTED, dnf.i18n.ucd(e))
            self.gpgkey = []
        if channel['version'] != opts.get('cached_version'):
            self.metadata_expire = 1

        # spacewalk stuff
        self.login_info = opts.get('login_info')
        self.keepalive = 0
        self.bandwidth = 0
        self.retries = 1
        self.throttle = 0
        self.timeout = opts.get('timeout')
        self.gpgcheck = opts.get('gpgcheck')
        self.force_http = opts.get('force_http')

        if opts.get('enabled'):
            self.enable()
        else:
            self.disable()
コード例 #2
0
ファイル: connections.py プロジェクト: mcalmer/spacewalk
def idn_ascii_to_puny(hostname):
    """ Convert domain name to Punycode (RFC3492). Hostname can be instance of string or Unicode """
    if hostname is None:
        return None
    else:
        hostname = i18n.ustr(hostname)
        return i18n.ustr(hostname.encode('idna'))
コード例 #3
0
ファイル: up2dateLog.py プロジェクト: jdobes/spacewalk
    def write_log(self, s):

        log_name = self.cfg["logFile"] or "/var/log/up2date"
        log_file = open(log_name, 'a')
        msg = u"%s %s\n" % (ustr(self.log_info), ustr(s))
        log_file.write(sstr(msg))
        log_file.flush()
        log_file.close()
コード例 #4
0
ファイル: up2dateErrors.py プロジェクト: Bearlock/spacewalk
 def __init__(self, args):
     Error.__init__(self, "")
     self.args = args
     for key in self.args.keys():
         self.args[key] = ustr(self.args[key])
         self.value = self.value + "%s failed because of %s\n" % (
             key, self.args[key])
     self.data = self.args
コード例 #5
0
ファイル: hardware.py プロジェクト: jdobes/spacewalk
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[ustr(key)] = ustr(props[key])

    system_and_smbios.update(get_smbios())
    return system_and_smbios
コード例 #6
0
ファイル: up2dateLog.py プロジェクト: jdobes/spacewalk
    def log_me(self, *args):
        """General logging function.
        Eg: log_me("I am a banana.")

        """
        self.log_info = "[%s] %s" % (time.ctime(time.time()), self.app)
        s = u""
        for i in args:
            # we really need unicode(str(i)) here, because i can be anything
            # from string or int to list, dict or even class
            i = ustr(str(i))
            s += i
        if self.cfg["debug"] > 1:
            print(s)
        self.write_log(s)
コード例 #7
0
ファイル: spacewalk.py プロジェクト: Bearlock/spacewalk
 def transaction(self):
     """ Update system's profile after transaction. """
     if not self.conf.enabled:
         return
     if not self.connected_to_spacewalk:
         # not connected so nothing to do here
         return
     if self.up2date_cfg['writeChangesToLog'] == 1:
         delta = self._make_package_delta()
         up2date_client.rhnPackageInfo.logDeltaPackages(delta)
     try:
         up2date_client.rhnPackageInfo.updatePackageProfile(
                                                     timeout=self.conf.timeout)
     except up2dateErrors.RhnServerException as e:
         logger.error("%s\n%s\n%s", COMMUNICATION_ERROR, PROFILE_NOT_SENT,
                                    ustr(e))
コード例 #8
0
ファイル: rhnreg.py プロジェクト: mcalmer/spacewalk
def _encode_characters(*args):
        """ All the data we gathered from dmi, bios, gudev are in utf-8,
            we need to convert characters beyond ord(127) - e.g \xae to unicode.
        """
        result=[]
        for item in args:
            item_type = type(item)
            if item_type == StringType:
                item = ustr(item)
            elif item_type == TupleType:
                item = tuple(_encode_characters(i) for i in item)
            elif item_type == ListType:
                item = [_encode_characters(i) for i in item]
            elif item_type == DictType or item_type == DictionaryType:
                item = dict([(_encode_characters(name, val)) for name, val in item.items()])
            # else: numbers or UnicodeType - are safe
            result.append(item)
        if len(result) == 1:
            return result[0]
        else:
            return tuple(result)
コード例 #9
0
 def __init__(self, errmsg):
     errmsg = ustr(errmsg)
     PmBaseError.__init__(self, errmsg)
     self.value = 'rhn-plugin: ' + self.premsg + errmsg
     self.log = up2dateLog.initLog()
コード例 #10
0
ファイル: testConfig.py プロジェクト: mcalmer/spacewalk
 def testConfigString(self):
     "Verify that Config loads a string as a string"
     cfg = config.initUp2dateConfig(test_up2date)
     assert type(cfg['systemIdPath']) == type(ustr(''))
コード例 #11
0
def convert_url_to_puny(url):
    """ returns url where hostname is converted to Punycode (RFC3492) """
    s = urlsplit(url)
    return sstr(urlunsplit((s[0], ustr(idn_ascii_to_puny(s[1])), s[2], s[3], s[4])))
コード例 #12
0
ファイル: config.py プロジェクト: TJM/spacewalk
    def load(self, filename = None):
        if filename:
            self.fileName = filename
        if self.fileName == None:
            return
        if not os.access(self.fileName, os.R_OK):
#            print("warning: can't access %s" % self.fileName)
            return

        f = open(self.fileName, "r")

        multiline = ''
        for line in f.readlines():
            # strip comments
            if line.find('#') == 0:
                continue
            line = multiline + line.strip()
            if not line:
                continue

            # if line ends in '\', append the next line before parsing
            if line[-1] == '\\':
                multiline = line[:-1].strip()
                continue
            else:
                multiline = ''

            split = line.split('=', 1)
            if len(split) != 2:
                # not in 'a = b' format. we should log this
                # or maybe error.
                continue
            key = split[0].strip()
            value = ustr(split[1].strip())

            # decode a comment line
            comment = None
            pos = key.find("[comment]")
            if pos != -1:
                key = key[:pos]
                comment = value
                value = None

            # figure out if we need to parse the value further
            if value:
                # possibly split value into a list
                values = value.split(";")
                if key in ['proxyUser', 'proxyPassword']:
                    value = str(value.encode(locale.getpreferredencoding()))
                elif len(values) == 1:
                    try:
                        value = int(value)
                    except ValueError:
                        pass
                elif values[0] == "":
                    value = []
                else:
                    # there could be whitespace between the values on
                    # one line, let's strip it out
                    value = [val.strip() for val in values if val.strip() ]

            # now insert the (comment, value) in the dictionary
            newval = (comment, value)
            if key in self.dict: # do we need to update
                newval = self.dict[key]
                if comment is not None: # override comment
                    newval = (comment, newval[1])
                if value is not None: # override value
                    newval = (newval[0], value)
            self.dict[key] = newval
        f.close()
コード例 #13
0
 def __init__(self, msg):
     msg = ustr(msg)
     self.value = self.premsg + msg
コード例 #14
0
def convert_url_from_puny(url):
    """ returns url where hostname is converted from Punycode (RFC3492). Returns unicode string. """
    s = urlsplit(url)
    return ustr(urlunsplit((s[0], idn_puny_to_unicode(s[1]), s[2], s[3], s[4])))
コード例 #15
0
ファイル: up2dateErrors.py プロジェクト: Bearlock/spacewalk
 def __init__(self, msg):
     msg = ustr(msg)
     self.value = self.premsg + msg
コード例 #16
0
ファイル: spacewalk.py プロジェクト: Bearlock/spacewalk
    def activate_channels(self, networking=True):
        enabled_channels = {}
        sslcacert = None
        force_http = 0
        proxy_url = None
        login_info = None
        cached_channels = self._read_channels_file()
        if not networking:
            # no network communication, use list of channels from persistdir
            enabled_channels = cached_channels
        else:
            # setup proxy according to up2date
            self.up2date_cfg = up2date_client.config.initUp2dateConfig()
            sslcacert = get_ssl_ca_cert(self.up2date_cfg)
            force_http = self.up2date_cfg['useNoSSLForPackages'],

            try:
                login_info = up2date_client.up2dateAuth.getLoginInfo(timeout=self.conf.timeout)
            except up2dateErrors.RhnServerException as e:
                logger.error("%s\n%s\n%s", COMMUNICATION_ERROR, RHN_DISABLED,
                                           ustr(e))
                return

            if not login_info:
                logger.error("%s\n%s", NOT_REGISTERED_ERROR, RHN_DISABLED)
                self._write_channels_file({})
                return

            try:
                svrChannels = up2date_client.rhnChannel.getChannelDetails(
                                                              timeout=self.conf.timeout)
            except up2dateErrors.CommunicationError as e:
                logger.error("%s\n%s\n%s", COMMUNICATION_ERROR, RHN_DISABLED,
                                           ustr(e))
                return
            except up2dateErrors.NoChannelsError:
                logger.error("%s\n%s", NOT_SUBSCRIBED_ERROR, CHANNELS_DISABLED)
                self._write_channels_file({})
                return
            except up2dateErrors.NoSystemIdError:
                logger.error("%s %s\n%s\n%s", NOT_SUBSCRIBED_ERROR,
                             NO_SYSTEM_ID_ERROR, USE_RHNREGISTER, RHN_DISABLED)
                return
            self.connected_to_spacewalk = True
            logger.info(UPDATES_FROM_SPACEWALK)

            for channel in svrChannels:
                if channel['version']:
                     enabled_channels[channel['label']] = dict(channel.items())
            self._write_channels_file(enabled_channels)

        repos = self.base.repos

        for (channel_id, channel_dict) in enabled_channels.items():
            cached_channel = cached_channels.get(channel_id)
            cached_version = None
            if cached_channel:
                cached_version = cached_channel.get('version')
            conf = copy(self.conf)
            if channel_id in self.parser.sections():
                options = self.parser.items(channel_id)
                for (key, value) in options:
                    setattr(conf, key, value)
            repo = SpacewalkRepo(channel_dict, {
                                    'cachedir'  : self.base.conf.cachedir,
                                    'proxy'     : proxy_url,
                                    'timeout'   : conf.timeout,
                                    'sslcacert' : sslcacert,
                                    'force_http': force_http,
                                    'cached_version' : cached_version,
                                    'login_info': login_info,
                                    'gpgcheck': conf.gpgcheck,
                                    'enabled': conf.enabled,
                                })
            repos.add(repo)

        # DEBUG
        logger.debug(enabled_channels)
コード例 #17
0
    def load(self, filename = None):
        if filename:
            self.fileName = filename
        if self.fileName == None:
            return
        if not os.access(self.fileName, os.R_OK):
#            print("warning: can't access %s" % self.fileName)
            return

        f = open(self.fileName, "r")

        multiline = ''
        for line in f.readlines():
            # strip comments
            if line.find('#') == 0:
                continue
            line = multiline + line.strip()
            if not line:
                continue

            # if line ends in '\', append the next line before parsing
            if line[-1] == '\\':
                multiline = line[:-1].strip()
                continue
            else:
                multiline = ''

            split = line.split('=', 1)
            if len(split) != 2:
                # not in 'a = b' format. we should log this
                # or maybe error.
                continue
            key = split[0].strip()
            value = ustr(split[1].strip())

            # decode a comment line
            comment = None
            pos = key.find("[comment]")
            if pos != -1:
                key = key[:pos]
                comment = value
                value = None

            # figure out if we need to parse the value further
            if value:
                # possibly split value into a list
                values = value.split(";")
                if key in ['proxyUser', 'proxyPassword']:
                    value = sstr(value.encode(locale.getpreferredencoding()))
                elif len(values) == 1:
                    try:
                        value = int(value)
                    except ValueError:
                        pass
                elif values[0] == "":
                    value = []
                else:
                    # there could be whitespace between the values on
                    # one line, let's strip it out
                    value = [val.strip() for val in values if val.strip() ]

            # now insert the (comment, value) in the dictionary
            newval = (comment, value)
            if key in self.dict: # do we need to update
                newval = self.dict[key]
                if comment is not None: # override comment
                    newval = (comment, newval[1])
                if value is not None: # override value
                    newval = (newval[0], value)
            self.dict[key] = newval
        f.close()
コード例 #18
0
ファイル: up2dateErrors.py プロジェクト: Bearlock/spacewalk
 def __init__(self, errmsg):
     errmsg = ustr(errmsg)
     PmBaseError.__init__(self, errmsg)
     self.value = 'rhn-plugin: ' + self.premsg + errmsg
     self.log = up2dateLog.initLog()
コード例 #19
0
ファイル: config.py プロジェクト: TJM/spacewalk
def convert_url_to_puny(url):
    """ returns url where hostname is converted to Punycode (RFC3492) """
    s = urlsplit(url)
    return sstr(urlunsplit((s[0], ustr(idn_ascii_to_puny(s[1])), s[2], s[3], s[4])))
コード例 #20
0
ファイル: config.py プロジェクト: TJM/spacewalk
def convert_url_from_puny(url):
    """ returns url where hostname is converted from Punycode (RFC3492). Returns unicode string. """
    s = urlsplit(url)
    return ustr(urlunsplit((s[0], idn_puny_to_unicode(s[1]), s[2], s[3], s[4])))
コード例 #21
0
ファイル: testConfig.py プロジェクト: zed/spacewalk
 def testConfigString(self):
     "Verify that Config loads a string as a string"
     cfg = config.initUp2dateConfig(test_up2date)
     assert type(cfg['systemIdPath']) == type(ustr(''))