Пример #1
0
def test_attribute_defaults(mode, monkeypatch):
    ipaddress = "1.2.3.4"
    hostname = "testhost"
    Scenario().add_host(hostname).apply(monkeypatch)

    configurator = TCPConfigurator(hostname, ipaddress, mode=mode)
    configurator.file_cache.path = Path("/my/path/")
    assert configurator.configure_fetcher() == {
        "file_cache": {
            "disabled": False,
            "max_age": None,
            "path": "/my/path",
            "simulation": False,
            "use_outdated": False,
        },
        "family": socket.AF_INET,
        "address": (ipaddress, 6556),
        "timeout": 5.0,
        "encryption_settings": {
            "use_realtime": "enforce",
            "use_regular": "disable",
        },
    }
    assert configurator.description == "TCP: %s:%s" % (ipaddress, 6556)

    source = TCPDataSource(configurator=configurator)

    assert source.hostname == hostname
    assert source.ipaddress == ipaddress
    assert source.id == "agent"
    assert configurator.file_cache.maybe is False

    # From the base class
    assert source.exception() is None
Пример #2
0
    def test_multiple_sources_from_different_hosts(self, hostname, ipaddress, config_cache, host_config):
        sources = [
            DSProgramDataSource(
                hostname + "0", ipaddress,
                configurator=DSProgramConfigurator(hostname + "0", ipaddress,
                                                   template="",),),
            TCPDataSource(hostname + "1", ipaddress),
            TCPDataSource(hostname + "2", ipaddress),
        ]

        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            sources=sources,
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        assert len(section.sections) == len(sources)
        for source in sources:
            # yapf: disable
            assert (
                section.sections[SectionName("section_name_%s" % source.hostname)]
                == [["section_content"]])
Пример #3
0
def test_tcpdatasource_only_from(monkeypatch, result, reported, rule):
    ts = Scenario().add_host("hostname")
    ts.set_option("agent_config", {"only_from": [rule]} if rule else {})
    config_cache = ts.apply(monkeypatch)

    source = TCPDataSource("hostname", "ipaddress")
    monkeypatch.setattr(config_cache, "host_extra_conf", lambda host, ruleset: ruleset)
    assert source._sub_result_only_from({"onlyfrom": reported}) == result
Пример #4
0
    def test_defaults(self, ipaddress, mode, monkeypatch):
        hostname = "testhost"
        Scenario().add_host(hostname).apply(monkeypatch)
        source = TCPDataSource(configurator=TCPConfigurator(
            hostname,
            ipaddress,
            mode=mode,
        ))

        summarizer = source.summarizer
        assert summarizer.summarize(AgentHostSections()) == (0, "Version: unknown, OS: unknown", [])
Пример #5
0
def test_tcpdatasource_only_from(monkeypatch, result, reported, rule):
    ts = Scenario().add_host("hostname")
    ts.set_option("agent_config", {"only_from": [rule]} if rule else {})
    config_cache = ts.apply(monkeypatch)

    # TODO(ml): Instantiating the DS here does not seem to be very useful.
    source = TCPDataSource("hostname", "ipaddress")
    monkeypatch.setattr(config_cache, "host_extra_conf",
                        lambda host, ruleset: ruleset)

    summarizer = Summarizer(source._host_config)
    assert summarizer._sub_result_only_from({"onlyfrom": reported}) == result
Пример #6
0
def test_attribute_defaults(monkeypatch, ipaddress):
    hostname = "testhost"
    Scenario().add_host(hostname).apply(monkeypatch)
    source = TCPDataSource(hostname, ipaddress)

    assert source._hostname == hostname
    assert source._ipaddress == ipaddress
    assert source.id() == "agent"
    assert source.port == 6556
    assert source.timeout == 5.0
    # From the base class
    assert source.get_check_plugin_names() == set()
    assert source.name() == ("agent:%s:%s" %
                             (hostname, ipaddress if ipaddress else ""))
    assert source.describe() == "TCP: %s:%s" % (ipaddress, source.port)
    assert source.is_agent_cache_disabled() is False
    assert source.get_may_use_cache_file() is False
    assert source.exception() is None
