Exemplo n.º 1
0
        def wrapped_check_func(hostname, *args, **kwargs):
            host_config = config.get_config_cache().get_host_config(hostname)
            exit_spec = host_config.exit_code_spec()

            status, infotexts, long_infotexts, perfdata = 0, [], [], []

            try:
                status, infotexts, long_infotexts, perfdata = check_func(hostname, *args, **kwargs)

            except SystemExit:
                raise

            except MKTimeout:
                if _in_keepalive_mode():
                    raise
                else:
                    infotexts.append("Timed out")
                    status = max(status, exit_spec.get("timeout", 2))

            except (MKAgentError, MKSNMPError, MKIPAddressLookupError) as e:
                infotexts.append("%s" % e)
                status = exit_spec.get("connection", 2)

            except MKGeneralException as e:
                infotexts.append("%s" % e)
                status = max(status, exit_spec.get("exception", 3))

            except Exception:
                if cmk.utils.debug.enabled():
                    raise
                crash_output = cmk_base.crash_reporting.create_crash_dump(
                    hostname, check_plugin_name, None, False, None, description, [])
                infotexts.append(crash_output.replace("Crash dump:\n", "Crash dump:\\n"))
                status = max(status, exit_spec.get("exception", 3))

            # Produce the service check result output
            output_txt = "%s - %s" % (defines.short_service_state_name(status),
                                      ", ".join(infotexts))
            if perfdata:
                output_txt += " | %s" % " ".join(perfdata)
            if long_infotexts:
                output_txt = "%s\n%s" % (output_txt, "\n".join(long_infotexts))
            output_txt += "\n"

            if _in_keepalive_mode():
                keepalive.add_keepalive_active_check_result(hostname, output_txt)
                console.verbose(output_txt.encode("utf-8"))
            else:
                console.output(output_txt.encode("utf-8"))

            return status
Exemplo n.º 2
0
def do_snmptranslate(walk_filename):
    if not walk_filename:
        raise MKGeneralException("Please provide the name of a SNMP walk file")

    walk_path = "%s/%s" % (cmk.utils.paths.snmpwalks_dir, walk_filename)
    if not os.path.exists(walk_path):
        raise MKGeneralException("The walk '%s' does not exist" % walk_path)

    def translate(lines):
        result_lines = []
        try:
            oids_for_command = []
            for line in lines:
                oids_for_command.append(line.split(" ")[0])

            command = ["snmptranslate", "-m", "ALL",
                       "-M+%s" % cmk.utils.paths.local_mibs_dir] + oids_for_command
            p = subprocess.Popen(command,
                                 stdout=subprocess.PIPE,
                                 stderr=open(os.devnull, "w"),
                                 close_fds=True)
            p.wait()
            output = p.stdout.read()
            result = output.split("\n")[0::2]
            for idx, line in enumerate(result):
                result_lines.append((line.strip(), lines[idx].strip()))

        except Exception as e:
            console.error("%s\n" % e)

        return result_lines

    # Translate n-oid's per cycle
    entries_per_cycle = 500
    translated_lines = []

    walk_lines = file(walk_path).readlines()
    console.error("Processing %d lines.\n" % len(walk_lines))

    i = 0
    while i < len(walk_lines):
        console.error("\r%d to go...    " % (len(walk_lines) - i))
        process_lines = walk_lines[i:i + entries_per_cycle]
        translated = translate(process_lines)
        i += len(translated)
        translated_lines += translated
    console.error("\rfinished.                \n")

    # Output formatted
    for translation, line in translated_lines:
        console.output("%s --> %s\n" % (line, translation))
Exemplo n.º 3
0
def output_profile():
    if not _profile:
        return

    _profile.dump_stats(_profile_path)
    show_profile = os.path.join(os.path.dirname(_profile_path), "show_profile.py")
    with file(show_profile, "w") as f:
        f.write("#!/usr/bin/python\n"
                "import pstats\n"
                "stats = pstats.Stats('%s')\n"
                "stats.sort_stats('time').print_stats()\n" % _profile_path)
    os.chmod(show_profile, 0755)

    console.output(
        "Profile '%s' written. Please run %s.\n" % (_profile_path, show_profile), stream=sys.stderr)
