Exemple #1
0
 def test_verify_common_config_opts(self):
     opts = util.get_parsed_args(prog='test')
     opts_dict = vars(opts[0])
     self.assertCountEqual(['config_file', 'clean', 'verbose'],
                          opts_dict.keys())
Exemple #2
0
def main():
    options, args = util.get_parsed_args()
    config = cfg.Config()
    collector_config = config.get_config(['Main', 'Api', 'Logging'])
    # todo autorestart isn't used remove
    autorestart = collector_config.get('autorestart', False)

    COMMANDS = [
        'start',
        'stop',
        'restart',
        'foreground',
        'status',
        'info',
        'check',
        'check_all',
        'configcheck',
        'jmx',
    ]

    if len(args) < 1:
        sys.stderr.write("Usage: %s %s\n" % (sys.argv[0], "|".join(COMMANDS)))
        return 2

    command = args[0]
    if command not in COMMANDS:
        sys.stderr.write("Unknown command: %s\n" % command)
        return 3

    pid_file = util.PidFile('monasca-agent')

    if options.clean:
        pid_file.clean()

    agent = CollectorDaemon(pid_file.get_path(), autorestart)

    if command in START_COMMANDS:
        log.info('Agent version %s' % config.get_version())

    if 'start' == command:
        log.info('Start daemon')
        agent.start()

    elif 'stop' == command:
        log.info('Stop daemon')
        agent.stop()

    elif 'restart' == command:
        log.info('Restart daemon')
        agent.restart()

    elif 'status' == command:
        agent.status()

    elif 'info' == command:
        return agent.info(verbose=options.verbose)

    elif 'foreground' == command:
        logging.info('Running in foreground')
        if autorestart:
            # Set-up the supervisor callbacks and fork it.
            logging.info('Running Agent with auto-restart ON')

            def child_func():
                agent.run()

            def parent_func():
                agent.start_event = False

            monasca_agent.common.daemon.AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.run(collector_config)

    elif 'check' == command:
        check_name = args[1]
        checks = util.load_check_directory()
        for check in checks['initialized_checks']:
            if check.name == check_name:
                run_check(check)

    elif 'check_all' == command:
        print("Loading check directory...")
        checks = util.load_check_directory()
        print("...directory loaded.\n")
        for check in checks['initialized_checks']:
            run_check(check)

    elif 'configcheck' == command or 'configtest' == command:
        osname = util.get_os()
        all_valid = True
        paths = util.Paths()
        for conf_path in glob.glob(os.path.join(paths.get_confd_path(), "*.yaml")):
            basename = os.path.basename(conf_path)
            try:
                config.check_yaml(conf_path)
            except Exception as e:
                all_valid = False
                print("%s contains errors:\n    %s" % (basename, e))
            else:
                print("%s is valid" % basename)
        if all_valid:
            print("All yaml files passed. You can now run the Monitoring agent.")
            return 0
        else:
            print("Fix the invalid yaml files above in order to start the Monitoring agent. "
                  "A useful external tool for yaml parsing can be found at "
                  "http://yaml-online-parser.appspot.com/")
            return 1

    elif 'jmx' == command:

        if len(args) < 2 or args[1] not in jmxfetch.JMX_LIST_COMMANDS.keys():
            print("#" * 80)
            print("JMX tool to be used to help configure your JMX checks.")
            print("See http://docs.datadoghq.com/integrations/java/ for more information")
            print("#" * 80)
            print("\n")
            print("You have to specify one of the following commands:")
            for command, desc in jmxfetch.JMX_LIST_COMMANDS.iteritems():
                print("      - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command, desc))
            print("Example: sudo /etc/init.d/monasca-agent jmx list_matching_attributes tomcat jmx solr")
            print("\n")

        else:
            jmx_command = args[1]
            checks_list = args[2:]
            paths = util.Paths()
            confd_path = paths.get_confd_path()
            # Start JMXFetch if needed
            should_run = jmxfetch.JMXFetch.init(confd_path,
                                                config,
                                                15,
                                                jmx_command,
                                                checks_list,
                                                reporter="console")
            if not should_run:
                print("Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_path)
                print("Have you enabled any JMX checks ?")

    return 0
Exemple #3
0
    def __init__(self, configFile=None):
        # importing it here, in order to avoid a circular import
        # as monasca_agent.common.util imports this module.
        from monasca_agent.common import util

        options, args = util.get_parsed_args()
        if configFile is not None:
            self._configFile = configFile
        elif options.config_file is not None:
            self._configFile = options.config_file
        elif os.path.exists(DEFAULT_CONFIG_FILE):
            self._configFile = DEFAULT_CONFIG_FILE
        elif os.path.exists(os.getcwd() + '/agent.yaml'):
            self._configFile = os.getcwd() + '/agent.yaml'
        else:
            error_msg = 'No config file found at {0} nor in the working directory.'.format(
                DEFAULT_CONFIG_FILE)
            log.error(error_msg)
            raise IOError(error_msg)

        # Define default values for the possible config items
        self._config = {'Main': {'check_freq': 15,
                                 'forwarder_url': 'http://localhost:17123',
                                 'hostname': None,
                                 'dimensions': None,
                                 'listen_port': None,
                                 'version': self.get_version(),
                                 'additional_checksd': '/usr/lib/monasca/agent/custom_checks.d',
                                 'limit_memory_consumption': None,
                                 'skip_ssl_validation': False,
                                 'autorestart': True,
                                 'non_local_traffic': False,
                                 'sub_collection_warn': 6,
                                 'collector_restart_interval': 24},
                        'Api': {'is_enabled': False,
                                'url': '',
                                'project_name': '',
                                'project_id': '',
                                'project_domain_name': '',
                                'project_domain_id': '',
                                'ca_file': '',
                                'insecure': False,
                                'username': '',
                                'password': '',
                                'use_keystone': True,
                                'keystone_timeout': 20,
                                'keystone_url': '',
                                'max_buffer_size': 1000,
                                'max_measurement_buffer_size': -1,
                                'write_timeout': 10,
                                'backlog_send_rate': 5,
                                'max_batch_size': 0},
                        'Statsd': {'recent_point_threshold': None,
                                   'monasca_statsd_interval': 20,
                                   'monasca_statsd_forward_host': None,
                                   'monasca_statsd_forward_port': 8125,
                                   'monasca_statsd_port': 8125},
                        'Logging': {'disable_file_logging': False,
                                    'log_level': None,
                                    'collector_log_file': DEFAULT_LOG_DIR + '/collector.log',
                                    'forwarder_log_file': DEFAULT_LOG_DIR + '/forwarder.log',
                                    'statsd_log_file': DEFAULT_LOG_DIR + '/statsd.log',
                                    'jmxfetch_log_file': DEFAULT_LOG_DIR + '/jmxfetch.log',
                                    'enable_logrotate': True,
                                    'log_to_event_viewer': False,
                                    'log_to_syslog': False,
                                    'syslog_host': None,
                                    'syslog_port': None}}

        self._read_config()
Exemple #4
0
    def __init__(self, configFile=None):
        # importing it here, in order to avoid a circular import
        # as monasca_agent.common.util imports this module.
        from monasca_agent.common import util

        options, args = util.get_parsed_args()
        if configFile is not None:
            self._configFile = configFile
        elif options.config_file is not None:
            self._configFile = options.config_file
        elif os.path.exists(DEFAULT_CONFIG_FILE):
            self._configFile = DEFAULT_CONFIG_FILE
        elif os.path.exists(os.getcwd() + '/agent.yaml'):
            self._configFile = os.getcwd() + '/agent.yaml'
        else:
            error_msg = 'No config file found at {0} nor in the working directory.'.format(
                DEFAULT_CONFIG_FILE)
            log.error(error_msg)
            raise IOError(error_msg)

        # Define default values for the possible config items
        self._config = {
            'Main': {
                'check_freq': 15,
                'forwarder_url': 'http://localhost:17123',
                'hostname': None,
                'dimensions': None,
                'listen_port': None,
                'version': self.get_version(),
                'additional_checksd': '/usr/lib/monasca/agent/custom_checks.d',
                'limit_memory_consumption': None,
                'skip_ssl_validation': False,
                'autorestart': True,
                'non_local_traffic': False,
                'sub_collection_warn': 6,
                'collector_restart_interval': 24
            },
            'Api': {
                'is_enabled': False,
                'url': '',
                'project_name': '',
                'project_id': '',
                'project_domain_name': '',
                'project_domain_id': '',
                'ca_file': '',
                'insecure': '',
                'username': '',
                'password': '',
                'use_keystone': True,
                'keystone_timeout': 20,
                'keystone_url': '',
                'max_buffer_size': 1000,
                'max_measurement_buffer_size': -1,
                'write_timeout': 10,
                'backlog_send_rate': 5
            },
            'Statsd': {
                'recent_point_threshold': None,
                'monasca_statsd_interval': 20,
                'monasca_statsd_forward_host': None,
                'monasca_statsd_forward_port': 8125,
                'monasca_statsd_port': 8125
            },
            'Logging': {
                'disable_file_logging': False,
                'log_level': None,
                'collector_log_file': DEFAULT_LOG_DIR + '/collector.log',
                'forwarder_log_file': DEFAULT_LOG_DIR + '/forwarder.log',
                'statsd_log_file': DEFAULT_LOG_DIR + '/statsd.log',
                'jmxfetch_log_file': DEFAULT_LOG_DIR + '/jmxfetch.log',
                'log_to_event_viewer': False,
                'log_to_syslog': False,
                'syslog_host': None,
                'syslog_port': None
            }
        }

        self._read_config()
Exemple #5
0
def main():
    options, args = util.get_parsed_args()
    config = cfg.Config()
    collector_config = config.get_config(['Main', 'Api', 'Logging'])
    # todo autorestart isn't used remove
    autorestart = collector_config.get('autorestart', False)

    COMMANDS = [
        'start',
        'stop',
        'restart',
        'foreground',
        'status',
        'info',
        'check',
        'check_all',
        'configcheck',
        'jmx',
    ]

    if len(args) < 1:
        sys.stderr.write("Usage: %s %s\n" % (sys.argv[0], "|".join(COMMANDS)))
        return 2

    command = args[0]
    if command not in COMMANDS:
        sys.stderr.write("Unknown command: %s\n" % command)
        return 3

    pid_file = util.PidFile('monasca-agent')

    if options.clean:
        pid_file.clean()

    agent = CollectorDaemon(pid_file.get_path(), autorestart)

    if command in START_COMMANDS:
        log.info('Agent version %s' % config.get_version())

    if 'start' == command:
        log.info('Start daemon')
        agent.start()

    elif 'stop' == command:
        log.info('Stop daemon')
        agent.stop()

    elif 'restart' == command:
        log.info('Restart daemon')
        agent.restart()

    elif 'status' == command:
        agent.status()

    elif 'info' == command:
        return agent.info(verbose=options.verbose)

    elif 'foreground' == command:
        logging.info('Running in foreground')
        if autorestart:
            # Set-up the supervisor callbacks and fork it.
            logging.info('Running Agent with auto-restart ON')

            def child_func():
                agent.run()

            def parent_func():
                agent.start_event = False

            monasca_agent.common.daemon.AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.run(collector_config)

    elif 'check' == command:
        check_name = args[1]
        checks = util.load_check_directory()
        for check in checks['initialized_checks']:
            if check.name == check_name:
                run_check(check)

    elif 'check_all' == command:
        print("Loading check directory...")
        checks = util.load_check_directory()
        print("...directory loaded.\n")
        for check in checks['initialized_checks']:
            run_check(check)

    elif 'configcheck' == command or 'configtest' == command:
        all_valid = True
        paths = util.Paths()
        for conf_path in glob.glob(os.path.join(paths.get_confd_path(), "*.yaml")):
            basename = os.path.basename(conf_path)
            try:
                config.check_yaml(conf_path)
            except Exception as e: 
               all_valid = False
                print("%s contains errors:\n    %s" % (basename, e))
            else:
                print("%s is valid" % basename)
        if all_valid:
            print("All yaml files passed. You can now run the Monitoring agent.")
            return 0
        else:
            print("Fix the invalid yaml files above in order to start the Monitoring agent. "
                  "A useful external tool for yaml parsing can be found at "
                  "http://yaml-online-parser.appspot.com/")
            return 1
Exemple #6
0
def main():
    options, args = util.get_parsed_args()
    config = cfg.Config()
    collector_config = config.get_config(["Main", "Api", "Logging"])
    autorestart = collector_config.get("autorestart", False)

    collector_restart_interval = collector_config.get("collector_restart_interval", 24)
    if collector_restart_interval in range(1, 49):
        pass
    else:
        log.error(
            "Collector_restart_interval = {0} is out of legal range"
            " [1, 48]. Reset collector_restart_interval to 24".format(collector_restart_interval)
        )
        collector_restart_interval = 24

    COMMANDS = ["start", "stop", "restart", "foreground", "status", "info", "check", "check_all", "configcheck", "jmx"]

    if len(args) < 1:
        sys.stderr.write("Usage: %s %s\n" % (sys.argv[0], "|".join(COMMANDS)))
        return 2

    command = args[0]
    if command not in COMMANDS:
        sys.stderr.write("Unknown command: %s\n" % command)
        return 3

    pid_file = util.PidFile("monasca-agent")

    if options.clean:
        pid_file.clean()

    agent = CollectorDaemon(pid_file.get_path(), autorestart)

    if command in START_COMMANDS:
        log.info("Agent version %s" % config.get_version())

    if "start" == command:
        log.info("Start daemon")
        agent.start()

    elif "stop" == command:
        log.info("Stop daemon")
        agent.stop()

    elif "restart" == command:
        log.info("Restart daemon")
        agent.restart()

    elif "status" == command:
        agent.status()

    elif "info" == command:
        return agent.info(verbose=options.verbose)

    elif "foreground" == command:
        logging.info("Running in foreground")
        if autorestart:
            # Set-up the supervisor callbacks and fork it.
            logging.info("Running Agent with auto-restart ON")
        # Run in the standard foreground.
        agent.run(collector_config)

    elif "check" == command:
        check_name = args[1]
        checks = util.load_check_directory()
        for check in checks["initialized_checks"]:
            if check.name == check_name:
                run_check(check)

    elif "check_all" == command:
        print("Loading check directory...")
        checks = util.load_check_directory()
        print("...directory loaded.\n")
        for check in checks["initialized_checks"]:
            run_check(check)

    elif "configcheck" == command or "configtest" == command:
        all_valid = True
        paths = util.Paths()
        for conf_path in glob.glob(os.path.join(paths.get_confd_path(), "*.yaml")):
            basename = os.path.basename(conf_path)
            try:
                config.check_yaml(conf_path)
            except Exception as e:
                all_valid = False
                print("%s contains errors:\n    %s" % (basename, e))
            else:
                print("%s is valid" % basename)
        if all_valid:
            print("All yaml files passed. You can now run the Monitoring agent.")
            return 0
        else:
            print(
                "Fix the invalid yaml files above in order to start the Monitoring agent. "
                "A useful external tool for yaml parsing can be found at "
                "http://yaml-online-parser.appspot.com/"
            )
            return 1

    elif "jmx" == command:

        if len(args) < 2 or args[1] not in jmxfetch.JMX_LIST_COMMANDS.keys():
            print("#" * 80)
            print("JMX tool to be used to help configure your JMX checks.")
            print("See http://docs.datadoghq.com/integrations/java/ for more information")
            print("#" * 80)
            print("\n")
            print("You have to specify one of the following commands:")
            for command, desc in jmxfetch.JMX_LIST_COMMANDS.iteritems():
                print("      - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command, desc))
            print("Example: sudo /etc/init.d/monasca-agent jmx list_matching_attributes tomcat jmx solr")
            print("\n")

        else:
            jmx_command = args[1]
            checks_list = args[2:]
            paths = util.Paths()
            confd_path = paths.get_confd_path()
            # Start JMXFetch if needed
            should_run = jmxfetch.JMXFetch.init(confd_path, config, 15, jmx_command, checks_list, reporter="console")
            if not should_run:
                print("Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_path)
                print("Have you enabled any JMX checks ?")

    return 0
 def test_verify_common_config_opts(self):
     opts = util.get_parsed_args(prog='test')
     opts_dict = vars(opts[0])
     self.assertItemsEqual(['config_file', 'clean', 'verbose'],
                           opts_dict.keys())