Пример #1
0
def sanitizeValue(value, datatype):
    if isinstance(datatype, DBstring):
        if value is None or value == '':
            return None         # we really want to preserve Nones
            # and not depend on Oracle converting
            # empty strings to NULLs -- PostgreSQL
            # does not do this
        elif isinstance(value, UnicodeType):
            value = UnicodeType.encode(value, 'utf-8')
        if len(value) > datatype.limit:
            value = value[:datatype.limit]
            # ignore incomplete characters created after truncating
            value = value.decode('utf-8', 'ignore')
            value = value.encode('utf-8')
        return value
    if isinstance(datatype, DBblob):
        if value is None:
            value = ''
        if isinstance(value, UnicodeType):
            value = UnicodeType.encode(value, 'utf-8')
        return str(value)
    if value in [None, '']:
        return None
    if isinstance(datatype, DBdateTime):
        s = str(value)
        if len(s) == 10:
            # Pad it to be a real datetime
            s = s + " 00:00:00"
        return s
    if isinstance(datatype, DBdate):
        return str(value)[:10]
    if isinstance(datatype, DBint):
        return int(value)
    return value
Пример #2
0
def sanitizeValue(value, datatype):
    if isinstance(datatype, DBstring):
        if value is None or value == '':
            return None  # we really want to preserve Nones
            # and not depend on Oracle converting
            # empty strings to NULLs -- PostgreSQL
            # does not do this
        elif isinstance(value, UnicodeType):
            value = UnicodeType.encode(value, 'utf-8')
        if len(value) > datatype.limit:
            value = value[:datatype.limit]
            # ignore incomplete characters created after truncating
            value = value.decode('utf-8', 'ignore')
            value = value.encode('utf-8')
        return value
    if isinstance(datatype, DBblob):
        if value is None:
            value = ''
        if isinstance(value, UnicodeType):
            value = UnicodeType.encode(value, 'utf-8')
        return str(value)
    if value in [None, '']:
        return None
    if isinstance(datatype, DBdateTime):
        s = str(value)
        if len(s) == 10:
            # Pad it to be a real datetime
            s = s + " 00:00:00"
        return s
    if isinstance(datatype, DBdate):
        return str(value)[:10]
    if isinstance(datatype, DBint):
        return int(value)
    return value
Пример #3
0
 def populate(self, hash):
     ChangeLog.populate(self, hash)
     # Fix the time
     tm = self['time']
     if type(tm) in (IntType, LongType):
         # A UNIX timestamp
         self['time'] = localtime(tm)
     # In changelog, data is either in UTF-8, or in any other
     # undetermined encoding. Assume ISO-Latin-1 if not UTF-8.
     for i in ('text', 'name'):
         try:
             self[i] = UnicodeType(self[i], "utf-8")
         except UnicodeDecodeError:
             self[i] = UnicodeType(self[i], "iso-8859-1")
Пример #4
0
    def submit(self, system_id, action_id, result, message="", data={}):
        """ Submit the results of a queue run.
            Maps old and new rhn_check behavior to new database status codes

            The new API uses 4 slightly different status codes than the
            old client does.  This function will "hopefully" sensibly
            map them.  Old methodology:
               -rhn_check retrieves an action from the top of the action queue.
               -It attempts to execute the desired action and returns either
                   (a) 0   -- presumed successful.
                   (b) rhnFault object -- presumed failed
                   (c) some other non-fault object -- *assumed* successful.
               -Regardless of result code, action is marked as "executed"

            We try to make a smarter status selection (i.e. failed||completed).

            For reference:
            New DB status codes:      Old DB status codes:
                  0: Queued               0: queued
                  1: Picked Up            1: picked up
                  2: Completed            2: executed
                  3: Failed               3: completed
        """
        if type(action_id) is not IntType:
            # Convert it to int
            try:
                action_id = int(action_id)
            except ValueError:
                log_error("Invalid action_id", action_id)
                raise_with_tb(rhnFault(30, _("Invalid action value type %s (%s)") %
                               (action_id, type(action_id))), sys.exc_info()[2])
        # Authenticate the system certificate
        self.auth_system(system_id)
        log_debug(1, self.server_id, action_id, result)
        # check that the action is valid
        # We have a uniqueness constraint on (action_id, server_id)
        h = rhnSQL.prepare("""
            select at.label action_type,
                   at.trigger_snapshot,
                   at.name
              from rhnServerAction sa,
                   rhnAction a,
                   rhnActionType at
             where sa.server_id = :server_id
               and sa.action_id = :action_id
               and sa.status = 1
               and a.id = :action_id
               and a.action_type = at.id
        """)
        h.execute(server_id=self.server_id, action_id=action_id)
        row = h.fetchone_dict()
        if not row:
            log_error("Server %s does not own action %s" % (
                self.server_id, action_id))
            raise rhnFault(22, _("Action %s does not belong to server %s") % (
                action_id, self.server_id))

        action_type = row['action_type']
        trigger_snapshot = (row['trigger_snapshot'] == 'Y')

        if 'missing_packages' in data:
            missing_packages = "Missing-Packages: %s" % str(
                data['missing_packages'])
            rmsg = "%s %s" % (message, missing_packages)
        elif 'koan' in data:
            rmsg = "%s: %s" % (message, data['koan'])
        else:
            rmsg = message

        rcode = result
        # Careful with this one, result can be a very complex thing
        # and this processing is required for compatibility with old
        # rhn_check clients
        if type(rcode) == type({}):
            if "faultCode" in result:
                rcode = result["faultCode"]
            if "faultString" in result:
                rmsg = result["faultString"] + str(data)
        if type(rcode) in [type({}), type(()), type([])] \
                or type(rcode) is not IntType:
            rmsg = u"%s [%s]" % (UnicodeType(message), UnicodeType(rcode))
            rcode = -1
        # map to db codes.
        status = self.status_for_action_type_code(action_type, rcode)

        if status == 3:
            # Failed action - invalidate children
            self._invalidate_child_actions(action_id)
        elif action_type == 'reboot.reboot':
            # reboot action should stay as pickup
            rhnSQL.commit()
            return 0
        elif status == 2 and trigger_snapshot and self.__should_snapshot():
            # if action status is 'Completed', snapshot if allowed and if needed
            self.server.take_snapshot("Scheduled action completion:  %s" % row['name'])

        self.__update_action(action_id, status, rcode, rmsg)

        # Store the status in a flag - easier than to complicate the action
        # plugin API by adding a status
        rhnFlags.set('action_id', action_id)
        rhnFlags.set('action_status', status)

        self.process_extra_data(self.server_id, action_id, data=data,
                                action_type=action_type)

        # commit, because nobody else will
        rhnSQL.commit()
        return 0
Пример #5
0
def to_unicode(obj):
    if isinstance(obj, StringType):
        return UnicodeType(obj, 'utf8')
    else:
        return obj