diff --git a/swh/vault/api/server.py b/swh/vault/api/server.py --- a/swh/vault/api/server.py +++ b/swh/vault/api/server.py @@ -6,6 +6,7 @@ import asyncio import collections import os +from typing import Any, Dict, Optional import aiohttp.web @@ -192,15 +193,14 @@ return app -def get_local_backend(cfg): +def check_config(cfg: Dict[str, Any]) -> Dict[str, Any]: if "vault" not in cfg: - raise ValueError("missing '%vault' configuration") + raise ValueError("missing 'vault' configuration") vcfg = cfg["vault"] if vcfg["cls"] != "local": raise EnvironmentError( - "The vault backend can only be started with a 'local' " "configuration", - err=True, + "The vault backend can only be started with a 'local' configuration", ) args = vcfg["args"] if "cache" not in args: @@ -212,20 +212,22 @@ for key in ("cache", "storage", "scheduler"): if not args.get(key): - raise ValueError("invalid configuration; missing %s config entry." % key) + raise ValueError(f"invalid configuration: missing {key} config entry.") - return get_vault("local", **args) + return args -def make_app_from_configfile(config_file=None, **kwargs): +def make_app_from_configfile(config_file: Optional[str] = None, **kwargs): if config_file is None: config_file = DEFAULT_CONFIG_PATH config_file = os.environ.get("SWH_CONFIG_FILENAME", config_file) + assert config_file is not None if os.path.isfile(config_file): cfg = config.read(config_file, DEFAULT_CONFIG) else: cfg = config.load_named_config(config_file, DEFAULT_CONFIG) - vault = get_local_backend(cfg) + kwargs = check_config(cfg) + vault = get_vault("local", **kwargs) return make_app(backend=vault, client_max_size=cfg["client_max_size"], **kwargs) diff --git a/swh/vault/cookers/__init__.py b/swh/vault/cookers/__init__.py --- a/swh/vault/cookers/__init__.py +++ b/swh/vault/cookers/__init__.py @@ -1,4 +1,4 @@ -# Copyright (C) 2017 The Software Heritage developers +# Copyright (C) 2017-2020 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information @@ -24,26 +24,37 @@ return COOKER_TYPES[obj_type] -def get_cooker(obj_type, obj_id): +def get_cooker(obj_type: str, obj_id: str): + """Instantiate a cooker class of type obj_type. + + Returns: + Cooker class in charge of cooking the obj_type with id obj_id. + + Raises: + ValueError in case of a missing top-level vault key configuration or a storage + key. + EnvironmentError in case the vault configuration reference a non remote class. + + """ if "SWH_CONFIG_FILENAME" in os.environ: cfg = read_config(os.environ["SWH_CONFIG_FILENAME"], DEFAULT_CONFIG) else: cfg = load_named_config(DEFAULT_CONFIG_PATH, DEFAULT_CONFIG) cooker_cls = get_cooker_cls(obj_type) if "vault" not in cfg: - raise ValueError("missing '%vault' configuration") + raise ValueError("missing 'vault' configuration") vcfg = cfg["vault"] if vcfg["cls"] != "remote": raise EnvironmentError( - "This vault backend can only be a 'remote' " "configuration", err=True + "This vault backend can only be a 'remote' configuration" ) args = vcfg["args"] if "storage" not in args: args["storage"] = cfg.get("storage") if not args.get("storage"): - raise ValueError("invalid configuration; missing 'storage' config entry.") + raise ValueError("invalid configuration: missing 'storage' config entry.") storage = get_storage(**args.pop("storage")) backend = get_vault(**vcfg) diff --git a/swh/vault/cookers/base.py b/swh/vault/cookers/base.py --- a/swh/vault/cookers/base.py +++ b/swh/vault/cookers/base.py @@ -15,8 +15,6 @@ MAX_BUNDLE_SIZE = 2 ** 29 # 512 MiB DEFAULT_CONFIG_PATH = "vault/cooker" DEFAULT_CONFIG = { - "storage": ("dict", {"cls": "remote", "args": {"url": "http://localhost:5002/",},}), - "vault": ("dict", {"cls": "remote", "args": {"url": "http://localhost:5005/",},}), "max_bundle_size": ("int", MAX_BUNDLE_SIZE), } diff --git a/swh/vault/tests/test_init_cookers.py b/swh/vault/tests/test_init_cookers.py new file mode 100644 --- /dev/null +++ b/swh/vault/tests/test_init_cookers.py @@ -0,0 +1,109 @@ +# Copyright (C) 2017-2020 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import os +from typing import Dict + +import pytest +import yaml + +from swh.vault.cookers import COOKER_TYPES, get_cooker +from swh.vault.tests.test_backend import TEST_HEX_ID + + +@pytest.fixture +def swh_cooker_config(): + return { + "vault": { + "cls": "remote", + "args": { + "url": "mock://vault-backend", + "storage": {"cls": "remote", "url": "mock://storage-url"}, + }, + } + } + + +def write_config_to_env(config: Dict, tmp_path, monkeypatch) -> str: + """Write the configuration dict into a temporary file, then reference that path to + SWH_CONFIG_FILENAME environment variable. + + """ + conf_path = os.path.join(str(tmp_path), "cooker.yml") + with open(conf_path, "w") as f: + f.write(yaml.dump(config)) + monkeypatch.setenv("SWH_CONFIG_FILENAME", conf_path) + return conf_path + + +def test_write_to_env(swh_cooker_config, tmp_path, monkeypatch): + actual_path = write_config_to_env(swh_cooker_config, tmp_path, monkeypatch) + + assert os.path.exists(actual_path) is True + assert os.environ["SWH_CONFIG_FILENAME"] == actual_path + + with open(actual_path, "r") as f: + actual_config = yaml.safe_load(f.read()) + assert actual_config == swh_cooker_config + + +@pytest.mark.parametrize( + "config_ko,exception_class,exception_msg", + [ + ({}, ValueError, "missing 'vault' configuration"), + ( + {"vault": {"cls": "local"}}, + EnvironmentError, + "This vault backend can only be a 'remote' configuration", + ), + ( + {"vault": {"cls": "remote", "args": {"missing-storage-key": ""}}}, + ValueError, + "invalid configuration: missing 'storage' config entry", + ), + ({"vault": {"cls": "remote"}}, KeyError, "args",), + ], +) +def test_get_cooker_config_ko( + config_ko, exception_class, exception_msg, monkeypatch, tmp_path +): + """Misconfigured cooker should fail the instantiation with exception message + + """ + write_config_to_env(config_ko, tmp_path, monkeypatch) + + with pytest.raises(exception_class, match=exception_msg): + get_cooker("directory", TEST_HEX_ID) + + +@pytest.mark.parametrize( + "config_ok", + [ + { + "vault": { + "cls": "remote", + "args": { + "url": "mock://vault-backend", + "storage": {"cls": "remote", "url": "mock://storage-url"}, + }, + } + }, + { + "vault": {"cls": "remote", "args": {"url": "mock://vault-backend",},}, + "storage": {"cls": "remote", "url": "mock://storage-url"}, + }, + ], +) +def test_get_cooker_nominal(config_ok, tmp_path, monkeypatch): + """Correct configuration should allow the instantiation of the cookers + + """ + for cooker_type in COOKER_TYPES.keys(): + write_config_to_env(config_ok, tmp_path, monkeypatch) + + cooker = get_cooker(cooker_type, TEST_HEX_ID) + + assert cooker is not None + assert isinstance(cooker, COOKER_TYPES[cooker_type]) diff --git a/swh/vault/tests/test_server.py b/swh/vault/tests/test_server.py --- a/swh/vault/tests/test_server.py +++ b/swh/vault/tests/test_server.py @@ -3,10 +3,12 @@ # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information +import copy + import pytest from swh.core.api.serializers import msgpack_dumps, msgpack_loads -from swh.vault.api.server import make_app +from swh.vault.api.server import check_config, make_app @pytest.fixture @@ -53,3 +55,37 @@ content = msgpack_loads(await resp.content.read()) assert content["exception"]["type"] == "NotFoundExc" assert content["exception"]["args"] == ["Batch 1 does not exist."] + + +def test_check_config_missing_vault_configuration() -> None: + """Irrelevant configuration file path raises""" + with pytest.raises(ValueError, match="missing 'vault' configuration"): + check_config({}) + + +def test_check_config_not_local() -> None: + """Wrong configuration raises""" + expected_error = ( + "The vault backend can only be started with a 'local' configuration" + ) + with pytest.raises(EnvironmentError, match=expected_error): + check_config({"vault": {"cls": "remote"}}) + + +@pytest.mark.parametrize("missing_key", ["storage", "cache", "scheduler"]) +def test_check_config_missing_key(missing_key, swh_vault_config) -> None: + """Any other configuration than 'local' (the default) is rejected""" + config_ok = {"vault": {"cls": "local", "args": swh_vault_config}} + config_ko = copy.deepcopy(config_ok) + config_ko["vault"]["args"].pop(missing_key, None) + + expected_error = f"invalid configuration: missing {missing_key} config entry" + with pytest.raises(ValueError, match=expected_error): + check_config(config_ko) + + +@pytest.mark.parametrize("missing_key", ["storage", "cache", "scheduler"]) +def test_check_config_ok(missing_key, swh_vault_config) -> None: + """Any other configuration than 'local' (the default) is rejected""" + config_ok = {"vault": {"cls": "local", "args": swh_vault_config}} + assert check_config(config_ok) is not None