Exemplo n.º 1
0
def test_discovered_host_labels_repr():
    labels = DiscoveredHostLabels()
    labels.add_label(HostLabel(u"äbc", u"123", "plugin_1"))
    labels.add_label(HostLabel(u"ccc", u"ddd", "plugin_2"))
    assert repr(
        labels
    ) == "DiscoveredHostLabels(HostLabel('ccc', 'ddd', plugin_name='plugin_2'), HostLabel('äbc', '123', plugin_name='plugin_1'))"
Exemplo n.º 2
0
def test_discovered_host_labels_repr():
    labels = DiscoveredHostLabels()
    labels.add_label(HostLabel(u"äbc", u"123", SectionName("plugin_1")))
    labels.add_label(HostLabel(u"ccc", u"ddd", SectionName("plugin_2")))
    assert repr(labels) == (
        "DiscoveredHostLabels("  #
        "HostLabel('ccc', 'ddd', plugin_name=SectionName('plugin_2')), "  #
        "HostLabel('äbc', '123', plugin_name=SectionName('plugin_1')))")
Exemplo n.º 3
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",
        },
    }
Exemplo n.º 4
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
Exemplo n.º 5
0
def test_discovered_host_labels_store_save(discovered_host_labels_dir):
    store = DiscoveredHostLabelsStore("host")

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

    assert not store.file_path.exists()

    store.save(label_dict)
    assert store.file_path.exists()
    assert store.load() == label_dict
Exemplo n.º 6
0
def test_discovered_host_labels_sub():
    labels_1 = DiscoveredHostLabels()
    labels_1.add_label(HostLabel("foo", "bär", SectionName("plugin_1")))
    labels_1.add_label(HostLabel("foo2", "bär2", SectionName("plugin_2")))

    labels_2 = DiscoveredHostLabels()
    labels_2.add_label(HostLabel("foo", "bär", SectionName("plugin_1")))

    assert (labels_1 - labels_2).to_dict() == {
        "foo2": {
            "value": "bär2",
            "plugin_name": "plugin_2",
        },
    }

    assert (labels_2 - labels_1).to_dict() == {}
Exemplo n.º 7
0
def test_discovered_host_labels_path(discovered_host_labels_dir):
    hostname = "test.host.de"
    config.get_config_cache().initialize()
    assert not (discovered_host_labels_dir / hostname).exists()
    DiscoveredHostLabelsStore(hostname).save(
        DiscoveredHostLabels(HostLabel("foo", "1.5")).to_dict())
    assert (discovered_host_labels_dir / (hostname + ".mk")).exists()
