示例#1
0
def _submit_via_command_pipe(host, service, state, output):
    # type: (HostName, ServiceName, ServiceState, ServiceDetails) -> None
    output = output.replace("\n", "\\n")
    _open_command_pipe()
    if _nagios_command_pipe is not None and not isinstance(_nagios_command_pipe, bool):
        # [<timestamp>] PROCESS_SERVICE_CHECK_RESULT;<host_name>;<svc_description>;<return_code>;<plugin_output>
        _nagios_command_pipe.write(
            "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n" %
            (int(time.time()), host, make_utf8(service), state, make_utf8(output)))
        # Important: Nagios needs the complete command in one single write() block!
        # Python buffers and sends chunks of 4096 bytes, if we do not flush.
        _nagios_command_pipe.flush()
示例#2
0
def _output_check_result(servicedesc, state, infotext, perftexts):
    if _show_perfdata:
        infotext_fmt = "%-56s"
        p = ' (%s)' % (" ".join(perftexts))
    else:
        p = ''
        infotext_fmt = "%s"

    console.verbose("%-20s %s%s" + infotext_fmt + "%s%s\n",
                    servicedesc.encode('utf-8'), tty.bold, tty.states[state],
                    make_utf8(infotext.split('\n')[0]), tty.normal,
                    make_utf8(p))
示例#3
0
def export_rule_pack(rule_pack, pretty_print=False, dir_=None):
    # type: (Dict[str, Any], bool, Optional[Path]) -> None
    """
    Export the representation of a rule pack (i.e. a dict) to a .mk
    file accessible by the WATO module Extension Packages. In case
    of a MkpRulePackProxy the representation of the underlying rule
    pack is used.
    The name of the .mk file is determined by the ID of the rule pack,
    i.e. the rule pack 'test' will be saved as 'test.mk'
    By default the rule pack is saved to the default directory for
    mkp rule packs. If dir_ is given the default is replaced by the
    directory dir_.
    """
    if isinstance(rule_pack, MkpRulePackProxy):
        rule_pack = rule_pack.rule_pack

    repr_ = (pprint.pformat(rule_pack) if pretty_print else repr(rule_pack))
    output = ("# Written by WATO\n"
              "# encoding: utf-8\n"
              "\n"
              "mkp_rule_packs['%s'] = \\\n"
              "%s\n") % (rule_pack['id'], repr_)

    if not dir_:
        dir_ = mkp_rule_pack_dir()
    dir_.mkdir(parents=True, exist_ok=True)
    store.save_file(str(dir_ / ("%s.mk" % rule_pack['id'])), make_utf8(output))
示例#4
0
def check_mk_local_automation(command, args=None, indata="", stdin_data=None, timeout=None):
    if args is None:
        args = []

    auto_logger = logger.getChild("automations")

    if timeout:
        args = ["--timeout", "%d" % timeout] + args

    cmd = ['check_mk', '--automation', command, '--'] + args
    if command in ['restart', 'reload']:
        call_hook_pre_activate_changes()

    cmd = [make_utf8(a) for a in cmd]
    try:
        # This debug output makes problems when doing bulk inventory, because
        # it garbles the non-HTML response output
        # if config.debug:
        #     html.write("<div class=message>Running <tt>%s</tt></div>\n" % subprocess.list2cmdline(cmd))
        auto_logger.info("RUN: %s" % subprocess.list2cmdline(cmd))
        p = subprocess.Popen(cmd,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=True)
    except Exception as e:
        raise _local_automation_failure(command=command, cmdline=cmd, exc=e)

    if stdin_data is not None:
        auto_logger.info("STDIN: %r" % stdin_data)
        p.stdin.write(stdin_data)
    else:
        auto_logger.info("STDIN: %r" % indata)
        p.stdin.write(repr(indata))

    p.stdin.close()
    outdata = p.stdout.read()
    exitcode = p.wait()
    auto_logger.info("FINISHED: %d" % exitcode)
    auto_logger.debug("OUTPUT: %r" % outdata)
    errdata = p.stderr.read()
    if errdata:
        auto_logger.warning("'%s' returned '%s'" % (" ".join(cmd), errdata))
    if exitcode != 0:
        auto_logger.error("Error running %r (exit code %d)" %
                          (subprocess.list2cmdline(cmd), exitcode))
        raise _local_automation_failure(command=command,
                                        cmdline=cmd,
                                        code=exitcode,
                                        out=outdata,
                                        err=errdata)

    # On successful "restart" command execute the activate changes hook
    if command in ['restart', 'reload']:
        call_hook_activate_changes()

    try:
        return ast.literal_eval(outdata)
    except SyntaxError as e:
        raise _local_automation_failure(command=command, cmdline=cmd, out=outdata, exc=e)
