예제 #1
0
 def test_install_extras_fails_with_bad_return_code(
         self, extras_installed_cmd, mock_http_get_to_file):
     extras_installed_cmd.return_value = False
     mock_http_get_to_file.return_value = False
     config_files = config.get_config_files()
     conf = config.AgentConfig(config_files)
     conf.extra_location = "fake"
     conf_args = [conf]
     with patch('dcm.agent.utils.run_command') as mock_run_cmd:
         mock_run_cmd.return_value = ('stdout', 'stderr', 1)
         self.assertRaises(Exception, agent_utils.install_extras, conf_args)
예제 #2
0
 def test_install_extras_passes_with_good_return_code(
         self, extras_installed_cmd, mock_http_get_to_file):
     extras_installed_cmd.return_value = False
     mock_http_get_to_file.return_value = False
     config_files = config.get_config_files()
     conf = config.AgentConfig(config_files)
     conf.extra_location = "fake"
     with patch('dcm.agent.utils.run_command') as mock_run_cmd:
         mock_run_cmd.return_value = ('stdout', 'stderr', 0)
         result = agent_utils.install_extras(conf)
     self.assertTrue(result)
예제 #3
0
 def test_install_extras_passes_with_good_return_code(
         self, extras_installed_cmd, mock_http_get_to_file):
     extras_installed_cmd.return_value = False
     mock_http_get_to_file.return_value = False
     config_files = config.get_config_files()
     conf = config.AgentConfig(config_files)
     conf.extra_location = "fake"
     with patch('dcm.agent.utils.run_command') as mock_run_cmd:
         mock_run_cmd.return_value = ('stdout', 'stderr', 0)
         result = agent_utils.install_extras(conf)
     self.assertTrue(result)
예제 #4
0
    def test_get_conf_files(self):
        osf, path = tempfile.mkstemp()
        osf, path2 = tempfile.mkstemp()
        os.environ["DCM_AGENT_CONF"] = path2

        try:
            file_list = config.get_config_files(conffile=path)
            self.assertIn(path, file_list)
            self.assertIn(path2, file_list)
        finally:
            utils.safe_delete(path)
            utils.safe_delete(path2)
예제 #5
0
 def test_install_extras_fails_with_bad_return_code(self,
                                                    extras_installed_cmd,
                                                    mock_http_get_to_file):
     extras_installed_cmd.return_value = False
     mock_http_get_to_file.return_value = False
     config_files = config.get_config_files()
     conf = config.AgentConfig(config_files)
     conf.extra_location = "fake"
     conf_args = [conf]
     with patch('dcm.agent.utils.run_command') as mock_run_cmd:
         mock_run_cmd.return_value = ('stdout', 'stderr', 1)
         self.assertRaises(Exception, agent_utils.install_extras, conf_args)
예제 #6
0
    def test_get_conf_files(self):
        osf, path = tempfile.mkstemp()
        osf, path2 = tempfile.mkstemp()
        os.environ["DCM_AGENT_CONF"] = path2

        try:
            file_list = config.get_config_files(conffile=path)
            self.assertIn(path, file_list)
            self.assertIn(path2, file_list)
        finally:
            utils.safe_delete(path)
            utils.safe_delete(path2)
예제 #7
0
def clean_agent_files(opts, tar):
    console_output(opts, 2, "Cleaning the agent files.")
    files_to_clean = ['/var/lib/waagent/provisioned',
                      '/tmp/boot.log',
                      '/tmp/agent_info.tar.gz',
                      '/tmp/meta_info.txt',
                      '/tmp/process_info.txt',
                      '/tmp/startup_script.txt',
                      '/tmp/error.log',
                      '/tmp/installer.sh']

    conf = config.AgentConfig(config.get_config_files())
    log_dir = os.path.join(conf.storage_base_dir, "logs")

    if not opts.agent_running:
        clean_agent_logs(opts, tar, log_dir)
        files_to_clean.append(conf.storage_dbfile)

    for f in files_to_clean:
        if os.path.exists(f):
            secure_delete(opts, tar, f)
