Beispiel #1
0
 def __init__(self, dict, db, sql, rowid, cache = None):
     UserDictCase.__init__(self, dict)
     if not isinstance(db, sql_base.Database):
         raise TypeError, "Second argument needs to be a database handle"
     self.__db = db
     self.__sql = sql
     self.__rowid = rowid
     self.__cache = cache
    def add_hardware(self, hardware):
        log_debug(4, hardware)
        if not hardware:
            return -1
        if type(hardware) == type({}):
            hardware = UserDictCase(hardware)
        if not isinstance(hardware, UserDictCase):
            log_error("argument type is not  hash: %s" % hardware)
            raise TypeError, "This function requires a hash as an argument"
        # validation is important
        hw_class = hardware.get("class")
        if hw_class is None:
            return -1
        hw_class = string.lower(hw_class)

        class_type = None
        
        if hw_class in ["video", "audio", "audio_hd", "usb", "other", "hd", "floppy",
                        "mouse", "modem", "network", "cdrom", "scsi",
                        "unspec", "scanner", "tape", "capture", "raid",
                        "socket", "keyboard", "printer", "firewire", "ide"]:
            class_type = HardwareDevice
        elif hw_class == "cpu":
            class_type = CPUDevice
        elif hw_class == "netinfo":
            class_type = NetworkInformation
        elif hw_class == "memory":
            class_type = MemoryInformation
        elif hw_class == "dmi":
            class_type = DMIInformation
        elif hw_class == "installinfo":
            class_type = InstallInformation
        elif hw_class == "netinterfaces":
            class_type = NetIfaceInformation
        else:
            log_error("UNKNOWN CLASS TYPE `%s'" % hw_class)
            # Same trick: try-except and raise the exception so that Traceback
            # can send the e-mail
            try:
                raise KeyError, "Unknwon class type `%s' for hardware '%s'" % (
                    hw_class, hardware)
            except:
                Traceback(mail=1)
                return

        # create the new device
        new_dev = class_type(hardware)
        
        if self.__hardware.has_key(class_type):
            _l = self.__hardware[class_type]
        else:
            _l = self.__hardware[class_type] = []
        _l.append(new_dev)
        self.__changed = 1
        return 0
class Device(GenericDevice):
    def __init__(self, table, fields, dict = None, mapping = None):
        GenericDevice.__init__(self, table)
        x = {}
        for k in fields:
            x[k] = None
        self.data = UserDictCase(x)
        if dict is None:
            return
        # make sure we get a UserDictCase to work with
        if type(dict) == type({}):
            dict = UserDictCase(dict)
        if mapping is None or type(mapping) == type({}):
            mapping = UserDictCase(mapping)
        if not isinstance(dict, UserDictCase) or \
           not isinstance(mapping, UserDictCase):
            log_error("Argument passed is not a dictionary", dict, mapping)
            raise TypeError("Argument passed is not a dictionary",
                            dict, mapping)
        # make sure we have a platform       
        for k in dict.keys():                        
            if self.data.has_key(k):
                self.data[k] = dict[k]
                continue
            if mapping.has_key(k):
                # the mapping dict might tell us to lose some fields
                if mapping[k] is not None:
                    self.data[mapping[k]] = dict[k]
            else:
                log_error("Unknown HW key =`%s'" % k,
                          dict.dict(), mapping.dict())
                # The try-except is added just so that we can send e-mails
                try:
                    raise KeyError("Don't know how to parse key `%s''" % k,
                                   dict.dict())
                except:
                    Traceback(mail=1)
                    # Ignore this key
                    continue
        # clean up this data
        try:
            for k in self.data.keys():
                if type(self.data[k]) == type("") and len(self.data[k]):
                    self.data[k] = string.strip(self.data[k])
                    if not len(self.data[k]):
                        continue
                    if self.data[k][0] == '"' and self.data[k][-1] == '"':
                        self.data[k] = self.data[k][1:-1]
        except IndexError:
            raise IndexError, "Can not process data = %s, key = %s" % (
                repr(self.data), k)