示例#5
0
文件: tty.py 项目: stefan927/checkmk
def print_table(headers, colors, rows, indent=""):
    num_columns = len(headers)
    lengths = _column_lengths(headers, rows, num_columns)
    fmt = _row_template(lengths, colors, indent)
    for index, row in enumerate([headers] + rows):
        sys.stdout.write(fmt % tuple(make_utf8(c) for c in row[:num_columns]))
        if index == 0:
            sys.stdout.write(fmt % tuple("-" * l for l in lengths))
示例#6
0
def _submit_via_check_result_file(host, service, state, output):
    output = output.replace("\n", "\\n")
    _open_checkresult_file()
    if _checkresult_file_fd:
        now = time.time()
        os.write(
            _checkresult_file_fd, """host_name=%s
service_description=%s
check_type=1
check_options=0
reschedule_check
latency=0.0
start_time=%.1f
finish_time=%.1f
return_code=%d
output=%s

""" % (host, make_utf8(service), now, now, state, make_utf8(output)))
示例#7
0
文件: tty.py 项目: stefan927/checkmk
def _column_lengths(headers, rows, num_columns):
    lengths = [len(h) for h in headers]
    for row in rows:
        for index, column in enumerate(row[:num_columns]):
            # FIXME alignment by reference to lengths of utf-8 strings?
            # column can be None, str, data structures, ...
            if not isinstance(column, six.string_types):
                column = six.binary_type(column)
            lengths[index] = max(len(make_utf8(column)), lengths[index])
    return lengths
示例#8
0
文件: __init__.py 项目: n00rm/checkmk
    def execute(self, cmd, args):
        # type: (str, List[str]) -> Any
        self._handle_generic_arguments(args)

        try:
            try:
                automation = self._automations[cmd]
            except KeyError:
                raise MKAutomationError(
                    "Automation command '%s' is not implemented." % cmd)

            if automation.needs_checks:
                config.load_all_checks(check_api.get_check_api_context)

            if automation.needs_config:
                config.load(validate_hosts=False)

            result = automation.execute(args)

        except (MKAutomationError, MKTimeout) as e:
            console.error("%s\n" % make_utf8("%s" % e))
            if cmk.utils.debug.enabled():
                raise
            return 1

        except Exception as e:
            if cmk.utils.debug.enabled():
                raise
            console.error("%s\n" % make_utf8("%s" % e))
            return 2

        finally:
            profiling.output_profile()

        if cmk.utils.debug.enabled():
            console.output(pprint.pformat(result) + "\n")
        else:
            console.output("%r\n" % (result, ))

        return 0
示例#9
0
def save_rule_packs(rule_packs, pretty_print=False, dir_=None):
    # type: (List[Dict[str, Any]], bool, Optional[Path]) -> None
    """Saves the given rule packs to rules.mk. By default they are saved to the
    default directory for rule packs. If dir_ is given it is used instead of
    the default."""
    output = "# Written by WATO\n# encoding: utf-8\n\n"

    if pretty_print:
        rule_packs_text = pprint.pformat(rule_packs)
    else:
        rule_packs_text = repr(rule_packs)

    output += "rule_packs += \\\n%s\n" % rule_packs_text

    if not dir_:
        dir_ = rule_pack_dir()
    dir_.mkdir(parents=True, exist_ok=True)
    store.save_file(str(dir_ / "rules.mk"), make_utf8(output))
