def discovered_labels_of(self, hostname, service_desc): # type: (str, Text) -> DiscoveredServiceLabels # Check if the autochecks for the given hostname were already read # The service in question might have no entry in the autochecks file # In this scenario it gets an empty DiscoveredServiceLabels entry host_results = self._discovered_labels_of.get(hostname) if host_results is not None: service_result = host_results.get(service_desc) if service_result is None: host_results[service_desc] = DiscoveredServiceLabels() return host_results[service_desc] # Only read the raw autochecks here. Do not compute the effective check parameters, # because that would invole ruleset matching which in would require the labels to # be already computed. # The following function reads the autochecks and populates the the discovered labels cache self._read_raw_autochecks_cached(hostname) result = self._discovered_labels_of.get(hostname, {}).get(service_desc) if result is None: # The service was not present in the autochecks, create an empty instance result = DiscoveredServiceLabels() self._discovered_labels_of.setdefault(hostname, {})[service_desc] = result return result
def test_ruleset_matcher_get_service_ruleset_values_labels( monkeypatch, hostname, service_description, expected_result): ts = Scenario() ts.add_host("host1") ts.set_autochecks("host1", [ Service("cpu.load", None, "CPU load", "{}", service_labels=DiscoveredServiceLabels( ServiceLabel(u"os", u"linux"), ServiceLabel(u"abc", u"xä"), ServiceLabel(u"hu", u"ha"), )) ]) ts.add_host("host2") ts.set_autochecks("host2", [ Service("cpu.load", None, "CPU load", "{}", service_labels=DiscoveredServiceLabels()), ]) config_cache = ts.apply(monkeypatch) matcher = config_cache.ruleset_matcher assert list( matcher.get_service_ruleset_values( config_cache.ruleset_match_object_of_service( hostname, service_description), ruleset=service_label_ruleset, is_binary=False)) == expected_result
def test_discovered_service_labels_to_dict(): labels = DiscoveredServiceLabels() assert labels.to_dict() == {} labels["äbc"] = "123" labels["xyz"] = "blä" assert labels.to_dict() == { "äbc": "123", "xyz": "blä", }
def _parse_discovered_service_label_from_ast(ast_service_labels): # type: (ast.Dict) -> DiscoveredServiceLabels labels = DiscoveredServiceLabels() # mypy does not get the types of the ast objects here if not hasattr(ast_service_labels, "keys"): # # type: ignore return labels for key, value in zip(ast_service_labels.keys, ast_service_labels.values): # mypy does not get the types of the ast objects here labels.add_label(ServiceLabel(key.s, value.s)) # type: ignore return labels
def __init__(self, check_plugin_name, item, description, parameters, service_labels=None): # type: (CheckPluginName, Item, Text, CheckParameters, DiscoveredServiceLabels) -> None self._check_plugin_name = check_plugin_name self._item = item self._description = description self._parameters = parameters self._service_labels = service_labels or DiscoveredServiceLabels()
def test_host_ruleset_match_object_of_service(monkeypatch): ts = Scenario() ts.add_host("xyz") ts.add_host("test-host", tags={"agent": "no-agent"}) ts.set_autochecks("test-host", [ Service("cpu.load", None, "CPU load", "{}", service_labels=DiscoveredServiceLabels(ServiceLabel(u"abc", u"xä"),)) ]) config_cache = ts.apply(monkeypatch) obj = config_cache.ruleset_match_object_of_service("xyz", "bla blä") assert isinstance(obj, RulesetMatchObject) assert obj.to_dict() == { "host_name": "xyz", "service_description": "bla blä", "service_labels": {}, "service_cache_id": ('bla bl\xc3\xa4', None), } obj = config_cache.ruleset_match_object_of_service("test-host", "CPU load") service_labels = {u"abc": u"xä"} assert isinstance(obj, RulesetMatchObject) assert obj.to_dict() == { "host_name": "test-host", "service_description": "CPU load", "service_labels": service_labels, "service_cache_id": ('CPU load', obj._generate_hash(service_labels)), }
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 discovered_labels_of(self, hostname, service_desc): # type: (str, Text) -> DiscoveredServiceLabels if (hostname, service_desc) in self._discovered_labels_of: return self._discovered_labels_of[(hostname, service_desc)] result = DiscoveredServiceLabels() # Only read the raw autochecks here. Do not compute the effective check parameters, # because that would invole ruleset matching which in would require the labels to # be already computed. for service in self._read_raw_autochecks_of(hostname): if service.description == service_desc: result = service.service_labels break self._discovered_labels_of[(hostname, service_desc)] = result return result
def _read_raw_autochecks_of(self, hostname): # type: (str) -> List[Service] """Read automatically discovered checks of one host""" basedir = cmk.utils.paths.autochecks_dir filepath = basedir + '/' + hostname + '.mk' result = [] # type: List[Service] if not os.path.exists(filepath): return result check_config = config.get_check_variables() try: cmk_base.console.vverbose("Loading autochecks from %s\n", filepath) autochecks_raw = eval( file(filepath).read().decode("utf-8"), check_config, check_config) # type: List[Dict] except SyntaxError as e: cmk_base.console.verbose("Syntax error in file %s: %s\n", filepath, e, stream=sys.stderr) if cmk.utils.debug.enabled(): raise return result except Exception as e: cmk_base.console.verbose("Error in file %s:\n%s\n", filepath, e, stream=sys.stderr) if cmk.utils.debug.enabled(): raise return result for entry in autochecks_raw: labels = DiscoveredServiceLabels() for label_id, label_value in entry["service_labels"].items(): labels.add_label(ServiceLabel(label_id, label_value)) # With Check_MK 1.2.7i3 items are now defined to be unicode strings. Convert # items from existing autocheck files for compatibility. TODO remove this one day item = entry["item"] if isinstance(item, str): item = config.decode_incoming_string(item) if not isinstance(entry["check_plugin_name"], six.string_types): raise MKGeneralException( "Invalid entry '%r' in check table of host '%s': " "The check type must be a string." % (entry, hostname)) try: description = config.service_description( hostname, entry["check_plugin_name"], item) except Exception: continue # ignore result.append( Service( check_plugin_name=str(entry["check_plugin_name"]), item=item, description=description, parameters=entry["parameters"], service_labels=labels, )) return result
def labels(request): if request.param == "host": return DiscoveredHostLabels(StructuredDataTree()) return DiscoveredServiceLabels()
def labels(request): if request.param == "host": return DiscoveredHostLabels() return DiscoveredServiceLabels()
def test_remove_autochecks_file(): assert autochecks.has_autochecks("host") is False autochecks.save_autochecks_file("host", []) assert autochecks.has_autochecks("host") is True autochecks.remove_autochecks_file("host") assert autochecks.has_autochecks("host") is False @pytest.mark.parametrize("items,expected_content", [ ([], "[\n]\n"), ([ discovery.DiscoveredService( 'df', u'/xyz', u"Filesystem /xyz", "None", DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))), discovery.DiscoveredService( 'df', u'/', u"Filesystem /", "{}", DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))), discovery.DiscoveredService( 'cpu.loads', None, "CPU load", "cpuload_default_levels", DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))), ], """[ {'check_plugin_name': 'cpu.loads', 'item': None, 'parameters': cpuload_default_levels, 'service_labels': {u'x': u'y'}}, {'check_plugin_name': 'df', 'item': u'/', 'parameters': {}, 'service_labels': {u'x': u'y'}}, {'check_plugin_name': 'df', 'item': u'/xyz', 'parameters': None, 'service_labels': {u'x': u'y'}}, ]\n"""), ]) def test_save_autochecks_file(items, expected_content): autochecks.save_autochecks_file("host", items)