示例#1
0
 def raw_data(self, file_cache):
     if isinstance(file_cache, DefaultAgentFileCache):
         return AgentRawData(b"<<<check_mk>>>\nagent raw data")
     assert isinstance(file_cache, SNMPFileCache)
     table: SNMPTable = []
     raw_data = SNMPRawData({SectionName("X"): table})
     return raw_data
示例#2
0
 def _deserialize(data: bytes) -> SNMPRawData:
     try:
         return SNMPRawData({
             SectionName(k): v
             for k, v in json.loads(data.decode("utf8")).items()
         })
     except json.JSONDecodeError:
         raise ValueError(repr(data))
示例#3
0
    def _fetch_from_io(self, mode: Mode) -> SNMPRawData:
        """Select the sections we need to fetch and do that

        Detection:

         * Mode.DISCOVERY / CACHED_DISCOVERY:
           In this straight forward case we must determine all applicable sections for
           the device in question.
           Should the fetcher make it to this IO function in *CACHED_*DISCOVERY mode, it
           should behave in the same way as DISCOVERY mode.

         * Mode.INVENTORY
           There is no need to try to detect all sections: For the inventory we have a
           set of sections known to be relevant for inventory plugins, and we can restrict
           detection to those.

         * Mode.CHECKING
           Sections needed for checking are known without detection. If the status data
           inventory is enabled, we detect from the inventory sections; but not those,
           which are fetched for checking anyway.

        """
        selected_sections = self._get_sections_fetched_unconditionally(mode)
        selected_sections |= self._detect(
            select_from=self._get_sections_fetch_detected(mode) -
            selected_sections, )

        if self.use_snmpwalk_cache:
            walk_cache_msg = "SNMP walk cache is enabled: Use any locally cached information"
            get_snmp = partial(snmp_table.get_snmp_table_cached,
                               backend=self._backend)
        else:
            walk_cache_msg = "SNMP walk cache is disabled"
            get_snmp = partial(snmp_table.get_snmp_table,
                               backend=self._backend)

        fetched_data: MutableMapping[SectionName, SNMPSectionContent] = {}
        for section_name in self._sort_section_names(selected_sections):
            self._logger.debug("%s: Fetching data (%s)", section_name,
                               walk_cache_msg)

            fetched_section_data = [
                get_snmp(section_name, entry)
                for entry in self.snmp_plugin_store[section_name].trees
            ]

            if any(fetched_section_data):
                fetched_data[section_name] = fetched_section_data

        return SNMPRawData(fetched_data)
示例#4
0
 def __init__(
     self,
     hostname: HostName,
     ipaddress: HostAddress,
     *,
     mode: Mode,
     source_type: SourceType,
     preselected_sections: PreselectedSectionNames,
     id_: str,
     cache_dir: Optional[Path] = None,
     persisted_section_dir: Optional[Path] = None,
     title: str,
     on_error: str = "raise",
 ):
     super().__init__(
         hostname,
         ipaddress,
         mode=mode,
         source_type=source_type,
         fetcher_type=FetcherType.SNMP,
         description=SNMPSource._make_description(hostname,
                                                  ipaddress,
                                                  title=title),
         default_raw_data=SNMPRawData({}),
         default_host_sections=SNMPHostSections(),
         preselected_sections=preselected_sections,
         id_=id_,
         cache_dir=cache_dir,
         persisted_section_dir=persisted_section_dir,
     )
     if self.ipaddress is None:
         # snmp_config.ipaddress is not Optional.
         #
         # At least classic SNMP enforces that there is an address set,
         # Inline-SNMP has some lookup logic for some reason. We need
         # to find out whether or not we can really have None here.
         # Looks like it could be the case for cluster hosts which
         # don't have an IP address set.
         raise TypeError(self.ipaddress)
     self.snmp_config = (
         # Because of crap inheritance.
         self.host_config.snmp_config(self.ipaddress)
         if self.source_type is SourceType.HOST else
         self.host_config.management_snmp_config)
     self.on_snmp_scan_error = on_error
     # Attributes below are wrong
     self.use_snmpwalk_cache = True
    def test_one_snmp_source(self, hostname, ipaddress, mode, config_cache,
                             host_config):
        mhs = MultiHostSections()
        update_host_sections(
            mhs,
            make_nodes(
                config_cache,
                host_config,
                ipaddress,
                mode=mode,
                sources=[
                    SNMPSource.snmp(
                        hostname,
                        ipaddress,
                        mode=mode,
                        selected_sections=NO_SELECTION,
                    ),
                ],
            ),
            max_cachefile_age=0,
            host_config=host_config,
            fetcher_messages=[
                FetcherMessage.from_raw_data(
                    result.OK(SNMPRawData({})),
                    Snapshot.null(),
                    FetcherType.SNMP,
                ),
            ],
            selected_sections=NO_SELECTION,
        )
        assert len(mhs) == 1

        key = HostKey(hostname, ipaddress, SourceType.HOST)
        assert key in mhs

        section = mhs[key]

        assert len(section.sections) == 1
        assert section.sections[SectionName("section_name_%s" %
                                            hostname)] == [["section_content"]]
示例#6
0
    def _extract_persisted_sections(
            self, raw_data: SNMPRawData) -> SNMPPersistedSections:
        """Extract the sections to be persisted from the raw_data and return it

        Gather the check types to be persisted, extract the related data from
        the raw data, calculate the times and store the persisted info for
        later use.
        """
        persisted_sections: SNMPPersistedSections = {}

        for section_name, section_content in raw_data.items():
            fetch_interval = self._host_config.snmp_fetch_interval(
                section_name)
            if fetch_interval is None:
                continue

            cached_at = int(time.time())
            until = cached_at + (fetch_interval * 60)
            persisted_sections[section_name] = (cached_at, until,
                                                section_content)

        return persisted_sections
示例#7
0
    def _extract_persisted_sections(
        raw_data: SNMPRawData,
        host_config: config.HostConfig,
    ) -> PersistedSections[SNMPSectionContent]:
        """Extract the sections to be persisted from the raw_data and return it

        Gather the check types to be persisted, extract the related data from
        the raw data, calculate the times and store the persisted info for
        later use.
        """
        persisted_sections = PersistedSections[SNMPSectionContent]({})

        for section_name, section_content in raw_data.items():
            fetch_interval = host_config.snmp_fetch_interval(section_name)
            if fetch_interval is None:
                continue

            cached_at = int(time.time())
            until = cached_at + (fetch_interval * 60)
            # pylint does not seem to understand `NewType`... leave the checking up to mypy.
            persisted_sections[section_name] = (  # false positive: pylint: disable=E1137
                (cached_at, until, section_content))

        return persisted_sections
示例#8
0
 def _to_cache_file(self, raw_data: SNMPRawData) -> bytes:
     return (repr({str(k): v
                   for k, v in raw_data.items()}) + "\n").encode("utf-8")
示例#9
0
 def _serialize(value: SNMPRawData) -> bytes:
     return json.dumps({str(k): v for k, v in value.items()}).encode("utf8")
示例#10
0
 def snmp_raw_data(self):
     table: SNMPTable = [[[6500337, 11822045]]]
     raw_data = SNMPRawData({SectionName('snmp_uptime'): table})
     return raw_data
示例#11
0
 def snmp_payload(self):
     table: SNMPTable = []
     return SNMPResultMessage(SNMPRawData({SectionName("name"): table}))
示例#12
0
 def _from_cache_file(raw_data: bytes) -> SNMPRawData:
     return SNMPRawData({
         SectionName(k): v
         for k, v in ast.literal_eval(raw_data.decode("utf-8")).items()
     })