예제 #8
0
파일: service.py 프로젝트: QSFT/unix-agent
def start_main_service(cli_args):
    agent = None
    try:
        config_files = config.get_config_files(conffile=cli_args.conffile)
        conf = config.AgentConfig(config_files)
        agent = DCMAgent(conf)
        if cli_args.version:
            print("Version %s" % dcm.agent.g_version)
            return 0

        agent.pre_threads()
        if cli_args.report:
            utils._g_logger.disabled = True
            cm._g_logger.disabled = True
            config._g_logger.disabled = True
            agent.g_logger.disabled = True
            _gather_info(conf)
            return 0

        utils.verify_config_file(conf)
        conf.start_job_runner()
        agent.run_agent()
    except exceptions.AgentOptionException as aoex:
        console_log(
            cli_args, 0, "The agent is not configured properly. "
            "please check the config file.")
        console_log(cli_args, 0, str(aoex))
        if agent:
            agent.shutdown_main_loop()
        if getattr(cli_args, "verbose", 0) > 2:
            raise
    except Exception:
        _g_logger = logging.getLogger(__name__)
        console_log(cli_args, 0, "Shutting down due to a top level exception")
        _g_logger.exception("An unknown exception bubbled to the top")
        if agent:
            agent.shutdown_main_loop()
        raise
    return 0
예제 #9
0
파일: service.py 프로젝트: JPWKU/unix-agent
def start_main_service(cli_args):
    agent = None
    try:
        config_files = config.get_config_files(conffile=cli_args.conffile)
        conf = config.AgentConfig(config_files)
        agent = DCMAgent(conf)
        if cli_args.version:
            print("Version %s" % dcm.agent.g_version)
            return 0

        agent.pre_threads()
        if cli_args.report:
            utils._g_logger.disabled = True
            cm._g_logger.disabled = True
            config._g_logger.disabled = True
            agent.g_logger.disabled = True
            _gather_info(conf)
            return 0

        utils.verify_config_file(conf)
        conf.start_job_runner()
        agent.run_agent()
    except exceptions.AgentOptionException as aoex:
        console_log(cli_args, 0, "The agent is not configured properly. " "please check the config file.")
        console_log(cli_args, 0, str(aoex))
        if agent:
            agent.shutdown_main_loop()
        if getattr(cli_args, "verbose", 0) > 2:
            raise
    except Exception:
        _g_logger = logging.getLogger(__name__)
        console_log(cli_args, 0, "Shutting down due to a top level exception")
        _g_logger.exception("An unknown exception bubbled to the top")
        if agent:
            agent.shutdown_main_loop()
        raise
    return 0
