Ejemplo n.º 1
0
 def setUp(self):
     self.config = {
             "snmp": {
                 "transport": {
                     "listen_address": "127.0.0.1",
                     "listen_port": 1620,
                     "udp": {
                         "enabled": True
                     },
                     "tcp": {
                         "enabled": False 
                     }
                 },
                 "auth": {
                     "version2": {
                         "community": "public",
                         "enabled": True
                     },
                     "version3": {
                         "enabled": True,
                         "users": {
                         }
                     }
                 }
             }
         }
     self.mibs = MibResolver()
     self.traps = []
     self.trap_receiver_thread = TrapReceiverThread(self.config, self.mibs, self._trap_receiver_callback)
     self.trap_receiver_thread.setDaemon(1)
     self.trap_receiver_thread.start()
Ejemplo n.º 2
0
    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(self._config['daemon']['trap_file'])

        LOG.debug("SensuTrapServer: Initialized")
Ejemplo n.º 3
0
    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(self._config['daemon']['trap_file'])

        LOG.debug("SensuTrapServer: Initialized")
Ejemplo n.º 4
0
class SensuTrapServer(object):
    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(
            self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(
            self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(
            self._config['daemon']['trap_path'])

        LOG.debug("SensuTrapServer: Initialized")

    def _configure_mibs(self):
        self._mibs = MibResolver(self._config['mibs']['paths'],
                                 self._config['mibs']['mibs'])

    def _parse_trap_handlers(self, trap_path):
        LOG.debug(
            "SensuTrapServer: Parsing trap handler files in '%s' directory" %
            trap_path)

        trap_handlers = dict()
        files = [f for f in listdir(trap_path) if isfile(join(trap_path, f))]

        for trap_file in files:
            try:
                LOG.debug("SensuTrapServer: Parsing trap handler file: %s" %
                          (trap_file))
                fh = open(join(trap_path, trap_file), 'r')
                trap_file_data = json.load(fh)
                for trap_handler_id, trap_handler_config in trap_file_data.items(
                ):
                    # Load TrapHandler
                    trap_handler = self._load_trap_handler(
                        trap_handler_id, trap_handler_config)
                    trap_handlers[trap_handler_id] = trap_handler
                    LOG.debug("SensuTrapServer: Parsed trap handler: %s" %
                              (trap_handler_id))
            finally:
                fh.close()

        return trap_handlers

    def _load_trap_handler(self, trap_handler_id, trap_handler_config):
        # Parse trap type
        trap_type_module, trap_type_symbol = tuple(
            trap_handler_config['trap']['type'])
        # TODO: handle OIDs as trap types
        trap_type_oid = self._mibs.lookup(trap_type_module, trap_type_symbol)

        #LOG.debug("%s type=%s::%s (%r)" % (trap_handler_id, trap_type_module, trap_type_symbol, trap_type_oid))

        # Parse trap arguments
        trap_args = dict()
        if 'args' in trap_handler_config['trap']:
            for trap_arg, trap_arg_type in trap_handler_config['trap'][
                    'args'].items():
                trap_arg_type_module, trap_arg_type_symbol = tuple(
                    trap_arg_type)
                # TODO: handle OIDs as trap arg type
                trap_arg_type_oid = self._mibs.lookup(trap_arg_type_module,
                                                      trap_arg_type_symbol)
                trap_args[trap_arg_type_oid] = trap_arg

                #LOG.debug("%s arg=%s type=%s::%s (%r)" % (trap_handler_id,
                #                                            trap_arg,
                #                                            trap_arg_type_module,
                #                                            trap_arg_type_symbol,
                #                                            trap_arg_type_oid))

        # Parse event info
        event_name = trap_handler_config['event']['name']
        event_output = trap_handler_config['event']['output']
        event_handlers = trap_handler_config['event']['handlers']
        event_source = trap_handler_config['event']['source']
        event_severity = parse_event_severity(
            trap_handler_config['event']['severity'])

        # TODO: parse predicates

        # Initialize TrapHandler
        trap_handler = TrapHandler(trap_type_oid, trap_args, event_name,
                                   event_output, event_handlers,
                                   event_severity, event_source, None)
        return trap_handler

    def _dispatch_trap_event(self, trap_event):
        self._trap_event_dispatcher_thread.dispatch(trap_event)

    def _handle_trap(self, trap):
        LOG.info("SensuTrapServer: Received Trap: %s" % (trap))

        # Find TrapHandler for this Trap
        trap_handler = None
        for trap_handler_id, th in self._trap_handlers.items():
            if th.handles(trap):
                LOG.info("SensuTrapServer: %s handling trap %r" %
                         (trap_handler_id, trap))
                # Transform Trap
                trap_event = th.transform(trap)
                # Dispatch TrapEvent
                self._dispatch_trap_event(trap_event)
                return
        LOG.warning("No trap handler found for %r" % (trap))
        # TODO: add default handler here for unmatched traps?

    def stop(self):
        if not self._run:
            return
        self._run = False

        # Stop TrapReceiverThread
        self._trap_receiver_thread.stop()

        # Stop TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.stop()

    def run(self):
        LOG.debug("SensuTrapServer: Started")
        self._run = True

        # Start TrapReceiverThread
        self._trap_receiver_thread.start()

        # Start TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.start()

        while self._run:
            time.sleep(1)

        # Wait for our threads to stop
        self._trap_receiver_thread.join()
        self._trap_event_dispatcher_thread.join()
        LOG.debug("SensuTrapServer: Exiting")
Ejemplo n.º 5
0
class SensuTrapServer(object):

    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(self._config['daemon']['trap_file'])

        LOG.debug("SensuTrapServer: Initialized")

    def _configure_mibs(self):
        try:
            self._mibs = MibResolver(self._config['mibs']['paths'], self._config['mibs']['mibs'])
        except Exception as e:
            LOG.debug(str(e))
            raise


    def _parse_trap_handlers(self, trap_file):
        # TODO: Support multiple trap files
        LOG.debug("SensuTrapServer: Parsing trap handler file: %s" % (trap_file))
        trap_handlers = dict()
        try:
            fh = open(trap_file, 'r')
            trap_file_data = json.load(fh)
            for trap_handler_id, trap_handler_config in trap_file_data.items():
                # Load TrapHandler
                trap_handler = self._load_trap_handler(trap_handler_id, trap_handler_config)
                trap_handlers[trap_handler_id] = trap_handler
                LOG.debug("SensuTrapServer: Parsed trap handler: %s" % (trap_handler_id))
        except Exception as e:
            LOG.debug(str(e))
        finally:
            fh.close()
        return trap_handlers

    def _load_trap_handler(self, trap_handler_id, trap_handler_config):
        # Parse trap type
        trap_type_module, trap_type_symbol = tuple(trap_handler_config['trap']['type'])
        # TODO: handle OIDs as trap types
        trap_type_oid = self._mibs.lookup(trap_type_module, trap_type_symbol)

        #LOG.debug("%s type=%s::%s (%r)" % (trap_handler_id, trap_type_module, trap_type_symbol, trap_type_oid))

        # Parse trap arguments
        trap_args = dict()
        if 'args' in trap_handler_config['trap']:
            for trap_arg, trap_arg_type in trap_handler_config['trap']['args'].items():
                trap_arg_type_module, trap_arg_type_symbol = tuple(trap_arg_type)
                # TODO: handle OIDs as trap arg type
                trap_arg_type_oid = self._mibs.lookup(trap_arg_type_module, trap_arg_type_symbol)
                trap_args[trap_arg_type_oid] = trap_arg

        # Initialize TrapHandler
        trap_handler = TrapHandler(trap_type_oid,
                                   trap_args,
                                   trap_handler_config['event'])
        return trap_handler

    def _dispatch_trap_event(self, trap_event):
        self._trap_event_dispatcher_thread.dispatch(trap_event)

    def _handle_trap(self, trap):
        LOG.info("SensuTrapServer: Received Trap: %s" % (trap))

        # Find TrapHandler for this Trap 
        trap_handler = None
        for trap_handler_id, th in self._trap_handlers.items():
            if th.handles(trap):
                LOG.info("SensuTrapServer: %s handling trap %r" % (trap_handler_id, trap))
                # Transform Trap
                trap_event = th.transform(trap)
                # Dispatch TrapEvent
                self._dispatch_trap_event(trap_event)
                return
        LOG.warning("No trap handler found for %r" % (trap))

    def stop(self):
        if not self._run:
            return
        self._run = False

        # Stop TrapReceiverThread
        self._trap_receiver_thread.stop()

        # Stop TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.stop()

    def run(self):
        LOG.debug("SensuTrapServer: Started")
        self._run = True

        # Start TrapReceiverThread
        self._trap_receiver_thread.start()

        # Start TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.start()

        while self._run:
            time.sleep(1)

        # Wait for our threads to stop
        self._trap_receiver_thread.join()
        self._trap_event_dispatcher_thread.join()
        LOG.debug("SensuTrapServer: Exiting")
Ejemplo n.º 6
0
class SensuTrapServer(object):
    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(
            self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(
            self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(
            self._config['daemon']['trap_file'])

        LOG.debug("SensuTrapServer: Initialized")

    def _configure_mibs(self):
        try:
            self._mibs = MibResolver(self._config['mibs']['paths'],
                                     self._config['mibs']['mibs'])
        except Exception as e:
            LOG.debug(str(e))
            raise

    def _parse_trap_handlers(self, trap_file):
        # TODO: Support multiple trap files
        LOG.debug("SensuTrapServer: Parsing trap handler file: %s" %
                  (trap_file))
        trap_handlers = dict()
        try:
            fh = open(trap_file, 'r')
            trap_file_data = json.load(fh)
            for trap_handler_id, trap_handler_config in trap_file_data.items():
                # Load TrapHandler
                trap_handler = self._load_trap_handler(trap_handler_id,
                                                       trap_handler_config)
                trap_handlers[trap_handler_id] = trap_handler
                LOG.debug("SensuTrapServer: Parsed trap handler: %s" %
                          (trap_handler_id))
        except Exception as e:
            LOG.debug(str(e))
        finally:
            fh.close()
        return trap_handlers

    def _load_trap_handler(self, trap_handler_id, trap_handler_config):
        # Parse trap type
        trap_type_module, trap_type_symbol = tuple(
            trap_handler_config['trap']['type'])
        # TODO: handle OIDs as trap types
        trap_type_oid = self._mibs.lookup(trap_type_module, trap_type_symbol)

        #LOG.debug("%s type=%s::%s (%r)" % (trap_handler_id, trap_type_module, trap_type_symbol, trap_type_oid))

        # Parse trap arguments
        trap_args = dict()
        if 'args' in trap_handler_config['trap']:
            for trap_arg, trap_arg_type in trap_handler_config['trap'][
                    'args'].items():
                trap_arg_type_module, trap_arg_type_symbol = tuple(
                    trap_arg_type)
                # TODO: handle OIDs as trap arg type
                trap_arg_type_oid = self._mibs.lookup(trap_arg_type_module,
                                                      trap_arg_type_symbol)
                trap_args[trap_arg_type_oid] = trap_arg

        # Initialize TrapHandler
        trap_handler = TrapHandler(trap_type_oid, trap_args,
                                   trap_handler_config['event'])
        return trap_handler

    def _dispatch_trap_event(self, trap_event):
        self._trap_event_dispatcher_thread.dispatch(trap_event)

    def _handle_trap(self, trap):
        LOG.info("SensuTrapServer: Received Trap: %s" % (trap))

        # Find TrapHandler for this Trap
        trap_handler = None
        for trap_handler_id, th in self._trap_handlers.items():
            if th.handles(trap):
                LOG.info("SensuTrapServer: %s handling trap %r" %
                         (trap_handler_id, trap))
                # Transform Trap
                trap_event = th.transform(trap)
                # Dispatch TrapEvent
                self._dispatch_trap_event(trap_event)
                return
        LOG.warning("No trap handler found for %r" % (trap))

    def stop(self):
        if not self._run:
            return
        self._run = False

        # Stop TrapReceiverThread
        self._trap_receiver_thread.stop()

        # Stop TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.stop()

    def run(self):
        LOG.debug("SensuTrapServer: Started")
        self._run = True

        # Start TrapReceiverThread
        self._trap_receiver_thread.start()

        # Start TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.start()

        while self._run:
            time.sleep(1)

        # Wait for our threads to stop
        self._trap_receiver_thread.join()
        self._trap_event_dispatcher_thread.join()
        LOG.debug("SensuTrapServer: Exiting")
Ejemplo n.º 7
0
class TrapReceiverTestCase(unittest.TestCase):

    def setUp(self):
        self.config = {
                "snmp": {
                    "transport": {
                        "listen_address": "127.0.0.1",
                        "listen_port": 1620,
                        "udp": {
                            "enabled": True
                        },
                        "tcp": {
                            "enabled": False 
                        }
                    },
                    "auth": {
                        "version2": {
                            "community": "public",
                            "enabled": True
                        },
                        "version3": {
                            "enabled": True,
                            "users": {
                            }
                        }
                    }
                }
            }
        self.mibs = MibResolver()
        self.traps = []
        self.trap_receiver_thread = TrapReceiverThread(self.config, self.mibs, self._trap_receiver_callback)
        self.trap_receiver_thread.setDaemon(1)
        self.trap_receiver_thread.start()

    def tearDown(self):
        self.traps = []
        self.trap_receiver_thread.stop()
        self.trap_receiver_thread.join()

    def send_trap(self, notification_trap, notification_args=None):
        if notification_args is None:
            notification_args = dict()
        return self.send_notification('trap', notification_trap, notification_args)

    def send_inform(self, notification_trap, notification_args=None):
        if notification_args is None:
            notification_args = dict()
        return self.send_notification('inform', notification_trap, notification_args)

    def send_notification(self, notify_type, notification_trap, notification_args):
        agent_host = self.config['snmp']['transport']['listen_address']
        agent_port = self.config['snmp']['transport']['listen_port']
        community = self.config['snmp']['auth']['version2']['community']

        # Initialize Notification Originator
        notifier = ntforg.NotificationOriginator()

        # Build Tarp Argument List
        varbinds = []
        for varName, val in notification_args.items():
            varbinds.append( (ntforg.MibVariable(*varName), val) )

        # Send Notification
        error = notifier.sendNotification(ntforg.CommunityData(community),
                    ntforg.UdpTransportTarget((agent_host, agent_port)),
                    notify_type,
                    ntforg.MibVariable(*notification_trap),
                    *varbinds)

        # Check if Notification was successfully sent
        if error:
            self.fail('Notification not sent: %s' % error)

        log.debug("Sent Trap: %s:%d %r" % (agent_host, agent_port, notification_trap))

        # stupid hack for race condition
        time.sleep(1)

    def _trap_receiver_callback(self, trap):
        self.traps.append(trap)
        log.debug("Recevied Trap: %r" % (trap))

    def assertTrapReceived(self, notification_trap, notification_args=None):
        if notification_args is None:
            notification_args = dict()
        result = False
        for trap in self.traps:
            if notification_trap == self.mibs.lookup_oid(trap.oid):
                for notification_arg_type, val in notification_args.items():
                    notification_arg_oid = self.mibs.lookup(*notification_arg_type)
                    self.assertTrue(notification_arg_oid in trap.arguments)
                    self.assertTrue(trap.arguments[notification_arg_oid] == val)
                result = True
        self.assertTrue(result, "trap not received (yet?)")

    def test_receive_trap(self):
        # send a trap
        self.send_trap(('SNMPv2-MIB', 'coldStart'), {('SNMPv2-MIB', 'sysName'): "whatup"})
        # make sure we got it
        self.assertTrapReceived(('SNMPv2-MIB', 'coldStart'), {('SNMPv2-MIB', 'sysName'): "whatup"})
Ejemplo n.º 8
0
class SensuTrapServer(object):

    def __init__(self, config):
        self._config = config
        self._run = False

        # Configure MIBs
        self._configure_mibs()

        # Initialize TrapReceiverThread
        self._trap_receiver_thread = TrapReceiverThread(self._config, self._mibs, self._handle_trap)

        # Initialize TrapEventDispatcher
        self._trap_event_dispatcher_thread = TrapEventDispatcherThread(self._config)

        # Configure Trap Handlers
        self._trap_handlers = self._parse_trap_handlers(self._config['daemon']['trap_path'])

        LOG.debug("SensuTrapServer: Initialized")

    def _configure_mibs(self):
        self._mibs = MibResolver(self._config['mibs']['paths'], self._config['mibs']['mibs'])

    def _parse_trap_handlers(self, trap_path):
        LOG.debug("SensuTrapServer: Parsing trap handler files in '%s' directory" % trap_path)

        trap_handlers = dict()
        files = [ f for f in listdir(trap_path) if isfile(join(trap_path,f)) ]

        for trap_file in files:
            try:
                LOG.debug("SensuTrapServer: Parsing trap handler file: %s" % (trap_file))
                fh = open(join(trap_path, trap_file), 'r')
                trap_file_data = json.load(fh)
                for trap_handler_id, trap_handler_config in trap_file_data.items():
                    # Load TrapHandler
                    trap_handler = self._load_trap_handler(trap_handler_id, trap_handler_config)
                    trap_handlers[trap_handler_id] = trap_handler
                    LOG.debug("SensuTrapServer: Parsed trap handler: %s" % (trap_handler_id))
            finally:
                fh.close()

        return trap_handlers

    def _load_trap_handler(self, trap_handler_id, trap_handler_config):
        # Parse trap type
        trap_type_module, trap_type_symbol = tuple(trap_handler_config['trap']['type'])
        # TODO: handle OIDs as trap types
        trap_type_oid = self._mibs.lookup(trap_type_module, trap_type_symbol)

        #LOG.debug("%s type=%s::%s (%r)" % (trap_handler_id, trap_type_module, trap_type_symbol, trap_type_oid))

        # Parse trap arguments
        trap_args = dict()
        if 'args' in trap_handler_config['trap']:
            for trap_arg, trap_arg_type in trap_handler_config['trap']['args'].items():
                trap_arg_type_module, trap_arg_type_symbol = tuple(trap_arg_type)
                # TODO: handle OIDs as trap arg type
                trap_arg_type_oid = self._mibs.lookup(trap_arg_type_module, trap_arg_type_symbol)
                trap_args[trap_arg_type_oid] = trap_arg

                #LOG.debug("%s arg=%s type=%s::%s (%r)" % (trap_handler_id,
                #                                            trap_arg,
                #                                            trap_arg_type_module,
                #                                            trap_arg_type_symbol,
                #                                            trap_arg_type_oid))

        # Parse event info
        event_name = trap_handler_config['event']['name']
        event_output = trap_handler_config['event']['output']
        event_handlers = trap_handler_config['event']['handlers']
        event_source = trap_handler_config['event']['source']
        event_severity = parse_event_severity(trap_handler_config['event']['severity'])

        # TODO: parse predicates

        # Initialize TrapHandler
        trap_handler = TrapHandler(trap_type_oid,
                                    trap_args,
                                    event_name,
                                    event_output,
                                    event_handlers,
                                    event_severity,
                                    event_source,
                                    None)
        return trap_handler

    def _dispatch_trap_event(self, trap_event):
        self._trap_event_dispatcher_thread.dispatch(trap_event)

    def _handle_trap(self, trap):
        LOG.info("SensuTrapServer: Received Trap: %s" % (trap))

        # Find TrapHandler for this Trap 
        trap_handler = None
        for trap_handler_id, th in self._trap_handlers.items():
            if th.handles(trap):
                LOG.info("SensuTrapServer: %s handling trap %r" % (trap_handler_id, trap))
                # Transform Trap
                trap_event = th.transform(trap)
                # Dispatch TrapEvent
                self._dispatch_trap_event(trap_event)
                return
        LOG.warning("No trap handler found for %r" % (trap))
        # TODO: add default handler here for unmatched traps?

    def stop(self):
        if not self._run:
            return
        self._run = False

        # Stop TrapReceiverThread
        self._trap_receiver_thread.stop()

        # Stop TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.stop()

    def run(self):
        LOG.debug("SensuTrapServer: Started")
        self._run = True

        # Start TrapReceiverThread
        self._trap_receiver_thread.start()

        # Start TrapEventDispatcherThread
        self._trap_event_dispatcher_thread.start()

        while self._run:
            time.sleep(1)

        # Wait for our threads to stop
        self._trap_receiver_thread.join()
        self._trap_event_dispatcher_thread.join()
        LOG.debug("SensuTrapServer: Exiting")