Пример #7
0
def test_piggyback_storage(mode, monkeypatch, mocker):
    hostname = "testhost"
    ipaddress = "1.2.3.4"
    raw_data = b"\n".join((
        b"<<<<piggyback header>>>>",
        b"<<<section>>>",
        b"first line",
        b"second line",
        b"<<<<>>>>",
    ))

    ts = Scenario()
    ts.add_host(hostname)
    ts.apply(monkeypatch)

    source = TCPDataSource(configurator=TCPConfigurator(
        hostname,
        ipaddress,
        mode=mode,
    ), )
    monkeypatch.setattr(time, "time", lambda: 0)
    mhs = agent.AgentParser(hostname,
                            logging.getLogger("test")).parse(raw_data)
    monkeypatch.setattr(
        type(source),
        "run",
        lambda self, *args, selected_raw_sections, **kwargs: mhs,
    )

    mocker.patch.object(
        cmk.utils.piggyback,
        "store_piggyback_raw_data",
        autospec=True,
    )

    # End of setup

    _make_host_sections(
        [(hostname, ipaddress, [source])],
        max_cachefile_age=0,
        selected_raw_sections=None,
    )

    args = cmk.utils.piggyback.store_piggyback_raw_data.call_args.args  # type: ignore[attr-defined]

    assert mhs.piggybacked_raw_data
    assert args == (hostname, mhs.piggybacked_raw_data)
Пример #8
0
    def test_multiple_sources_from_the_same_host(
        self,
        hostname,
        ipaddress,
        mode,
        config_cache,
        host_config,
    ):
        sources = [
            ProgramDataSource(configurator=ProgramConfigurator.ds(
                hostname,
                ipaddress,
                mode=mode,
                template="",
            ),),
            TCPDataSource(configurator=TCPConfigurator(
                hostname,
                ipaddress,
                mode=mode,
            ),),
        ]

        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=sources,
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        assert len(section.sections) == 1
        # yapf: disable
        assert (section.sections[SectionName("section_name_%s" % hostname)]
                == len(sources) * [["section_content"]])