예제 #10
0
파일: service.py 프로젝트: QSFT/unix-agent
def get_status(cli_args):
    config_files = config.get_config_files(conffile=cli_args.conffile)
    conf = config.AgentConfig(config_files)

    db_obj = messaging.persistence.SQLiteAgentDB(conf.storage_dbfile)

    complete = db_obj.get_all_complete()
    replied = db_obj.get_all_reply()
    rejected = db_obj.get_all_rejected()
    acked = db_obj.get_all_ack()
    reply_nacked = db_obj.get_all_reply_nacked()
    status = "UNKNOWN"
    color_func = clint.textui.colored.yellow

    def _check_command(cmd):
        try:
            payload_doc = request_doc['payload']
            command = payload_doc['command']
            if command == cmd:
                return True
        except:
            pass
        return False

    for r in complete:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZED"
            color_func = clint.textui.colored.green
    for r in acked:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZING"
            color_func = clint.textui.colored.green
    for r in replied:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZING"
            color_func = clint.textui.colored.green
    for r in reply_nacked:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "UNKNOWN INITIALIZATION STATE"
            color_func = clint.textui.colored.red

    for r in rejected:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZATION REJECTED"
            color_func = clint.textui.colored.red

    clint.textui.puts(color_func(status))
    complete = db_obj.get_all_complete()
    replied = db_obj.get_all_reply()
    rejected = db_obj.get_all_rejected()
    acked = db_obj.get_all_ack()
    reply_nacked = db_obj.get_all_reply_nacked()

    label_col_width = 30
    vals = [(complete, "Commands processed: "),
            (rejected, "Commands rejected: "),
            (acked, "Commands being processed: "),
            (replied, "Commands being replying to: "),
            (reply_nacked, "Replies rejected: ")]
    with clint.textui.indent(4):
        for v, k in vals:
            clint.textui.puts(
                clint.textui.columns([k, label_col_width], [str(len(v)), 5]))

    try:
        pid_file = os.path.join(conf.storage_base_dir, "dcm-agent.pid")
        if not os.path.exists(pid_file):
            run_status = "NOT RUNNING"
            run_reason = "PID file not found"
        else:
            with open(pid_file, "r") as fptr:
                pid = int(fptr.read().strip())
            p = psutil.Process(pid)
            clint.textui.puts(clint.textui.colored.green("RUNNING"))
            start_time_str = datetime.datetime.fromtimestamp(
                p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
            with clint.textui.indent(4):
                clint.textui.puts(
                    clint.textui.columns(
                        ["Started at:", label_col_width],
                        [start_time_str, 70 - label_col_width]))
                clint.textui.puts(
                    clint.textui.columns(["User:"******"Status:", label_col_width],
                                         [p.status(), 70 - label_col_width]))
                clint.textui.puts(
                    clint.textui.columns(["Pid:", label_col_width],
                                         [str(pid), 70 - label_col_width]))

            return 0
    except psutil.NoSuchProcess:
        run_status = "NOT RUNNING"
        run_reason = "The PID %d was not found" % pid
    except Exception as ex:
        run_reason = str(ex)
        run_status = "UNKNOWN"

    clint.textui.puts(clint.textui.colored.red(run_status))
    clint.textui.puts(clint.textui.colored.red(run_reason))

    return 1
예제 #11
0
파일: service.py 프로젝트: JPWKU/unix-agent
def get_status(cli_args):
    config_files = config.get_config_files(conffile=cli_args.conffile)
    conf = config.AgentConfig(config_files)

    db_obj = messaging.persistence.SQLiteAgentDB(conf.storage_dbfile)

    complete = db_obj.get_all_complete()
    replied = db_obj.get_all_reply()
    rejected = db_obj.get_all_rejected()
    acked = db_obj.get_all_ack()
    reply_nacked = db_obj.get_all_reply_nacked()
    status = "UNKNOWN"
    color_func = clint.textui.colored.yellow

    def _check_command(cmd):
        try:
            payload_doc = request_doc["payload"]
            command = payload_doc["command"]
            if command == cmd:
                return True
        except:
            pass
        return False

    for r in complete:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZED"
            color_func = clint.textui.colored.green
    for r in acked:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZING"
            color_func = clint.textui.colored.green
    for r in replied:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZING"
            color_func = clint.textui.colored.green
    for r in reply_nacked:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "UNKNOWN INITIALIZATION STATE"
            color_func = clint.textui.colored.red

    for r in rejected:
        request_doc = json.loads(r.request_doc)
        if _check_command("initialize"):
            status = "INITIALIZATION REJECTED"
            color_func = clint.textui.colored.red

    clint.textui.puts(color_func(status))
    complete = db_obj.get_all_complete()
    replied = db_obj.get_all_reply()
    rejected = db_obj.get_all_rejected()
    acked = db_obj.get_all_ack()
    reply_nacked = db_obj.get_all_reply_nacked()

    label_col_width = 30
    vals = [
        (complete, "Commands processed: "),
        (rejected, "Commands rejected: "),
        (acked, "Commands being processed: "),
        (replied, "Commands being replying to: "),
        (reply_nacked, "Replies rejected: "),
    ]
    with clint.textui.indent(4):
        for v, k in vals:
            clint.textui.puts(clint.textui.columns([k, label_col_width], [str(len(v)), 5]))

    try:
        pid_file = os.path.join(conf.storage_base_dir, "dcm-agent.pid")
        if not os.path.exists(pid_file):
            run_status = "NOT RUNNING"
            run_reason = "PID file not found"
        else:
            with open(pid_file, "r") as fptr:
                pid = int(fptr.read().strip())
            p = psutil.Process(pid)
            clint.textui.puts(clint.textui.colored.green("RUNNING"))
            start_time_str = datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
            with clint.textui.indent(4):
                clint.textui.puts(
                    clint.textui.columns(["Started at:", label_col_width], [start_time_str, 70 - label_col_width])
                )
                clint.textui.puts(
                    clint.textui.columns(["User:"******"Status:", label_col_width], [p.status(), 70 - label_col_width])
                )
                clint.textui.puts(clint.textui.columns(["Pid:", label_col_width], [str(pid), 70 - label_col_width]))

            return 0
    except psutil.NoSuchProcess:
        run_status = "NOT RUNNING"
        run_reason = "The PID %d was not found" % pid
    except Exception as ex:
        run_reason = str(ex)
        run_status = "UNKNOWN"

    clint.textui.puts(clint.textui.colored.red(run_status))
    clint.textui.puts(clint.textui.colored.red(run_reason))

    return 1