示例#10
0
def dump_host(hostname):
    # type: (HostName) -> None
    config_cache = config.get_config_cache()
    host_config = config_cache.get_host_config(hostname)

    console.output("\n")
    if host_config.is_cluster:
        nodes = host_config.nodes
        if nodes is None:
            raise RuntimeError()
        color = tty.bgmagenta
        add_txt = " (cluster of " + (", ".join(nodes)) + ")"
    else:
        color = tty.bgblue
        add_txt = ""
    console.output(
        "%s%s%s%-78s %s\n" %
        (color, tty.bold, tty.white, hostname + add_txt, tty.normal))

    ipaddress = _ip_address_for_dump_host(host_config)

    addresses = ""  # type: Optional[str]
    if not host_config.is_ipv4v6_host:
        addresses = ipaddress
    else:
        try:
            if host_config.is_ipv6_primary:
                secondary = _ip_address_for_dump_host(host_config, 4)
            else:
                secondary = _ip_address_for_dump_host(host_config, 6)
        except Exception:
            secondary = "X.X.X.X"

        addresses = "%s, %s" % (ipaddress, secondary)
        if host_config.is_ipv6_primary:
            addresses += " (Primary: IPv6)"
        else:
            addresses += " (Primary: IPv4)"

    console.output(tty.yellow + "Addresses:              " + tty.normal +
                   (addresses if addresses is not None else "No IP") + "\n")

    tag_template = tty.bold + "[" + tty.normal + "%s" + tty.bold + "]" + tty.normal
    tags = [(tag_template % ":".join(t))
            for t in sorted(host_config.tag_groups.iteritems())]
    console.output(tty.yellow + "Tags:                   " + tty.normal +
                   ", ".join(tags) + "\n")

    labels = [(tag_template % ":".join(l)).encode("utf-8")
              for l in sorted(host_config.labels.iteritems())]
    console.output(tty.yellow + "Labels:                 " + tty.normal +
                   ", ".join(labels) + "\n")

    # TODO: Clean this up once cluster parent handling has been moved to HostConfig
    if host_config.is_cluster:
        parents_list = host_config.nodes
        if parents_list is None:
            raise RuntimeError()
    else:
        parents_list = host_config.parents
    if len(parents_list) > 0:
        console.output(tty.yellow + "Parents:                " + tty.normal +
                       ", ".join(parents_list) + "\n")
    console.output(tty.yellow + "Host groups:            " + tty.normal +
                   make_utf8(", ".join(host_config.hostgroups)) + "\n")
    console.output(tty.yellow + "Contact groups:         " + tty.normal +
                   make_utf8(", ".join(host_config.contactgroups)) + "\n")

    agenttypes = []
    sources = data_sources.DataSources(hostname, ipaddress)
    for source in sources.get_data_sources():
        agenttypes.append(source.describe())

    if host_config.is_ping_host:
        agenttypes.append('PING only')

    console.output(tty.yellow + "Agent mode:             " + tty.normal)
    console.output(sources.describe_data_sources() + "\n")

    console.output(tty.yellow + "Type of agent:          " + tty.normal)
    if len(agenttypes) == 1:
        console.output(agenttypes[0] + "\n")
    else:
        console.output("\n  ")
        console.output("\n  ".join(agenttypes) + "\n")

    console.output(tty.yellow + "Services:" + tty.normal + "\n")

    headers = ["checktype", "item", "params", "description", "groups"]
    colors = [tty.normal, tty.blue, tty.normal, tty.green, tty.normal]

    table_data = []  # type: tty.TableRows
    for service in sorted(check_table.get_check_table(hostname).values(),
                          key=lambda s: s.description):
        table_data.append(
            (service.check_plugin_name, make_utf8("%s" % service.item),
             _evaluate_params(service.parameters),
             make_utf8(service.description),
             make_utf8(",".join(
                 config_cache.servicegroups_of_service(hostname,
                                                       service.description)))))

    tty.print_table(headers, colors, table_data, "  ")