Example #1
0
class Listener(ncpadaemon.Daemon):
    default_conf = os.path.abspath(os.path.join(filename.get_dirname_file(), 'etc', 'ncpa.cfg'))
    section = 'listener'

    def run(self):
        try:
            address = self.config_parser.get('listener', 'ip')
            port = self.config_parser.getint('listener', 'port')
            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                cert, key = listener.certificate.create_self_signed_cert(basepath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')
            ssl_context = {'certfile': cert, 'keyfile': key}

            listener.server.listener.secret_key = os.urandom(24)
            http_server = WSGIServer(listener=(address, port),
                                     application=listener.server.listener,
                                     handler_class=webhandler.PatchedWSGIHandler,
                                     spawn=Pool(100),
                                     **ssl_context)
            http_server.serve_forever()
        except Exception, e:
            logging.exception(e)
Example #2
0
    def run(self):

        # Read config once (restart required for new configs)
        self.read_basic_config()
        plugins_abs = os.path.abspath(os.path.join(filename.get_dirname_file(), self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path', plugins_abs)
        self.config_parser.file_path = os.path.abspath(u'etc/ncpa.cfg')

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('passive', 'delay_start')
            if delay_start:
                logging.info('Delayed start in configuration. Waiting %s seconds to start.', delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Set next DB maintenance period to +1 day
        self.db.run_db_maintenance(self.config_parser)
        next_db_maintenance = datetime.datetime.now() + datetime.timedelta(days=1)

        try:
            while True:
                self.run_all_handlers()

                # Do DB maintenance if the time is greater than next DB maintenance run
                if datetime.datetime.now() > next_db_maintenance:
                    self.db.run_db_maintenance(self.config_parser)
                    next_db_maintenance = datetime.datetime.now() + datetime.timedelta(days=1)

                time.sleep(1)
        except Exception, e:
            logging.exception(e)
Example #3
0
    def run(self):

        # Read config once (restart required for new configs)
        self.read_basic_config()
        plugins_abs = os.path.abspath(os.path.join(filename.get_dirname_file(), self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path', plugins_abs)
        self.config_parser.file_path = self.default_conf

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('passive', 'delay_start')
            if delay_start:
                logging.info('Delayed start in configuration. Waiting %s seconds to start.', delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Set next DB maintenance period to +1 day
        self.db.run_db_maintenance(self.config_parser)
        next_db_maintenance = datetime.datetime.now() + datetime.timedelta(days=1)

        try:
            while True:
                self.run_all_handlers()

                # Do DB maintenance if the time is greater than next DB maintenance run
                if datetime.datetime.now() > next_db_maintenance:
                    self.db.run_db_maintenance(self.config_parser)
                    next_db_maintenance = datetime.datetime.now() + datetime.timedelta(days=1)

                time.sleep(1)
        except Exception, e:
            logging.exception(e)
Example #4
0
class Passive(ncpadaemon.Daemon):
    default_conf = os.path.abspath(
        os.path.join(filename.get_dirname_file(), 'etc', 'ncpa.cfg'))
    section = u'passive'

    def run_all_handlers(self, *args, **kwargs):
        """
        Will run all handlers that exist.

        The handler must:
        - Have a config header entry
        - Abide by the handler API set forth by passive.abstract.NagiosHandler
        - Terminate in a timely fashion
        """
        handlers = self.config_parser.get('passive', 'handlers').split(',')

        for handler in handlers:
            try:
                handler = handler.strip()
                module_name = 'passive.%s' % handler
                __import__(module_name)
                tmp_handler = sys.modules[module_name]
            except ImportError:
                logging.error(
                    u'Could not import module passive.%s, skipping...' %
                    handler)
            else:
                try:
                    plugins_abs = os.path.abspath(
                        self.config_parser.get(u'plugin directives',
                                               u'plugin_path'))
                    self.config_parser.set(u'plugin directives',
                                           u'plugin_path', plugins_abs)
                    self.config_parser.file_path = os.path.abspath(
                        u'etc/ncpa.cfg')
                    ins_handler = tmp_handler.Handler(self.config_parser)
                    ins_handler.run()
                    logging.debug(u'Successfully ran handler %s' % handler)
                except Exception as exc:
                    logging.exception(exc)

    def run(self):
        while True:
            self.read_basic_config()
            try:
                self.run_all_handlers()
            except Exception, e:
                logging.exception(e)
            sleep = int(self.config_parser.get('passive', 'sleep'))
            time.sleep(sleep)
Example #5
0
    def run(self):

        # Check if there is a start delay
        try:
            delay_start = self.config.get('listener', 'delay_start')
            if delay_start:
                logging.info('Delayed start in configuration. Waiting %s seconds to start.', delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass
        
        try:
            address = self.config_parser.get('listener', 'ip')
            port = self.config_parser.getint('listener', 'port')
            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')

            ssl_str_version = self.config_parser.get('listener',
                                                     'ssl_version',
                                                     'TLSv1')
            try:
                ssl_version = getattr(ssl, 'PROTOCOL_' + ssl_str_version)
            except:
                ssl_version = getattr(ssl, 'PROTOCOL_TLSv1')
                ssl_str_version = 'TLSv1'
            logging.info('Using SSL version %s', ssl_str_version)

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                cert, key = listener.certificate.create_self_signed_cert(basepath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')
            ssl_context = {
                'certfile': cert,
                'keyfile': key,
                'ssl_version': ssl_version
            }

            listener.server.listener.secret_key = os.urandom(24)
            http_server = WSGIServer(listener=(address, port),
                                     application=listener.server.listener,
                                     handler_class=webhandler.PatchedWSGIHandler,
                                     spawn=Pool(200),
                                     **ssl_context)
            http_server.serve_forever()
        except Exception, e:
            logging.exception(e)
Example #6
0
    def run(self):
        try:
            address = self.config_parser.get('listener', 'ip')
            port = self.config_parser.getint('listener', 'port')
            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                cert, key = listener.certificate.create_self_signed_cert(basepath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')
            ssl_context = {'certfile': cert, 'keyfile': key}

            listener.server.listener.secret_key = os.urandom(24)
            http_server = WSGIServer(listener=(address, port),
                                     application=listener.server.listener,
                                     handler_class=webhandler.PatchedWSGIHandler,
                                     spawn=Pool(100),
                                     **ssl_context)
            http_server.serve_forever()
        except Exception, e:
            logging.exception(e)
Example #7
0
    def run(self):

        # Set absolute plugin path
        plugins_abs = os.path.abspath(os.path.join(filename.get_dirname_file(), self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path', plugins_abs)

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('listener', 'delay_start')
            if delay_start:
                logging.info('Delayed start in configuration. Waiting %s seconds to start.', delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Handle DB maintenance
        self.db.run_db_maintenance(self.config_parser)

        try:
            try:
                address = self.config_parser.get('listener', 'ip')
            except Exception:
                self.config_parser.set('listener', 'ip', '::')
                address = '::'

            try:
                port = self.config_parser.getint('listener', 'port')
            except Exception:
                self.config_parser.set('listener', 'port', 5693)
                port = 5693

            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')
            ssl_str_version = self.config_parser.get('listener', 'ssl_version')

            try:
                ssl_str_ciphers = self.config_parser.get('listener', 'ssl_ciphers')
            except Exception:
                ssl_str_ciphers = None

            try:
                ssl_version = getattr(ssl, 'PROTOCOL_' + ssl_str_version)
            except:
                ssl_version = getattr(ssl, 'PROTOCOL_TLSv1')
                ssl_str_version = 'TLSv1'
            logging.info('Using SSL version %s', ssl_str_version)

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                certpath = os.path.abspath(os.path.join(basepath, 'var'))
                cert, key = listener.certificate.create_self_signed_cert(certpath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')

            # Create SSL context that will be passed to the server
            ssl_context = {
                'certfile': cert,
                'keyfile': key,
                'ssl_version': ssl_version
            }

            # Add SSL cipher list if one is given
            if ssl_str_ciphers:
                ssl_context['ciphers'] = ssl_str_ciphers

            # Create connection pool
            try:
                max_connections = self.config_parser.get('listener', 'max_connections')
            except Exception:
                max_connections = 200

            listener.server.listener.secret_key = os.urandom(24)

            try:
                http_server = WSGIServer(listener=(address, port),
                                         application=listener.server.listener,
                                         handler_class=WebSocketHandler,
                                         spawn=Pool(max_connections),
                                         **ssl_context)
                http_server.serve_forever()
            except SocketError as e:
                if address == '::':
                    logging.error("Failed to start in dual stack mode: %s", e)
                    logging.info("Falling back to IPv4 only")
                else:
                    logging.exception(e)
                address = '0.0.0.0'
                http_server = WSGIServer(listener=(address, port),
                                         application=listener.server.listener,
                                         handler_class=WebSocketHandler,
                                         spawn=Pool(max_connections),
                                         **ssl_context)
                http_server.serve_forever()
        except Exception, e:
            logging.exception(e)
Example #8
0
class Passive(ncpadaemon.Daemon):

    default_conf = os.path.abspath(
        os.path.join(filename.get_dirname_file(), 'etc', 'ncpa.cfg'))
    section = u'passive'

    def run_all_handlers(self, *args, **kwargs):
        """
        Will run all handlers that exist.

        The handler must:
        - Have a config header entry
        - Abide by the handler API set forth by passive.abstract.NagiosHandler
        - Terminate in a timely fashion
        """
        handlers = self.config_parser.get('passive', 'handlers').split(',')
        run_time = time.time()

        # Empty passive handlers will skip trying to run any handlers
        if handlers[0] == 'None' or handlers[0] == '':
            return

        for handler in handlers:
            try:
                handler = handler.strip()
                module_name = 'passive.%s' % handler
                __import__(module_name)
                tmp_handler = sys.modules[module_name]
            except ImportError as e:
                logging.error(
                    'Could not import module passive.%s, skipping. %s' %
                    (handler, str(e)))
                logging.exception(e)
            else:
                try:
                    ins_handler = tmp_handler.Handler(self.config_parser)
                    ins_handler.run(run_time)
                    logging.debug(u'Successfully ran handler %s' % handler)
                except Exception as e:
                    logging.exception(e)

    def run(self):

        # Read config once (restart required for new configs)
        self.read_basic_config()
        plugins_abs = os.path.abspath(
            os.path.join(
                filename.get_dirname_file(),
                self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path',
                               plugins_abs)
        self.config_parser.file_path = self.default_conf

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('passive', 'delay_start')
            if delay_start:
                logging.info(
                    'Delayed start in configuration. Waiting %s seconds to start.',
                    delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Set next DB maintenance period to +1 day
        self.db.run_db_maintenance(self.config_parser)
        next_db_maintenance = datetime.datetime.now() + datetime.timedelta(
            days=1)

        try:
            while True:
                self.run_all_handlers()

                # Do DB maintenance if the time is greater than next DB maintenance run
                if datetime.datetime.now() > next_db_maintenance:
                    self.db.run_db_maintenance(self.config_parser)
                    next_db_maintenance = datetime.datetime.now(
                    ) + datetime.timedelta(days=1)

                time.sleep(1)
        except Exception, e:
            logging.exception(e)
Example #9
0
            u'gid': u'nagios',
        }

        cp = ConfigParser.ConfigParser(defaults)
        cp.optionxform = unicode
        cp.read(self.config_filenames)
        self.config_parser = cp

        try:
            self.uid, self.gid, self.username = get_uid_gid(cp, self.section)
        except ValueError, e:
            sys.exit(unicode(e))

        self.logmaxmb = int(cp.get(self.section, u'logmaxmb'))
        self.logbackups = int(cp.get(self.section, u'logbackups'))
        self.pidfile = os.path.abspath(os.path.join(filename.get_dirname_file(),
                                                    cp.get(self.section, u'pidfile')))
        self.logfile = os.path.abspath(os.path.join(filename.get_dirname_file(),
                                                    cp.get(self.section, u'logfile')))
        self.loglevel = cp.get(self.section, u'loglevel')

    def on_sigterm(self, signalnum, frame):
        u"""Handle sigterm by treating as a keyboard interrupt"""
        self.remove_pid()
        sys.exit(0)

    def add_signal_handlers(self):
        u"""Register the sigterm handler"""
        signal.signal(signal.SIGTERM, self.on_sigterm)

    def start(self):
Example #10
0
    def run(self):

        # Set absolute plugin path
        plugins_abs = os.path.abspath(
            os.path.join(
                filename.get_dirname_file(),
                self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path',
                               plugins_abs)

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('listener', 'delay_start')
            if delay_start:
                logging.info(
                    'Delayed start in configuration. Waiting %s seconds to start.',
                    delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Handle DB maintenance
        self.db.run_db_maintenance(self.config_parser)

        try:
            try:
                address = self.config_parser.get('listener', 'ip')
            except Exception:
                self.config_parser.set('listener', 'ip', '0.0.0.0')
                address = '0.0.0.0'

            try:
                port = self.config_parser.getint('listener', 'port')
            except Exception:
                self.config_parser.set('listener', 'port', 5693)
                port = 5693

            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')

            ssl_str_version = self.config_parser.get('listener', 'ssl_version')
            try:
                ssl_version = getattr(ssl, 'PROTOCOL_' + ssl_str_version)
            except:
                ssl_version = getattr(ssl, 'PROTOCOL_TLSv1')
                ssl_str_version = 'TLSv1'
            logging.info('Using SSL version %s', ssl_str_version)

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                cert, key = listener.certificate.create_self_signed_cert(
                    basepath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')

            ssl_context = {
                'certfile': cert,
                'keyfile': key,
                'ssl_version': ssl_version
            }

            listener.server.listener.secret_key = os.urandom(24)
            http_server = WSGIServer(listener=(address, port),
                                     application=listener.server.listener,
                                     handler_class=WebSocketHandler,
                                     spawn=Pool(200),
                                     **ssl_context)
            http_server.serve_forever()
        except Exception, e:
            logging.exception(e)
Example #11
0
class Daemon(object):
    def __init__(self):
        u"""Override to change where the daemon looks for config information.

        By default we use the 'daemon' section of a file with the same name
        as the python module holding the subclass, ending in .conf
        instead of .py.
        """
        if not hasattr(self, u'default_conf'):
            # Grabs the filename that the Daemon subclass resides in...
            #self.daemon_file = sys.modules[self.__class__.__module__].__file__
            #self.default_conf = self.daemon_file.rpartition('.')[0] + '.conf'
            pass
        if not hasattr(self, u'section'):
            self.section = u'daemon'

    def setup_root(self):
        u"""Override to perform setup tasks with root privileges.

        When this is called, logging has been initialized, but the
        terminal has not been detached and the pid of the long-running
        process is not yet known.
        """

        # We need to chown any temp files we wrote out as root (or any other user)
        # to the currently set user and group so checks don't error out
        tmpdir = os.path.join(tempfile.gettempdir())
        for file in os.listdir(tmpdir):
            if os.path.isfile(file):
                if 'ncpa-' in file:
                    self.chown(os.path.join(tmpdir, file))

    def setup_user(self):
        u"""Override to perform setup tasks with user privileges.

        Like setup_root, the terminal is still attached and the pid is
        temporary.  However, the process has dropped root privileges.
        """
        # Set up database
        self.db = listener.database.DB()
        self.db.setup()

    def run(self):
        u"""Override.

        The terminal has been detached at this point.
        """

    def main(self):
        u"""Read the command line and either start or stop the daemon"""
        self.parse_options()
        action = self.options.action
        self.read_basic_config()
        if action == u'start':
            self.start()
        elif action == u'stop':
            self.stop()
        elif action == u'status':
            self.status()
        else:
            raise ValueError(action)

    def parse_options(self):
        u"""Parse the command line"""
        p = optparse.OptionParser()
        p.add_option(u'--start',
                     dest=u'action',
                     action=u'store_const',
                     const=u'start',
                     default=u'start',
                     help=u'Start the daemon (the default action)')
        p.add_option(u'-s',
                     u'--stop',
                     dest=u'action',
                     action=u'store_const',
                     const=u'stop',
                     default=u'start',
                     help=u'Stop the daemon')
        p.add_option(u'--status',
                     dest=u'action',
                     action=u'store_const',
                     const=u'status',
                     default=u'start',
                     help=u'Status of the daemon')
        p.add_option(u'-c',
                     dest=u'config_filename',
                     action=u'store',
                     default=self.default_conf,
                     help=u'Specify alternate configuration file name')
        p.add_option(u'-n',
                     u'--nodaemon',
                     dest=u'daemonize',
                     action=u'store_false',
                     default=True,
                     help=u'Run in the foreground')
        self.options, self.args = p.parse_args()
        if not os.path.exists(self.options.config_filename):
            p.error(u'configuration file not found: %s' %
                    self.options.config_filename)

    def read_basic_config(self):
        u"""Read basic options from the daemon config file"""
        self.config_filenames = [self.options.config_filename]
        self.config_filenames.extend(
            sorted(
                glob.glob(
                    os.path.join(self.options.config_filename + ".d",
                                 "*.cfg"))))

        # Set defaults for below section
        defaults = {
            u'logmaxmb': u'5',
            u'logbackups': u'5',
            u'loglevel': u'warning',
            u'uid': u'nagios',
            u'gid': u'nagios',
        }

        cp = ConfigParser.ConfigParser(defaults)
        cp.optionxform = unicode
        cp.read(self.config_filenames)
        self.config_parser = cp

        try:
            self.uid, self.gid = list(imap(int, get_uid_gid(cp, self.section)))
        except ValueError, e:
            sys.exit(unicode(e))

        self.logmaxmb = int(cp.get(self.section, u'logmaxmb'))
        self.logbackups = int(cp.get(self.section, u'logbackups'))
        self.pidfile = os.path.abspath(
            os.path.join(filename.get_dirname_file(),
                         cp.get(self.section, u'pidfile')))
        self.logfile = os.path.abspath(
            os.path.join(filename.get_dirname_file(),
                         cp.get(self.section, u'logfile')))
        self.loglevel = cp.get(self.section, u'loglevel')
Example #12
0
    def run(self):

        # Set absolute plugin path
        plugins_abs = os.path.abspath(os.path.join(filename.get_dirname_file(), self.config_parser.get(u'plugin directives', u'plugin_path')))
        self.config_parser.set(u'plugin directives', u'plugin_path', plugins_abs)

        # Check if there is a start delay
        try:
            delay_start = self.config_parser.get('listener', 'delay_start')
            if delay_start:
                logging.info('Delayed start in configuration. Waiting %s seconds to start.', delay_start)
                time.sleep(int(delay_start))
        except Exception:
            pass

        # Handle DB maintenance
        self.db.run_db_maintenance(self.config_parser)

        try:
            try:
                address = self.config_parser.get('listener', 'ip')
            except Exception:
                self.config_parser.set('listener', 'ip', '::')
                address = '::'

            try:
                port = self.config_parser.getint('listener', 'port')
            except Exception:
                self.config_parser.set('listener', 'port', 5693)
                port = 5693

            listener.server.listener.config['iconfig'] = self.config_parser

            user_cert = self.config_parser.get('listener', 'certificate')
            ssl_str_version = self.config_parser.get('listener', 'ssl_version')

            try:
                ssl_str_ciphers = self.config_parser.get('listener', 'ssl_ciphers')
            except Exception:
                ssl_str_ciphers = None

            try:
                ssl_version = getattr(ssl, 'PROTOCOL_' + ssl_str_version)
            except:
                ssl_version = getattr(ssl, 'PROTOCOL_TLSv1')
                ssl_str_version = 'TLSv1'
            logging.info('Using SSL version %s', ssl_str_version)

            if user_cert == 'adhoc':
                basepath = filename.get_dirname_file()
                certpath = os.path.abspath(os.path.join(basepath, 'var'))
                cert, key = listener.certificate.create_self_signed_cert(certpath, 'ncpa.crt', 'ncpa.key')
            else:
                cert, key = user_cert.split(',')

            # Create SSL context that will be passed to the server
            ssl_context = {
                'certfile': cert,
                'keyfile': key,
                'ssl_version': ssl_version
            }

            # Add SSL cipher list if one is given
            if ssl_str_ciphers:
                ssl_context['ciphers'] = ssl_str_ciphers

            # Create connection pool
            try:
                max_connections = self.config_parser.get('listener', 'max_connections')
            except Exception:
                max_connections = 200

            listener.server.listener.secret_key = os.urandom(24)
            http_server = WSGIServer(listener=(address, port),
                                     application=listener.server.listener,
                                     handler_class=WebSocketHandler,
                                     spawn=Pool(max_connections),
                                     **ssl_context)
            http_server.serve_forever()
        except Exception, e:
            logging.exception(e)