Ejemplo n.º 1
0
def test_discovered_host_labels_add():
    labels_1 = DiscoveredHostLabels()
    labels_1.add_label(HostLabel(u"äbc", u"123", "plugin_1"))

    labels_2 = DiscoveredHostLabels()
    labels_2.add_label(HostLabel(u"xyz", u"blä", "plugin_2"))

    new_labels = labels_1 + labels_2
    assert new_labels.to_dict() == {
        u"äbc": {
            "value": u"123",
            "plugin_name": "plugin_1",
        },
        u"xyz": {
            "value": u"blä",
            "plugin_name": "plugin_2",
        },
    }

    labels_1 += labels_2
    assert labels_1.to_dict() == {
        u"äbc": {
            "value": u"123",
            "plugin_name": "plugin_1",
        },
        u"xyz": {
            "value": u"blä",
            "plugin_name": "plugin_2",
        },
    }
Ejemplo n.º 2
0
def test_discovered_host_labels_store_save(discovered_host_labels_dir):
    store = DiscoveredHostLabelsStore("host")

    labels = DiscoveredHostLabels(HostLabel(u"xyz", u"äbc"))
    label_dict = labels.to_dict()

    assert not store.file_path.exists()  # pylint: disable=no-member

    store.save(label_dict)
    assert store.file_path.exists()  # pylint: disable=no-member
    assert store.load() == label_dict
Ejemplo n.º 3
0
 def __init__(self, result=()):
     self.entries = []
     self.labels = DiscoveredHostLabels()
     if not result:
         # discovering nothing is valid!
         return
     for entry in result:
         if isinstance(entry, DiscoveredHostLabels):
             self.labels += entry
         elif isinstance(entry, HostLabel):
             self.labels.add_label(entry)
         else:
             self.entries.append(DiscoveryEntry(entry))
     self.entries.sort(key=repr)
Ejemplo n.º 4
0
def _do_inv_for(sources, multi_host_sections, host_config, ipaddress,
                do_status_data_inv):
    # type: (data_sources.DataSources, data_sources.MultiHostSections, config.HostConfig, Optional[str], bool) -> Tuple[Optional[float], StructuredDataTree, StructuredDataTree, DiscoveredHostLabels]
    hostname = host_config.hostname

    _initialize_inventory_tree()
    inventory_tree = g_inv_tree
    status_data_tree = StructuredDataTree()
    discovered_host_labels = DiscoveredHostLabels(inventory_tree)

    node = inventory_tree.get_dict("software.applications.check_mk.cluster.")
    if host_config.is_cluster:
        node["is_cluster"] = True
        _do_inv_for_cluster(host_config, inventory_tree)
    else:
        node["is_cluster"] = False
        _do_inv_for_realhost(host_config, sources, multi_host_sections,
                             hostname, ipaddress, inventory_tree,
                             status_data_tree, discovered_host_labels)

    inventory_tree.normalize_nodes()
    old_timestamp = _save_inventory_tree(hostname, inventory_tree)
    _run_inventory_export_hooks(host_config, inventory_tree)

    success_msg = [
        "Found %s%s%d%s inventory entries" %
        (tty.bold, tty.yellow, inventory_tree.count_entries(), tty.normal)
    ]

    if host_config.do_host_label_discovery:
        DiscoveredHostLabelsStore(hostname).save(
            discovered_host_labels.to_dict())
        success_msg.append(
            "and %s%s%d%s host labels" %
            (tty.bold, tty.yellow, len(discovered_host_labels), tty.normal))

    console.section_success(", ".join(success_msg))

    if do_status_data_inv:
        status_data_tree.normalize_nodes()
        _save_status_data_tree(hostname, status_data_tree)

        console.section_success("Found %s%s%d%s status entries" %
                                (tty.bold, tty.yellow,
                                 status_data_tree.count_entries(), tty.normal))

    return old_timestamp, inventory_tree, status_data_tree, discovered_host_labels
Ejemplo n.º 5
0
 def __init__(self,
              item,
              parameters=None,
              service_labels=None,
              host_labels=None):
     # type: (Item, CheckParameters, DiscoveredServiceLabels, DiscoveredHostLabels) -> None
     self.item = item
     self.parameters = parameters
     self.service_labels = service_labels or DiscoveredServiceLabels()
     self.host_labels = host_labels or DiscoveredHostLabels()
Ejemplo n.º 6
0
def test_discovered_host_labels_from_dict():
    label_dict = {
        u"äbc": {
            "value": u"123",
            "plugin_name": "plugin_1",
        },
        u"xyz": {
            "value": u"blä",
            "plugin_name": "plugin_2",
        },
    }
    labels = DiscoveredHostLabels.from_dict(label_dict)
    assert labels.to_dict() == label_dict
