예제 #1
0
def _validate_detect_spec(detect_spec: SNMPDetectBaseType) -> None:
    if not (isinstance(detect_spec, list)
            and all(isinstance(element, list) for element in detect_spec)):
        raise TypeError(
            "value of 'detect' keyword must be a list of lists of 3-tuples")

    for atom in itertools.chain(*detect_spec):
        if not isinstance(atom, tuple) or not len(atom) == 3:
            raise TypeError(
                "value of 'detect' keyword must be a list of lists of 3-tuples"
            )
        oid_string, expression, expected_match = atom

        if not isinstance(oid_string, str):
            raise TypeError(
                "value of 'detect' keywords first element must be a string: %r"
                % (oid_string, ))
        if not str(oid_string).startswith('.'):
            raise ValueError(
                "OID in value of 'detect' keyword must start with '.': %r" %
                (oid_string, ))
        SNMPTree.validate_oid_string(oid_string.rstrip('.*'))

        if expression is not None:
            try:
                _ = regex(expression)
            except MKGeneralException as exc:
                raise ValueError(
                    "invalid regex in value of 'detect' keyword: %s" % exc)

        if not isinstance(expected_match, bool):
            TypeError(
                "value of 'detect' keywords third element must be a boolean: %r"
                % (expected_match, ))
예제 #2
0
def _create_snmp_trees_from_tuple(
        snmp_info_element: tuple) -> Tuple[List[SNMPTree], Optional[LayoutRecoverSuboids]]:
    """Create a SNMPTrees from (part of) a legacy definition

    Legacy definition *elements* can be 2-tuple or 3-tuple.
    We are quite generous here: we will make sure that
     * base will not end with '.'
     * subtrees are strings, starting but not ending with '.'
     * oids are not the empty string.
    """
    assert isinstance(snmp_info_element, tuple)
    assert len(snmp_info_element) in (2, 3)
    base = snmp_info_element[0].rstrip('.')

    # "Triple"-case: recursively return a list
    if len(snmp_info_element) == 3:
        tmp_base, suboids, oids = snmp_info_element
        base_list = [("%s.%s" % (tmp_base, str(i).strip('.'))) for i in suboids]
        return sum((_create_snmp_trees_from_tuple((base, oids))[0] for base in base_list),
                   []), suboids

    # this fixes 7 weird cases:
    oids = ["%d" % oid if isinstance(oid, int) and oid > 0 else oid for oid in snmp_info_element[1]]

    if '' in oids:  # this fixes 19 cases
        base, tail = str(base).rsplit('.', 1)
        oids = [
            o if isinstance(o, int) else type(o)(("%s.%s" % (tail, o)).strip('.')) for o in oids
        ]
    else:  # this fixes 21 cases
        common, oids = _extract_conmmon_part(oids)
        if common:
            base = "%s.%s" % (base, common)

    return [SNMPTree(base=base, oids=oids)], None
예제 #3
0
def test_create_snmp_section_plugin():

    trees: List[SNMPTree] = [
        SNMPTree(
            base=".1.2.3",
            oids=[OIDEnd(), "2.3"],
        ),
    ]

    detect = SNMPDetectSpecification([
        [(".1.2.3.4.5", "Foo.*", True)],
    ])

    plugin = section_plugins.create_snmp_section_plugin(
        name="norris",
        parsed_section_name="chuck",
        parse_function=_parse_dummy,
        fetch=trees,
        detect_spec=detect,
        supersedes=["foo", "bar"],
    )

    assert isinstance(plugin, SNMPSectionPlugin)
    assert len(plugin) == 11
    assert plugin.name == SectionName("norris")
    assert plugin.parsed_section_name == ParsedSectionName("chuck")
    assert plugin.parse_function is _parse_dummy
    assert plugin.host_label_function is section_plugins._noop_host_label_function
    assert plugin.host_label_default_parameters is None
    assert plugin.host_label_ruleset_name is None
    assert plugin.host_label_ruleset_type == "merged"
    assert plugin.detect_spec == detect
    assert plugin.trees == trees
    assert plugin.supersedes == {SectionName("bar"), SectionName("foo")}
