Example #1
0
 def _recv_nhm_result(self, zmq_sock):
     # receive result from non-host-monitor target
     data = []
     while True:
         data.append(zmq_sock.recv())
         if not zmq_sock.getsockopt(zmq.RCVMORE):
             break
     if len(data) == 2:
         src_id = data[0].decode("utf-8")
         if src_id in self.__raw_nhm_dict:
             srv_result = etree.fromstring(data[1])
             srv_com = self.__raw_nhm_dict[src_id][1]
             cur_id = srv_com["identity"].text
             self._send_result(cur_id, srv_result.findtext("nodestatus"), limits.mon_STATE_OK)
             del self.__raw_nhm_dict[src_id]
         else:
             srv_result = server_command.srv_command(source=data[1])
             if "command" in srv_result and srv_result["*command"] in ["relayer_info"]:
                 self.log(
                     "relayer_info command no longer supported",
                     logging_tools.LOG_LEVEL_ERROR
                 )
             elif "identity" in srv_result:
                 cur_id = srv_result["identity"].text
                 if cur_id in self.__nhm_dict:
                     del self.__nhm_dict[cur_id]
                     if "result" in srv_result:
                         self._send_result(
                             cur_id,
                             srv_result["result"].attrib["reply"],
                             server_command.srv_reply_to_nag_state(
                                 int(srv_result["result"].attrib["state"])
                             )
                         )
                     else:
                         self._send_result(
                             cur_id,
                             "no result tag found",
                             limits.mon_STATE_CRITICAL,
                         )
                 else:
                     self.log(
                         "received nhm-result for unknown id '{}', ignoring".format(cur_id),
                         logging_tools.LOG_LEVEL_ERROR
                     )
             else:
                 self.log(
                     "no identity-tag found in result",
                     logging_tools.LOG_LEVEL_ERROR
                 )
Example #2
0
def ClientCode(global_config):
    from initat.host_monitoring import modules
    if global_config["VERBOSE"] > 1:
        print("{:d} import errors:".format(len(modules.IMPORT_ERRORS)))
        for mod, com, _str in modules.IMPORT_ERRORS:
            print("{:<30s} {:<20s} {}".format(com, mod.split(".")[-1], _str))
    conn_str = "tcp://{}:{:d}".format(global_config["HOST"],
                                      global_config["COMMAND_PORT"])
    arg_stuff = global_config.get_argument_stuff()
    arg_list = arg_stuff["arg_list"]
    com_name = arg_list.pop(0)
    if com_name in modules.command_dict:
        srv_com = server_command.srv_command(command=com_name)
        for src_key, dst_key in [("HOST", "host"), ("COMMAND_PORT", "port")]:
            srv_com[dst_key] = global_config[src_key]
        com_struct = modules.command_dict[com_name]
        try:
            cur_ns, rest = com_struct.handle_commandline(arg_list)
        except ValueError, what:
            ret = ExtReturn(limits.mon_STATE_CRITICAL,
                            "error parsing: {}".format(what[1]))
        else:
            # see also struct.py in collrelay
            if hasattr(cur_ns, "arguments"):
                for arg_index, arg in enumerate(cur_ns.arguments):
                    srv_com["arguments:arg{:d}".format(arg_index)] = arg
            srv_com["arguments:rest"] = " ".join(rest)
            for key, value in vars(cur_ns).iteritems():
                srv_com["namespace:{}".format(key)] = value
            result = net_tools.ZMQConnection(
                "{}:{:d}".format(global_config["IDENTITY_STRING"],
                                 os.getpid()),
                timeout=global_config["TIMEOUT"],
            ).add_connection(
                conn_str,
                srv_com,
                immediate=True,
            )
            if result:
                if global_config["COMMAND_PORT"] == InstanceXML(
                        quiet=True).get_port_dict("host-monitoring",
                                                  command=True):
                    error_result = result.xpath(".//ns:result[@state != '0']",
                                                smart_strings=False)
                    if error_result:
                        error_result = error_result[0]
                        ret = ExtReturn(int(error_result.attrib["state"]),
                                        error_result.attrib["reply"])
                    else:
                        if hasattr(com_struct, "interpret"):
                            ret = ExtReturn.get_ext_return(
                                com_struct.interpret(result, cur_ns))
                        else:
                            _result = result.xpath(".//ns:result",
                                                   smart_strings=False)[0]
                            ret = ExtReturn(
                                server_command.srv_reply_to_nag_state(
                                    int(_result.attrib["state"])),
                                result.attrib["reply"])
                else:
                    ret_str, ret_state = result.get_log_tuple()
                    ret = ExtReturn(
                        server_command.srv_reply_to_nag_state(ret_state),
                        ret_str)
            else:
                ret = ExtReturn(limits.mon_STATE_CRITICAL, "timeout")