Beispiel #4
0
    def __init__(self, db, table, hashname, hashval = None):
        UserDictCase.__init__(self)
        if not isinstance(db, sql_base.Database):
            raise rhnException("Argument db is not a database instance", db)
        self.db = db              
        self.table = table
        self.hashname = string.lower(hashname)

        # and the data dictionary
        self.data = {}
        # is this a real entry (ie, use insert or update)
        self.real = 0
        if hashval is not None: # if we have to load an entry already...
            self.load(hashval)
    def __init__(self, req):
        rhnHandler.__init__(self)
        dumper.XML_Dumper.__init__(self)
        self.headers_out = UserDictCase()
        self._raw_stream = req
        self._raw_stream.content_type = 'application/octet-stream'
        # State machine
        self._headers_sent = 0
        self._is_closed = 0
        self._compressed_stream = None

        # Don't check for abuse
        self.check_for_abuse = 0

        self.functions = [
            'arches',
            'arches_extra',
            'channel_families',
            'channels',
            'get_comps',
            'channel_packages_short',
            'packages_short',
            'packages',
            'source_packages',
            'errata',
            'blacklist_obsoletes',
            'product_names',
            'get_rpm',
            'get_source_rpm',
            'kickstartable_trees',
            'get_ks_file',
        ]

        self.system_id = None
        self._channel_family_query_template = """
            select cfm.channel_family_id, 0 quantity
              from rhnChannelFamilyMembers cfm,
                   rhnChannel c, rhnChannelFamily cf
             where cfm.channel_id = c.id
               and c.label in (%s)
               and cfm.channel_family_id = cf.id
               and cf.label != 'rh-public'
            union
            select id channel_family_id, NULL quantity
              from rhnChannelFamily
             where label = 'rh-public'
        """
        self._channel_family_query_public = """
            select id channel_family_id, 0 quantity
              from rhnChannelFamily
        """
        self._channel_family_query = None
    def _executemany(self, *args, **kwargs):
        if not kwargs:
            return 0

        params = UserDictCase(kwargs)

        # First break all the incoming keyword arg lists into individual
        # hashes:
        all_kwargs = []
        for key in params.keys():
            if len(all_kwargs) < len(params[key]):
                for i in range(len(params[key])):
                    all_kwargs.append({})

            i = 0
            for val in params[key]:
                all_kwargs[i][key] = val
                i = i + 1

        self._real_cursor.executemany(self.sql, all_kwargs)
        self.description = self._real_cursor.description
        rowcount = self._real_cursor.rowcount
        return rowcount
class NonAuthenticatedDumper(rhnHandler, dumper.XML_Dumper):
    def __init__(self, req):
        rhnHandler.__init__(self)
        dumper.XML_Dumper.__init__(self)
        self.headers_out = UserDictCase()
        self._raw_stream = req
        self._raw_stream.content_type = 'application/octet-stream'
        # State machine
        self._headers_sent = 0
        self._is_closed = 0
        self._compressed_stream = None

        # Don't check for abuse
        self.check_for_abuse = 0

        self.functions = [
            'arches',
            'arches_extra',
            'channel_families',
            'channels',
            'get_comps',
            'channel_packages_short',
            'packages_short',
            'packages',
            'source_packages',
            'errata',
            'blacklist_obsoletes',
            'product_names',
            'get_rpm',
            'get_source_rpm',
            'kickstartable_trees',
            'get_ks_file',
        ]

        self.system_id = None
        self._channel_family_query_template = """
            select cfm.channel_family_id, 0 quantity
              from rhnChannelFamilyMembers cfm,
                   rhnChannel c, rhnChannelFamily cf
             where cfm.channel_id = c.id
               and c.label in (%s)
               and cfm.channel_family_id = cf.id
               and cf.label != 'rh-public'
            union
            select id channel_family_id, NULL quantity
              from rhnChannelFamily
             where label = 'rh-public'
        """
        self._channel_family_query_public = """
            select id channel_family_id, 0 quantity
              from rhnChannelFamily
        """
        self._channel_family_query = None

    def _send_headers(self, error=0, init_compressed_stream=1):
        log_debug(4, "is_closed", self._is_closed)
        if self._is_closed:
            raise Exception, "Trying to write to a closed connection"
        if self._headers_sent:
            return
        self._headers_sent = 1
        if self.compress_level:
            self.headers_out['Content-Encoding'] = 'gzip'
        # Send the headers
        if error:
            # No compression
            self.compress_level = 0
            self._raw_stream.content_type = 'text/xml'
        for h, v in self.headers_out.items():
            self._raw_stream.headers_out[h] = str(v)
        self._raw_stream.send_http_header()
        # If need be, start gzipping
        if self.compress_level and init_compressed_stream:
            log_debug(4, "Compressing with factor %s" % self.compress_level)
            self._compressed_stream = gzip.GzipFile(None, "wb",
                self.compress_level, self._raw_stream)

    def send(self, data):
        log_debug(3, "Sending %d bytes" % len(data))
        try:
            self._send_headers()
            if self._compressed_stream:
                log_debug(4, "Sending through a compressed stream")
                self._compressed_stream.write(data)
            else:
                self._raw_stream.write(data)
        except IOError:
            log_error("Client appears to have closed connection")
            self.close()
            raise dumper.ClosedConnectionError
        log_debug(5, "Bytes sent", len(data))

    write = send

    def close(self):
        log_debug(2, "Closing")
        if self._is_closed:
            log_debug(3, "Already closed")
            return

        if self._compressed_stream:
            log_debug(5, "Closing a compressed stream")
            try:
                self._compressed_stream.close()
            except IOError, e:
                # Remote end has closed connection already
                log_error("Error closing the stream", str(e))
                pass
            self._compressed_stream = None
        self._is_closed = 1
        log_debug(3, "Closed")
