Exemple #1
0
def _do_inv_for_realhost(host_config, sources, multi_host_sections, hostname,
                         ipaddress, inventory_tree, status_data_tree):
    # type: (config.HostConfig, data_sources.DataSources, Optional[data_sources.MultiHostSections], HostName, Optional[HostAddress], StructuredDataTree, StructuredDataTree) -> None
    for source in sources.get_data_sources():
        if isinstance(source, data_sources.SNMPDataSource):
            source.set_on_error("raise")
            source.set_do_snmp_scan(True)
            source.disable_data_source_cache()
            source.set_use_snmpwalk_cache(False)
            source.set_ignore_check_interval(True)
            source.set_check_plugin_name_filter(
                _gather_snmp_check_plugin_names_inventory)
            if multi_host_sections is not None:
                # Status data inventory already provides filled multi_host_sections object.
                # SNMP data source: If 'do_status_data_inv' is enabled there may be
                # sections for inventory plugins which were not fetched yet.
                source.enforce_check_plugin_names(None)
                host_sections = multi_host_sections.add_or_get_host_sections(
                    hostname, ipaddress, deflt=SNMPHostSections())
                source.set_fetched_check_plugin_names(
                    set(host_sections.sections))
                host_sections_from_source = source.run()
                host_sections.update(host_sections_from_source)

    if multi_host_sections is None:
        multi_host_sections = sources.get_host_sections()

    console.step("Executing inventory plugins")
    import cmk.base.inventory_plugins as inventory_plugins  # pylint: disable=import-outside-toplevel
    console.verbose("Plugins:")
    for section_name, plugin in inventory_plugins.sorted_inventory_plugins():
        section_content = multi_host_sections.get_section_content(
            hostname, ipaddress, section_name, for_discovery=False)
        if not section_content:  # section not present (None or [])
            # Note: this also excludes existing sections without info..
            continue

        if all([x in [[], {}, None] for x in section_content]):
            # Inventory plugins which get parsed info from related
            # check plugin may have more than one return value, eg
            # parse function of oracle_tablespaces returns ({}, {})
            continue

        console.verbose(" %s%s%s%s" %
                        (tty.green, tty.bold, section_name, tty.normal))

        # Inventory functions can optionally have a second argument: parameters.
        # These are configured via rule sets (much like check parameters).
        inv_function = plugin["inv_function"]
        kwargs = cmk.utils.misc.make_kwargs_for(
            inv_function,
            inventory_tree=inventory_tree,
            status_data_tree=status_data_tree)
        non_kwargs = set(
            cmk.utils.misc.getfuncargs(inv_function)) - set(kwargs)
        args = [section_content]
        if len(non_kwargs) == 2:
            args += [host_config.inventory_parameters(section_name)]
        inv_function(*args, **kwargs)
    console.verbose("\n")
Exemple #2
0
    def get_host_sections(self, max_cachefile_age=None):
        """Gather ALL host info data for any host (hosts, nodes, clusters) in Check_MK.

        Returns a dictionary object of already parsed HostSections() constructs for each related host.
        For single hosts it's just a single entry in the dictionary. For cluster hosts it contains one
        HostSections() entry for each related node.

        Communication errors are not raised through by this functions. All agent related errors are
        caught by the source.run() method and saved in it's _exception attribute. The caller should
        use source.get_summary_result() to get the state, output and perfdata of the agent excecution
        or source.exception() to get the exception object.
        """
        console.step("Fetching data")

        # First abstract clusters/nodes/hosts
        hosts = []
        nodes = self._host_config.nodes
        if nodes is not None:
            for node_hostname in nodes:
                node_ipaddress = ip_lookup.lookup_ip_address(node_hostname)

                node_check_names = check_table.get_needed_check_names(node_hostname,
                                                                      remove_duplicates=True,
                                                                      filter_mode="only_clustered")

                node_data_sources = DataSources(node_hostname, node_ipaddress)
                node_data_sources.enforce_check_plugin_names(set(node_check_names))
                hosts.append((node_hostname, node_ipaddress, node_data_sources,
                              config.cluster_max_cachefile_age))
        else:
            hosts.append((self._hostname, self._ipaddress, self, config.check_max_cachefile_age))

        if nodes:
            import cmk.base.data_sources.abstract as abstract
            abstract.DataSource.set_may_use_cache_file()

        # Special agents can produce data for the same check_plugin_name on the same host, in this case
        # the section lines need to be extended
        multi_host_sections = MultiHostSections()
        for this_hostname, this_ipaddress, these_sources, this_max_cachefile_age in hosts:
            # In case a max_cachefile_age is given with the function call, always use this one
            # instead of the host individual one. This is only used in discovery mode.
            if max_cachefile_age is not None:
                these_sources.set_max_cachefile_age(max_cachefile_age)
            else:
                these_sources.set_max_cachefile_age(this_max_cachefile_age)

            host_sections =\
                multi_host_sections.add_or_get_host_sections(this_hostname, this_ipaddress)

            for source in these_sources.get_data_sources():
                host_sections_from_source = source.run()
                host_sections.update(host_sections_from_source)

            # Store piggyback information received from all sources of this host. This
            # also implies a removal of piggyback files received during previous calls.
            cmk.utils.piggyback.store_piggyback_raw_data(this_hostname,
                                                         host_sections.piggybacked_raw_data)

        return multi_host_sections
