Пример #1
0
    def test_plugin_loader_raises_no_exception_if_plugin_has_no_initialize_method(
            self):
        loader = load_handler_modules([self.plugin_b])
        assert loader[0] == __import__('nav.snmptrapd.handlers.bar', globals(),
                                       locals(), ['bar'])

        assert not hasattr(loader[0], 'initialize')
Пример #2
0
def test_plugin_loader_raises_no_exception_if_plugin_has_no_initialize_method():
    loader = load_handler_modules(['nav.snmptrapd.handlers.airespace'])

    assert loader[0] == __import__(
        'nav.snmptrapd.handlers.airespace', globals(), locals(), 'airespace'
    )
    assert not hasattr(loader[0], 'initialize')
Пример #3
0
    def test_plugin_loader_raises_no_exception_if_plugin_has_no_initialize_method(
            self):
        loader = load_handler_modules([self.plugin_b])
        assert loader[0] == __import__('nav.snmptrapd.handlers.bar',
                                       globals(), locals(), ['bar'])

        assert not hasattr(loader[0], 'initialize')
Пример #4
0
    def test_loading_plugin_with_initialize_method_raises_no_exception(self):
        loader = load_handler_modules(['nav.snmptrapd.handlers.weathergoose'])

        assert loader[0] == __import__('nav.snmptrapd.handlers.weathergoose',
                                       globals(), locals(), ['weathergoose'])

        assert hasattr(loader[0], 'initialize')
Пример #5
0
    def test_loading_plugin_with_initialize_method_raises_no_exception(self):
        loader = load_handler_modules(['nav.snmptrapd.handlers.weathergoose'])

        assert loader[0] == __import__('nav.snmptrapd.handlers.weathergoose',
                                       globals(), locals(), ['weathergoose'])

        assert hasattr(loader[0], 'initialize')
Пример #6
0
    def test_plugin_loader_reading_in_modules_from_config_file(self):
        configfile = sysconfdir + "/snmptrapd.conf"
        config = ConfigParser.ConfigParser()
        config.read(configfile)
        list_from_config = config.get('snmptrapd', 'handlermodules').split(',')

        assert type(list_from_config) == list
        if len(list_from_config) <= 0:
            pytest.skip("Requires at least one plugin in snmptrapd.conf to run"
            + " this integration test with loading plugins")

        loaded_modules = load_handler_modules(list_from_config)
        assert len(list_from_config) == len(loaded_modules)
Пример #7
0
def test_plugin_loader_reading_in_modules_from_config_file():
    configfile = find_configfile("snmptrapd.conf")
    config = configparser.ConfigParser()
    config.read(configfile)
    list_from_config = config.get('snmptrapd', 'handlermodules').split(',')

    assert type(list_from_config) == list
    if len(list_from_config) <= 0:
        pytest.skip("Requires at least one plugin in snmptrapd.conf to run"
                    " this integration test with loading plugins")

    loaded_modules = load_handler_modules(list_from_config)
    assert len(list_from_config) == len(loaded_modules)
Пример #8
0
def main():

    # Verify that subsystem exists, if not insert it into database
    verify_subsystem()

    # Initialize and read startupconfig
    global config
    config = ConfigParser.ConfigParser()
    config.read(configfile)

    # Create parser and define options
    opts = parse_args()

    # When binding to a port < 1024 we need to be root
    minport = min(port for addr, port in opts.address)
    if minport < 1024:
        if os.geteuid() != 0:
            print("Must be root to bind to ports < 1024, exiting")
            sys.exit(-1)

    # Check if already running
    try:
        daemon.justme(pidfile)
    except daemon.DaemonError as why:
        print(why)
        sys.exit(-1)

    # Create SNMP agent object
    server = agent.TrapListener(*opts.address)
    server.open()

    # We have bound to a port and can safely drop privileges
    runninguser = config.get('snmptrapd', 'user')
    try:
        if os.geteuid() == 0:
            daemon.switchuser(runninguser)
    except daemon.DaemonError as why:
        print(why)
        server.close()
        sys.exit(-1)

    global handlermodules

    nav.logs.init_generic_logging(stderr=True, read_config=True)

    logger.debug("using %r as SNMP backend", agent.BACKEND)

    # Load handlermodules
    try:
        logger.debug('Trying to load handlermodules')
        handlermodules = load_handler_modules(
            config.get('snmptrapd', 'handlermodules').split(','))
    except ModuleLoadError as why:
        logger.error("Could not load handlermodules %s" % why)
        sys.exit(1)

    addresses_text = ", ".join(
        address_to_string(*addr) for addr in opts.address)
    if opts.daemon:
        # Daemonize and listen for traps
        try:
            logger.debug("Going into daemon mode...")
            logfile = open(logfile_path, 'a')
            daemon.daemonize(pidfile, stderr=logfile, stdout=logfile)
        except daemon.DaemonError as why:
            logger.error("Could not daemonize: %s", why)
            server.close()
            sys.exit(1)

        # Daemonized; reopen log files
        nav.logs.reopen_log_files()
        logger.debug('Daemonization complete; reopened log files.')

        # Reopen lost db connection
        # This is a workaround for a double free bug in psycopg 2.0.7
        # which is why we don't need to keep the return value
        getConnection('default')

        # Reopen log files on SIGHUP
        logger.debug(
            'Adding signal handler for reopening log files on SIGHUP.')
        signal.signal(signal.SIGHUP, signal_handler)
        # Exit on SIGTERM
        signal.signal(signal.SIGTERM, signal_handler)

        logger.info("Snmptrapd started, listening on %s", addresses_text)
        try:
            server.listen(opts.community, trap_handler)
        except SystemExit:
            raise
        except Exception as why:
            logger.critical("Fatal exception ocurred", exc_info=True)

    else:
        # Start listening and exit cleanly if interrupted.
        try:
            logger.info("Listening on %s", addresses_text)
            server.listen(opts.community, trap_handler)
        except KeyboardInterrupt as why:
            logger.error("Received keyboardinterrupt, exiting.")
            server.close()