Exemplo n.º 4
0
def do_snmpget(*args):
    if not args[0]:
        raise MKBailOut("You need to specify an OID.")
    oid = args[0][0]

    config_cache = config.get_config_cache()

    hostnames = args[0][1:]
    if not hostnames:
        hostnames = []
        for host in config_cache.all_active_realhosts():
            host_config = config_cache.get_host_config(host)
            if host_config.is_snmp_host:
                hostnames.append(host)

    for hostname in hostnames:
        #TODO what about SNMP management boards?
        snmp_config = create_snmp_host_config(hostname)

        value = get_single_oid(snmp_config, oid)
        console.output("%s (%s): %r\n" % (hostname, snmp_config.ipaddress, value))
        cmk_base.cleanup.cleanup_globals()
Exemplo n.º 5
0
def output_profile():
    if not _profile:
        return

    _profile.dump_stats(_profile_path)
    show_profile = os.path.join(os.path.dirname(_profile_path),
                                "show_profile.py")
    with open(show_profile, "w") as f:
        f.write("#!/usr/bin/env python\n"
                "import sys\n"
                "import pstats\n"
                "try:\n"
                "    profile_file = sys.argv[1]\n"
                "except IndexError:\n"
                "    profile_file = %r\n"
                "stats = pstats.Stats(profile_file)\n"
                "stats.sort_stats('time').print_stats()\n" % _profile_path)
    os.chmod(show_profile, 0o755)

    console.output("Profile '%s' written. Please run %s.\n" %
                   (_profile_path, show_profile),
                   stream=sys.stderr)
Exemplo n.º 6
0
    def execute(self, cmd, args):
        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" % cmk.utils.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" % cmk.utils.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
Exemplo n.º 7
0
def do_inv_check(hostname):
    try:
        inv_tree, old_timestamp = do_inv_for(hostname)
        num_entries = count_nodes(g_inv_tree)
        if not num_entries:
            console.output("OK - Found no data\n")
            sys.exit(0)

        infotext = "found %d entries" % num_entries
        state = 0
        if not inv_tree.get("software") and opt_inv_sw_missing:
            infotext += ", software information is missing"
            state = opt_inv_sw_missing
            infotext += state_markers[opt_inv_sw_missing]

        if old_timestamp:
            path = inventory_archive_dir + "/" + hostname + "/%d" % old_timestamp
            old_tree = eval(file(path).read())

            if inv_tree.get("software") != old_tree.get("software"):
                infotext += ", software changes"
                if opt_inv_sw_changes:
                    state = opt_inv_sw_changes
                    infotext += state_markers[opt_inv_sw_changes]

            if inv_tree.get("hardware") != old_tree.get("hardware"):
                infotext += ", hardware changes"
                if state == 2 or opt_inv_hw_changes == 2:
                    state = 2
                else:
                    state = max(state, opt_inv_sw_changes)
                if opt_inv_hw_changes:
                    infotext += state_markers[opt_inv_hw_changes]

        console.output(core_state_names[state] + " - " + infotext + "\n")
        sys.exit(state)

    except Exception, e:
        if cmk.debug.enabled():
            raise
        console.output("Inventory failed: %s\n" % e)
        sys.exit(opt_inv_fail_status)
Exemplo n.º 8
0
def do_inv_check(hostname):
    try:
        inv_tree, old_timestamp = do_inv_for(hostname)
        num_entries = count_nodes(g_inv_tree)
        if not num_entries:
            console.output("OK - Found no data\n")
            sys.exit(0)

        infotext = "found %d entries" % num_entries
        state = 0
        if not inv_tree.get("software") and opt_inv_sw_missing:
            infotext += ", software information is missing"
            state = opt_inv_sw_missing
            infotext += state_markers[opt_inv_sw_missing]

        if old_timestamp:
            path = inventory_archive_dir + "/" + hostname + "/%d" % old_timestamp
            old_tree = eval(file(path).read())

            if inv_tree.get("software") != old_tree.get("software"):
                infotext += ", software changes"
                if opt_inv_sw_changes:
                    state = opt_inv_sw_changes
                    infotext += state_markers[opt_inv_sw_changes]

            if inv_tree.get("hardware") != old_tree.get("hardware"):
                infotext += ", hardware changes"
                if state == 2 or opt_inv_hw_changes == 2:
                    state = 2
                else:
                    state = max(state, opt_inv_sw_changes)
                if opt_inv_hw_changes:
                    infotext += state_markers[opt_inv_hw_changes]

        console.output(core_state_names[state] + " - " + infotext + "\n")
        sys.exit(state)

    except Exception, e:
        if cmk.debug.enabled():
            raise
        console.output("Inventory failed: %s\n" % e)
        sys.exit(opt_inv_fail_status)
