Ejemplo n.º 1
0
 def __delitem__(self, key):
     # type: (str) -> None
     self._raise_for_scope_violation()
     unique_key = get_item_state_prefix() + (key, )
     if unique_key not in get_all_item_states():
         raise KeyError(key)
     clear_item_state(key)
Ejemplo n.º 2
0
    def _update_with_parse_function(self, section_content, section_name):
        # type: (AbstractSectionContent, SectionName) -> ParsedSectionContent
        """Transform the section_content using the defined parse functions.

        Some checks define a parse function that is used to transform the section_content
        somehow. It is applied by this function.

        Please note that this is not a check/subcheck individual setting. This option is related
        to the agent section.

        All exceptions raised by the parse function will be catched and re-raised as
        MKParseFunctionError() exceptions."""

        if section_name not in config.check_info:
            return section_content

        parse_function = cast(Callable[[AbstractSectionContent], ParsedSectionContent],
                              config.check_info[section_name]["parse_function"])
        if not parse_function:
            return section_content

        # TODO: Item state needs to be handled in local objects instead of the
        # item_state._cached_item_states object
        orig_item_state_prefix = item_state.get_item_state_prefix()
        try:
            item_state.set_item_state_prefix(section_name, None)
            return parse_function(section_content)
        except Exception:
            if cmk.utils.debug.enabled():
                raise
            raise MKParseFunctionError(*sys.exc_info())
        finally:
            item_state.set_item_state_prefix(*orig_item_state_prefix)

        return section_content
Ejemplo n.º 3
0
def initialised_item_state():
    previous = item_state.get_item_state_prefix()
    item_state._cached_item_states.reset()
    item_state.set_item_state_prefix(("unitialised-test-env", None))
    try:
        yield
    finally:
        item_state.set_item_state_prefix(previous)
Ejemplo n.º 4
0
def context(plugin_name: CheckPluginName,
            item: Optional[str]) -> Iterator[None]:
    """Set item state prefix"""
    saved_prefix = get_item_state_prefix()
    set_item_state_prefix((str(plugin_name), item))

    try:
        yield
    finally:
        set_item_state_prefix(saved_prefix)
Ejemplo n.º 5
0
def context(plugin, item):
    # type: (ItemStateKeyElement, ItemStateKeyElement) -> Iterator[None]
    """Set item state prefix"""
    saved_prefix = get_item_state_prefix()
    set_item_state_prefix(plugin, item)

    try:
        yield
    finally:
        set_item_state_prefix(*saved_prefix)
Ejemplo n.º 6
0
def context(plugin_name, item):
    # type: (PluginName, Optional[str]) -> Iterator[None]
    """Set item state prefix"""
    saved_prefix = get_item_state_prefix()
    set_item_state_prefix(str(plugin_name), item)

    try:
        yield
    finally:
        set_item_state_prefix(*saved_prefix)
def _test_context(mock_state: Mapping[str, object]):
    previous_prefix = item_state.get_item_state_prefix()
    item_state._cached_item_states.reset()
    item_state.set_item_state_prefix(("item_state_unit_tests", None))
    for k, v in mock_state.items():
        item_state.set_item_state(k, v)
    try:
        yield
    finally:
        item_state._cached_item_states.reset()
        item_state.set_item_state_prefix(previous_prefix)