Exemplo n.º 8
0
class DiscoveryResult(object):  # pylint: disable=useless-object-inheritance
    """
    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)
            # preparation for ServiceLabel Discovery
            #elif isinstance(entry, Service):
            #
            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

    # TODO: Very questionable __repr__ conversion, leading to even more
    # interesting typing Kung Fu...
    def __repr__(self):
        # type: () -> str
        entries = [o for o in self.entries
                   if isinstance(o, object)]  # type: List[object]
        host_labels = [
            HostLabel(six.text_type(k), six.text_type(self.labels[k]))
            for k in self.labels
        ]  # type: List[object]
        return "DiscoveryResult(%r)" % (entries + host_labels, )

    # TODO: Very obscure and inconsistent __str__ conversion...
    def __str__(self):
        return "%s%s" % (map(
            tuple, self.entries), [self.labels[k].label for k in self.labels])
Exemplo n.º 9
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)
         # preparation for ServiceLabel Discovery
         #elif isinstance(entry, Service):
         #
         else:
             self.entries.append(DiscoveryEntry(entry))
     self.entries.sort(key=repr)
Exemplo n.º 10
0
 def __init__(self,
              item: Item,
              parameters: LegacyCheckParameters = None,
              service_labels: DiscoveredServiceLabels = None,
              host_labels: DiscoveredHostLabels = None) -> None:
     self.item = item
     self.parameters = parameters
     self.service_labels = service_labels or DiscoveredServiceLabels()
     self.host_labels = host_labels or DiscoveredHostLabels()
Exemplo n.º 11
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()
def old_school_discover_function(parsed_extra):
    _parsed, _extra_section = parsed_extra
    yield "item1", {"discoverd_param": 42}
    yield HOST_LABELS[0]
    yield Service(
        "item2",
        {},
        host_labels=DiscoveredHostLabels(*HOST_LABELS[1:]),
    )
    yield "item3", "{'how_bad_is_this': 100}"
Exemplo n.º 13
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)
            # preparation for ServiceLabel Discovery
            #elif isinstance(entry, Service):
            #
            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])
Exemplo n.º 14
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
Exemplo n.º 15
0
def test_perform_host_label_discovery(discovered_host_labels_dir,
                                      existing_labels, new_labels,
                                      expected_labels, load_labels):
    hostname = "testhost"
    config.get_config_cache().initialize()
    store = DiscoveredHostLabelsStore(hostname)
    store.save(
        DiscoveredHostLabels(*[HostLabel(*x)
                               for x in existing_labels]).to_dict())

    discovery_parameters = DiscoveryParameters(
        on_error="raise",
        load_labels=load_labels,
        save_labels=False,
    )

    new_host_labels, _host_labels_per_plugin = _perform_host_label_discovery(
        hostname, DiscoveredHostLabels(*[HostLabel(*x) for x in new_labels]),
        discovery_parameters)

    labels_expected = DiscoveredHostLabels(
        *[HostLabel(*x) for x in expected_labels])
    assert new_host_labels.to_dict() == labels_expected.to_dict()
Exemplo n.º 16
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")
    ]
Exemplo n.º 17
0
def test_discovered_host_labels_to_list():
    labels = DiscoveredHostLabels()
    assert labels.to_list() == []

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

    assert labels.to_list() == [
        HostLabel("xyz", "blä", SectionName("plugin_2")),
        HostLabel("äbc", "123", SectionName("plugin_1")),
    ]
Exemplo n.º 18
0
def test_host_labels_ps_no_match_pattern():
    section = (
        1,
        [
            (
                ps.ps_info("(root,4056,1512,0.0/52-04:56:05,5689)".split()
                           ),  # type: ignore[call-arg]
                ["/usr/lib/ssh/sshd"],
            ),
        ])
    params = [
        Parameters({
            "default_params": {},
            "descr": "SSH",
            "match": "~wat?",
            "label": DiscoveredHostLabels(HostLabel(u'marco', u'polo')),
        }),
        Parameters({}),
    ]
    assert list(ps.host_labels_ps(params, section)) == []
Exemplo n.º 19
0
def test_discovered_host_labels_to_dict():
    labels = DiscoveredHostLabels()
    assert labels.to_dict() == {}

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

    assert labels.to_dict() == {
        "äbc": {
            "value": "123",
            "plugin_name": "plugin_1",
        },
        "xyz": {
            "value": "blä",
            "plugin_name": "plugin_2",
        },
    }
Exemplo n.º 20
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",
        },
    }
Exemplo n.º 21
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))
Exemplo n.º 22
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",
Exemplo n.º 23
0
         "cpu_rescale_max": "cpu_rescale_max_unspecified",
         "process_info": "text"
     },
     "match": "~.*(fire)fox",
     "descr": "firefox is on %s",
     "user": None,
 },
 {
     "default_params": {
         "cpu_rescale_max": "cpu_rescale_max_unspecified",
         "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')),
 },
 {
     "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",
     "user": False
 },
Exemplo n.º 24
0
def test_get_discovery_specs():
    assert ps.get_discovery_specs([
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
            "descr": "smss",
            "match": "~smss.exe",
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "cpulevels": (90.0, 98.0),
                "handle_count": (1000, 2000),
                "levels": (1, 1, 99999, 99999),
                "max_age": (3600, 7200),
                "resident_levels": (104857600, 209715200),
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "virtual_levels": (1073741824000, 2147483648000),
            },
            "descr": "svchost",
            "match": "svchost.exe",
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "process_info": "text",
            },
            "match": "~.*(fire)fox",
            "descr": "firefox is on %s",
            "user": None,
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "process_info": "text",
            },
            "match": "~.*(fire)fox",
            "descr": "firefox is on %s",
            "user": None,
            "label": TEST_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",
            "user": False,
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "max_age": (3600, 7200),
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "resident_levels": (104857600, 209715200),
            },
            "match": "~.*cron",
            "descr": "cron",
            "user": "******",
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
            "descr": "sshd",
            "match": "~.*sshd",
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
            "descr": "PS counter",
            "user": "******",
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "process_info": "text",
            },
            "match": r"~/omd/sites/(\w+)/lib/cmc/checkhelper",
            "descr": "Checkhelpers %s",
            "user": None,
        },
        {
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "process_info": "text",
            },
            "match": r"~/omd/sites/\w+/lib/cmc/checkhelper",
            "descr": "Checkhelpers Overall",
            "user": None,
        },
        {
            "descr": "cron",
            "match": "/usr/sbin/cron",
            "user": None,
            "default_params": {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "levels": (1, 1, 20, 20),
            },
        },
        {},
    ]) == [
        (
            "smss",
            "~smss.exe",
            None,
            (None, False),
            DiscoveredHostLabels(),
            {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
        ),
        (
            "svchost",
            "svchost.exe",
            None,
            (None, False),
            {},
            {
                "cpulevels": (90.0, 98.0),
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "handle_count": (1000, 2000),
                "levels": (1, 1, 99999, 99999),
                "max_age": (3600, 7200),
                "resident_levels": (104857600, 209715200),
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "virtual_levels": (1073741824000, 2147483648000),
            },
        ),
        (
            "firefox is on %s",
            "~.*(fire)fox",
            None,
            (None, False),
            {},
            {
                "process_info": "text",
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
            },
        ),
        (
            "firefox is on %s",
            "~.*(fire)fox",
            None,
            (None, False),
            TEST_LABELS,
            {
                "process_info": "text",
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
            },
        ),
        (
            "emacs %u",
            "emacs",
            False,
            (None, False),
            {},
            {
                "cpu_average": 15,
                "cpu_rescale_max": True,
                "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",
            },
        ),
        (
            "cron",
            "~.*cron",
            "root",
            (None, False),
            {},
            {
                "max_age": (3600, 7200),
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "resident_levels": (104857600, 209715200),
            },
        ),
        (
            "sshd",
            "~.*sshd",
            None,
            (None, False),
            {},
            {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
        ),
        (
            "PS counter",
            None,
            "zombie",
            (None, False),
            {},
            {
                "cpu_rescale_max": "cpu_rescale_max_unspecified"
            },
        ),
        (
            "Checkhelpers %s",
            r"~/omd/sites/(\w+)/lib/cmc/checkhelper",
            None,
            (None, False),
            {},
            {
                "process_info": "text",
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
            },
        ),
        (
            "Checkhelpers Overall",
            r"~/omd/sites/\w+/lib/cmc/checkhelper",
            None,
            (None, False),
            {},
            {
                "process_info": "text",
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
            },
        ),
        (
            "cron",
            "/usr/sbin/cron",
            None,
            (None, False),
            {},
            {
                "cpu_rescale_max": "cpu_rescale_max_unspecified",
                "levels": (1, 1, 20, 20),
            },
        ),
    ]
Exemplo n.º 25
0
# conditions defined in the file COPYING, which is part of this source code package.

import pytest  # type: ignore[import]

from cmk.base.discovered_labels import DiscoveredHostLabels

from cmk.base.plugins.agent_based.agent_based_api.v1 import HostLabel, type_defs
from cmk.base.plugins.agent_based.utils import ps

pytestmark = pytest.mark.checks

TEST_LABELS = DiscoveredHostLabels.from_dict({
    "marco": {
        "value": "polo",
        "plugin_name": None
    },
    "peter": {
        "value": "pan",
        "plugin_name": None
    }
})


def test_get_discovery_specs():
    assert ps.get_discovery_specs([
        {
            "default_params": {
                'cpu_rescale_max': 'cpu_rescale_max_unspecified'
            },
            "descr": "smss",
            "match": "~smss.exe"
        },
Exemplo n.º 26
0
def labels(request):
    if request.param == "host":
        return DiscoveredHostLabels()
    return DiscoveredServiceLabels()
Exemplo n.º 27
0
def get_check_preview(
    *,
    host_name: HostName,
    max_cachefile_age: int,
    use_cached_snmp_data: bool,
    on_error: str,
) -> Tuple[CheckPreviewTable, DiscoveredHostLabels]:
    """Get the list of service of a host or cluster and guess the current state of
    all services if possible"""
    config_cache = config.get_config_cache()
    host_config = config_cache.get_host_config(host_name)

    ip_address = None if host_config.is_cluster else config.lookup_ip_address(host_config)
    discovery_parameters = DiscoveryParameters(
        on_error=on_error,
        load_labels=False,
        save_labels=False,
        only_host_labels=False,
    )

    _set_cache_opts_of_checkers(use_cached_snmp_data=use_cached_snmp_data)
    nodes = sources.make_nodes(
        config_cache, host_config, ip_address, Mode.DISCOVERY,
        sources.make_sources(
            host_config,
            ip_address,
            mode=Mode.DISCOVERY,
            on_scan_error=on_error,
        ))

    parsed_sections_broker = ParsedSectionsBroker()
    sources.update_host_sections(
        parsed_sections_broker,
        nodes,
        max_cachefile_age=max_cachefile_age,
        host_config=host_config,
        fetcher_messages=list(
            sources.fetch_all(
                nodes,
                max_cachefile_age=max_cachefile_age,
                host_config=host_config,
            )),
        selected_sections=NO_SELECTION,
    )

    grouped_services, host_label_result = _get_host_services(
        host_config,
        ip_address,
        parsed_sections_broker,
        discovery_parameters,
    )

    table: CheckPreviewTable = []
    for check_source, services_with_nodes in grouped_services.items():
        for service, found_on_nodes in services_with_nodes:
            plugin = agent_based_register.get_check_plugin(service.check_plugin_name)
            params = _preview_params(host_name, service, plugin, check_source)

            if check_source in ['legacy', 'active', 'custom']:
                exitcode = None
                output = u"WAITING - %s check, cannot be done offline" % check_source.title()
                ruleset_name: Optional[RulesetName] = None
            else:

                ruleset_name = (str(plugin.check_ruleset_name)
                                if plugin and plugin.check_ruleset_name else None)
                wrapped_params = (Parameters(wrap_parameters(params)) if plugin and
                                  plugin.check_default_parameters is not None else None)

                exitcode, output, _perfdata = checking.get_aggregated_result(
                    parsed_sections_broker,
                    host_config,
                    ip_address,
                    service,
                    plugin,
                    lambda p=wrapped_params: p,  # type: ignore[misc]  # "type of lambda"
                ).result

            # Service discovery never uses the perfdata in the check table. That entry
            # is constantly discarded, yet passed around(back and forth) as part of the
            # discovery result in the request elements. Some perfdata VALUES are not parsable
            # by ast.literal_eval such as "inf" it lead to ValueErrors. Thus keep perfdata empty
            perfdata: List[MetricTuple] = []
            table.append((
                _preview_check_source(host_name, service, check_source),
                str(service.check_plugin_name),
                ruleset_name,
                service.item,
                service.parameters,
                params,
                service.description,
                exitcode,
                output,
                perfdata,
                service.service_labels.to_dict(),
                found_on_nodes,
            ))

    return table, DiscoveredHostLabels(
        *{
            # TODO (mo): According to unit tests, this is what was done prior to refactoring.
            # Im not sure this is desired. If it is, it should be explained.
            **{l.name: l for l in host_label_result.vanished},
            **{l.name: l for l in host_label_result.present},
        }.values())
Exemplo n.º 28
0
def test_get_discovery_specs():
    assert ps.get_discovery_specs([
        {
            "default_params": {},
            "descr": "smss",
            "match": "~smss.exe"
        },
        {
            "default_params": {
                "cpulevels": (90.0, 98.0),
                "handle_count": (1000, 2000),
                "levels": (1, 1, 99999, 99999),
                "max_age": (3600, 7200),
                "resident_levels": (104857600, 209715200),
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "virtual_levels": (1073741824000, 2147483648000),
            },
            "descr": "svchost",
            "match": "svchost.exe"
        },
        {
            "default_params": {
                "process_info": "text"
            },
            "match": "~.*(fire)fox",
            "descr": "firefox is on %s",
            "user": None,
        },
        {
            "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')),
        },
        {
            "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",
            "user": False
        },
        {
            "default_params": {
                "max_age": (3600, 7200),
                "resident_levels_perc": (25.0, 50.0),
                "single_cpulevels": (90.0, 98.0),
                "resident_levels": (104857600, 209715200),
            },
            "match": "~.*cron",
            "descr": "cron",
            "user": "******"
        },
        {
            "default_params": {},
            "descr": "sshd",
            "match": "~.*sshd"
        },
        {
            'default_params': {},
            'descr': 'PS counter',
            'user': '******',
        },
        {
            "default_params": {
                "process_info": "text"
            },
            "match": r"~/omd/sites/(\w+)/lib/cmc/checkhelper",
            "descr": "Checkhelpers %s",
            "user": None,
        },
        {
            "default_params": {
                "process_info": "text"
            },
            "match": r"~/omd/sites/\w+/lib/cmc/checkhelper",
            "descr": "Checkhelpers Overall",
            "user": None,
        },
        {},
    ]) == [
        ("smss", "~smss.exe", None, (None, False), DiscoveredHostLabels(), {
            'cpu_rescale_max': None
        }),
        ("svchost", "svchost.exe", None, (None, False), {}, {
            "cpulevels": (90.0, 98.0),
            'cpu_rescale_max': None,
            "handle_count": (1000, 2000),
            "levels": (1, 1, 99999, 99999),
            "max_age": (3600, 7200),
            "resident_levels": (104857600, 209715200),
            "resident_levels_perc": (25.0, 50.0),
            "single_cpulevels": (90.0, 98.0),
            "virtual_levels": (1073741824000, 2147483648000),
        }),
        ("firefox is on %s", "~.*(fire)fox", None, (None, False), {}, {
            "process_info": "text",
            'cpu_rescale_max': None,
        }),
        ("firefox is on %s", "~.*(fire)fox", None, (None, False),
         DiscoveredHostLabels(HostLabel(u'marco', u'polo'), HostLabel(u'peter', u'pan')), {
             "process_info": "text",
             'cpu_rescale_max': None,
         }),
        ("emacs %u", "emacs", False, (None, False), {}, {
            "cpu_average": 15,
            'cpu_rescale_max': True,
            "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",
        }),
        ("cron", "~.*cron", "root", (None, False), {}, {
            "max_age": (3600, 7200),
            'cpu_rescale_max': None,
            "resident_levels_perc": (25.0, 50.0),
            "single_cpulevels": (90.0, 98.0),
            "resident_levels": (104857600, 209715200)
        }),
        ("sshd", "~.*sshd", None, (None, False), {}, {
            'cpu_rescale_max': None
        }),
        ('PS counter', None, 'zombie', (None, False), {}, {
            'cpu_rescale_max': None
        }),
        ("Checkhelpers %s", r"~/omd/sites/(\w+)/lib/cmc/checkhelper", None, (None, False), {}, {
            "process_info": "text",
            'cpu_rescale_max': None,
        }),
        ("Checkhelpers Overall", r"~/omd/sites/\w+/lib/cmc/checkhelper", None, (None, False), {}, {
            "process_info": "text",
            'cpu_rescale_max': None,
        }),
    ]