Пример #1
0
def test_transform_influxdb_connnections(
        uc: update_config.UpdateConfig) -> None:
    if version.is_raw_edition():
        return

    # fmt: off
    from cmk.gui.cee.plugins.wato import influxdb  # type: ignore[import] # isort:skip # pylint: disable=no-name-in-module
    # fmt: on

    influx_db_connection_config = influxdb.InfluxDBConnectionConfig()
    influx_db_connection_config.save({
        "InfluxDB_Connection_1": {
            "title": "influxdb",
            "comment": "",
            "docu_url": "",
            "disabled": False,
            "site": ["-all-sites"],
            "instance": {
                "protocol": ("https", {
                    "port": 8086,
                    "no-cert-check": True
                }),
                "instance_host": "influx.somwhere.com",
                "instance_token": "to_be_transformed",
            },
        }
    })

    uc._transform_influxdb_connnections()
    assert influx_db_connection_config.load_for_reading(
    )["InfluxDB_Connection_1"]["instance"]["instance_token"] == (
        "password",
        "to_be_transformed",
    )
Пример #2
0
def test__transform_contact_groups(
    uc: update_config.UpdateConfig,
    contact_groups: Mapping[ContactgroupName, MutableMapping[str, Any]],
    expected_contact_groups: Mapping[ContactgroupName, MutableMapping[str, Any]],
) -> None:
    uc._transform_contact_groups(contact_groups)
    assert contact_groups == expected_contact_groups
Пример #3
0
def test_remove_removed_check_plugins_from_ignored_checks(
        uc: update_config.UpdateConfig) -> None:
    ruleset = Ruleset("ignored_checks", {})
    ruleset.from_config(
        Folder(""),
        [
            {
                "id": "1",
                "condition": {},
                "options": {
                    "disabled": False
                },
                "value": ["a", "b", "mgmt_c"],
            },
            {
                "id": "2",
                "condition": {},
                "options": {
                    "disabled": False
                },
                "value": ["d", "e"],
            },
            {
                "id": "3",
                "condition": {},
                "options": {
                    "disabled": False
                },
                "value": ["mgmt_f"],
            },
            {
                "id": "4",
                "condition": {},
                "options": {
                    "disabled": False
                },
                "value": ["a", "g"],
            },
        ],
    )
    rulesets = RulesetCollection()
    rulesets.set_rulesets({"ignored_checks": ruleset})
    uc._remove_removed_check_plugins_from_ignored_checks(
        rulesets,
        {
            CheckPluginName("b"),
            CheckPluginName("d"),
            CheckPluginName("e"),
            CheckPluginName("f"),
        },
    )
    leftover_rules = [
        rule
        for (_folder, idx, rule) in rulesets.get("ignored_checks").get_rules()
    ]
    assert len(leftover_rules) == 2
    assert leftover_rules[0].id == "1"
    assert leftover_rules[1].id == "4"
    assert leftover_rules[0].value == ["a", "mgmt_c"]
    assert leftover_rules[1].value == ["a", "g"]
Пример #4
0
def test__rename_discovered_host_label_files_do_not_overwrite(
    monkeypatch: pytest.MonkeyPatch,
    uc: update_config.UpdateConfig,
) -> None:
    ts = Scenario()
    ts.add_host("abc.d")
    ts.apply(monkeypatch)

    host_name = "abc.d"
    old_path = (cmk.utils.paths.discovered_host_labels_dir /
                host_name).with_suffix(".mk")
    new_path = cmk.utils.paths.discovered_host_labels_dir / (host_name + ".mk")

    old_path.parent.mkdir(exist_ok=True, parents=True)
    with old_path.open("w") as f:
        f.write("{}\n")
    assert old_path.exists()

    with new_path.open("w") as f:
        f.write("{}\n")
    assert new_path.exists()

    uc._rename_discovered_host_label_files()

    assert old_path.exists()
    assert new_path.exists()
Пример #5
0
def test__transform_replaced_wato_rulesets_and_params(
    uc: update_config.UpdateConfig,
    ruleset_name: RulesetName,
    param_value: RuleValue,
    new_ruleset_name: RulesetName,
    transformed_param_value: RuleValue,
) -> None:
    all_rulesets = RulesetCollection()
    # checkmk: all_rulesets are loaded via
    # all_rulesets = cmk.gui.watolib.rulesets.AllRulesets()
    all_rulesets.set_rulesets({
        ruleset_name:
        _instantiate_ruleset(ruleset_name, param_value),
        new_ruleset_name:
        Ruleset(new_ruleset_name, {}),
    })

    uc._transform_replaced_wato_rulesets(all_rulesets)
    uc._transform_wato_rulesets_params(all_rulesets)

    assert not all_rulesets.exists(ruleset_name)

    rules = all_rulesets.get(new_ruleset_name).get_rules()
    assert len(rules) == 1

    rule = rules[0]
    assert len(rule) == 3
    assert rule[2].value == transformed_param_value