Ejemplo n.º 7
0
class DiscoveryResult(object):
    """
    The result of the discovery as a whole.

    Much like in the case of the check result, this also makes sure
    that yield-based discovery functions run, and that no exceptions
    get lost in the laziness.
    """

    # TODO: Add some more consistency checks here.
    def __init__(self, result=()):
        self.entries = []
        self.labels = DiscoveredHostLabels()
        if not result:
            # discovering nothing is valid!
            return
        for entry in result:
            if isinstance(entry, DiscoveredHostLabels):
                self.labels += entry
            elif isinstance(entry, HostLabel):
                self.labels.add_label(entry)
            else:
                self.entries.append(DiscoveryEntry(entry))
        self.entries.sort(key=repr)

    def __eq__(self, other):
        return self.entries == other.entries and self.labels == other.labels

    def __repr__(self):
        args = self.entries + [
            HostLabel(six.text_type(k), six.text_type(self.labels[k]))
            for k in self.labels
        ]
        return "DiscoveryResult(%r)" % (args, )

    def __str__(self):
        return "%s%s" % (map(
            tuple, self.entries), [self.labels[k].label for k in self.labels])
Ejemplo n.º 8
0
def test_discovered_host_labels_to_list():
    labels = DiscoveredHostLabels()
    assert labels.to_list() == []

    labels.add_label(HostLabel(u"äbc", u"123", "plugin_1"))
    labels.add_label(HostLabel(u"xyz", u"blä", "plugin_2"))

    assert labels.to_list() == [
        HostLabel(u"xyz", u"blä", "plugin_2"),
        HostLabel(u"äbc", u"123", "plugin_1")
    ]
Ejemplo n.º 9
0
def test_discovered_host_labels_to_dict():
    labels = DiscoveredHostLabels()
    assert labels.to_dict() == {}

    labels.add_label(HostLabel(u"äbc", u"123", "plugin_1"))
    labels.add_label(HostLabel(u"xyz", u"blä", "plugin_2"))

    assert labels.to_dict() == {
        u"äbc": {
            "value": u"123",
            "plugin_name": "plugin_1",
        },
        u"xyz": {
            "value": u"blä",
            "plugin_name": "plugin_2",
        },
    }
Ejemplo n.º 10
0
def labels(request):
    if request.param == "host":
        return DiscoveredHostLabels(StructuredDataTree())
    return DiscoveredServiceLabels()
Ejemplo n.º 11
0
def labels(request):
    if request.param == "host":
        return DiscoveredHostLabels()
    return DiscoveredServiceLabels()
Ejemplo n.º 12
0
def test_subset_patterns(check_manager):

    check = check_manager.get_check("ps")
    check.set_check_api_utils_globals()  # needed for host name

    parsed = check.context['parse_ps'](
        splitter("""(user,0,0,0.5) main
(user,0,0,0.4) main_dev
(user,0,0,0.1) main_dev
(user,0,0,0.5) main_test"""))[1]

    # Boundary in match is necessary otherwise main instance accumulates all
    wato_rule = [({
        'default_params': {
            'cpu_rescale_max': True,
            'levels': (1, 1, 99999, 99999)
        },
        'match': '~(main.*)\\b',
        'descr': '%s'
    }, [], ["@all"], {})]

    discovered = [
        ('main', {
            'cpu_rescale_max': True,
            'levels': (1, 1, 99999, 99999),
            'process': '~(main.*)\\b',
            'match_groups': ('main',),
            'user': None,
            'cgroup': (None, False),
        }),
        ('main_dev', {
            'cpu_rescale_max': True,
            'levels': (1, 1, 99999, 99999),
            'process': '~(main.*)\\b',
            'match_groups': ('main_dev',),
            'user': None,
            'cgroup': (None, False),
        }),
        ('main_test', {
            'cpu_rescale_max': True,
            'levels': (1, 1, 99999, 99999),
            'process': '~(main.*)\\b',
            'match_groups': ('main_test',),
            'user': None,
            'cgroup': (None, False),
        }),
        DiscoveredHostLabels(),
        DiscoveredHostLabels(),
        DiscoveredHostLabels(),
    ]

    assert check.context["inventory_ps_common"](wato_rule, parsed) == discovered

    def counted_reference(count):
        return CheckResult([
            (0, "%s process%s" % (count, '' if count == 1 else 'es'), [("count", count, 100000,
                                                                        100000, 0, None)]),
            (0, "0.5% CPU", [("pcpu", 0.5, None, None, None, None)]),
        ])

    for (item, params), count in zip(discovered, [1, 2, 1]):
        output = CheckResult(check.context["check_ps_common"](item, params, parsed, cpu_cores=1))
        assertCheckResultsEqual(output, counted_reference(count))
Ejemplo n.º 13
0
         "process_info": "text"
     },
     "match": "~.*(fire)fox",
     "descr": "firefox is on %s",
     "user": None,
 }, [], ["@all"], {
     "description": u"Firefox"
 }),
 ({
     "default_params": {
         "process_info": "text"
     },
     "match": "~.*(fire)fox",
     "descr": "firefox is on %s",
     "user": None,
     "label": DiscoveredHostLabels(HostLabel(u'marco', u'polo'), HostLabel(u'peter', u'pan')),
 }, [], ["@all"], {
     "description": u"Firefox with host labels"
 }),
 ({
     "default_params": {
         "cpu_rescale_max": True,
         "cpu_average": 15,
         "process_info": "html",
         "resident_levels_perc": (25.0, 50.0),
         "virtual_levels": (1024**3, 2 * 1024**3),
         "resident_levels": (1024**3, 2 * 1024**3),
         "icon": "emacs.png",
     },
     "descr": "emacs %u",
     "match": "emacs",