diff --git a/.github/workflows/end-to-end-test-oxigraph.yml b/.github/workflows/end-to-end-test-oxigraph.yml new file mode 100644 index 00000000..0cdf2665 --- /dev/null +++ b/.github/workflows/end-to-end-test-oxigraph.yml @@ -0,0 +1,81 @@ +name: End-to-end test for oxigraph + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + merge_group: + +permissions: + contents: read + +jobs: + oxigraph-end-to-end-test: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + system: [ native, docker, podman ] + + steps: + - name: Checkout the repository + uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Install the qeval script + dependencies needed for testing + run: | + python -m pip install --upgrade pip + pip install -e ".[plot]" + sudo apt-get update && sudo apt-get install -y unzip + + - name: Check that every command loads and shows its help + run: | + export QEVAL_ARGCOMPLETE_ENABLED=1 + commands=$(python -c "from qlever import load_commands; print(*load_commands('qeval.oxigraph'))") + for command in $commands; do + echo "Checking qeval oxigraph $command --help" + qeval oxigraph $command --help > /dev/null + done + + - name: Install the latest oxigraph release binary on PATH + if: matrix.system == 'native' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release download --repo oxigraph/oxigraph \ + --pattern '*x86_64_linux_gnu' -O oxigraph + chmod +x oxigraph + sudo mv oxigraph /usr/local/bin/oxigraph + oxigraph --version + + - name: Make sure the container runtime is available and pull the image + if: matrix.system != 'native' + run: | + command -v ${{matrix.system}} || (sudo apt-get update && sudo apt-get install -y ${{matrix.system}}) + ${{matrix.system}} --version + ${{matrix.system}} pull ghcr.io/oxigraph/oxigraph + + - name: End-to-end test on the olympics dataset (${{matrix.system}}) + run: | + export QEVAL_ARGCOMPLETE_ENABLED=1 + mkdir -p oxigraph-e2e && cd oxigraph-e2e + qeval oxigraph setup-config olympics --system ${{matrix.system}} + qeval oxigraph get-data + qeval oxigraph index + + echo "Checking that the resource-usage log and plot were produced" + test -s olympics.oxigraph.index.resource-usage-log.tsv + test -f olympics.oxigraph.resource-usage-plot.png + + qeval oxigraph index-stats + qeval oxigraph start + qeval oxigraph status + qeval oxigraph query + qeval oxigraph stop + ls -lh diff --git a/src/qeval/engines.py b/src/qeval/engines.py index 83e67a9b..c8248685 100644 --- a/src/qeval/engines.py +++ b/src/qeval/engines.py @@ -19,6 +19,11 @@ class Engine(NamedTuple): "qlever": Engine( package="qlever", display_name="QLever", endpoint_path="/" ), + "oxigraph": Engine( + package="qeval.oxigraph", + display_name="Oxigraph", + endpoint_path="/query", + ), } diff --git a/src/qeval/oxigraph/__init__.py b/src/qeval/oxigraph/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/qeval/oxigraph/commands/__init__.py b/src/qeval/oxigraph/commands/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/qeval/oxigraph/commands/benchmark_queries.py b/src/qeval/oxigraph/commands/benchmark_queries.py new file mode 100644 index 00000000..217bd8fd --- /dev/null +++ b/src/qeval/oxigraph/commands/benchmark_queries.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from qeval.base_commands.benchmark_queries import BaseBenchmarkQueriesCommand +from qeval.oxigraph.commands.index_stats import IndexStatsCommand + + +class BenchmarkQueriesCommand(BaseBenchmarkQueriesCommand): + """Run benchmark queries against the Oxigraph SPARQL endpoint.""" + + def index_stats_command(self) -> IndexStatsCommand: + return IndexStatsCommand() diff --git a/src/qeval/oxigraph/commands/get_data.py b/src/qeval/oxigraph/commands/get_data.py new file mode 100644 index 00000000..29bba0e2 --- /dev/null +++ b/src/qeval/oxigraph/commands/get_data.py @@ -0,0 +1 @@ +from qlever.commands.get_data import GetDataCommand # noqa diff --git a/src/qeval/oxigraph/commands/index.py b/src/qeval/oxigraph/commands/index.py new file mode 100644 index 00000000..85ed3201 --- /dev/null +++ b/src/qeval/oxigraph/commands/index.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import shlex +import time +from pathlib import Path + +from qeval.oxigraph.usage_plot import overlay, subtitle +from qeval.resource_monitor import ResourceMonitor +from qlever.command import QleverCommand +from qlever.containerize import Containerize +from qlever.log import log +from qlever.resource_usage.plot_util import render_usage_plot_if_installed +from qlever.util import ( + binary_exists, + get_total_file_size, + input_files_exist, + run_command, +) + + +def wrap_cmd_in_container(args, cmd: str, ulimit: int | None = None) -> str: + """ + Wrap an indexing command in a container that is automatically removed + after the process exits (`--rm`). Use `use_bash=False` as Oxigraph image + doesn't support bash entrypoint. + """ + run_subcommand = "run --rm" + if ulimit: + run_subcommand += f" --ulimit nofile={ulimit}:{ulimit}" + return Containerize().containerize_command( + cmd=cmd, + container_system=args.system, + run_subcommand=run_subcommand, + image_name=args.image, + container_name=args.index_container, + volumes=[("$(pwd)", "/opt")], + working_directory="/opt", + use_bash=False, + ) + + +class IndexCommand(QleverCommand): + """ + Build an Oxigraph index for an RDF dataset. The indexing workflow is: + 1. Run `oxigraph load` to import input files into a RocksDB store. + 2. Optionally run `oxigraph optimize` to compact storage for read-only use. + + For large datasets (>5 GB), the file descriptor ulimit is raised + automatically because RocksDB opens many .sst files concurrently. + """ + + def __init__(self): + pass + + def description(self) -> str: + return "Build the index for a given RDF dataset" + + def should_have_qleverfile(self) -> bool: + return True + + def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: + return { + "data": ["name"], + "index": [ + "input_files", + "ulimit", + "index_binary", + "lenient", + "extra_args", + "resource_usage_interval", + "resource_usage_plot_max_points", + ], + "server": ["read_only"], + "runtime": ["system", "image", "index_container"], + } + + def additional_arguments(self, subparser) -> None: + subparser.add_argument( + "--resource-usage-plot-only", + action="store_true", + default=False, + help="Only render the resource-usage plot from the existing " + "`.oxigraph.index.resource-usage-log.tsv`; do not build " + "the index. Use to re-render with a different " + "`--resource-usage-plot-max-points`", + ) + + def execute(self, args) -> bool: + # Render the resource-usage plot from the existing log without + # rebuilding the index. + if args.resource_usage_plot_only: + plot_path = render_usage_plot_if_installed( + args, + plot_only=True, + engine_overlay=overlay, + engine_subtitle=subtitle, + ) + return plot_path is not None + + cmds_to_execute = [] + log_file_name = f"{args.name}.index-log.txt" + index_cmd = ( + f"load {'--lenient ' if args.lenient == 'yes' else ''}" + f"--location {args.name}_index/ --file {args.input_files} " + f"{args.extra_args} |& tee {log_file_name}" + ) + + ulimit = args.ulimit + # RocksDB opens many .sst files concurrently. For datasets larger + # than 5 GB, raise the file descriptor limit so the process does + # not hit the default OS soft limit. + total_file_size = get_total_file_size(shlex.split(args.input_files)) + if not ulimit and total_file_size > 5e9: + ulimit = 500_000 + if args.system in Containerize.supported_systems(): + index_cmd = wrap_cmd_in_container(args, index_cmd, ulimit) + else: + index_cmd = f"{args.index_binary} {index_cmd}" + if ulimit: + index_cmd = f"ulimit -Sn {ulimit} && {index_cmd}" + + cmds_to_execute.append(index_cmd) + + # Compact the RocksDB storage for read-only serving. This reduces + # disk usage and speeds up queries but makes the index immutable. + optimize_cmd = None + if args.read_only == "yes": + optimize_cmd = f"optimize -l {args.name}_index/" + if args.system in Containerize.supported_systems(): + optimize_cmd = wrap_cmd_in_container(args, optimize_cmd) + else: + optimize_cmd = f"{args.index_binary} {optimize_cmd}" + cmds_to_execute.append(optimize_cmd) + + # Show the command line. + self.show("\n".join(cmds_to_execute), only_show=args.show) + if args.show: + return True + + if not input_files_exist(args.input_files, args.main_command_name): + return False + + # When running natively, check if the binary exists and works. + if args.system in Containerize.supported_systems(): + if Containerize().is_running(args.system, args.index_container): + log.info( + f"{args.system} container {args.index_container} is " + "still up, which means that data loading is in progress. " + "Please wait..." + ) + return False + else: + if not binary_exists(args.index_binary, "index-binary", args): + return False + + # Abort if a previous index already exists. RocksDB .sst files in + # the index directory indicate an existing store. + if any(Path(f"{args.name}_index").glob("*.sst")): + log.error( + f"Index files (*.sst) found in {args.name}_index directory " + "which shows presence of a previous index" + ) + log.info("") + log.info("Aborting the index operation...") + return False + + # Run the index command and record the elapsed time in the log + # file. Oxigraph's progress output is unreliable (may not print a + # final summary line when loading multiple files), so we measure + # the time externally. + with ResourceMonitor.from_args(args): + try: + load_start = time.time() + run_command(index_cmd, show_output=True, show_stderr=True) + load_s = time.time() - load_start + except Exception as e: + log.error(f"Building the index failed: {e}") + return False + + # Stays None if the optimize step is skipped or fails, so that the + # log only has the times of steps that completed. + optimize_s = None + if optimize_cmd: + try: + log.info("") + log.info("Optimizing read-only database storage:") + self.show(optimize_cmd) + optimize_start = time.time() + run_command( + optimize_cmd, show_output=True, show_stderr=True + ) + optimize_s = time.time() - optimize_start + except Exception as e: + log.error(f"Optimizing the database storage failed: {e}") + log.info( + f"Please run manually: " + f"{args.index_binary} optimize -l {args.name}_index/" + ) + + total_s = load_s + with open(log_file_name, "a") as f: + f.write(f"Load time: {load_s:.0f}s\n") + if optimize_s is not None: + f.write(f"Optimize time: {optimize_s:.0f}s\n") + total_s += optimize_s + f.write(f"TOTAL time: {total_s:.0f}s\n") + + render_usage_plot_if_installed( + args, + plot_only=False, + engine_overlay=overlay, + engine_subtitle=subtitle, + ) + + return True diff --git a/src/qeval/oxigraph/commands/index_stats.py b/src/qeval/oxigraph/commands/index_stats.py new file mode 100644 index 00000000..cffe08b3 --- /dev/null +++ b/src/qeval/oxigraph/commands/index_stats.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import re + +from qeval.base_commands.index_stats import BaseIndexStatsCommand + + +class IndexStatsCommand(BaseIndexStatsCommand): + """ + Show how long the Oxigraph index build took and how much space the + index uses. + """ + + def index_size_patterns(self, args) -> list[str]: + return [f"{args.name}_index/*.sst"] + + def parse_index_durations(self, log_text: str) -> dict[str, float]: + """ + The times that `index` writes at the end of the log. A build with + no optimize step reports only its total, because then loading is + the whole build rather than one phase of it. + """ + durations = {} + for label in ("Load time", "Optimize time", "TOTAL time"): + match = re.search(rf"{re.escape(label)}:\s*(\d+)s", log_text) + if match: + durations[label] = float(match.group(1)) + if "Optimize time" not in durations: + durations.pop("Load time", None) + return durations diff --git a/src/qeval/oxigraph/commands/log.py b/src/qeval/oxigraph/commands/log.py new file mode 100644 index 00000000..b2d35bd0 --- /dev/null +++ b/src/qeval/oxigraph/commands/log.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from qlever.commands.log import LogCommand as QleverLogCommand +from qlever.containerize import Containerize +from qlever.log import log +from qlever.util import run_command + + +class LogCommand(QleverLogCommand): + """ + Show server logs for Oxigraph. For native execution, tails the log + file as usual. For containers, uses `docker/podman logs` as it is + not possible to redirect oxigraph logs to a log file. + """ + + def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: + return { + "data": ["name"], + "runtime": [ + "system", + "image", + "server_container", + ], + } + + def execute(self, args) -> bool: + if args.system not in Containerize.supported_systems(): + return super().execute(args) + + # A container has no `.server-log.txt`, so show its logs with + # `docker/podman logs` instead of `tail`. + log_cmd = f"{args.system} logs " + + if not args.from_beginning: + log_cmd += f"-n {args.tail_num_lines} " + if not args.no_follow: + log_cmd += "-f " + + log_cmd += args.server_container + + # Show the command line. + self.show(log_cmd, only_show=args.show) + if args.show: + return True + + if not Containerize().is_running(args.system, args.server_container): + log.error(f"No server container {args.server_container} found!\n") + log.info( + f"Are you sure you called `{args.main_command_name} start`?" + ) + return False + + try: + run_command(log_cmd, show_output=True, show_stderr=True) + except Exception as e: + log.error(f"Cannot display container logs - {e}") + return True diff --git a/src/qeval/oxigraph/commands/query.py b/src/qeval/oxigraph/commands/query.py new file mode 100644 index 00000000..392a68f4 --- /dev/null +++ b/src/qeval/oxigraph/commands/query.py @@ -0,0 +1 @@ +from qeval.base_commands.query import BaseQueryCommand as QueryCommand # noqa diff --git a/src/qeval/oxigraph/commands/setup_config.py b/src/qeval/oxigraph/commands/setup_config.py new file mode 100644 index 00000000..896b2489 --- /dev/null +++ b/src/qeval/oxigraph/commands/setup_config.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from qeval.base_commands.setup_config import BaseSetupConfigCommand + + +class SetupConfigCommand(BaseSetupConfigCommand): + """Create a Qleverfile for Oxigraph.""" + + def image(self) -> str: + return "ghcr.io/oxigraph/oxigraph" + + def engine_settings(self, args) -> dict[str, dict[str, str]]: + return {"server": {"READ_ONLY": "yes", "TIMEOUT": "60s"}} diff --git a/src/qeval/oxigraph/commands/start.py b/src/qeval/oxigraph/commands/start.py new file mode 100644 index 00000000..cbe26a80 --- /dev/null +++ b/src/qeval/oxigraph/commands/start.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import contextlib +import subprocess +import time +from pathlib import Path + +from qlever.command import QleverCommand +from qlever.commands.start import ( + make_server_liveness_check, + show_log_follow_info, + wait_for_foreground_server, + wait_until_server_ready, +) +from qlever.commands.stop import stop_container +from qlever.containerize import Containerize +from qlever.log import log +from qlever.util import ( + binary_exists, + is_server_alive, + run_command, + stop_tailing, + tail_log_file, + timeout_seconds, +) + + +def wrap_cmd_in_container(args, cmd: str) -> str: + """Wrap the server start command in a container with restart policy.""" + run_subcommand = "run --restart=unless-stopped" + if not args.run_in_foreground: + run_subcommand += " -d" + return Containerize().containerize_command( + cmd=cmd, + container_system=args.system, + run_subcommand=run_subcommand, + image_name=args.image, + container_name=args.server_container, + volumes=[("$(pwd)", "/opt")], + ports=[(args.port, args.port)], + working_directory="/opt", + use_bash=False, + ) + + +class StartCommand(QleverCommand): + """ + Start the Oxigraph SPARQL server for an already-indexed dataset. + Supports both native and containerized execution, with an option + to run in the foreground. Uses `serve-read-only` or `serve` + depending on the read_only setting. + """ + + def __init__(self): + pass + + def description(self) -> str: + return ( + "Start the server for Oxigraph (requires that you have built an " + "index before)" + ) + + def should_have_qleverfile(self) -> bool: + return True + + def relevant_qleverfile_arguments(self) -> dict[str, list[str]]: + return { + "data": ["name"], + "server": [ + "host_name", + "port", + "read_only", + "server_binary", + "timeout", + "extra_args", + ], + "runtime": ["system", "image", "server_container"], + } + + def additional_arguments(self, subparser): + subparser.add_argument( + "--run-in-foreground", + action="store_true", + default=False, + help=( + "Run the start command in the foreground " + "(default: run in the background)" + ), + ) + + def execute(self, args) -> bool: + is_containerized = args.system in Containerize.supported_systems() + # Inside a container, bind to 0.0.0.0 so the port mapping is + # reachable from the host; natively, bind to the configured host. + bind = ( + f"0.0.0.0:{args.port}" + if is_containerized + else f"{args.host_name}:{args.port}" + ) + serve_subcommand = ( + "serve-read-only" if args.read_only == "yes" else "serve" + ) + start_cmd = ( + f"{serve_subcommand} --location {args.name}_index/ " + f"{args.extra_args} --timeout-s {timeout_seconds(args.timeout)} " + f"--bind={bind}" + ) + + if is_containerized: + start_cmd = wrap_cmd_in_container(args, start_cmd) + else: + start_cmd = ( + f"{args.server_binary} {start_cmd} " + f"> {args.name}.server-log.txt 2>&1" + ) + if not args.run_in_foreground: + # The `echo $!` reports the PID of the server process, which + # the liveness check uses to detect a server that exits + # before it becomes ready. + start_cmd = f"nohup {start_cmd} & echo $!" + + # Show the command line. + self.show(start_cmd, only_show=args.show) + if args.show: + return True + + endpoint_url = ( + f"http://{args.host_name}:{args.port}{args.endpoint_path}" + ) + + # When running natively, check if the binary exists and works. + if not is_containerized: + if not binary_exists(args.server_binary, "server-binary", args): + return False + + # Check if index files (*.sst) present in index directory + if not any(Path(f"{args.name}_index").glob("*.sst")): + log.error(f"No Oxigraph index files for {args.name} found!\n") + log.info( + f"Did you call `{args.main_command_name} index`? If you did, " + "check if .sst index files are present in index directory." + ) + return False + + # Check if server already alive at endpoint url from a previous run + if is_server_alive(url=endpoint_url): + log.error(f"Oxigraph server already running on {endpoint_url}\n") + log.info( + "To kill the existing server, use " + f"`{args.main_command_name} stop`" + ) + return False + + # Remove old log file so that tail starts clean. + log_file = Path(f"{args.name}.server-log.txt") + log_file.unlink(missing_ok=True) + + # Keep what the liveness check needs: the process handle or the PID. + process = None + pid = None + try: + if args.run_in_foreground: + process = run_command(start_cmd, use_popen=True) + elif is_containerized: + run_command(start_cmd) + else: + output = run_command(start_cmd, return_output=True) + with contextlib.suppress(ValueError): + pid = int(output.strip()) + except Exception as error: + log.error(f"Starting the Oxigraph server failed ({error})") + return False + + # Follow the server log until the server is ready. For containers, + # use `docker/podman logs -f` as Oxigraph doesn't support + # redirecting its log to a file. + if is_containerized: + log_name = f"the logs of container {args.server_container}" + else: + log_name = str(log_file) + show_log_follow_info(log_name, args.run_in_foreground) + if is_containerized: + # A short delay ensures the container is up before attaching. + # In a session of its own, like `tail_log_file`, so that + # `stop_tailing` can stop it. + time.sleep(2) + log_cmd = f"{args.system} logs -f {args.server_container}" + log_proc = subprocess.Popen( + log_cmd, shell=True, start_new_session=True + ) + else: + log_proc = tail_log_file(log_file) + if log_proc is None: + return False + try: + server_ready = wait_until_server_ready( + lambda: is_server_alive(url=endpoint_url), + make_server_liveness_check(args, process, pid), + ) + except KeyboardInterrupt: + # The log follower runs in a session of its own, so the Ctrl-C + # does not reach it. + stop_tailing(log_proc) + raise + if not server_ready: + stop_tailing(log_proc) + return False + + log.info( + f"Oxigraph server webapp for {args.name} will be available at " + f"http://{args.host_name}:{args.port} and the sparql endpoint for " + f"queries is {endpoint_url} when the server is ready" + ) + + # Stop following the log. + if not args.run_in_foreground: + stop_tailing(log_proc) + + # With `--run-in-foreground`, wait until the server is stopped. + # On Ctrl-C, terminate the process and clean up the container. + if args.run_in_foreground: + + def remove_container() -> None: + if is_containerized: + if stop_container(args.server_container): + return + log.warning( + "No container with name " + f'"{args.server_container}" found' + ) + + wait_for_foreground_server(process, log_proc, remove_container) + + return True diff --git a/src/qeval/oxigraph/commands/status.py b/src/qeval/oxigraph/commands/status.py new file mode 100644 index 00000000..2c34fcfc --- /dev/null +++ b/src/qeval/oxigraph/commands/status.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from qeval.base_commands.status import BaseStatusCommand + + +class StatusCommand(BaseStatusCommand): + """Show Oxigraph processes running on this machine.""" + + def default_regex(self) -> str: + # `serve` also matches `serve-read-only`. + # `load` and `optimize` are the index-time processes. + # Anchored, so that the shell that started a process does not match. + return r"^(\S*/)?oxigraph\s+(serve|load|optimize)" diff --git a/src/qeval/oxigraph/commands/stop.py b/src/qeval/oxigraph/commands/stop.py new file mode 100644 index 00000000..00218520 --- /dev/null +++ b/src/qeval/oxigraph/commands/stop.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from qeval.base_commands.stop import BaseStopCommand +from qeval.oxigraph.commands.status import StatusCommand + + +class StopCommand(BaseStopCommand): + """Stop the Oxigraph server for a given dataset.""" + + def default_regex(self) -> str: + return r"^(\S*/)?oxigraph\s+serve.*%%NAME%%_index" + + def status_command(self) -> StatusCommand: + return StatusCommand() + + def status_regex(self) -> str: + # `serve` also matches `serve-read-only`. + return r"^(\S*/)?oxigraph\s+serve" diff --git a/src/qeval/oxigraph/qleverfile.py b/src/qeval/oxigraph/qleverfile.py new file mode 100644 index 00000000..7dd6e4d2 --- /dev/null +++ b/src/qeval/oxigraph/qleverfile.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from qlever.util import parse_timeout + + +def qleverfile_args(all_args: dict[str, dict[str, tuple]]) -> None: + """Define additional oxigraph specific Qleverfile parameters""" + + def arg(*args, **kwargs): + return args, kwargs + + index_args = all_args["index"] + server_args = all_args["server"] + + index_args["index_binary"] = arg( + "--index-binary", + type=str, + default="oxigraph", + help=( + "The binary for building the index (default: oxigraph) " + "(this requires that you have oxigraph-cli installed " + "on your machine)" + ), + ) + index_args["lenient"] = arg( + "--lenient", + type=str, + choices=["yes", "no"], + default="no", + help="Attempt to keep loading even if the data file is invalid", + ) + index_args["extra_args"] = arg( + "--extra-args", + type=str, + default="", + help=( + "Additional arguments to pass directly to the oxigraph load " + "process. This allows advanced users to specify options not " + "exposed in Qleverfile. The string is appended verbatim to " + "the command." + ), + ) + + server_args["server_binary"] = arg( + "--server-binary", + type=str, + default="oxigraph", + help=( + "The binary for starting the server (default: oxigraph) " + "(this requires that you have oxigraph-cli installed " + "on your machine)" + ), + ) + server_args["read_only"] = arg( + "--read-only", + type=str, + choices=["yes", "no"], + default="yes", + help=( + "The HTTP server will not permit mutation operations in " + "read-only mode" + ), + ) + server_args["timeout"] = arg( + "--timeout", + type=parse_timeout, + default="60s", + help=( + "The maximal time a query is allowed to run, for example " + "`60s` or `5min`" + ), + ) + server_args["extra_args"] = arg( + "--extra-args", + type=str, + default="", + help=( + "Additional arguments to pass directly to the oxigraph " + "serve/serve-read-only. This allows advanced users to specify " + "options not exposed in Qleverfile. The string is appended " + "verbatim to the command." + ), + ) diff --git a/src/qeval/oxigraph/usage_plot.py b/src/qeval/oxigraph/usage_plot.py new file mode 100644 index 00000000..126cef2b --- /dev/null +++ b/src/qeval/oxigraph/usage_plot.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import re +from pathlib import Path + +from qeval.oxigraph.commands.index_stats import IndexStatsCommand +from qlever.containerize import Containerize +from qlever.resource_usage.plot_util import ( + SUBTITLE_SEPARATOR, + BandType, + bands_from_durations, +) +from qlever.util import run_command + + +def overlay(args, log_path: Path) -> list[BandType]: + """ + Shade the load and optimize phases of an Oxigraph index build. The + log has no timestamps, so the phases are assumed to run back to back + from the build start. + """ + return bands_from_durations(IndexStatsCommand().index_durations(log_path)) + + +def subtitle(args, log_path: Path) -> str | None: + """Assemble a 'version | read-only' line from the index args.""" + if args.system in Containerize.supported_systems(): + version_cmd = f"{args.system} run --rm {args.image} --version" + else: + version_cmd = f"{args.index_binary} --version" + try: + version_output = run_command(version_cmd, return_output=True) + except Exception: + version_output = "" + version_match = re.search(r"\d+(?:\.\d+)+", version_output) + parts = [] + if version_match: + parts.append(f"{args.index_binary} v{version_match.group()}") + parts.append(f"read-only = {args.read_only}") + return SUBTITLE_SEPARATOR.join(parts) diff --git a/test/qeval/base_commands/conftest.py b/test/qeval/base_commands/conftest.py index 1d7afb9f..4b21c535 100644 --- a/test/qeval/base_commands/conftest.py +++ b/test/qeval/base_commands/conftest.py @@ -1,10 +1,6 @@ -import argparse - import pytest from qeval.base_commands.index_stats import BaseIndexStatsCommand -from qlever.config import add_subparser_for_command -from qlever.qleverfile import Qleverfile class FakeIndexStatsCommand(BaseIndexStatsCommand): @@ -24,28 +20,3 @@ def fake_index_stats(): `.fake-index.*`. """ return FakeIndexStatsCommand() - - -@pytest.fixture -def parse_args(): - """Parse a command line with the real parser of a command.""" - - def parse(command, argv): - parser = argparse.ArgumentParser() - parser.set_defaults( - script_name="qeval", - engine_short_name="fake", - engine_display_name="Fake", - endpoint_path="/sparql", - main_command_name="qeval fake", - ) - subparsers = parser.add_subparsers() - add_subparser_for_command( - subparsers, - "cmd", - command, - Qleverfile.all_arguments("qeval fake"), - ) - return parser.parse_args(["cmd", *argv]) - - return parse diff --git a/test/qeval/conftest.py b/test/qeval/conftest.py new file mode 100644 index 00000000..634fe1c0 --- /dev/null +++ b/test/qeval/conftest.py @@ -0,0 +1,44 @@ +import argparse + +import pytest + +from qeval.engines import ENGINES, add_engine_qleverfile_args +from qlever.config import add_subparser_for_command +from qlever.qleverfile import Qleverfile + + +@pytest.fixture +def parse_args(): + """ + Parse a command line with the real parser of a command. Without an + `engine`, the command belongs to a fake engine that has only the shared + Qleverfile arguments. + """ + + def parse(command, argv, engine=None): + if engine is None: + engine_short_name = "fake" + engine_display_name = "Fake" + endpoint_path = "/sparql" + else: + engine_short_name = engine + engine_display_name = ENGINES[engine].display_name + endpoint_path = ENGINES[engine].endpoint_path + main_command_name = f"qeval {engine_short_name}" + all_args = Qleverfile.all_arguments(main_command_name) + if engine is not None: + add_engine_qleverfile_args(engine, all_args) + + parser = argparse.ArgumentParser() + parser.set_defaults( + script_name="qeval", + engine_short_name=engine_short_name, + engine_display_name=engine_display_name, + endpoint_path=endpoint_path, + main_command_name=main_command_name, + ) + subparsers = parser.add_subparsers() + add_subparser_for_command(subparsers, "cmd", command, all_args) + return parser.parse_args(["cmd", *argv]) + + return parse diff --git a/test/qeval/oxigraph/test_oxigraph_index.py b/test/qeval/oxigraph/test_oxigraph_index.py new file mode 100644 index 00000000..47456426 --- /dev/null +++ b/test/qeval/oxigraph/test_oxigraph_index.py @@ -0,0 +1,106 @@ +import pytest + +from qeval.oxigraph.commands.index import IndexCommand +from qeval.oxigraph.commands.index_stats import IndexStatsCommand + + +# Every test runs in an empty folder with a small dataset, and nothing that +# `index` would start really runs, so that `index` only decides what to do. +@pytest.fixture(autouse=True) +def dataset_folder(mock_command, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.nt").write_text(" .\n") + module = "qeval.oxigraph.commands.index" + mock_command(module, "binary_exists").return_value = True + mock_command(module, "ResourceMonitor") + mock_command(module, "render_usage_plot_if_installed") + + +@pytest.fixture(autouse=True) +def run_command(mock_command): + return mock_command("qeval.oxigraph.commands.index", "run_command") + + +@pytest.fixture +def run_index(parse_args): + """Run `index` with the real parser and return its result.""" + + def run(*argv): + command = IndexCommand() + args = parse_args( + command, + [ + "--name", + "olympics", + "--input-files", + "olympics.nt", + "--system", + "native", + *argv, + ], + engine="oxigraph", + ) + return command.execute(args) + + return run + + +def shown_phases(): + """The phases that `index-stats` shows for the index log.""" + durations = IndexStatsCommand().index_durations("olympics.index-log.txt") + return list(durations) + + +def test_oxigraph_index_loads_and_optimizes(run_command, run_index): + assert run_index() + + assert run_command.call_count == 2 + assert shown_phases() == ["Load time", "Optimize time", "TOTAL time"] + + +def test_oxigraph_index_skips_optimize_when_not_read_only( + run_command, run_index +): + assert run_index("--read-only", "no") + + assert run_command.call_count == 1 + assert shown_phases() == ["TOTAL time"] + + +def test_oxigraph_index_succeeds_when_optimize_fails(run_command, run_index): + run_command.side_effect = [None, Exception("optimize failed")] + + assert run_index() + + assert shown_phases() == ["TOTAL time"] + + +def test_oxigraph_index_fails_when_load_fails(run_command, run_index): + run_command.side_effect = Exception("load failed") + + assert not run_index() + + assert shown_phases() == [] + + +def test_oxigraph_index_refuses_to_overwrite_index( + run_command, run_index, tmp_path +): + (tmp_path / "olympics_index").mkdir() + (tmp_path / "olympics_index" / "000001.sst").write_bytes(b"x") + + assert not run_index() + + run_command.assert_not_called() + + +def test_oxigraph_index_waits_for_running_index_container( + run_command, run_index, mock_command +): + mock_command( + "qlever.containerize.Containerize", "is_running" + ).return_value = True + + assert not run_index("--system", "docker") + + run_command.assert_not_called() diff --git a/test/qeval/oxigraph/test_oxigraph_index_stats.py b/test/qeval/oxigraph/test_oxigraph_index_stats.py new file mode 100644 index 00000000..fdf68feb --- /dev/null +++ b/test/qeval/oxigraph/test_oxigraph_index_stats.py @@ -0,0 +1,57 @@ +import pytest + +from qeval.oxigraph.commands.index_stats import IndexStatsCommand +from qlever.commands.benchmark_queries import compute_index_stats + +# Oxigraph's own output, which comes before the times that `index` appends to +# the log. It also has seconds in it, which must not be taken for a phase. +PROGRESS = "1000 triples loaded in 1s (1000 triples/s)\n" + +# The times that `index` appends after a build with an optimize step. +LOAD_AND_OPTIMIZE_TIMES = ( + "Load time: 100s\nOptimize time: 20s\nTOTAL time: 120s\n" +) + +# The times that `index` appends without an optimize step, or when it failed. +LOAD_ONLY_TIMES = "Load time: 100s\nTOTAL time: 100s\n" + + +@pytest.mark.parametrize( + "times,expected", + [ + ( + LOAD_AND_OPTIMIZE_TIMES, + [ + ("Load time", 100.0), + ("Optimize time", 20.0), + ("TOTAL time", 120.0), + ], + ), + # Loading is the whole build, so only the total is shown. + (LOAD_ONLY_TIMES, [("TOTAL time", 100.0)]), + # The build did not finish. + ("", []), + ], + ids=["load and optimize", "load only", "unfinished"], +) +def test_oxigraph_index_stats_parses_times_from_log(times, expected): + durations = IndexStatsCommand().parse_index_durations(PROGRESS + times) + + assert list(durations.items()) == expected + + +def test_oxigraph_index_stats_gives_benchmark_total_time_and_size( + tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics.index-log.txt").write_text( + PROGRESS + LOAD_AND_OPTIMIZE_TIMES + ) + index_dir = tmp_path / "olympics_index" + index_dir.mkdir() + (index_dir / "000001.sst").write_bytes(b"x" * 1000) + (index_dir / "000002.sst").write_bytes(b"x" * 500) + # A small RocksDB file next to the `.sst` files, which does not count. + (index_dir / "CURRENT").write_bytes(b"x" * 16) + + assert compute_index_stats(IndexStatsCommand()) == (120.0, 1500) diff --git a/test/qeval/oxigraph/test_oxigraph_start.py b/test/qeval/oxigraph/test_oxigraph_start.py new file mode 100644 index 00000000..0ea6135e --- /dev/null +++ b/test/qeval/oxigraph/test_oxigraph_start.py @@ -0,0 +1,139 @@ +from types import SimpleNamespace + +import pytest + +from qeval.oxigraph.commands.start import StartCommand + +MODULE = "qeval.oxigraph.commands.start" + + +# Every test runs in an empty folder that holds an Oxigraph index. +@pytest.fixture(autouse=True) +def index_folder(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + (tmp_path / "olympics_index").mkdir() + (tmp_path / "olympics_index" / "000001.sst").write_bytes(b"x") + + +# Nothing that `start` would start or check really runs, so that `start` +# only decides what to do. By default, no server answers before the start, +# the started server becomes ready, and Ctrl-C is pressed at once when the +# server runs in the foreground. +@pytest.fixture(autouse=True) +def mocks(mock_command): + run_command = mock_command(MODULE, "run_command") + # The PID of the server that `nohup` started. + run_command.return_value = "4711\n" + mock_command(MODULE, "binary_exists").return_value = True + is_server_alive = mock_command(MODULE, "is_server_alive") + is_server_alive.return_value = False + wait_until_server_ready = mock_command(MODULE, "wait_until_server_ready") + wait_until_server_ready.return_value = True + mock_command( + MODULE, + "wait_for_foreground_server", + lambda process, log_proc, on_interrupt: on_interrupt(), + ) + # In a container, the log is followed with `docker logs -f` after a wait. + mock_command(f"{MODULE}.subprocess", "Popen") + mock_command(f"{MODULE}.time", "sleep") + return SimpleNamespace( + run_command=run_command, + is_server_alive=is_server_alive, + wait_until_server_ready=wait_until_server_ready, + tail_log_file=mock_command(MODULE, "tail_log_file"), + stop_tailing=mock_command(MODULE, "stop_tailing"), + stop_container=mock_command(MODULE, "stop_container"), + ) + + +@pytest.fixture +def run_start(parse_args): + """Run `start` with the real parser and return its result.""" + + def run(*argv): + command = StartCommand() + args = parse_args( + command, + [ + "--name", + "olympics", + "--host-name", + "localhost", + "--port", + "7878", + "--server-container", + "olympics.oxigraph", + "--system", + "native", + *argv, + ], + engine="oxigraph", + ) + return command.execute(args) + + return run + + +def test_oxigraph_start_starts_server(mocks, run_start): + assert run_start() + + mocks.run_command.assert_called_once() + mocks.stop_tailing.assert_called_once_with( + mocks.tail_log_file.return_value + ) + + +def test_oxigraph_start_needs_index(mocks, run_start, tmp_path): + (tmp_path / "olympics_index" / "000001.sst").unlink() + + assert not run_start() + + mocks.run_command.assert_not_called() + + +def test_oxigraph_start_refuses_when_server_answers(mocks, run_start): + mocks.is_server_alive.return_value = True + + assert not run_start() + + mocks.run_command.assert_not_called() + + +def test_oxigraph_start_stops_following_log_when_server_not_ready( + mocks, run_start +): + mocks.wait_until_server_ready.return_value = False + + assert not run_start() + + mocks.stop_tailing.assert_called_once_with( + mocks.tail_log_file.return_value + ) + + +@pytest.mark.parametrize( + "system,container_found,removes_container,warns", + [ + ("docker", True, True, False), + ("docker", False, True, True), + # A native server is already stopped by Ctrl-C itself. + ("native", False, False, False), + ], + ids=["container found", "container gone", "native"], +) +def test_oxigraph_start_cleans_up_after_ctrl_c( + mocks, run_start, caplog, system, container_found, removes_container, warns +): + mocks.stop_container.return_value = container_found + + assert run_start("--run-in-foreground", "--system", system) + + assert mocks.stop_container.called == removes_container + if removes_container: + mocks.stop_container.assert_called_once_with("olympics.oxigraph") + warned = any( + record.levelname == "WARNING" and "olympics.oxigraph" in record.message + for record in caplog.records + ) + assert warned == warns diff --git a/test/qeval/oxigraph/test_oxigraph_usage_plot.py b/test/qeval/oxigraph/test_oxigraph_usage_plot.py new file mode 100644 index 00000000..92dd8571 --- /dev/null +++ b/test/qeval/oxigraph/test_oxigraph_usage_plot.py @@ -0,0 +1,39 @@ +import pytest + +from qeval.oxigraph.commands.index import IndexCommand +from qeval.oxigraph.usage_plot import subtitle +from qlever.resource_usage.plot_util import SUBTITLE_SEPARATOR + + +@pytest.mark.parametrize( + "version_output,expected", + [ + ( + "oxigraph 0.4.9\n", + f"oxigraph v0.4.9{SUBTITLE_SEPARATOR}read-only = yes", + ), + ("oxigraph dev build\n", "read-only = yes"), + (Exception("oxigraph not found"), "read-only = yes"), + ], + ids=["version", "no version number", "version command fails"], +) +def test_oxigraph_usage_plot_subtitle( + parse_args, mock_command, tmp_path, version_output, expected +): + run_command = mock_command("qeval.oxigraph.usage_plot", "run_command") + run_command.side_effect = [version_output] + # `index` draws the plot, so the subtitle gets the arguments of `index`. + args = parse_args( + IndexCommand(), + [ + "--name", + "olympics", + "--input-files", + "olympics.nt", + "--system", + "native", + ], + engine="oxigraph", + ) + + assert subtitle(args, tmp_path / "olympics.index-log.txt") == expected