Пример #6
0
def test__migrate_pre_2_0_audit_log_not_existing(
    uc: update_config.UpdateConfig,
    old_path: Path,
    new_path: Path,
) -> None:
    assert not new_path.exists()
    assert not old_path.exists()
    uc._migrate_pre_2_0_audit_log()
    assert not new_path.exists()
    assert not old_path.exists()
Пример #7
0
def test__transform_wato_rulesets_params(
    uc: update_config.UpdateConfig,
    ruleset_name: RulesetName,
    param_value: RuleValue,
    transformed_param_value: RuleValue,
) -> None:
    ruleset = _instantiate_ruleset(ruleset_name, param_value)
    rulesets = RulesetCollection()
    rulesets.set_rulesets({ruleset_name: ruleset})

    uc._transform_wato_rulesets_params(rulesets)

    assert len(ruleset.get_rules()[0]) == 3
    assert ruleset.get_rules()[0][2].value == transformed_param_value
Пример #8
0
def test_cleanup_version_specific_caches(uc: update_config.UpdateConfig) -> None:
    paths = [
        Path(cmk.utils.paths.include_cache_dir, "builtin"),
        Path(cmk.utils.paths.include_cache_dir, "local"),
        Path(cmk.utils.paths.precompiled_checks_dir, "builtin"),
        Path(cmk.utils.paths.precompiled_checks_dir, "local"),
    ]
    for base_dir in paths:
        base_dir.mkdir(parents=True, exist_ok=True)
        cached_file = base_dir / "if"
        with cached_file.open("w", encoding="utf-8") as f:
            f.write("\n")
        uc._cleanup_version_specific_caches()
        assert not cached_file.exists()
        assert base_dir.exists()
Пример #9
0
def test__transform_discovery_disabled_services(
    uc: update_config.UpdateConfig,
    ruleset_spec: Sequence[RuleSpec],
    expected_ruleset: Sequence[RuleSpec],
) -> None:
    ruleset = Ruleset("ignored_services", {})
    ruleset.from_config(Folder(""), ruleset_spec)
    assert ruleset.get_rules()

    rulesets = RulesetCollection()
    rulesets.set_rulesets({"ignored_services": ruleset})

    uc._transform_discovery_disabled_services(rulesets)

    folder_rules = ruleset.get_folder_rules(Folder(""))
    assert [r.to_config() for r in folder_rules] == expected_ruleset
Пример #10
0
def test__migrate_pre_2_0_audit_log_not_migrate_already_migrated(
    uc: update_config.UpdateConfig,
    old_audit_log: Path,
    new_path: Path,
) -> None:
    assert not new_path.exists()
    assert old_audit_log.exists()

    new_path.parent.mkdir(exist_ok=True, parents=True)
    with new_path.open("w") as f:
        f.write("abc\n")
    assert new_path.exists()

    uc._migrate_pre_2_0_audit_log()

    assert new_path.open().read() == "abc\n"
    assert old_audit_log.exists()
Пример #11
0
def test_rewrite_password_store_migrate(uc: update_config.UpdateConfig) -> None:
    with pytest.raises(ValueError):
        assert password_store.load()

    with pytest.raises(ValueError):
        assert PasswordStore().load_for_reading()

    assert _read_passwords_mk()["ding"]["password"] == "dong"

    uc._rewrite_password_store()

    assert password_store.load()["ding"] == "dong"
    assert _read_passwords_mk()["ding"]["password"] == ""
    assert PasswordStore().load_for_reading()["ding"]["password"] == "dong"

    # Once we have the new format, a second execution must not fail
    uc._rewrite_password_store()
Пример #12
0
def test_rewrite_mknotifyd_migrate(uc: update_config.UpdateConfig) -> None:
    for key, value in _read_sitespecific_mknotifyd_config().items():
        if key == "incoming":
            assert "encryption" not in value
        if key == "outgoing":
            for outgoing in value:
                assert "encryption" not in outgoing

    uc._update_mknotifyd()

    for key, value in _read_sitespecific_mknotifyd_config().items():
        if key == "incoming":
            assert value["encryption"] == "unencrypted"
        if key == "outgoing":
            for outgoing in value:
                assert outgoing["encryption"] == "upgradable"

    # Once we have the new format, a second execution must not fail
    uc._update_mknotifyd()