예제 #4
0
def test_create_snmp_section_plugin():

    trees: List[SNMPTree] = [
        SNMPTree(
            base='.1.2.3',
            oids=[OIDEnd(), '2.3'],
        ),
    ]

    detect = SNMPDetectSpecification([
        [('.1.2.3.4.5', 'Foo.*', True)],
    ])

    plugin = section_plugins.create_snmp_section_plugin(
        name="norris",
        parsed_section_name="chuck",
        parse_function=_parse_dummy,
        fetch=trees,
        detect_spec=detect,
        supersedes=["foo", "bar"],
    )

    assert isinstance(plugin, SNMPSectionPlugin)
    assert len(plugin) == 8
    assert plugin.name == SectionName("norris")
    assert plugin.parsed_section_name == ParsedSectionName("chuck")
    assert plugin.parse_function is _parse_dummy
    assert plugin.host_label_function is section_plugins._noop_host_label_function
    assert plugin.detect_spec == detect
    assert plugin.trees == trees
    assert plugin.supersedes == {SectionName("bar"), SectionName("foo")}
예제 #5
0
def test_create_snmp_section_plugin_single_tree():

    single_tree = SNMPTree(base=".1.2.3", oids=[OIDEnd(), "2.3"])

    plugin = section_plugins.create_snmp_section_plugin(
        name="norris",
        parse_function=lambda string_table: string_table,
        # just one, no list:
        fetch=single_tree,
        detect_spec=SNMPDetectSpecification([[(".1.2.3.4.5", "Foo.*", True)]]),
    )

    assert plugin.trees == [single_tree]
    # the plugin only specified a single tree (not a list),
    # so a wrapper should unpack the argument:
    assert plugin.parse_function([[["A", "B"]]]) == [["A", "B"]]
예제 #6
0
def test_create_snmp_section_plugin_from_legacy():

    plugin = section_plugins_legacy.create_snmp_section_plugin_from_legacy(
        "norris",
        {
            'parse_function': old_school_parse_function,
            'inventory_function': old_school_discover_function,
        },
        old_school_scan_function,
        (".1.2.3.4.5", ["2", 3]),
        validate_creation_kwargs=True,
    )

    assert plugin.name == SectionName("norris")
    assert plugin.parsed_section_name == ParsedSectionName("norris")
    assert plugin.parse_function.__name__ == "old_school_parse_function"
    assert plugin.host_label_function.__name__ == "_noop_host_label_function"
    assert plugin.supersedes == set()
    assert plugin.detect_spec == [[(".1.2.3.4.5", "norris.*", True)]]
    assert plugin.trees == [SNMPTree(base=".1.2.3.4.5", oids=["2", "3"])]
            ],
        ),
    ],
)
def test_create_layout_recover_function(suboids_list, input_data,
                                        expected_output):
    layout_recover_func = _create_layout_recover_function(suboids_list)
    assert layout_recover_func(input_data) == expected_output


@pytest.mark.parametrize(
    "element, expected_tree, expected_suboids",
    [
        (
            (".1.2.3", ["4", "5"]),
            [SNMPTree(base=".1.2.3", oids=["4", "5"])],
            None,
        ),
        (
            (".1.2.3", ["4", ""]),
            [SNMPTree(base=".1.2", oids=["3.4", "3"])],
            None,
        ),
        (
            (".1.2", ["3.4", "3.5"]),
            [SNMPTree(base=".1.2.3", oids=["4", "5"])],
            None,
        ),
        (
            (".1.2.3", list(range(4, 6))),
            [SNMPTree(base=".1.2.3", oids=["4", "5"])],
예제 #8
0
def test_oidspec_invalid_value(value):
    with pytest.raises(ValueError):
        SNMPTree.validate_oid_string(value)
예제 #9
0
def test_snmptree_valid(base, oids):
    with pytest.raises((ValueError, TypeError)):
        SNMPTree(base=base, oids=oids).validate()