Пример #9
0
    def test_plugin_loads_all_plugins(self):
        loader = load_handler_modules([self.plugin_a, self.plugin_b])

        assert self.plugin_a.initialize.call_count == 1
        assert loader == [self.plugin_a, self.plugin_b]
Пример #10
0
    def test_plugin_loader_calls_initialize_method_if_it_exists(self):
        loader = load_handler_modules([self.plugin_a])

        assert self.plugin_a.initialize.call_count == 1
        assert loader[0] == self.plugin_a
Пример #11
0
 def test_plugin_raises_module_load_error_import_error(self):
     with pytest.raises(ModuleLoadError):
         load_handler_modules(['nav.snmptrapd.handlers.non_existent'])
Пример #12
0
 def test_plugin_raises_module_load_error_on_bad_plugin(self):
     with pytest.raises(ModuleLoadError):
         load_handler_modules([self.bad_plugin])
Пример #13
0
        handler = logging.StreamHandler()

        logger = logging.getLogger('')
        logger.setLevel(logging.DEBUG)
        traplogger = logging.getLogger('')
        traplogger.setLevel(logging.DEBUG)

        logger.addHandler(handler)
        traplogger.addHandler(handler)

    logger.debug("using %r as SNMP backend", agent.BACKEND)

    # Load handlermodules
    try:
        logger.debug('Trying to load handlermodules')
        handlermodules = load_handler_modules(
            config.get('snmptrapd', 'handlermodules').split(','))
    except ModuleLoadError, why:
        logger.error("Could not load handlermodules %s" % why)
        sys.exit(1)

    addresses_text = ", ".join(address_to_string(*addr) for addr in addresses)
    if opts.daemon:
        # Daemonize and listen for traps
        try:
            logger.debug("Going into daemon mode...")
            daemon.daemonize(pidfile,
                             stderr=nav.logs.get_logfile_from_logger())
        except daemon.DaemonError, why:
            logger.error("Could not daemonize: %s", why)
            server.close()
            sys.exit(1)
Пример #14
0
    def test_plugin_loads_all_plugins(self):
        loader = load_handler_modules([self.plugin_a, self.plugin_b])

        assert self.plugin_a.initialize.call_count == 1
        assert loader == [self.plugin_a, self.plugin_b]
Пример #15
0
    def test_plugin_loader_calls_initialize_method_if_it_exists(self):
        loader = load_handler_modules([self.plugin_a])

        assert self.plugin_a.initialize.call_count == 1
        assert loader[0] == self.plugin_a
Пример #16
0
        handler = logging.StreamHandler()

        logger = logging.getLogger('')
        logger.setLevel(logging.DEBUG)
        traplogger = logging.getLogger('')
        traplogger.setLevel(logging.DEBUG)

        logger.addHandler(handler)
        traplogger.addHandler(handler)

    logger.debug("using %r as SNMP backend", agent.BACKEND)

    # Load handlermodules
    try:
        logger.debug('Trying to load handlermodules')
        handlermodules = load_handler_modules(config.get('snmptrapd','handlermodules').split(','))
    except ModuleLoadError, why:
        logger.error("Could not load handlermodules %s" %why)
        sys.exit(1)

    addresses_text = ", ".join(address_to_string(*addr) for addr in addresses)
    if opts.daemon:
        # Daemonize and listen for traps
        try:
            logger.debug("Going into daemon mode...")
            daemon.daemonize(pidfile,
                             stderr=nav.logs.get_logfile_from_logger())
        except daemon.DaemonError, why:
            logger.error("Could not daemonize: %s", why)
            server.close()
            sys.exit(1)