Пример #13
0
def test_validate_rule_values(
    mocker: MockerFixture,
    uc: update_config.UpdateConfig,
    rulesets: Mapping[RulesetName, RuleValue],
    n_expected_warnings: int,
) -> None:
    all_rulesets = RulesetCollection()
    all_rulesets.set_rulesets({
        ruleset_name: _instantiate_ruleset(
            ruleset_name,
            rule_value,
        )
        for ruleset_name, rule_value in rulesets.items()
    })
    mock_warner = mocker.patch.object(
        uc._logger,
        "warning",
    )
    uc._validate_rule_values(all_rulesets)
    assert mock_warner.call_count == n_expected_warnings
Пример #14
0
def test_update_global_config(
    mocker: MockerFixture,
    uc: update_config.UpdateConfig,
) -> None:
    mocker.patch.object(
        update_config,
        "REMOVED_GLOBALS_MAP",
        [
            ("global_a", "new_global_a", {
                True: 1,
                False: 0
            }),
            ("global_b", "new_global_b", {}),
            ("missing", "new_missing", {}),
        ],
    )
    mocker.patch.object(
        update_config,
        "filter_unknown_settings",
        lambda global_config:
        {k: v
         for k, v in global_config.items() if k != "unknown"},
    )
    mocker.patch.object(
        update_config.UpdateConfig,
        "_transform_global_config_value",
        lambda _self, config_var, config_val: {
            "new_global_a": config_val,
            "new_global_b": 15,
            "global_c": ["x", "y", "z"],
            "unchanged": config_val,
        }[config_var],
    )
    assert uc._update_global_config({
        "global_a": True,
        "global_b": 14,
        "global_c": None,
        "unchanged": "please leave me alone",
        "unknown": "How did this get here?",
    }) == {
        "global_c": ["x", "y", "z"],
        "unchanged": "please leave me alone",
        "new_global_a": 1,
        "new_global_b": 15,
    }
Пример #15
0
def test__migrate_pre_2_0_audit_log(
    uc: update_config.UpdateConfig,
    old_audit_log: Path,
    new_path: Path,
) -> None:
    assert not new_path.exists()
    assert old_audit_log.exists()

    uc._migrate_pre_2_0_audit_log()

    assert new_path.exists()
    assert not old_audit_log.exists()

    # Now try to parse the migrated log with the new logic
    log_store = AuditLogStore(new_path)
    assert log_store.read() == [
        AuditLogStore.Entry(
            time=1604991356,
            object_ref=None,
            user_id="cmkadmin",
            action="liveproxyd-activate",
            text="Activating changes of Livestatus Proxy configuration",
            diff_text=None,
        ),
        AuditLogStore.Entry(
            time=1604991356,
            object_ref=None,
            user_id="cmkadmin",
            action="liveproxyd-activate",
            text="Activating changes of Livestatus Proxy configuration",
            diff_text=None,
        ),
        AuditLogStore.Entry(
            time=1604992040,
            object_ref=ObjectRef(ObjectRefType.Host, "heute2"),
            user_id="cmkadmin",
            action="create-host",
            text="Created new host heute2.",
            diff_text=None,
        ),
        AuditLogStore.Entry(
            time=1604992159,
            object_ref=ObjectRef(ObjectRefType.Host, "heute2"),
            user_id="cmkadmin",
            action="delete-host",
            text="Deleted host heute2",
            diff_text=None,
        ),
        AuditLogStore.Entry(
            time=1604992163,
            object_ref=ObjectRef(ObjectRefType.Host, "heute1"),
            user_id="cmkadmin",
            action="create-host",
            text="Created new host heute1.",
            diff_text=None,
        ),
        AuditLogStore.Entry(
            time=1604992166,
            object_ref=ObjectRef(ObjectRefType.Host, "heute12"),
            user_id="cmkadmin",
            action="create-host",
            text="Created new host heute12.",
            diff_text=None,
        ),
    ]
Пример #16
0
def test_rewrite_password_store_skip_when_empty(
        uc: update_config.UpdateConfig) -> None:
    store.save_text_to_file(password_store.password_store_path(), "")
    assert os.path.getsize(password_store.password_store_path()) == 0
    uc._rewrite_password_store()
    assert os.path.getsize(password_store.password_store_path()) == 0
Пример #17
0
def test_rewrite_password_store_skip_when_missing(
        uc: update_config.UpdateConfig) -> None:
    assert not password_store.password_store_path().exists()
    uc._rewrite_password_store()
    assert not password_store.password_store_path().exists()
Пример #18
0
def test_cleanup_version_specific_caches_missing_directory(
        uc: update_config.UpdateConfig) -> None:
    uc._cleanup_version_specific_caches()