Ejemplo n.º 8
0
    def _update_with_parse_function(
        section_content: AbstractSectionContent,
        section_name: SectionName,
    ) -> ParsedSectionContent:
        """Transform the section_content using the defined parse functions.

        Some checks define a parse function that is used to transform the section_content
        somehow. It is applied by this function.

        Please note that this is not a check/subcheck individual setting. This option is related
        to the agent section.

        All exceptions raised by the parse function will be catched and re-raised as
        MKParseFunctionError() exceptions."""
        section_plugin = config.get_registered_section_plugin(section_name)
        if section_plugin is None:
            # use legacy parse function for unmigrated sections
            parse_function = config.check_info.get(str(section_name),
                                                   {}).get("parse_function")
            if parse_function is None:
                return section_content
        else:
            # TODO (mo): deal with the parsed_section_name feature (CMK-4006)
            if str(section_plugin.name) != str(
                    section_plugin.parsed_section_name):
                raise NotImplementedError()
            parse_function = section_plugin.parse_function

        # TODO (mo): make this unnecessary
        parse_function = cast(
            Callable[[AbstractSectionContent], ParsedSectionContent],
            parse_function)

        # TODO: Item state needs to be handled in local objects instead of the
        # item_state._cached_item_states object
        # TODO (mo): ValueStores (formally Item state) need to be *only* available
        # from within the check function, nowhere else.
        orig_item_state_prefix = item_state.get_item_state_prefix()
        try:
            item_state.set_item_state_prefix(section_name, None)
            return parse_function(section_content)

        except item_state.MKCounterWrapped:
            raise

        except Exception:
            if cmk.utils.debug.enabled():
                raise
            raise MKParseFunctionError(*sys.exc_info())

        finally:
            item_state.set_item_state_prefix(*orig_item_state_prefix)
Ejemplo n.º 9
0
    def _update_with_parse_function(
        section_content: ABCRawDataSection,
        section_name: SectionName,
        check_legacy_info: Dict[str, Dict[str, Any]],
    ) -> ParsedSectionContent:
        """Transform the section_content using the defined parse functions.

        Some checks define a parse function that is used to transform the section_content
        somehow. It is applied by this function.

        Please note that this is not a check/subcheck individual setting. This option is related
        to the agent section.

        All exceptions raised by the parse function will be catched and re-raised as
        MKParseFunctionError() exceptions."""
        # We can use the migrated section: we refuse to migrate sections with
        # "'node_info'=True", so the auto-migrated ones will keep working.
        # This function will never be called on checks programmed against the new
        # API (or migrated manually)
        if not agent_based_register.is_registered_section_plugin(section_name):
            # use legacy parse function for unmigrated sections
            parse_function = check_legacy_info.get(str(section_name),
                                                   {}).get("parse_function")
        else:
            section_plugin = agent_based_register.get_section_plugin(
                section_name)
            parse_function = cast(
                Callable[[ABCRawDataSection], ParsedSectionContent],
                section_plugin.parse_function)

        if parse_function is None:
            return section_content

        # (mo): ValueStores (formally Item state) need to be *only* available
        # from within the check function, nowhere else.
        orig_item_state_prefix = item_state.get_item_state_prefix()
        try:
            item_state.set_item_state_prefix(section_name, None)
            return parse_function(section_content)

        except item_state.MKCounterWrapped:
            raise

        except Exception:
            if cmk.utils.debug.enabled():
                raise
            raise MKParseFunctionError(*sys.exc_info())

        finally:
            item_state.set_item_state_prefix(*orig_item_state_prefix)
Ejemplo n.º 10
0
 def __repr__() -> str:
     return "<value store %r>" % (get_item_state_prefix(), )
Ejemplo n.º 11
0
 def __iter__(self) -> Iterator:
     self._raise_for_scope_violation()
     prefix = get_item_state_prefix()
     return iter(unique_key[-1] for unique_key in get_all_item_states()
                 if unique_key[:2] == prefix)
Ejemplo n.º 12
0
 def __len__(self) -> int:
     self._raise_for_scope_violation()
     prefix = get_item_state_prefix()
     return sum(unique_key[:2] == prefix
                for unique_key in get_all_item_states())
Ejemplo n.º 13
0
 def _get_validated_item_state_prefix() -> ServicePrefix:
     prefix = get_item_state_prefix()
     if not prefix:
         raise MKGeneralException(
             "accessing value store outside check function")
     return prefix
Ejemplo n.º 14
0
 def __getitem__(self, key):
     # type: (str) -> Any
     self._raise_for_scope_violation()
     unique_key = get_item_state_prefix() + (key, )
     return get_all_item_states()[unique_key]
Ejemplo n.º 15
0
 def _raise_for_scope_violation():
     if not get_item_state_prefix():
         raise MKGeneralException(
             "accessing value store outside check function")