Exemplo n.º 9
0
def do_core_action(action, quiet=False):
    if not quiet:
        console.output("%sing monitoring core..." % action.title())

    if config.monitoring_core == "nagios":
        os.putenv("CORE_NOVERIFY", "yes")
        command = ["%s/etc/init.d/core" % cmk.utils.paths.omd_root, action]
    else:
        command = ["omd", action, "cmc"]

    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         close_fds=True)
    result = p.wait()
    if result != 0:
        output = p.stdout.read()
        if not quiet:
            console.output("ERROR: %s\n" % output)
        raise MKGeneralException("Cannot %s the monitoring core: %s" %
                                 (action, output))
    else:
        if not quiet:
            console.output(tty.ok + "\n")
Exemplo n.º 10
0
 def precompile(self):
     console.output("Precompiling host checks...")
     precompile_hostchecks()
     console.output(tty.ok + "\n")
Exemplo n.º 11
0
# Read all inventory plugins right now
filelist = plugin_pathnames_in_directory(cmk.paths.inventory_dir) \
         + plugin_pathnames_in_directory(cmk.paths.local_inventory_dir)

# read include files always first, but still in the sorted
# order with local ones last (possibly overriding variables)
filelist = [ f for f in filelist if f.endswith(".include") ] + \
           [ f for f in filelist if not f.endswith(".include") ]

for f in filelist:
    if not f.endswith("~"):  # ignore emacs-like backup files
        try:
            execfile(f)
        except Exception, e:
            console.output("Error in inventory plugin file %s: %s\n",
                           f,
                           e,
                           stream=sys.stderr)
            if cmk.debug.enabled():
                raise
            sys.exit(5)


# This is just a small wrapper for the inv_tree() function which makes
# it clear that the requested tree node is treated as a list.
def inv_tree_list(path):
    # The [] is needed to tell pylint that a list is returned
    return inv_tree(path, [])