Example #3
0
 def interpret(self, srv_com, cur_ns):
     _result, _state = srv_com.get_log_tuple()
     _state = server_command.srv_reply_to_nag_state(_state)
     return _state, _result
Example #4
0
def ClientCode(global_config):
    from initat.host_monitoring.modules import local_mc
    from initat.debug import ICSW_DEBUG_MODE
    if ICSW_DEBUG_MODE:
        # dummy logger of module loader
        def dummy_log(what, log_level=logging_tools.LOG_LEVEL_OK):
            print("{} {}".format(logging_tools.get_log_level_str(log_level),
                                 what))

        local_mc.set_log_command(dummy_log)
    local_mc.build_structure(None, None)
    conn_str = "tcp://{}:{:d}".format(global_config["HOST"],
                                      global_config["COMMAND_PORT"])
    arg_list = global_config["ARGUMENTS"]
    com_name = arg_list.pop(0)
    if com_name in local_mc:
        srv_com = server_command.srv_command(command=com_name)
        for src_key, dst_key in [("HOST", "host"), ("COMMAND_PORT", "port")]:
            srv_com[dst_key] = global_config[src_key]
        com_struct = local_mc[com_name]
        try:
            cur_ns, rest = com_struct.handle_commandline(arg_list)
        except ValueError as what:
            ret = ExtReturn(limits.mon_STATE_CRITICAL,
                            "error parsing: {}".format(what.args[1]))
        else:
            # see also struct.py in collrelay
            if hasattr(cur_ns, "arguments"):
                for arg_index, arg in enumerate(cur_ns.arguments):
                    srv_com["arguments:arg{:d}".format(arg_index)] = arg
            srv_com["arguments:rest"] = " ".join(rest)
            for key, value in vars(cur_ns).items():
                srv_com["namespace:{}".format(key)] = value
            result = net_tools.ZMQConnection(
                "{}:{:d}".format(global_config["IDENTITY_STRING"],
                                 os.getpid()),
                timeout=global_config["TIMEOUT"],
            ).add_connection(
                conn_str,
                srv_com,
                immediate=True,
            )
            if result:
                if global_config["COMMAND_PORT"] == InstanceXML(
                        quiet=True).get_port_dict(
                            icswServiceEnum.host_monitoring, command=True):
                    error_result = result.xpath(".//ns:result[@state != '0']",
                                                smart_strings=False)
                    if error_result:
                        error_result = error_result[0]
                        ret = ExtReturn(int(error_result.attrib["state"]),
                                        error_result.attrib["reply"])
                    else:
                        if hasattr(com_struct, "interpret"):
                            ret = ExtReturn.get_ext_return(
                                com_struct.interpret(result, cur_ns))
                        else:
                            _result = result.xpath(".//ns:result",
                                                   smart_strings=False)[0]
                            ret = ExtReturn(
                                server_command.srv_reply_to_nag_state(
                                    int(_result.attrib["state"])),
                                result.attrib["reply"])
                else:
                    ret_str, ret_state = result.get_log_tuple()
                    ret = ExtReturn(
                        server_command.srv_reply_to_nag_state(ret_state),
                        ret_str)
            else:
                ret = ExtReturn(limits.mon_STATE_CRITICAL, "timeout")
    else:
        import difflib
        c_matches = difflib.get_close_matches(com_name, list(local_mc.keys()))
        if c_matches:
            cm_str = "close matches: {}".format(", ".join(c_matches))
        else:
            cm_str = "no matches found"
        ret = ExtReturn(limits.mon_STATE_CRITICAL,
                        "unknown command {}, {}".format(com_name, cm_str))
    if ret.ascii_chunk:
        print("Ignoring ascii_chunk with {:d} bytes".format(
            len(ret.ascii_chunk)))
    # output
    print(ret.ret_str)
    return ret.ret_state