예제 #1
0
파일: utils.py 프로젝트: crudbug/canopsis
    def test_forceUTF8(self):
        """Test the forceUTF8 function.
        """
        notutf8 = "é"
        utf8 = unicode(notutf8, "utf-8") if PYVER < "3" else notutf8

        data_to_check = notutf8
        result = forceUTF8(data_to_check)
        self.assertEqual(result, utf8)

        data_to_check = {notutf8: notutf8, utf8: utf8, 1: 1}
        result = forceUTF8(data_to_check)
        data_to_compere = data_to_check if PYVER < "3" else {utf8: utf8, 1: 1}
        self.assertEqual(str(result), str(data_to_compere))

        data_to_check = [notutf8, utf8, 1]
        result = forceUTF8(data_to_check)
        self.assertEqual(result, [utf8, utf8, 1])

        data_to_check = (notutf8, utf8, 1)
        result = forceUTF8(data_to_check)
        self.assertEqual(result, (utf8, utf8, 1))

        data_to_check = {notutf8, utf8, 1}
        result = forceUTF8(data_to_check)
        self.assertEqual(result, {utf8, 1})
예제 #2
0
    def test_forceUTF8(self):
        """Test the forceUTF8 function.
        """
        notutf8 = "é"
        utf8 = unicode(notutf8, "utf-8") if PYVER < "3" else notutf8

        data_to_check = notutf8
        result = forceUTF8(data_to_check)
        self.assertEqual(result, utf8)

        data_to_check = {notutf8: notutf8, utf8: utf8, 1: 1}
        result = forceUTF8(data_to_check)
        data_to_compere = data_to_check if PYVER < "3" else {utf8: utf8, 1: 1}
        self.assertEqual(str(result), str(data_to_compere))

        data_to_check = [notutf8, utf8, 1]
        result = forceUTF8(data_to_check)
        self.assertEqual(result, [utf8, utf8, 1])

        data_to_check = (notutf8, utf8, 1)
        result = forceUTF8(data_to_check)
        self.assertEqual(result, (utf8, utf8, 1))

        data_to_check = {notutf8, utf8, 1}
        result = forceUTF8(data_to_check)
        self.assertEqual(result, {utf8, 1})
예제 #3
0
    def work(self, body, msg, *args, **kargs):
        ## Sanity Checks
        rk = msg.delivery_info['routing_key']
        if not rk:
            raise Exception("Invalid routing-key '%s' (%s)" % (rk, body))

        #self.logger.info( body )
        ## Try to decode event
        if isinstance(body, dict):
            event = body
            # force utf8 only if python version is 2
            if PYVER < '3':
                event = forceUTF8(event)
        else:
            self.logger.debug(" + Decode JSON")
            try:
                if isinstance(body, basestring):
                    try:
                        event = loads(body)
                        self.logger.debug("   + Ok")
                    except Exception as err:
                        try:
                            self.logger.debug(" + Try hack for windows string")
                            # Hack for windows FS -_-
                            event = loads(body.replace('\\', '\\\\'))
                            self.logger.debug("   + Ok")
                        except Exception as err:
                            try:
                                self.logger.debug(" + Decode BSON")
                                bson = BSON(body)
                                event = bson.decode()
                                self.logger.debug("   + Ok")
                            except Exception as err:
                                raise Exception(err)

            except Exception as err:
                self.logger.error("   + Failed (%s)" % err)
                self.logger.debug("RK: '%s', Body:" % rk)
                self.logger.debug(body)
                raise Exception("Impossible to parse event '%s'" % rk)

        event['rk'] = ensure_unicode(rk)

        if "resource" in event:
            if not isinstance(event['resource'], basestring):
                event['resource'] = ''
            else:
                event['resource'] = ensure_unicode(event['resource'])
            if not event['resource']:
                del event['resource']

        # Clean tags field
        event['tags'] = event.get('tags', [])

        tags = event['tags']

        if isinstance(tags, basestring) and tags != "":
            event['tags'] = [event['tags']]

        elif not isinstance(tags, list):
            event['tags'] = []

        event["timestamp"] = int(event.get("timestamp", time()))

        event["state"] = event.get("state", 0)
        event["state_type"] = event.get("state_type", 1)
        event["event_type"] = event.get("event_type", "check")

        default_status = 0 if not event["state"] else 1
        event["status"] = event.get("status", default_status)

        event['output'] = event.get('output', '')

        # Get perfdata
        perf_data = event.get('perf_data')
        perf_data_array = event.get('perf_data_array')

        if perf_data_array is None:
            perf_data_array = []

        # Parse perfdata
        if perf_data:
            self.logger.debug(u' + perf_data: {0}'.format(perf_data))

            try:
                perf_data_array += PerfDataParser(perf_data).perf_data_array

            except Exception as err:
                self.logger.error(
                    "Impossible to parse perfdata from: {0} ({1})".format(
                        event, err
                    )
                )

            event['perf_data_array'] = perf_data_array

        return event