# Function for accessing the inventory tree of the current host
# Example: path = "software.packages:17."
Exemplo n.º 12
0
def dump_host(hostname):
    config_cache = config.get_config_cache()
    host_config = config_cache.get_host_config(hostname)

    console.output("\n")
    if host_config.is_cluster:
        color = tty.bgmagenta
        add_txt = " (cluster of " + (", ".join(host_config.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 = ""
    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:
            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.items())]
    console.output(tty.yellow + "Tags:                   " + tty.normal +
                   ", ".join(tags) + "\n")
    # TODO: Clean this up once cluster parent handling has been moved to HostConfig
    if host_config.is_cluster:
        parents_list = host_config.nodes
    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 +
        cmk_base.utils.make_utf8(", ".join(host_config.hostgroups)) + "\n")
    console.output(
        tty.yellow + "Contact groups:         " + tty.normal +
        cmk_base.utils.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")
    check_items = check_table.get_sorted_check_table(hostname)

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

    tty.print_table(headers, colors, [[
        checktype,
        cmk_base.utils.make_utf8(item),
        _evaluate_params(params),
        cmk_base.utils.make_utf8(description),
        cmk_base.utils.make_utf8(",".join(
            config_cache.servicegroups_of_service(hostname, description)))
    ] for checktype, item, params, description in check_items], "  ")
Exemplo n.º 13
0
def do_scan_parents(hosts):
    config_cache = config.get_config_cache()

    if not hosts:
        hosts = config_cache.all_active_realhosts()

    parent_hosts = []
    parent_ips = {}
    parent_rules = []
    gateway_hosts = set([])

    if config.max_num_processes < 1:
        config.max_num_processes = 1

    outfilename = cmk.utils.paths.check_mk_config_dir + "/parents.mk"

    if not traceroute_available():
        raise MKGeneralException('The program "traceroute" was not found.\n'
                                 'The parent scan needs this program.\n'
                                 'Please install it and try again.')

    if os.path.exists(outfilename):
        first_line = open(outfilename, "r").readline()
        if not first_line.startswith('# Automatically created by --scan-parents at'):
            raise MKGeneralException("conf.d/parents.mk seems to be created manually.\n\n"
                                     "The --scan-parents function would overwrite this file.\n"
                                     "Please rename it to keep the configuration or delete "
                                     "the file and try again.")

    console.output("Scanning for parents (%d processes)..." % config.max_num_processes)
    while hosts:
        chunk = []
        while len(chunk) < config.max_num_processes and len(hosts) > 0:
            host = hosts.pop()

            host_config = config_cache.get_host_config(host)

            # skip hosts that already have a parent
            if host_config.parents:
                console.verbose("(manual parent) ")
                continue
            chunk.append(host)

        gws = scan_parents_of(config_cache, chunk)

        for host, (gw, _unused_state, _unused_ping_fails, _unused_message) in zip(chunk, gws):
            if gw:
                gateway, gateway_ip, dns_name = gw
                if not gateway:  # create artificial host
                    if dns_name:
                        gateway = dns_name
                    else:
                        gateway = "gw-%s" % (gateway_ip.replace(".", "-"))
                    if gateway not in gateway_hosts:
                        gateway_hosts.add(gateway)
                        parent_hosts.append("%s|parent|ping" % gateway)
                        parent_ips[gateway] = gateway_ip
                        if config.monitoring_host:
                            parent_rules.append(
                                (config.monitoring_host, [gateway]))  # make Nagios a parent of gw
                parent_rules.append((gateway, [host]))
            elif host != config.monitoring_host and config.monitoring_host:
                # make monitoring host the parent of all hosts without real parent
                parent_rules.append((config.monitoring_host, [host]))

    with open(outfilename, "w") as out:
        out.write("# Automatically created by --scan-parents at %s\n\n" % time.asctime())
        out.write("# Do not edit this file. If you want to convert an\n")
        out.write("# artificial gateway host into a permanent one, then\n")
        out.write("# move its definition into another *.mk file\n")

        out.write("# Parents which are not listed in your all_hosts:\n")
        out.write("all_hosts += %s\n\n" % pprint.pformat(parent_hosts))

        out.write("# IP addresses of parents not listed in all_hosts:\n")
        out.write("ipaddresses.update(%s)\n\n" % pprint.pformat(parent_ips))

        out.write("# Parent definitions\n")
        out.write("parents += %s\n\n" % pprint.pformat(parent_rules))
    console.output("\nWrote %s\n" % outfilename)
Exemplo n.º 14
0
 def dot(color, dot='o'):
     if not silent:
         console.output(tty.bold + color + dot + tty.normal)
Exemplo n.º 15
0
# Read all inventory plugins right now
filelist = plugin_pathnames_in_directory(cmk.paths.inventory_dir) + plugin_pathnames_in_directory(
    cmk.paths.local_inventory_dir
)


# read include files always first, but still in the sorted
# order with local ones last (possibly overriding variables)
filelist = [f for f in filelist if f.endswith(".include")] + [f for f in filelist if not f.endswith(".include")]

for f in filelist:
    if not f.endswith("~"):  # ignore emacs-like backup files
        try:
            execfile(f)
        except Exception, e:
            console.output("Error in inventory plugin file %s: %s\n", f, e, stream=sys.stderr)
            if cmk.debug.enabled():
                raise
            sys.exit(5)


# This is just a small wrapper for the inv_tree() function which makes
# it clear that the requested tree node is treated as a list.
def inv_tree_list(path):
    # The [] is needed to tell pylint that a list is returned
    return inv_tree(path, [])


# Function for accessing the inventory tree of the current host
# Example: path = "software.packages:17."
# The path must end with : or .