Exemplo n.º 1
0
def main():
    """Parse CLI and starts daemon."""

    args = docopt(__doc__, version=version)
    if args['--print']:
        for section in DEFAULT_OPTIONS:
            print("[{}]".format(section))
            for key, value in DEFAULT_OPTIONS[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    try:
        config = load_configuration(args['--file'],
                                    args['--dir'],
                                    args['--service-file'])
    except ValueError as exc:
        sys.exit('Invalid configuration: ' + str(exc))

    if args['--check']:
        print("OK")
        sys.exit(0)

    if args['--print-conf']:
        for section in config:
            print("[{}]".format(section))
            for key, value in config[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)


    # Catch already running process and clean up stale pid file.
    pidfile = config.get('daemon', 'pidfile')
    if os.path.exists(pidfile):
        pid = open(pidfile).read().rstrip()
        try:
            pid = int(pid)
        except ValueError:
            print("Cleaning stale pid file with invalid data:{}".format(pid))
            os.unlink(pidfile)
        else:
            if running(pid):
                sys.exit("Process {} is already running".format(pid))
            else:
                print("Cleaning stale pid file with pid:{}".format(pid))
                os.unlink(pidfile)

    # Map log level to numeric which can be accepted by loggers.
    num_level = getattr(
        logging,
        config.get('daemon', 'loglevel').upper(),  # pylint: disable=no-member
        None
    )

    # Set up loggers for stdout, stderr and daemon stream
    log = lib.LoggerExt(
        'daemon',
        config.get('daemon', 'log_file'),
        log_level=num_level,
        maxbytes=config.getint('daemon', 'log_maxbytes'),
        backupcount=config.getint('daemon', 'log_backups')
    )
    if config.getboolean('daemon', 'json_logging', fallback=False):
        log.add_central_logging(
            server=config.get('daemon', 'http_server'),
            timeout=config.getfloat('daemon', 'http_server_timeout'),
            protocol=config.get('daemon', 'http_server_protocol'),
            port=config.get('daemon', 'http_server_port')
        )
    stdout_log = lib.LoggerExt(
        'stdout',
        config.get('daemon', 'stdout_file'),
        log_level=num_level)

    stderrformat = ('%(asctime)s [%(process)d] line:%(lineno)d '
                    'func:%(funcName)s %(levelname)-8s %(threadName)-32s '
                    '%(message)s')
    stderr_log = lib.LoggerExt(
        'stderr',
        config.get('daemon', 'stderr_file'),
        log_level=num_level,
        log_format=stderrformat)

    if config.getboolean('daemon', 'json_logging', fallback=False):
        stderr_log.add_central_logging(
            server=config.get('daemon', 'http_server'),
            timeout=config.getfloat('daemon', 'http_server_timeout'),
            protocol=config.get('daemon', 'http_server_protocol'),
            port=config.get('daemon', 'http_server_port')
        )

    # Perform a sanity check on IP-Prefixes
    ip_prefixes_check(log, config)

    # Make some noise.
    log.debug('Before we are daemonized')
    stdout_log.debug('before we are daemonized')
    stderr_log.debug('before we are daemonized')

    # Get and set the DaemonContext.
    context = lib.LoggingDaemonContext()
    context.loggers_preserve = [log]
    context.stdout_logger = stdout_log
    context.stderr_logger = stderr_log

    # Set pidfile for DaemonContext
    pid_lockfile = PIDLockFile(config.get('daemon', 'pidfile'))
    context.pidfile = pid_lockfile

    # Create our master process.
    checker = healthchecker.HealthChecker(
        log,
        config,
        config.get('daemon', 'bird_conf'),
        config.get('daemon', 'bird_variable'),
        config.get('daemon', 'dummy_ip_prefix'),
        config.getboolean('daemon', 'keep_bird_changes'),
        config.getint('daemon', 'changes_counter'),
    )

    # Set signal mapping to catch singals and act accordingly.
    context.signal_map = {
        signal.SIGHUP: checker.catch_signal,
        signal.SIGTERM: checker.catch_signal,
    }

    # OK boy go and daemonize yourself.
    with context:
        log.info("starting daemon {}".format(version))
        checker.run()
Exemplo n.º 2
0
def main():
    """Parse CLI and starts daemon."""

    args = docopt(__doc__, version=version)
    if args['--print']:
        for section in DEFAULT_OPTIONS:
            print("[{}]".format(section))
            for key, value in DEFAULT_OPTIONS[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    # Parse configuration.
    defaults = copy.copy(DEFAULT_OPTIONS['DEFAULT'])
    daemon_defaults = {'daemon': copy.copy(DEFAULT_OPTIONS['daemon'])}
    config = configparser.ConfigParser(defaults=defaults)
    config.read_dict(daemon_defaults)
    config_files = [args['--file']]
    config_files.extend(glob.glob(os.path.join(args['--dir'], '*.conf')))
    config.read(config_files)

    if args['--print-conf']:
        for section in config:
            print("[{}]".format(section))
            for key, value in config[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    # Perform a sanity check on the configuration
    configuration_check(config)
    if args['--check']:
        print("OK")
        sys.exit(0)

    # Catch already running process and clean up stale pid file.
    pidfile = config['daemon']['pidfile']
    if os.path.exists(pidfile):
        pid = open(pidfile).read().rstrip()
        try:
            pid = int(pid)
        except ValueError:
            print("Cleaning stale pid file with invalid data:{}".format(pid))
            os.unlink(pidfile)
        else:
            if running(pid):
                sys.exit("Process {} is already running".format(pid))
            else:
                print("Cleaning stale pid file with pid:{}".format(pid))
                os.unlink(pidfile)

    # Map log level to numeric which can be accepted by loggers.
    numeric_level = getattr(logging, config['daemon']['loglevel'].upper(), None)

    # Set up loggers for stdout, stderr and daemon stream
    log = lib.get_file_logger(
        'daemon',
        config['daemon']['log_file'],
        log_level=numeric_level,
        maxbytes=config.getint('daemon', 'log_maxbytes'),
        backupcount=config.getint('daemon', 'log_backups')
    )
    stdout_log = lib.get_file_logger(
        'stdout',
        config['daemon']['stdout_file'],
        log_level=numeric_level)

    stderrformat = ('%(asctime)s [%(process)d] line:%(lineno)d '
                    'func:%(funcName)s %(levelname)-8s %(threadName)-32s '
                    '%(message)s')
    stderr_log = lib.get_file_logger(
        'stderr',
        config['daemon']['stderr_file'],
        log_level=numeric_level,
        log_format=stderrformat)

    # Make some noise.
    log.debug('Before we are daemonized')
    stdout_log.debug('Before we are daemonized')
    stderr_log.debug('Before we are daemonized')

    # Get and set the DaemonContext.
    context = lib.LoggingDaemonContext()
    context.loggers_preserve = [log]
    context.stdout_logger = stdout_log
    context.stderr_logger = stderr_log

    # Set pidfile for DaemonContext
    pid_lockfile = PIDLockFile(config['daemon']['pidfile'])
    context.pidfile = pid_lockfile

    # Create our master process.
    checker = healthchecker.HealthChecker(
        log,
        config,
        config['daemon']['bird_conf'],
        config['daemon']['bird_variable'],
        config['daemon']['dummy_ip_prefix'])

    # Set signal mapping to catch singals and act accordingly.
    context.signal_map = {
        signal.SIGHUP: checker.catch_signal,
        signal.SIGTERM: checker.catch_signal,
    }

    # OK boy go and daemonize yourself.
    with context:
        log.info("Starting daemon {}".format(version))
        checker.run()
Exemplo n.º 3
0
def main():
    """Parse CLI and starts daemon."""
    args = docopt(__doc__, version=version)
    if args['--print']:
        for section in DEFAULT_OPTIONS:
            print("[{}]".format(section))
            for key, value in DEFAULT_OPTIONS[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    try:
        config, bird_configuration = load_configuration(
            args['--file'], args['--dir'], args['--service-file'])
    except ValueError as exc:
        sys.exit('Invalid configuration: ' + str(exc))

    if args['--check']:
        print("OK")
        sys.exit(0)

    if args['--print-conf']:
        for section in config:
            print("[{}]".format(section))
            for key, value in config[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    # Catch already running process and clean up stale pid file.
    pidfile = config.get('daemon', 'pidfile')
    if not os.path.isdir(os.path.dirname(pidfile)):
        sys.exit("{d} does not exit".format(d=os.path.dirname(pidfile)))
    try:
        with open(pidfile) as _file:
            pid = _file.read().rstrip()
        try:
            pid = int(pid)
        except ValueError:
            print("cleaning stale pid file with invalid data:{}".format(pid))
            os.unlink(pidfile)
        else:
            if running(pid):
                sys.exit("process {} is already running".format(pid))
            else:
                print("cleaning stale pid file with pid:{}".format(pid))
                os.unlink(pidfile)
    except FileNotFoundError:
        pass  # it is OK if pidfile doesn't exist
    except OSError as exc:
        sys.exit("failed to parse pidfile:{e}".format(e=exc))

    # Create bird configs, if they doen't exist, and history directories
    for ip_version in bird_configuration:
        config_file = bird_configuration[ip_version]['config_file']
        try:
            touch(config_file)
        except OSError as exc:
            sys.exit("failed to create {f}:{e}".format(f=config_file, e=exc))

        if bird_configuration[ip_version]['keep_changes']:
            history_dir = os.path.join(os.path.dirname(config_file), 'history')
            try:
                os.mkdir(history_dir)
            except FileExistsError:
                pass
            except OSError as exc:
                sys.exit("failed to make directory {d} for keeping a history "
                         "of changes for {b}:{e}".format(d=history_dir,
                                                         b=config_file,
                                                         e=exc))
            else:
                print("{d} is created".format(d=history_dir))

    # Map log level to numeric which can be accepted by loggers.
    num_level = getattr(
        logging,
        config.get('daemon', 'loglevel').upper(),  # pylint: disable=no-member
        None)

    # Set up loggers for stdout, stderr and daemon stream
    log = lib.LoggerExt('daemon',
                        config.get('daemon', 'log_file'),
                        log_level=num_level,
                        maxbytes=config.getint('daemon', 'log_maxbytes'),
                        backupcount=config.getint('daemon', 'log_backups'))
    if config.getboolean('daemon', 'json_logging', fallback=False):
        log.add_central_logging(server=config.get('daemon', 'http_server'),
                                timeout=config.getfloat(
                                    'daemon', 'http_server_timeout'),
                                protocol=config.get('daemon',
                                                    'http_server_protocol'),
                                port=config.get('daemon', 'http_server_port'))
    stdout_log = lib.LoggerExt('stdout',
                               config.get('daemon', 'stdout_file'),
                               log_level=num_level)

    stderrformat = ('%(asctime)s [%(process)d] line:%(lineno)d '
                    'func:%(funcName)s %(levelname)-8s %(threadName)-32s '
                    '%(message)s')
    stderr_log = lib.LoggerExt('stderr',
                               config.get('daemon', 'stderr_file'),
                               log_level=num_level,
                               log_format=stderrformat)

    if config.getboolean('daemon', 'json_logging', fallback=False):
        stderr_log.add_central_logging(
            server=config.get('daemon', 'http_server'),
            timeout=config.getfloat('daemon', 'http_server_timeout'),
            protocol=config.get('daemon', 'http_server_protocol'),
            port=config.get('daemon', 'http_server_port'))

    # Perform a sanity check on IP-Prefixes
    ip_prefixes_sanity_check(log, config, bird_configuration)

    # Make some noise.
    log.debug('Before we are daemonized')
    stdout_log.debug('before we are daemonized')
    stderr_log.debug('before we are daemonized')

    # Get and set the DaemonContext.
    context = lib.LoggingDaemonContext()
    context.loggers_preserve = [log]
    context.stdout_logger = stdout_log
    context.stderr_logger = stderr_log

    # Set pidfile for DaemonContext
    pid_lockfile = PIDLockFile(config.get('daemon', 'pidfile'))
    context.pidfile = pid_lockfile

    # Create our master process.
    checker = healthchecker.HealthChecker(log, config, bird_configuration)

    # Set signal mapping to catch singals and act accordingly.
    context.signal_map = {
        signal.SIGHUP: checker.catch_signal,
        signal.SIGTERM: checker.catch_signal,
    }

    # OK boy go and daemonize yourself.
    with context:
        log.info("starting daemon {}".format(version))
        checker.run()
Exemplo n.º 4
0
def main():
    """Parse CLI and starts daemon."""

    args = docopt(__doc__, version=version)
    if args['--print']:
        for section in DEFAULT_OPTIONS:
            print("[{}]".format(section))
            for key, value in DEFAULT_OPTIONS[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    try:
        config, bird_configuration = load_configuration(args['--file'],
                                                        args['--dir'],
                                                        args['--service-file'])
    except ValueError as exc:
        sys.exit('Invalid configuration: ' + str(exc))

    if args['--check']:
        print("OK")
        sys.exit(0)

    if args['--print-conf']:
        for section in config:
            print("[{}]".format(section))
            for key, value in config[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    # Catch already running process and clean up stale pid file.
    pidfile = config.get('daemon', 'pidfile')
    if os.path.exists(pidfile):
        pid = open(pidfile).read().rstrip()
        try:
            pid = int(pid)
        except ValueError:
            print("Cleaning stale pid file with invalid data:{}".format(pid))
            os.unlink(pidfile)
        else:
            if running(pid):
                sys.exit("Process {} is already running".format(pid))
            else:
                print("Cleaning stale pid file with pid:{}".format(pid))
                os.unlink(pidfile)

    # Create history directories
    for ip_version in bird_configuration:
        config_file = bird_configuration[ip_version]['config_file']
        if bird_configuration[ip_version]['keep_changes']:
            history_dir = os.path.join(
                os.path.dirname(os.path.realpath(config_file)),
                'history'
            )
            try:
                os.mkdir(history_dir)
            except FileExistsError:
                pass
            except OSError as exc:
                sys.exit("failed to make directory {d} for keeping a history "
                         "of changes for {b}:{e}"
                         .format(d=history_dir, b=config_file, e=exc))

    # Map log level to numeric which can be accepted by loggers.
    num_level = getattr(
        logging,
        config.get('daemon', 'loglevel').upper(),  # pylint: disable=no-member
        None
    )

    # Set up loggers for stdout, stderr and daemon stream
    log = lib.LoggerExt(
        'daemon',
        config.get('daemon', 'log_file'),
        log_level=num_level,
        maxbytes=config.getint('daemon', 'log_maxbytes'),
        backupcount=config.getint('daemon', 'log_backups')
    )
    if config.getboolean('daemon', 'json_logging', fallback=False):
        log.add_central_logging(
            server=config.get('daemon', 'http_server'),
            timeout=config.getfloat('daemon', 'http_server_timeout'),
            protocol=config.get('daemon', 'http_server_protocol'),
            port=config.get('daemon', 'http_server_port')
        )
    stdout_log = lib.LoggerExt(
        'stdout',
        config.get('daemon', 'stdout_file'),
        log_level=num_level)

    stderrformat = ('%(asctime)s [%(process)d] line:%(lineno)d '
                    'func:%(funcName)s %(levelname)-8s %(threadName)-32s '
                    '%(message)s')
    stderr_log = lib.LoggerExt(
        'stderr',
        config.get('daemon', 'stderr_file'),
        log_level=num_level,
        log_format=stderrformat)

    if config.getboolean('daemon', 'json_logging', fallback=False):
        stderr_log.add_central_logging(
            server=config.get('daemon', 'http_server'),
            timeout=config.getfloat('daemon', 'http_server_timeout'),
            protocol=config.get('daemon', 'http_server_protocol'),
            port=config.get('daemon', 'http_server_port')
        )

    # Perform a sanity check on IP-Prefixes
    ip_prefixes_sanity_check(log, config, bird_configuration)

    # Make some noise.
    log.debug('Before we are daemonized')
    stdout_log.debug('before we are daemonized')
    stderr_log.debug('before we are daemonized')

    # Get and set the DaemonContext.
    context = lib.LoggingDaemonContext()
    context.loggers_preserve = [log]
    context.stdout_logger = stdout_log
    context.stderr_logger = stderr_log

    # Set pidfile for DaemonContext
    pid_lockfile = PIDLockFile(config.get('daemon', 'pidfile'))
    context.pidfile = pid_lockfile

    # Create our master process.
    checker = healthchecker.HealthChecker(log, config, bird_configuration)

    # Set signal mapping to catch singals and act accordingly.
    context.signal_map = {
        signal.SIGHUP: checker.catch_signal,
        signal.SIGTERM: checker.catch_signal,
    }

    # OK boy go and daemonize yourself.
    with context:
        log.info("starting daemon {}".format(version))
        checker.run()