コード例 #1
0
ファイル: jmx.py プロジェクト: darron/dd-agent
 def _get_dir(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Datadog')
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return path
コード例 #2
0
 def _get_pickle_path(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Datamonitor')
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return os.path.join(path, cls.__name__ + '.pickle')
コード例 #3
0
ファイル: jmx.py プロジェクト: chr0n1x/dd-agent
 def _get_dir(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Datadog')
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return path
コード例 #4
0
ファイル: check_status.py プロジェクト: 7040210/dd-agent
 def _get_pickle_path(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Datadog')
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return os.path.join(path, cls.__name__ + '.pickle')
コード例 #5
0
ファイル: jmx.py プロジェクト: ufou/sd-agent
 def _get_dir(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Server Density')
         if not os.path.isdir(path):
             path = tempfile.gettempdir()
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return path
コード例 #6
0
ファイル: jmx.py プロジェクト: serverdensity/sd-agent
 def _get_dir(cls):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'Server Density')
         if not os.path.isdir(path):
             path = tempfile.gettempdir()
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return path
コード例 #7
0
ファイル: check_status.py プロジェクト: vishalxebia/sts-agent
 def _get_pickle_path(cls, prefix=""):
     if Platform.is_win32():
         path = os.path.join(_windows_commondata_path(), 'StackState')
         if not os.path.isdir(path):
             path = tempfile.gettempdir()
     elif os.path.isdir(PidFile.get_dir()):
         path = PidFile.get_dir()
     else:
         path = tempfile.gettempdir()
     return os.path.join(path, prefix + cls.__name__ + '.pickle')
コード例 #8
0
ファイル: test_config.py プロジェクト: zeus911/sd-agent
    def testBadPidFile(self):
        pid_dir = "/does-not-exist"

        p = PidFile('test', pid_dir)
        path = p.get_path()
        self.assertEquals(path, os.path.join(tempfile.gettempdir(), 'test.pid'))

        pid = "666"
        pid_f = open(path, 'w')
        pid_f.write(pid)
        pid_f.close()

        self.assertEquals(p.get_pid(), 666)
        self.assertEquals(p.clean(), True)
        self.assertEquals(os.path.exists(path), False)
コード例 #9
0
ファイル: test_config.py プロジェクト: KnownSubset/dd-agent
    def testBadPidFile(self):
        pid_dir = "/does-not-exist"

        p = PidFile('test', pid_dir)
        path = p.get_path()
        self.assertEquals(path, os.path.join(tempfile.gettempdir(), 'test.pid'))

        pid = "666"
        pid_f = open(path, 'w')
        pid_f.write(pid)
        pid_f.close()

        self.assertEquals(p.get_pid(), 666)
        self.assertEquals(p.clean(), True)
        self.assertEquals(os.path.exists(path), False)
コード例 #10
0
    def testGoodPidFie(self):
        """Verify that the pid file succeeds and fails appropriately"""

        pid_dir = tempfile.mkdtemp()
        program = 'test'

        expected_path = os.path.join(pid_dir, '%s.pid' % program)
        pid = "666"
        pid_f = open(expected_path, 'w')
        pid_f.write(pid)
        pid_f.close()

        p = PidFile(program, pid_dir)

        self.assertEquals(p.get_pid(), 666)
        # clean up
        self.assertEquals(p.clean(), True)
        self.assertEquals(os.path.exists(expected_path), False)
コード例 #11
0
def main():
    parser = OptionParser()
    parser.add_option('-b',
                      '--background',
                      action='store_true',
                      default=False,
                      dest='background',
                      help='Run agent on the foreground')
    options, args = parser.parse_args()

    if len(args) < 1:
        sys.stderr.write(Agent.usage())
        return 2

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

    try:
        init_config()
    except Exception as e:
        logging.error("Problem initializing configuration: %s", e)
        return 1

    if (os.path.dirname(os.path.realpath(__file__)) != os.path.join(
            DEFAULT_PATH, 'agent')):
        log.info(
            """You don't seem to be running a package installed agent (expected
                 at %s). You may need to specify sane locations for your configs,
                 logs, run path, etc. And remember to drop the configuration
                 file in one of the supported locations.""" % DEFAULT_PATH)

    pid_dir = config.get('run_path')
    agent = Agent(PidFile(PID_NAME, pid_dir).get_path())

    foreground = not options.background
    if 'start' == command:
        logging.info('Start daemon')
        agent.start(foreground=foreground)

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

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

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

    elif 'flare' == command:
        case_id = input(
            'Do you have a support case id? Please enter it here (otherwise just hit enter): '
        ).lower()
        agent.flare(case_id)
コード例 #12
0
ファイル: test_config.py プロジェクト: KnownSubset/dd-agent
    def testGoodPidFie(self):
        """Verify that the pid file succeeds and fails appropriately"""

        pid_dir = tempfile.mkdtemp()
        program = 'test'

        expected_path = os.path.join(pid_dir, '%s.pid' % program)
        pid = "666"
        pid_f = open(expected_path, 'w')
        pid_f.write(pid)
        pid_f.close()

        p = PidFile(program, pid_dir)

        self.assertEquals(p.get_pid(), 666)
        # clean up
        self.assertEquals(p.clean(), True)
        self.assertEquals(os.path.exists(expected_path), False)
コード例 #13
0
def main(config_path=None):
    """ The main entry point for the unix version of sdstatsd. """
    COMMANDS_START_SDSTATSD = ['start', 'stop', 'restart', 'status']

    parser = optparse.OptionParser("%prog [start|stop|restart|status]")
    parser.add_option('-u',
                      '--use-local-forwarder',
                      action='store_true',
                      dest="use_forwarder",
                      default=False)
    opts, args = parser.parse_args()

    in_developer_mode = False
    if not args or args[0] in COMMANDS_START_SDSTATSD:
        reporter, server, cnf = init(config_path,
                                     use_watchdog=True,
                                     use_forwarder=opts.use_forwarder,
                                     args=args)
        daemon = Sdstatsd(
            PidFile(PID_NAME, PID_DIR).get_path(), server, reporter,
            cnf.get('autorestart', False))
        in_developer_mode = cnf.get('developer_mode')

    # If no args were passed in, run the server in the foreground.
    if not args:
        daemon.start(foreground=True)
        return 0

    # Otherwise, we're process the deamon command.
    else:
        command = args[0]

        # TODO: actually kill the start/stop/restart/status command for 5.11
        if command in ['start', 'stop', 'restart', 'status'
                       ] and not in_developer_mode:
            logging.error('Please use supervisor to manage the agent')
            return 1

        if command == 'start':
            daemon.start()
        elif command == 'stop':
            daemon.stop()
        elif command == 'restart':
            daemon.restart()
        elif command == 'status':
            daemon.status()
        elif command == 'info':
            return Sdstatsd.info()
        else:
            sys.stderr.write("Unknown command: %s\n\n" % command)
            parser.print_help()
            return 1
        return 0
コード例 #14
0
def main(config_path=None):
    """ The main entry point for the unix version of dogstatsd. """
    COMMANDS_START_DOGSTATSD = [
        'start',
    ]

    parser = optparse.OptionParser(
        "%prog [{commands}]".format(commands='|'.join(Dogstatsd.COMMANDS)))
    parser.add_option('-u',
                      '--use-local-forwarder',
                      action='store_true',
                      dest="use_forwarder",
                      default=False)
    parser.add_option('-b',
                      '--background',
                      action='store_true',
                      default=False,
                      dest='background',
                      help='Run agent on the foreground')
    options, args = parser.parse_args()

    try:
        init_config()
    except Exception as e:
        logging.error("Problem initializing configuration: %s", e)
        return 1

    if (os.path.dirname(os.path.realpath(__file__)) != os.path.join(
            DEFAULT_PATH, 'agent')):
        log.info(
            """You don't seem to be running a package installed agent (expected
                 at %s). You may need to specify sane locations for your configs,
                 logs, run path, etc. And remember to drop the configuration
                 file in one of the supported locations.""" % DEFAULT_PATH)

    # If no args were passed in, run the server in the foreground.
    pid_dir = config.get('run_path')
    dogstatsd = Dogstatsd(PidFile(PID_NAME, pid_dir).get_path())

    foreground = not options.background
    command = 'start' if not args else args[0]
    if command in COMMANDS_START_DOGSTATSD:
        dogstatsd.start(foreground=foreground)
    elif command == 'stop':
        dogstatsd.stop()
    else:
        sys.stderr.write("Unknown command: %s\n\n" % command)
        parser.print_help()
        sys.exit(1)

    sys.exit(0)
コード例 #15
0
def main(config_path=None):
    """ The main entry point for the unix version of monitorstatsd. """
    # Deprecation notice
    from utils.deprecations import deprecate_old_command_line_tools
    deprecate_old_command_line_tools()

    COMMANDS_START_monitorSTATSD = ['start', 'stop', 'restart', 'status']

    parser = optparse.OptionParser("%prog [start|stop|restart|status]")
    parser.add_option('-u',
                      '--use-local-forwarder',
                      action='store_true',
                      dest="use_forwarder",
                      default=False)
    opts, args = parser.parse_args()

    if not args or args[0] in COMMANDS_START_monitorSTATSD:
        reporter, server, cnf = init(config_path,
                                     use_watchmonitor=True,
                                     use_forwarder=opts.use_forwarder,
                                     args=args)
        daemon = Monitorstatsd(
            PidFile(PID_NAME, PID_DIR).get_path(), server, reporter,
            cnf.get('autorestart', False))

    # If no args were passed in, run the server in the foreground.
    if not args:
        daemon.start(foreground=True)
        return 0

    # Otherwise, we're process the deamon command.
    else:
        command = args[0]

        if command == 'start':
            daemon.start()
        elif command == 'stop':
            daemon.stop()
        elif command == 'restart':
            daemon.restart()
        elif command == 'status':
            daemon.status()
        elif command == 'info':
            return Monitorstatsd.info()
        else:
            sys.stderr.write("Unknown command: %s\n\n" % command)
            parser.print_help()
            return 1
        return 0
コード例 #16
0
def kill_old_process():
    """ Kills or brings to the foreground (if possible) any other instance of this program. It
    avoids multiple icons in the Tray on Windows. On OSX, we don't have to do anything: icons
    don't get duplicated. """
    # Is there another Agent Manager process running ?
    pidfile = PidFile('agent-manager-gui').get_path()

    old_pid = None
    try:
        pf = file(pidfile, 'r')
        old_pid = int(pf.read().strip())
        pf.close()
    except (IOError, ValueError):
        pass

    if old_pid is not None and pid_exists(old_pid):
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False,
                                      old_pid)
        exe_path = win32process.GetModuleFileNameEx(handle, 0)

        # If (and only if) this process is indeed an instance of the GUI, let's kill it
        if 'agent-manager.exe' in exe_path:
            win32api.TerminateProcess(handle, -1)

        win32api.CloseHandle(handle)

    # If we reached that point it means the current process should be the only running
    # agent-manager.exe, let's save its pid
    pid = str(os.getpid())
    try:
        fp = open(pidfile, 'w+')
        fp.write(str(pid))
        fp.close()
    except Exception, e:
        msg = "Unable to write pidfile: %s" % pidfile
        log.exception(msg)
        sys.stderr.write(msg + "\n")
        sys.exit(1)
コード例 #17
0
def kill_old_process():
    """ Kills any other instance of this program. It avoids multiple icons in the Tray on Windows.
    On OSX, we don't have to do anything: icons don't get duplicated.
    TODO: If possible, we should bring the running instance in the foreground instead of killing it"""
    # Is there another Agent Manager process running ?
    pidfile = PidFile('agent-manager-gui').get_path()

    old_pid = None
    try:
        pf = file(pidfile, 'r')
        old_pid = int(pf.read().strip())
        pf.close()
    except (IOError, ValueError):
        pass

    if old_pid is not None:
        try:
            p = psutil.Process(old_pid)
            if 'agent-manager.exe' in p.name():
                p.terminate()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            # Either the process doesn't exist anymore or we don't have access to it (so it's probably not an agent-manager process)
            # In both cases we can consider that the old process isn't running anymore
            pass

    # If we reached that point it means the current process should be the only running
    # agent-manager.exe, let's save its pid
    pid = str(os.getpid())
    try:
        with open(pidfile, 'w+') as fp:
            fp.write(str(pid))
    except Exception as e:
        msg = "Unable to write pidfile: %s %s" % (pidfile, str(e))
        log.exception(msg)
        sys.stderr.write(msg + "\n")
        sys.exit(1)
コード例 #18
0
def main():
    options, args = get_parsed_args()
    agentConfig = get_config(options=options)
    autorestart = agentConfig.get('autorestart', False)
    hostname = get_hostname(agentConfig)
    in_developer_mode = agentConfig.get('developer_mode')

    COMMANDS_AGENT = [
        'start',
        'stop',
        'restart',
        'status',
        'foreground',
    ]

    COMMANDS_NO_AGENT = [
        'info',
        'check',
        'configcheck',
        'jmx',
        'flare',
    ]

    COMMANDS = COMMANDS_AGENT + COMMANDS_NO_AGENT

    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

    # TODO: actually kill the start/stop/restart/status command for 5.11
    if command in ['start', 'stop', 'restart', 'status'
                   ] and not in_developer_mode:
        logging.error('Please use supervisor to manage the agent')
        return 1

    if command in COMMANDS_AGENT:
        agent = Agent(PidFile(PID_NAME, PID_DIR).get_path(),
                      autorestart,
                      in_developer_mode=in_developer_mode)

    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:
        log.info('Agent version %s' % get_version())
        if autorestart:
            # Set-up the supervisor callbacks and fork it.
            logging.info('Running Agent with auto-restart ON')

            def child_func():
                agent.start(foreground=True)

            def parent_func():
                agent.start_event = False

            AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.start(foreground=True)

    elif 'check' == command:
        if len(args) < 2:
            sys.stderr.write(
                "Usage: %s check <check_name> [check_rate]\n"
                "Add check_rate as last argument to compute rates\n" %
                sys.argv[0])
            return 1

        check_name = args[1]
        try:
            import checks.collector
            # Try the old-style check first
            print getattr(checks.collector, check_name)(log).check(agentConfig)
        except Exception:
            # If not an old-style check, try checks.d
            checks = load_check_directory(agentConfig, hostname)
            for check in checks['initialized_checks']:
                if check.name == check_name:
                    if in_developer_mode:
                        check.run = AgentProfiler.wrap_profiling(check.run)

                    cs = Collector.run_single_check(check, verbose=True)
                    print CollectorStatus.render_check_status(cs)

                    if len(args) == 3 and args[2] == 'check_rate':
                        print "Running 2nd iteration to capture rate metrics"
                        time.sleep(1)
                        cs = Collector.run_single_check(check, verbose=True)
                        print CollectorStatus.render_check_status(cs)

                    check.stop()

    elif 'configcheck' == command or 'configtest' == command:
        configcheck()
        sd_configcheck(agentConfig)

    elif 'jmx' == command:
        jmx_command(args[1:], agentConfig)

    elif 'flare' == command:
        Flare.check_user_rights()
        case_id = int(args[1]) if len(args) > 1 else None
        f = Flare(True, case_id)
        f.collect()
        try:
            f.upload()
        except Exception as e:
            print 'The upload failed:\n{0}'.format(str(e))

    return 0
コード例 #19
0
def main():
    options, args = get_parsed_args()
    agentConfig = get_config(options=options)
    autorestart = agentConfig.get('autorestart', False)
    hostname = get_hostname(agentConfig)
    in_developer_mode = agentConfig.get('developer_mode')
    COMMANDS_AGENT = [
        'start',
        'stop',
        'restart',
        'status',
        'foreground',
    ]

    COMMANDS_NO_AGENT = [
        'info',
        'check',
        'configcheck',
        'jmx',
        'flare',
    ]

    COMMANDS = COMMANDS_AGENT + COMMANDS_NO_AGENT

    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

    # Deprecation notice
    if command not in DD_AGENT_COMMANDS:
        # Will become an error message and exit after deprecation period
        from utils.deprecations import deprecate_old_command_line_tools
        deprecate_old_command_line_tools()

    if command in COMMANDS_AGENT:
        agent = Agent(PidFile('sd-agent').get_path(),
                      autorestart,
                      in_developer_mode=in_developer_mode)

    if command in START_COMMANDS:
        log.info('Agent version %s' % 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.start(foreground=True)

            def parent_func():
                agent.start_event = False

            AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.start(foreground=True)

    elif 'check' == command:
        if len(args) < 2:
            sys.stderr.write(
                "Usage: %s check <check_name> [check_rate]\n"
                "Add check_rate as last argument to compute rates\n" %
                sys.argv[0])
            return 1

        check_name = args[1]
        try:
            import checks.collector
            # Try the old-style check first
            print getattr(checks.collector, check_name)(log).check(agentConfig)
        except Exception:
            # If not an old-style check, try checks.d
            checks = load_check_directory(agentConfig, hostname)
            for check in checks['initialized_checks']:
                if check.name == check_name:
                    if in_developer_mode:
                        check.run = AgentProfiler.wrap_profiling(check.run)

                    cs = Collector.run_single_check(check, verbose=True)
                    print CollectorStatus.render_check_status(cs)

                    if len(args) == 3 and args[2] == 'check_rate':
                        print "Running 2nd iteration to capture rate metrics"
                        time.sleep(1)
                        cs = Collector.run_single_check(check, verbose=True)
                        print CollectorStatus.render_check_status(cs)

                    check.stop()

    elif 'configcheck' == command or 'configtest' == command:
        configcheck()

    elif 'jmx' == command:
        jmx_command(args[1:], agentConfig)

    return 0
コード例 #20
0
    # variable acts as a fail-safe which aborts the application if this
    # happens more than once. Similar situation arises when another clipboard
    # management app (like GPaste) is running alongside chaos.
    os.environ["QT_FATAL_WARNINGS"] = "1"

    signal.signal(signal.SIGTERM, qt_quit)
    signal.signal(signal.SIGINT, qt_quit)
    signal.signal(signal.SIGTSTP, qt_quit)
    signal.signal(signal.SIGHUP, qt_quit)

    app = QGuiApplication(sys.argv)
    timer(100, lambda: None)
    cb = Clipboard(config_dict)
    sys.exit(app.exec_())


if __name__ == "__main__":
    uid = os.geteuid()
    pid_path = "/tmp/chaos-{}.pid".format(uid)
    config_dict = get_config()

    context = DaemonContext(
        stdin=sys.stdin,
        stdout=sys.stdout,
        stderr=sys.stderr,
        pidfile=PidFile(pid_path),
    )

    with context:
        execute_app(config_dict)
コード例 #21
0
ファイル: agent.py プロジェクト: degemer/dd-agent
def main():
    options, args = get_parsed_args()
    agentConfig = get_config(options=options)
    autorestart = agentConfig.get('autorestart', False)
    hostname = get_hostname(agentConfig)

    COMMANDS_AGENT = [
        'start',
        'stop',
        'restart',
        'status',
        'foreground',
    ]

    COMMANDS_NO_AGENT = [
        'info',
        'check',
        'configcheck',
        'jmx',
        'flare',
    ]

    COMMANDS = COMMANDS_AGENT + COMMANDS_NO_AGENT

    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

    # Deprecation notice
    if command not in DD_AGENT_COMMANDS:
        # Will become an error message and exit after deprecation period
        from utils.deprecations import deprecate_old_command_line_tools
        deprecate_old_command_line_tools()

    if command in COMMANDS_AGENT:
        agent = Agent(PidFile('dd-agent').get_path(), autorestart)

    if command in START_COMMANDS:
        log.info('Agent version %s' % 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.start(foreground=True)

            def parent_func():
                agent.start_event = False

            AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.start(foreground=True)

    elif 'check' == command:
        if len(args) < 2:
            sys.stderr.write(
                "Usage: %s check <check_name> [check_rate]\n"
                "Add check_rate as last argument to compute rates\n" %
                sys.argv[0])
            return 1

        check_name = args[1]
        try:
            import checks.collector
            # Try the old-style check first
            print getattr(checks.collector, check_name)(log).check(agentConfig)
        except Exception:
            # If not an old-style check, try checks.d
            checks = load_check_directory(agentConfig, hostname)
            for check in checks['initialized_checks']:
                if check.name == check_name:
                    check.run()
                    print check.get_metrics()
                    print check.get_events()
                    print check.get_service_checks()
                    if len(args) == 3 and args[2] == 'check_rate':
                        print "Running 2nd iteration to capture rate metrics"
                        time.sleep(1)
                        check.run()
                        print check.get_metrics()
                        print check.get_events()
                        print check.get_service_checks()
                    check.stop()

    elif 'configcheck' == command or 'configtest' == command:
        configcheck()

    elif 'jmx' == command:
        from jmxfetch import JMX_LIST_COMMANDS, JMXFetch

        if len(args) < 2 or args[1] not in JMX_LIST_COMMANDS.keys():
            print "#" * 80
            print "JMX tool to be used to help configuring 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 JMX_LIST_COMMANDS.iteritems():
                print "      - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command,
                                                                     desc)
            print "Example: sudo /etc/init.d/datadog-agent jmx list_matching_attributes tomcat jmx solr"
            print "\n"

        else:
            jmx_command = args[1]
            checks_list = args[2:]
            confd_directory = get_confd_path(get_os())

            jmx_process = JMXFetch(confd_directory, agentConfig)
            jmx_process.configure()
            should_run = jmx_process.should_run()

            if should_run:
                jmx_process.run(jmx_command, checks_list, reporter="console")
            else:
                print "Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_directory
                print "Have you enabled any JMX check ?"
                print "If you think it's not normal please get in touch with Datadog Support"

    elif 'flare' == command:
        Flare.check_user_rights()
        case_id = int(args[1]) if len(args) > 1 else None
        f = Flare(True, case_id)
        f.collect()
        try:
            f.upload()
        except Exception, e:
            print 'The upload failed:\n{0}'.format(str(e))
コード例 #22
0
ファイル: agent.py プロジェクト: geowa4/dd-agent
def main():
    options, args = get_parsed_args()
    agentConfig = get_config(options=options)
    autorestart = agentConfig.get('autorestart', False)
    hostname = get_hostname(agentConfig)
    in_developer_mode = agentConfig.get('developer_mode')
    COMMANDS_AGENT = [
        'start',
        'stop',
        'restart',
        'status',
        'foreground',
    ]

    COMMANDS_NO_AGENT = [
        'info',
        'check',
        'configcheck',
        'jmx',
        'flare',
    ]

    COMMANDS = COMMANDS_AGENT + COMMANDS_NO_AGENT

    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

    # Deprecation notice
    if command not in DD_AGENT_COMMANDS:
        # Will become an error message and exit after deprecation period
        from utils.deprecations import deprecate_old_command_line_tools
        deprecate_old_command_line_tools()

    if command in COMMANDS_AGENT:
        agent = Agent(PidFile(PID_NAME, PID_DIR).get_path(),
                      autorestart,
                      in_developer_mode=in_developer_mode)

    if command in START_COMMANDS:
        log.info('Agent version %s' % 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.start(foreground=True)

            def parent_func():
                agent.start_event = False

            AgentSupervisor.start(parent_func, child_func)
        else:
            # Run in the standard foreground.
            agent.start(foreground=True)

    elif 'check' == command:
        if len(args) < 2:
            sys.stderr.write(
                "Usage: %s check <check_name> [check_rate]\n"
                "Add check_rate as last argument to compute rates\n" %
                sys.argv[0])
            return 1

        check_name = args[1]
        try:
            import checks.collector
            # Try the old-style check first
            print getattr(checks.collector, check_name)(log).check(agentConfig)
        except Exception:
            # If not an old-style check, try checks.d
            checks = load_check_directory(agentConfig, hostname)
            for check in checks['initialized_checks']:
                if check.name == check_name:
                    if in_developer_mode:
                        check.run = AgentProfiler.wrap_profiling(check.run)

                    cs = Collector.run_single_check(check, verbose=True)
                    print CollectorStatus.render_check_status(cs)

                    if len(args) == 3 and args[2] == 'check_rate':
                        print "Running 2nd iteration to capture rate metrics"
                        time.sleep(1)
                        cs = Collector.run_single_check(check, verbose=True)
                        print CollectorStatus.render_check_status(cs)

                    check.stop()

    elif 'configcheck' == command or 'configtest' == command:
        configcheck()

        if agentConfig.get('service_discovery', False):
            # set the TRACE_CONFIG flag to True to make load_check_directory return
            # the source of config objects.
            # Then call load_check_directory here and pass the result to sd_configcheck
            # to avoid circular imports
            agentConfig[TRACE_CONFIG] = True
            configs = {
                # check_name: (config_source, config)
            }
            print("\nLoading check configurations...\n\n")
            configs = load_check_directory(agentConfig, hostname)
            sd_configcheck(agentConfig, configs)

    elif 'jmx' == command:
        jmx_command(args[1:], agentConfig)

    elif 'flare' == command:
        Flare.check_user_rights()
        case_id = int(args[1]) if len(args) > 1 else None
        f = Flare(True, case_id)
        f.collect()
        try:
            f.upload()
        except Exception, e:
            print 'The upload failed:\n{0}'.format(str(e))
コード例 #23
0
def main():
    CRED = '\033[91m'
    CEND = '\033[0m'

    parser = OptionParser()
    parser.add_option('-b',
                      '--background',
                      action='store_true',
                      default=False,
                      dest='background',
                      help='Run agent on the foreground')
    parser.add_option('-l',
                      '--force-logging',
                      action='store_true',
                      default=False,
                      dest='logging',
                      help='force logging')
    parser.add_option('-m',
                      '--manual',
                      action='store_true',
                      default=False,
                      dest='manual',
                      help='Apply action manually - advanced feature')
    options, args = parser.parse_args()
    if len(args) < 1:
        sys.stderr.write(Agent.usage())
        return 2

    command = args[0]
    if command not in Agent.COMMANDS:
        sys.stderr.write(CRED + "Unknown command: {}\n".format(command) + CEND)
        return 3

    try:
        do_log = options.logging or Agent.COMMANDS[command]
        init_config(do_log=do_log)
    except Exception as e:
        logging.error(CRED +
                      "Problem initializing configuration: {}".format(e) +
                      CEND)
        return 1

    if (os.path.dirname(os.path.realpath(__file__)) != os.path.join(
            DEFAULT_PATH, 'agent')):
        log.info(
            """You don't seem to be running a package installed agent (expected
                 at %s). You may need to specify sane locations for your configs,
                 logs, run path, etc. And remember to drop the configuration
                 file in one of the supported locations.""" % DEFAULT_PATH)

        # if pid_dir below doesn't exist a temporary dir will be used
        pid_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'run')
    else:
        pid_dir = config.get('run_path')

    agent = Agent(PidFile(PID_NAME, pid_dir).get_path())

    foreground = not options.background
    manual = options.manual
    if 'start' == command:
        if manual:
            logging.info('Start daemon')
            agent.start(foreground=foreground)
        else:
            sys.stderr.write(CRED +
                             'Please use OS facilities to start the agent!\n' +
                             CEND)
            return 1

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

    elif 'restart' == command:
        if manual:
            logging.info('Restart daemon')
            agent.restart()
        else:
            sys.stderr.write(
                CRED + 'Please use OS facilities to restart the agent!\n' +
                CEND)
            return 1

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

    elif 'flare' == command:
        case_id = input(
            'Do you have a support case id? Please enter it here (otherwise just hit enter): '
        ).lower()
        agent.flare(config, case_id)
コード例 #24
0
ファイル: stsstatsd.py プロジェクト: vishalxebia/sts-agent
def main(config_path=None):
    """ The main entry point for the unix version of dogstatsd. """
    COMMANDS_START_DOGSTATSD = [
        'start',
        'stop',
        'restart',
        'status'
    ]

    parser = optparse.OptionParser("%prog [start|stop|restart|status]")
    parser.add_option('-u', '--use-local-forwarder', action='store_true',
                      dest="use_forwarder", default=False)
    opts, args = parser.parse_args()

    c = get_config(parse_args=False, cfg_path=config_path)
    dsd6_enabled = Dogstatsd6.enabled(c)
    in_developer_mode = False
    if not args or args[0] in COMMANDS_START_DOGSTATSD:
        if dsd6_enabled:
            dsd6_path, env = init6(c, config_path, args)
            dsd6 = Dogstatsd6(c)
        else:
            reporter, server = init5(c, use_watchdog=True, use_forwarder=opts.use_forwarder, args=args)
            daemon = Dogstatsd(PidFile(PID_NAME, PID_DIR).get_path(), server, reporter,
                            c.get('autorestart', False))
            in_developer_mode = c.get('developer_mode')

    # If no args were passed in, run the server in the foreground.
    if not args:
        if dsd6_enabled:
            logging.info("Launching Dogstatsd6 - logging to dogstatsd6.log")
            dsd6.execute([dsd6_path, 'start'], env=env)
        else:
            daemon.start(foreground=True)
            return 0

    # Otherwise, we're process the deamon command.
    else:
        command = args[0]

        # TODO: actually kill the start/stop/restart/status command for 5.11
        if command in ['start', 'stop', 'restart', 'status'] and not in_developer_mode:
            logging.error('Please use supervisor to manage the agent')
            return 1

        if command == 'start':
            if not dsd6_enabled:
                daemon.start()
        elif command == 'stop':
            if not dsd6_enabled:
                daemon.stop()
        elif command == 'restart':
            if not dsd6_enabled:
                daemon.restart()
        elif command == 'status':
            if dsd6_enabled:
                message = 'Status unavailable for dogstatsd6'
                log.warning(message)
                sys.stderr.write(message)
            else:
                daemon.status()
        elif command == 'info':
            if dsd6_enabled:
                return Dogstatsd6.info(c)
            else:
                return Dogstatsd.info(c)
        else:
            sys.stderr.write("Unknown command: %s\n\n" % command)
            parser.print_help()
            return 1
        return 0