Пример #9
0
class TestMakeHostSectionsHosts:
    @pytest.fixture(autouse=False)
    def patch_fs(self, fs):
        # piggyback.store_piggyback_raw_data() writes to disk.
        pass

    @pytest.fixture(autouse=True)
    def patch_io(self, monkeypatch):
        class DummyHostSection(ABCHostSections):
            def _extend_section(self, section_name, section_content):
                pass

        monkeypatch.setattr(
            ABCDataSource,
            "run",
            lambda self, *args, selected_raw_sections, **kwargs: DummyHostSection(
                sections={SectionName("section_name_%s" % self.hostname): [["section_content"]]},
                cache_info={},
                piggybacked_raw_data={},
                persisted_sections="",
            ),
        )

    @pytest.fixture
    def hostname(self):
        return "testhost"

    @pytest.fixture
    def ipaddress(self):
        return "1.2.3.4"

    @pytest.fixture
    def host_config(self, hostname):
        return config.HostConfig.make_host_config(hostname)

    @pytest.fixture
    def config_cache(self, hostname, ipaddress, monkeypatch):
        ts = Scenario().add_host(hostname)
        return ts.apply(monkeypatch)

    def test_no_sources(self, hostname, ipaddress, mode, config_cache, host_config):
        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=[],
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        # The length is not zero because the function always sets,
        # at least, a piggy back section.
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        # Public attributes from ABCHostSections:
        assert not section.sections
        assert not section.cache_info
        assert not section.piggybacked_raw_data
        assert not section.persisted_sections

    def test_one_snmp_source(self, hostname, ipaddress, mode, config_cache, host_config):
        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=[
                SNMPDataSource(configurator=SNMPConfigurator.snmp(
                    hostname,
                    ipaddress,
                    mode=mode,
                ),),
            ],
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, SNMPHostSections)

        assert len(section.sections) == 1
        assert section.sections[SectionName("section_name_%s" % hostname)] == [["section_content"]]

    @pytest.mark.parametrize(
        "source",
        [
            lambda hostname, ipaddress, *, mode: PiggyBackDataSource(configurator=
                                                                     PiggyBackConfigurator(
                                                                         hostname,
                                                                         ipaddress,
                                                                         mode=mode,
                                                                     ),),
            lambda hostname, ipaddress, *, mode: ProgramDataSource(configurator=ProgramConfigurator.
                                                                   ds(
                                                                       hostname,
                                                                       ipaddress,
                                                                       mode=mode,
                                                                       template="",
                                                                   ),),
            lambda hostname, ipaddress, *, mode: TCPDataSource(configurator=TCPConfigurator(
                hostname,
                ipaddress,
                mode=mode,
            ),),
        ],
    )
    def test_one_nonsnmp_source(self, hostname, ipaddress, mode, config_cache, host_config, source):
        source = source(hostname, ipaddress, mode=mode)
        assert source.configurator.source_type is SourceType.HOST

        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=[source],
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

        key = HostKey(hostname, ipaddress, source.configurator.source_type)
        assert key in mhs

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        assert len(section.sections) == 1
        assert section.sections[SectionName("section_name_%s" % hostname)] == [["section_content"]]

    def test_multiple_sources_from_the_same_host(
        self,
        hostname,
        ipaddress,
        mode,
        config_cache,
        host_config,
    ):
        sources = [
            ProgramDataSource(configurator=ProgramConfigurator.ds(
                hostname,
                ipaddress,
                mode=mode,
                template="",
            ),),
            TCPDataSource(configurator=TCPConfigurator(
                hostname,
                ipaddress,
                mode=mode,
            ),),
        ]

        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=sources,
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        assert len(section.sections) == 1
        # yapf: disable
        assert (section.sections[SectionName("section_name_%s" % hostname)]
                == len(sources) * [["section_content"]])

    def test_multiple_sources_from_different_hosts(self, hostname, ipaddress, mode, config_cache, host_config):
        sources = [
            ProgramDataSource(
                configurator=ProgramConfigurator.ds(hostname + "0", ipaddress,
                                                    mode=mode,
                                                   template="",),),
            TCPDataSource(configurator=TCPConfigurator(hostname + "1", ipaddress, mode=mode,),),
            TCPDataSource(
                configurator=TCPConfigurator(hostname + "2", ipaddress, mode=mode),
            ),
        ]

        mhs = make_host_sections(
            config_cache,
            host_config,
            ipaddress,
            mode=mode,
            sources=sources,
            max_cachefile_age=0,
            selected_raw_sections=None,
        )
        assert len(mhs) == 1

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

        section = mhs[key]
        assert isinstance(section, AgentHostSections)

        assert len(section.sections) == len(sources)
        for source in sources:
            # yapf: disable
            assert (
                section.sections[SectionName("section_name_%s" % source.hostname)]
                == [["section_content"]])
Пример #10
0
def test_get_summary_result_requires_host_sections(monkeypatch, ipaddress):
    hostname = "testhost"
    Scenario().add_host(hostname).apply(monkeypatch)
    source = TCPDataSource(hostname, ipaddress)

    with pytest.raises(AssertionError):
        source.get_summary_result_for_discovery()
    with pytest.raises(AssertionError):
        source.get_summary_result_for_inventory()
    with pytest.raises(AssertionError):
        source.get_summary_result_for_checking()

    source._host_sections = _abstract.AgentHostSections()

    defaults = (0, "Version: unknown, OS: unknown", []
                )  # type: ServiceCheckResult
    assert source.get_summary_result_for_discovery() == defaults
    assert source.get_summary_result_for_inventory() == defaults
    assert source.get_summary_result_for_checking() == defaults
Пример #11
0
def test_decrypt_payload_with_wrong_protocol_raises_MKAgentError():
    settings = {"use_regular": "enforce"}
    output = b"the first two bytes are not a number"

    with pytest.raises(MKAgentError):
        TCPDataSource._decrypt(output, settings)
Пример #12
0
def test_decrypt_plaintext_with_enforce_raises_MKAgentError():
    settings = {"use_regular": "enforce"}
    output = b"<<<section:sep(0)>>>\nbody\n"

    with pytest.raises(MKAgentError):
        TCPDataSource._decrypt(output, settings)
Пример #13
0
def test_decrypt_plaintext_is_noop():
    settings = {"use_regular": "allow"}
    output = b"<<<section:sep(0)>>>\nbody\n"

    assert TCPDataSource._decrypt(output, settings) == output