Exemple #3
0
def _run_inventory_export_hooks(host_config, inventory_tree):
    import cmk.base.inventory_plugins as inventory_plugins
    hooks = host_config.inventory_export_hooks

    if not hooks:
        return

    console.step("Execute inventory export hooks")
    for hookname, params in hooks:
        console.verbose("Execute export hook: %s%s%s%s" %
                        (tty.blue, tty.bold, hookname, tty.normal))
        try:
            func = inventory_plugins.inv_export[hookname]["export_function"]
            func(host_config.hostname, params, inventory_tree.get_raw_tree())
        except Exception as e:
            if cmk.utils.debug.enabled():
                raise
            raise MKGeneralException("Failed to execute export hook %s: %s" %
                                     (hookname, e))
Exemple #4
0
def _do_inv_for_realhost(host_config, sources, multi_host_sections, hostname,
                         ipaddress, inventory_tree, status_data_tree):
    for source in sources.get_data_sources():
        if isinstance(source, data_sources.SNMPDataSource):
            source.set_on_error("raise")
            source.set_do_snmp_scan(True)
            source.disable_data_source_cache()
            source.set_use_snmpwalk_cache(False)
            source.set_ignore_check_interval(True)
            source.set_check_plugin_name_filter(
                _gather_snmp_check_plugin_names_inventory)
            if multi_host_sections is not None:
                # Status data inventory already provides filled multi_host_sections object.
                # SNMP data source: If 'do_status_data_inv' is enabled there may be
                # sections for inventory plugins which were not fetched yet.
                source.enforce_check_plugin_names(None)
                host_sections = multi_host_sections.add_or_get_host_sections(
                    hostname, ipaddress)
                source.set_fetched_check_plugin_names(
                    host_sections.sections.keys())
                host_sections_from_source = source.run()
                host_sections.update(host_sections_from_source)

    if multi_host_sections is None:
        multi_host_sections = sources.get_host_sections()

    console.step("Executing inventory plugins")
    import cmk.base.inventory_plugins as inventory_plugins
    console.verbose("Plugins:")
    for section_name, plugin in inventory_plugins.sorted_inventory_plugins():
        section_content = multi_host_sections.get_section_content(
            hostname, ipaddress, section_name, for_discovery=False)
        # TODO: Don't we need to take config.check_info[check_plugin_name]["handle_empty_info"]:
        #       like it is done in checking.execute_check()? Standardize this!
        if not section_content:  # section not present (None or [])
            # Note: this also excludes existing sections without info..
            continue

        if all([x in [[], {}, None] for x in section_content]):
            # Inventory plugins which get parsed info from related
            # check plugin may have more than one return value, eg
            # parse function of oracle_tablespaces returns ({}, {})
            continue

        console.verbose(" %s%s%s%s" %
                        (tty.green, tty.bold, section_name, tty.normal))

        # Inventory functions can optionally have a second argument: parameters.
        # These are configured via rule sets (much like check parameters).
        inv_function = plugin["inv_function"]
        inv_function_args = inspect.getargspec(inv_function).args

        kwargs = {}
        for dynamic_arg_name, dynamic_arg_value in [
            ("inventory_tree", inventory_tree),
            ("status_data_tree", status_data_tree),
        ]:
            if dynamic_arg_name in inv_function_args:
                inv_function_args.remove(dynamic_arg_name)
                kwargs[dynamic_arg_name] = dynamic_arg_value

        if len(inv_function_args) == 2:
            params = host_config.inventory_parameters(section_name)
            args = [section_content, params]
        else:
            args = [section_content]
        inv_function(*args, **kwargs)
    console.verbose("\n")