예제 #4
0
    def work(self, body, msg, *args, **kargs):
        ## Sanity Checks
        rk = msg.delivery_info['routing_key']
        if not rk:
            raise Exception("Invalid routing-key '%s' (%s)" % (rk, body))

        #self.logger.info( body )
        ## Try to decode event
        if isinstance(body, dict):
            event = body
            # force utf8 only if python version is 2
            if PYVER < '3':
                event = forceUTF8(event)
        else:
            self.logger.debug(" + Decode JSON")
            try:
                if isinstance(body, basestring):
                    try:
                        event = loads(body)
                        self.logger.debug("   + Ok")
                    except Exception as err:
                        try:
                            self.logger.debug(" + Try hack for windows string")
                            # Hack for windows FS -_-
                            event = loads(body.replace('\\', '\\\\'))
                            self.logger.debug("   + Ok")
                        except Exception as err:
                            try:
                                self.logger.debug(" + Decode BSON")
                                bson = BSON(body)
                                event = bson.decode()
                                self.logger.debug("   + Ok")
                            except Exception as err:
                                raise Exception(err)

            except Exception as err:
                self.logger.error("   + Failed (%s)" % err)
                self.logger.debug("RK: '%s', Body:" % rk)
                self.logger.debug(body)
                raise Exception("Impossible to parse event '%s'" % rk)

        event['rk'] = ensure_unicode(rk)

        if event.get("resource", ''):
            if not isinstance(event['resource'], basestring):
                event['resource'] = ''
            else:
                event['resource'] = ensure_unicode(event['resource'])
            if not event['resource']:
                del event['resource']

        # Clean tags field
        event['tags'] = event.get('tags', [])

        tags = event['tags']

        if isinstance(tags, basestring) and tags != "":
            event['tags'] = [event['tags']]

        elif not isinstance(tags, list):
            event['tags'] = []

        event['timestamp'] = int(event.get('timestamp', time()))

        try:
            event['state'] = int(event.get('state', 0))
        except (ValueError, TypeError, AttributeError):
            self.logger.error(
                'state convertion failed: must be an int ({})'.format(event))
            event['state'] = 0

        event['state_type'] = event.get('state_type', 1)
        event['event_type'] = event.get('event_type', 'check')

        default_status = 0 if not event["state"] else 1
        event['status'] = event.get("status", default_status)

        event['output'] = event.get('output', '')

        # Get perfdata
        perf_data = event.get('perf_data')
        perf_data_array = event.get('perf_data_array')

        if perf_data_array is None:
            perf_data_array = []

        # Parse perfdata
        if perf_data:
            self.logger.debug(u' + perf_data: {0}'.format(perf_data))

            try:
                perf_data_array += PerfDataParser(perf_data).perf_data_array

            except Exception as err:
                self.logger.error(
                    "Impossible to parse perfdata from: {0} ({1})".format(
                        event, err))

            event['perf_data_array'] = perf_data_array

        return event