Beispiel #8
0
    def set_info(self, name, value):
        log_debug(3, name, value)
        # translation from what the client send us to real names of the fields
        # in the tables.
        mapping = {
            "first_name" : "first_names",
            "position"   : "title",
            "title"      : "prefix"
            }       
        if not name:
            return -1
        name = string.lower(name)
        if type(value) == type(""):
            value = string.strip(value)
        # We have to watch over carefully for different field names
        # being sent from rhn_register (up2date --register)
        changed = 0

        # translation
        if name in mapping.keys():
            name = mapping[name]
        # Some fields can not have null string values
        if name in ["first_names", "last_name", "prefix", # personal_info
                    "address1", "city", "country"]:       # site_info
            # we require something of it
            if len(str(value)) == 0:
                return -1
        # fields in personal_info (and some in site)
        if name in ["last_name", "first_names",
                    "company", "phone", "fax", "email", "title"]:
            self.info[name] = value[:128]
            changed = 1            
        elif name == "prefix":
            values = ["Mr.", "Mrs.", "Ms.", "Dr.", "Hr.", "Sr."]
            # Now populate a dictinary of valid values
            valids = UserDictCase()
            for v in values: # initialize from good values, with and w/o the dot
                valids[v] = v
                valids[v[:-1]] = v
            # commonly encountered values            
            valids["Miss"] = "Miss"
            valids["Herr"] = "Hr."
            valids["Sig."] = "Sr."
            valids["Sir"]  = "Mr."
            # Now check it out
            if valids.has_key(value):
                self.info["prefix"] = valids[value]
                changed = 1
            else:
                log_error("Unknown prefix value `%s'. Assumed `Mr.' instead"
                          % value)
                self.info["prefix"] = "Mr."
                changed = 1

        # fields in site
        if name in ["phone", "fax", "zip"]:
            self.site[name] = value[:32]
            changed = 1
        elif name in ["city",  "country", "alt_first_names", "alt_last_name",
                      "address1", "address2", "email",
                      "last_name", "first_names"]:
            if name == "last_name":
                self.site["alt_last_name"] = value
                changed = 1
            elif name == "first_names":
                self.site["alt_first_names"] = value
                changed = 1
            else:
                self.site[name] = value[:128]
                changed = 1
        elif name in ["state"]: # stupid people put stupid things in here too
            self.site[name] = value[:60]
            changed = 1
        if not changed:
            log_error("SET_INFO: Unknown info `%s' = `%s'" % (name, value))
        return 0
Beispiel #9
0
 def __init__(self):
     self.server = UserDictCase()
     Packages.__init__(self)
     History.__init__(self)
     Hardware.__init__(self)
     SolarisPatches.__init__(self)
Beispiel #10
0
class ServerWrapper(Packages, Hardware, History, SolarisPatches):
    def __init__(self):
        self.server = UserDictCase()
        Packages.__init__(self)
        History.__init__(self)
        Hardware.__init__(self)
        SolarisPatches.__init__(self)

    def __repr__(self):
        return "<%s instance>" % (self.__class__,)
    
    # update a value in self.server
    def set_value(self, name, value):
        if name is None or value is None:
            return -1
        self.server[name] = value
        return 0    

    ###
    ### PACKAGES
    ###
    
    # Wrappers for the similar functions from Packages class that supplementaly
    # require a valid sysid.
    def add_package(self, entry):
        if entry['name'].startswith("patch-solaris"):
            SolarisPatches.add_patch(self, self.server.get("id"), entry)
        return Packages.add_package(self, self.server.get("id"), entry)
    
    def delete_package(self, entry):
        return Packages.delete_package(self, self.server.get("id"), entry)
    
    def dispose_packages(self):
        SolarisPatches.dispose_patched_packages(self, self.server["id"])
        return Packages.dispose_packages(self, self.server["id"])

    # wrapper for the Packages.save_packages_byid() which requires the sysid
    def save_packages(self, schedule=1):
        SolarisPatches.save_patched_packages(self, self.server["id"])
        ret = self.save_packages_byid(self.server["id"], schedule=schedule)
        # this function is primarily called from outside
        # so we have to commit here
        rhnSQL.commit()
        return ret
        # wrapper for the Packages.reload_packages_byid() which requires the
        # sysid
    def reload_packages(self):
        ret = self.reload_packages_byid(self.server["id"])
        return ret

    ###
    ### HARDWARE
    ###
    
    # Wrappers for the similar functions from Hardware class
    def delete_hardware(self):
        return Hardware.delete_hardware(self, self.server.get("id"))
    # wrapper for the Hardware.save_hardware_byid() which requires the sysid
    def save_hardware(self):
        ret = self.save_hardware_byid(self.server["id"])
        # this function is primarily called from outside
        # so we have to commit here
        rhnSQL.commit()
        return ret   
    # wrapper for the Hardware.reload_hardware_byid() which requires the sysid
    def reload_hardware(self):
        ret = self.reload_hardware_byid(self.server["id"])
        return ret

    ###
    ### HISTORY
    ###
    def save_history(self):
        ret = self.save_history_byid(self.server["id"])
        # this function is primarily called from outside
        # so we have to commit here
        rhnSQL.commit()
        return ret