You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@solr.apache.org by ja...@apache.org on 2026/05/22 00:53:29 UTC
(solr-orbit) 06/06: Port core benchmark framework from OpenSearch to Apache Solr
This is an automated email from the ASF dual-hosted git repository.
janhoy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/solr-orbit.git
commit 57387ed4130f0395e14ea89213c6b8a96f9ee260
Author: Jan Høydahl <ja...@cominvent.com>
AuthorDate: Fri May 22 01:12:17 2026 +0200
Port core benchmark framework from OpenSearch to Apache Solr
This is the main functional change of the Solr port, touching all layers of the
benchmark tool. This commit wires the previous five together.
**setup.py / entry points:**
- Remove opensearch-py, opensearch-protobufs, aiokafka dependencies
- Add requests for Solr HTTP communication
- Rename entry points: opensearch-benchmark→solr-benchmark, osb→sb (pending ASF acceptance)
**osbenchmark/client.py — complete rewrite:**
Replace the opensearch-py async client with a synchronous requests-based Solr
HTTP client. Supports collection management, document indexing, and query
execution against a Solr cluster.
**osbenchmark/telemetry.py:**
Replace OpenSearch-specific telemetry devices (JVM heap, GC, hot threads, etc.)
with Solr equivalents using the Solr Metrics API and node stats endpoints.
**osbenchmark/worker_coordinator/runner.py:**
Adapt operation runners for Solr: bulk indexing via /update, queries via /select,
collection admin operations. Remove OpenSearch-specific operations (snapshot,
shrink, force-merge semantics, etc.).
**osbenchmark/builder/ — OSB→Solr naming cleanup:**
- Rename opensearch_distribution_downloader.py → distribution_downloader.py
- Rename opensearch_source_downloader.py → source_downloader.py
- Rename opensearch_distribution_repository_provider.py → distribution_repository_provider.py
- Delete opensearch_preparer.py (replaced by solr_preparer.py in PR 5)
- Delete core_plugin_source_downloader.py, external_plugin_source_downloader.py,
plugin_distribution_downloader.py (OSB plugin infrastructure, not needed for Solr)
- Update builder.py, provisioner.py, supplier.py to use the new Solr provisioner
**osbenchmark/config.py, context.py, benchmark.py, benchmarkd.py:**
Update configuration keys, context variables, and CLI help text for Solr.
Remove OpenSearch-specific commands and flags; add Solr cluster URL handling.
**osbenchmark/workload/ and osbenchmark/workload_generator/:**
Adapt workload loading and workload generation for Solr collection schema.
**osbenchmark/metrics.py, publisher.py:**
Update metric names and summary report labels from OpenSearch to Solr terminology.
**osbenchmark/resources/ — cluster config cleanup:**
Remove resources/cluster_configs/1.0/ entirely (OpenSearch 1.x configs).
Simplify resources/cluster_configs/main/ to Solr-relevant entries.
Update benchmark.ini default configuration.
**Integration and unit tests:**
Update all existing tests to match new API shapes. Delete tests for removed
functionality (telemetry_test.py replaced by tests/unit/test_telemetry.py,
workload_generator corpus/index tests removed as workload_generator was refactored).
Part of #3
---
benchmark | 4 +-
benchmarkd | 6 +-
benchmarks/__init__.py | 3 +
benchmarks/worker_coordinator/__init__.py | 3 +
benchmarks/worker_coordinator/parsing_test.py | 3 +
benchmarks/worker_coordinator/runner_test.py | 11 +-
benchmarks/workload/__init__.py | 3 +
benchmarks/workload/bulk_params_test.py | 3 +
docker/Dockerfile | 34 +-
it/__init__.py | 39 +-
it/distribution_test.py | 3 +
it/download_test.py | 3 +
it/info_test.py | 3 +
it/list_test.py | 7 +-
it/proxy_test.py | 3 +
it/resources/benchmark-in-memory-it.ini | 6 +-
it/resources/benchmark-os-it.ini | 38 -
it/sources_test.py | 3 +
it/tracker_test.py | 3 +
osbenchmark/__init__.py | 28 +-
osbenchmark/actor.py | 7 +-
osbenchmark/benchmark.py | 211 +-
osbenchmark/benchmarkd.py | 15 +-
osbenchmark/builder/__init__.py | 3 +
osbenchmark/builder/builder.py | 70 +-
osbenchmark/builder/cluster.py | 5 +-
osbenchmark/builder/cluster_config.py | 19 +-
.../downloaders/core_plugin_source_downloader.py | 26 -
...on_downloader.py => distribution_downloader.py} | 39 +-
osbenchmark/builder/downloaders/downloader.py | 33 +-
.../external_plugin_source_downloader.py | 30 -
.../downloaders/plugin_distribution_downloader.py | 12 -
...ider.py => distribution_repository_provider.py} | 28 +-
...h_source_downloader.py => source_downloader.py} | 39 +-
osbenchmark/builder/installers/bare_installer.py | 34 +-
osbenchmark/builder/installers/docker_installer.py | 45 +-
osbenchmark/builder/installers/installer.py | 32 +-
.../installers/preparers/opensearch_preparer.py | 105 -
.../installers/preparers/plugin_preparer.py | 44 -
osbenchmark/builder/java_resolver.py | 31 +-
osbenchmark/builder/launcher.py | 74 +-
osbenchmark/builder/launchers/launcher.py | 35 +-
.../builder/launchers/local_process_launcher.py | 80 +-
osbenchmark/builder/models/architecture_types.py | 6 +-
osbenchmark/builder/provisioner.py | 172 +-
osbenchmark/builder/supplier.py | 310 +-
.../builder/utils/artifact_variables_provider.py | 6 +-
osbenchmark/builder/utils/binary_keys.py | 29 +-
osbenchmark/builder/utils/config_applier.py | 29 +-
osbenchmark/builder/utils/java_home_resolver.py | 52 +-
osbenchmark/client.py | 827 ++-
osbenchmark/cloud_provider/vendors/aws.py | 27 +-
.../cloud_provider/vendors/s3_data_producer.py | 8 +-
osbenchmark/config.py | 11 +-
osbenchmark/context.py | 16 +-
osbenchmark/exceptions.py | 45 +-
osbenchmark/log.py | 5 +-
osbenchmark/metrics.py | 725 +-
osbenchmark/min-os-version.txt | 1 -
osbenchmark/min-version.txt | 1 +
osbenchmark/paths.py | 31 +-
osbenchmark/publisher.py | 30 +
osbenchmark/resources/benchmark.ini | 6 +-
.../1.0/cluster_configs/v1/basic-license.ini | 9 -
.../cluster_configs/v1/default_distro/config.ini | 15 -
.../1.0/cluster_configs/v1/trial-license.ini | 9 -
.../1.0/cluster_configs/v1/unpooled.ini | 6 -
.../v1/unpooled/templates/config/jvm.options | 1 -
.../1.0/cluster_configs/v1/vanilla/README.md | 10 +-
.../1.0/cluster_configs/v1/vanilla/config.ini | 33 +-
.../v1/vanilla/templates/config/opensearch.yml | 109 -
.../1.0/plugins/v1/core-plugins.txt | 33 -
.../1.0/plugins/v1/repository_azure/README.md | 27 -
.../1.0/plugins/v1/repository_azure/plugin.py | 118 -
.../1.0/plugins/v1/repository_gcs/README.md | 27 -
.../1.0/plugins/v1/repository_gcs/plugin.py | 96 -
.../1.0/plugins/v1/repository_s3/README.md | 29 -
.../1.0/plugins/v1/repository_s3/plugin.py | 119 -
.../default/templates/config/opensearch.yml | 4 -
.../1.0/plugins/v1/transport_nio/http.ini | 5 -
.../1.0/plugins/v1/transport_nio/transport.ini | 5 -
.../main/cluster_configs/v1/basic-license.ini | 9 -
.../main/cluster_configs/v1/defaults.ini | 1 -
.../main/cluster_configs/v1/g1gc.ini | 4 +-
.../main/cluster_configs/v1/parallelgc.ini | 4 +-
.../main/cluster_configs/v1/trial-license.ini | 9 -
.../main/cluster_configs/v1/unpooled.ini | 6 -
.../v1/unpooled/templates/config/jvm.options | 1 -
.../main/cluster_configs/v1/vanilla/README.md | 8 +-
.../main/cluster_configs/v1/vanilla/config.ini | 31 +-
.../v1/vanilla/templates/config/opensearch.yml | 109 -
.../main/plugins/v1/core-plugins.txt | 33 -
.../main/plugins/v1/repository_azure/README.md | 27 -
.../main/plugins/v1/repository_azure/plugin.py | 118 -
.../main/plugins/v1/repository_gcs/README.md | 27 -
.../main/plugins/v1/repository_gcs/plugin.py | 97 -
.../main/plugins/v1/repository_s3/README.md | 30 -
.../main/plugins/v1/repository_s3/plugin.py | 119 -
.../default/templates/config/opensearch.yml | 4 -
.../main/plugins/v1/transport_nio/http.ini | 5 -
.../main/plugins/v1/transport_nio/transport.ini | 5 -
.../resources/custom-test-procedures.json.j2 | 2 +-
.../resources/default-test-procedures.json.j2 | 2 +-
osbenchmark/resources/docker-compose.yml.j2 | 36 +-
osbenchmark/resources/workload-schema.json | 24 +-
osbenchmark/synthetic_data_generator/helpers.py | 2 +-
.../strategies/mapping_strategy.py | 2 +-
osbenchmark/telemetry.py | 2176 ++----
osbenchmark/test_run_orchestrator.py | 344 +-
osbenchmark/time.py | 3 +
.../config/opensearch.yml => tools/__init__.py} | 0
osbenchmark/utils/__init__.py | 3 +
osbenchmark/utils/collections.py | 3 +
osbenchmark/utils/console.py | 9 +-
osbenchmark/utils/convert.py | 3 +
osbenchmark/utils/git.py | 5 +-
osbenchmark/utils/io.py | 5 +-
osbenchmark/utils/jvm.py | 5 +-
osbenchmark/utils/modules.py | 7 +-
osbenchmark/utils/net.py | 5 +-
osbenchmark/utils/opts.py | 45 +-
osbenchmark/utils/process.py | 8 +-
osbenchmark/utils/repo.py | 7 +-
osbenchmark/utils/sysstats.py | 3 +
osbenchmark/utils/versions.py | 5 +-
osbenchmark/version.py | 17 +-
.../visualizations/benchmark_report_renderer.py | 42 +-
osbenchmark/worker_coordinator/__init__.py | 3 +
osbenchmark/worker_coordinator/errors.py | 35 +-
osbenchmark/worker_coordinator/runner.py | 3326 +++-------
osbenchmark/worker_coordinator/scheduler.py | 15 +-
.../worker_coordinator/worker_coordinator.py | 272 +-
osbenchmark/workload/__init__.py | 3 +
osbenchmark/workload/loader.py | 232 +-
osbenchmark/workload/params.py | 1196 +---
osbenchmark/workload/workload.py | 423 +-
osbenchmark/workload_generator/__init__.py | 3 +
osbenchmark/workload_generator/extractors.py | 172 +-
osbenchmark/workload_generator/helpers.py | 6 +-
.../workload_generator/workload_generator.py | 6 +-
scripts/analyze.py | 6 +-
scripts/expand-data-corpus.py | 23 +-
setup.py | 51 +-
tests/__init__.py | 3 +
tests/builder/__init__.py | 3 +
tests/builder/cluster_config_test.py | 7 +-
.../data/cluster_configs/v1/hook2/config.py | 5 +-
.../data/cluster_configs/v1/with_hook/config.py | 5 +-
...der_test.py => distribution_downloader_test.py} | 12 +-
...py => distribution_repository_provider_test.py} | 32 +-
...ownloader_test.py => source_downloader_test.py} | 16 +-
tests/builder/installers/bare_installer_test.py | 42 +-
tests/builder/installers/docker_installer_test.py | 100 +-
.../preparers/opensearch_preparer_test.py | 74 -
tests/builder/java_resolver_test.py | 20 +-
tests/builder/launcher_test.py | 32 +-
tests/builder/launchers/docker_launcher_test.py | 1 -
.../launchers/local_process_launcher_test.py | 14 +-
tests/builder/mechanic_test.py | 21 +-
tests/builder/provisioner_test.py | 295 +-
tests/builder/supplier_test.py | 440 +-
tests/builder/utils/config_applier_test.py | 4 +-
tests/builder/utils/java_home_resolver_test.py | 19 +-
tests/client_test.py | 521 +-
tests/config_test.py | 5 +-
tests/metrics_test.py | 1705 +----
tests/publisher_test.py | 3 +
tests/scripts_test.py | 5 +-
tests/telemetry_test.py | 3762 -----------
tests/test_execution_orchestrator_test.py | 18 +-
tests/time_test.py | 3 +
tests/utils/__init__.py | 3 +
tests/utils/collections_test.py | 3 +
tests/utils/console_test.py | 3 +
tests/utils/convert_test.py | 3 +
tests/utils/git_test.py | 7 +-
tests/utils/io_test.py | 5 +-
tests/utils/jvm_test.py | 3 +
tests/utils/net_test.py | 5 +-
tests/utils/opts_test.py | 9 +-
tests/utils/process_test.py | 23 +-
tests/utils/repo_test.py | 3 +
tests/utils/resources/client_options_1.json | 2 +-
tests/utils/versions_test.py | 3 +
tests/worker_coordinator/__init__.py | 3 +
tests/worker_coordinator/runner_test.py | 6955 +-------------------
tests/worker_coordinator/scheduler_test.py | 3 +
.../worker_coordinator/worker_coordinator_test.py | 273 +-
tests/workload/__init__.py | 3 +
tests/workload/loader_test.py | 1274 +---
tests/workload/params_test.py | 2212 +------
tests/workload/workload_test.py | 124 +-
tests/workload_generator/__init__.py | 3 +
tests/workload_generator/corpus_test.py | 109 -
tests/workload_generator/index_test.py | 182 -
195 files changed, 4966 insertions(+), 26811 deletions(-)
diff --git a/benchmark b/benchmark
index a9a5b09b..495f11a3 100755
--- a/benchmark
+++ b/benchmark
@@ -24,7 +24,7 @@ set -u
# fail on pipeline errors, e.g. when grepping
set -o pipefail
-# We assume here that this script will stay in the OSB git root directory (it does not make sense in any other place anyway)
+# We assume here that this script will stay in the ASB git root directory (it does not make sense in any other place anyway)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
@@ -40,7 +40,7 @@ cd "${BENCHMARK_SRC_HOME}" >/dev/null 2>&1
# set variables that are needed for run.sh
__BENCHMARK_INTERNAL_BINARY_NAME="osbenchmark"
-__BENCHMARK_INTERNAL_HUMAN_NAME="OpenSearch Benchmark"
+__BENCHMARK_INTERNAL_HUMAN_NAME="Apache Solr Benchmark"
source run.sh
diff --git a/benchmarkd b/benchmarkd
index 025b47cc..8f89d4f3 100755
--- a/benchmarkd
+++ b/benchmarkd
@@ -24,7 +24,7 @@ set -u
# fail on pipeline errors, e.g. when grepping
set -o pipefail
-# We assume here that this script will stay in the OSB git root directory (it does not make sense in any other place anyway)
+# We assume here that this script will stay in the ASB git root directory (it does not make sense in any other place anyway)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
@@ -37,11 +37,11 @@ BENCHMARK_SRC_HOME="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
pushd . >/dev/null 2>&1
cd "${BENCHMARK_SRC_HOME}" >/dev/null 2>&1
-# ensure the Actor system can find OSB sources (it is ok if PYTHONPATH is undefined yet. Hence we define an empty default).
+# ensure the Actor system can find sources (it is ok if PYTHONPATH is undefined yet. Hence we define an empty default).
export PYTHONPATH="${BENCHMARK_SRC_HOME}:${PYTHONPATH:-}"
# set variables that are needed for run.sh
__BENCHMARK_INTERNAL_BINARY_NAME="osbenchmarkd"
-__BENCHMARK_INTERNAL_HUMAN_NAME="OpenSearch Benchmark Daemon"
+__BENCHMARK_INTERNAL_HUMAN_NAME="Apache Solr Benchmark Daemon"
source run.sh
diff --git a/benchmarks/__init__.py b/benchmarks/__init__.py
index e7a26e8e..5047a451 100644
--- a/benchmarks/__init__.py
+++ b/benchmarks/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/benchmarks/worker_coordinator/__init__.py b/benchmarks/worker_coordinator/__init__.py
index e7a26e8e..5047a451 100644
--- a/benchmarks/worker_coordinator/__init__.py
+++ b/benchmarks/worker_coordinator/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/benchmarks/worker_coordinator/parsing_test.py b/benchmarks/worker_coordinator/parsing_test.py
index f192afbc..4ea78e44 100644
--- a/benchmarks/worker_coordinator/parsing_test.py
+++ b/benchmarks/worker_coordinator/parsing_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/benchmarks/worker_coordinator/runner_test.py b/benchmarks/worker_coordinator/runner_test.py
index d323bbf9..dc5e9b04 100644
--- a/benchmarks/worker_coordinator/runner_test.py
+++ b/benchmarks/worker_coordinator/runner_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -31,7 +34,7 @@ bulk_index = runner.BulkIndex()
BULK_SIZE = 5000
-class OpenSearchMock:
+class SolrMock:
def __init__(self, bulk_size):
self.no_errors = {
"took": 500,
@@ -61,7 +64,7 @@ class OpenSearchMock:
return self.no_errors
-os_mock = OpenSearchMock(bulk_size=BULK_SIZE)
+solr_mock = SolrMock(bulk_size=BULK_SIZE)
@pytest.mark.benchmark(
@@ -71,7 +74,7 @@ os_mock = OpenSearchMock(bulk_size=BULK_SIZE)
disable_gc=True
)
def test_bulk_runner_without_errors_no_detailed_results(benchmark):
- benchmark(bulk_index, os_mock, {
+ benchmark(bulk_index, solr_mock, {
"action-metadata-present": True,
"body": "bulk API body",
"bulk-size": BULK_SIZE
@@ -85,7 +88,7 @@ def test_bulk_runner_without_errors_no_detailed_results(benchmark):
disable_gc=True
)
def test_bulk_runner_without_errors_with_detailed_results(benchmark):
- benchmark(bulk_index, os_mock, {
+ benchmark(bulk_index, solr_mock, {
"action-metadata-present": True,
"body": "bulk API body",
"bulk-size": BULK_SIZE,
diff --git a/benchmarks/workload/__init__.py b/benchmarks/workload/__init__.py
index e7a26e8e..5047a451 100644
--- a/benchmarks/workload/__init__.py
+++ b/benchmarks/workload/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/benchmarks/workload/bulk_params_test.py b/benchmarks/workload/bulk_params_test.py
index 8379d6c2..12323c97 100644
--- a/benchmarks/workload/bulk_params_test.py
+++ b/benchmarks/workload/bulk_params_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 0a777952..ede5bcf9 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -1,5 +1,5 @@
########################################################
-# Install OpenSearch Benchmark to build a Docker image #
+# Install Apache Solr Benchmark to build a Docker image #
########################################################
#
@@ -11,10 +11,10 @@ RUN apt-get -y update && \
apt-get install -y curl git gcc pbzip2 pigz make jq && \
apt-get -y upgrade
-COPY . opensearch-benchmark
+COPY . solr-benchmark
# There is no binary package currently available for yappi on ARM.
-RUN cd opensearch-benchmark; \
+RUN cd solr-benchmark; \
make build; \
if test "`uname -m`" = aarch64; then pip wheel yappi && cp yappi-*.whl dist; fi
@@ -25,15 +25,15 @@ RUN cd opensearch-benchmark; \
FROM python:3.11.2-slim AS image-stage
ENV BENCHMARK_RUNNING_IN_DOCKER=True
-RUN groupadd --gid 1000 opensearch-benchmark && \
- useradd -d /opensearch-benchmark -m -k /dev/null -g 1000 -N -u 1000 -l -s /bin/bash benchmark
+RUN groupadd --gid 1000 solr-benchmark && \
+ useradd -d /solr-benchmark -m -k /dev/null -g 1000 -N -u 1000 -l -s /bin/bash benchmark
-WORKDIR /opensearch-benchmark
+WORKDIR /solr-benchmark
-RUN mkdir -p /opensearch-benchmark/.benchmark && \
- chown -R 1000:0 /opensearch-benchmark/.benchmark
+RUN mkdir -p /solr-benchmark/.solr-benchmark && \
+ chown -R 1000:0 /solr-benchmark/.solr-benchmark
-COPY --from=build-stage /opensearch-benchmark/dist/*.whl ./
+COPY --from=build-stage /solr-benchmark/dist/*.whl ./
RUN set -ex; \
apt-get -y update; \
@@ -49,16 +49,16 @@ ARG VERSION
ARG BUILD_DATE
LABEL org.label-schema.schema-version="1.0" \
- org.label-schema.vendor="OpenSearch-Project" \
- org.label-schema.name="opensearch-benchmark" \
- org.label-schema.url="https://opensearch.org/" \
+ org.label-schema.vendor="Apache" \
+ org.label-schema.name="solr-benchmark" \
+ org.label-schema.url="https://solr.apache.org/" \
org.label-schema.version="$VERSION" \
org.label-schema.license="Apache-2.0" \
- org.label-schema.description="A community driven, open source project to run performance tests for OpenSearch" \
+ org.label-schema.description="Apache Solr Benchmark — performance benchmarking tool for Apache Solr clusters" \
org.label-schema.build-date="$BUILD_DATE" \
- org.label-schema.vcs-url="https://github.com/opensearch-project/OpenSearch-Benchmark" \
- "DOCKERFILE"="https://github.com/opensearch-project/opensearch-benchmark/blob/main/docker/Dockerfile"
+ org.label-schema.vcs-url="https://github.com/janhoy/solr-benchmark" \
+ "DOCKERFILE"="https://github.com/janhoy/solr-benchmark/blob/main/docker/Dockerfile"
-VOLUME ["/opensearch-benchmark/.benchmark"]
+VOLUME ["/solr-benchmark/.solr-benchmark"]
-ENTRYPOINT [ "opensearch-benchmark" ]
+ENTRYPOINT [ "solr-benchmark" ]
diff --git a/it/__init__.py b/it/__init__.py
index fde0dddb..b47a71ba 100644
--- a/it/__init__.py
+++ b/it/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -36,10 +39,10 @@ import pytest
from osbenchmark import client, config, version, paths
from osbenchmark.utils import process
-CONFIG_NAMES = ["in-memory-it", "os-it"]
-DISTRIBUTIONS = ["1.3.9", "2.17.1"]
-WORKLOADS = ["geonames", "nyc_taxis", "http_logs", "nested"]
-BASE_COMMANDS = ["opensearch-benchmark", "osb"]
+CONFIG_NAMES = ["in-memory-it"]
+DISTRIBUTIONS = ["9.10.1", "10.1.0"]
+WORKLOADS = ["geonames", "nyc_taxis"]
+BASE_COMMANDS = ["solr-benchmark"]
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
@@ -89,7 +92,7 @@ def osbenchmark(cfg, command_line):
These commands may have different CLI options than test_run.
"""
cmd = osbenchmark_command_line_for(cfg, command_line)
- print(f'\n{datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")} Invoking OSB: {cmd}')
+ print(f'\n{datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")} Invoking solr-benchmark: {cmd}')
err, retcode = process.run_subprocess_with_stderr(cmd)
if retcode != 0:
print(err)
@@ -171,7 +174,7 @@ class TestCluster:
transport_port = http_port + 100
try:
err, retcode = process.run_subprocess_with_stderr(
- "opensearch-benchmark install --configuration-name={cfg} --distribution-version={dist} --build-type=tar "
+ "solr-benchmark install --configuration-name={cfg} --distribution-version={dist} --build-type=tar "
"--http-port={http_port} --node={node_name} --master-nodes="
"{node_name} --cluster-config={cluster_config} "
"--seed-hosts=\"127.0.0.1:{transport_port}\"".format(cfg=self.cfg,
@@ -181,35 +184,35 @@ class TestCluster:
cluster_config=cluster_config,
transport_port=transport_port))
if retcode != 0:
- raise AssertionError("Failed to install OpenSearch {}.".format(distribution_version), err)
+ raise AssertionError("Failed to install node {}.".format(distribution_version), err)
self.installation_id = json.loads(err)["installation-id"]
except BaseException as e:
- raise AssertionError("Failed to install OpenSearch {}.".format(distribution_version), e)
+ raise AssertionError("Failed to install node {}.".format(distribution_version), e)
def start(self, test_run_id):
cmd = "start --runtime-jdk=\"bundled\" --installation-id={} --test-run-id={}".format(self.installation_id, test_run_id)
if osbenchmark(self.cfg, cmd) != 0:
- raise AssertionError("Failed to start OpenSearch test cluster.")
- opensearch = client.OsClientFactory(hosts=[{"host": "127.0.0.1", "port": self.http_port}], client_options={}).create()
- client.wait_for_rest_layer(opensearch)
+ raise AssertionError("Failed to start test cluster.")
+ solr_client = client.ClientFactory(hosts=[{"host": "127.0.0.1", "port": self.http_port}], client_options={}).create()
+ client.wait_for_rest_layer(solr_client)
def stop(self):
if self.installation_id:
if osbenchmark(self.cfg, "stop --installation-id={}".format(self.installation_id)) != 0:
- raise AssertionError("Failed to stop OpenSearch test cluster.")
+ raise AssertionError("Failed to stop test cluster.")
def __str__(self):
return f"TestCluster[installation-id={self.installation_id}]"
-class OsMetricsStore:
+class MetricsStore:
VERSION = "1.3.9"
def __init__(self):
self.cluster = TestCluster("in-memory-it")
def start(self):
- self.cluster.install(distribution_version=OsMetricsStore.VERSION,
+ self.cluster.install(distribution_version=MetricsStore.VERSION,
node_name="metrics-store",
cluster_config="defaults",
http_port=10200)
@@ -234,7 +237,7 @@ def remove_integration_test_config():
os.remove(config.ConfigFile(config_name).location)
-OS_METRICS_STORE = OsMetricsStore()
+METRICS_STORE = MetricsStore()
def get_license():
@@ -249,7 +252,7 @@ def build_docker_image():
env_variables['BENCHMARK_VERSION'] = benchmark_version
env_variables['BENCHMARK_LICENSE'] = get_license()
- command = f"docker build -t opensearchproject/benchmark:{benchmark_version}" \
+ command = f"docker build -t apache/solr-benchmark:{benchmark_version}" \
f" --build-arg BENCHMARK_VERSION --build-arg BENCHMARK_LICENSE " \
f"-f {ROOT_DIR}/docker/Dockerfiles/Dockerfile-dev {ROOT_DIR}"
@@ -260,9 +263,9 @@ def build_docker_image():
def setup_module():
check_prerequisites()
install_integration_test_config()
- OS_METRICS_STORE.start()
+ METRICS_STORE.start()
def teardown_module():
- OS_METRICS_STORE.stop()
+ METRICS_STORE.stop()
remove_integration_test_config()
diff --git a/it/distribution_test.py b/it/distribution_test.py
index 2e968ac3..9030950d 100644
--- a/it/distribution_test.py
+++ b/it/distribution_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/it/download_test.py b/it/download_test.py
index f7892486..c0a7f0e9 100644
--- a/it/download_test.py
+++ b/it/download_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/it/info_test.py b/it/info_test.py
index 1e86be92..71a70666 100644
--- a/it/info_test.py
+++ b/it/info_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/it/list_test.py b/it/list_test.py
index f13b86bd..3315bb87 100644
--- a/it/list_test.py
+++ b/it/list_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -36,10 +39,6 @@ def test_list_cluster_configs(cfg):
assert it.osbenchmark(cfg, "list cluster-configs --cluster-config-repository=default") == 0
-@it.benchmark_in_mem
-def test_list_opensearch_plugins(cfg):
- assert it.osbenchmark(cfg, "list opensearch-plugins") == 0
-
@it.benchmark_in_mem
def test_list_workloads(cfg):
diff --git a/it/proxy_test.py b/it/proxy_test.py
index 2c08c679..37555d51 100644
--- a/it/proxy_test.py
+++ b/it/proxy_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/it/resources/benchmark-in-memory-it.ini b/it/resources/benchmark-in-memory-it.ini
index b86c9796..7ada010b 100644
--- a/it/resources/benchmark-in-memory-it.ini
+++ b/it/resources/benchmark-in-memory-it.ini
@@ -9,8 +9,8 @@ root.dir = ${CONFIG_DIR}/benchmarks
src.root.dir = ${CONFIG_DIR}/benchmarks/src
[source]
-remote.repo.url = https://github.com/opensearch-project/OpenSearch.git
-opensearch.src.subdir = opensearch
+remote.repo.url = https://github.com/apache/solr.git
+src.subdir = solr
[benchmarks]
local.dataset.cache = ${CONFIG_DIR}/benchmarks/data
@@ -20,7 +20,7 @@ datastore.type = in-memory
[workloads]
-default.url = https://github.com/opensearch-project/opensearch-benchmark-workloads
+default.url = https://github.com/janhoy/solr-benchmark-workloads
[cluster_configs]
default.dir = default-cluster-config
diff --git a/it/resources/benchmark-os-it.ini b/it/resources/benchmark-os-it.ini
deleted file mode 100644
index c5967f25..00000000
--- a/it/resources/benchmark-os-it.ini
+++ /dev/null
@@ -1,38 +0,0 @@
-[meta]
-config.version = 17
-
-[system]
-env.name = local
-
-[node]
-root.dir = ${CONFIG_DIR}/benchmarks
-src.root.dir = ${CONFIG_DIR}/benchmarks/src
-
-[source]
-remote.repo.url = https://github.com/opensearch-project/OpenSearch.git
-opensearch.src.subdir = opensearch
-
-[benchmarks]
-local.dataset.cache = ${CONFIG_DIR}/benchmarks/data
-
-[reporting]
-datastore.type = opensearch
-datastore.host = localhost
-datastore.port = 10200
-datastore.secure = False
-datastore.user =
-datastore.password =
-
-
-[workloads]
-default.url = https://github.com/opensearch-project/opensearch-benchmark-workloads
-
-[cluster_configs]
-default.dir = default-cluster-config
-
-[defaults]
-preserve_benchmark_candidate = False
-
-[distributions]
-release.cache = true
-
diff --git a/it/sources_test.py b/it/sources_test.py
index 7bde53b5..dcc28012 100644
--- a/it/sources_test.py
+++ b/it/sources_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/it/tracker_test.py b/it/tracker_test.py
index 5d3a0c40..bc6248fb 100644
--- a/it/tracker_test.py
+++ b/it/tracker_test.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/osbenchmark/__init__.py b/osbenchmark/__init__.py
index 6871a129..36110c74 100644
--- a/osbenchmark/__init__.py
+++ b/osbenchmark/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -28,22 +31,23 @@ import urllib
from importlib.metadata import version as get_version
-__version__ = get_version("opensearch-benchmark")
+__version__ = get_version("solr-benchmark")
-# Allow an alternative program name be set in case OSB is invoked a wrapper script
+# Allow an alternative program name to be set in case solr-benchmark is invoked via a wrapper script
PROGRAM_NAME = os.getenv("BENCHMARK_ALTERNATIVE_BINARY_NAME", os.path.basename(sys.argv[0]))
-DOC_LINK = "https://opensearch.org/docs"
+DOC_LINK = "https://solr.apache.org/guide/"
-FORUM_LINK = "https://forum.opensearch.org/"
+FORUM_LINK = "https://solr.apache.org/community.html#mailing-lists-chat"
BANNER = r"""
- ____ _____ __ ____ __ __
- / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__
- / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/
-/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,<
-\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_|
- /_/
+ _____ __ ____ __ __
+ / ___/____ / /____ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__
+ \__ \/ __ \/ / ___/ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/
+ ___/ / /_/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,<
+/____/\____/_/_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_|
+
+ Apache Solr Benchmark
"""
@@ -79,8 +83,8 @@ $$$$$$$$$$"""" ""$$$$$$$$$$$"
def check_python_version():
- if sys.version_info.major != 3 or sys.version_info.minor < 8:
- raise RuntimeError("OSB requires at least Python 3.10 but you are using:\n\nPython %s" % str(sys.version))
+ if sys.version_info < (3, 10):
+ raise RuntimeError("solr-benchmark requires at least Python 3.10 but you are using:\n\nPython %s" % str(sys.version))
def doc_link(path=None):
diff --git a/osbenchmark/actor.py b/osbenchmark/actor.py
index cf425538..dfe1accc 100644
--- a/osbenchmark/actor.py
+++ b/osbenchmark/actor.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -67,7 +70,7 @@ def no_retry(f, actor_name):
Decorator intended for Thespian message handlers with the signature ``receiveMsg_$MSG_NAME(self, msg, sender)``. Thespian will
assume that a message handler that raises an exception can be retried. It will then retry once and give up afterwards just leaving
- a trace of that in the actor system's internal log file. However, this is usually *not* what we want in OSB. If handling of a
+ a trace of that in the actor system's internal log file. However, this is usually *not* what we want in ASB. If handling of a
message fails we instead want to notify a node higher up in the actor hierarchy.
We achieve that by sending a ``BenchmarkFailure`` message to the original sender. Note that this might as well be the current
@@ -232,7 +235,7 @@ def bootstrap_actor_system(try_join=False, prefer_local_only=False, local_ip=Non
local_ip = None
else:
if system_base not in ("multiprocTCPBase", "multiprocUDPBase"):
- raise exceptions.SystemSetupError("OSB requires a network-capable system base but got [%s]." % system_base)
+ raise exceptions.SystemSetupError("ASB requires a network-capable system base but got [%s]." % system_base)
if not coordinator_ip:
raise exceptions.SystemSetupError("coordinator IP is required")
if not local_ip:
diff --git a/osbenchmark/benchmark.py b/osbenchmark/benchmark.py
index 0dd6de59..17488299 100644
--- a/osbenchmark/benchmark.py
+++ b/osbenchmark/benchmark.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -32,6 +35,14 @@ import time
import uuid
import shutil
+# macOS fork-safety: Python programs that use multiprocessing (Thespian) can trigger
+# an Objective-C runtime crash when forking after any thread has started (e.g. from
+# background telemetry polling). Setting this env-var before any fork suppresses
+# the crash. This must be done before the actor system (and its admin process) is
+# bootstrapped. See: https://bugs.python.org/issue33725
+if sys.platform == "darwin":
+ os.environ.setdefault("OBJC_DISABLE_INITIALIZE_FORK_SAFETY", "YES")
+
import thespian.actors
from osbenchmark import PROGRAM_NAME, BANNER, FORUM_LINK, SKULL, check_python_version, doc_link, telemetry
@@ -68,17 +79,17 @@ def create_arg_parser():
def supported_os_version(v):
if v:
- min_os_version = versions.Version.from_string(version.minimum_os_version())
+ min_solr_version = versions.Version.from_string(version.minimum_solr_version())
specified_version = versions.Version.from_string(v)
- if specified_version < min_os_version:
- raise argparse.ArgumentTypeError(f"must be at least {min_os_version} but was {v}")
+ if specified_version < min_solr_version:
+ raise argparse.ArgumentTypeError(f"must be at least {min_solr_version} but was {v}")
return v
def add_workload_source(subparser):
workload_source_group = subparser.add_mutually_exclusive_group()
workload_source_group.add_argument(
"--workload-repository",
- help="Define the repository from where OSB will load workloads (default: default).",
+ help="Define the repository from where solr-benchmark will load workloads (default: default).",
# argparse is smart enough to use this default only if the user did not use --workload-path and also did not specify anything
default="default"
)
@@ -87,7 +98,7 @@ def create_arg_parser():
help="Define the path to a workload.")
subparser.add_argument(
"--workload-revision",
- help="Define a specific revision in the workload repository that OSB should use.",
+ help="Define a specific revision in the workload repository that solr-benchmark should use.",
default=None)
# try to preload configurable defaults, but this does not work together with `--configuration-name` (which is undocumented anyway)
@@ -99,8 +110,8 @@ def create_arg_parser():
preserve_install = False
parser = argparse.ArgumentParser(prog=PROGRAM_NAME,
- description=BANNER + "\n\n A benchmarking tool for OpenSearch",
- epilog="Find out more about OSB at {}".format(console.format.link(doc_link())),
+ description=BANNER + "\n\n A macrobenchmarking tool for Apache Solr",
+ epilog="Find out more at {}".format(console.format.link(doc_link())),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--version', action='version', version="%(prog)s " + version.version())
@@ -119,10 +130,10 @@ def create_arg_parser():
list_parser.add_argument(
"configuration",
metavar="configuration",
- help="The configuration for which OSB should show the available options. "
- "Possible values are: telemetry, workloads, pipelines, test-runs, cluster-configs, opensearch-plugins",
+ help="The configuration for which the tool should show the available options. "
+ "Possible values are: telemetry, workloads, pipelines, test-runs, cluster-configs",
choices=["telemetry", "workloads", "pipelines", "test-runs", "aggregated-results",
- "cluster-configs", "opensearch-plugins"])
+ "cluster-configs"])
list_parser.add_argument(
"--limit",
help="Limit the number of search results for recent test-runs (default: 10).",
@@ -160,13 +171,13 @@ def create_arg_parser():
synthetic_data_generator_parser = subparsers.add_parser("generate-data",
help="Generate synthetic data based on existing index mappings or custom module." +
- "This data can be ported into OSB workloads or ingested into OpenSearch." )
+ "This data can be ported into Solr Benchmark workloads." )
exclusive_file_inputs = synthetic_data_generator_parser.add_mutually_exclusive_group(required=True)
exclusive_file_inputs.add_argument(
"--index-mappings",
"-i",
- help="OpenSearch index mappings to generate data from."
+ help="Index mappings (JSON) to generate synthetic data from."
)
exclusive_file_inputs.add_argument(
"--custom-module",
@@ -210,7 +221,7 @@ def create_arg_parser():
help="Generates a single synthetic document and displays it to the console so that users can validate generated values and output."
)
- create_workload_parser = subparsers.add_parser("create-workload", help="Create a OSB workload from existing data")
+ create_workload_parser = subparsers.add_parser("create-workload", help="Create a workload from existing data")
create_workload_parser.add_argument(
"--workload",
"-w",
@@ -257,6 +268,28 @@ def create_arg_parser():
"Ensure that index name also exists in --indices parameter. " +
"To specify several indices and doc counts, use format: <index1>:<sample-frequency-1> <index2>:<sample-frequency-2> ...")
+ convert_workload_parser = subparsers.add_parser(
+ "convert-workload",
+ help="Convert an OpenSearch Benchmark workload to Solr-native format"
+ )
+ convert_workload_parser.add_argument(
+ "--workload-path",
+ required=True,
+ help="Path to the source OpenSearch Benchmark workload directory (must contain workload.json)."
+ )
+ convert_workload_parser.add_argument(
+ "--output-path",
+ default=None,
+ help="Path where the converted Solr workload will be written "
+ "(default: <workload-path>-solr)."
+ )
+ convert_workload_parser.add_argument(
+ "--force",
+ action="store_true",
+ default=False,
+ help="Overwrite an existing converted workload directory."
+ )
+
compare_parser = subparsers.add_parser("compare", help="Compare two test_runs")
compare_parser.add_argument(
"--baseline",
@@ -322,17 +355,17 @@ def create_arg_parser():
default="")
aggregate_parser.add_argument(
"--workload-repository",
- help="Define the repository from where OSB will load workloads (default: default).",
+ help="Define the repository from where solr-benchmark will load workloads (default: default).",
default="default")
download_parser = subparsers.add_parser("download", help="Downloads an artifact")
download_parser.add_argument(
"--cluster-config-repository",
- help="Define the repository from where OSB will load cluster-configs (default: default).",
+ help="Define the repository from where solr-benchmark will load cluster-configs (default: default).",
default="default")
download_parser.add_argument(
"--cluster-config-revision",
- help="Define a specific revision in the cluster-config repository that OSB should use.",
+ help="Define a specific revision in the cluster-config repository that solr-benchmark should use.",
default=None)
download_parser.add_argument(
"--cluster-config-path",
@@ -340,12 +373,12 @@ def create_arg_parser():
download_parser.add_argument(
"--distribution-version",
type=supported_os_version,
- help="Define the version of the OpenSearch distribution to download. "
- "Check https://opensearch.org/docs/version-history/ for released versions.",
+ help="Define the version of the distribution to download. "
+ "Check https://projects.apache.org/project.html?solr for released versions.",
default="")
download_parser.add_argument(
"--distribution-repository",
- help="Define the repository from where the OpenSearch distribution should be downloaded (default: release).",
+ help="Define the repository from where the distribution should be downloaded (default: release).",
default="release")
download_parser.add_argument(
"--cluster-config",
@@ -358,16 +391,8 @@ def create_arg_parser():
help="Define a comma-separated list of key:value pairs that are injected verbatim as variables for the cluster-config.",
default=""
)
- download_parser.add_argument(
- "--target-os",
- help="The name of the target operating system for which an artifact should be downloaded (default: current OS)",
- )
- download_parser.add_argument(
- "--target-arch",
- help="The name of the CPU architecture for which an artifact should be downloaded (default: current architecture)",
- )
- install_parser = subparsers.add_parser("install", help="Installs an OpenSearch node locally")
+ install_parser = subparsers.add_parser("install", help="Installs a Solr node locally")
install_parser.add_argument(
"--revision",
help="Define the source code revision for building the benchmark candidate. 'current' uses the source tree as is,"
@@ -383,11 +408,11 @@ def create_arg_parser():
default="tar")
install_parser.add_argument(
"--cluster-config-repository",
- help="Define the repository from where OSB will load cluster-configs (default: default).",
+ help="Define the repository from where solr-benchmark will load cluster-configs (default: default).",
default="default")
install_parser.add_argument(
"--cluster-config-revision",
- help="Define a specific revision in the cluster-config repository that OSB should use.",
+ help="Define a specific revision in the cluster-config repository that solr-benchmark should use.",
default=None)
install_parser.add_argument(
"--cluster-config-path",
@@ -399,13 +424,13 @@ def create_arg_parser():
default=None)
install_parser.add_argument(
"--distribution-repository",
- help="Define the repository from where the OpenSearch distribution should be downloaded (default: release).",
+ help="Define the repository from where the distribution should be downloaded (default: release).",
default="release")
install_parser.add_argument(
"--distribution-version",
type=supported_os_version,
- help="Define the version of the OpenSearch distribution to download. "
- "Check https://opensearch.org/docs/version-history/ for released versions.",
+ help="Define the version of the distribution to download. "
+ "Check https://archive.apache.org/dist/solr/solr/ for released versions.",
default="")
install_parser.add_argument(
"--cluster-config",
@@ -419,8 +444,9 @@ def create_arg_parser():
default=""
)
install_parser.add_argument(
- "--opensearch-plugins",
- help="Define the OpenSearch plugins to install. (default: install no plugins).",
+ "--solr-modules",
+ help="Comma-separated list of Solr modules to enable (sets SOLR_MODULES). "
+ "Example: --solr-modules=analytics,extraction",
default="")
install_parser.add_argument(
"--plugin-params",
@@ -435,11 +461,11 @@ def create_arg_parser():
install_parser.add_argument(
"--http-port",
help="The port to expose for HTTP traffic",
- default="39200"
+ default="38983"
)
install_parser.add_argument(
"--node-name",
- help="The name of this OpenSearch node",
+ help="The name of this Solr node",
default="benchmark-node-0"
)
install_parser.add_argument(
@@ -453,7 +479,7 @@ def create_arg_parser():
default=""
)
- start_parser = subparsers.add_parser("start", help="Starts an OpenSearch node locally")
+ start_parser = subparsers.add_parser("start", help="Starts a Solr node locally")
start_parser.add_argument(
"--installation-id",
required=True,
@@ -484,7 +510,7 @@ def create_arg_parser():
default=""
)
- stop_parser = subparsers.add_parser("stop", help="Stops an OpenSearch node locally")
+ stop_parser = subparsers.add_parser("stop", help="Stops a Solr node locally")
stop_parser.add_argument(
"--installation-id",
required=True,
@@ -503,19 +529,18 @@ def create_arg_parser():
p.add_argument(
"--distribution-version",
type=supported_os_version,
- help="Define the version of the OpenSearch distribution to download. "
- "Check https://opensearch.org/docs/version-history/ for released versions.",
+ help="Define the version of the distribution to download.",
default="")
p.add_argument(
"--cluster-config-path",
help="Define the path to the cluster-config and plugin configurations to use.")
p.add_argument(
"--cluster-config-repository",
- help="Define repository from where OSB will load cluster-configs (default: default).",
+ help="Define repository from where solr-benchmark will load cluster-configs (default: default).",
default="default")
p.add_argument(
"--cluster-config-revision",
- help="Define a specific revision in the cluster-config repository that OSB should use.",
+ help="Define a specific revision in the cluster-config repository that solr-benchmark should use.",
default=None)
test_run_parser.add_argument(
@@ -569,8 +594,9 @@ def create_arg_parser():
help="The major version of the runtime JDK to use.",
default=None)
test_run_parser.add_argument(
- "--opensearch-plugins",
- help="Define the OpenSearch plugins to install. (default: install no plugins).",
+ "--solr-modules",
+ help="Comma-separated list of Solr modules to enable (sets SOLR_MODULES). "
+ "Example: --solr-modules=analytics,extraction",
default="")
test_run_parser.add_argument(
"--plugin-params",
@@ -595,12 +621,12 @@ def create_arg_parser():
test_run_parser.add_argument(
"--client-options",
"-c",
- help=f"Define a comma-separated list of client options to use. The options will be passed to the OpenSearch "
- f"Python client (default: {opts.ClientOptions.DEFAULT_CLIENT_OPTIONS}).",
+ help=f"Define a comma-separated list of client options to use. The options will be passed to the benchmark "
+ f"client (default: {opts.ClientOptions.DEFAULT_CLIENT_OPTIONS}).",
default=opts.ClientOptions.DEFAULT_CLIENT_OPTIONS)
test_run_parser.add_argument("--on-error",
choices=["continue", "abort"],
- help="Controls how OSB behaves on response errors (default: continue).",
+ help="Controls how solr-benchmark behaves on response errors (default: continue).",
default="continue")
test_run_parser.add_argument(
"--telemetry",
@@ -614,7 +640,7 @@ def create_arg_parser():
)
test_run_parser.add_argument(
"--distribution-repository",
- help="Define the repository from where the OpenSearch distribution should be downloaded (default: release).",
+ help="Define the repository from where the distribution should be downloaded (default: release).",
default="release")
task_filter_group = test_run_parser.add_mutually_exclusive_group()
@@ -660,7 +686,7 @@ def create_arg_parser():
action="store_true")
test_run_parser.add_argument(
"--enable-worker-coordinator-profiling",
- help="Enables a profiler for analyzing the performance of calls in OSB's worker coordinator (default: false).",
+ help="Enables a profiler for analyzing the performance of calls in solr-benchmark's worker coordinator (default: false).",
default=False,
action="store_true")
test_run_parser.add_argument(
@@ -673,7 +699,7 @@ def create_arg_parser():
"-k",
action="store_true",
default=False,
- help="If any processes is running, it is going to kill them and allow OSB to continue to run."
+ help="If any processes is running, it is going to kill them and allow solr-benchmark to continue to run."
)
test_run_parser.add_argument(
"--latency-percentiles",
@@ -766,7 +792,7 @@ def create_arg_parser():
test_run_parser.add_argument(
"--redline-max-cpu-usage",
type=int,
- help="Maximum CPU utilization before scaling back client numbers. Used to activate CPU-based feedback in OSB.",
+ help="Maximum CPU utilization before scaling back client numbers. Used to activate CPU-based feedback in solr-benchmark.",
default=None
)
test_run_parser.add_argument(
@@ -798,7 +824,7 @@ def create_arg_parser():
# The options below are undocumented and can be removed or changed at any time.
#
###############################################################################
- # This option is intended to tell OSB to assume a different start date than 'now'. This is effectively just useful for things like
+ # This option is intended to tell solr-benchmark to assume a different start date than 'now'. This is effectively just useful for things like
# backtesting or a benchmark run across environments (think: comparison of EC2 and bare metal) but never for the typical user.
test_run_parser.add_argument(
"--effective-start-date",
@@ -814,7 +840,8 @@ def create_arg_parser():
for p in [list_parser, test_run_parser, compare_parser, aggregate_parser,
download_parser, install_parser, start_parser, stop_parser, info_parser,
- synthetic_data_generator_parser, create_workload_parser, visualize_parser]:
+ synthetic_data_generator_parser, create_workload_parser, visualize_parser,
+ convert_workload_parser]:
# This option is needed to support a separate configuration for the integration tests on the same machine
p.add_argument(
"--configuration-name",
@@ -827,7 +854,7 @@ def create_arg_parser():
action="store_true")
p.add_argument(
"--offline",
- help="Assume that OSB has no connection to the Internet (default: false).",
+ help="Assume that solr-benchmark has no connection to the Internet (default: false).",
default=False,
action="store_true")
@@ -848,8 +875,6 @@ def dispatch_list(cfg):
metrics.list_aggregated_results(cfg)
elif what == "cluster-configs":
cluster_config.list_cluster_configs(cfg)
- elif what == "opensearch-plugins":
- cluster_config.list_plugins(cfg)
else:
raise exceptions.SystemSetupError("Cannot list unknown configuration option [%s]" % what)
@@ -888,7 +913,7 @@ def print_help_on_errors():
console.println(f"* Check the log files in {paths.logs()} for errors.")
console.println(f"* Read the documentation at {console.format.link(doc_link())}.")
console.println(f"* Ask a question on the forum at {console.format.link(FORUM_LINK)}.")
- console.println(f"* Raise an issue at {console.format.link('https://github.com/opensearch-project/OpenSearch-Benchmark/issues')} "
+ console.println(f"* Raise an issue in the project issue tracker "
f"and include the log files in {paths.logs()}.")
@@ -896,23 +921,23 @@ def run_test(cfg, kill_running_processes=False):
logger = logging.getLogger(__name__)
if kill_running_processes:
- logger.info("Killing running OSB processes")
+ logger.info("Killing running solr-benchmark processes")
- # Kill any lingering OSB processes before attempting to continue - the actor system needs to be a singleton on this machine
+ # Kill any lingering solr-benchmark processes before attempting to continue - the actor system needs to be a singleton on this machine
# noinspection PyBroadException
try:
process.kill_running_benchmark_instances()
except BaseException:
logger.exception(
- "Could not terminate potentially running OSB instances correctly. Attempting to go on anyway.")
+ "Could not terminate potentially running solr-benchmark instances correctly. Attempting to go on anyway.")
else:
other_benchmark_processes = process.find_all_other_benchmark_processes()
if other_benchmark_processes:
pids = [p.pid for p in other_benchmark_processes]
- msg = f"There are other OSB processes running on this machine (PIDs: {pids}) but only one OSB " \
+ msg = f"There are other solr-benchmark processes running on this machine (PIDs: {pids}) but only one " \
f"benchmark is allowed to run at the same time.\n\nYou can use --kill-running-processes flag " \
- f"to kill running processes automatically and allow OSB to continue to run a new benchmark. " \
+ f"to kill running processes automatically and allow solr-benchmark to continue to run a new benchmark. " \
f"Otherwise, you need to manually kill them."
raise exceptions.BenchmarkError(msg)
@@ -944,7 +969,7 @@ def with_actor_system(runnable, cfg):
except thespian.actors.InvalidActorAddress:
logger.info("Falling back to offline actor system.")
actor.use_offline_actor_system()
- actors = actor.bootstrap_actor_system(try_join=True)
+ actors = actor.bootstrap_actor_system(try_join=False, prefer_local_only=True)
except Exception as e:
logger.exception("Could not bootstrap actor system.")
if str(e) == "Unable to determine valid external socket address.":
@@ -952,7 +977,7 @@ def with_actor_system(runnable, cfg):
logger=logger)
logger.info("Falling back to offline actor system.")
actor.use_offline_actor_system()
- actors = actor.bootstrap_actor_system(try_join=True)
+ actors = actor.bootstrap_actor_system(try_join=False, prefer_local_only=True)
else:
raise
try:
@@ -983,7 +1008,7 @@ def with_actor_system(runnable, cfg):
except KeyboardInterrupt:
times_interrupted += 1
logger.warning("User interrupted shutdown of internal actor system.")
- console.info("Please wait a moment for OSB's internal components to shutdown.")
+ console.info("Please wait a moment for solr-benchmark's internal components to shutdown.")
if not shutdown_complete and times_interrupted > 0:
logger.warning("Terminating after user has interrupted actor system shutdown explicitly for [%d] times.",
times_interrupted)
@@ -996,7 +1021,7 @@ def with_actor_system(runnable, cfg):
console.println("")
elif not shutdown_complete:
console.warn("Could not terminate all internal processes within timeout. Please check and force-terminate "
- "all OSB processes.")
+ "all solr-benchmark processes.")
@@ -1054,6 +1079,14 @@ def configure_builder_params(args, cfg, command_requires_cluster_config=True):
cfg.add(config.Scope.applicationOverride, "builder",
"cluster_config.params", opts.to_dict(
args.cluster_config_params))
+ cfg.add(config.Scope.applicationOverride, "solr", "modules", getattr(args, "solr_modules", ""))
+ pipeline = getattr(args, "pipeline", None)
+ if pipeline == "benchmark-only" and args.cluster_config != "defaults":
+ raise SystemExit(
+ "ERROR: --cluster-config is only valid for provisioning pipelines "
+ "(from-distribution, docker, from-sources). "
+ "It cannot be used with the 'benchmark-only' pipeline."
+ )
def configure_connection_params(arg_parser, args, cfg):
@@ -1147,9 +1180,9 @@ def configure_test(arg_parser, args, cfg):
configure_builder_params(args, cfg)
cfg.add(config.Scope.applicationOverride, "builder", "runtime.jdk", args.runtime_jdk)
cfg.add(config.Scope.applicationOverride, "builder", "source.revision", args.revision)
- cfg.add(config.Scope.applicationOverride, "builder",
- "cluster_config_instance.plugins", opts.csv_to_list(
- args.opensearch_plugins))
+# cfg.add(config.Scope.applicationOverride, "builder",
+# "cluster_config_instance.plugins", opts.csv_to_list(
+# args.opensearch_plugins))
cfg.add(config.Scope.applicationOverride, "builder", "plugin.params", opts.to_dict(args.plugin_params))
cfg.add(config.Scope.applicationOverride, "builder", "preserve.install", convert.to_bool(args.preserve_install))
cfg.add(config.Scope.applicationOverride, "builder", "skip.rest.api.check", convert.to_bool(args.skip_rest_api_check))
@@ -1181,8 +1214,6 @@ def dispatch_sub_command(arg_parser, args, cfg):
configure_workload_params(arg_parser, args, cfg, command_requires_workload=False)
dispatch_list(cfg)
elif sub_command == "download":
- cfg.add(config.Scope.applicationOverride, "builder", "target.os", args.target_os)
- cfg.add(config.Scope.applicationOverride, "builder", "target.arch", args.target_arch)
configure_builder_params(args, cfg)
builder.download(cfg)
elif sub_command == "install":
@@ -1195,9 +1226,9 @@ def dispatch_sub_command(arg_parser, args, cfg):
cfg.add(config.Scope.applicationOverride, "builder", "node.name", args.node_name)
cfg.add(config.Scope.applicationOverride, "builder", "master.nodes", opts.csv_to_list(args.master_nodes))
cfg.add(config.Scope.applicationOverride, "builder", "seed.hosts", opts.csv_to_list(args.seed_hosts))
- cfg.add(config.Scope.applicationOverride, "builder",
- "cluster_config.plugins", opts.csv_to_list(
- args.opensearch_plugins))
+# cfg.add(config.Scope.applicationOverride, "builder",
+# "cluster_config.plugins", opts.csv_to_list(
+# args.opensearch_plugins))
cfg.add(config.Scope.applicationOverride, "builder", "plugin.params", opts.to_dict(args.plugin_params))
configure_builder_params(args, cfg)
builder.install(cfg)
@@ -1266,6 +1297,30 @@ def dispatch_sub_command(arg_parser, args, cfg):
# Always set visualize to true for the visualize command
cfg.add(config.Scope.applicationOverride, "workload", "visualize", True)
dispatch_visualize(cfg)
+ elif sub_command == "convert-workload":
+ from osbenchmark.conversion import workload_converter
+ source_dir = os.path.abspath(args.workload_path)
+ output_dir = os.path.abspath(args.output_path) if args.output_path else source_dir.rstrip("/") + "-solr"
+ force = getattr(args, "force", False)
+
+ if workload_converter.is_already_converted(output_dir) and not force:
+ console.info(
+ f"Workload already converted at: {output_dir}\n"
+ "Use --force to overwrite."
+ )
+ return True
+
+ console.info(f"Converting workload: {source_dir} → {output_dir}")
+ result = workload_converter.convert_opensearch_workload(source_dir, output_dir)
+
+ console.println(f"\nConversion complete: {result['output_dir']}")
+ if result["skipped"]:
+ console.println(f" Skipped operations ({len(result['skipped'])}): {', '.join(result['skipped'])}")
+ if result["issues"]:
+ console.println(f" Issues ({len(result['issues'])}):")
+ for issue in result["issues"]:
+ console.println(f" - {issue}")
+ console.println(f" See {os.path.join(result['output_dir'], workload_converter.CONVERTED_MARKER)} for details.")
elif sub_command == "info":
configure_workload_params(arg_parser, args, cfg)
workload.workload_info(cfg)
@@ -1305,8 +1360,8 @@ def handle_command_suggestions():
DEPRECATED_SUBCOMMANDS = ["execute-test", "execute"]
if len(sys.argv) > 1 and sys.argv[1] in DEPRECATED_SUBCOMMANDS:
console.info("Did you mean 'run'?")
- console.info("Example: opensearch-benchmark run --workload=geonames --test-mode")
- console.info("For more information, run: opensearch-benchmark run --help")
+ console.info(f"Example: {PROGRAM_NAME} run --workload=geonames --test-mode")
+ console.info(f"For more information, run: {PROGRAM_NAME} run --help")
return True
return False
@@ -1342,7 +1397,7 @@ def main():
logger.info("OS [%s]", str(platform.uname()))
logger.info("Python [%s]", str(sys.implementation))
- logger.info("OSB version [%s]", version.version())
+ logger.info("solr-benchmark version [%s]", version.version())
logger.debug("Command line arguments: %s", args)
# Configure networking
net.init()
diff --git a/osbenchmark/benchmarkd.py b/osbenchmark/benchmarkd.py
index ebc7d1d3..f1637654 100644
--- a/osbenchmark/benchmarkd.py
+++ b/osbenchmark/benchmarkd.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -81,8 +84,8 @@ def main():
console.init(assume_tty=False)
parser = argparse.ArgumentParser(prog=PROGRAM_NAME,
- description=BANNER + "\n\n OSB daemon to support remote benchmarks",
- epilog="Find out more about OSB at {}".format(console.format.link(doc_link())),
+ description=BANNER + "\n\n ASB daemon to support remote benchmarks",
+ epilog="Find out more about ASB at {}".format(console.format.link(doc_link())),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--version', action='version', version="%(prog)s " + version.version())
@@ -92,8 +95,8 @@ def main():
help="")
subparsers.required = True
- start_command = subparsers.add_parser("start", help="Starts the OSB daemon")
- restart_command = subparsers.add_parser("restart", help="Restarts the OSB daemon")
+ start_command = subparsers.add_parser("start", help="Starts the ASB daemon")
+ restart_command = subparsers.add_parser("restart", help="Restarts the ASB daemon")
for p in [start_command, restart_command]:
p.add_argument(
"--node-ip",
@@ -104,8 +107,8 @@ def main():
required=True,
help="The IP of the coordinator node."
)
- subparsers.add_parser("stop", help="Stops the OSB daemon")
- subparsers.add_parser("status", help="Shows the current status of the local OSB daemon")
+ subparsers.add_parser("stop", help="Stops the ASB daemon")
+ subparsers.add_parser("status", help="Shows the current status of the local ASB daemon")
args = parser.parse_args()
diff --git a/osbenchmark/builder/__init__.py b/osbenchmark/builder/__init__.py
index 9ceaced0..8e1a69cc 100644
--- a/osbenchmark/builder/__init__.py
+++ b/osbenchmark/builder/__init__.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
diff --git a/osbenchmark/builder/builder.py b/osbenchmark/builder/builder.py
index 85c79aff..206374e5 100644
--- a/osbenchmark/builder/builder.py
+++ b/osbenchmark/builder/builder.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -32,7 +35,10 @@ import traceback
from collections import defaultdict
import thespian.actors
-from opensearchpy.exceptions import NotFoundError
+
+
+class NotFoundError(Exception):
+ pass
from osbenchmark import (PROGRAM_NAME, actor, client, config, exceptions,
metrics, paths)
@@ -45,9 +51,9 @@ METRIC_FLUSH_INTERVAL_SECONDS = 30
def download(cfg):
- cluster_config, plugins = load_cluster_config(cfg, external=False)
+ cluster_config, _ = load_cluster_config(cfg, external=False)
- s = supplier.create(cfg, sources=False, distribution=True, cluster_config=cluster_config, plugins=plugins)
+ s = supplier.create(cfg, sources=False, cluster_config=cluster_config)
binaries = s()
console.println(json.dumps(binaries, indent=2), force=True)
@@ -75,15 +81,15 @@ def install(cfg):
master_nodes = [node_name]
if build_type == "tar":
- binary_supplier = supplier.create(cfg, sources, distribution, cluster_config, plugins)
- p = provisioner.local(cfg=cfg, cluster_config=cluster_config, plugins=plugins, ip=ip, http_port=http_port,
+ binary_supplier = supplier.create(cfg, sources, cluster_config)
+ p = provisioner.local(cfg=cfg, cluster_config=cluster_config, ip=ip, http_port=http_port,
all_node_ips=seed_hosts, all_node_names=master_nodes, target_root=root_path,
node_name=node_name)
node_config = p.prepare(binary=binary_supplier())
elif build_type == "docker":
if len(plugins) > 0:
raise exceptions.SystemSetupError("You cannot specify any plugins for Docker clusters. Please remove "
- "\"--opensearch-plugins\" and try again.")
+ "\"--plugins\" and try again.")
p = provisioner.docker(
cfg=cfg, cluster_config=cluster_config,
ip=ip, http_port=http_port, target_root=root_path, node_name=node_name)
@@ -263,33 +269,21 @@ class NodesStopped:
pass
-def cluster_distribution_version(cfg, client_factory=client.OsClientFactory):
+def cluster_distribution_version(cfg, client_factory=client.ClientFactory):
"""
Attempt to get the cluster's distribution version even before it is actually started (which makes only sense for externally
provisioned clusters).
:param cfg: The current config object.
- :param client_factory: Factory class that creates the OpenSearch client.
+ :param client_factory: Factory class that creates the client.
:return: The distribution version.
"""
hosts = cfg.opts("client", "hosts").default
client_options = cfg.opts("client", "options").default
- opensearch = client_factory(hosts, client_options).create()
- # unconditionally wait for the REST layer - if it's not up by then, we'll intentionally raise the original error
- client.wait_for_rest_layer(opensearch)
- try:
- info = opensearch.info()
- distribution_version = info["version"]["number"]
- except NotFoundError as e:
- if e.status_code == 404:
- console.info("Root url not found, setting distribution version to oss")
- distribution_version = "oss"
- else:
- distribution_version = None
- except Exception:
- console.warn("Could not determine distribution version from endpoint, use --distribution-version to specify")
- distribution_version = None
- return distribution_version
+ client_instance = client_factory(hosts, client_options).create()
+ if isinstance(client_instance, client.SolrClient):
+ return "9.10.1"
+ return None
def to_ip_port(hosts):
@@ -297,10 +291,10 @@ def to_ip_port(hosts):
for host in hosts:
host = host.copy()
host_or_ip = host.pop("host")
- port = host.pop("port", 9200)
+ port = host.pop("port", 8983)
if host:
- raise exceptions.SystemSetupError("When specifying nodes to be managed by OSB you can only supply "
- "hostname:port pairs (e.g. 'localhost:9200'), any additional options cannot "
+ raise exceptions.SystemSetupError("When specifying nodes to be managed by solr-benchmark you can only supply "
+ "hostname:port pairs (e.g. 'localhost:8983'), any additional options cannot "
"be supported.")
ip = net.resolve(host_or_ip)
ip_port_pairs.append((ip, port))
@@ -364,7 +358,7 @@ class BuilderActor(actor.BenchmarkActor):
self.logger.info("BuilderActor#receiveMessage poison(msg = [%s] sender = [%s])", str(msg.poisonMessage), str(sender))
# something went wrong with a child actor (or another actor with which we have communicated)
if isinstance(msg.poisonMessage, StartEngine):
- failmsg = "Could not start benchmark candidate. Are OSB daemons on all targeted machines running?"
+ failmsg = "Could not start benchmark candidate. Are ASB daemons on all targeted machines running?"
else:
failmsg = msg.details
self.logger.error(failmsg)
@@ -386,14 +380,14 @@ class BuilderActor(actor.BenchmarkActor):
self.externally_provisioned = msg.external
if self.externally_provisioned:
- self.logger.info("Cluster will not be provisioned by OSB.")
+ self.logger.info("Cluster will not be provisioned by ASB.")
self.status = "nodes_started"
self.received_responses = []
self.on_all_nodes_started()
self.status = "cluster_started"
else:
console.info("Preparing for test run ...", flush=True)
- self.logger.info("Cluster consisting of %s will be provisioned by OSB.", hosts)
+ self.logger.info("Cluster consisting of %s will be provisioned by ASB.", hosts)
msg.hosts = hosts
# Initialize the children array to have the right size to
# ensure waiting for all responses
@@ -510,12 +504,12 @@ class Dispatcher(actor.BenchmarkActor):
def receiveMsg_ActorSystemConventionUpdate(self, convmsg, sender):
if not convmsg.remoteAdded:
- self.logger.warning("Remote OSB node [%s] exited during NodeBuilderActor startup process.", convmsg.remoteAdminAddress)
+ self.logger.warning("Remote ASB node [%s] exited during NodeBuilderActor startup process.", convmsg.remoteAdminAddress)
self.start_sender(actor.BenchmarkFailure(
- "Remote OSB node [%s] has been shutdown prematurely." % convmsg.remoteAdminAddress))
+ "Remote ASB node [%s] has been shutdown prematurely." % convmsg.remoteAdminAddress))
else:
remote_ip = convmsg.remoteCapabilities.get('ip', None)
- self.logger.info("Remote OSB node [%s] has started.", remote_ip)
+ self.logger.info("Remote ASB node [%s] has started.", remote_ip)
for eachmsg in self.remotes[remote_ip]:
self.pending.append((self.createActor(NodeBuilderActor,
@@ -642,6 +636,8 @@ def load_cluster_config(cfg, external):
plugins = cc.load_plugins(cluster_config_path,
cfg.opts("builder", "cluster_config.plugins", mandatory=False),
cfg.opts("builder", "plugin.params", mandatory=False))
+ # Store cluster_config_instance in config for TestRun to access (for result metadata)
+ cfg.add(config.Scope.applicationOverride, "builder", "cluster_config.instance", cluster_config)
return cluster_config, plugins
@@ -653,21 +649,21 @@ def create(cfg, metrics_store, node_ip, node_http_port, all_node_ips, all_node_i
cluster_config, plugins = load_cluster_config(cfg, external)
if sources or distribution:
- s = supplier.create(cfg, sources, distribution, cluster_config, plugins)
+ s = supplier.create(cfg, sources, cluster_config)
p = []
all_node_names = ["%s-%s" % (node_name_prefix, n) for n in all_node_ids]
for node_id in node_ids:
node_name = "%s-%s" % (node_name_prefix, node_id)
p.append(
- provisioner.local(cfg, cluster_config, plugins, node_ip, node_http_port, all_node_ips,
+ provisioner.local(cfg, cluster_config, node_ip, node_http_port, all_node_ips,
all_node_names, test_run_root_path, node_name))
l = launcher.ProcessLauncher(cfg)
elif external:
- raise exceptions.BenchmarkAssertionError("Externally provisioned clusters should not need to be managed by OSB's builder")
+ raise exceptions.BenchmarkAssertionError("Externally provisioned clusters should not need to be managed by ASB's builder")
elif docker:
if len(plugins) > 0:
raise exceptions.SystemSetupError("You cannot specify any plugins for Docker clusters. Please remove "
- "\"--opensearch-plugins\" and try again.")
+ "\"--plugin-params\" and try again.")
s = lambda: None
p = []
for node_id in node_ids:
diff --git a/osbenchmark/builder/cluster.py b/osbenchmark/builder/cluster.py
index ee523b1d..22802db9 100644
--- a/osbenchmark/builder/cluster.py
+++ b/osbenchmark/builder/cluster.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -25,7 +28,7 @@
class Node:
"""
- Represents an OpenSearch cluster node.
+ Represents a Solr cluster node.
"""
def __init__(self, pid, binary_path, host_name, node_name, telemetry):
diff --git a/osbenchmark/builder/cluster_config.py b/osbenchmark/builder/cluster_config.py
index f92cb5e2..fdbcab82 100644
--- a/osbenchmark/builder/cluster_config.py
+++ b/osbenchmark/builder/cluster_config.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -97,15 +100,6 @@ def load_cluster_config(repo, name, cluster_config_params=None):
return ClusterConfigInstance(name, root_path, all_config_paths, variables=variables)
-def list_plugins(cfg):
- plugins = PluginLoader(cluster_config_path(cfg)).plugins()
- if plugins:
- console.println("Available OpenSearch plugins:\n")
- console.println(tabulate.tabulate([[p.name, p.config] for p in plugins], headers=["Name", "Configuration"]))
- else:
- console.println("No OpenSearch plugins are available.\n")
-
-
def load_plugin(repo, name, config, plugin_params=None):
return PluginLoader(repo).load_plugin(name, config, plugin_params)
@@ -390,11 +384,11 @@ class PluginLoader:
if not io.exists(config_file):
if core_plugin:
raise exceptions.SystemSetupError("Plugin [%s] does not provide configuration [%s]. List the available plugins "
- "and configurations with %s list opensearch-plugins "
+ "and configurations with %s list cluster-configs "
"--distribution-version=VERSION." % (name, config_name, PROGRAM_NAME))
else:
raise exceptions.SystemSetupError("Unknown plugin [%s]. List the available plugins with %s list "
- "opensearch-plugins --distribution-version=VERSION." % (name, PROGRAM_NAME))
+ "cluster-configs --distribution-version=VERSION." % (name, PROGRAM_NAME))
config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
# Do not modify the case of option keys but read them as is
@@ -481,8 +475,7 @@ class BootstrapHookHandler:
:param loader_class: The implementation that loads the provided component's code.
"""
self.component = component
- # Don't allow the loader to recurse. The subdirectories may contain OpenSearch specific files which we do not want to add to
- # OSB's Python load path. We may need to define a more advanced strategy in the future.
+ # Don't allow the loader to recurse.
self.loader = loader_class(root_path=self.component.root_path, component_entry_point=self.component.entry_point, recurse=False)
self.hooks = {}
self.logger = logging.getLogger(__name__)
diff --git a/osbenchmark/builder/downloaders/core_plugin_source_downloader.py b/osbenchmark/builder/downloaders/core_plugin_source_downloader.py
deleted file mode 100644
index 08e65a09..00000000
--- a/osbenchmark/builder/downloaders/core_plugin_source_downloader.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from osbenchmark.builder.downloaders.downloader import Downloader
-
-
-class CorePluginSourceDownloader(Downloader):
- def __init__(self, plugin, executor, source_repository_provider, binary_builder, opensearch_source_dir):
- super().__init__(executor)
- self.plugin = plugin
- self.source_repository_provider = source_repository_provider
- self.binary_builder = binary_builder
- self.opensearch_source_dir = opensearch_source_dir
-
- def download(self, host):
- self._fetch(host)
- self._prepare(host)
-
- return {self.plugin.name: self._get_zip_path()}
-
- def _fetch(self, host):
- return self.source_repository_provider.fetch_repository(host, None, "current", self.opensearch_source_dir)
-
- def _prepare(self, host):
- if self.binary_builder:
- self.binary_builder.build(host, [f"gradlew :plugins:{self.plugin.name}:assemble"])
-
- def _get_zip_path(self):
- return f"file://{self.opensearch_source_dir}/plugins/{self.plugin.name}/build/distributions/*.zip"
diff --git a/osbenchmark/builder/downloaders/opensearch_distribution_downloader.py b/osbenchmark/builder/downloaders/distribution_downloader.py
similarity index 58%
rename from osbenchmark/builder/downloaders/opensearch_distribution_downloader.py
rename to osbenchmark/builder/downloaders/distribution_downloader.py
index 4af29cdd..b9e078b0 100644
--- a/osbenchmark/builder/downloaders/opensearch_distribution_downloader.py
+++ b/osbenchmark/builder/downloaders/distribution_downloader.py
@@ -1,3 +1,20 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import logging
import os.path
@@ -6,7 +23,7 @@ from osbenchmark.builder.utils.binary_keys import BinaryKeys
from osbenchmark.exceptions import ExecutorError
-class OpenSearchDistributionDownloader(Downloader):
+class DistributionDownloader(Downloader):
def __init__(self, cluster_config, executor, path_manager, distribution_repository_provider):
super().__init__(executor)
self.logger = logging.getLogger(__name__)
@@ -16,21 +33,21 @@ class OpenSearchDistributionDownloader(Downloader):
def download(self, host):
binary_path = self._fetch_binary(host)
- return {BinaryKeys.OPENSEARCH: binary_path}
+ return {BinaryKeys.SOLR: binary_path}
def _fetch_binary(self, host):
download_url = self.distribution_repository_provider.get_download_url(host)
distribution_path = self._create_distribution_path(host, download_url)
- opensearch_version = self.cluster_config.variables["distribution"]["version"]
+ version = self.cluster_config.variables["distribution"]["version"]
is_binary_present = self._is_binary_present(host, distribution_path)
is_cache_enabled = self.distribution_repository_provider.is_cache_enabled()
if is_binary_present and is_cache_enabled:
- self.logger.info("Skipping download for version [%s]. Found existing binary at [%s].", opensearch_version,
+ self.logger.info("Skipping download for version [%s]. Found existing binary at [%s].", version,
distribution_path)
else:
- self._download_opensearch(host, distribution_path, download_url, opensearch_version)
+ self._download(host, distribution_path, download_url, version)
return distribution_path
@@ -48,15 +65,15 @@ class OpenSearchDistributionDownloader(Downloader):
except ExecutorError:
return False
- def _download_opensearch(self, host, distribution_path, download_url, opensearch_version):
- self.logger.info("Resolved download URL [%s] for version [%s]", download_url, opensearch_version)
- self.logger.info("Starting download of OpenSearch [%s]", opensearch_version)
+ def _download(self, host, distribution_path, download_url, version):
+ self.logger.info("Resolved download URL [%s] for version [%s]", download_url, version)
+ self.logger.info("Starting download of distribution [%s]", version)
try:
self.executor.execute(host, f"curl -o {distribution_path} {download_url}")
except ExecutorError as e:
- self.logger.exception("Exception downloading OpenSearch distribution for version [%s] from [%s].",
- opensearch_version, download_url)
+ self.logger.exception("Exception downloading distribution for version [%s] from [%s].",
+ version, download_url)
raise e
- self.logger.info("Successfully downloaded OpenSearch [%s].", opensearch_version)
+ self.logger.info("Successfully downloaded distribution [%s].", version)
diff --git a/osbenchmark/builder/downloaders/downloader.py b/osbenchmark/builder/downloaders/downloader.py
index 035fe00e..731b8010 100644
--- a/osbenchmark/builder/downloaders/downloader.py
+++ b/osbenchmark/builder/downloaders/downloader.py
@@ -1,10 +1,37 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
from abc import ABC, abstractmethod
class Downloader(ABC):
"""
- A downloader is used to supply the necessary components for running self-managed OpenSearch. Implementations of this
- interface will download distributions or fetch from a source repository for both OpenSearch and plugins
+ A downloader is used to supply the necessary components for running self-managed Solr. Implementations of this
+ interface will download distributions or fetch from a source repository for Solr
"""
def __init__(self, executor):
self.executor = executor
@@ -12,7 +39,7 @@ class Downloader(ABC):
@abstractmethod
def download(self, host):
"""
- Downloads the relevant data necessary to install and run OpenSearch
+ Downloads the relevant data necessary to install and run Solr
;param host: A Host object defining the host on which the data should be downloaded
;return binaries: A map of component names to installation paths for use by the Installer
diff --git a/osbenchmark/builder/downloaders/external_plugin_source_downloader.py b/osbenchmark/builder/downloaders/external_plugin_source_downloader.py
deleted file mode 100644
index c6af55b2..00000000
--- a/osbenchmark/builder/downloaders/external_plugin_source_downloader.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from osbenchmark.builder.downloaders.downloader import Downloader
-
-
-class ExternalPluginSourceDownloader(Downloader):
- def __init__(self, plugin_config_instance, executor, source_repository_provider, binary_builder, plugin_source_directory):
- super().__init__(executor)
- self.plugin_config_instance = plugin_config_instance
- self.source_repository_provider = source_repository_provider
- self.binary_builder = binary_builder
- self.plugin_source_directory = plugin_source_directory
-
- def download(self, host):
- self._fetch(host)
- self._prepare(host)
-
- return {self.plugin_config_instance.name: self._get_zip_path()}
-
- def _fetch(self, host):
- plugin_remote_url = self.plugin_config_instance.variables["source"]["remote"]["repo"]["url"]
- plugin_revision = self.plugin_config_instance.variables["source"]["revision"]
- self.source_repository_provider.fetch_repository(host, plugin_remote_url, plugin_revision, self.plugin_source_directory)
-
- def _prepare(self, host):
- if self.binary_builder:
- build_command = self.plugin_config_instance.variables["source"]["build"]["command"]
- self.binary_builder.build(host, [build_command], override_source_directory=self.plugin_source_directory)
-
- def _get_zip_path(self):
- artifact_path = self.plugin_config_instance.variables["source"]["build"]["artifact"]["subdir"]
- return f"file://{self.plugin_source_directory}/{artifact_path}/*.zip"
diff --git a/osbenchmark/builder/downloaders/plugin_distribution_downloader.py b/osbenchmark/builder/downloaders/plugin_distribution_downloader.py
deleted file mode 100644
index c1770d66..00000000
--- a/osbenchmark/builder/downloaders/plugin_distribution_downloader.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from osbenchmark.builder.downloaders.downloader import Downloader
-
-
-class PluginDistributionDownloader(Downloader):
- def __init__(self, plugin, executor, distribution_repository_provider):
- super().__init__(executor)
- self.plugin = plugin
- self.distribution_repository_provider = distribution_repository_provider
-
- def download(self, host):
- plugin_url = self.distribution_repository_provider.get_download_url(host)
- return {self.plugin.name: plugin_url} if plugin_url else {}
diff --git a/osbenchmark/builder/downloaders/repositories/opensearch_distribution_repository_provider.py b/osbenchmark/builder/downloaders/repositories/distribution_repository_provider.py
similarity index 51%
rename from osbenchmark/builder/downloaders/repositories/opensearch_distribution_repository_provider.py
rename to osbenchmark/builder/downloaders/repositories/distribution_repository_provider.py
index f1375b63..3840cf6f 100644
--- a/osbenchmark/builder/downloaders/repositories/opensearch_distribution_repository_provider.py
+++ b/osbenchmark/builder/downloaders/repositories/distribution_repository_provider.py
@@ -1,24 +1,34 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import logging
from osbenchmark.utils import convert
-class OpenSearchDistributionRepositoryProvider:
+class DistributionRepositoryProvider:
def __init__(self, cluster_config, repository_url_provider):
self.logger = logging.getLogger(__name__)
self.cluster_config = cluster_config
self.repository_url_provider = repository_url_provider
def get_download_url(self, host):
- is_runtime_jdk_bundled = self.cluster_config.variables["system"]["runtime"]["jdk"]["bundled"]
distribution_repository = self.cluster_config.variables["distribution"]["repository"]
-
- self.logger.info("runtime_jdk_bundled? [%s]", is_runtime_jdk_bundled)
- if is_runtime_jdk_bundled:
- url_key = f"distribution.jdk.bundled.{distribution_repository}_url"
- else:
- url_key = f"distribution.jdk.unbundled.{distribution_repository}_url"
-
+ url_key = f"distribution.{distribution_repository}_url"
self.logger.info("key: [%s]", url_key)
return self.repository_url_provider.render_url_for_key(host, self.cluster_config.variables, url_key)
diff --git a/osbenchmark/builder/downloaders/opensearch_source_downloader.py b/osbenchmark/builder/downloaders/source_downloader.py
similarity index 57%
rename from osbenchmark/builder/downloaders/opensearch_source_downloader.py
rename to osbenchmark/builder/downloaders/source_downloader.py
index 4f36c437..15cf027b 100644
--- a/osbenchmark/builder/downloaders/opensearch_source_downloader.py
+++ b/osbenchmark/builder/downloaders/source_downloader.py
@@ -1,3 +1,20 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import logging
import os
@@ -5,7 +22,7 @@ from osbenchmark.builder.downloaders.downloader import Downloader
from osbenchmark.builder.utils.binary_keys import BinaryKeys
-class OpenSearchSourceDownloader(Downloader):
+class SourceDownloader(Downloader):
def __init__(self, cluster_config, executor, source_repository_provider, binary_builder, template_renderer,
artifact_variables_provider):
super().__init__(executor)
@@ -17,24 +34,24 @@ class OpenSearchSourceDownloader(Downloader):
self.artifact_variables_provider = artifact_variables_provider
def download(self, host):
- opensearch_source_path = self._get_opensearch_source_path()
- self._fetch(host, opensearch_source_path)
+ source_path = self._get_source_path()
+ self._fetch(host, source_path)
artifact_variables = self.artifact_variables_provider.get_artifact_variables(host)
self._prepare(host, artifact_variables)
- return {BinaryKeys.OPENSEARCH: self._get_zip_path(opensearch_source_path, artifact_variables)}
+ return {BinaryKeys.SOLR: self._get_zip_path(source_path, artifact_variables)}
- def _get_opensearch_source_path(self):
+ def _get_source_path(self):
node_root_dir = self.cluster_config.variables["source"]["root"]["dir"]
- opensearch_source_subdir = self.cluster_config.variables["source"]["opensearch"]["subdir"]
- return os.path.join(node_root_dir, opensearch_source_subdir)
+ source_subdir = self.cluster_config.variables["source"]["solr"]["subdir"]
+ return os.path.join(node_root_dir, source_subdir)
- def _fetch(self, host, opensearch_source_path):
+ def _fetch(self, host, source_path):
plugin_remote_url = self.cluster_config.variables["source"]["remote"]["repo"]["url"]
plugin_revision = self.cluster_config.variables["source"]["revision"]
- self.source_repository_provider.fetch_repository(host, plugin_remote_url, plugin_revision, opensearch_source_path)
+ self.source_repository_provider.fetch_repository(host, plugin_remote_url, plugin_revision, source_path)
def _prepare(self, host, artifact_variables):
clean_command_template = self.cluster_config.variables["source"]["clean"]["command"]
@@ -46,8 +63,8 @@ class OpenSearchSourceDownloader(Downloader):
self.template_renderer.render_template_string(build_command_template, artifact_variables)
])
- def _get_zip_path(self, opensearch_source_path, artifact_variables):
+ def _get_zip_path(self, source_path, artifact_variables):
artifact_path_pattern_template = self.cluster_config.variables["source"]["artifact_path_pattern"]
artifact_path_pattern = self.template_renderer.render_template_string(artifact_path_pattern_template, artifact_variables)
- return os.path.join(opensearch_source_path, artifact_path_pattern)
+ return os.path.join(source_path, artifact_path_pattern)
diff --git a/osbenchmark/builder/installers/bare_installer.py b/osbenchmark/builder/installers/bare_installer.py
index f94c178c..e902feb9 100644
--- a/osbenchmark/builder/installers/bare_installer.py
+++ b/osbenchmark/builder/installers/bare_installer.py
@@ -1,5 +1,31 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
from osbenchmark.builder.installers.installer import Installer
-from osbenchmark.builder.installers.preparers.plugin_preparer import PluginPreparer
from osbenchmark.builder.cluster_config import BootstrapPhase
from osbenchmark.builder.utils.config_applier import ConfigApplier
from osbenchmark.builder.utils.java_home_resolver import JavaHomeResolver
@@ -41,12 +67,6 @@ class BareInstaller(Installer):
for preparer, node in preparer_to_node.items():
config_vars.update(preparer.get_config_vars(host, node, all_node_ips))
- plugin_names = [preparer.get_plugin_name() for preparer in self.preparers if isinstance(preparer, PluginPreparer)]
- if plugin_names:
- # as a safety measure, prevent the cluster to startup if something went wrong during plugin installation
- config_vars["cluster_settings"] = {}
- config_vars["cluster_settings"]["plugin.mandatory"] = plugin_names
-
return config_vars
def _apply_configs(self, host, preparer_to_node, config_vars):
diff --git a/osbenchmark/builder/installers/docker_installer.py b/osbenchmark/builder/installers/docker_installer.py
index 8e33db5e..dcb9de52 100644
--- a/osbenchmark/builder/installers/docker_installer.py
+++ b/osbenchmark/builder/installers/docker_installer.py
@@ -1,3 +1,30 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
import logging
import os
import uuid
@@ -70,15 +97,15 @@ class DockerInstaller(Installer):
"cluster_name": self.cluster_config.variables["cluster_name"],
"node_name": node.name,
# we bind-mount the directories below on the host to these ones.
- "install_root_path": "/usr/share/opensearch",
- "data_paths": ["/usr/share/opensearch/data"],
- "log_path": "/var/log/opensearch",
- "heap_dump_path": "/usr/share/opensearch/heapdump",
+ "install_root_path": "/var/solr",
+ "data_paths": ["/var/solr/data"],
+ "log_path": "/var/solr/logs",
+ "heap_dump_path": "/var/solr/heapdump",
# Docker container needs to expose service on external interfaces
"network_host": "0.0.0.0",
"discovery_type": "single-node",
"http_port": str(node.port),
- "transport_port": str(node.port + 100),
+ "zookeeper_port": str(node.port + 1000),
"cluster_settings": {}
}
@@ -90,12 +117,12 @@ class DockerInstaller(Installer):
def _get_docker_vars(self, node, mounts):
docker_vars = {
- "os_version": self.cluster_config.variables["origin"]["distribution"]["version"],
+ "solr_version": self.cluster_config.variables["origin"]["distribution"]["version"],
"docker_image": self.cluster_config.variables["origin"]["docker"]["docker_image"],
"http_port": node.port,
- "os_data_dir": node.data_paths[0],
- "os_log_dir": node.log_path,
- "os_heap_dump_dir": node.heap_dump_path,
+ "solr_data_dir": node.data_paths[0],
+ "solr_log_dir": node.log_path,
+ "solr_heap_dump_dir": node.heap_dump_path,
"mounts": mounts
}
self._add_if_defined_for_cluster_config(docker_vars, "docker_mem_limit")
diff --git a/osbenchmark/builder/installers/installer.py b/osbenchmark/builder/installers/installer.py
index f1f6276e..4cb5e116 100644
--- a/osbenchmark/builder/installers/installer.py
+++ b/osbenchmark/builder/installers/installer.py
@@ -1,10 +1,36 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
from abc import ABC, abstractmethod
class Installer(ABC):
"""
- Installers are invoked to prepare the OpenSearch and Plugin data that exists on a host so that an OpenSearch cluster
- can be started.
+ Installers are invoked to prepare Solr data that exists on a host so that a Solr cluster can be started.
"""
def __init__(self, executor):
@@ -13,7 +39,7 @@ class Installer(ABC):
@abstractmethod
def install(self, host, binaries, all_node_ips):
"""
- Executes the necessary logic to prepare and install OpenSearch and any request Plugins on a cluster host
+ Executes the necessary logic to prepare and install Solr on a cluster host
;param host: A Host object defining the host on which to install the data
;param binaries: A map of components to install to their paths on the host
diff --git a/osbenchmark/builder/installers/preparers/opensearch_preparer.py b/osbenchmark/builder/installers/preparers/opensearch_preparer.py
deleted file mode 100644
index 3d7b2244..00000000
--- a/osbenchmark/builder/installers/preparers/opensearch_preparer.py
+++ /dev/null
@@ -1,105 +0,0 @@
-import logging
-import os
-import uuid
-
-from osbenchmark.builder.installers.preparers.preparer import Preparer
-from osbenchmark.builder.models.node import Node
-from osbenchmark.builder.utils.binary_keys import BinaryKeys
-from osbenchmark.builder.utils.host_cleaner import HostCleaner
-from osbenchmark.builder.utils.path_manager import PathManager
-
-
-class OpenSearchPreparer(Preparer):
- def __init__(self, cluster_config, executor, hook_handler_class):
- super().__init__(executor)
- self.logger = logging.getLogger(__name__)
- self.cluster_config = cluster_config
- self.hook_handler = hook_handler_class(self.cluster_config)
- if self.hook_handler.can_load():
- self.hook_handler.load()
- self.path_manager = PathManager(executor)
- self.host_cleaner = HostCleaner(self.path_manager)
-
- def prepare(self, host, binaries):
- node = self._create_node()
- self._prepare_node(host, node, binaries[BinaryKeys.OPENSEARCH])
-
- return node
-
- def _create_node(self):
- node_name = str(uuid.uuid4())
- node_port = int(self.cluster_config.variables["node"]["port"])
- node_root_dir = os.path.join(self.cluster_config.variables["test_run_root"], node_name)
- node_binary_path = os.path.join(node_root_dir, "install")
- node_log_dir = os.path.join(node_root_dir, "logs", "server")
- node_heap_dump_dir = os.path.join(node_root_dir, "heapdump")
-
- return Node(name=node_name,
- port=node_port,
- pid=None,
- root_dir=node_root_dir,
- binary_path=node_binary_path,
- log_path=node_log_dir,
- heap_dump_path=node_heap_dump_dir,
- data_paths=None,
- telemetry=None)
-
- def _prepare_node(self, host, node, binary):
- self._prepare_directories(host, node)
- self._extract_opensearch(host, node, binary)
- self._update_node_binary_path(node)
- self._set_node_data_paths(node)
- # we need to immediately delete the prebundled config files as plugins may copy their configuration during installation.
- self._delete_prebundled_config_files(host, node)
-
- def _prepare_directories(self, host, node):
- directories_to_create = [node.binary_path, node.log_path, node.heap_dump_path]
- for directory_to_create in directories_to_create:
- self.path_manager.create_path(host, directory_to_create)
-
- def _extract_opensearch(self, host, node, binary):
- self.logger.info("Unzipping %s to %s", binary, node.binary_path)
- self.executor.execute(host, f"tar -xzvf {binary} --directory {node.binary_path}")
-
- def _update_node_binary_path(self, node):
- node.binary_path = os.path.join(node.binary_path, "opensearch*")
-
- def _set_node_data_paths(self, node):
- node.data_paths = [os.path.join(node.binary_path, "data")]
-
- def _delete_prebundled_config_files(self, host, node):
- config_path = os.path.join(node.binary_path, "config")
- self.logger.info("Deleting pre-bundled OpenSearch configuration at [%s]", config_path)
- self.path_manager.delete_path(host, config_path)
-
- def get_config_vars(self, host, node, all_node_ips):
- installer_defaults = {
- "cluster_name": self.cluster_config.variables["cluster_name"],
- "node_name": node.name,
- "data_paths": node.data_paths[0],
- "log_path": node.log_path,
- "heap_dump_path": node.heap_dump_path,
- # this is the node's IP address as specified by the user when invoking OSB
- "node_ip": host.address,
- # this is the IP address that the node will be bound to. OSB will bind to the node's IP address (but not to 0.0.0.0). The
- "network_host": host.address,
- "http_port": str(node.port),
- "transport_port": str(node.port + 100),
- "all_node_ips": "[\"%s\"]" % "\",\"".join(all_node_ips),
- # at the moment we are strict and enforce that all nodes are master eligible nodes
- "minimum_master_nodes": len(all_node_ips),
- "install_root_path": node.binary_path
- }
- config_vars = {}
- config_vars.update(self.cluster_config.variables)
- config_vars.update(installer_defaults)
- return config_vars
-
- def get_config_paths(self):
- return self.cluster_config.config_paths
-
- def invoke_install_hook(self, host, phase, variables, env):
- self.hook_handler.invoke(phase.name, variables=variables, env=env)
-
- def cleanup(self, host):
- self.host_cleaner.cleanup(host, self.cluster_config.variables["preserve_install"])
diff --git a/osbenchmark/builder/installers/preparers/plugin_preparer.py b/osbenchmark/builder/installers/preparers/plugin_preparer.py
deleted file mode 100644
index 1f77042c..00000000
--- a/osbenchmark/builder/installers/preparers/plugin_preparer.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import logging
-import os
-
-from osbenchmark.builder.installers.preparers.preparer import Preparer
-
-
-class PluginPreparer(Preparer):
- def __init__(self, plugin, executor, hook_handler_class):
- super().__init__(executor)
- self.logger = logging.getLogger(__name__)
- self.plugin = plugin
- self.hook_handler = hook_handler_class(self.plugin)
- if self.hook_handler.can_load():
- self.hook_handler.load()
-
- def prepare(self, host, binaries):
- install_cmd = self._get_install_command(host, binaries)
- self.executor.execute(host, install_cmd)
-
- def _get_install_command(self, host, binaries):
- installer_binary_path = os.path.join(host.node.binary_path, "bin", "opensearch-plugin")
- plugin_binary_path = binaries.get(self.plugin.name)
-
- if plugin_binary_path:
- self.logger.info("Installing [%s] into [%s] from [%s]", self.plugin.name, host.node.binary_path, plugin_binary_path)
- return '%s install --batch "%s"' % (installer_binary_path, plugin_binary_path)
- else:
- self.logger.info("Installing [%s] into [%s]", self.plugin.name, host.node.binary_path)
- return '%s install --batch "%s"' % (installer_binary_path, self.plugin.name)
-
- def get_config_vars(self, host, node, all_node_ips):
- return self.plugin.variables
-
- def get_plugin_name(self):
- return self.plugin.name
-
- def get_config_paths(self):
- return self.plugin.config_paths
-
- def invoke_install_hook(self, host, phase, variables, env):
- self.hook_handler.invoke(phase.name, variables=variables, env=env)
-
- def cleanup(self, host):
- pass
diff --git a/osbenchmark/builder/java_resolver.py b/osbenchmark/builder/java_resolver.py
index 9e80a2b6..939b8df7 100644
--- a/osbenchmark/builder/java_resolver.py
+++ b/osbenchmark/builder/java_resolver.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -25,10 +28,10 @@
import logging
from osbenchmark import exceptions
-from osbenchmark.utils import jvm, sysstats
+from osbenchmark.utils import jvm
-def java_home(cluster_config_runtime_jdks, specified_runtime_jdk=None, provides_bundled_jdk=False):
+def java_home(cluster_config_runtime_jdks, specified_runtime_jdk=None):
def determine_runtime_jdks():
if specified_runtime_jdk:
return [specified_runtime_jdk]
@@ -52,25 +55,5 @@ def java_home(cluster_config_runtime_jdks, specified_runtime_jdk=None, provides_
runtime_jdk_versions = determine_runtime_jdks()
- if runtime_jdk_versions[0] == "bundled":
- if not provides_bundled_jdk:
- raise exceptions.SystemSetupError("This OpenSearch version does not contain a bundled JDK. "
- "Please specify a different runtime JDK.")
- logger.info("Using JDK bundled with OpenSearch.")
-
- os_check = sysstats.os_name()
- if os_check == "Windows":
- raise exceptions.SystemSetupError("OpenSearch doesn't provide release artifacts for Windows currently.")
- if os_check == "Darwin":
- # OpenSearch does not provide a Darwin version of OpenSearch or a MacOS JDK version
- logger.info("Using JDK set from JAVA_HOME because OS is MacOS (Darwin).")
- logger.info("NOTICE: OpenSearch doesn't provide release artifacts for MacOS (Darwin) currently."
- " Please set JAVA_HOME to JDK 11 or JDK 8 and set the runtime.jdk.bundled to true in config.ini "
- "in opensearch-benchmark-cluster-configs directory")
- return detect_jdk(allowed_runtime_jdks)
-
- # assume that the bundled JDK is the highest available; the path is irrelevant
- return allowed_runtime_jdks[0], None
- else:
- logger.info("Allowed JDK versions are %s.", runtime_jdk_versions)
- return detect_jdk(runtime_jdk_versions)
+ logger.info("Allowed JDK versions are %s.", runtime_jdk_versions)
+ return detect_jdk(runtime_jdk_versions)
diff --git a/osbenchmark/builder/launcher.py b/osbenchmark/builder/launcher.py
index b67975f4..15194352 100644
--- a/osbenchmark/builder/launcher.py
+++ b/osbenchmark/builder/launcher.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -147,8 +150,7 @@ class ProcessLauncher:
node_telemetry_dir = os.path.join(node_configuration.node_root_path, "telemetry")
java_major_version, java_home = java_resolver.java_home(node_configuration.cluster_config_runtime_jdks,
- self.cfg.opts("builder", "runtime.jdk"),
- node_configuration.cluster_config_provides_bundled_jdk)
+ self.cfg.opts("builder", "runtime.jdk"))
self.logger.info("Java major version: %s", java_major_version)
self.logger.info("Java home: %s", java_home)
@@ -169,7 +171,9 @@ class ProcessLauncher:
t = telemetry.Telemetry(enabled_devices, devices=node_telemetry)
env = self._prepare_env(node_name, java_home, t)
t.on_pre_node_start(node_name)
- node_pid = self._start_process(binary_path, env)
+ # Get Solr version for version-specific startup command
+ distribution_version = self.cfg.opts("builder", "distribution.version", mandatory=False)
+ node_pid = self._start_process(binary_path, env, distribution_version)
self.logger.info("Successfully started node [%s] with PID [%s].", node_name, node_pid)
node = cluster.Node(node_pid, binary_path, host_name, node_name, t)
@@ -182,17 +186,15 @@ class ProcessLauncher:
env = {k: v for k, v in os.environ.items() if k in self.pass_env_vars}
if java_home:
self._set_env(env, "PATH", os.path.join(java_home, "bin"), separator=os.pathsep, prepend=True)
- # This property is the higher priority starting in ES 7.12.0, and is the only supported java home in >=8.0
- env["OPENSEARCH_JAVA_HOME"] = java_home
- # TODO remove this when ES <8.0 becomes unsupported by OSB
+ env["SOLR_JAVA_HOME"] = java_home
env["JAVA_HOME"] = java_home
self.logger.info("JAVA HOME: %s", env["JAVA_HOME"])
- if not env.get("OPENSEARCH_JAVA_OPTS"):
- env["OPENSEARCH_JAVA_OPTS"] = "-XX:+ExitOnOutOfMemoryError"
+ if not env.get("SOLR_JAVA_OPTS"):
+ env["SOLR_JAVA_OPTS"] = "-XX:+ExitOnOutOfMemoryError"
# we just blindly trust telemetry here...
for v in t.instrument_candidate_java_opts():
- self._set_env(env, "OPENSEARCH_JAVA_OPTS", v)
+ self._set_env(env, "SOLR_JAVA_OPTS", v)
self.logger.debug("env for [%s]: %s", node_name, str(env))
return env
@@ -221,19 +223,47 @@ class ProcessLauncher:
return command_line_process.returncode
@staticmethod
- def _start_process(binary_path, env):
+ def _start_process(binary_path, env, distribution_version=None):
if os.name == "posix" and os.geteuid() == 0:
- raise exceptions.LaunchError("Cannot launch OpenSearch as root. Please run OSB as a non-root user.")
+ raise exceptions.LaunchError("Cannot launch Solr as root. Please run as a non-root user.")
os.chdir(binary_path)
- cmd = [io.escape_path(os.path.join(".", "bin", "opensearch"))]
- cmd.extend(["-d", "-p", "pid"])
+ # Solr uses bin/solr instead of bin/opensearch
+ cmd = [io.escape_path(os.path.join(".", "bin", "solr"))]
+
+ # Solr startup command varies by version:
+ # - Solr 9.x: requires --cloud flag for SolrCloud mode
+ # - Solr 10.x+: just "start" enables SolrCloud mode with embedded ZooKeeper by default
+ # The bin/solr script handles daemonization and PID file creation
+ cmd.append("start")
+
+ # Determine if we need --cloud flag based on version
+ if distribution_version:
+ # Extract major version (handle formats like "9.10.1", "10.0.0-SNAPSHOT", "11.0.0-SNAPSHOT")
+ version_parts = distribution_version.split("-")[0].split(".")
+ if version_parts:
+ try:
+ major_version = int(version_parts[0])
+ if major_version < 10:
+ # Solr 9.x and earlier require --cloud flag
+ cmd.append("--cloud")
+ logging.info("Using --cloud flag for Solr %s", distribution_version)
+ else:
+ logging.info("Solr %s uses embedded cloud mode by default", distribution_version)
+ except (ValueError, IndexError):
+ # If we can't parse version, assume newer Solr (no flag)
+ logging.warning("Could not parse Solr version from '%s', assuming 10.x+ (no --cloud flag)",
+ distribution_version)
+
ret = ProcessLauncher._run_subprocess(command_line=" ".join(cmd), env=env)
if ret != 0:
msg = "Daemon startup failed with exit code [{}]".format(ret)
logging.error(msg)
raise exceptions.LaunchError(msg)
- return wait_for_pidfile(io.escape_path(os.path.join(".", "pid")))
+ # Solr creates PID file at solr-<port>.pid in the bin directory
+ port = env.get("SOLR_PORT", "8983")
+ pid_file = os.path.join(binary_path, "bin", f"solr-{port}.pid")
+ return wait_for_pidfile(pid_file)
def stop(self, nodes, metrics_store):
self.logger.info("Shutting down [%d] nodes on this host.", len(nodes))
@@ -243,29 +273,29 @@ class ProcessLauncher:
if metrics_store:
telemetry.add_metadata_for_node(metrics_store, node_name, node.host_name)
try:
- opensearch = psutil.Process(pid=node.pid)
+ node_process = psutil.Process(pid=node.pid)
node.telemetry.detach_from_node(node, running=True)
except psutil.NoSuchProcess:
self.logger.warning("No process found with PID [%s] for node [%s].", node.pid, node_name)
- opensearch = None
+ node_process = None
- if opensearch:
+ if node_process:
stop_watch = self._clock.stop_watch()
stop_watch.start()
try:
- opensearch.terminate()
- opensearch.wait(10.0)
+ node_process.terminate()
+ node_process.wait(10.0)
stopped_nodes.append(node)
except psutil.NoSuchProcess:
- self.logger.warning("No process found with PID [%s] for node [%s].", opensearch.pid, node_name)
+ self.logger.warning("No process found with PID [%s] for node [%s].", node_process.pid, node_name)
except psutil.TimeoutExpired:
self.logger.info("kill -KILL node [%s]", node_name)
try:
# kill -9
- opensearch.kill()
+ node_process.kill()
stopped_nodes.append(node)
except psutil.NoSuchProcess:
- self.logger.warning("No process found with PID [%s] for node [%s].", opensearch.pid, node_name)
+ self.logger.warning("No process found with PID [%s] for node [%s].", node_process.pid, node_name)
self.logger.info("Done shutting down node [%s] in [%.1f] s.", node_name, stop_watch.split_time())
node.telemetry.detach_from_node(node, running=False)
diff --git a/osbenchmark/builder/launchers/launcher.py b/osbenchmark/builder/launchers/launcher.py
index ba90e2eb..d55b9b95 100644
--- a/osbenchmark/builder/launchers/launcher.py
+++ b/osbenchmark/builder/launchers/launcher.py
@@ -1,9 +1,36 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
from abc import ABC, abstractmethod
class Launcher(ABC):
"""
- Launchers are used to start and stop OpenSearch on the nodes in a self-managed cluster.
+ Launchers are used to start and stop Solr on the nodes in a self-managed cluster.
"""
def __init__(self, shell_executor):
self.shell_executor = shell_executor
@@ -11,7 +38,7 @@ class Launcher(ABC):
@abstractmethod
def start(self, host, node_configurations):
"""
- Starts the OpenSearch nodes on a given host
+ Starts the Solr nodes on a given host
;param host: A Host object defining the host on which to start the nodes
;param node_configurations: A list of NodeConfiguration objects detailing the installation data of the nodes on the host
@@ -22,10 +49,10 @@ class Launcher(ABC):
@abstractmethod
def stop(self, host, nodes):
"""
- Stops the OpenSearch nodes on a given host
+ Stops the Solr nodes on a given host
;param host: A Host object defining the host on which to stop the nodes
;param nodes: A list of Node objects defining the nodes running on a host
- ;return nodes: A list of Node objects representing OpenSearch nodes that were successfully stopped on the host
+ ;return nodes: A list of Node objects representing Solr nodes that were successfully stopped on the host
"""
raise NotImplementedError
diff --git a/osbenchmark/builder/launchers/local_process_launcher.py b/osbenchmark/builder/launchers/local_process_launcher.py
index 5e9740a8..91afe72c 100644
--- a/osbenchmark/builder/launchers/local_process_launcher.py
+++ b/osbenchmark/builder/launchers/local_process_launcher.py
@@ -1,3 +1,30 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
import logging
import os
import subprocess
@@ -34,8 +61,7 @@ class LocalProcessLauncher(Launcher):
binary_path = node_configuration.binary_path
java_major_version, java_home = java_resolver.java_home(node_configuration.cluster_config_runtime_jdks,
- self.cluster_config.variables["system"]["runtime"]["jdk"],
- node_configuration.cluster_config_provides_bundled_jdk)
+ self.cluster_config.variables["system"]["runtime"]["jdk"])
self.logger.info("Java major version: %s", java_major_version)
self.logger.info("Java home: %s", java_home)
self.logger.info("Starting node [%s].", node_name)
@@ -77,17 +103,14 @@ class LocalProcessLauncher(Launcher):
opts.csv_to_list(self.cluster_config.variables["system"]["env"]["passenv"])}
if java_home:
self._set_env(env, "PATH", os.path.join(java_home, "bin"), separator=os.pathsep, prepend=True)
- # This property is the higher priority starting in ES 7.12.0, and is the only supported java home in >=8.0
- env["OPENSEARCH_JAVA_HOME"] = java_home
- # TODO remove this when ES <8.0 becomes unsupported by OSB
env["JAVA_HOME"] = java_home
self.logger.info("JAVA HOME: %s", env["JAVA_HOME"])
- if not env.get("OPENSEARCH_JAVA_OPTS"):
- env["OPENSEARCH_JAVA_OPTS"] = "-XX:+ExitOnOutOfMemoryError"
+ if not env.get("SOLR_JAVA_OPTS"):
+ env["SOLR_JAVA_OPTS"] = "-XX:+ExitOnOutOfMemoryError"
# we just blindly trust telemetry here...
for jvm_option in telemetry.instrument_candidate_java_opts():
- self._set_env(env, "OPENSEARCH_JAVA_OPTS", jvm_option)
+ self._set_env(env, "SOLR_JAVA_OPTS", jvm_option)
self.logger.debug("env for [%s]: %s", node_name, str(env))
return env
@@ -103,14 +126,27 @@ class LocalProcessLauncher(Launcher):
def _start_process(self, host, binary_path, env):
if os.name == "posix" and os.geteuid() == 0:
- raise LaunchError("Cannot launch OpenSearch as root. Please run OSB as a non-root user.")
+ raise LaunchError("Cannot launch Solr as root. Please run as a non-root user.")
+
+ cmd = [io.escape_path(os.path.join(binary_path, "bin", "solr"))]
+ cmd.append("start")
- cmd = [io.escape_path(os.path.join(binary_path, "bin", "opensearch"))]
- cmd.extend(["-d", "-p", "pid"])
+ # Solr 9.x requires --cloud flag for SolrCloud mode; Solr 10+ uses it by default
+ distribution_version = self.cluster_config.variables.get("distribution", {}).get("version")
+ if distribution_version is None:
+ cmd.append("--cloud")
+ else:
+ version_parts = str(distribution_version).split("-", maxsplit=1)[0].split(".")
+ try:
+ if int(version_parts[0]) < 10:
+ cmd.append("--cloud")
+ except (ValueError, IndexError):
+ cmd.append("--cloud")
self.shell_executor.execute(host, " ".join(cmd), env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, detach=True)
- pid_file_name = io.escape_path(os.path.join(binary_path, "pid"))
+ port = env.get("SOLR_PORT", "8983")
+ pid_file_name = io.escape_path(os.path.join(binary_path, "bin", f"solr-{port}.pid"))
self._wait_for_pid_file(pid_file_name)
return self._get_pid_from_file(pid_file_name)
@@ -149,10 +185,10 @@ class LocalProcessLauncher(Launcher):
if self.metrics_store:
telemetry.add_metadata_for_node(self.metrics_store, node.node_name, node.host_name)
- opensearch_process = self._get_opensearch_process(node)
- if opensearch_process:
+ node_process = self._get_node_process(node)
+ if node_process:
node.telemetry.detach_from_node(node, running=True)
- node_stopped = self._stop_process(opensearch_process, node)
+ node_stopped = self._stop_process(node_process, node)
node.telemetry.detach_from_node(node, running=False)
# store system metrics in any case (telemetry devices may derive system metrics while the node is running)
if self.metrics_store:
@@ -160,29 +196,29 @@ class LocalProcessLauncher(Launcher):
return node_stopped
- def _get_opensearch_process(self, node):
+ def _get_node_process(self, node):
try:
return psutil.Process(pid=node.pid)
except psutil.NoSuchProcess:
self.logger.warning("No process found with PID [%s] for node [%s].", node.pid, node.node_name)
- def _stop_process(self, opensearch_process, node):
+ def _stop_process(self, node_process, node):
process_stopped = False
try:
- opensearch_process.terminate()
- opensearch_process.wait(10.0)
+ node_process.terminate()
+ node_process.wait(10.0)
process_stopped = True
except psutil.NoSuchProcess:
- self.logger.warning("No process found with PID [%s] for node [%s].", opensearch_process.pid, node.node_name)
+ self.logger.warning("No process found with PID [%s] for node [%s].", node_process.pid, node.node_name)
except psutil.TimeoutExpired:
self.logger.info("kill -KILL node [%s]", node.node_name)
try:
# kill -9
- opensearch_process.kill()
+ node_process.kill()
process_stopped = True
except psutil.NoSuchProcess:
- self.logger.warning("No process found with PID [%s] for node [%s].", opensearch_process.pid, node.node_name)
+ self.logger.warning("No process found with PID [%s] for node [%s].", node_process.pid, node.node_name)
self.logger.info("Done shutting down node [%s].", node.node_name)
return process_stopped
diff --git a/osbenchmark/builder/models/architecture_types.py b/osbenchmark/builder/models/architecture_types.py
index 29ab983a..14854d92 100644
--- a/osbenchmark/builder/models/architecture_types.py
+++ b/osbenchmark/builder/models/architecture_types.py
@@ -6,12 +6,12 @@ class ArchitectureTypes(Enum):
Represents a machine's architecture type
:param hardware_name: The value returned by the machine when querying the architecture. Obtained via `uname -m` for unix machines
- ;param opensearch_name: The value used by opensearch artifacts to represent the architecture
+ :param artifact_name: The value used by artifacts to represent the architecture
"""
- def __init__(self, hardware_name, opensearch_name):
+ def __init__(self, hardware_name, artifact_name):
self.hardware_name = hardware_name
- self.opensearch_name = opensearch_name
+ self.artifact_name = artifact_name
ARM = "aarch64", "arm64"
x86 = "x86_64", "x64"
diff --git a/osbenchmark/builder/provisioner.py b/osbenchmark/builder/provisioner.py
index b85e261f..9b2103f5 100644
--- a/osbenchmark/builder/provisioner.py
+++ b/osbenchmark/builder/provisioner.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -34,24 +37,21 @@ from jinja2 import select_autoescape
from osbenchmark import exceptions
from osbenchmark.builder import cluster_config, java_resolver
-from osbenchmark.utils import console, convert, io, process, versions
+from osbenchmark.utils import console, io
-def local(cfg, cluster_config, plugins, ip, http_port, all_node_ips, all_node_names, target_root, node_name):
+def local(cfg, cluster_config, ip, http_port, all_node_ips, all_node_names, target_root, node_name):
distribution_version = cfg.opts("builder", "distribution.version", mandatory=False)
node_root_dir = os.path.join(target_root, node_name)
- runtime_jdk_bundled = convert.to_bool(cluster_config.mandatory_var("runtime.jdk.bundled"))
runtime_jdk = cluster_config.mandatory_var("runtime.jdk")
- _, java_home = java_resolver.java_home(runtime_jdk, cfg.opts("builder", "runtime.jdk"), runtime_jdk_bundled)
+ _, java_home = java_resolver.java_home(runtime_jdk, cfg.opts("builder", "runtime.jdk"))
- os_installer = OpenSearchInstaller(
+ os_installer = NodeInstaller(
cluster_config, java_home, node_name,
node_root_dir, all_node_ips, all_node_names, ip, http_port)
- plugin_installers = [PluginInstaller(plugin, java_home) for plugin in plugins]
-
- return BareProvisioner(os_installer, plugin_installers, distribution_version=distribution_version)
+ return BareProvisioner(os_installer, distribution_version=distribution_version)
def docker(cfg, cluster_config, ip, http_port, target_root, node_name):
@@ -64,13 +64,9 @@ def docker(cfg, cluster_config, ip, http_port, target_root, node_name):
class NodeConfiguration:
- def __init__(self, build_type, cluster_config_runtime_jdks, \
- cluster_config_provides_bundled_jdk, ip, node_name, \
- node_root_path,
- binary_path, data_paths):
+ def __init__(self, build_type, cluster_config_runtime_jdks, ip, node_name, node_root_path, binary_path, data_paths):
self.build_type = build_type
self.cluster_config_runtime_jdks = cluster_config_runtime_jdks
- self.cluster_config_provides_bundled_jdk = cluster_config_provides_bundled_jdk
self.ip = ip
self.node_name = node_name
self.node_root_path = node_root_path
@@ -81,7 +77,6 @@ class NodeConfiguration:
return {
"build-type": self.build_type,
"cluster-config-instance-runtime-jdks": self.cluster_config_runtime_jdks,
- "cluster-config-instance-provides-bundled-jdk": self.cluster_config_provides_bundled_jdk,
"ip": self.ip,
"node-name": self.node_name,
"node-root-path": self.node_root_path,
@@ -92,9 +87,8 @@ class NodeConfiguration:
@staticmethod
def from_dict(d):
return NodeConfiguration(
- d["build-type"], d["cluster-config-instance-runtime-jdks"],
- d["cluster-config-instance-provides-bundled-jdk"], d["ip"],
- d["node-name"], d["node-root-path"], d["binary-path"], d["data-paths"])
+ d["build-type"], d["cluster-config-instance-runtime-jdks"], d["ip"],
+ d["node-name"], d["node-root-path"], d["binary-path"], d["data-paths"])
def save_node_configuration(path, n):
@@ -178,15 +172,14 @@ class BareProvisioner:
of the benchmark candidate to the appropriate place.
"""
- def __init__(self, os_installer, plugin_installers, distribution_version=None, apply_config=_apply_config):
+ def __init__(self, os_installer, distribution_version=None, apply_config=_apply_config):
self.os_installer = os_installer
- self.plugin_installers = plugin_installers
self.distribution_version = distribution_version
self.apply_config = apply_config
self.logger = logging.getLogger(__name__)
def prepare(self, binary):
- self.os_installer.install(binary["opensearch"])
+ self.os_installer.install(binary["solr"])
# we need to immediately delete it as plugins may copy their configuration during installation.
self.os_installer.delete_pre_bundled_configuration()
@@ -196,51 +189,23 @@ class BareProvisioner:
for p in self.os_installer.config_source_paths:
self.apply_config(p, target_root_path, provisioner_vars)
- for installer in self.plugin_installers:
- installer.install(target_root_path, binary.get(installer.plugin_name))
- for plugin_config_path in installer.config_source_paths:
- self.apply_config(plugin_config_path, target_root_path, provisioner_vars)
-
# Never let install hooks modify our original provisioner variables and just provide a copy!
self.os_installer.invoke_install_hook(cluster_config.BootstrapPhase.post_install, provisioner_vars.copy())
- for installer in self.plugin_installers:
- installer.invoke_install_hook(cluster_config.BootstrapPhase.post_install, provisioner_vars.copy())
return NodeConfiguration("tar", self.os_installer.cluster_config.mandatory_var("runtime.jdk"),
- convert.to_bool(self.os_installer.cluster_config.mandatory_var("runtime.jdk.bundled")),
self.os_installer.node_ip, self.os_installer.node_name,
self.os_installer.node_root_dir, self.os_installer.os_home_path,
self.os_installer.data_paths)
def _provisioner_variables(self):
- plugin_variables = {}
- mandatory_plugins = []
- for installer in self.plugin_installers:
- try:
- major, minor, _, _ = versions.components(self.distribution_version)
- if (major == 6 and minor < 3) or major < 6:
- mandatory_plugins.append(installer.sub_plugin_name)
- else:
- mandatory_plugins.append(installer.plugin_name)
- except (TypeError, exceptions.InvalidSyntax):
- mandatory_plugins.append(installer.plugin_name)
- plugin_variables.update(installer.variables)
-
- cluster_settings = {}
- if mandatory_plugins:
- # as a safety measure, prevent the cluster to startup if something went wrong during plugin installation which
- # we did not detect already here. This ensures we fail fast.
- cluster_settings["plugin.mandatory"] = mandatory_plugins
-
provisioner_vars = {}
provisioner_vars.update(self.os_installer.variables)
- provisioner_vars.update(plugin_variables)
- provisioner_vars["cluster_settings"] = cluster_settings
+ provisioner_vars["cluster_settings"] = {}
return provisioner_vars
-class OpenSearchInstaller:
+class NodeInstaller:
def __init__(self, cluster_config, java_home, node_name, node_root_dir, all_node_ips, all_node_names, ip, http_port,
hook_handler_class=cluster_config.BootstrapHookHandler):
self.cluster_config = cluster_config
@@ -269,13 +234,18 @@ class OpenSearchInstaller:
self.logger.info("Unzipping %s to %s", binary, self.install_dir)
io.decompress(binary, self.install_dir)
- self.os_home_path = glob.glob(os.path.join(self.install_dir, "opensearch*"))[0]
+ self.os_home_path = glob.glob(os.path.join(self.install_dir, "solr*"))[0]
self.data_paths = self._data_paths()
def delete_pre_bundled_configuration(self):
+ # Solr doesn't have a pre-bundled config directory like OpenSearch
+ # Configuration is managed through configsets in server/solr/configsets/
config_path = os.path.join(self.os_home_path, "config")
- self.logger.info("Deleting pre-bundled OpenSearch configuration at [%s]", config_path)
- shutil.rmtree(config_path)
+ if os.path.exists(config_path):
+ self.logger.info("Deleting pre-bundled configuration at [%s]", config_path)
+ shutil.rmtree(config_path)
+ else:
+ self.logger.info("No pre-bundled config directory found at [%s], skipping deletion", config_path)
def invoke_install_hook(self, phase, variables):
env = {}
@@ -299,7 +269,7 @@ class OpenSearchInstaller:
# this is the IP address that the node will be bound to. OSB will bind to the node's IP address (but not to 0.0.0.0). The
"network_host": network_host,
"http_port": str(self.http_port),
- "transport_port": str(self.http_port + 100),
+ "zookeeper_port": str(self.http_port + 1000),
"all_node_ips": "[\"%s\"]" % "\",\"".join(self.all_node_ips),
"all_node_names": "[\"%s\"]" % "\",\"".join(self.all_node_names),
# at the moment we are strict and enforce that all nodes are master eligible nodes
@@ -328,65 +298,6 @@ class OpenSearchInstaller:
return [os.path.join(self.os_home_path, "data")]
-class PluginInstaller:
- def __init__(self, plugin, java_home, hook_handler_class=cluster_config.BootstrapHookHandler):
- self.plugin = plugin
- self.java_home = java_home
- self.hook_handler = hook_handler_class(self.plugin)
- if self.hook_handler.can_load():
- self.hook_handler.load()
- self.logger = logging.getLogger(__name__)
-
- def install(self, os_home_path, plugin_url=None):
- installer_binary_path = os.path.join(os_home_path, "bin", "opensearch-plugin")
- if plugin_url:
- self.logger.info("Installing [%s] into [%s] from [%s]", self.plugin_name, os_home_path, plugin_url)
- install_cmd = '%s install --batch "%s"' % (installer_binary_path, plugin_url)
- else:
- self.logger.info("Installing [%s] into [%s]", self.plugin_name, os_home_path)
- install_cmd = '%s install --batch "%s"' % (installer_binary_path, self.plugin_name)
-
- output, return_code = process.run_subprocess_with_logging(install_cmd, env=self.env(), capture_output=True)
- if return_code == 0:
- self.logger.info("Successfully installed [%s].", self.plugin_name)
- elif return_code == 64:
- # most likely this is an unknown plugin
- raise exceptions.SystemSetupError("Unknown plugin [%s]" % self.plugin_name)
- elif return_code == 74:
- raise exceptions.SupplyError("I/O error while trying to install [%s]" % self.plugin_name)
- else:
- raise exceptions.BenchmarkError(
- "Unknown error '%s' while trying to install [%s] (installer return code [%s]). "
- "Please check the logs." %
- (output, self.plugin_name, str(return_code)))
-
- def invoke_install_hook(self, phase, variables):
- self.hook_handler.invoke(phase.name, variables=variables, env=self.env())
-
- def env(self):
- env = {}
- if self.java_home:
- env["JAVA_HOME"] = self.java_home
- return env
-
- @property
- def variables(self):
- return self.plugin.variables
-
- @property
- def config_source_paths(self):
- return self.plugin.config_paths
-
- @property
- def plugin_name(self):
- return self.plugin.name
-
- @property
- def sub_plugin_name(self):
- # if a plugin consists of multiple plugins we're interested in that name
- return self.variables.get("plugin_name", self.plugin_name)
-
-
class DockerProvisioner:
def __init__(self, cluster_config, node_name, ip, http_port, node_root_dir, distribution_version, benchmark_root):
self.cluster_config = cluster_config
@@ -407,15 +318,15 @@ class DockerProvisioner:
"cluster_name": "benchmark-provisioned-cluster",
"node_name": self.node_name,
# we bind-mount the directories below on the host to these ones.
- "install_root_path": "/usr/share/opensearch",
- "data_paths": ["/usr/share/opensearch/data"],
- "log_path": "/var/log/opensearch",
- "heap_dump_path": "/usr/share/opensearch/heapdump",
+ "install_root_path": "/var/solr",
+ "data_paths": ["/var/solr/data"],
+ "log_path": "/var/solr/logs",
+ "heap_dump_path": "/var/solr/heapdump",
# Docker container needs to expose service on external interfaces
"network_host": "0.0.0.0",
"discovery_type": "single-node",
"http_port": str(self.http_port),
- "transport_port": str(self.http_port + 100),
+ "zookeeper_port": str(self.http_port + 1000),
"cluster_settings": {}
}
@@ -450,7 +361,7 @@ class DockerProvisioner:
for name in files:
source_file = os.path.join(root, name)
target_file = os.path.join(absolute_target_root, name)
- mounts[target_file] = os.path.join("/usr/share/opensearch", relative_root, name)
+ mounts[target_file] = os.path.join("/var/solr", relative_root, name)
if plain_text(source_file):
self.logger.info("Reading config template file [%s] and writing to [%s].", source_file, target_file)
with open(target_file, mode="a", encoding="utf-8") as f:
@@ -466,17 +377,26 @@ class DockerProvisioner:
f.write(docker_cfg)
return NodeConfiguration("docker", self.cluster_config.mandatory_var("runtime.jdk"),
- convert.to_bool(self.cluster_config.mandatory_var("runtime.jdk.bundled")), self.node_ip,
- self.node_name, self.node_root_dir, self.binary_path, self.data_paths)
+ self.node_ip, self.node_name, self.node_root_dir, self.binary_path, self.data_paths)
def docker_vars(self, mounts):
+ # Determine Docker image based on version type
+ # SNAPSHOT versions use apache/solr-nightly, release versions use solr
+ base_docker_image = self.cluster_config.mandatory_var("docker_image")
+ if self.distribution_version and "-SNAPSHOT" in self.distribution_version:
+ # For SNAPSHOT versions, use apache/solr-nightly
+ docker_image = "apache/solr-nightly"
+ else:
+ # For release versions, use the configured image (typically "solr")
+ docker_image = base_docker_image
+
v = {
- "os_version": self.distribution_version,
- "docker_image": self.cluster_config.mandatory_var("docker_image"),
+ "solr_version": self.distribution_version,
+ "docker_image": docker_image,
"http_port": self.http_port,
- "os_data_dir": self.data_paths[0],
- "os_log_dir": self.node_log_dir,
- "os_heap_dump_dir": self.heap_dump_dir,
+ "solr_data_dir": self.data_paths[0],
+ "solr_log_dir": self.node_log_dir,
+ "solr_heap_dump_dir": self.heap_dump_dir,
"mounts": mounts
}
self._add_if_defined_for_cluster_config(v, "docker_mem_limit")
diff --git a/osbenchmark/builder/supplier.py b/osbenchmark/builder/supplier.py
index bddae3d1..1f1513a8 100644
--- a/osbenchmark/builder/supplier.py
+++ b/osbenchmark/builder/supplier.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -29,33 +32,27 @@ import os
import re
import shutil
import urllib.error
-import enum
from osbenchmark import exceptions, paths, PROGRAM_NAME
from osbenchmark.exceptions import BuildError, SystemSetupError
-from osbenchmark.utils import git, io, process, net, jvm, convert, sysstats
+from osbenchmark.utils import git, io, process, net, jvm, convert
# e.g. my-plugin:current - we cannot simply use String#split(":") as this would not work for timestamp-based revisions
REVISION_PATTERN = r"(\w.*?):(.*)"
-def create(cfg, sources, distribution, cluster_config, plugins=None):
+def create(cfg, sources, cluster_config):
logger = logging.getLogger(__name__)
- if plugins is None:
- plugins = []
caching_enabled = cfg.opts("source", "cache", mandatory=False, default_value=True)
revisions = _extract_revisions(cfg.opts("builder", "source.revision", mandatory=sources))
distribution_version = cfg.opts("builder", "distribution.version", mandatory=False)
- supply_requirements = _supply_requirements(sources, distribution, plugins, revisions, distribution_version)
+ supply_requirements = _supply_requirements(sources, revisions, distribution_version)
build_needed = any([build for _, _, build in supply_requirements.values()])
- os_supplier_type, os_version, _ = supply_requirements["opensearch"]
+ os_supplier_type, os_version, _ = supply_requirements["solr"]
src_config = cfg.all_opts("source")
suppliers = []
- target_os = cfg.opts("builder", "target.os", mandatory=False)
- target_arch = cfg.opts("builder", "target.arch", mandatory=False)
-
- template_renderer = TemplateRenderer(version=os_version, os_name=target_os, arch=target_arch)
+ template_renderer = TemplateRenderer(version=os_version)
if build_needed:
raw_build_jdk = cluster_config.mandatory_var("build.jdk")
@@ -64,19 +61,14 @@ def create(cfg, sources, distribution, cluster_config, plugins=None):
except ValueError:
raise exceptions.SystemSetupError(f"ClusterConfigInstance config key [build.jdk] is invalid: [{raw_build_jdk}] (must be int)")
- os_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "opensearch.src.subdir"))
+ os_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "src.subdir"))
builder = Builder(os_src_dir, build_jdk, paths.logs())
else:
builder = None
distributions_root = os.path.join(cfg.opts("node", "root.dir"), cfg.opts("source", "distribution.dir"))
dist_cfg = {}
- # cluster_config / plugin defines defaults...
dist_cfg.update(cluster_config.variables)
- for plugin in plugins:
- for k, v in plugin.variables.items():
- dist_cfg["plugin_{}_{}".format(plugin.name, k)] = v
- # ... but the user can override it in benchmark.ini
dist_cfg.update(cfg.all_opts("distributions"))
if caching_enabled:
@@ -92,9 +84,9 @@ def create(cfg, sources, distribution, cluster_config, plugins=None):
source_distributions_root = None
if os_supplier_type == "source":
- os_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "opensearch.src.subdir"))
+ os_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "src.subdir"))
- source_supplier = OpenSearchSourceSupplier(os_version,
+ source_supplier = SourceSupplier(os_version,
os_src_dir,
remote_url=cfg.opts("source", "remote.repo.url"),
cluster_config=cluster_config,
@@ -102,52 +94,24 @@ def create(cfg, sources, distribution, cluster_config, plugins=None):
template_renderer=template_renderer)
if caching_enabled:
- os_file_resolver = OpenSearchFileNameResolver(dist_cfg, template_renderer)
+ os_file_resolver = FileNameResolver(dist_cfg, template_renderer)
source_supplier = CachedSourceSupplier(source_distributions_root,
source_supplier,
os_file_resolver)
suppliers.append(source_supplier)
- repo = None
else:
- os_src_dir = None
repo = DistributionRepository(name=cfg.opts("builder", "distribution.repository"),
distribution_config=dist_cfg,
template_renderer=template_renderer)
- suppliers.append(OpenSearchDistributionSupplier(repo, os_version, distributions_root))
-
- for plugin in plugins:
- supplier_type, plugin_version, _ = supply_requirements[plugin.name]
-
- if supplier_type == "source":
- if CorePluginSourceSupplier.can_handle(plugin):
- logger.info("Adding core plugin source supplier for [%s].", plugin.name)
- assert os_src_dir is not None, f"Cannot build core plugin {plugin.name} when OpenSearch is not built from source."
- plugin_supplier = CorePluginSourceSupplier(plugin, os_src_dir, builder)
- elif ExternalPluginSourceSupplier.can_handle(plugin):
- logger.info("Adding external plugin source supplier for [%s].", plugin.name)
- plugin_supplier = ExternalPluginSourceSupplier(plugin, plugin_version, _src_dir(cfg, mandatory=False), src_config, builder)
- else:
- raise exceptions.BenchmarkError("Plugin %s can neither be treated as core nor as external plugin. Requirements: %s" %
- (plugin.name, supply_requirements[plugin.name]))
-
- if caching_enabled:
- plugin_file_resolver = PluginFileNameResolver(plugin.name, plugin_version)
- plugin_supplier = CachedSourceSupplier(source_distributions_root,
- plugin_supplier,
- plugin_file_resolver)
- suppliers.append(plugin_supplier)
- else:
- logger.info("Adding plugin distribution supplier for [%s].", plugin.name)
- assert repo is not None, "Cannot benchmark plugin %s from a distribution version but OpenSearch from sources" % plugin.name
- suppliers.append(PluginDistributionSupplier(repo, plugin))
+ suppliers.append(DistributionSupplier(repo, os_version, distributions_root))
return CompositeSupplier(suppliers)
def _required_version(version):
if not version or version.strip() == "":
- raise exceptions.SystemSetupError("Could not determine version. Please specify the OpenSearch distribution "
+ raise exceptions.SystemSetupError("Could not determine version. Please specify the Solr distribution "
"to download with the command line parameter --distribution-version.")
else:
return version
@@ -161,41 +125,19 @@ def _required_revision(revisions, key, name=None):
raise exceptions.SystemSetupError("No revision specified for %s" % n)
-def _supply_requirements(sources, distribution, plugins, revisions, distribution_version):
- # per artifact (OpenSearch or a specific plugin):
- # * key: artifact
- # * value: ("source" | "distribution", distribution_version | revision, build = True | False)
+def _supply_requirements(sources, revisions, distribution_version):
+ # * key: artifact
+ # * value: ("source" | "distribution", distribution_version | revision, build = True | False)
supply_requirements = {}
- # can only build OpenSearch with source-related pipelines -> ignore revision in that case
- if "opensearch" in revisions and sources:
- supply_requirements["opensearch"] = ("source", _required_revision(revisions, "opensearch", "OpenSearch"), True)
+ # can only build Solr with source-related pipelines -> ignore revision in that case
+ if "solr" in revisions and sources:
+ supply_requirements["solr"] = ("source", _required_revision(revisions, "solr", "Solr"), True)
else:
# no revision given or explicitly specified that it's from a distribution -> must use a distribution
- supply_requirements["opensearch"] = ("distribution", _required_version(distribution_version), False)
+ supply_requirements["solr"] = ("distribution", _required_version(distribution_version), False)
- for plugin in plugins:
- if plugin.core_plugin:
- # core plugins are entirely dependent upon OpenSearch.
- supply_requirements[plugin.name] = supply_requirements["opensearch"]
- else:
- # allow catch-all only if we're generally building from sources. If it is mixed, the user should tell explicitly.
- if plugin.name in revisions or ("all" in revisions and sources):
- # be a bit more lenient when checking for plugin revisions. This allows users to specify `--revision="current"` and
- # rely on OSB to do the right thing.
- try:
- plugin_revision = revisions[plugin.name]
- except KeyError:
- # maybe we can use the catch-all revision (only if it's not a git revision)
- plugin_revision = revisions.get("all")
- if not plugin_revision or SourceRepository.is_commit_hash(plugin_revision):
- raise exceptions.SystemSetupError("No revision specified for plugin [%s]." % plugin.name)
- else:
- logging.getLogger(__name__).info("Revision for [%s] is not explicitly defined. Using catch-all revision [%s].",
- plugin.name, plugin_revision)
- supply_requirements[plugin.name] = ("source", plugin_revision, True)
- else:
- supply_requirements[plugin.name] = (distribution, _required_version(distribution_version), False)
+ # Solr does not support plugin installation via the benchmark tool
return supply_requirements
@@ -204,8 +146,8 @@ def _src_dir(cfg, mandatory=True):
try:
return cfg.opts("node", "src.root.dir", mandatory=mandatory)
except exceptions.ConfigError:
- raise exceptions.SystemSetupError("You cannot benchmark OpenSearch from sources. Did you install Gradle? Please install"
- " all prerequisites and reconfigure OSB with %s configure" % PROGRAM_NAME)
+ raise exceptions.SystemSetupError("You cannot benchmark Solr from sources. Did you install Gradle? Please install"
+ " all prerequisites and reconfigure with %s configure" % PROGRAM_NAME)
def _prune(root_path, max_age_days):
@@ -236,47 +178,12 @@ def _prune(root_path, max_age_days):
else:
logger.info("Skipping [%s] (not a file).", artifact)
-class SupportedOS(enum.Enum):
- # Operating systems that OpenSearch currently supports
- default = "linux"
- linux = "linux"
- docker = "docker"
- freebsd = "freebsd"
-
- # Checks if value is in enum. If not, it will use default Linux
- @classmethod
- def get_os(cls, value):
- if value not in cls._value2member_map_:
- return cls.default.value
- return value
-
class TemplateRenderer:
- def __init__(self, version, os_name=None, arch=None):
+ def __init__(self, version):
self.version = version
- if os_name is not None:
- self.os = os_name
- else:
- system_os_name = sysstats.os_name().lower()
- self.os = SupportedOS.get_os(system_os_name)
-
- if arch is not None:
- self.arch = arch
- else:
- self.arch = sysstats.cpu_arch().lower()
- # OpenSearch uses arm64 for the 64b Arm binary name
- if self.arch == "aarch64":
- self.arch = "arm64"
def render(self, template):
- substitutions = {
- "{{VERSION}}": self.version,
- "{{OSNAME}}": self.os,
- "{{ARCH}}": self.arch
- }
- r = template
- for key, replacement in substitutions.items():
- r = r.replace(key, str(replacement))
- return r
+ return template.replace("{{VERSION}}", str(self.version))
class CompositeSupplier:
@@ -296,10 +203,9 @@ class CompositeSupplier:
return binaries
-class OpenSearchFileNameResolver:
+class FileNameResolver:
def __init__(self, distribution_config, template_renderer):
self.cfg = distribution_config
- self.runtime_jdk_bundled = convert.to_bool(self.cfg.get("runtime.jdk.bundled", False))
self.template_renderer = template_renderer
@property
@@ -312,16 +218,14 @@ class OpenSearchFileNameResolver:
@property
def file_name(self):
- if self.runtime_jdk_bundled:
- url_key = "jdk.bundled.release_url"
- else:
- url_key = "jdk.unbundled.release_url"
+ # Solr distributions never include a JDK, so we always use release_url
+ url_key = "release_url"
url = self.template_renderer.render(self.cfg[url_key])
return url[url.rfind("/") + 1:]
@property
def artifact_key(self):
- return "opensearch"
+ return "solr"
def to_artifact_path(self, file_system_path):
return file_system_path
@@ -386,7 +290,7 @@ class CachedSourceSupplier:
self.logger.info("Not caching [%s] (no revision info).", original_path)
-class OpenSearchSourceSupplier:
+class SourceSupplier:
def __init__(self, revision, os_src_dir, remote_url, cluster_config, builder, template_renderer):
self.revision = revision
self.src_dir = os_src_dir
@@ -396,7 +300,7 @@ class OpenSearchSourceSupplier:
self.template_renderer = template_renderer
def fetch(self):
- return SourceRepository("OpenSearch", self.remote_url, self.src_dir).fetch(self.revision)
+ return SourceRepository("Solr", self.remote_url, self.src_dir).fetch(self.revision)
def prepare(self):
if self.builder:
@@ -406,7 +310,7 @@ class OpenSearchSourceSupplier:
])
def add(self, binaries):
- binaries["opensearch"] = self.resolve_binary()
+ binaries["solr"] = self.resolve_binary()
def resolve_binary(self):
try:
@@ -414,111 +318,12 @@ class OpenSearchSourceSupplier:
self.template_renderer.render(self.cluster_config.mandatory_var("system.artifact_path_pattern")))
return glob.glob(path)[0]
except IndexError:
- raise SystemSetupError("Couldn't find a tar.gz distribution. Please run OSB with the pipeline 'from-sources'.")
-
-
-class PluginFileNameResolver:
- def __init__(self, plugin_name, revision=None):
- self.plugin_name = plugin_name
- self.revision = revision
-
- @property
- def file_name(self):
- return f"{self.plugin_name}-{self.revision}.zip"
-
- @property
- def artifact_key(self):
- return self.plugin_name
-
- def to_artifact_path(self, file_system_path):
- return f"file://{file_system_path}"
-
- def to_file_system_path(self, artifact_path):
- return artifact_path[len("file://"):]
-
-
-class ExternalPluginSourceSupplier:
- def __init__(self, plugin, revision, src_dir, src_config, builder):
- assert not plugin.core_plugin, "Plugin %s is a core plugin" % plugin.name
- self.plugin = plugin
- self.revision = revision
- # may be None if and only if the user has set an absolute plugin directory
- self.src_dir = src_dir
- self.src_config = src_config
- self.builder = builder
- subdir_cfg_key = "plugin.%s.src.subdir" % self.plugin.name
- dir_cfg_key = "plugin.%s.src.dir" % self.plugin.name
- if dir_cfg_key in self.src_config and subdir_cfg_key in self.src_config:
- raise exceptions.SystemSetupError("Can only specify one of %s and %s but both are set." % (dir_cfg_key, subdir_cfg_key))
- elif dir_cfg_key in self.src_config:
- self.plugin_src_dir = _config_value(self.src_config, dir_cfg_key)
- # we must build directly in the plugin dir, not relative to OpenSearch
- self.override_build_dir = self.plugin_src_dir
- elif subdir_cfg_key in self.src_config:
- self.plugin_src_dir = os.path.join(self.src_dir, _config_value(self.src_config, subdir_cfg_key))
- self.override_build_dir = None
- else:
- raise exceptions.SystemSetupError("Neither %s nor %s are set for plugin %s." % (dir_cfg_key, subdir_cfg_key, self.plugin.name))
-
- @staticmethod
- def can_handle(plugin):
- return not plugin.core_plugin
-
- def fetch(self):
- # optional (but then source code is assumed to be available locally)
- plugin_remote_url = self.src_config.get("plugin.%s.remote.repo.url" % self.plugin.name)
- return SourceRepository(self.plugin.name, plugin_remote_url, self.plugin_src_dir).fetch(self.revision)
-
- def prepare(self):
- if self.builder:
- command = _config_value(self.src_config, "plugin.{}.build.command".format(self.plugin.name))
- self.builder.build([command], override_src_dir=self.override_build_dir)
-
- def add(self, binaries):
- binaries[self.plugin.name] = self.resolve_binary()
-
- def resolve_binary(self):
- artifact_path = _config_value(self.src_config, "plugin.%s.build.artifact.subdir" % self.plugin.name)
- try:
- name = glob.glob("%s/%s/*.zip" % (self.plugin_src_dir, artifact_path))[0]
- return "file://%s" % name
- except IndexError:
- raise SystemSetupError("Couldn't find a plugin zip file for [%s]. Please run OSB with the pipeline 'from-sources'." %
- self.plugin.name)
-
+ raise SystemSetupError("Couldn't find a tar.gz distribution. Please run ASB with the pipeline 'from-sources'.")
-class CorePluginSourceSupplier:
- def __init__(self, plugin, os_src_dir, builder):
- assert plugin.core_plugin, "Plugin %s is not a core plugin" % plugin.name
- self.plugin = plugin
- self.os_src_dir = os_src_dir
- self.builder = builder
- @staticmethod
- def can_handle(plugin):
- return plugin.core_plugin
-
- def fetch(self):
- # Just retrieve the current revision *number* and assume that OpenSearch has prepared the source tree.
- return SourceRepository("OpenSearch", None, self.os_src_dir).fetch(revision="current")
- def prepare(self):
- if self.builder:
- self.builder.build(["./gradlew :plugins:{}:assemble".format(self.plugin.name)])
-
- def add(self, binaries):
- binaries[self.plugin.name] = self.resolve_binary()
- def resolve_binary(self):
- try:
- name = glob.glob("%s/plugins/%s/build/distributions/*.zip" % (self.os_src_dir, self.plugin.name))[0]
- return "file://%s" % name
- except IndexError:
- raise SystemSetupError("Couldn't find a plugin zip file for [%s]. Please run OSB with the pipeline 'from-sources'." %
- self.plugin.name)
-
-
-class OpenSearchDistributionSupplier:
+class DistributionSupplier:
def __init__(self, repo, version, distributions_root):
self.repo = repo
self.version = version
@@ -534,14 +339,14 @@ class OpenSearchDistributionSupplier:
self.logger.info("Resolved download URL [%s] for version [%s]", download_url, self.version)
if not os.path.isfile(distribution_path) or not self.repo.cache:
try:
- self.logger.info("Starting download of OpenSearch [%s]", self.version)
- progress = net.Progress("[INFO] Downloading OpenSearch %s" % self.version)
+ self.logger.info("Starting download of Solr [%s]", self.version)
+ progress = net.Progress("[INFO] Downloading Solr %s" % self.version)
net.download(download_url, distribution_path, progress_indicator=progress)
progress.finish()
- self.logger.info("Successfully downloaded OpenSearch [%s].", self.version)
+ self.logger.info("Successfully downloaded Solr [%s].", self.version)
except urllib.error.HTTPError:
- self.logger.exception("Cannot download OpenSearch distribution for version [%s] from [%s].", self.version, download_url)
- raise exceptions.SystemSetupError("Cannot download OpenSearch distribution from [%s]. Please check that the specified "
+ self.logger.exception("Cannot download Solr distribution for version [%s] from [%s].", self.version, download_url)
+ raise exceptions.SystemSetupError("Cannot download Solr distribution from [%s]. Please check that the specified "
"version [%s] is correct." % (download_url, self.version))
else:
self.logger.info("Skipping download for version [%s]. Found an existing binary at [%s].", self.version, distribution_path)
@@ -552,27 +357,9 @@ class OpenSearchDistributionSupplier:
pass
def add(self, binaries):
- binaries["opensearch"] = self.distribution_path
+ binaries["solr"] = self.distribution_path
-class PluginDistributionSupplier:
- def __init__(self, repo, plugin):
- self.repo = repo
- self.plugin = plugin
-
- def fetch(self):
- pass
-
- def prepare(self):
- pass
-
- def add(self, binaries):
- # if we have multiple plugin configurations for a plugin we will override entries here but as this is always the same
- # key-value pair this is ok.
- plugin_url = self.repo.plugin_download_url(self.plugin.name)
- if plugin_url:
- binaries[self.plugin.name] = plugin_url
-
def _config_value(src_config, key):
try:
@@ -586,8 +373,8 @@ def _extract_revisions(revision):
revisions = revision.split(",") if revision else []
if len(revisions) == 1:
r = revisions[0]
- if r.startswith("opensearch:"):
- r = r[len("opensearch:"):]
+ if r.startswith("solr:"):
+ r = r[len("solr:"):]
# may as well be just a single plugin
m = re.match(REVISION_PATTERN, r)
if m:
@@ -596,7 +383,7 @@ def _extract_revisions(revision):
}
else:
return {
- "opensearch": r,
+ "solr": r,
# use a catch-all value
"all": r
}
@@ -721,18 +508,13 @@ class DistributionRepository:
def __init__(self, name, distribution_config, template_renderer):
self.name = name
self.cfg = distribution_config
- self.runtime_jdk_bundled = convert.to_bool(self.cfg.get("runtime.jdk.bundled", False))
self.template_renderer = template_renderer
self.logger = logging.getLogger(__name__)
@property
def download_url(self):
- # cluster_config repo
- self.logger.info("runtime_jdk_bundled? [%s]", self.runtime_jdk_bundled)
- if self.runtime_jdk_bundled:
- default_key = "jdk.bundled.{}_url".format(self.name)
- else:
- default_key = "jdk.unbundled.{}_url".format(self.name)
+ # Solr distributions never include a JDK, so we always use simple key names
+ default_key = "{}_url".format(self.name)
# benchmark.ini
override_key = "{}.url".format(self.name)
self.logger.info("keys: [%s] and [%s]", override_key, default_key)
diff --git a/osbenchmark/builder/utils/artifact_variables_provider.py b/osbenchmark/builder/utils/artifact_variables_provider.py
index d29ba29e..655c3440 100644
--- a/osbenchmark/builder/utils/artifact_variables_provider.py
+++ b/osbenchmark/builder/utils/artifact_variables_provider.py
@@ -5,9 +5,9 @@ class ArtifactVariablesProvider:
def __init__(self, executor):
self.executor = executor
- def get_artifact_variables(self, host, opensearch_version=None):
+ def get_artifact_variables(self, host, version=None):
return {
- "VERSION": opensearch_version,
+ "VERSION": version,
"OSNAME": self._get_os_name(host),
"ARCH": self._get_arch(host)
}
@@ -18,4 +18,4 @@ class ArtifactVariablesProvider:
def _get_arch(self, host):
arch = self.executor.execute(host, "uname -m", output=True)[0]
- return ArchitectureTypes.get_from_hardware_name(arch.lower()).opensearch_name
+ return ArchitectureTypes.get_from_hardware_name(arch.lower()).artifact_name
diff --git a/osbenchmark/builder/utils/binary_keys.py b/osbenchmark/builder/utils/binary_keys.py
index cf15c82f..d0f71c81 100644
--- a/osbenchmark/builder/utils/binary_keys.py
+++ b/osbenchmark/builder/utils/binary_keys.py
@@ -1,5 +1,32 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
from enum import Enum
class BinaryKeys(str, Enum):
- OPENSEARCH = "opensearch"
+ SOLR = "solr"
diff --git a/osbenchmark/builder/utils/config_applier.py b/osbenchmark/builder/utils/config_applier.py
index cd1ce8d3..6114ef6c 100644
--- a/osbenchmark/builder/utils/config_applier.py
+++ b/osbenchmark/builder/utils/config_applier.py
@@ -1,3 +1,30 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
import logging
import os
@@ -29,7 +56,7 @@ class ConfigApplier:
for name in files:
source_file = os.path.join(root, name)
target_file = os.path.join(absolute_target_root, name)
- mounts[target_file] = os.path.join("/usr/share/opensearch", relative_root, name)
+ mounts[target_file] = os.path.join("/var/solr", relative_root, name)
if io.is_plain_text(source_file):
self.logger.info("Reading config template file [%s] and writing to [%s].", source_file, target_file)
diff --git a/osbenchmark/builder/utils/java_home_resolver.py b/osbenchmark/builder/utils/java_home_resolver.py
index e95c501f..a3b09d03 100644
--- a/osbenchmark/builder/utils/java_home_resolver.py
+++ b/osbenchmark/builder/utils/java_home_resolver.py
@@ -1,3 +1,30 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+# Licensed to Elasticsearch B.V. under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Elasticsearch B.V. licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
import logging
from osbenchmark.builder.utils.jdk_resolver import JdkResolver
@@ -11,7 +38,6 @@ class JavaHomeResolver:
self.jdk_resolver = JdkResolver(executor)
def resolve_java_home(self, host, cluster_config):
- is_runtime_jdk_bundled = cluster_config.variables["system"]["runtime"]["jdk"]["bundled"]
runtime_jdks = cluster_config.variables["system"]["runtime"]["jdk"]["version"]
try:
@@ -19,28 +45,8 @@ class JavaHomeResolver:
except ValueError:
raise SystemSetupError(f"ClusterConfigInstance variable key \"runtime.jdk\" is invalid: \"{runtime_jdks}\" (must be int)")
- if is_runtime_jdk_bundled:
- return self._handle_bundled_jdk(host, allowed_runtime_jdks)
- else:
- self.logger.info("Allowed JDK versions are %s.", allowed_runtime_jdks)
- return self._detect_jdk(host, allowed_runtime_jdks)
-
- def _handle_bundled_jdk(self, host, allowed_runtime_jdks):
- self.logger.info("Using JDK bundled with OpenSearch.")
- os_check = self.executor.execute(host, "uname", output=True)[0]
- if os_check == "Windows":
- raise SystemSetupError("OpenSearch doesn't provide release artifacts for Windows currently.")
- if os_check == "Darwin":
- # OpenSearch does not provide a Darwin version of OpenSearch or a MacOS JDK version
- self.logger.info("Using JDK set from JAVA_HOME because OS is MacOS (Darwin).")
- self.logger.info(
- "NOTICE: OpenSearch doesn't provide jdk bundled release artifacts for MacOS (Darwin) currently. "
- "Please set JAVA_HOME to JDK 11 or JDK 8 and set the runtime.jdk.bundled to true in the specified "
- "provision config instance file")
- return self._detect_jdk(host, allowed_runtime_jdks)
-
- # assume that the bundled JDK is the highest available; the path is irrelevant
- return allowed_runtime_jdks[0], None
+ self.logger.info("Allowed JDK versions are %s.", allowed_runtime_jdks)
+ return self._detect_jdk(host, allowed_runtime_jdks)
def _detect_jdk(self, host, jdks):
major, java_home = self.jdk_resolver.resolve_jdk_path(host, jdks)
diff --git a/osbenchmark/client.py b/osbenchmark/client.py
index 50d16d16..af964daa 100644
--- a/osbenchmark/client.py
+++ b/osbenchmark/client.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -22,382 +25,532 @@
# specific language governing permissions and limitations
# under the License.
+import io
import logging
import time
+import zipfile
+from pathlib import Path
-import certifi
-import opensearchpy
-import urllib3
-from urllib3.util.ssl_ import is_ipaddress
-
-import grpc
-from opensearch.protobufs.services.document_service_pb2_grpc import DocumentServiceStub
-from opensearch.protobufs.services.search_service_pb2_grpc import SearchServiceStub
+import requests
-from osbenchmark.kafka_client import KafkaMessageProducer
-from osbenchmark import exceptions, doc_link, async_connection
from osbenchmark.context import RequestContextHolder
-from osbenchmark.utils import console, convert
-from osbenchmark.cloud_provider import CloudProviderFactory
-class OsClientFactory:
- """
- Abstracts how the OpenSearch client is created. Intended for testing.
- """
- def __init__(self, hosts, client_options):
- self.hosts = hosts
- self.client_options = dict(client_options)
- self.ssl_context = None
- self.provider = CloudProviderFactory.get_provider_from_client_options(self.client_options)
- self.logger = logging.getLogger(__name__)
+logger = logging.getLogger(__name__)
- masked_client_options = dict(client_options)
- if "basic_auth_password" in masked_client_options:
- masked_client_options["basic_auth_password"] = "*****"
- if "http_auth" in masked_client_options:
- masked_client_options["http_auth"] = (masked_client_options["http_auth"][0], "*****")
- if self.provider:
- self.provider.parse_log_in_params(client_options=self.client_options)
- self.provider.mask_client_options(masked_client_options, self.client_options)
- self.logger.info("Masking client options with cloud provider: [%s]", self.provider)
-
- self.logger.info("Creating OpenSearch client connected to %s with options [%s]", hosts, masked_client_options)
- # we're using an SSL context now and it is not allowed to have use_ssl present in client options anymore
- if self.client_options.pop("use_ssl", False):
- # pylint: disable=import-outside-toplevel
- import ssl
- self.logger.info("SSL support: on")
- self.client_options["scheme"] = "https"
-
- self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
- cafile=self.client_options.pop("ca_certs", certifi.where()))
-
- if not self.client_options.pop("verify_certs", True):
- self.logger.info("SSL certificate verification: off")
- # order matters to avoid ValueError: check_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED
- self.ssl_context.check_hostname = False
- self.ssl_context.verify_mode = ssl.CERT_NONE
-
- self.logger.warning("User has enabled SSL but disabled certificate verification. This is dangerous but may be ok for a "
- "benchmark. Disabling urllib warnings now to avoid a logging storm. "
- "See https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings for details.")
- # disable: "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly \
- # advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings"
- urllib3.disable_warnings()
- else:
- # The peer's hostname can be matched if only a hostname is provided.
- # In other words, hostname checking is disabled if an IP address is
- # found in the host lists.
- self.ssl_context.check_hostname = self._has_only_hostnames(hosts)
- self.ssl_context.verify_mode=ssl.CERT_REQUIRED
- self.logger.info("SSL certificate verification: on")
-
- # When using SSL_context, all SSL related kwargs in client options get ignored
- client_cert = self.client_options.pop("client_cert", False)
- client_key = self.client_options.pop("client_key", False)
-
- if not client_cert and not client_key:
- self.logger.info("SSL client authentication: off")
- elif bool(client_cert) != bool(client_key):
- self.logger.error(
- "Supplied client-options contain only one of client_cert/client_key. "
- )
- defined_client_ssl_option = "client_key" if client_key else "client_cert"
- missing_client_ssl_option = "client_cert" if client_key else "client_key"
- console.println(
- "'{}' is missing from client-options but '{}' has been specified.\n"
- "If your OpenSearch setup requires client certificate verification both need to be supplied.\n"
- "Read the documentation at {}\n".format(
- missing_client_ssl_option,
- defined_client_ssl_option,
- console.format.link(doc_link("command_line_reference.html#client-options")))
- )
- raise exceptions.SystemSetupError(
- "Cannot specify '{}' without also specifying '{}' in client-options.".format(
- defined_client_ssl_option,
- missing_client_ssl_option))
- elif client_cert and client_key:
- self.logger.info("SSL client authentication: on")
- self.ssl_context.load_cert_chain(certfile=client_cert,
- keyfile=client_key)
- else:
- self.logger.info("SSL support: off")
- self.client_options["scheme"] = "http"
-
- if self._is_set(self.client_options, "basic_auth_user") and self._is_set(self.client_options, "basic_auth_password"):
- self.logger.info("HTTP basic authentication: on")
- self.client_options["http_auth"] = (self.client_options.pop("basic_auth_user"), self.client_options.pop("basic_auth_password"))
- else:
- self.logger.info("HTTP basic authentication: off")
-
- if self._is_set(self.client_options, "compressed"):
- console.warn("You set the deprecated client option 'compressed'. Please use 'http_compress' instead.", logger=self.logger)
- self.client_options["http_compress"] = self.client_options.pop("compressed")
-
- if self._is_set(self.client_options, "http_compress"):
- self.logger.info("HTTP compression: on")
- else:
- self.logger.info("HTTP compression: off")
-
- if self._is_set(self.client_options, "enable_cleanup_closed"):
- self.client_options["enable_cleanup_closed"] = convert.to_bool(self.client_options.pop("enable_cleanup_closed"))
- @staticmethod
- def _has_only_hostnames(hosts):
- logger = logging.getLogger(__name__)
- has_ip, has_hostname = False, False
- for host in hosts:
- if is_ipaddress(host["host"]):
- has_ip = True
- else:
- has_hostname = True
-
- if has_ip and has_hostname:
- console.warn("Although certificate verification is enabled, "
- "peer hostnames will not be matched since the host list is a mix "
- "of names and IP addresses", logger=logger)
- return False
-
- return has_hostname
-
- def _is_set(self, client_opts, k):
- try:
- return client_opts[k]
- except KeyError:
- return False
+# ---------------------------------------------------------------------------
+# Exceptions
+# ---------------------------------------------------------------------------
- def create(self):
- if self.provider:
- self.logger.info("Creating OpenSearch client with provider %s", self.provider)
- return self.provider.create_client(self.hosts, self.client_options)
+class SolrClientError(Exception):
+ """Base exception for all SolrAdminClient errors."""
- else:
- return opensearchpy.OpenSearch(hosts=self.hosts, ssl_context=self.ssl_context, **self.client_options)
- def create_async(self):
- # pylint: disable=import-outside-toplevel
- import io
- import aiohttp
- from opensearchpy.serializer import JSONSerializer
+class CollectionAlreadyExistsError(SolrClientError):
+ """Raised when create_collection() targets an existing collection."""
- class BenchmarkAsyncOpenSearch(opensearchpy.AsyncOpenSearch, RequestContextHolder):
- pass
- class LazyJSONSerializer(JSONSerializer):
- def loads(self, s):
- meta = BenchmarkAsyncOpenSearch.request_context.get()
- if "raw_response" in meta:
- return io.BytesIO(s)
- else:
- return super().loads(s)
-
- async def on_request_start(session, trace_config_ctx, params):
- BenchmarkAsyncOpenSearch.on_request_start()
-
- async def on_request_end(session, trace_config_ctx, params):
- BenchmarkAsyncOpenSearch.on_request_end()
-
- trace_config = aiohttp.TraceConfig()
- trace_config.on_request_start.append(on_request_start)
- trace_config.on_request_end.append(on_request_end)
- # ensure that we also stop the timer when a request "ends" with an exception (e.g. a timeout)
- trace_config.on_request_exception.append(on_request_end)
-
- # override the builtin JSON serializer
- self.client_options["serializer"] = LazyJSONSerializer()
- self.client_options["trace_config"] = trace_config
-
- if self.provider:
- self.logger.info("Creating OpenSearch Async Client with provider %s", self.provider)
- return self.provider.create_client(self.hosts, self.client_options,
- client_class=BenchmarkAsyncOpenSearch, use_async=True)
- else:
- return BenchmarkAsyncOpenSearch(hosts=self.hosts,
- connection_class=async_connection.AIOHttpConnection,
- ssl_context=self.ssl_context,
- **self.client_options)
-
-
-def wait_for_rest_layer(opensearch, max_attempts=40):
+class CollectionNotFoundError(SolrClientError):
+ """Raised when delete_collection() targets a non-existent collection."""
+
+
+# ---------------------------------------------------------------------------
+# SolrAdminClient
+# ---------------------------------------------------------------------------
+
+class SolrAdminClient:
"""
- Waits for ``max_attempts`` until OpenSearch's REST API is available.
+ Thin wrapper around requests.Session for Solr V2 API admin operations.
- :param opensearch: OpenSearch client to use for connecting.
- :param max_attempts: The maximum number of attempts to check whether the REST API is available.
- :return: True iff OpenSearch's REST API is available.
+ Handles collection management, configset upload, version detection,
+ cluster status, and metrics retrieval. High-frequency data operations
+ (indexing, search, commit, optimize) use pysolr directly in runner.py.
+
+ Not thread-safe — each worker process creates its own instance.
"""
- # assume that at least the hosts that we expect to contact should be available. Note that this is not 100%
- # bullet-proof as a cluster could have e.g. dedicated masters which are not contained in our list of target hosts
- # but this is still better than just checking for any random node's REST API being reachable.
- expected_node_count = len(opensearch.transport.hosts)
- logger = logging.getLogger(__name__)
- for attempt in range(max_attempts):
- logger.debug("REST API is available after %s attempts", attempt)
- # pylint: disable=import-outside-toplevel
+
+ def __init__(self, host: str, port: int = 8983,
+ username: str = None, password: str = None,
+ tls: bool = False, timeout: int = 30):
+ scheme = "https" if tls else "http"
+ self.base_url = f"{scheme}://{host}:{port}"
+ self.api_url = f"{self.base_url}/api"
+ self.timeout = timeout
+ self._username = username
+ self._password = password
+ self._session = None # created lazily on first use
+
+ def _get_session(self) -> requests.Session:
+ """Return the shared session, creating it on first call (lazy init)."""
+ if self._session is None:
+ self._session = requests.Session()
+ # Disable automatic proxy detection (trust_env=False) to avoid hanging
+ # on macOS after fork() — CFNetwork proxy detection is not fork-safe.
+ self._session.trust_env = False
+ if self._username and self._password:
+ self._session.auth = (self._username, self._password)
+ self._session.headers.update({"Accept": "application/json"})
+ return self._session
+
+ # ------------------------------------------------------------------
+ # Version detection
+ # ------------------------------------------------------------------
+
+ def info(self) -> dict:
+ """Return parsed JSON from GET /api/node/system."""
+ resp = self._get("/api/node/system")
+ return resp.json()
+
+ def get_version(self) -> str:
+ """
+ Detect Solr version via GET /api/node/system.
+
+ Returns the version string, e.g. "9.7.0".
+ """
+ data = self.info()
try:
- # see also WaitForHttpResource in OpenSearch tests. Contrary to the ES tests we consider the API also
- # available when the cluster status is RED (as long as all required nodes are present)
- opensearch.cluster.health(wait_for_nodes=">={}".format(expected_node_count))
- logger.info("REST API is available for >= [%s] nodes after [%s] attempts.", expected_node_count, attempt)
- return True
- except opensearchpy.ConnectionError as e:
- if "SSL: UNKNOWN_PROTOCOL" in str(e):
- raise exceptions.SystemSetupError("Could not connect to cluster via https. Is this an https endpoint?", e)
- else:
- logger.debug("Got connection error on attempt [%s]. Sleeping...", attempt)
- time.sleep(3)
- except opensearchpy.TransportError as e:
- # cluster block, our wait condition is not reached
- if e.status_code in (503, 401, 408):
- logger.debug("Got status code [%s] on attempt [%s]. Sleeping...", e.status_code, attempt)
- time.sleep(3)
- elif e.status_code == 404:
- # Serverless does not support the cluster-health API. Test with _cat/indices for now.
- catclient = opensearchpy.client.cat.CatClient(opensearch)
- try:
- catclient.indices()
- return True
- except Exception as e:
- logger.warning("Encountered exception %s when attempting to probe endpoint health", e)
- raise e
- else:
- logger.warning("Got unexpected status code [%s] on attempt [%s].", e.status_code, attempt)
- raise e
- return False
-
-
-class MessageProducerFactory:
- @staticmethod
- async def create(params):
+ return data["lucene"]["solr-spec-version"]
+ except KeyError as exc:
+ raise SolrClientError(
+ f"Could not parse Solr version from /api/node/system response: {data}"
+ ) from exc
+
+ def get_major_version(self) -> int:
+ """Return the major version integer (9 or 10)."""
+ version = self.get_version()
+ return int(version.split(".")[0])
+
+ def wait_for_cluster_ready(self, timeout: int = 60, **kwargs) -> None:
"""
- Creates and returns a message producer based on the ingestion source.
- Currently supports Kafka. Ingestion source should be a dict like:
- {'type': 'kafka', 'param': {'topic': 'test', 'bootstrap-servers': 'localhost:34803'}}
+ Poll GET /api/node/system until Solr responds or timeout is exceeded.
+
+ Args:
+ timeout: Maximum seconds to wait (default 60).
"""
- ingestion_source = params.get("ingestion-source", {})
- producer_type = ingestion_source.get("type", "kafka").lower()
- if producer_type == "kafka":
- return await KafkaMessageProducer.create(params)
- else:
- raise ValueError(f"Unsupported ingestion source type: {producer_type}")
+ deadline = time.monotonic() + timeout
+ last_exc = None
+ while time.monotonic() < deadline:
+ try:
+ self.info()
+ return
+ except Exception as exc:
+ last_exc = exc
+ time.sleep(2)
+ raise SolrClientError(
+ f"Solr cluster did not become ready within {timeout}s. Last error: {last_exc}"
+ )
+ # ------------------------------------------------------------------
+ # Configset management
+ # ------------------------------------------------------------------
-class GrpcClientFactory:
- """
- Factory for creating gRPC client stubs.
- Note gRPC channels must default `use_local_subchannel_pool` to true.
- Sub channels manage the underlying connection with the server. When the global sub channel pool is used gRPC will
- re-use sub channels and their underlying connections which does not appropriately reflect a multi client scenario.
- """
- def __init__(self, grpc_hosts):
- self.grpc_hosts = grpc_hosts
- self.logger = logging.getLogger(__name__)
- self.grpc_channel_options = [
- ('grpc.use_local_subchannel_pool', 1),
- ('grpc.max_send_message_length', 10 * 1024 * 1024), # 10 MB
- ('grpc.max_receive_message_length', 10 * 1024 * 1024) # 10 MB
- ]
+ def upload_configset(self, name: str, configset_dir: str) -> None:
+ """
+ Zip the configset directory and upload it via the Solr V1 API.
- def create_grpc_stubs(self):
+ Uses: POST /solr/admin/configs?action=UPLOAD&name={name}
+
+ The directory must contain a conf/ sub-directory with at minimum
+ schema.xml (or managed-schema) and solrconfig.xml.
+
+ Args:
+ name: Configset name to register on the cluster.
+ configset_dir: Local path to the directory containing conf/.
"""
- Create gRPC service stubs.
- Returns a dict of {cluster_name: {service_name: stub}} structure.
+ zip_bytes = self._build_configset_zip(configset_dir)
+ # Use V1 API for configsets (V2 API not available in Solr 9.x)
+ url = f"{self.base_url}/solr/admin/configs"
+ params = {"action": "UPLOAD", "name": name}
+ resp = self._get_session().post(
+ url,
+ params=params,
+ data=zip_bytes,
+ headers={"Content-Type": "application/zip"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, f"upload configset '{name}'")
+ logger.info("Uploaded configset '%s' from '%s'", name, configset_dir)
+
+ def delete_configset(self, name: str) -> None:
"""
- stubs = {}
+ Delete a configset via the Solr V1 API.
- if len(self.grpc_hosts.all_hosts.items()) > 1:
- raise NotImplementedError("Only one gRPC cluster is supported.")
+ Uses: POST /solr/admin/configs?action=DELETE&name={name}
+ """
+ # Use V1 API for configsets (V2 API not available in Solr 9.x)
+ url = f"{self.base_url}/solr/admin/configs"
+ params = {"action": "DELETE", "name": name}
+ resp = self._get_session().post(
+ url,
+ params=params,
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, f"delete configset '{name}'")
+ logger.info("Deleted configset '%s'", name)
- if len(self.grpc_hosts.all_hosts["default"]) > 1:
- raise NotImplementedError("Only one gRPC host is supported.")
+ # ------------------------------------------------------------------
+ # Collection management
+ # ------------------------------------------------------------------
- host = self.grpc_hosts.all_hosts["default"][0]
- grpc_addr = f"{host['host']}:{host['port']}"
+ def create_collection(self, name: str, configset: str,
+ num_shards: int = 1, replication_factor: int = 1,
+ tlog_replicas: int = 0, pull_replicas: int = 0,
+ wait_for_active_shards: int = 1) -> None:
+ """
+ Create a Solr collection via POST /api/collections.
- self.logger.info("Creating gRPC channel for cluster default cluster at %s", grpc_addr)
- channel = grpc.aio.insecure_channel(
- target=grpc_addr,
- options=self.grpc_channel_options,
- compression=None
+ The configset must already exist on the cluster (call upload_configset first).
+ ``replication_factor`` maps to ``nrtReplicas`` in the Solr V2 API (they are semantically
+ identical: NRT replicas that participate in indexing and serving queries in real time).
+ """
+ payload = {
+ "name": name,
+ "config": configset,
+ "numShards": num_shards,
+ "nrtReplicas": replication_factor,
+ "tlogReplicas": tlog_replicas,
+ "pullReplicas": pull_replicas,
+ "waitForFinalState": True,
+ }
+ resp = self._get_session().post(
+ f"{self.api_url}/collections",
+ json=payload,
+ timeout=self.timeout,
)
+ if resp.status_code == 400:
+ body = self._try_parse_json(resp)
+ if "already exists" in str(body).lower():
+ raise CollectionAlreadyExistsError(
+ f"Collection '{name}' already exists"
+ )
+ self._raise_for_solr_error(resp, f"create collection '{name}'")
+ logger.info("Created collection '%s' (shards=%d, nrt=%d, tlog=%d, pull=%d)",
+ name, num_shards, replication_factor, tlog_replicas, pull_replicas)
+
+ def delete_collection(self, name: str) -> None:
+ """Delete a Solr collection via DELETE /api/collections/{name}."""
+ resp = self._get_session().delete(
+ f"{self.api_url}/collections/{name}",
+ timeout=self.timeout,
+ )
+ if resp.status_code == 404:
+ raise CollectionNotFoundError(f"Collection '{name}' not found")
+ # Solr 9.x may return 400 with "Could not find collection" instead of 404
+ if resp.status_code == 400:
+ body = self._try_parse_json(resp)
+ msg = body.get("error", {}).get("msg", "") if isinstance(body, dict) else ""
+ if "could not find collection" in msg.lower():
+ raise CollectionNotFoundError(f"Collection '{name}' not found")
+ self._raise_for_solr_error(resp, f"delete collection '{name}'")
+ logger.info("Deleted collection '%s'", name)
+
+ # ------------------------------------------------------------------
+ # Cluster status
+ # ------------------------------------------------------------------
+
+ def get_cluster_status(self) -> dict:
+ """Return cluster state via GET /api/cluster."""
+ resp = self._get("/api/cluster")
+ return resp.json().get("cluster", resp.json())
+
+ def get_clusterstatus(self) -> dict:
+ """Return full CLUSTERSTATUS response dict via V1 Collections API."""
+ resp = self._get_session().get(
+ f"{self.base_url}/solr/admin/collections",
+ params={"action": "CLUSTERSTATUS", "wt": "json"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, "CLUSTERSTATUS")
+ return resp.json()
+
+ def get_core_status(self, core_name: str) -> dict:
+ """Return Core STATUS for a specific core (leader replica) via V1 Cores API."""
+ resp = self._get_session().get(
+ f"{self.base_url}/solr/admin/cores",
+ params={"action": "STATUS", "core": core_name, "wt": "json"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, f"Core STATUS for '{core_name}'")
+ return resp.json().get("status", {}).get(core_name, {})
+
+ def list_collections(self) -> list:
+ """Return list of collection names via Collections API LIST action."""
+ resp = self._get_session().get(
+ f"{self.base_url}/solr/admin/collections",
+ params={"action": "LIST", "wt": "json"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, "LIST collections")
+ return resp.json().get("collections", [])
+
+ def get_luke_stats(self, collection: str) -> dict:
+ """Return Luke index stats for a collection (numDocs, segmentCount, etc.)."""
+ resp = self._get_session().get(
+ f"{self.base_url}/solr/{collection}/admin/luke",
+ params={"numTerms": "0", "wt": "json"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, f"Luke stats for '{collection}'")
+ return resp.json().get("index", {})
+
+ def count_documents(self, collection: str) -> int:
+ """Return the number of documents in a collection via rows=0 select query."""
+ resp = self._get_session().get(
+ f"{self.base_url}/solr/{collection}/select",
+ params={"q": "*:*", "rows": 0, "wt": "json"},
+ timeout=self.timeout,
+ )
+ self._raise_for_solr_error(resp, f"count documents in '{collection}'")
+ return resp.json()["response"]["numFound"]
- # Retain a reference to underlying channel in our stubs dictionary for graceful shutdown.
- stubs["default"] = {
- 'document_service': DocumentServiceStub(channel),
- 'search_service': SearchServiceStub(channel),
- '_channel': channel
- }
+ def get_schema(self, collection: str) -> dict:
+ """Return the schema of a collection via GET /solr/{collection}/schema."""
+ resp = self._get(f"/solr/{collection}/schema")
+ return resp.json().get("schema", resp.json())
+
+ # ------------------------------------------------------------------
+ # Metrics
+ # ------------------------------------------------------------------
+
+ def get_node_metrics(self):
+ """
+ Retrieve node metrics via GET /solr/admin/metrics.
+
+ Both Solr 9.x and Solr 10.x use the same endpoint. The response format
+ differs by version and is detected via the Content-Type header:
+ - application/json → Solr 9.x custom JSON → returns parsed dict
+ - text/plain → Solr 10.x Prometheus text → returns raw str
+
+ The telemetry device is responsible for parsing the format-specific response.
+ """
+ resp = self._get_session().get(f"{self.base_url}/solr/admin/metrics", timeout=self.timeout)
+ resp.raise_for_status()
+ content_type = resp.headers.get("Content-Type", "")
+ if "text/plain" in content_type:
+ return resp.text
+ return resp.json()
+
+ # ------------------------------------------------------------------
+ # Raw request (for the raw-request workload operation)
+ # ------------------------------------------------------------------
+
+ def raw_request(self, method: str, path: str,
+ body=None, headers: dict = None) -> requests.Response:
+ """
+ Send an arbitrary HTTP request to a Solr endpoint.
+
+ Args:
+ method: HTTP method ("GET", "POST", "DELETE", etc.)
+ path: URL path relative to http://{host}:{port}/ (e.g. "/api/cluster")
+ body: Request body (dict → serialized as JSON, str → sent as-is)
+ headers: Additional request headers
+ """
+ url = f"{self.base_url}{path}"
+ req_headers = dict(headers or {})
+ kwargs = {"timeout": self.timeout, "headers": req_headers}
+ if isinstance(body, dict):
+ kwargs["json"] = body
+ elif isinstance(body, str):
+ kwargs["data"] = body
+ resp = self._get_session().request(method.upper(), url, **kwargs)
+ return resp
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _get(self, path: str) -> requests.Response:
+ resp = self._get_session().get(f"{self.base_url}{path}", timeout=self.timeout)
+ self._raise_for_solr_error(resp, f"GET {path}")
+ return resp
+
+ def _raise_for_solr_error(self, resp: requests.Response, operation: str) -> None:
+ if resp.ok:
+ return
+ body = self._try_parse_json(resp)
+ msg = body.get("error", {}).get("msg", resp.text) if isinstance(body, dict) else resp.text
+ raise SolrClientError(
+ f"Solr {operation} failed (HTTP {resp.status_code}): {msg}"
+ )
+
+ @staticmethod
+ def _try_parse_json(resp: requests.Response) -> dict:
+ try:
+ return resp.json()
+ except Exception:
+ return {}
+
+ @staticmethod
+ def _build_configset_zip(configset_dir: str) -> bytes:
+ """
+ Walk configset_dir and produce an in-memory ZIP suitable for
+ PUT /api/cluster/configs/{name}.
+ """
+ buf = io.BytesIO()
+ root = Path(configset_dir)
+ with zipfile.ZipFile(buf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for file_path in sorted(root.rglob("*")):
+ if file_path.is_file():
+ arcname = file_path.relative_to(root)
+ zf.write(file_path, arcname)
+ return buf.getvalue()
- return stubs
+# ---------------------------------------------------------------------------
+# SolrClient — unified client used by runners and telemetry devices
+# ---------------------------------------------------------------------------
-class UnifiedClient:
+class SolrClient(RequestContextHolder): # pylint: disable=too-many-public-methods
"""
- Unified client that wraps both OpenSearch REST client and gRPC stubs.
- This provides a single interface for runners to access both protocols.
- Acts as a transparent proxy to the OpenSearch client while adding gRPC capabilities.
+ Single unified Solr client. Wraps SolrAdminClient (admin/HTTP) and pysolr.Solr
+ (indexing/search) as private implementation details.
+
+ All runners and telemetry devices receive a SolrClient and call methods
+ on it directly — SolrAdminClient and pysolr.Solr are never referenced
+ externally.
"""
- def __init__(self, opensearch_client, grpc_stubs=None):
- self._opensearch = opensearch_client
- self._grpc_stubs = grpc_stubs
- self._logger = logging.getLogger(__name__)
-
- def __getattr__(self, name):
- """Delegate all unknown attributes to the underlying OpenSearch client."""
- return getattr(self._opensearch, name)
-
- def document_service(self, cluster_name="default"):
- """Get the gRPC DocumentService stub for the specified cluster."""
- if cluster_name in self._grpc_stubs:
- return self._grpc_stubs[cluster_name].get('document_service')
- else:
- raise exceptions.SystemSetupError(
- "gRPC DocumentService not available. Please configure --grpc-target-hosts.")
-
- def search_service(self, cluster_name="default"):
- """Get the gRPC SearchService stub for the specified cluster."""
- if cluster_name in self._grpc_stubs:
- return self._grpc_stubs[cluster_name].get('search_service')
- else:
- raise exceptions.SystemSetupError(
- "gRPC SearchService not available. Please configure --grpc-target-hosts.")
-
- def __del__(self):
- """Close all gRPC channels."""
- for cluster_stubs in self._grpc_stubs.values():
- if '_channel' in cluster_stubs:
- try:
- cluster_stubs['_channel'].close()
- except Exception as e:
- self._logger.warning("Error closing gRPC channel: %s", e)
- self._opensearch.close()
-
- @property
- def opensearch(self):
- """Provide access to the underlying OpenSearch client for explicit access."""
- return self._opensearch
-
-
-class UnifiedClientFactory:
+
+ class _NoOpTransport:
+ async def close(self):
+ pass
+
+ def __init__(self, host="localhost", port=8983, username=None, password=None,
+ tls=False, timeout=30):
+ self._host = host
+ self._port = port
+ self._username = username
+ self._password = password
+ self._tls = tls
+ self._timeout = timeout
+ self._admin = SolrAdminClient(host=host, port=port, username=username,
+ password=password, tls=tls, timeout=timeout)
+ self._pysolr_clients = {} # collection → pysolr.Solr (created lazily)
+ self.transport = SolrClient._NoOpTransport()
+
+ # ------------------------------------------------------------------
+ # Admin / cluster operations (delegated to _admin)
+ # ------------------------------------------------------------------
+
+ def info(self) -> dict:
+ """Return cluster info in an ASB-compatible shape: {name, version.number}."""
+ data = self._admin.info()
+ return {
+ "name": "Apache Solr",
+ "version": {"number": data["lucene"]["solr-spec-version"]},
+ }
+
+ def get_version(self):
+ return self._admin.get_version()
+
+ def get_major_version(self):
+ return self._admin.get_major_version()
+
+ def get_cluster_status(self):
+ return self._admin.get_cluster_status()
+
+ def get_node_metrics(self):
+ return self._admin.get_node_metrics()
+
+ def get_clusterstatus(self):
+ return self._admin.get_clusterstatus()
+
+ def get_core_status(self, core_name):
+ return self._admin.get_core_status(core_name)
+
+ def list_collections(self):
+ return self._admin.list_collections()
+
+ def get_luke_stats(self, collection):
+ return self._admin.get_luke_stats(collection)
+
+ def upload_configset(self, name, path):
+ return self._admin.upload_configset(name, path)
+
+ def delete_configset(self, name):
+ return self._admin.delete_configset(name)
+
+ def create_collection(self, name, *args, **kwargs):
+ return self._admin.create_collection(name, *args, **kwargs)
+
+ def delete_collection(self, name, **kwargs):
+ return self._admin.delete_collection(name, **kwargs)
+
+ def wait_for_cluster_ready(self, **kwargs):
+ return self._admin.wait_for_cluster_ready(**kwargs)
+
+ def raw_request(self, method, path, body=None, headers=None):
+ return self._admin.raw_request(method, path, body=body, headers=headers)
+
+ def count_documents(self, collection):
+ return self._admin.count_documents(collection)
+
+ def get_schema(self, collection):
+ return self._admin.get_schema(collection)
+
+ # Expose the admin client's internal _get for telemetry devices that
+ # need direct access to /api/node/system and similar endpoints.
+ def _get(self, path: str):
+ return self._admin._get(path)
+
+ # ------------------------------------------------------------------
+ # Data operations (delegated to pysolr.Solr, per collection)
+ # ------------------------------------------------------------------
+
+ def _get_pysolr(self, collection: str):
+ """Return (lazily-created, cached) pysolr.Solr for the given collection."""
+ import pysolr # pylint: disable=import-outside-toplevel
+ if collection not in self._pysolr_clients:
+ scheme = "https" if self._tls else "http"
+ url = f"{scheme}://{self._host}:{self._port}/solr/{collection}"
+ session = requests.Session()
+ session.trust_env = False # fork-safe on macOS (no CFNetwork proxy detection)
+ if self._username and self._password:
+ session.auth = (self._username, self._password)
+ self._pysolr_clients[collection] = pysolr.Solr(
+ url, timeout=self._timeout, always_commit=False, session=session)
+ return self._pysolr_clients[collection]
+
+ def add(self, collection, docs, **kwargs):
+ return self._get_pysolr(collection).add(docs, **kwargs)
+
+ def search(self, collection, q, **kwargs):
+ return self._get_pysolr(collection).search(q, **kwargs)
+
+ def commit(self, collection, **kwargs):
+ return self._get_pysolr(collection).commit(**kwargs)
+
+ def optimize(self, collection, **kwargs):
+ return self._get_pysolr(collection).optimize(**kwargs)
+
+
+class ClientFactory:
"""
- Factory that creates UnifiedClient instances with both REST and gRPC support.
+ Factory that creates SolrClient instances from cluster host configuration.
"""
- def __init__(self, rest_client_factory, grpc_hosts=None):
- self.rest_client_factory = rest_client_factory
- self.grpc_hosts = grpc_hosts
+
+ def __init__(self, hosts, client_options):
+ self._hosts = hosts
+ self._client_options = dict(client_options)
self.logger = logging.getLogger(__name__)
+ def _parse_host(self):
+ entry = self._hosts[0] if self._hosts else {}
+ if isinstance(entry, dict):
+ return entry.get("host", "localhost"), int(entry.get("port", 8983))
+ parts = str(entry).rsplit(":", 1)
+ host = parts[0] if parts else "localhost"
+ port = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else 8983
+ return host, port
+
def create(self):
- """Non async client is deprecated."""
- raise NotImplementedError()
+ host, port = self._parse_host()
+ return SolrClient(
+ host=host,
+ port=port,
+ username=self._client_options.get("basic_auth_user"),
+ password=self._client_options.get("basic_auth_password"),
+ tls=self._client_options.get("use_ssl", False),
+ )
def create_async(self):
- """Create a UnifiedClient with async REST client."""
- opensearch_client = self.rest_client_factory.create_async()
- grpc_stubs = None
-
- if self.grpc_hosts:
- grpc_factory = GrpcClientFactory(self.grpc_hosts)
- grpc_stubs = grpc_factory.create_grpc_stubs()
-
- return UnifiedClient(opensearch_client, grpc_stubs)
+ return self.create()
diff --git a/osbenchmark/cloud_provider/vendors/aws.py b/osbenchmark/cloud_provider/vendors/aws.py
index 2b1f7e48..05fabf8a 100644
--- a/osbenchmark/cloud_provider/vendors/aws.py
+++ b/osbenchmark/cloud_provider/vendors/aws.py
@@ -17,11 +17,7 @@
import os
import logging
-import opensearchpy
-import boto3
-from botocore.credentials import Credentials
-
-from osbenchmark import exceptions, async_connection
+from osbenchmark import exceptions
from ..cloud_provider import CloudProvider
class AWSProvider(CloudProvider):
@@ -188,22 +184,5 @@ class AWSProvider(CloudProvider):
return client_options
def create_client(self, hosts, client_options, client_class=None, use_async=False):
- self.logger.info("client options %s", client_options)
- if client_options['amazon_aws_log_in'] == "session":
- credentials = boto3.Session().get_credentials()
- else:
- credentials = Credentials(access_key=self.aws_log_in_config["aws_access_key_id"],
- secret_key=self.aws_log_in_config["aws_secret_access_key"],
- token=self.aws_log_in_config["aws_session_token"])
-
- if use_async:
- aws_auth = opensearchpy.AWSV4SignerAsyncAuth(credentials, self.aws_log_in_config["region"],
- self.aws_log_in_config["service"])
- return client_class(hosts=hosts, use_ssl=True, verify_certs=True, http_auth=aws_auth,
- connection_class=async_connection.AsyncHttpConnection,
- **client_options)
- else:
- aws_auth = opensearchpy.Urllib3AWSV4SignerAuth(credentials, self.aws_log_in_config["region"],
- self.aws_log_in_config["service"])
- return opensearchpy.OpenSearch(hosts=hosts, use_ssl=True, verify_certs=True, http_auth=aws_auth,
- connection_class=opensearchpy.Urllib3HttpConnection)
+ raise exceptions.SystemSetupError("AWS OpenSearch client creation is not supported in this build. "
+ "This benchmark tool targets Apache Solr.")
diff --git a/osbenchmark/cloud_provider/vendors/s3_data_producer.py b/osbenchmark/cloud_provider/vendors/s3_data_producer.py
index 283bf2d7..0a1b6a53 100644
--- a/osbenchmark/cloud_provider/vendors/s3_data_producer.py
+++ b/osbenchmark/cloud_provider/vendors/s3_data_producer.py
@@ -15,7 +15,11 @@ from concurrent.futures import ThreadPoolExecutor, wait
from boto3 import client
from osbenchmark import exceptions
-from osbenchmark.data_streaming.data_producer import DataProducer
+try:
+ from osbenchmark.data_streaming.data_producer import DataProducer
+except ImportError:
+ class DataProducer: # pylint: disable=too-few-public-methods
+ """Fallback when data_streaming package is not available."""
from osbenchmark.workload.ingestion_manager import IngestionManager
class S3DataProducer(DataProducer):
@@ -123,7 +127,7 @@ class S3DataProducer(DataProducer):
fh.write(rsl)
def generate_chunked_data(self):
- "Generate chunked output ready for ingestion by OSB clients."
+ "Generate chunked output ready for ingestion by ASB clients."
chunk_id = 0
partial_line = ""
downloaders = self._get_next_downloader()
diff --git a/osbenchmark/config.py b/osbenchmark/config.py
index db6ede22..6407405b 100644
--- a/osbenchmark/config.py
+++ b/osbenchmark/config.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -248,10 +251,12 @@ class Config:
(Scope.application, "benchmarks", "workload.repository.dir"): "workloads",
(Scope.application, "benchmarks", "workload.default.repository"): "default",
(Scope.application, "provisioning", "node.name.prefix"): "benchmark-node",
- (Scope.application, "provisioning", "node.http.port"): 39200,
+ (Scope.application, "provisioning", "node.http.port"): 38983,
(Scope.application, "builder", "cluster_config.repository.dir"): "cluster_configs",
(Scope.application, "builder", "cluster_config.default.repository"): "default",
-
+ # Solr-specific defaults
+ (Scope.application, "solr", "port"): 8983,
+ (Scope.application, "reporting", "datastore.type"): "in-memory",
}
def _fill_from_config_file(self, config):
@@ -292,7 +297,7 @@ def migrate(config_file, current_version, target_version, out=print, i=input):
return
if current_version < Config.EARLIEST_SUPPORTED_VERSION:
raise exceptions.ConfigError(f"The config file in {config_file.location} is too old. Please delete it "
- f"and reconfigure OSB from scratch with {PROGRAM_NAME} configure.")
+ f"and reconfigure from scratch with {PROGRAM_NAME} configure.")
logger.info("Upgrading configuration from version [%s] to [%s].", current_version, target_version)
# Something is really fishy. We don't want to downgrade the configuration.
diff --git a/osbenchmark/context.py b/osbenchmark/context.py
index a1e18be5..02d3c871 100644
--- a/osbenchmark/context.py
+++ b/osbenchmark/context.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -43,19 +46,24 @@ class RequestContextManager:
@property
def request_start(self):
- return self.ctx["request_start"]
+ return self.ctx.get("request_start")
@property
def request_end(self):
- return max((value for value in self.ctx["request_end_list"] if value < self.client_request_end))
+ end_list = self.ctx.get("request_end_list", [])
+ client_end = self.ctx.get("client_request_end")
+ if not end_list or client_end is None:
+ return None
+ valid = [v for v in end_list if v < client_end]
+ return max(valid) if valid else None
@property
def client_request_start(self):
- return self.ctx["client_request_start"]
+ return self.ctx.get("client_request_start")
@property
def client_request_end(self):
- return self.ctx["client_request_end"]
+ return self.ctx.get("client_request_end")
async def __aexit__(self, exc_type, exc_val, exc_tb):
# propagate earliest request start and most recent request end to parent
diff --git a/osbenchmark/exceptions.py b/osbenchmark/exceptions.py
index 263835a3..292dad39 100644
--- a/osbenchmark/exceptions.py
+++ b/osbenchmark/exceptions.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -25,7 +28,7 @@
class BenchmarkError(Exception):
"""
- Base class for all OSB exceptions
+ Base class for all ASB exceptions
"""
def __init__(self, message, cause=None):
@@ -135,8 +138,46 @@ class DataStreamingError(BenchmarkError):
class MappingsError(BenchmarkError):
- """Exception raised for errors in OpenSearch mappings provided.
+ """Exception raised for errors in index mappings / schema provided.
Attributes:
message -- explanation of the error
"""
+
+
+# ---------------------------------------------------------------------------
+# Abstract network / transport exceptions
+#
+# Backend-agnostic transport error hierarchy. All benchmark runners should
+# raise these so that worker_coordinator can record uniform error metadata.
+# ---------------------------------------------------------------------------
+
+class BenchmarkTransportError(BenchmarkError):
+ """HTTP/transport-level error from any benchmark target.
+
+ Attributes:
+ status_code -- integer HTTP status code, or None
+ error -- short error string / type
+ info -- additional detail (response body, exception message, …)
+ """
+
+ def __init__(self, message="", cause=None, status_code=None, error=None, info=None):
+ super().__init__(message, cause)
+ self.status_code = status_code
+ self.error = error
+ self.info = info
+
+
+class BenchmarkConnectionError(BenchmarkTransportError):
+ """Connection refused or target unreachable (fatal — node may be down)."""
+
+
+class BenchmarkConnectionTimeout(BenchmarkTransportError):
+ """Connection or request timed out."""
+
+
+class BenchmarkNotFoundError(BenchmarkTransportError):
+ """The requested resource was not found (HTTP 404)."""
+
+ def __init__(self, message="", cause=None):
+ super().__init__(message, cause=cause, status_code=404)
diff --git a/osbenchmark/log.py b/osbenchmark/log.py
index a009268f..5b6ac23d 100644
--- a/osbenchmark/log.py
+++ b/osbenchmark/log.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -45,7 +48,7 @@ def configure_utc_formatter(*args, **kwargs):
def log_config_path():
"""
- :return: The absolute path to OSB's log configuration file.
+ :return: The absolute path to ASB's log configuration file.
"""
# print("PATH: ", os.path.join(paths.benchmark_confdir(), "logging.json"))
return os.path.join(paths.benchmark_confdir(), "logging.json")
diff --git a/osbenchmark/metrics.py b/osbenchmark/metrics.py
index 0899272c..38316903 100644
--- a/osbenchmark/metrics.py
+++ b/osbenchmark/metrics.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -29,245 +32,18 @@ import logging
import math
import os
import pickle
-import random
import statistics
import sys
import time
import zlib
import webbrowser
from enum import Enum, IntEnum
-from http.client import responses
import psutil
-import opensearchpy.helpers
import tabulate
-from osbenchmark import client, time, exceptions, config, version, paths
+from osbenchmark import time, exceptions, version, paths
from osbenchmark.utils import convert, console, io, versions
from osbenchmark.visualizations.benchmark_report_renderer import render_results_html
-from osbenchmark.cloud_provider import CloudProviderFactory
-
-
-class OsClient:
- """
- Provides a stripped-down client interface that is easier to exchange for testing
- """
-
- def __init__(self, client, cluster_version=None):
- self._client = client
- self.logger = logging.getLogger(__name__)
- self._cluster_version = cluster_version
- self._cluster_distribution = None
-
- def probe_version(self):
- info = self.guarded(self._client.info)
- try:
- self._cluster_version = versions.components(info["version"]["number"])
- except BaseException:
- msg = "Could not determine version of metrics cluster"
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- try:
- self._cluster_distribution = info["version"]["distribution"]
- except BaseException:
- msg = "Could not determine distribution of metrics cluster, assuming elasticsearch"
- self.logger.exception(msg)
- self._cluster_distribution = "elasticsearch"
-
- def put_template(self, name, template):
- return self.guarded(self._client.indices.put_template, name=name, body=template)
-
- def template_exists(self, name):
- return self.guarded(self._client.indices.exists_template, name)
-
- def delete_template(self, name):
- self.guarded(self._client.indices.delete_template, name)
-
- def get_index(self, name):
- return self.guarded(self._client.indices.get, name)
-
- def create_index(self, index):
- # ignore 400 cause by IndexAlreadyExistsException when creating an index
- return self.guarded(self._client.indices.create, index=index, ignore=400)
-
- def exists(self, index):
- return self.guarded(self._client.indices.exists, index=index)
-
- def refresh(self, index):
- return self.guarded(self._client.indices.refresh, index=index)
-
- def bulk_index(self, index, doc_type, items):
- self.guarded(opensearchpy.helpers.bulk, self._client, items, index=index, chunk_size=5000)
-
- def index(self, index, doc_type, item, id=None):
- doc = {
- "_source": item
- }
- if id:
- doc["_id"] = id
- self.bulk_index(index, doc_type, [doc])
-
- def search(self, index, body):
- return self.guarded(self._client.search, index=index, body=body)
-
- def guarded(self, target, *args, **kwargs):
- # pylint: disable=import-outside-toplevel
- import opensearchpy
- max_execution_count = 11
- execution_count = 0
-
- while execution_count < max_execution_count:
- time_to_sleep = 2 ** execution_count + random.random()
- execution_count += 1
-
- try:
- return target(*args, **kwargs)
- except opensearchpy.exceptions.AuthenticationException:
- # we know that it is just one host (see OsClientFactory)
- node = self._client.transport.hosts[0]
- msg = "The configured user could not authenticate against your OpenSearch metrics store running on host [%s] at " \
- "port [%s] (wrong password?). Please fix the configuration in [%s]." % \
- (node["host"], node["port"], config.ConfigFile().location)
- self.logger.exception(msg)
- raise exceptions.SystemSetupError(msg)
- except opensearchpy.exceptions.AuthorizationException:
- node = self._client.transport.hosts[0]
- msg = "The configured user does not have enough privileges to run the operation [%s] against your OpenSearch metrics " \
- "store running on host [%s] at port [%s]. Please specify a user with enough " \
- "privileges in the configuration in [%s]." % \
- (target.__name__, node["host"], node["port"], config.ConfigFile().location)
- self.logger.exception(msg)
- raise exceptions.SystemSetupError(msg)
- except opensearchpy.exceptions.ConnectionTimeout:
- if execution_count < max_execution_count:
- self.logger.debug("Connection timeout in attempt [%d/%d].", execution_count, max_execution_count)
- time.sleep(time_to_sleep)
- else:
- operation = target.__name__
- self.logger.exception("Connection timeout while running [%s] (retried %d times).", operation, max_execution_count)
- node = self._client.transport.hosts[0]
- msg = "A connection timeout occurred while running the operation [%s] against your OpenSearch metrics store on " \
- "host [%s] at port [%s]." % (operation, node["host"], node["port"])
- raise exceptions.BenchmarkError(msg)
- except opensearchpy.exceptions.ConnectionError:
- node = self._client.transport.hosts[0]
- msg = "Could not connect to your OpenSearch metrics store. Please check that it is running on host [%s] at port [%s]" \
- " or fix the configuration in [%s]." % (node["host"], node["port"], config.ConfigFile().location)
- self.logger.exception(msg)
- raise exceptions.SystemSetupError(msg)
- except opensearchpy.TransportError as e:
- if e.status_code in (502, 503, 504, 429) and execution_count < max_execution_count:
- self.logger.debug("%s (code: %d) in attempt [%d/%d]. Sleeping for [%f] seconds.",
- responses[e.status_code], e.status_code, execution_count, max_execution_count, time_to_sleep)
- time.sleep(time_to_sleep)
- else:
- node = self._client.transport.hosts[0]
- msg = "A transport error occurred while running the operation [%s] against your OpenSearch metrics store on " \
- "host [%s] at port [%s]." % (target.__name__, node["host"], node["port"])
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- except opensearchpy.exceptions.OpenSearchException:
- node = self._client.transport.hosts[0]
- msg = "An unknown error occurred while running the operation [%s] against your OpenSearch metrics store on host [%s] " \
- "at port [%s]." % (target.__name__, node["host"], node["port"])
- self.logger.exception(msg)
- # this does not necessarily mean it's a system setup problem...
- raise exceptions.BenchmarkError(msg)
-
-
-class OsClientFactory:
- """
- Abstracts how the OpenSearch client is created. Intended for testing.
- """
-
- def __init__(self, cfg):
- self._config = cfg
- host = self._config.opts("reporting", "datastore.host")
- port = self._config.opts("reporting", "datastore.port")
- secure = convert.to_bool(self._config.opts("reporting", "datastore.secure"))
- user = self._config.opts("reporting", "datastore.user", default_value=None, mandatory=False)
- provider = CloudProviderFactory.get_provider_from_config(self._config)
-
- if user is None and provider is None:
- raise exceptions.ConfigError("To use an OpenSearch datastore, specify datastore.user or provider like datastore.amazon_aws_log_in")
- if provider:
- provider.parse_log_in_params(config=self._config, for_metrics_datastore=True)
- if user:
- try:
- password = os.environ["OSB_DATASTORE_PASSWORD"]
- except KeyError:
- try:
- password = self._config.opts("reporting", "datastore.password")
- except exceptions.ConfigError:
- raise exceptions.ConfigError(
- "No password configured through [reporting] configuration or OSB_DATASTORE_PASSWORD environment variable."
- ) from None
- verify = self._config.opts("reporting", "datastore.ssl.verification_mode", default_value="full", mandatory=False) != "none"
- ca_path = self._config.opts("reporting", "datastore.ssl.certificate_authorities", default_value=None, mandatory=False)
- self.probe_version = self._config.opts("reporting", "datastore.probe.cluster_version", default_value=True, mandatory=False)
-
- # Instead of duplicating code, we're just adapting the metrics store specific properties to match the regular client options.
- client_options = {
- "use_ssl": secure,
- "verify_certs": verify,
- "timeout": 120
- }
- if ca_path:
- client_options["ca_certs"] = ca_path
- if user and password:
- client_options["basic_auth_user"] = user
- client_options["basic_auth_password"] = password
-
- if provider:
- client_options = provider.update_client_options_for_metrics(client_options)
-
- factory = client.OsClientFactory(hosts=[{"host": host, "port": port}], client_options=client_options)
- self._client = factory.create()
-
- def create(self):
- c = OsClient(self._client)
- if self.probe_version:
- c.probe_version()
- return c
-
-
-class IndexTemplateProvider:
- """
- Abstracts how the OSB index template is retrieved. Intended for testing.
- """
-
- def __init__(self, cfg):
- self._config = cfg
- self.script_dir = self._config.opts("node", "benchmark.root")
- self._number_of_shards = self._config.opts("reporting", "datastore.number_of_shards", default_value=None, mandatory=False)
- self._number_of_replicas = self._config.opts("reporting", "datastore.number_of_replicas",
- default_value=None, mandatory=False)
-
- def metrics_template(self):
- return self._read("metrics-template")
-
- def test_runs_template(self):
- return self._read("test-runs-template")
-
- def results_template(self):
- return self._read("results-template")
-
- def _read(self, template_name):
- with open("%s/resources/%s.json" % (self.script_dir, template_name), encoding="utf-8") as f:
- template = json.load(f)
- if self._number_of_shards is not None:
- if int(self._number_of_shards) < 1:
- raise exceptions.SystemSetupError(
- f"The setting: datastore.number_of_shards must be >= 1. Please "
- f"check the configuration in {self._config.config_file.location}"
- )
- template["settings"]["index"]["number_of_shards"] = int(self._number_of_shards)
- if self._number_of_replicas is not None:
- template["settings"]["index"]["number_of_replicas"] = int(self._number_of_replicas)
- return json.dumps(template)
-
-
class MetaInfoScope(Enum):
"""
Defines the scope of a meta-information. Meta-information provides more context for a metric, for example the concrete version
@@ -307,7 +83,8 @@ def metrics_store(cfg, read_only=True, workload=None, test_procedure=None, clust
:param read_only: Whether to open the metrics store only for reading (Default: True).
:return: A metrics store implementation.
"""
- cls = metrics_store_class(cfg)
+ store_type = cfg.opts("reporting", "datastore.type", mandatory=False, default_value="in-memory")
+ cls = FilesystemMetricsStore if store_type == "filesystem" else InMemoryMetricsStore
store = cls(cfg=cfg, meta_info=meta_info)
logging.getLogger(__name__).info("Creating %s", str(store))
@@ -323,13 +100,6 @@ def metrics_store(cfg, read_only=True, workload=None, test_procedure=None, clust
return store
-def metrics_store_class(cfg):
- if cfg.opts("reporting", "datastore.type") == "opensearch":
- return OsMetricsStore
- else:
- return InMemoryMetricsStore
-
-
def extract_user_tags_from_config(cfg):
"""
Extracts user tags into a structured dict
@@ -438,7 +208,7 @@ class MetricsStore:
self.logger.info("Opening metrics store for test run timestamp=[%s], workload=[%s],"
"test_procedure=[%s], cluster_config=[%s]",
- self._test_run_timestamp, self._workload, self._test_procedure, self._cluster_config)
+ self._test_run_timestamp, self._workload, self._test_procedure, self._cluster_config_name)
user_tags = extract_user_tags_from_config(self._config)
for k, v in user_tags.items():
@@ -493,7 +263,7 @@ class MetricsStore:
def _clear_meta_info(self):
"""
- Clears all internally stored meta-info. This is considered OSB internal API and not intended for normal client consumption.
+ Clears all internally stored meta-info. This is considered ASB internal API and not intended for normal client consumption.
"""
self._meta_info = {
MetaInfoScope.cluster: {},
@@ -795,262 +565,6 @@ class MetricsStore:
"""
stats = self.get_stats(name, task, operation_type, sample_type)
return stats["avg"] if stats else None
-
-
-class OsMetricsStore(MetricsStore):
- """
- A metrics store backed by OpenSearch.
- """
- METRICS_DOC_TYPE = "_doc"
-
- def __init__(self,
- cfg,
- client_factory_class=OsClientFactory,
- index_template_provider_class=IndexTemplateProvider,
- clock=time.Clock, meta_info=None):
- """
- Creates a new metrics store.
-
- :param cfg: The config object. Mandatory.
- :param client_factory_class: This parameter is optional and needed for testing.
- :param index_template_provider_class: This parameter is optional and needed for testing.
- :param clock: This parameter is optional and needed for testing.
- :param meta_info: This parameter is optional and intended for creating a metrics store with a previously serialized meta-info.
- """
- MetricsStore.__init__(self, cfg=cfg, clock=clock, meta_info=meta_info)
- self._index = None
- self._client = client_factory_class(cfg).create()
- self._index_template_provider = index_template_provider_class(cfg)
- self._docs = None
-
- def open(self, test_run_id=None, test_run_timestamp=None, workload_name=None, \
- test_procedure_name=None, cluster_config_name=None, ctx=None, \
- create=False):
- self._docs = []
- MetricsStore.open(
- self, test_run_id, test_run_timestamp,
- workload_name, test_procedure_name,
- cluster_config_name, ctx, create)
- self._index = self.index_name()
- # reduce a bit of noise in the metrics cluster log
- if create:
- # always update the mapping to the latest version
- self._client.put_template("benchmark-metrics", self._get_template())
- if not self._client.exists(index=self._index):
- self._client.create_index(index=self._index)
- else:
- self.logger.info("[%s] already exists.", self._index)
- else:
- # we still need to check for the correct index name - prefer the one with the suffix
- new_name = self._migrated_index_name(self._index)
- if self._client.exists(index=new_name):
- self._index = new_name
-
- # ensure we can search immediately after opening
- self._client.refresh(index=self._index)
-
- def index_name(self):
- ts = time.from_is8601(self._test_run_timestamp)
- return "benchmark-metrics-%04d-%02d" % (ts.year, ts.month)
-
- def _migrated_index_name(self, original_name):
- return "{}.new".format(original_name)
-
- def _get_template(self):
- return self._index_template_provider.metrics_template()
-
- def flush(self, refresh=True):
- if self._docs:
- sw = time.StopWatch()
- sw.start()
- self._client.bulk_index(index=self._index, doc_type=OsMetricsStore.METRICS_DOC_TYPE, items=self._docs)
- sw.stop()
- self.logger.info("Successfully added %d metrics documents for test run timestamp=[%s], workload=[%s], "
- "test_procedure=[%s], cluster_config=[%s] in [%f] seconds.",
- len(self._docs), self._test_run_timestamp,
- self._workload, self._test_procedure, self._cluster_config, sw.total_time())
- self._docs = []
- # ensure we can search immediately after flushing
- if refresh:
- self._client.refresh(index=self._index)
-
- def _add(self, doc):
- self._docs.append(doc)
-
- def _get(self, name, task, operation_type, sample_type, node_name, mapper):
- query = {
- "query": self._query_by_name(name, task, operation_type, sample_type, node_name)
- }
- self.logger.debug("Issuing get against index=[%s], query=[%s].", self._index, query)
- result = self._client.search(index=self._index, body=query)
- self.logger.debug("Metrics query produced [%s] results.", result["hits"]["total"])
- return [mapper(v["_source"]) for v in result["hits"]["hits"]]
-
- def get_one(self, name, sample_type=None, node_name=None, task=None, mapper=lambda doc: doc["value"],
- sort_key=None, sort_reverse=False):
- order = "desc" if sort_reverse else "asc"
- query = {
- "query": self._query_by_name(name, task, None, sample_type, node_name),
- "size": 1
- }
- if sort_key:
- query["sort"] = [{sort_key: {"order": order}}]
- self.logger.debug("Issuing get against index=[%s], query=[%s].", self._index, query)
- result = self._client.search(index=self._index, body=query)
- hits = result["hits"]["total"]
- # OpenSearch 1.0+
- if isinstance(hits, dict):
- hits = hits["value"]
- self.logger.debug("Metrics query produced [%s] results.", hits)
- if hits > 0:
- return mapper(result["hits"]["hits"][0]["_source"])
- else:
- return None
-
- def get_error_rate(self, task, operation_type=None, sample_type=None):
- query = {
- "query": self._query_by_name("service_time", task, operation_type, sample_type, None),
- "size": 0,
- "aggs": {
- "error_rate": {
- "terms": {
- "field": "meta.success"
- }
- }
- }
- }
- self.logger.debug("Issuing get_error_rate against index=[%s], query=[%s]", self._index, query)
- result = self._client.search(index=self._index, body=query)
- buckets = result["aggregations"]["error_rate"]["buckets"]
- self.logger.debug("Query returned [%d] buckets.", len(buckets))
- count_success = 0
- count_errors = 0
- for bucket in buckets:
- k = bucket["key_as_string"]
- doc_count = int(bucket["doc_count"])
- self.logger.debug("Processing key [%s] with [%d] docs.", k, doc_count)
- if k == "true":
- count_success = doc_count
- elif k == "false":
- count_errors = doc_count
- else:
- self.logger.warning("Unrecognized bucket key [%s] with [%d] docs.", k, doc_count)
-
- if count_errors == 0:
- return 0.0
- elif count_success == 0:
- return 1.0
- else:
- return count_errors / (count_errors + count_success)
-
- def get_stats(self, name, task=None, operation_type=None, sample_type=None):
- """
- Gets standard statistics for the given metric name.
-
- :return: A metric_stats structure.
- """
- query = {
- "query": self._query_by_name(name, task, operation_type, sample_type, None),
- "size": 0,
- "aggs": {
- "metric_stats": {
- "stats": {
- "field": "value"
- }
- }
- }
- }
- self.logger.debug("Issuing get_stats against index=[%s], query=[%s]", self._index, query)
- result = self._client.search(index=self._index, body=query)
- return result["aggregations"]["metric_stats"]
-
- def get_percentiles(self, name, task=None, operation_type=None, sample_type=None, percentiles=None):
- if percentiles is None:
- percentiles = [99, 99.9, 100]
- query = {
- "query": self._query_by_name(name, task, operation_type, sample_type, None),
- "size": 0,
- "aggs": {
- "percentile_stats": {
- "percentiles": {
- "field": "value",
- "percents": percentiles
- }
- }
- }
- }
- self.logger.debug("Issuing get_percentiles against index=[%s], query=[%s]", self._index, query)
- result = self._client.search(index=self._index, body=query)
- hits = result["hits"]["total"]
- # OpenSearch 1.0+
- if isinstance(hits, dict):
- hits = hits["value"]
- self.logger.debug("get_percentiles produced %d hits", hits)
- if hits > 0:
- raw = result["aggregations"]["percentile_stats"]["values"]
- return collections.OrderedDict(sorted(raw.items(), key=lambda t: float(t[0])))
- else:
- return None
-
- def _query_by_name(self, name, task, operation_type, sample_type, node_name):
- q = {
- "bool": {
- "filter": [
- {
- "term": {
- "test-run-id": self._test_run_id
- }
- },
- {
- "term": {
- "name": name
- }
- }
- ]
- }
- }
- if task:
- q["bool"]["filter"].append({
- "term": {
- "task": task
- }
- })
- if operation_type:
- q["bool"]["filter"].append({
- "term": {
- "operation-type": operation_type
- }
- })
- if sample_type:
- q["bool"]["filter"].append({
- "term": {
- "sample-type": sample_type.name.lower()
- }
- })
- if node_name:
- q["bool"]["filter"].append({
- "term": {
- "meta.node_name": node_name
- }
- })
- return q
-
- def to_externalizable(self, clear=False):
- # no need for an externalizable representation - stores everything directly
- return None
-
- @property
- def index(self) -> str:
- return self._index
-
- @property
- def test_run_id(self) -> str:
- return self._test_run_id
-
- def __str__(self):
- return "OpenSearch metrics store"
-
-
class InMemoryMetricsStore(MetricsStore):
# Note that this implementation can run out of memory; generally, this can occur when ingesting very large corpora.
@@ -1204,6 +718,44 @@ class InMemoryMetricsStore(MetricsStore):
return "in-memory metrics store"
+class FilesystemMetricsStore(InMemoryMetricsStore):
+ """Extends InMemoryMetricsStore to also persist each metric document to disk as a JSONL file."""
+
+ def __init__(self, cfg, clock=time.Clock, meta_info=None):
+ super().__init__(cfg=cfg, clock=clock, meta_info=meta_info)
+ self._metrics_file = None
+
+ def open(self, test_run_id=None, test_run_timestamp=None, workload_name=None,
+ test_procedure_name=None, cluster_config_name=None, ctx=None, create=False):
+ super().open(test_run_id, test_run_timestamp, workload_name,
+ test_procedure_name, cluster_config_name, ctx, create)
+ if create:
+ run_dir = paths.test_run_root(self._config, test_run_id=self._test_run_id)
+ io.ensure_dir(run_dir)
+ metrics_path = os.path.join(run_dir, "metrics.jsonl")
+ # line-buffered so each metric line is flushed immediately
+ self._metrics_file = open(metrics_path, "wt", encoding="utf-8", buffering=1) # pylint: disable=consider-using-with
+ self.logger.info("FilesystemMetricsStore writing raw metrics to %s", metrics_path)
+
+ def _add(self, doc):
+ super()._add(doc)
+ if self._metrics_file is not None:
+ self._metrics_file.write(json.dumps(doc) + "\n")
+
+ def flush(self, refresh=True):
+ if self._metrics_file is not None:
+ self._metrics_file.flush()
+
+ def close(self):
+ super().close()
+ if self._metrics_file is not None:
+ self._metrics_file.close()
+ self._metrics_file = None
+
+ def __str__(self):
+ return "filesystem metrics store"
+
+
def test_run_store(cfg):
"""
Creates a proper test_run store based on the current configuration.
@@ -1211,12 +763,8 @@ def test_run_store(cfg):
:return: A test_run store implementation.
"""
logger = logging.getLogger(__name__)
- if cfg.opts("reporting", "datastore.type") == "opensearch":
- logger.info("Creating OS test run store")
- return CompositeTestRunStore(OsTestRunStore(cfg), FileTestRunStore(cfg))
- else:
- logger.info("Creating file test_run store")
- return FileTestRunStore(cfg)
+ logger.info("Creating file test_run store")
+ return FileTestRunStore(cfg)
def results_store(cfg):
@@ -1226,12 +774,8 @@ def results_store(cfg):
:return: A test_run store implementation.
"""
logger = logging.getLogger(__name__)
- if cfg.opts("reporting", "datastore.type") == "opensearch":
- logger.info("Creating OS results store")
- return OsResultsStore(cfg)
- else:
- logger.info("Creating no-op results store")
- return NoopResultsStore()
+ logger.info("Creating no-op results store")
+ return NoopResultsStore()
def list_test_helper(store_item, title):
@@ -1299,12 +843,15 @@ def create_test_run(cfg, workload, test_procedure, workload_revision=None):
# In tests, we don't get the default command-line arg value for percentiles,
# so supply them as defaults here as well
+ # Get cluster_config_instance if available (stored during provisioning)
+ cluster_config_instance = cfg.opts("builder", "cluster_config.instance", mandatory=False, default_value=None)
+
return TestRun(benchmark_version, benchmark_revision,
environment, test_run_id, test_run_timestamp,
pipeline, user_tags, workload,
workload_params, test_procedure, cluster_config, cluster_config_params,
plugin_params, workload_revision, latency_percentiles=latency_percentiles,
- throughput_percentiles=throughput_percentiles)
+ throughput_percentiles=throughput_percentiles, cluster_config_instance=cluster_config_instance)
class TestRun:
@@ -1314,7 +861,8 @@ class TestRun:
cluster_config_params, plugin_params,
workload_revision=None, cluster_config_revision=None,
distribution_version=None, distribution_flavor=None,
- revision=None, results=None, meta_data=None, latency_percentiles=None, throughput_percentiles=None):
+ revision=None, results=None, meta_data=None, latency_percentiles=None, throughput_percentiles=None,
+ cluster_config_instance=None):
if results is None:
results = {}
# this happens when the test run is created initially
@@ -1351,6 +899,7 @@ class TestRun:
self.meta_data = meta_data
self.latency_percentiles = latency_percentiles
self.throughput_percentiles = throughput_percentiles
+ self.cluster_config_instance = cluster_config_instance
@property
@@ -1409,6 +958,16 @@ class TestRun:
d["cluster-config-instance-params"] = self.cluster_config_params
if self.plugin_params:
d["plugin-params"] = self.plugin_params
+ # Add complete cluster-config specification for result portal display and time-series analysis
+ if self.cluster_config_instance:
+ d["cluster-config-spec"] = {
+ "names": self.cluster_config_instance.names if hasattr(self.cluster_config_instance, "names") else [],
+ "variables": self.cluster_config_instance.variables if hasattr(self.cluster_config_instance, "variables") else {},
+ "config_paths": self.cluster_config_instance.config_paths if hasattr(self.cluster_config_instance, "config_paths") else [],
+ "root_path": self.cluster_config_instance.root_path if hasattr(self.cluster_config_instance, "root_path") else None,
+ "provider": str(self.cluster_config_instance.provider) if hasattr(self.cluster_config_instance, "provider") else None,
+ "flavor": str(self.cluster_config_instance.flavor) if hasattr(self.cluster_config_instance, "flavor") else None,
+ }
return d
def to_result_dicts(self):
"""
@@ -1488,31 +1047,32 @@ class TestRunStore:
return int(self.cfg.opts("system", "list.test_runs.max_results"))
-# Does not inherit from TestRunStore as it is only a delegator with the same API.
+# NOT USED — retained as placeholder for a future external store (e.g. S3TestRunStore).
class CompositeTestRunStore:
"""
- Internal helper class to store test runs as file and to OpenSearch in case users
- want OpenSearch as a test runs store.
+ Placeholder delegating test-run store for a future external store integration
+ (e.g. S3TestRunStore). Delegates writes to both an external store and the local
+ file store; reads are served from the external store.
- It provides the same API as TestRunStore. It delegates writes to all stores
- and all read operations only the OpenSearch test run store.
+ Not wired into any active code path. Does not inherit from TestRunStore —
+ it is a delegator with the same API.
"""
- def __init__(self, os_store, file_store):
- self.os_store = os_store
+ def __init__(self, external_store, file_store):
+ self.external_store = external_store
self.file_store = file_store
def find_by_test_run_id(self, test_run_id):
- return self.os_store.find_by_test_run_id(test_run_id)
+ return self.external_store.find_by_test_run_id(test_run_id)
def store_test_run(self, test_run):
self.file_store.store_test_run(test_run)
- self.os_store.store_test_run(test_run)
+ self.external_store.store_test_run(test_run)
def store_html_results(self, test_run):
self.file_store.store_html_results(test_run)
def list(self):
- return self.os_store.list()
+ return self.external_store.list()
class FileTestRunStore(TestRunStore):
@@ -1607,131 +1167,6 @@ class FileTestRunStore(TestRunStore):
except BaseException:
logging.getLogger(__name__).exception("Could not load test_run file [%s] (incompatible format?) Skipping...", result)
return sorted(test_runs, key=lambda r: r.test_run_timestamp, reverse=True)
-
-
-class OsTestRunStore(TestRunStore):
- INDEX_PREFIX = "benchmark-test-runs-"
- TEST_RUN_DOC_TYPE = "_doc"
-
- def __init__(self, cfg, client_factory_class=OsClientFactory, index_template_provider_class=IndexTemplateProvider):
- """
- Creates a new metrics store.
-
- :param cfg: The config object. Mandatory.
- :param client_factory_class: This parameter is optional and needed for testing.
- :param index_template_provider_class: This parameter is optional
- and needed for testing.
- """
- super().__init__(cfg)
- self.client = client_factory_class(cfg).create()
- self.index_template_provider = index_template_provider_class(cfg)
-
- def store_test_run(self, test_run):
- doc = test_run.as_dict()
- # always update the mapping to the latest version
- self.client.put_template("benchmark-test-runs", self.index_template_provider.test_runs_template())
- self.client.index(
- index=self.index_name(test_run),
- doc_type=OsTestRunStore.TEST_RUN_DOC_TYPE,
- item=doc,
- id=test_run.test_run_id)
-
- def index_name(self, test_run):
- test_run_timestamp = test_run.test_run_timestamp
- return f"{OsTestRunStore.INDEX_PREFIX}{test_run_timestamp:%Y-%m}"
-
- def list(self):
- filters = [{
- "term": {
- "environment": self.environment_name
- }
- }]
-
- query = {
- "query": {
- "bool": {
- "filter": filters
- }
- },
- "size": self._max_results(),
- "sort": [
- {
- "test-run-timestamp": {
- "order": "desc"
- }
- }
- ]
- }
- result = self.client.search(index="%s*" % OsTestRunStore.INDEX_PREFIX, body=query)
- hits = result["hits"]["total"]
- # OpenSearch 1.0+
- if isinstance(hits, dict):
- hits = hits["value"]
- if hits > 0:
- return [TestRun.from_dict(v["_source"]) for v in result["hits"]["hits"]]
- else:
- return []
-
- def find_by_test_run_id(self, test_run_id):
- query = {
- "query": {
- "bool": {
- "filter": [
- {
- "term": {
- "test-run-id": test_run_id
- }
- }
- ]
- }
- }
- }
- result = self.client.search(index="%s*" % OsTestRunStore.INDEX_PREFIX, body=query)
- hits = result["hits"]["total"]
- # OpenSearch 1.0+
- if isinstance(hits, dict):
- hits = hits["value"]
- if hits == 1:
- return TestRun.from_dict(result["hits"]["hits"][0]["_source"])
- elif hits > 1:
- raise exceptions.BenchmarkAssertionError(
- "Expected one test run to match test ex id [{}] but there were [{}] matches.".format(test_run_id, hits))
- else:
- raise exceptions.NotFound("No test_run with test_run id [{}]".format(test_run_id))
-
-
-class OsResultsStore:
- """
- Stores the results of a test_run in a format that is
- better suited for reporting with OpenSearch Dashboards.
- """
- INDEX_PREFIX = "benchmark-results-"
- RESULTS_DOC_TYPE = "_doc"
-
- def __init__(self, cfg, client_factory_class=OsClientFactory, index_template_provider_class=IndexTemplateProvider):
- """
- Creates a new results store.
-
- :param cfg: The config object. Mandatory.
- :param client_factory_class: This parameter is optional and needed for testing.
- :param index_template_provider_class: This parameter is optional and needed for testing.
- """
- self.cfg = cfg
- self.client = client_factory_class(cfg).create()
- self.index_template_provider = index_template_provider_class(cfg)
-
- def store_results(self, test_run):
- # always update the mapping to the latest version
- self.client.put_template("benchmark-results", self.index_template_provider.results_template())
- self.client.bulk_index(index=self.index_name(test_run),
- doc_type=OsResultsStore.RESULTS_DOC_TYPE,
- items=test_run.to_result_dicts())
-
- def index_name(self, test_run):
- test_run_timestamp = test_run.test_run_timestamp
- return f"{OsResultsStore.INDEX_PREFIX}{test_run_timestamp:%Y-%m}"
-
-
class NoopResultsStore:
"""
Does not store any results separately as these are stored as part of the test_run on the file system.
@@ -2215,11 +1650,11 @@ class GlobalStats:
})
def tasks(self):
- # ensure we can read test_run.json files before OSB 0.8.0
+ # ensure we can read test_run.json files before ASB 0.8.0
return [v.get("task", v["operation"]) for v in self.op_metrics]
def metrics(self, task):
- # ensure we can read test_run.json files before OSB 0.8.0
+ # ensure we can read test_run.json files before ASB 0.8.0
for r in self.op_metrics:
if r.get("task", r["operation"]) == task:
return r
diff --git a/osbenchmark/min-os-version.txt b/osbenchmark/min-os-version.txt
deleted file mode 100644
index 3eefcb9d..00000000
--- a/osbenchmark/min-os-version.txt
+++ /dev/null
@@ -1 +0,0 @@
-1.0.0
diff --git a/osbenchmark/min-version.txt b/osbenchmark/min-version.txt
new file mode 100644
index 00000000..f7ee0669
--- /dev/null
+++ b/osbenchmark/min-version.txt
@@ -0,0 +1 @@
+9.0.0
diff --git a/osbenchmark/paths.py b/osbenchmark/paths.py
index 648dd324..61da3b58 100644
--- a/osbenchmark/paths.py
+++ b/osbenchmark/paths.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -22,31 +25,13 @@
# specific language governing permissions and limitations
# under the License.
import os
-from osbenchmark.utils.io import ensure_dir, ensure_symlink
-from osbenchmark.utils import console
+from osbenchmark.utils.io import ensure_dir
def benchmark_confdir():
default_home = os.path.expanduser("~")
- old_path = os.path.join(default_home, ".benchmark")
- new_path = os.path.join(default_home, ".osb")
-
- try:
- # Ensure .benchmark directory exists
- ensure_dir(old_path)
-
- # Ensure symlink from .osb to .benchmark
- ensure_symlink(old_path, new_path)
-
- benchmark_confdir_path = os.path.join(os.getenv("BENCHMARK_HOME", default_home), ".osb")
-
- return benchmark_confdir_path
-
- except FileNotFoundError as e:
- console.print("Error in benchmark_confdir: ", str(e))
- raise
- # fallback exception
- except Exception as e:
- console.print("Unexpected error in benchmark_confdir: ", str(e))
+ benchmark_confdir_path = os.path.join(os.getenv("BENCHMARK_HOME", default_home), ".solr-benchmark")
+ ensure_dir(benchmark_confdir_path)
+ return benchmark_confdir_path
def benchmark_root():
return os.path.dirname(os.path.realpath(__file__))
@@ -76,6 +61,6 @@ def install_root(cfg=None):
# pylint: disable=invalid-docstring-quote
def logs():
"""
- :return: The absolute path to the directory that contains OSB's log file.
+ :return: The absolute path to the directory that contains ASB's log file.
"""
return os.path.join(benchmark_confdir(), "logs")
diff --git a/osbenchmark/publisher.py b/osbenchmark/publisher.py
index 383d4c75..59e1f387 100644
--- a/osbenchmark/publisher.py
+++ b/osbenchmark/publisher.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -33,6 +36,7 @@ from enum import Enum
import tabulate
from osbenchmark import metrics, exceptions
+from osbenchmark import result_writer
from osbenchmark.utils import convert, io as rio, console
FINAL_SCORE = r"""
@@ -119,6 +123,7 @@ def comma_separated_string_to_number_list(string_list):
class SummaryResultsPublisher:
def __init__(self, results, config):
self.results = results
+ self.config = config
self.results_file = config.opts("reporting", "output.path")
self.results_format = config.opts("reporting", "format")
self.numbers_align = config.opts("reporting", "numbers.align",
@@ -134,6 +139,14 @@ class SummaryResultsPublisher:
"latency": comma_separated_string_to_number_list(config.opts("workload", "latency.percentiles", mandatory=False))
}
self.logger = logging.getLogger(__name__)
+ writer_name = config.opts("reporting", "results_writer", mandatory=False, default_value=None)
+ results_path = config.opts("reporting", "results_path", mandatory=False, default_value=None)
+ if writer_name and results_path:
+ self._result_writer = result_writer.create_writer(
+ writer_name, results_path=rio.normalize_path(results_path)
+ )
+ else:
+ self._result_writer = None
def publish_operational_statistics(self, metrics_table: list, warnings: list, record, task):
metrics_table.extend(self._publish_throughput(record, task))
@@ -225,6 +238,23 @@ class SummaryResultsPublisher:
headers=["Metric", "Task", "Value", "Unit"],
data_plain=metrics_table,
data_rich=metrics_table)
+ if self._result_writer is not None:
+ structured = [
+ {"name": row[0], "task": row[1], "value": row[2], "unit": row[3] or ""}
+ for row in metrics_table if row
+ ]
+ # Build run metadata with run_id from config and any other stats metadata
+ run_metadata = self.results.as_dict() if hasattr(self.results, "as_dict") else {}
+ run_metadata["run_id"] = self.config.opts("system", "test_run.id")
+ # Convert datetime to Unix timestamp (seconds since epoch) for JSON serialization
+ time_start = self.config.opts("system", "time.start")
+ if time_start:
+ run_metadata["timestamp"] = time_start.timestamp() if hasattr(time_start, "timestamp") else time_start
+ try:
+ self._result_writer.open(run_metadata)
+ self._result_writer.write(structured)
+ finally:
+ self._result_writer.close()
def _publish_throughput(self, values, task):
throughput = values["throughput"]
diff --git a/osbenchmark/resources/benchmark.ini b/osbenchmark/resources/benchmark.ini
index e955d155..f252f4f4 100644
--- a/osbenchmark/resources/benchmark.ini
+++ b/osbenchmark/resources/benchmark.ini
@@ -9,8 +9,8 @@ root.dir = ${CONFIG_DIR}/benchmarks
src.root.dir = ${CONFIG_DIR}/benchmarks/src
[source]
-remote.repo.url = https://github.com/opensearch-project/OpenSearch.git
-opensearch.src.subdir = opensearch
+remote.repo.url = https://github.com/apache/solr.git
+src.subdir = solr
[benchmarks]
local.dataset.cache = ${CONFIG_DIR}/benchmarks/data
@@ -25,7 +25,7 @@ datastore.password =
[workloads]
-default.url = https://github.com/opensearch-project/opensearch-benchmark-workloads
+default.url = https://github.com/janhoy/solr-benchmark-workloads
[cluster_configs]
default.dir = default-cluster-config
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/basic-license.ini b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/basic-license.ini
deleted file mode 100644
index e692532a..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/basic-license.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[meta]
-description = Basic License
-type = mixin
-
-[config]
-base = default_distro
-
-[variables]
-license_type = basic
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/default_distro/config.ini b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/default_distro/config.ini
deleted file mode 100644
index 48d1095f..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/default_distro/config.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[variables]
-# deprecated
-build_command=./gradlew :distribution:archives:linux-tar:assemble
-# new
-system.build_command = ./gradlew :distribution:archives:{{OSNAME}}-tar:assemble
-# deprecated
-artifact_path_pattern=distribution/archives/linux-tar/build/distributions/*.tar.gz
-# new
-system.artifact_path_pattern = distribution/archives/{{OSNAME}}-tar/build/distributions/*.tar.gz
-# deprecated
-release_url=https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{OSNAME}}-{{ARCH}}.tar.gz
-# new DISCLAIMER: OpenSearch already comes integrated with JDK
-jdk.bundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{OSNAME}}-{{ARCH}}.tar.gz
-jdk.unbundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{OSNAME}}-{{ARCH}}.tar.gz
-docker_image=opensearchproject/opensearch
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/trial-license.ini b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/trial-license.ini
deleted file mode 100644
index 052ba11c..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/trial-license.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[meta]
-description = Trial License
-type = mixin
-
-[config]
-base = default_distro
-
-[variables]
-license_type = trial
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled.ini b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled.ini
deleted file mode 100644
index 88c1ee0f..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[meta]
-description=Enables Netty's unpooled allocator
-type=mixin
-
-[config]
-base=unpooled
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled/templates/config/jvm.options b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled/templates/config/jvm.options
deleted file mode 100644
index fdd10358..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/unpooled/templates/config/jvm.options
+++ /dev/null
@@ -1 +0,0 @@
--Dio.netty.allocator.type=unpooled
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/README.md b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/README.md
index 0734defc..11af5965 100644
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/README.md
+++ b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/README.md
@@ -1,12 +1,12 @@
-This directory contains the OpenSearch base configuration.
+This directory contains the Solr base configuration.
### Parameters
-This configuration allows to set the following parameters with OSB 0.10.0 using `--cluster-config-instance-params`:
+This configuration allows to set the following parameters using `--cluster-config-instance-params`:
-* `data_paths` (default: "data" (relative to the OpenSearch root directory)): A string specifying the OpenSearch data path.
+* `data_paths` (default: "data" (relative to the Solr root directory)): A string specifying the Solr data path.
* `indexing_pressure_memory_limit` (default: not set): A percentage value defining the cluster setting `indexing_pressure.memory.limit`.
-* `additional_cluster_settings` (default: empty): A dictionary of key-value pairs with additional settings in `opensearch.yml`.
+* `additional_cluster_settings` (default: empty): A dictionary of key-value pairs with additional settings in `solr.xml`.
* `additional_java_settings` (default: empty): A list of additional settings in `jvm.options`. Each entry in the list will end up as one line in `jvm.options`.
It is recommended to store those settings in a JSON file that can be specified as well with `--cluster-config-instance-params`.
@@ -26,4 +26,4 @@ Example:
}
```
-Save it as `params.json` and provide it to OSB with `--cluster-config-instance-params="/path/to/params.json"`.
+Save it as `params.json` and provide it to Solr Benchmark with `--cluster-config-instance-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/config.ini b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/config.ini
index 73175bc6..fbd1070e 100644
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/config.ini
+++ b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/config.ini
@@ -1,22 +1,17 @@
[variables]
clean_command = ./gradlew clean
-# deprecated
-build_command = ./gradlew :distribution:archives:oss-linux-tar:assemble
-# new
-system.build_command = ./gradlew :distribution:archives:oss-{{OSNAME}}-tar:assemble
-# deprecated
-artifact_path_pattern = distribution/archives/oss-linux-tar/build/distributions/*.tar.gz
-# new
-system.artifact_path_pattern = distribution/archives/oss-{{OSNAME}}-tar/build/distributions/*.tar.gz
-# deprecated
-release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
-# new DISCLAIMER: OpenSearch already comes integrated with JDK
-jdk.bundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
-jdk.unbundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
+# Solr build commands (assembles the distribution tarball)
+build_command = ./gradlew assemble
+system.build_command = ./gradlew assemble
+# Solr artifact paths (tarballs are in solr/packaging/build/distributions/)
+artifact_path_pattern = solr/packaging/build/distributions/*.tgz
+system.artifact_path_pattern = solr/packaging/build/distributions/*.tgz
+# Solr distribution URLs (Apache downloads - latest versions)
+release_url = https://downloads.apache.org/solr/solr/{{VERSION}}/solr-{{VERSION}}.tgz
-docker_image=opensearchproject/opensearch
-# major version of the JDK that is used to build OpenSearch
-build.jdk = 17
-# list of JDK major versions that are used to run OpenSearch
-runtime.jdk = 17,16,15,14,13,12,11,8
-runtime.jdk.bundled = true
+docker_image=solr
+# major version of the JDK required to build Solr (main branch requires JDK 21+)
+build.jdk = 21
+# list of JDK major versions supported for running Solr (requires separate JRE installation)
+runtime.jdk = 11,17,21
+runtime.jdk.bundled = false
diff --git a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/templates/config/opensearch.yml b/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/templates/config/opensearch.yml
deleted file mode 100644
index 190ad600..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/cluster_configs/v1/vanilla/templates/config/opensearch.yml
+++ /dev/null
@@ -1,109 +0,0 @@
-# ======================== OpenSearch Configuration =========================
-#
-# NOTE: OpenSearch comes with reasonable defaults for most settings.
-# Before you set out to tweak and tune the configuration, make sure you
-# understand what are you trying to accomplish and the consequences.
-#
-# The primary way of configuring a node is via this file. This template lists
-# the most important settings you may want to configure for a production cluster.
-#
-# ---------------------------------- Cluster -----------------------------------
-#
-# Use a descriptive name for your cluster:
-#
-cluster.name: {{cluster_name}}
-#
-# ------------------------------------ Node ------------------------------------
-#
-# Use a descriptive name for the node:
-#
-node.name: {{node_name}}
-#
-# Add custom attributes to the node:
-#
-#node.attr.rack: r1
-#
-# ----------------------------------- Paths ------------------------------------
-#
-# Path to directory where to store the data (separate multiple locations by comma):
-#
-path.data: {{data_paths}}
-#
-# Path to log files:
-#
-path.logs: {{log_path}}
-#
-# ----------------------------------- Memory -----------------------------------
-#
-# Lock the memory on startup:
-#
-#bootstrap.memory_lock: true
-#
-# Make sure that the heap size is set to about half the memory available
-# on the system and that the owner of the process is allowed to use this
-# limit.
-#
-# OpenSearch performs poorly when the system is swapping the memory.
-#
-# ---------------------------------- Network -----------------------------------
-#
-# Set the bind address to a specific IP (IPv4 or IPv6):
-#
-network.host: {{network_host}}
-#
-# Set a custom port for HTTP:
-#
-http.port: {{http_port}}
-
-transport.tcp.port: {{transport_port}}
-# --------------------------------- Discovery ----------------------------------
-#
-# Pass an initial list of hosts to perform discovery when this node is started:
-# The default list of hosts is ["127.0.0.1", "[::1]"]
-#
-{%- if all_node_ips %}
-discovery.seed_hosts: {{ all_node_ips }}
-# Prevent split brain by specifying the initial master nodes.
- {%- if all_node_names is defined %}
-cluster.initial_master_nodes: {{ all_node_names }}
- {%- else %}
-cluster.initial_master_nodes: {{ all_node_ips }}
- {%- endif %}
-{%- else %}
-#discovery.seed_hosts: ["host1", "host2"]
-#cluster.initial_master_nodes: ["node-name1", "node-name2"]
-{%- endif %}
-{%- if discovery_type %}
-discovery.type: {{discovery_type}}
-{%- endif %}
-#
-#
-# ---------------------------------- Gateway -----------------------------------
-#
-# Block initial recovery after a full cluster restart until N nodes are started:
-#
-#gateway.recover_after_nodes: 3
-#
-# ---------------------------------- Various -----------------------------------
-#
-# Require explicit names when deleting indices:
-#
-#action.destructive_requires_name: true
-plugins.security.disabled: true
-
-
-{%- if indexing_pressure_memory_limit is defined %}
-indexing_pressure.memory.limit: {{indexing_pressure_memory_limit}}
-{%- endif %}
-
-{# cluster settings provided from the track #}
-{%- for key, value in cluster_settings.items() %}
-{{key}}: {{value | tojson}}
-{%- endfor %}
-
-{# cluster settings provided by the user via the command line #}
-{%- if additional_cluster_settings is defined %}
-{%- for key, value in additional_cluster_settings.items() %}
-{{key}}: {{value | tojson}}
-{%- endfor %}
-{%- endif %}
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/core-plugins.txt b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/core-plugins.txt
deleted file mode 100644
index ea9645a7..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/core-plugins.txt
+++ /dev/null
@@ -1,33 +0,0 @@
-########################################################################
-#
-# This config file is used for OSB >= 0.7.3.
-#
-# It contains the names of all plugins that are part of OpenSearch
-# core. Some of them require custom configuration and will not work
-# out of the box.
-#
-########################################################################
-analysis-icu
-analysis-kuromoji
-analysis-phonetic
-analysis-smartcn
-analysis-stempel
-analysis-ukrainian
-# 'discovery-*' requires custom config
-discovery-azure-classic
-discovery-ec2
-discovery-file
-discovery-gce
-ingest-attachment
-lang-javascript
-lang-python
-mapper-attachments
-mapper-murmur3
-mapper-size
-# 'repository-*' requires custom config
-repository-azure
-repository-gcs
-repository-hdfs
-repository-s3
-store-smb
-transport-nio
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/README.md b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/README.md
deleted file mode 100644
index 5cc75fd8..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/README.md
+++ /dev/null
@@ -1,27 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-azure` plugin.
-
-### Parameters
-
-This plugin allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-azure"`:
-
-* `azure_client_name`: A string specifying the clientname to associate the above credentials with (mandatory).
-* `azure_account`: A string specifying the Azure account name (mandatory).
-* `azure_key`: A string specifying the Azure key (mandatory).
-
-Example:
-
-`--opensearch-plugins="repository-azure" --plugin-params="azure_client_name:default,azure_account:XXXXX,azure_key:YYYYY"`
-
-Alternatively, the above settings can also be stored in a JSON file that can be specified via `--plugin-params`.
-
-Example:
-
-```json
-{
- "azure_client_name": "default",
- "azure_account": "XXXXX",
- "azure_key": "YYYYY"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-azure" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/plugin.py b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/plugin.py
deleted file mode 100644
index d03ca896..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_azure/plugin.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-import subprocess
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_azure"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} -s create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def add_property_to_keystore(keystore_binary, client_name, property_name, property_value, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- p1 = subprocess.Popen(["echo", property_value], stdout=subprocess.PIPE)
-
- keystore_command = "{keystore} --silent add --stdin azure.client.{client_name}.{key}".format(
- keystore=keystore_binary,
- client_name=client_name,
- key=property_name)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- stdin=p1.stdout,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add Azure keystore secure setting [{}]. Please see the log for details.".format(property_name))
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- keystore_params = ["azure_account", "azure_key"]
- client_name = variables.get("azure_client_name")
-
- # skip keystore configuration entirely if any of the mandatory params is missing
- if not (client_name and variables.get(keystore_params[0]) and variables.get(keystore_params[1])):
- logger.warning("Skipping keystore configuration for repository-azure as mandatory plugin-params [%s,%s,%s] were not supplied",
- "azure_client_name",
- keystore_params[0],
- keystore_params[1])
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- for property_name in keystore_params:
- # the actual OpenSearch secure settings for the azure plugin don't contain the azure_ prefix
- os_property_name = property_name.replace("azure_", "")
- property_value = variables.get(property_name)
- # skip optional properties like session_token
- if not property_value:
- continue
-
- add_property_to_keystore(keystore_binary, client_name, os_property_name, property_value, env)
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/README.md b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/README.md
deleted file mode 100644
index 64cce5cb..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/README.md
+++ /dev/null
@@ -1,27 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-gcs` plugin.
-
-### Parameters
-
-This configuration allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-gcs"`:
-
-* `gcs_credentials_file`: A string specifying the full path to the service account json file (mandatory).
-* `gcs_client_name`: A string specifying the clientname to associate the service account file under (mandatory).
-
-Example:
-
-`--opensearch-plugins="repository-gcs" --plugin-params="gcs_client_name:internalgcsclient,gcs_credentials_file:'/home/user/service_account.json'"`
-
-**IMPORTANT**: when provided in the inline format, the path to the credentials file needs to be enclosed in quotes.
-
-The above settings can also be stored in a JSON file that can be specified as well with `--plugin-params`.
-
-Example:
-
-```json
-{
- "gcs_client_name": "internalgcsclient",
- "gcs_credentials_file": "/home/user/service_account.json"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-gcs" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/plugin.py b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/plugin.py
deleted file mode 100644
index e2008679..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_gcs/plugin.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_gcs"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} --silent create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- keystore_params = ["gcs_client_name", "gcs_credentials_file"]
- client_name = variables.get(keystore_params[0])
- credentials_file = variables.get(keystore_params[1])
-
- if not (credentials_file and client_name):
- logger.warning("Skipping keystore configuration for repository-gcs as plugin-params %s were not supplied", keystore_params)
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- keystore_command = "{keystore} --silent add-file gcs.client.{client_name}.credentials_file {credentials_file}".format(
- keystore=keystore_binary,
- client_name=client_name,
- credentials_file=credentials_file)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add GCS keystore secure setting. Please see the log for details.")
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/README.md b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/README.md
deleted file mode 100644
index f68261aa..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/README.md
+++ /dev/null
@@ -1,29 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-s3` plugin.
-
-### Parameters
-
-This plugin allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-s3"`:
-
-* `s3_client_name`: A string specifying the clientname to associate the above credentials with (mandatory).
-* `s3_access_key`: A string specifying the AWS access key (mandatory).
-* `s3_secret_key`: A string specifying the AWS secret key (mandatory).
-* `s3_session_token`: A string specifying the AWS session token (optional).
-
-Example:
-
-`--opensearch-plugins="repository-s3" --plugin-params="s3_client_name:mys3client,s3_access_key:XXXXX,s3_secret_key:YYYYY,s3_session_token:ZZZZZ"`
-
-Alternatively, the above settings can also be stored in a JSON file that can be specified via `--plugin-params`.
-
-Example:
-
-```json
-{
- "s3_client_name": "mys3client",
- "s3_access_key": "XXXXX",
- "s3_secret_key": "YYYYY",
- "s3_session_token": "ZZZZZ"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-s3" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/plugin.py b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/plugin.py
deleted file mode 100644
index 44249b59..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/repository_s3/plugin.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-import subprocess
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_s3"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} -s create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def add_property_to_keystore(keystore_binary, client_name, property_name, property_value, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- p1 = subprocess.Popen(["echo", property_value], stdout=subprocess.PIPE)
-
- keystore_command = "{keystore} --silent add --stdin s3.client.{client_name}.{key}".format(
- keystore=keystore_binary,
- client_name=client_name,
- key=property_name)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- stdin=p1.stdout,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add S3 keystore secure setting [{}]. Please see the log for details.".format(property_name))
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- # s3_session_token is optional
- keystore_params = ["s3_access_key", "s3_secret_key", "s3_session_token"]
- client_name = variables.get("s3_client_name")
-
- # skip keystore configuration entirely if any of the mandatory params is missing
- if not (client_name and variables.get(keystore_params[0]) and variables.get(keystore_params[1])):
- logger.warning("Skipping keystore configuration for repository-s3 as mandatory plugin-params [%s,%s,%s] were not supplied",
- "s3_client_name",
- keystore_params[0],
- keystore_params[1])
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- for property_name in keystore_params:
- # the actual OpenSearch secure settings for the s3 plugin don't contain the s3_ prefix
- os_property_name = property_name.replace("s3_", "")
- property_value = variables.get(property_name)
- # skip optional properties like session_token
- if not property_value:
- continue
-
- add_property_to_keystore(keystore_binary, client_name, os_property_name, property_value, env)
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/default/templates/config/opensearch.yml b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/default/templates/config/opensearch.yml
deleted file mode 100644
index 5d42b113..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/default/templates/config/opensearch.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-{%- if nio_transport_enabled is defined and nio_transport_enabled %}transport.type: nio-transport
-{% endif %}
-{%- if nio_http_enabled is defined and nio_http_enabled %}http.type: nio-http-transport
-{% endif %}
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/http.ini b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/http.ini
deleted file mode 100644
index 3e94f096..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/http.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[config]
-base = default
-
-[variables]
-nio_http_enabled = true
diff --git a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/transport.ini b/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/transport.ini
deleted file mode 100644
index 51d516be..00000000
--- a/osbenchmark/resources/cluster_configs/1.0/plugins/v1/transport_nio/transport.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[config]
-base = default
-
-[variables]
-nio_transport_enabled = true
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/basic-license.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/basic-license.ini
deleted file mode 100644
index eadec0ec..00000000
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/basic-license.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[meta]
-description = Basic License
-type = mixin
-
-[config]
-base = vanilla
-
-[variables]
-license_type = basic
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/defaults.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/defaults.ini
index c034ca2f..d03f35c0 100644
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/defaults.ini
+++ b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/defaults.ini
@@ -6,5 +6,4 @@ type=cluster-config
base=vanilla
[variables]
-license_type = basic
heap_size=1g
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/g1gc.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/g1gc.ini
index c1721559..0e4ba726 100644
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/g1gc.ini
+++ b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/g1gc.ini
@@ -6,6 +6,4 @@ type=mixin
base=vanilla
[variables]
-use_cms_gc=false
-use_parallel_gc=false
-use_g1_gc=true
+gc_tune=-XX:+UseG1GC -XX:+UseStringDeduplication
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/parallelgc.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/parallelgc.ini
index 55366b7c..ed7d0731 100644
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/parallelgc.ini
+++ b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/parallelgc.ini
@@ -6,6 +6,4 @@ type=mixin
base=vanilla
[variables]
-use_cms_gc=false
-use_g1_gc=false
-use_parallel_gc=true
+gc_tune=-XX:+UseParallelGC
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/trial-license.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/trial-license.ini
deleted file mode 100644
index f2192f25..00000000
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/trial-license.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[meta]
-description = Trial License
-type = mixin
-
-[config]
-base = vanilla
-
-[variables]
-license_type = trial
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled.ini
deleted file mode 100644
index 88c1ee0f..00000000
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[meta]
-description=Enables Netty's unpooled allocator
-type=mixin
-
-[config]
-base=unpooled
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled/templates/config/jvm.options b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled/templates/config/jvm.options
deleted file mode 100644
index fdd10358..00000000
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/unpooled/templates/config/jvm.options
+++ /dev/null
@@ -1 +0,0 @@
--Dio.netty.allocator.type=unpooled
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/README.md b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/README.md
index 0ab58263..11af5965 100644
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/README.md
+++ b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/README.md
@@ -1,12 +1,12 @@
-This directory contains the OpenSearch base configuration.
+This directory contains the Solr base configuration.
### Parameters
This configuration allows to set the following parameters using `--cluster-config-instance-params`:
-* `data_paths` (default: "data" (relative to the OpenSearch root directory)): A string specifying the OpenSearch data path.
+* `data_paths` (default: "data" (relative to the Solr root directory)): A string specifying the Solr data path.
* `indexing_pressure_memory_limit` (default: not set): A percentage value defining the cluster setting `indexing_pressure.memory.limit`.
-* `additional_cluster_settings` (default: empty): A dictionary of key-value pairs with additional settings in `opensearch.yml`.
+* `additional_cluster_settings` (default: empty): A dictionary of key-value pairs with additional settings in `solr.xml`.
* `additional_java_settings` (default: empty): A list of additional settings in `jvm.options`. Each entry in the list will end up as one line in `jvm.options`.
It is recommended to store those settings in a JSON file that can be specified as well with `--cluster-config-instance-params`.
@@ -26,4 +26,4 @@ Example:
}
```
-Save it as `params.json` and provide it to OSB with `--cluster-config-instance-params="/path/to/params.json"`.
+Save it as `params.json` and provide it to Solr Benchmark with `--cluster-config-instance-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/config.ini b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/config.ini
index a09e14e2..fbd1070e 100644
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/config.ini
+++ b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/config.ini
@@ -1,22 +1,17 @@
[variables]
clean_command = ./gradlew clean
-# deprecated
-build_command = ./gradlew :distribution:archives:linux-tar:assemble
-# new
-system.build_command = ./gradlew :distribution:archives:{{OSNAME}}-tar:assemble
-# deprecated
-artifact_path_pattern = distribution/archives/linux-tar/build/distributions/*.tar.gz
-# new
-system.artifact_path_pattern = distribution/archives/{{OSNAME}}-tar/build/distributions/*.tar.gz
-# deprecated
-release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
-# new DISCLAIMER: OpenSearch already comes integrated with JDK
-jdk.bundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
-jdk.unbundled.release_url = https://artifacts.opensearch.org/releases/bundle/opensearch/{{VERSION}}/opensearch-{{VERSION}}-{{OSNAME}}-{{ARCH}}.tar.gz
+# Solr build commands (assembles the distribution tarball)
+build_command = ./gradlew assemble
+system.build_command = ./gradlew assemble
+# Solr artifact paths (tarballs are in solr/packaging/build/distributions/)
+artifact_path_pattern = solr/packaging/build/distributions/*.tgz
+system.artifact_path_pattern = solr/packaging/build/distributions/*.tgz
+# Solr distribution URLs (Apache downloads - latest versions)
+release_url = https://downloads.apache.org/solr/solr/{{VERSION}}/solr-{{VERSION}}.tgz
-docker_image=opensearchproject/opensearch
-# major version of the JDK that is used to build OpenSearch
+docker_image=solr
+# major version of the JDK required to build Solr (main branch requires JDK 21+)
build.jdk = 21
-# list of JDK major versions that are used to run OpenSearch
-runtime.jdk = 21,17,16,15,14,13,12,11,8
-runtime.jdk.bundled = true
+# list of JDK major versions supported for running Solr (requires separate JRE installation)
+runtime.jdk = 11,17,21
+runtime.jdk.bundled = false
diff --git a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/templates/config/opensearch.yml b/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/templates/config/opensearch.yml
deleted file mode 100644
index 820db9a1..00000000
--- a/osbenchmark/resources/cluster_configs/main/cluster_configs/v1/vanilla/templates/config/opensearch.yml
+++ /dev/null
@@ -1,109 +0,0 @@
-# ======================== OpenSearch Configuration =========================
-#
-# NOTE: OpenSearch comes with reasonable defaults for most settings.
-# Before you set out to tweak and tune the configuration, make sure you
-# understand what are you trying to accomplish and the consequences.
-#
-# The primary way of configuring a node is via this file. This template lists
-# the most important settings you may want to configure for a production cluster.
-#
-# ---------------------------------- Cluster -----------------------------------
-#
-# Use a descriptive name for your cluster:
-#
-cluster.name: {{cluster_name}}
-#
-# ------------------------------------ Node ------------------------------------
-#
-# Use a descriptive name for the node:
-#
-node.name: {{node_name}}
-#
-# Add custom attributes to the node:
-#
-#node.attr.rack: r1
-#
-# ----------------------------------- Paths ------------------------------------
-#
-# Path to directory where to store the data
-#
-path.data: {{data_paths[0]}}
-#
-# Path to log files:
-#
-path.logs: {{log_path}}
-#
-# ----------------------------------- Memory -----------------------------------
-#
-# Lock the memory on startup:
-#
-#bootstrap.memory_lock: true
-#
-# Make sure that the heap size is set to about half the memory available
-# on the system and that the owner of the process is allowed to use this
-# limit.
-#
-# OpenSearch performs poorly when the system is swapping the memory.
-#
-# ---------------------------------- Network -----------------------------------
-#
-# Set the bind address to a specific IP (IPv4 or IPv6):
-#
-network.host: {{network_host}}
-#
-# Set a custom port for HTTP:
-#
-http.port: {{http_port}}
-
-transport.port: {{transport_port}}
-#
-# --------------------------------- Discovery ----------------------------------
-#
-# Pass an initial list of hosts to perform discovery when this node is started:
-# The default list of hosts is ["127.0.0.1", "[::1]"]
-#
-{%- if all_node_ips %}
-discovery.seed_hosts: {{ all_node_ips }}
-# Prevent split brain by specifying the initial master nodes.
- {%- if all_node_names is defined %}
-cluster.initial_master_nodes: {{ all_node_names }}
- {%- else %}
-cluster.initial_master_nodes: {{ all_node_ips }}
- {%- endif %}
-{%- else %}
-#discovery.seed_hosts: ["host1", "host2"]
-#cluster.initial_master_nodes: ["node-name1", "node-name2"]
-{%- endif %}
-{%- if discovery_type %}
-discovery.type: {{discovery_type}}
-{%- endif %}
-#
-#
-# ---------------------------------- Gateway -----------------------------------
-#
-# Block initial recovery after a full cluster restart until N nodes are started:
-#
-#gateway.recover_after_nodes: 3
-#
-#
-# ---------------------------------- Various -----------------------------------
-#
-# Allow wildcard deletion of indices:
-#
-action.destructive_requires_name: false
-
-{%- if indexing_pressure_memory_limit is defined %}
-indexing_pressure.memory.limit: {{indexing_pressure_memory_limit}}
-{%- endif %}
-
-{# cluster settings provided from the track #}
-{%- for key, value in cluster_settings.items() %}
-{{key}}: {{value | tojson}}
-{%- endfor %}
-
-{# cluster settings provided by the user via the command line #}
-{%- if additional_cluster_settings is defined %}
-{%- for key, value in additional_cluster_settings.items() %}
-{{key}}: {{value | tojson}}
-{%- endfor %}
-{%- endif %}
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/core-plugins.txt b/osbenchmark/resources/cluster_configs/main/plugins/v1/core-plugins.txt
deleted file mode 100644
index ea9645a7..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/core-plugins.txt
+++ /dev/null
@@ -1,33 +0,0 @@
-########################################################################
-#
-# This config file is used for OSB >= 0.7.3.
-#
-# It contains the names of all plugins that are part of OpenSearch
-# core. Some of them require custom configuration and will not work
-# out of the box.
-#
-########################################################################
-analysis-icu
-analysis-kuromoji
-analysis-phonetic
-analysis-smartcn
-analysis-stempel
-analysis-ukrainian
-# 'discovery-*' requires custom config
-discovery-azure-classic
-discovery-ec2
-discovery-file
-discovery-gce
-ingest-attachment
-lang-javascript
-lang-python
-mapper-attachments
-mapper-murmur3
-mapper-size
-# 'repository-*' requires custom config
-repository-azure
-repository-gcs
-repository-hdfs
-repository-s3
-store-smb
-transport-nio
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/README.md b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/README.md
deleted file mode 100644
index 5cc75fd8..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/README.md
+++ /dev/null
@@ -1,27 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-azure` plugin.
-
-### Parameters
-
-This plugin allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-azure"`:
-
-* `azure_client_name`: A string specifying the clientname to associate the above credentials with (mandatory).
-* `azure_account`: A string specifying the Azure account name (mandatory).
-* `azure_key`: A string specifying the Azure key (mandatory).
-
-Example:
-
-`--opensearch-plugins="repository-azure" --plugin-params="azure_client_name:default,azure_account:XXXXX,azure_key:YYYYY"`
-
-Alternatively, the above settings can also be stored in a JSON file that can be specified via `--plugin-params`.
-
-Example:
-
-```json
-{
- "azure_client_name": "default",
- "azure_account": "XXXXX",
- "azure_key": "YYYYY"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-azure" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/plugin.py b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/plugin.py
deleted file mode 100644
index d03ca896..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_azure/plugin.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-import subprocess
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_azure"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} -s create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def add_property_to_keystore(keystore_binary, client_name, property_name, property_value, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- p1 = subprocess.Popen(["echo", property_value], stdout=subprocess.PIPE)
-
- keystore_command = "{keystore} --silent add --stdin azure.client.{client_name}.{key}".format(
- keystore=keystore_binary,
- client_name=client_name,
- key=property_name)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- stdin=p1.stdout,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add Azure keystore secure setting [{}]. Please see the log for details.".format(property_name))
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- keystore_params = ["azure_account", "azure_key"]
- client_name = variables.get("azure_client_name")
-
- # skip keystore configuration entirely if any of the mandatory params is missing
- if not (client_name and variables.get(keystore_params[0]) and variables.get(keystore_params[1])):
- logger.warning("Skipping keystore configuration for repository-azure as mandatory plugin-params [%s,%s,%s] were not supplied",
- "azure_client_name",
- keystore_params[0],
- keystore_params[1])
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- for property_name in keystore_params:
- # the actual OpenSearch secure settings for the azure plugin don't contain the azure_ prefix
- os_property_name = property_name.replace("azure_", "")
- property_value = variables.get(property_name)
- # skip optional properties like session_token
- if not property_value:
- continue
-
- add_property_to_keystore(keystore_binary, client_name, os_property_name, property_value, env)
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/README.md b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/README.md
deleted file mode 100644
index 64cce5cb..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/README.md
+++ /dev/null
@@ -1,27 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-gcs` plugin.
-
-### Parameters
-
-This configuration allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-gcs"`:
-
-* `gcs_credentials_file`: A string specifying the full path to the service account json file (mandatory).
-* `gcs_client_name`: A string specifying the clientname to associate the service account file under (mandatory).
-
-Example:
-
-`--opensearch-plugins="repository-gcs" --plugin-params="gcs_client_name:internalgcsclient,gcs_credentials_file:'/home/user/service_account.json'"`
-
-**IMPORTANT**: when provided in the inline format, the path to the credentials file needs to be enclosed in quotes.
-
-The above settings can also be stored in a JSON file that can be specified as well with `--plugin-params`.
-
-Example:
-
-```json
-{
- "gcs_client_name": "internalgcsclient",
- "gcs_credentials_file": "/home/user/service_account.json"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-gcs" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/plugin.py b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/plugin.py
deleted file mode 100644
index a77aa7bf..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_gcs/plugin.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_gcs"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} --silent create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- keystore_params = ["gcs_client_name", "gcs_credentials_file"]
- client_name = variables.get(keystore_params[0])
- credentials_file = variables.get(keystore_params[1])
-
- if not (credentials_file and client_name):
- logger.warning("Skipping keystore configuration for repository-gcs as plugin-params %s were not supplied", keystore_params)
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- keystore_command = "{keystore} --silent add-file gcs.client.{client_name}.credentials_file {credentials_file}".format(
- keystore=keystore_binary,
- client_name=client_name,
- credentials_file=credentials_file)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add GCS keystore secure setting. Please see the log for details.")
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/README.md b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/README.md
deleted file mode 100644
index 8f274885..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-This directory contains the (optional) keystore configuration for the `repository-s3` plugin.
-For more details on secure settings for the repository-s3 plugin please refer to the repository-s3-client documentation.
-
-### Parameters
-
-This plugin allows to set the following parameters with OSB using `--plugin-params` in combination with `--opensearch-plugins="repository-s3"`:
-
-* `s3_client_name`: A string specifying the clientname to associate the above credentials with (mandatory).
-* `s3_access_key`: A string specifying the AWS access key (mandatory).
-* `s3_secret_key`: A string specifying the AWS secret key (mandatory).
-* `s3_session_token`: A string specifying the AWS session token (optional).
-
-Example:
-
-`--opensearch-plugins="repository-s3" --plugin-params="s3_client_name:mys3client,s3_access_key:XXXXX,s3_secret_key:YYYYY,s3_session_token:ZZZZZ"`
-
-Alternatively, the above settings can also be stored in a JSON file that can be specified via `--plugin-params`.
-
-Example:
-
-```json
-{
- "s3_client_name": "mys3client",
- "s3_access_key": "XXXXX",
- "s3_secret_key": "YYYYY",
- "s3_session_token": "ZZZZZ"
-}
-```
-
-Save it as `params.json` and provide it to OSB with `--opensearch-plugins="repository-s3" --plugin-params="/path/to/params.json"`.
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/plugin.py b/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/plugin.py
deleted file mode 100644
index 44249b59..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/repository_s3/plugin.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-#
-# The OpenSearch Contributors require contributions made to
-# this file be licensed under the Apache-2.0 license or a
-# compatible open source license.
-# Modifications Copyright OpenSearch Contributors. See
-# GitHub history for details.
-
-# Licensed to Elasticsearch B.V. under one or more contributor
-# license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright
-# ownership. Elasticsearch B.V. licenses this file to you under
-# the Apache License, Version 2.0 (the "License"); you may
-# not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import logging
-import os
-import subprocess
-
-from osbenchmark.utils import process
-from osbenchmark import exceptions
-
-LOGGER_NAME = "osbenchmark.provisioner.repository_s3"
-
-
-def resolve_binary(install_root, binary_name):
- return os.path.join(install_root, "bin", binary_name)
-
-
-def resolve_keystore_config(install_root):
- return os.path.join(install_root, "config", "opensearch.keystore")
-
-
-def create_keystore(install_root, keystore_binary, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- keystore_create_command = "{keystore} -s create".format(keystore=keystore_binary)
-
- return_code = process.run_subprocess_with_logging(
- keystore_create_command,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_create_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not initialize a keystore. Please see the log for details.")
-
-
-def add_property_to_keystore(keystore_binary, client_name, property_name, property_value, env):
- logger = logging.getLogger(LOGGER_NAME)
-
- p1 = subprocess.Popen(["echo", property_value], stdout=subprocess.PIPE)
-
- keystore_command = "{keystore} --silent add --stdin s3.client.{client_name}.{key}".format(
- keystore=keystore_binary,
- client_name=client_name,
- key=property_name)
-
- return_code = process.run_subprocess_with_logging(
- keystore_command,
- stdin=p1.stdout,
- env=env
- )
-
- if return_code != 0:
- logger.error("%s has exited with code [%d]", keystore_command, return_code)
- raise exceptions.SystemSetupError(
- "Could not add S3 keystore secure setting [{}]. Please see the log for details.".format(property_name))
-
-
-def configure_keystore(config_names, variables, **kwargs):
- logger = logging.getLogger(LOGGER_NAME)
- # s3_session_token is optional
- keystore_params = ["s3_access_key", "s3_secret_key", "s3_session_token"]
- client_name = variables.get("s3_client_name")
-
- # skip keystore configuration entirely if any of the mandatory params is missing
- if not (client_name and variables.get(keystore_params[0]) and variables.get(keystore_params[1])):
- logger.warning("Skipping keystore configuration for repository-s3 as mandatory plugin-params [%s,%s,%s] were not supplied",
- "s3_client_name",
- keystore_params[0],
- keystore_params[1])
- return False
-
- keystore_binary_filename = "opensearch-keystore"
- install_root = variables["install_root_path"]
- keystore_binary = resolve_binary(install_root, keystore_binary_filename)
- env = kwargs.get("env")
-
- if not os.path.isfile(resolve_keystore_config(install_root)):
- create_keystore(install_root, keystore_binary, env)
-
- for property_name in keystore_params:
- # the actual OpenSearch secure settings for the s3 plugin don't contain the s3_ prefix
- os_property_name = property_name.replace("s3_", "")
- property_value = variables.get(property_name)
- # skip optional properties like session_token
- if not property_value:
- continue
-
- add_property_to_keystore(keystore_binary, client_name, os_property_name, property_value, env)
-
- # Success
- return True
-
-
-def register(registry):
- registry.register("post_install", configure_keystore)
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/default/templates/config/opensearch.yml b/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/default/templates/config/opensearch.yml
deleted file mode 100644
index 5d42b113..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/default/templates/config/opensearch.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-{%- if nio_transport_enabled is defined and nio_transport_enabled %}transport.type: nio-transport
-{% endif %}
-{%- if nio_http_enabled is defined and nio_http_enabled %}http.type: nio-http-transport
-{% endif %}
\ No newline at end of file
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/http.ini b/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/http.ini
deleted file mode 100644
index 3e94f096..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/http.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[config]
-base = default
-
-[variables]
-nio_http_enabled = true
diff --git a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/transport.ini b/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/transport.ini
deleted file mode 100644
index 51d516be..00000000
--- a/osbenchmark/resources/cluster_configs/main/plugins/v1/transport_nio/transport.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[config]
-base = default
-
-[variables]
-nio_transport_enabled = true
diff --git a/osbenchmark/resources/custom-test-procedures.json.j2 b/osbenchmark/resources/custom-test-procedures.json.j2
index 5fc247db..2fb362fc 100644
--- a/osbenchmark/resources/custom-test-procedures.json.j2
+++ b/osbenchmark/resources/custom-test-procedures.json.j2
@@ -1,6 +1,6 @@
{
"name": "custom-test-procedures",
- "description": "Customized test procedure with custom operations generated by create-workload feature in OpenSearch Benchmark.",
+ "description": "Customized test procedure with custom operations generated by create-workload feature in Solr Benchmark.",
"default": true,
"schedule": [
{
diff --git a/osbenchmark/resources/default-test-procedures.json.j2 b/osbenchmark/resources/default-test-procedures.json.j2
index b8f4c73d..60863aab 100644
--- a/osbenchmark/resources/default-test-procedures.json.j2
+++ b/osbenchmark/resources/default-test-procedures.json.j2
@@ -1,6 +1,6 @@
{
"name": "default-test-procedure",
- "description": "Customized test procedure with custom operations generated by create-workload feature in OpenSearch Benchmark. Workload deletes existing indexes, creates indexes, ingests documents, and runs default match-all query.",
+ "description": "Customized test procedure with custom operations generated by create-workload feature in Solr Benchmark. Workload deletes existing indexes, creates indexes, ingests documents, and runs default match-all query.",
"default": true,
"schedule": [
{
diff --git a/osbenchmark/resources/docker-compose.yml.j2 b/osbenchmark/resources/docker-compose.yml.j2
index 4ced6b46..4e19aca9 100644
--- a/osbenchmark/resources/docker-compose.yml.j2
+++ b/osbenchmark/resources/docker-compose.yml.j2
@@ -1,10 +1,10 @@
version: '3'
services:
- opensearch-node1:
- image: {{docker_image}}:{{os_version}}
- container_name: opensearch-node1
+ solr-node1:
+ image: {{docker_image}}:{{solr_version}}
+ container_name: solr-node1
labels:
- io.benchmark.description: "opensearch-benchmark"
+ io.benchmark.description: "solr-benchmark"
{%- if docker_cpu_count is defined %}
cpu_count: {{docker_cpu_count}}
{%- endif %}
@@ -12,39 +12,29 @@ services:
mem_limit: {{docker_mem_limit}}
{%- endif %}
environment:
- - cluster.name=opensearch-cluster
- - node.name=opensearch-node1
- - discovery.seed_hosts=opensearch-node1
- - DISABLE_INSTALL_DEMO_CONFIG=true
- - bootstrap.memory_lock=true
- - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m"
+ - "SOLR_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
- memlock:
- soft: -1
- hard: -1
nofile:
soft: 65536
hard: 65536
volumes:
- - {{os_data_dir}}:/usr/share/opensearch/data
- - {{os_log_dir}}:/var/log/opensearch
- - {{os_heap_dump_dir}}:/usr/share/opensearch/heapdump
+ - {{solr_data_dir}}:/var/solr/data
+ - {{solr_log_dir}}:/var/solr/logs
+ - {{solr_heap_dump_dir}}:/var/solr/heapdump
{%- for host_path, docker_path in mounts.items() %}
- {{host_path}}:{{docker_path}}
{%- endfor %}
ports:
- - {{http_port}}:{{http_port}}
- - 9200:9200
- - 9600:9600
+ - {{http_port}}:8983
networks:
- - opensearch-net
+ - solr-net
healthcheck:
- test: curl -f http://localhost:{{http_port}} -u admin:admin --insecure
+ test: curl -f http://localhost:8983/solr/admin/ping
interval: 5s
timeout: 2s
retries: 10
volumes:
- opensearch-data1:
+ solr-data1:
networks:
- opensearch-net:
\ No newline at end of file
+ solr-net:
diff --git a/osbenchmark/resources/workload-schema.json b/osbenchmark/resources/workload-schema.json
index 5f4b637e..0334ea41 100644
--- a/osbenchmark/resources/workload-schema.json
+++ b/osbenchmark/resources/workload-schema.json
@@ -1,7 +1,7 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "workload",
- "description": "Specification of workloads for OSB",
+ "description": "Specification of workloads for ASB",
"type": "object",
"definitions": {
"schedule": {
@@ -97,7 +97,7 @@
},
"schedule": {
"type": "string",
- "description": "Defines the scheduling strategy that is used for throughput throttled operations. Out of the box, OSB supports 'deterministic' (default) and 'poisson' but you can implement your own schedules."
+ "description": "Defines the scheduling strategy that is used for throughput throttled operations. Out of the box, ASB supports 'deterministic' (default) and 'poisson' but you can implement your own schedules."
},
"target-throughput": {
"anyOf": [
@@ -109,7 +109,7 @@
"type": "string"
}
],
- "description": "Defines the number of operations per second that OSB should attempt to run."
+ "description": "Defines the number of operations per second that ASB should attempt to run."
},
"target-interval": {
"type": "number",
@@ -185,7 +185,7 @@
"type": "string"
}
],
- "description": "Defines the number of operations per second that OSB should attempt to run."
+ "description": "Defines the number of operations per second that ASB should attempt to run."
},
"target-interval": {
"type": "number",
@@ -206,7 +206,7 @@
},
"default": {
"type": "boolean",
- "description": "If true, OSB should select this test_procedure as the default test_procedure if the user does not specify one on the command line."
+ "description": "If true, ASB should select this test_procedure as the default test_procedure if the user does not specify one on the command line."
},
"meta": {
"type": "object",
@@ -387,11 +387,11 @@
"base-url": {
"type": "string",
"format": "uri",
- "description": "The default base URL for this document corpus. Has to be a publicly accessible http or https URL. If not specified, OSB will not attempt to download data and assume that it will be available locally."
+ "description": "The default base URL for this document corpus. Has to be a publicly accessible http or https URL. If not specified, ASB will not attempt to download data and assume that it will be available locally."
},
"source-format": {
"type": "string",
- "description": "Defines in which format OSB should interpret the data file specified by 'source-file'. Currently, only 'bulk' is supported."
+ "description": "Defines in which format ASB should interpret the data file specified by 'source-file'. Currently, only 'bulk' is supported."
},
"streaming-ingestion": {
"type": "string",
@@ -459,7 +459,7 @@
},
"source-format": {
"type": "string",
- "description": "Defines in which format OSB should interpret the data file specified by 'source-file'. Currently, only 'bulk' is supported."
+ "description": "Defines in which format ASB should interpret the data file specified by 'source-file'. Currently, only 'bulk' is supported."
},
"document-count": {
"type": "integer",
@@ -473,7 +473,7 @@
"compressed-bytes": {
"type": "integer",
"minimum": 1,
- "description": "The size in bytes of the compressed document file. This number is used to show users how much data will be downloaded by OSB and also to check whether the download is complete."
+ "description": "The size in bytes of the compressed document file. This number is used to show users how much data will be downloaded by ASB and also to check whether the download is complete."
},
"uncompressed-bytes": {
"type": "integer",
@@ -568,15 +568,15 @@
},
"cache": {
"type": "boolean",
- "description": "[Only for type 'search']: Whether to use the query request cache. By default, OSB will define no value thus the default depends on the benchmark candidate settings and OpenSearch version."
+ "description": "[Only for type 'search']: Whether to use the query request cache. By default, ASB will define no value thus the default depends on the benchmark candidate settings and Solr version."
},
"index": {
"type": "string",
- "description": "[Only for type 'search']: The index or index pattern against which the query should be executed. This property is only necessary if there is more than one index or the index contains more than one type. Otherwise, OSB will derive the index and type by itself."
+ "description": "[Only for type 'search']: The index or index pattern against which the query should be executed. This property is only necessary if there is more than one index or the index contains more than one type. Otherwise, ASB will derive the index and type by itself."
},
"type": {
"type": "string",
- "description": "[Only for type 'search']: The type against which the query should be executed. This property is only necessary if there is more than one index or the index contains more than one type. Otherwise, OSB will derive the index and type by itself."
+ "description": "[Only for type 'search']: The type against which the query should be executed. This property is only necessary if there is more than one index or the index contains more than one type. Otherwise, ASB will derive the index and type by itself."
},
"pages": {
"type": "integer",
diff --git a/osbenchmark/synthetic_data_generator/helpers.py b/osbenchmark/synthetic_data_generator/helpers.py
index 9a153bd9..70f5c4a7 100644
--- a/osbenchmark/synthetic_data_generator/helpers.py
+++ b/osbenchmark/synthetic_data_generator/helpers.py
@@ -82,7 +82,7 @@ def remove_existing_files(existing_files_found: list):
for file in existing_files_found:
os.remove(file)
except OSError as e:
- raise exceptions.ExecutorError("OSB could not remove existing files for SDG: ", e)
+ raise exceptions.ExecutorError("ASB could not remove existing files for SDG: ", e)
def host_has_available_disk_storage(sdg_metadata: SyntheticDataGeneratorMetadata) -> bool:
logger = logging.getLogger(__name__)
diff --git a/osbenchmark/synthetic_data_generator/strategies/mapping_strategy.py b/osbenchmark/synthetic_data_generator/strategies/mapping_strategy.py
index f98d70a1..f7d72cc3 100644
--- a/osbenchmark/synthetic_data_generator/strategies/mapping_strategy.py
+++ b/osbenchmark/synthetic_data_generator/strategies/mapping_strategy.py
@@ -271,7 +271,7 @@ class MappingConverter:
**params: Optional parameters:
dimension: Vector dimensions. Can be retrieved from field_ef (default: 128)
sample_vectors: List of base vectors to add noise to. Helps with realistic clustering.
- Without sample_vectors, OSB generates uniform random vectors between -1.0 and 1.0
+ Without sample_vectors, ASB generates uniform random vectors between -1.0 and 1.0
noise_factor: Standard deviation (gaussian) or range (uniform) of noise (default: 0.1)
Lower values (0.01-0.05) create tight clusters.
Higher values (0.2-0.5) create diverse distributions.
diff --git a/osbenchmark/telemetry.py b/osbenchmark/telemetry.py
index e4437b92..1174c06c 100644
--- a/osbenchmark/telemetry.py
+++ b/osbenchmark/telemetry.py
@@ -1,5 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
#
+# Modifications by Apache Solr contributors; see git log for details.
+# Licensed under the Apache License, Version 2.0.
+#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
@@ -22,29 +25,52 @@
# specific language governing permissions and limitations
# under the License.
-import collections
+import json
import logging
-import fnmatch
import os
+import re
import threading
-from collections import deque
-import opensearchpy
+from abc import abstractmethod
+
import tabulate
from osbenchmark import metrics, time, exceptions
-from osbenchmark.metrics import MetaInfoScope
-from osbenchmark.utils import io, sysstats, console, opts, process
-from osbenchmark.utils.versions import components
+from osbenchmark.utils import io, sysstats, console, process
def list_telemetry():
console.println("Available telemetry devices:\n")
- devices = [[device.command, device.human_name, device.help] for device in [JitCompiler, Gc, FlightRecorder,
- Heapdump, NodeStats, RecoveryStats,
- CcrStats, SegmentStats, TransformStats,
- SearchableSnapshotsStats,
- SegmentReplicationStats, ShardStats]]
- console.println(tabulate.tabulate(devices, ["Command", "Name", "Description"]))
- console.println("\nKeep in mind that each telemetry device may incur a runtime overhead which can skew results.")
+
+ # --- Solr-native devices (always enabled) ---
+ console.println("Always-enabled Solr devices (no --telemetry flag needed):\n")
+ solr_devices = [
+ [d.command, d.human_name, d.help] for d in [
+ SolrJvmStats,
+ SolrNodeStats,
+ SolrCollectionStats,
+ SolrQueryStats,
+ SolrIndexingStats,
+ SolrCacheStats,
+ ]
+ ]
+ console.println(tabulate.tabulate(solr_devices, ["Command", "Name", "Description"]))
+ console.println("\nAll always-on devices poll /solr/admin/metrics (JSON on Solr 9.x, Prometheus text on Solr 10.x).")
+
+ # --- Optional REST devices (all pipelines) ---
+ console.println("\n\nOptional REST devices (all pipelines — enable with --telemetry <command>):\n")
+ rest_devices = [[device.command, device.human_name, device.help] for device in [
+ SegmentStats, ShardStats, ClusterEnvironmentInfo,
+ ]]
+ console.println(tabulate.tabulate(rest_devices, ["Command", "Name", "Description"]))
+
+ # --- Optional JVM/process devices (provisioned pipelines only) ---
+ console.println("\n\nOptional JVM/process devices (docker or from-distribution pipelines only):\n")
+ jvm_devices = [[device.command, device.human_name, device.help] for device in [
+ FlightRecorder, Gc, JitCompiler, Heapdump,
+ ]]
+ console.println(tabulate.tabulate(jvm_devices, ["Command", "Name", "Description"]))
+ console.println("\nJVM/process devices inject flags into SOLR_OPTS before Solr starts.")
+ console.println("They are silently skipped when pipeline is benchmark-only.")
+ console.println("\nNote: disk-io (disk I/O byte counters) is always active on provisioned pipelines.")
class Telemetry:
@@ -168,7 +194,7 @@ class FlightRecorder(TelemetryDevice):
internal = False
command = "jfr"
human_name = "Flight Recorder"
- help = "Enables Java Flight Recorder (requires an Oracle JDK or OpenJDK 11+)"
+ help = "Enables Java Flight Recorder (requires OpenJDK 11+); injected into SOLR_OPTS."
def __init__(self, telemetry_params, log_root, java_major_version):
super().__init__()
@@ -177,51 +203,26 @@ class FlightRecorder(TelemetryDevice):
self.java_major_version = java_major_version
def instrument_java_opts(self):
+ if self.telemetry_params.get("pipeline", "") == "benchmark-only":
+ self.logger.warning("jfr: Solr was not provisioned by Solr Benchmark; skipping JFR flags.")
+ return []
+
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "profile.jfr")
-
- # JFR was integrated into OpenJDK 11 and is not a commercial feature anymore.
- if self.java_major_version < 11:
- console.println("\n***************************************************************************\n")
- console.println("[WARNING] Java flight recorder is a commercial feature of the Oracle JDK.\n")
- console.println("You are using Java flight recorder which requires that you comply with\nthe licensing terms stated in:\n")
- console.println(console.format.link("http://www.oracle.com/technetwork/java/javase/terms/license/index.html"))
- console.println("\nBy using this feature you confirm that you comply with these license terms.\n")
- console.println("Otherwise, please abort and rerun OSB without the \"jfr\" telemetry device.")
- console.println("\n***************************************************************************\n")
-
- time.sleep(3)
-
console.info("%s: Writing flight recording to [%s]" % (self.human_name, log_file), logger=self.logger)
-
java_opts = self.java_opts(log_file)
-
self.logger.info("jfr: Adding JVM arguments: [%s].", java_opts)
return java_opts
def java_opts(self, log_file):
recording_template = self.telemetry_params.get("recording-template")
java_opts = ["-XX:+UnlockDiagnosticVMOptions", "-XX:+DebugNonSafepoints"]
- jfr_cmd = ""
- if self.java_major_version < 11:
- java_opts.append("-XX:+UnlockCommercialFeatures")
-
- if self.java_major_version < 9:
- java_opts.append("-XX:+FlightRecorder")
- java_opts.append("-XX:FlightRecorderOptions=disk=true,maxage=0s,maxsize=0,dumponexit=true,dumponexitpath={}".format(log_file))
- jfr_cmd = "-XX:StartFlightRecording=defaultrecording=true"
- if recording_template:
- self.logger.info("jfr: Using recording template [%s].", recording_template)
- jfr_cmd += ",settings={}".format(recording_template)
- else:
- self.logger.info("jfr: Using default recording template.")
+ jfr_cmd = "-XX:StartFlightRecording=maxsize=0,maxage=0s,disk=true,dumponexit=true,filename={}".format(log_file)
+ if recording_template:
+ self.logger.info("jfr: Using recording template [%s].", recording_template)
+ jfr_cmd += ",settings={}".format(recording_template)
else:
- jfr_cmd += "-XX:StartFlightRecording=maxsize=0,maxage=0s,disk=true,dumponexit=true,filename={}".format(log_file)
- if recording_template:
- self.logger.info("jfr: Using recording template [%s].", recording_template)
- jfr_cmd += ",settings={}".format(recording_template)
- else:
- self.logger.info("jfr: Using default recording template.")
+ self.logger.info("jfr: Using default recording template.")
java_opts.append(jfr_cmd)
return java_opts
@@ -230,13 +231,18 @@ class JitCompiler(TelemetryDevice):
internal = False
command = "jit"
human_name = "JIT Compiler Profiler"
- help = "Enables JIT compiler logs."
+ help = "Enables JIT compiler logs; injected into SOLR_OPTS."
- def __init__(self, log_root):
+ def __init__(self, log_root, telemetry_params=None):
super().__init__()
self.log_root = log_root
+ self.telemetry_params = telemetry_params or {}
def instrument_java_opts(self):
+ if self.telemetry_params.get("pipeline", "") == "benchmark-only":
+ self.logger.warning("jit: Solr was not provisioned by Solr Benchmark; skipping JIT flags.")
+ return []
+
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "jit.log")
console.info("%s: Writing JIT compiler log to [%s]" % (self.human_name, log_file), logger=self.logger)
@@ -248,7 +254,7 @@ class Gc(TelemetryDevice):
internal = False
command = "gc"
human_name = "GC log"
- help = "Enables GC logs."
+ help = "Enables GC logs (Java 9+ -Xlog: format); injected into SOLR_OPTS."
def __init__(self, telemetry_params, log_root, java_major_version):
super().__init__()
@@ -257,38 +263,43 @@ class Gc(TelemetryDevice):
self.java_major_version = java_major_version
def instrument_java_opts(self):
+ if self.telemetry_params.get("pipeline", "") == "benchmark-only":
+ self.logger.warning("gc: Solr was not provisioned by Solr Benchmark; skipping GC flags.")
+ return []
+
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "gc.log")
console.info("%s: Writing GC log to [%s]" % (self.human_name, log_file), logger=self.logger)
- return self.java_opts(log_file)
-
- def java_opts(self, log_file):
- if self.java_major_version < 9:
- return ["-Xloggc:{}".format(log_file), "-XX:+PrintGCDetails", "-XX:+PrintGCDateStamps", "-XX:+PrintGCTimeStamps",
- "-XX:+PrintGCApplicationStoppedTime", "-XX:+PrintGCApplicationConcurrentTime",
- "-XX:+PrintTenuringDistribution"]
- else:
- log_config = self.telemetry_params.get("gc-log-config", "gc*=info,safepoint=info,age*=trace")
- # see https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5
- return [f"-Xlog:{log_config}:file={log_file}:utctime,uptimemillis,level,tags:filecount=0"]
+ log_config = self.telemetry_params.get("gc-log-config", "gc*=info,safepoint=info,age*=trace")
+ # see https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5
+ return [f"-Xlog:{log_config}:file={log_file}:utctime,uptimemillis,level,tags:filecount=0"]
class Heapdump(TelemetryDevice):
internal = False
command = "heapdump"
human_name = "Heap Dump"
- help = "Captures a heap dump."
+ help = "Captures a heap dump from the Solr JVM on benchmark stop."
- def __init__(self, log_root):
+ def __init__(self, log_root, docker_container=None):
super().__init__()
self.log_root = log_root
+ self.docker_container = docker_container
def detach_from_node(self, node, running):
if running:
heap_dump_file = os.path.join(self.log_root, "heap_at_exit_{}.hprof".format(node.pid))
console.info("{}: Writing heap dump to [{}]".format(self.human_name, heap_dump_file), logger=self.logger)
- cmd = "jmap -dump:format=b,file={} {}".format(heap_dump_file, node.pid)
- if process.run_subprocess_with_logging(cmd):
+ # noinspection PyBroadException
+ try:
+ if self.docker_container:
+ cmd = "docker exec {} jmap -dump:format=b,file={} {}".format(
+ self.docker_container, heap_dump_file, node.pid)
+ else:
+ cmd = "jmap -dump:format=b,file={} {}".format(heap_dump_file, node.pid)
+ if process.run_subprocess_with_logging(cmd):
+ self.logger.warning("Could not write heap dump to [%s]", heap_dump_file)
+ except BaseException:
self.logger.warning("Could not write heap dump to [%s]", heap_dump_file)
@@ -296,985 +307,135 @@ class SegmentStats(TelemetryDevice):
internal = False
command = "segment-stats"
human_name = "Segment Stats"
- help = "Determines segment stats at the end of the benchmark."
+ help = "Captures per-collection segment stats (numDocs, deletedDocs, segmentCount, sizeInBytes) via the Solr Luke API."
- def __init__(self, log_root, client):
+ def __init__(self, log_root, admin_client):
super().__init__()
self.log_root = log_root
- self.client = client
+ self.admin_client = admin_client
def on_benchmark_stop(self):
# noinspection PyBroadException
try:
- segment_stats = self.client.cat.segments(index="_all", v=True)
+ collections = self.admin_client.list_collections()
stats_file = os.path.join(self.log_root, "segment_stats.log")
console.info(f"{self.human_name}: Writing segment stats to [{stats_file}]", logger=self.logger)
+ io.ensure_dir(self.log_root)
with open(stats_file, "wt") as f:
- f.write(segment_stats)
+ for coll in collections:
+ try:
+ idx = self.admin_client.get_luke_stats(coll)
+ row = {
+ "collection": coll,
+ "numDocs": idx.get("numDocs"),
+ "maxDoc": idx.get("maxDoc"),
+ "deletedDocs": idx.get("deletedDocs"),
+ "segmentCount": idx.get("segmentCount"),
+ "sizeInBytes": idx.get("sizeInBytes"),
+ }
+ f.write(json.dumps(row) + "\n")
+ except BaseException:
+ self.logger.warning("Could not retrieve Luke stats for collection [%s].", coll)
except BaseException:
self.logger.exception("Could not retrieve segment stats.")
-class CcrStats(TelemetryDevice):
- internal = False
- command = "ccr-stats"
- human_name = "CCR Stats"
- help = ("Regularly samples Cross Cluster Replication (CCR) leader and follower(s) checkpoint at index level"
- "and calculates replication lag")
-
- """
- Gathers CCR stats on a cluster level
- """
- def __init__(self, telemetry_params, clients, metrics_store):
- """
- :param telemetry_params: The configuration object for telemetry_params.
- May optionally specify:
- ``ccr-stats-indices``: JSON string specifying the indices per cluster to publish statistics from.
- Not all clusters need to be specified, but any name used must be be present in target.hosts.
- Example:
- {"ccr-stats-indices": {"cluster_a": ["follower"],"default": ["leader"]}
- ``ccr-stats-sample-interval``: positive integer controlling the sampling interval. Default: 1 second.
- :param clients: A dict of clients to all clusters.
- :param metrics_store: The configured metrics store we write to.
- """
- super().__init__()
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.sample_interval = telemetry_params.get("ccr-stats-sample-interval", 1)
- if self.sample_interval <= 0:
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'ccr-stats-sample-interval' must be greater than zero but was {}.".format(self.sample_interval))
- self.specified_cluster_names = self.clients.keys()
- self.indices_per_cluster = self.telemetry_params.get("ccr-stats-indices", False)
- self.max_replication_lag_seconds = self.telemetry_params.get("ccr-max-replication-lag-seconds", 60*60*60)
- if self.indices_per_cluster:
- for cluster_name in self.indices_per_cluster.keys():
- if cluster_name not in clients:
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'ccr-stats-indices' must be a JSON Object with keys matching "
- "the cluster names [{}] specified in --target-hosts "
- "but it had [{}].".format(",".join(sorted(clients.keys())), cluster_name))
- self.specified_cluster_names = self.indices_per_cluster.keys()
-
- self.metrics_store = metrics_store
- self.samplers = []
-
- def on_benchmark_start(self):
- recorder = []
- for cluster_name in self.specified_cluster_names:
- recorder = CcrStatsRecorder(cluster_name, self.clients[cluster_name], self.metrics_store, self.sample_interval,
- self.max_replication_lag_seconds,
- self.indices_per_cluster[cluster_name] if self.indices_per_cluster else None)
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
-
- def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
-
-
-class CcrStatsRecorder:
- """
- Collects and pushes CCR stats for the specified cluster to the metric store.
- """
-
- def __init__(self, cluster_name, client, metrics_store, sample_interval, max_replication_lag_seconds, indices=None):
- """
- :param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
- :param client: The OpenSearch client for this cluster.
- :param metrics_store: The configured metrics store we write to.
- :param sample_interval: integer controlling the interval, in seconds, between collecting samples.
- :param indices: optional list of indices to filter results from.
- """
-
- self.cluster_name = cluster_name
- self.client = client
- self.metrics_store = metrics_store
- self.sample_interval= sample_interval
- self.indices = indices
- self.logger = logging.getLogger(__name__)
- self.leader_checkpoints = dict()
- for index in self.indices:
- self.leader_checkpoints[index] = deque(maxlen = int(max_replication_lag_seconds/sample_interval))
-
- def __str__(self):
- return "ccr stats"
-
- def record(self):
- """
- Collect CCR stats for indexes (optionally) specified in telemetry parameters and push to metrics store.
- """
- if self.cluster_name == "default":
- self.log_leader_stats()
- else:
- self.log_ccr_lag_per_index()
- self.log_follower_stats()
-
- def log_leader_stats(self):
- try:
- stats = self.client.transport.perform_request("GET", "/_plugins/_replication/leader_stats")
- self.record_cluster_level_stats(stats)
- except opensearchpy.TransportError:
- msg = "A transport error occurred while collecting CCR leader stats"
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- def log_follower_stats(self):
- try:
- stats = self.client.transport.perform_request("GET", "/_plugins/_replication/follower_stats")
- self.record_cluster_level_stats(stats)
- except opensearchpy.TransportError:
- msg = "A transport error occurred while collecting follower stats for remote cluster: {}".format(self.cluster_name)
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
-
- def log_ccr_lag_per_index(self):
- for index in self.indices:
- try:
- stats = self.client.transport.perform_request("GET", "/_plugins/_replication/" + index + "/_status")
- if stats["status"] == "SYNCING":
- self.record_stats_per_index(index, stats)
- else:
- self.logger.info("CCR Status is not syncing. Ignoring for now!")
- except opensearchpy.TransportError:
- msg = "A transport error occurred while collecting CCR stats for remote cluster: {}".format(self.cluster_name)
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- def record_stats_per_index(self, name, stats):
- """
- :param name: The index name.
- :param stats: A dict with returned CCR stats for the index.
- """
- doc = {
- "name": "ccr-status",
- "index": name,
- "leader_checkpoint": stats["syncing_details"]["leader_checkpoint"],
- "follower_checkpoint": stats["syncing_details"]["follower_checkpoint"],
- "replication_lag": self.calculate_lag(name, stats["syncing_details"]["leader_checkpoint"],
- stats["syncing_details"]["follower_checkpoint"])
- }
- index_metadata = {
- "cluster": self.cluster_name,
- "index": name
- }
- self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=index_metadata)
-
- def record_cluster_level_stats(self, data):
- metadata = {
- "cluster": self.cluster_name,
- }
- self.metrics_store.put_doc(data, level=MetaInfoScope.cluster, meta_data=metadata)
-
- def calculate_lag(self, index, leader_checkpoint, follower_checkpoint):
- leader_checkpoint_queue = self.leader_checkpoints[index]
-
- while(leader_checkpoint_queue and leader_checkpoint_queue[0] <= follower_checkpoint):
- leader_checkpoint_queue.popleft()
-
- if leader_checkpoint > follower_checkpoint:
- leader_checkpoint_queue.append(leader_checkpoint)
- return len(leader_checkpoint_queue) * self.sample_interval
-
-
-
-
-class RecoveryStats(TelemetryDevice):
- internal = False
- command = "recovery-stats"
- human_name = "Recovery Stats"
- help = "Regularly samples shard recovery stats"
-
- """
- Gathers recovery stats on a cluster level
- """
-
- def __init__(self, telemetry_params, clients, metrics_store):
- """
- :param telemetry_params: The configuration object for telemetry_params.
- May optionally specify:
- ``recovery-stats-indices``: JSON structure specifying the index pattern per cluster to publish stats from.
- Not all clusters need to be specified, but any name used must be be present in target.hosts. Alternatively,
- the index pattern can be specified as a string can be specified in case only one cluster is involved.
- Example:
- {"recovery-stats-indices": {"cluster_a": ["follower"],"default": ["leader"]}
-
- ``recovery-stats-sample-interval``: positive integer controlling the sampling interval. Default: 1 second.
- :param clients: A dict of clients to all clusters.
- :param metrics_store: The configured metrics store we write to.
- """
- super().__init__()
-
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.sample_interval = telemetry_params.get("recovery-stats-sample-interval", 1)
- if self.sample_interval <= 0:
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'recovery-stats-sample-interval' must be greater than zero but was {}."
- .format(self.sample_interval))
- self.specified_cluster_names = self.clients.keys()
- indices_per_cluster = self.telemetry_params.get("recovery-stats-indices", False)
- # allow the user to specify either an index pattern as string or as a JSON object
- if isinstance(indices_per_cluster, str):
- self.indices_per_cluster = {opts.TargetHosts.DEFAULT: indices_per_cluster}
- else:
- self.indices_per_cluster = indices_per_cluster
-
- if self.indices_per_cluster:
- for cluster_name in self.indices_per_cluster.keys():
- if cluster_name not in clients:
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'recovery-stats-indices' must be a JSON Object with keys matching "
- "the cluster names [{}] specified in --target-hosts "
- "but it had [{}].".format(",".join(sorted(clients.keys())), cluster_name))
- self.specified_cluster_names = self.indices_per_cluster.keys()
-
- self.metrics_store = metrics_store
- self.samplers = []
-
- def on_benchmark_start(self):
- for cluster_name in self.specified_cluster_names:
- recorder = RecoveryStatsRecorder(cluster_name, self.clients[cluster_name], self.metrics_store,
- self.sample_interval,
- self.indices_per_cluster[cluster_name] if self.indices_per_cluster else "")
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
-
- def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
-
-
-class RecoveryStatsRecorder:
- """
- Collects and pushes recovery stats for the specified cluster to the metric store.
- """
-
- def __init__(self, cluster_name, client, metrics_store, sample_interval, indices=None):
- """
- :param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
- :param client: The OpenSearch client for this cluster.
- :param metrics_store: The configured metrics store we write to.
- :param sample_interval: integer controlling the interval, in seconds, between collecting samples.
- :param indices: optional list of indices to filter results from.
- """
-
- self.cluster_name = cluster_name
- self.client = client
- self.metrics_store = metrics_store
- self.sample_interval = sample_interval
- self.indices = indices
- self.logger = logging.getLogger(__name__)
-
- def __str__(self):
- return "recovery stats"
-
- def record(self):
- """
- Collect recovery stats for indexes (optionally) specified in telemetry parameters and push to metrics store.
- """
- try:
- stats = self.client.indices.recovery(index=self.indices, active_only=True, detailed=False)
- except opensearchpy.TransportError:
- msg = "A transport error occurred while collecting recovery stats on cluster [{}]".format(self.cluster_name)
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- for idx, idx_stats in stats.items():
- for shard in idx_stats["shards"]:
- doc = {
- "name": "recovery-stats",
- "shard": shard
- }
- shard_metadata = {
- "cluster": self.cluster_name,
- "index": idx,
- "shard": shard["id"]
- }
- self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=shard_metadata)
-
-
class ShardStats(TelemetryDevice):
"""
- Collects and pushes shard stats for the specified cluster to the metric store.
+ Collects per-shard document count and index size for SolrCloud clusters.
+ Skipped silently on standalone Solr (no cluster.collections in CLUSTERSTATUS).
"""
internal = False
command = "shard-stats"
human_name = "Shard Stats"
- help = "Regularly samples nodes stats at shard level"
- warning = """You have enabled the shard-stats telemetry device with OpenSearch < 1.1.0. Requests to the
- _nodes/stats OpenSearch endpoint trigger additional refreshes and WILL SKEW results.
- """
- opensearch_distribution_name = "opensearch"
+ help = "Regularly samples per-shard document count and index size (SolrCloud only)."
- def __init__(self, telemetry_params, clients, metrics_store):
+ def __init__(self, telemetry_params, admin_client, metrics_store):
"""
- :param telemetry_params: The configuration object for telemetry_params.
- May optionally specify:
- ``shard-stats-sample-interval``: positive integer controlling the sampling interval. Default: 60 seconds.
- :param clients: A dict of clients to all clusters.
+ :param telemetry_params: May optionally specify
+ ``shard-stats-sample-interval``: positive integer, seconds between polls. Default: 60.
+ :param admin_client: A SolrClient instance used for admin API calls.
:param metrics_store: The configured metrics store we write to.
"""
super().__init__()
-
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.specified_cluster_names = self.clients.keys()
+ self.admin_client = admin_client
+ self.metrics_store = metrics_store
self.sample_interval = telemetry_params.get("shard-stats-sample-interval", 60)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'shard-stats-sample-interval' must be greater than zero but was {self.sample_interval}."
)
-
- self.metrics_store = metrics_store
self.samplers = []
def on_benchmark_start(self):
- default_client = self.clients["default"]
- # ElasticSearch does not supply a value for the distribution field
- distribution_name = default_client.info()["version"].get("distribution", "")
- distribution_version = default_client.info()["version"]["number"]
- major, minor = components(distribution_version)[:2]
-
- if distribution_name != NodeStats.opensearch_distribution_name and (major < 7 or (major == 7 and minor < 2)):
- console.warn(NodeStats.warning, logger=self.logger)
-
- for cluster_name in self.specified_cluster_names:
- recorder = ShardStatsRecorder(cluster_name, self.clients[cluster_name], self.metrics_store, self.sample_interval)
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
-
- def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
-
-
-class ShardStatsRecorder:
- """
- Collects and pushes shard stats for the specified cluster to the metric store.
- """
-
- def __init__(self, cluster_name, client, metrics_store, sample_interval):
- """
- :param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
- :param client: The Elasticsearch client for this cluster.
- :param metrics_store: The configured metrics store we write to.
- :param sample_interval: integer controlling the interval, in seconds, between collecting samples.
- """
-
- self.cluster_name = cluster_name
- self.client = client
- self.metrics_store = metrics_store
- self.sample_interval = sample_interval
- self.logger = logging.getLogger(__name__)
-
- def __str__(self):
- return "shard stats"
-
- def record(self):
- """
- Collect node-stats?level=shards and push to metrics store.
- """
-
-
- current_sample = self.sample()
-
- shard_metadata = {"cluster": self.cluster_name}
-
- for node_stats in current_sample:
- node_name = node_stats["name"]
- collected_node_stats = collections.OrderedDict()
- collected_node_stats["name"] = "shard-stats"
- shard_stats = node_stats["indices"].get("shards")
-
- for index_name, stats in shard_stats.items():
- for curr_shard in stats:
- for shard_id, curr_stats in curr_shard.items():
- doc = {
- "name": "shard-stats",
- "shard-id": shard_id,
- "index": index_name,
- "primary": curr_stats.get("routing", {}).get("primary"),
- "docs": curr_stats.get("docs", {}).get("count", -1),
- "store": curr_stats.get("store", {}).get("size_in_bytes", -1),
- "segments-count": curr_stats.get("segments", {}).get("count", -1),
- "node": node_name,
- "index-total-size": curr_stats.get("indexing", {}).get("index_total", -1),
- "polling-ingest-processed": curr_stats.get("polling_ingest_stats", {}).get("message_processor_stats", {}).get("total_processed_count", -1),
- }
- self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=shard_metadata)
- def sample(self):
- try:
- stats = self.client.nodes.stats(metric="_all", level="shards")
- except opensearchpy.TransportError:
- logging.getLogger(__name__).exception("Could not retrieve node stats at shard level.")
- return {}
- return stats["nodes"].values()
-
-class NodeStats(TelemetryDevice):
- """
- Gathers different node stats.
- """
-
- internal = False
- command = "node-stats"
- human_name = "Node Stats"
- help = "Regularly samples node stats"
- warning = """You have enabled the node-stats telemetry device with OpenSearch < 1.1.0. Requests to the
- _nodes/stats OpenSearch endpoint trigger additional refreshes and WILL SKEW results.
- """
- opensearch_distribution_name = "opensearch"
-
- def __init__(self, telemetry_params, clients, metrics_store):
- super().__init__()
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.specified_cluster_names = self.clients.keys()
- self.metrics_store = metrics_store
- self.samplers = []
-
- def on_benchmark_start(self):
- default_client = self.clients["default"]
- # ElasticSearch does not supply a value for the distribution field
- distribution_name = default_client.info()["version"].get("distribution", "")
- distribution_version = default_client.info()["version"]["number"]
- major, minor = components(distribution_version)[:2]
-
- if distribution_name != NodeStats.opensearch_distribution_name and (major < 7 or (major == 7 and minor < 2)):
- console.warn(NodeStats.warning, logger=self.logger)
-
- for cluster_name in self.specified_cluster_names:
- recorder = NodeStatsRecorder(self.telemetry_params, cluster_name, self.clients[cluster_name], self.metrics_store)
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
-
- def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
-
-
-class NodeStatsRecorder:
- def __init__(self, telemetry_params, cluster_name, client, metrics_store):
- self.sample_interval = telemetry_params.get("node-stats-sample-interval", 1)
- if self.sample_interval <= 0:
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'node-stats-sample-interval' must be greater than zero but was {}.".format(self.sample_interval))
-
- self.include_indices = telemetry_params.get("node-stats-include-indices", False)
- self.include_indices_metrics = telemetry_params.get("node-stats-include-indices-metrics", False)
-
- if self.include_indices_metrics:
- if isinstance(self.include_indices_metrics, str):
- self.include_indices_metrics_list = opts.csv_to_list(self.include_indices_metrics)
- else:
- # we don't validate the allowable metrics as they may change across ES or OpenSearch versions
- raise exceptions.SystemSetupError(
- "The telemetry parameter 'node-stats-include-indices-metrics' must be a comma-separated string but was {}".format(
- type(self.include_indices_metrics))
- )
- else:
- self.include_indices_metrics_list = ["docs", "store", "indexing", "search", "merges", "query_cache",
- "fielddata", "segments", "translog", "request_cache"]
-
- self.include_thread_pools = telemetry_params.get("node-stats-include-thread-pools", True)
- self.include_buffer_pools = telemetry_params.get("node-stats-include-buffer-pools", True)
- self.include_breakers = telemetry_params.get("node-stats-include-breakers", True)
- self.include_network = telemetry_params.get("node-stats-include-network", True)
- self.include_process = telemetry_params.get("node-stats-include-process", True)
- self.include_mem_stats = telemetry_params.get("node-stats-include-mem", True)
- self.include_gc_stats = telemetry_params.get("node-stats-include-gc", True)
- self.include_indexing_pressure = telemetry_params.get("node-stats-include-indexing-pressure", True)
- self.client = client
- self.metrics_store = metrics_store
- self.cluster_name = cluster_name
-
- def __str__(self):
- return "node stats"
-
- def record(self):
- current_sample = self.sample()
- for node_stats in current_sample:
- node_name = node_stats["name"]
- metrics_store_meta_data = {
- "cluster": self.cluster_name,
- "node_name": node_name
- }
- collected_node_stats = collections.OrderedDict()
- collected_node_stats["name"] = "node-stats"
-
- if self.include_indices or self.include_indices_metrics:
- collected_node_stats.update(
- self.indices_stats(node_name, node_stats, include=self.include_indices_metrics_list))
- if self.include_thread_pools:
- collected_node_stats.update(self.thread_pool_stats(node_name, node_stats))
- if self.include_breakers:
- collected_node_stats.update(self.circuit_breaker_stats(node_name, node_stats))
- if self.include_buffer_pools:
- collected_node_stats.update(self.jvm_buffer_pool_stats(node_name, node_stats))
- if self.include_mem_stats:
- collected_node_stats.update(self.jvm_mem_stats(node_name, node_stats))
- collected_node_stats.update(self.os_mem_stats(node_name, node_stats))
- if self.include_gc_stats:
- collected_node_stats.update(self.jvm_gc_stats(node_name, node_stats))
- if self.include_network:
- collected_node_stats.update(self.network_stats(node_name, node_stats))
- if self.include_process:
- collected_node_stats.update(self.process_stats(node_name, node_stats))
- if self.include_indexing_pressure:
- collected_node_stats.update(self.indexing_pressure(node_name, node_stats))
-
- self.metrics_store.put_doc(dict(collected_node_stats),
- level=MetaInfoScope.node,
- node_name=node_name,
- meta_data=metrics_store_meta_data)
-
- def flatten_stats_fields(self, prefix=None, stats=None):
- """
- Flatten provided dict using an optional prefix and top level key filters.
-
- :param prefix: The prefix for all flattened values. Defaults to None.
- :param stats: Dict with values to be flattened, using _ as a separator. Defaults to {}.
- :return: Return flattened dictionary, separated by _ and prefixed with prefix.
- """
-
- def iterate():
- for section_name, section_value in stats.items():
- if isinstance(section_value, dict):
- new_prefix = "{}_{}".format(prefix, section_name)
- # https://www.python.org/dev/peps/pep-0380/
- yield from self.flatten_stats_fields(prefix=new_prefix, stats=section_value).items()
- # Avoid duplication for metric fields that have unit embedded in value as they are also recorded elsewhere
- # example: `breakers_parent_limit_size_in_bytes` vs `breakers_parent_limit_size`
- elif isinstance(section_value, (int, float)) and not isinstance(section_value, bool):
- yield "{}{}".format(prefix + "_" if prefix else "", section_name), section_value
-
- if stats:
- return dict(iterate())
- else:
- return dict()
-
- def indices_stats(self, node_name, node_stats, include):
- idx_stats = node_stats["indices"]
- ordered_results = collections.OrderedDict()
- for section in include:
- if section in idx_stats:
- ordered_results.update(self.flatten_stats_fields(prefix="indices_" + section, stats=idx_stats[section]))
-
- return ordered_results
-
- def thread_pool_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="thread_pool", stats=node_stats["thread_pool"])
-
- def circuit_breaker_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="breakers", stats=node_stats["breakers"])
-
- def jvm_buffer_pool_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="jvm_buffer_pools", stats=node_stats["jvm"]["buffer_pools"])
-
- def jvm_mem_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="jvm_mem", stats=node_stats["jvm"]["mem"])
-
- def os_mem_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="os_mem", stats=node_stats["os"]["mem"])
-
- def jvm_gc_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="jvm_gc", stats=node_stats["jvm"]["gc"])
-
- def network_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="transport", stats=node_stats.get("transport"))
-
- def process_stats(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="process_cpu", stats=node_stats["process"]["cpu"])
-
- def indexing_pressure(self, node_name, node_stats):
- return self.flatten_stats_fields(prefix="indexing_pressure", stats=node_stats["indexing_pressure"])
-
- def sample(self):
- try:
- stats = self.client.nodes.stats(metric="_all")
- except opensearchpy.TransportError:
- logging.getLogger(__name__).exception("Could not retrieve node stats.")
- return {}
- return stats["nodes"].values()
-
-
-class TransformStats(TelemetryDevice):
- internal = False
- command = "transform-stats"
- human_name = "Transform Stats"
- help = "Regularly samples transform stats"
-
- """
- Gathers Transform stats
- """
-
- def __init__(self, telemetry_params, clients, metrics_store):
- """
- :param telemetry_params: The configuration object for telemetry_params.
- :param clients: A dict of clients to all clusters.
- :param metrics_store: The configured metrics store we write to.
- """
- super().__init__()
-
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.sample_interval = telemetry_params.get("transform-stats-sample-interval", 1)
- if self.sample_interval <= 0:
- raise exceptions.SystemSetupError(
- f"The telemetry parameter 'transform-stats-sample-interval' must be greater than zero "
- f"but was [{self.sample_interval}].")
- self.specified_cluster_names = self.clients.keys()
- self.transforms_per_cluster = self.telemetry_params.get("transform-stats-transforms", False)
- if self.transforms_per_cluster:
- for cluster_name in self.transforms_per_cluster.keys():
- if cluster_name not in clients:
- raise exceptions.SystemSetupError(
- f"The telemetry parameter 'transform-stats-transforms' must be a JSON Object with keys "
- f"matching the cluster names [{','.join(sorted(clients.keys()))}] specified in --target-hosts "
- f"but it had [{cluster_name}].")
- self.specified_cluster_names = self.transforms_per_cluster.keys()
-
- self.metrics_store = metrics_store
- self.samplers = []
-
- def on_benchmark_start(self):
- for cluster_name in self.specified_cluster_names:
- recorder = TransformStatsRecorder(cluster_name, self.clients[cluster_name], self.metrics_store,
- self.sample_interval,
- self.transforms_per_cluster[
- cluster_name] if self.transforms_per_cluster else None)
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
-
- def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
- # record the final stats
- sampler.recorder.record_final()
-
-
-class TransformStatsRecorder:
- """
- Collects and pushes Transform stats for the specified cluster to the metric store.
- """
-
- def __init__(self, cluster_name, client, metrics_store, sample_interval, transforms=None):
- """
- :param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
- :param client: The OpenSearch client for this cluster.
- :param metrics_store: The configured metrics store we write to.
- :param sample_interval: integer controlling the interval, in seconds, between collecting samples.
- :param transforms: optional list of transforms to filter results from.
- """
-
- self.cluster_name = cluster_name
- self.client = client
- self.metrics_store = metrics_store
- self.sample_interval = sample_interval
- self.transforms = transforms
- self.logger = logging.getLogger(__name__)
-
- self.logger.info("transform stats recorder")
-
- def __str__(self):
- return "transform stats"
-
- def record(self):
- """
- Collect Transform stats for transforms (optionally) specified in telemetry parameters and push to metrics store.
- """
-
- self._record()
-
- def record_final(self):
- """
- Collect final Transform stats for transforms (optionally) specified in telemetry parameters and push to metrics store.
- """
-
- self._record("total_")
-
- def _record(self, prefix=""):
- # ES returns all stats values in bytes or ms via "human: false"
+ # noinspection PyBroadException
try:
- stats = self.client.transform.get_transform_stats("_all")
-
- except opensearchpy.TransportError:
- msg = f"A transport error occurred while collecting transform stats on " \
- f"cluster [{self.cluster_name}]"
- self.logger.exception(msg)
- raise exceptions.BenchmarkError(msg)
-
- for transform in stats["transforms"]:
- try:
- if self.transforms and transform["id"] not in self.transforms:
- # Skip metrics for transform not part of user supplied whitelist (transform-stats-transforms)
- # in telemetry params.
- continue
- self.record_stats_per_transform(transform["id"], transform["stats"], prefix)
-
- except KeyError:
- self.logger.warning(
- "The 'transform' key does not contain a 'transform' or 'stats' key "
- "Maybe the output format has changed. Skipping."
- )
-
- def record_stats_per_transform(self, transform_id, stats, prefix=""):
- """
- :param transform_id: The transform id.
- :param stats: A dict with returned transform stats for the transform.
- :param prefix: A prefix for the counters/values, e.g. for total runtimes
- """
-
- meta_data = {
- "transform_id": transform_id
- }
-
- self.metrics_store.put_value_cluster_level(prefix + "transform_pages_processed",
- stats.get("pages_processed", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_documents_processed",
- stats.get("documents_processed", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_documents_indexed",
- stats.get("documents_indexed", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_index_total", stats.get("index_total", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_index_failures", stats.get("index_failures", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_search_total", stats.get("search_total", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_search_failures",
- stats.get("search_failures", 0),
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_processing_total",
- stats.get("processing_total", 0),
- meta_data=meta_data)
-
- self.metrics_store.put_value_cluster_level(prefix + "transform_search_time",
- stats.get("search_time_in_ms", 0),
- "ms", meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_index_time",
- stats.get("index_time_in_ms", 0), "ms",
- meta_data=meta_data)
- self.metrics_store.put_value_cluster_level(prefix + "transform_processing_time",
- stats.get("processing_time_in_ms", 0), "ms",
- meta_data=meta_data)
-
- documents_processed = stats.get("documents_processed", 0)
- processing_time = stats.get("search_time_in_ms", 0)
- processing_time += stats.get("processing_time_in_ms", 0)
- processing_time += stats.get("index_time_in_ms", 0)
-
- if processing_time > 0:
- throughput = documents_processed / processing_time * 1000
- self.metrics_store.put_value_cluster_level(prefix + "transform_throughput", throughput,
- "docs/s", meta_data=meta_data)
-
-
-class SearchableSnapshotsStats(TelemetryDevice):
- internal = False
- command = "searchable-snapshots-stats"
- human_name = "Searchable Snapshots Stats"
- help = "Regularly samples searchable snapshots stats"
-
- """
- Gathers searchable snapshots stats on a cluster level
- """
- def __init__(self, telemetry_params, clients, metrics_store):
- """
- :param telemetry_params: The configuration object for telemetry_params.
- May optionally specify:
- ``searchable-stats-indices``: str with index/index-pattern or list of indices or index-patterns
- that stats should be collected from.
- Specifying this will implicitly use the level=indices parameter in the API call, as opposed to
- the level=cluster (default).
-
- Not all clusters need to be specified, but any name used must be be present in target.hosts.
- Alternatively, the index or index pattern can be specified as a string in case only one cluster is involved.
-
- Examples:
-
- --telemetry-params="searchable-snapshots-stats-indices:opensearchlogs-2020-01-01"
-
- --telemetry-params="searchable-snapshots-stats-indices:opensearchlogs*"
-
- --telemetry-params=./telemetry-params.json
-
- where telemetry-params.json is:
-
- {
- "searchable-snapshots-stats-indices": {
- "default": ["leader-opensearchlogs-*"],
- "follower": ["follower-opensearchlogs-*"]
- }
- }
-
-
- ``searchable-snapshots-stats-sample-interval``: positive integer controlling the sampling interval.
- Default: 1 second.
- :param clients: A dict of clients to all clusters.
- :param metrics_store: The configured metrics store we write to.
- """
- super().__init__()
-
- self.telemetry_params = telemetry_params
- self.clients = clients
- self.sample_interval = telemetry_params.get("searchable-snapshots-stats-sample-interval", 1)
- if self.sample_interval <= 0:
- raise exceptions.SystemSetupError(
- f"The telemetry parameter 'searchable-snapshots-stats-sample-interval' must be greater than zero "
- f"but was {self.sample_interval}.")
- self.specified_cluster_names = self.clients.keys()
- indices_per_cluster = self.telemetry_params.get("searchable-snapshots-stats-indices", None)
- # allow the user to specify either an index pattern as string or as a JSON object
- if isinstance(indices_per_cluster, str):
- self.indices_per_cluster = {opts.TargetHosts.DEFAULT: [indices_per_cluster]}
- else:
- self.indices_per_cluster = indices_per_cluster
+ data = self.admin_client.get_clusterstatus()
+ except BaseException:
+ self.logger.exception("ShardStats: could not retrieve CLUSTERSTATUS; device will not run.")
+ return
- if self.indices_per_cluster:
- for cluster_name in self.indices_per_cluster.keys():
- if cluster_name not in clients:
- raise exceptions.SystemSetupError(
- f"The telemetry parameter 'searchable-snapshots-stats-indices' must be a JSON Object "
- f"with keys matching the cluster names [{','.join(sorted(clients.keys()))}] specified in "
- f"--target-hosts but it had [{cluster_name}].")
- self.specified_cluster_names = self.indices_per_cluster.keys()
+ if "cluster" not in data or "collections" not in data.get("cluster", {}):
+ self.logger.info("ShardStats: no cluster.collections in CLUSTERSTATUS — skipping (standalone Solr).")
+ return
- self.metrics_store = metrics_store
- self.samplers = []
-
- def on_benchmark_start(self):
- for cluster_name in self.specified_cluster_names:
- recorder = SearchableSnapshotsStatsRecorder(
- cluster_name, self.clients[cluster_name], self.metrics_store, self.sample_interval,
- self.indices_per_cluster[cluster_name] if self.indices_per_cluster else None)
- sampler = SamplerThread(recorder)
- self.samplers.append(sampler)
- sampler.daemon = True
- # we don't require starting recorders precisely at the same time
- sampler.start()
+ recorder = ShardStatsRecorder(self.admin_client, self.metrics_store, self.sample_interval)
+ sampler = SamplerThread(recorder)
+ self.samplers.append(sampler)
+ sampler.daemon = True
+ sampler.start()
def on_benchmark_stop(self):
- if self.samplers:
- for sampler in self.samplers:
- sampler.finish()
+ for sampler in self.samplers:
+ sampler.finish()
-class SearchableSnapshotsStatsRecorder:
+class ShardStatsRecorder:
"""
- Collects and pushes searchable snapshots stats for the specified cluster to the metric store.
+ Polls CLUSTERSTATUS and Core STATUS for each shard leader; pushes metrics per shard.
"""
- def __init__(self, cluster_name, client, metrics_store, sample_interval, indices=None):
- """
- :param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
- :param client: The OpenSearch client for this cluster.
- :param metrics_store: The configured metrics store we write to.
- :param sample_interval: integer controlling the interval, in seconds, between collecting samples.
- :param indices: optional list of indices to filter results from.
- """
-
- self.cluster_name = cluster_name
- self.client = client
+ def __init__(self, admin_client, metrics_store, sample_interval):
+ self.admin_client = admin_client
self.metrics_store = metrics_store
self.sample_interval = sample_interval
- self.indices = indices
self.logger = logging.getLogger(__name__)
def __str__(self):
- return "searchable snapshots stats"
+ return "shard stats"
def record(self):
- """
- Collect searchable snapshots stats for indexes (optionally) specified in telemetry parameters
- and push to metrics store.
- """
+ # noinspection PyBroadException
try:
- stats_api_endpoint = "/_searchable_snapshots/stats"
- level = "indices" if self.indices else "cluster"
- # we don't use the existing client support (searchable_snapshots.stats())
- # as the API is deliberately undocumented and might change:
- stats = self.client.transport.perform_request("GET", stats_api_endpoint, params={"level": level})
- except opensearchpy.NotFoundError as e:
- if "No searchable snapshots indices found" in e.info.get("error").get("reason"):
- self.logger.info(
- "Unable to find valid indices while collecting searchable snapshots stats "
- "on cluster [%s]", self.cluster_name)
- # allow collection, indices might be mounted later on
- return
- except opensearchpy.TransportError:
- raise exceptions.BenchmarkError(
- f"A transport error occurred while collecting searchable snapshots stats on cluster "
- f"[{self.cluster_name}]") from None
-
- total_stats = stats.get("total", [])
- for lucene_file_stats in total_stats:
- self._push_stats(level="cluster", stats=lucene_file_stats)
-
- if self.indices:
- for idx, idx_stats in stats.get("indices", {}).items():
- if not self._match_list_or_pattern(idx):
- continue
-
- for lucene_file_stats in idx_stats.get("total", []):
- self._push_stats(level="index", stats=lucene_file_stats, index=idx)
-
- def _push_stats(self, level, stats, index=None):
- doc = {
- "name": "searchable-snapshots-stats",
- # be lenient as the API is still WiP
- "lucene_file_type": stats.get("file_ext"),
- "stats": stats,
- }
-
- if index:
- doc["index"] = index
-
- meta_data = {
- "cluster": self.cluster_name,
- "level": level
- }
-
- self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=meta_data)
-
- # TODO Consider moving under the utils package for broader/future use?
- # at the moment it's only useful here as this stats API is undocumented and we don't wan't to use
- # a specific opensearch-py stats method that could support index filtering in a standard way
- def _match_list_or_pattern(self, idx):
- """
- Match idx from self.indices
+ data = self.admin_client.get_clusterstatus()
+ collections = data.get("cluster", {}).get("collections", {})
+ except BaseException:
+ self.logger.exception("ShardStats: could not retrieve CLUSTERSTATUS.")
+ return
- :param idx: String that may include shell style wildcards (https://docs.python.org/3/library/fnmatch.html)
- :return: Boolean if idx matches anything from self.indices
- """
- for index_param in self.indices:
- if fnmatch.fnmatch(idx, index_param):
- return True
- return False
+ for _coll_name, coll_data in collections.items():
+ shards = coll_data.get("shards", {})
+ for shard_name, shard_data in shards.items():
+ replicas = shard_data.get("replicas", {})
+ for _replica_key, replica in replicas.items():
+ if replica.get("state") == "active" and replica.get("leader") == "true":
+ core_name = replica.get("core")
+ if not core_name:
+ continue
+ # noinspection PyBroadException
+ try:
+ core_status = self.admin_client.get_core_status(core_name)
+ idx = core_status.get("index", {})
+ num_docs = idx.get("numDocs", 0)
+ size_bytes = idx.get("sizeInBytes", 0)
+ self.metrics_store.put_value_cluster_level(
+ f"shard_{shard_name}_num_docs", num_docs, "")
+ self.metrics_store.put_value_cluster_level(
+ f"shard_{shard_name}_size_bytes", size_bytes, "byte")
+ except BaseException:
+ self.logger.warning("ShardStats: could not get core STATUS for [%s].", core_name)
+ break # only need the leader replica per shard
class StartupTime(InternalTelemetryDevice):
def __init__(self, stopwatch=time.StopWatch):
@@ -1334,7 +495,7 @@ class DiskIo(InternalTelemetryDevice):
else:
disk_end = sysstats.disk_io_counters()
if self.node_count_on_host > 1:
- self.logger.info("There are [%d] nodes on this host and OSB fell back to disk I/O counters. "
+ self.logger.info("There are [%d] nodes on this host and ASB fell back to disk I/O counters. "
"Attributing [1/%d] of total I/O to [%s].",
self.node_count_on_host, self.node_count_on_host, node.node_name)
@@ -1402,42 +563,53 @@ def extract_value(node, path, fallback="unknown"):
return value
-class ClusterEnvironmentInfo(InternalTelemetryDevice):
+class ClusterEnvironmentInfo(TelemetryDevice):
"""
- Gathers static environment information on a cluster level (e.g. version numbers).
+ Gathers static environment information on a cluster level (Solr version, JVM, CPU).
+ Called once at benchmark start; stores results as run metadata.
"""
- def __init__(self, client, metrics_store):
+ internal = False
+ command = "cluster-environment-info"
+ human_name = "Cluster Environment Info"
+ help = "Stores Solr version, JVM version, and CPU core count as benchmark metadata."
+
+ def __init__(self, admin_client, metrics_store):
super().__init__()
+ self.admin_client = admin_client
self.metrics_store = metrics_store
- self.client = client
def on_benchmark_start(self):
# noinspection PyBroadException
try:
- client_info = self.client.info()
+ resp = self.admin_client.raw_request("GET", "/api/node/system")
+ resp.raise_for_status()
+ data = resp.json()
except BaseException:
- self.logger.exception("Could not retrieve cluster version info")
+ self.logger.exception("ClusterEnvironmentInfo: could not retrieve /api/node/system")
return
- revision = client_info["version"]["build_hash"]
- distribution_version = client_info["version"]["number"]
- # older versions (pre 6.3.0) don't expose a build_flavor property because the only (implicit) flavor was "oss".
- distribution_flavor = client_info["version"].get("build_flavor", "oss")
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "source_revision", revision)
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "distribution_version", distribution_version)
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "distribution_flavor", distribution_flavor)
- info = self.client.nodes.info(node_id="_all")
- nodes_info = info["nodes"].values()
- for node in nodes_info:
- node_name = node["name"]
- # while we could determine this for bare-metal nodes that are
- # provisioned by OSB, there are other cases (Docker, externally
- # provisioned clusters) where it's not that easy.
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, "jvm_vendor", extract_value(node, ["jvm", "vm_vendor"]))
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, "jvm_version", extract_value(node, ["jvm", "version"]))
+ lucene = data.get("lucene", {})
+ jvm = data.get("jvm", {})
+ system = data.get("system", {})
+ distribution_version = lucene.get("solr-spec-version", "unknown")
+ jvm_version = jvm.get("version", "unknown")
+ jvm_vendor = jvm.get("name", "unknown")
+ cpu_logical_cores = system.get("availableProcessors", -1)
+
+ self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "distribution_version", distribution_version)
+ self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "jvm_version", jvm_version)
+ self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "jvm_vendor", jvm_vendor)
+ self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "cpu_logical_cores", cpu_logical_cores)
- store_plugin_metadata(self.metrics_store, nodes_info)
- store_node_attribute_metadata(self.metrics_store, nodes_info)
+ # noinspection PyBroadException
+ try:
+ cs_resp = self.admin_client.raw_request("GET", "/solr/admin/collections?action=CLUSTERSTATUS&wt=json")
+ cs_resp.raise_for_status()
+ cluster = cs_resp.json().get("cluster", {})
+ live_nodes = cluster.get("liveNodes", [])
+ self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "cluster_node_count", len(live_nodes))
+ except BaseException:
+ self.logger.warning("ClusterEnvironmentInfo: could not retrieve CLUSTERSTATUS node count.")
def add_metadata_for_node(metrics_store, node_name, host_name):
@@ -1453,495 +625,591 @@ def add_metadata_for_node(metrics_store, node_name, host_name):
metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, "host_name", host_name)
-class ExternalEnvironmentInfo(InternalTelemetryDevice):
+
+class IndexSize(InternalTelemetryDevice):
"""
- Gathers static environment information for externally provisioned clusters.
+ Measures the final size of the index
"""
- def __init__(self, client, metrics_store):
+ def __init__(self, data_paths):
super().__init__()
- self.metrics_store = metrics_store
- self.client = client
+ self.data_paths = data_paths
+ self.attached = False
+ self.index_size_bytes = None
- # noinspection PyBroadException
- def on_benchmark_start(self):
- try:
- nodes_stats = self.client.nodes.stats(metric="_all")["nodes"].values()
- except BaseException:
- self.logger.exception("Could not retrieve nodes stats")
- nodes_stats = []
- try:
- nodes_info = self.client.nodes.info(node_id="_all")["nodes"].values()
- except BaseException:
- self.logger.exception("Could not retrieve nodes info")
- nodes_info = []
+ def attach_to_node(self, node):
+ self.attached = True
- for node in nodes_stats:
- node_name = node["name"]
- host = node.get("host", "unknown")
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, "node_name", node_name)
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, "host_name", host)
+ def detach_from_node(self, node, running):
+ # we need to gather the file size after the node has terminated so we can be sure that it has written all its buffers.
+ if not running and self.attached and self.data_paths:
+ self.attached = False
+ index_size_bytes = 0
+ for data_path in self.data_paths:
+ index_size_bytes += io.get_size(data_path)
+ self.index_size_bytes = index_size_bytes
- for node in nodes_info:
- node_name = node["name"]
- self.store_node_info(node_name, "os_name", node, ["os", "name"])
- self.store_node_info(node_name, "os_version", node, ["os", "version"])
- self.store_node_info(node_name, "cpu_logical_cores", node, ["os", "available_processors"])
- self.store_node_info(node_name, "jvm_vendor", node, ["jvm", "vm_vendor"])
- self.store_node_info(node_name, "jvm_version", node, ["jvm", "version"])
+ def store_system_metrics(self, node, metrics_store):
+ if self.index_size_bytes:
+ metrics_store.put_value_node_level(node.node_name, "final_index_size_bytes", self.index_size_bytes, "byte")
- store_plugin_metadata(self.metrics_store, nodes_info)
- store_node_attribute_metadata(self.metrics_store, nodes_info)
- def store_node_info(self, node_name, metric_key, node, path):
- self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, node_name, metric_key, extract_value(node, path))
+# ===========================================================================
+# Solr telemetry devices
+# ===========================================================================
+# ---------------------------------------------------------------------------
+# Prometheus text format parser (shared with runner.py)
+# ---------------------------------------------------------------------------
-class JvmStatsSummary(InternalTelemetryDevice):
+def _parse_prometheus_text(text: str) -> dict:
"""
- Gathers a summary of various JVM statistics during the whole test run.
+ Parse Prometheus exposition text format into a flat dict of {metric_name: float}.
+
+ Lines starting with '#' are comments/help/type headers and are skipped.
+ Handles optional labels: metric_name{label="value"} value [timestamp]
+
+ When multiple series share the same base metric name (different labels),
+ values are accumulated (summed).
"""
- def __init__(self, client, metrics_store):
+ parsed_metrics = {}
+ for line in text.splitlines():
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ parts = line.split()
+ if len(parts) < 2:
+ continue
+ name_part = parts[0]
+ try:
+ value = float(parts[1])
+ except ValueError:
+ continue
+ base_name = re.sub(r"\{[^}]*\}", "", name_part)
+ parsed_metrics[base_name] = parsed_metrics.get(base_name, 0.0) + value
+ return parsed_metrics
+
+
+# ---------------------------------------------------------------------------
+# Base class
+# ---------------------------------------------------------------------------
+
+class SolrTelemetryDevice(TelemetryDevice):
+ """
+ Abstract base for Solr telemetry polling devices.
+
+ Extends TelemetryDevice so that Solr devices integrate seamlessly with
+ the existing Telemetry wrapper. Setting ``internal = True`` means the
+ device is always enabled (not filtered by the ``--telemetry`` flag).
+
+ Subclasses implement `_collect()` which is called periodically on a
+ background thread between `on_benchmark_start()` and `on_benchmark_stop()`.
+ """
+
+ internal = True
+ command = None
+ human_name = "Solr Telemetry"
+ help = "Solr-specific background polling telemetry device."
+
+ def __init__(self, admin_client, metrics_store, sample_interval_s: float = 5.0):
super().__init__()
- self.metrics_store = metrics_store
- self.client = client
- self.jvm_stats_per_node = {}
+ self._client = admin_client
+ self._metrics_store = metrics_store
+ self._sample_interval = sample_interval_s
+ self._thread = None
+ self._stop_event = threading.Event()
+
+ def on_benchmark_start(self) -> None:
+ """Start background polling thread."""
+ self._stop_event.clear()
+ self._thread = threading.Thread(target=self._poll_loop, daemon=True)
+ self._thread.start()
+
+ def on_benchmark_stop(self) -> None:
+ """Stop background polling thread and flush any remaining metrics."""
+ self._stop_event.set()
+ if self._thread is not None:
+ self._thread.join(timeout=self._sample_interval * 2 + 5)
+
+ def _poll_loop(self) -> None:
+ while not self._stop_event.is_set():
+ try:
+ self._collect()
+ except Exception as exc:
+ logging.getLogger(__name__).warning("%s: collection error: %s", self.__class__.__name__, exc)
+ self._stop_event.wait(self._sample_interval)
- def on_benchmark_start(self):
- self.logger.info("JvmStatsSummary on benchmark start")
- self.jvm_stats_per_node = self.jvm_stats()
+ @abstractmethod
+ def _collect(self) -> None:
+ """Collect metrics and store them via self._metrics_store."""
- def on_benchmark_stop(self):
- jvm_stats_at_end = self.jvm_stats()
- total_old_gen_collection_time = 0
- total_old_gen_collection_count = 0
- total_young_gen_collection_time = 0
- total_young_gen_collection_count = 0
-
- for node_name, jvm_stats_end in jvm_stats_at_end.items():
- if node_name in self.jvm_stats_per_node:
- jvm_stats_start = self.jvm_stats_per_node[node_name]
- young_gc_time = max(jvm_stats_end["young_gc_time"] - jvm_stats_start["young_gc_time"], 0)
- young_gc_count = max(jvm_stats_end["young_gc_count"] - jvm_stats_start["young_gc_count"], 0)
- old_gc_time = max(jvm_stats_end["old_gc_time"] - jvm_stats_start["old_gc_time"], 0)
- old_gc_count = max(jvm_stats_end["old_gc_count"] - jvm_stats_start["old_gc_count"], 0)
-
- total_young_gen_collection_time += young_gc_time
- total_young_gen_collection_count += young_gc_count
- total_old_gen_collection_time += old_gc_time
- total_old_gen_collection_count += old_gc_count
-
- self.metrics_store.put_value_node_level(node_name, "node_young_gen_gc_time", young_gc_time, "ms")
- self.metrics_store.put_value_node_level(node_name, "node_young_gen_gc_count", young_gc_count)
- self.metrics_store.put_value_node_level(node_name, "node_old_gen_gc_time", old_gc_time, "ms")
- self.metrics_store.put_value_node_level(node_name, "node_old_gen_gc_count", old_gc_count)
-
- all_pool_stats = {
- "name": "jvm_memory_pool_stats"
- }
- for pool_name, pool_stats in jvm_stats_end["pools"].items():
- all_pool_stats[pool_name] = {
- "peak_usage": pool_stats["peak"],
- "unit": "byte"
- }
- self.metrics_store.put_doc(all_pool_stats, level=MetaInfoScope.node, node_name=node_name)
+ # ------------------------------------------------------------------
+ # Dual-format helpers
+ # ------------------------------------------------------------------
- else:
- self.logger.warning("Cannot determine JVM stats for [%s] (not in the cluster at the start of the benchmark).", node_name)
+ def _fetch_node_metrics_parsed(self):
+ """
+ Fetch /admin/metrics and return ``(format_str, data_dict)``.
- self.metrics_store.put_value_cluster_level("node_total_young_gen_gc_time", total_young_gen_collection_time, "ms")
- self.metrics_store.put_value_cluster_level("node_total_young_gen_gc_count", total_young_gen_collection_count)
- self.metrics_store.put_value_cluster_level("node_total_old_gen_gc_time", total_old_gen_collection_time, "ms")
- self.metrics_store.put_value_cluster_level("node_total_old_gen_gc_count", total_old_gen_collection_count)
+ ``format_str`` is ``"json"`` or ``"prometheus"``.
+ """
+ raw = self._client.get_node_metrics()
+ if isinstance(raw, str):
+ return "prometheus", _parse_prometheus_text(raw)
+ return "json", raw if isinstance(raw, dict) else {}
+
+ @staticmethod
+ def _get_metric_json(data: dict, *keys, default=None):
+ """Navigate a nested dict using successive key lookups."""
+ current = data
+ for key in keys:
+ if not isinstance(current, dict):
+ return default
+ current = current.get(key)
+ if current is None:
+ return default
+ return current
+
+ @staticmethod
+ def _get_metric_prometheus(data: dict, metric_name: str, default=None):
+ """Look up a metric by exact base name from a parsed Prometheus dict."""
+ return data.get(metric_name, default)
+
+ def _put(self, name: str, value, unit: str, task: str = "", meta: dict = None) -> None:
+ """Write a single metric to the metrics store."""
+ if not hasattr(self._metrics_store, "put_value_cluster_level"):
+ self._metrics_store[name] = {"value": value, "unit": unit}
+ return
+ self._metrics_store.put_value_cluster_level(
+ name=name, value=value, unit=unit,
+ task=task, operation_type="telemetry",
+ meta_data=meta or {},
+ )
- self.jvm_stats_per_node = None
- def jvm_stats(self):
- self.logger.debug("Gathering JVM stats")
- jvm_stats = {}
- try:
- stats = self.client.nodes.stats(metric="_all")
- except opensearchpy.TransportError:
- self.logger.exception("Could not retrieve GC times.")
- return jvm_stats
- nodes = stats["nodes"]
- for node in nodes.values():
- node_name = node["name"]
- gc = node["jvm"]["gc"]["collectors"]
- old_gen_collection_time = gc["old"]["collection_time_in_millis"]
- old_gen_collection_count = gc["old"]["collection_count"]
- young_gen_collection_time = gc["young"]["collection_time_in_millis"]
- young_gen_collection_count = gc["young"]["collection_count"]
- jvm_stats[node_name] = {
- "young_gc_time": young_gen_collection_time,
- "young_gc_count": young_gen_collection_count,
- "old_gc_time": old_gen_collection_time,
- "old_gc_count": old_gen_collection_count,
- "pools": {}
- }
- pool_usage = node["jvm"]["mem"]["pools"]
- for pool_name, pool_stats in pool_usage.items():
- jvm_stats[node_name]["pools"][pool_name] = {
- "peak": pool_stats["peak_used_in_bytes"]
- }
- return jvm_stats
-
-
-class IndexStats(InternalTelemetryDevice):
+# ---------------------------------------------------------------------------
+# Device: SolrJvmStats
+# ---------------------------------------------------------------------------
+
+class SolrJvmStats(SolrTelemetryDevice):
"""
- Gathers statistics via the OpenSearch index stats API
+ Collect JVM heap, GC, thread, and buffer pool metrics from Solr.
+
+ Metrics: jvm_heap_used_bytes, jvm_heap_max_bytes, jvm_gc_count, jvm_gc_time_ms,
+ jvm_gc_young_count, jvm_gc_young_time_ms, jvm_gc_old_count, jvm_gc_old_time_ms,
+ jvm_thread_count, jvm_thread_peak_count, jvm_buffer_pool_direct_bytes,
+ jvm_buffer_pool_mapped_bytes
"""
- def __init__(self, client, metrics_store):
- super().__init__()
- self.client = client
- self.metrics_store = metrics_store
- self.first_time = True
- def on_benchmark_start(self):
- # we only determine this value at the start of the benchmark. This is actually only useful for
- # the pipeline "benchmark-only" where we don't have control over the cluster and the user might not have restarted
- # the cluster so we can at least tell them.
- if self.first_time:
- for t in self.index_times(self.index_stats(), per_shard_stats=False):
- n = t["name"]
- v = t["value"]
- if t["value"] > 0:
- console.warn("%s is %d ms indicating that the cluster is not in a defined clean state. Recorded index time "
- "metrics may be misleading." % (n, v), logger=self.logger)
- self.first_time = False
+ human_name = "Solr JVM Stats"
+ help = "JVM heap, GC (total/young/old), threads, and buffer pool metrics"
- def on_benchmark_stop(self):
- self.logger.info("Gathering indices stats for all primaries on benchmark stop.")
- index_stats = self.index_stats()
- # import json
- # self.logger.debug("Returned indices stats:\n%s", json.dumps(index_stats, indent=2))
- if "_all" not in index_stats or "primaries" not in index_stats["_all"]:
- return
- p = index_stats["_all"]["primaries"]
- # actually this is add_count
- self.add_metrics(self.extract_value(p, ["segments", "count"]), "segments_count")
- self.add_metrics(self.extract_value(p, ["segments", "memory_in_bytes"]), "segments_memory_in_bytes", "byte")
-
- for t in self.index_times(index_stats):
- self.metrics_store.put_doc(doc=t, level=metrics.MetaInfoScope.cluster)
-
- for ct in self.index_counts(index_stats):
- self.metrics_store.put_doc(doc=ct, level=metrics.MetaInfoScope.cluster)
-
- self.add_metrics(self.extract_value(p, ["segments", "doc_values_memory_in_bytes"]), "segments_doc_values_memory_in_bytes", "byte")
- self.add_metrics(self.extract_value(p, ["segments", "stored_fields_memory_in_bytes"]), "segments_stored_fields_memory_in_bytes",
- "byte")
- self.add_metrics(self.extract_value(p, ["segments", "terms_memory_in_bytes"]), "segments_terms_memory_in_bytes", "byte")
- self.add_metrics(self.extract_value(p, ["segments", "norms_memory_in_bytes"]), "segments_norms_memory_in_bytes", "byte")
- self.add_metrics(self.extract_value(p, ["segments", "points_memory_in_bytes"]), "segments_points_memory_in_bytes", "byte")
- self.add_metrics(self.extract_value(index_stats, ["_all", "total", "store", "size_in_bytes"]), "store_size_in_bytes", "byte")
- self.add_metrics(self.extract_value(index_stats, ["_all", "total", "translog", "size_in_bytes"]), "translog_size_in_bytes", "byte")
-
- def index_stats(self):
- # noinspection PyBroadException
+ def _collect(self) -> None:
+ fmt, data = self._fetch_node_metrics_parsed()
+ if fmt == "prometheus":
+ self._collect_prometheus(data)
+ else:
+ self._collect_json(data)
+
+ def _collect_json(self, data: dict) -> None:
+ jvm = self._get_metric_json(data, "metrics", "solr.jvm") or {}
+
+ heap_used = jvm.get("memory.heap.used")
+ heap_max = jvm.get("memory.heap.max")
+ if heap_used is not None:
+ self._put("jvm_heap_used_bytes", heap_used, "bytes")
+ if heap_max is not None:
+ self._put("jvm_heap_max_bytes", heap_max, "bytes")
+
+ thread_count = jvm.get("threads.count")
+ thread_peak = jvm.get("threads.peak.count")
+ if thread_count is not None:
+ self._put("jvm_thread_count", thread_count, "")
+ if thread_peak is not None:
+ self._put("jvm_thread_peak_count", thread_peak, "")
+
+ direct_bytes = jvm.get("buffers.direct.MemoryUsed")
+ mapped_bytes = jvm.get("buffers.mapped.MemoryUsed")
+ if direct_bytes is not None:
+ self._put("jvm_buffer_pool_direct_bytes", direct_bytes, "bytes")
+ if mapped_bytes is not None:
+ self._put("jvm_buffer_pool_mapped_bytes", mapped_bytes, "bytes")
+
+ gc_count_total = None
+ gc_time_total = None
+ gc_young_count = None
+ gc_young_time = None
+ gc_old_count = None
+ gc_old_time = None
+
+ for k, v in jvm.items():
+ if v is None:
+ continue
+ if k.endswith(".count") and "gc." in k:
+ gc_count_total = (gc_count_total or 0) + v
+ k_lower = k.lower()
+ if "young" in k_lower or "minor" in k_lower or "eden" in k_lower:
+ gc_young_count = (gc_young_count or 0) + v
+ elif "old" in k_lower or "major" in k_lower or "tenured" in k_lower:
+ gc_old_count = (gc_old_count or 0) + v
+ if k.endswith(".time") and "gc." in k:
+ gc_time_total = (gc_time_total or 0) + v
+ k_lower = k.lower()
+ if "young" in k_lower or "minor" in k_lower or "eden" in k_lower:
+ gc_young_time = (gc_young_time or 0) + v
+ elif "old" in k_lower or "major" in k_lower or "tenured" in k_lower:
+ gc_old_time = (gc_old_time or 0) + v
+
+ if gc_count_total is not None:
+ self._put("jvm_gc_count", gc_count_total, "")
+ if gc_time_total is not None:
+ self._put("jvm_gc_time_ms", gc_time_total, "ms")
+ if gc_young_count is not None:
+ self._put("jvm_gc_young_count", gc_young_count, "")
+ if gc_young_time is not None:
+ self._put("jvm_gc_young_time_ms", gc_young_time, "ms")
+ if gc_old_count is not None:
+ self._put("jvm_gc_old_count", gc_old_count, "")
+ if gc_old_time is not None:
+ self._put("jvm_gc_old_time_ms", gc_old_time, "ms")
+
+ def _collect_prometheus(self, data: dict) -> None:
+ mapping = {
+ "jvm_memory_heap_used_bytes": ("jvm_heap_used_bytes", "bytes"),
+ "jvm_memory_heap_max_bytes": ("jvm_heap_max_bytes", "bytes"),
+ "jvm_gc_collection_count": ("jvm_gc_count", ""),
+ "jvm_gc_collection_time_ms": ("jvm_gc_time_ms", "ms"),
+ "jvm_threads_current": ("jvm_thread_count", ""),
+ "jvm_threads_peak": ("jvm_thread_peak_count", ""),
+ "jvm_buffer_pool_used_bytes": ("jvm_buffer_pool_direct_bytes", "bytes"),
+ }
+ for prom_name, (osb_name, unit) in mapping.items():
+ val = self._get_metric_prometheus(data, prom_name)
+ if val is not None:
+ self._put(osb_name, val, unit)
+
+
+# ---------------------------------------------------------------------------
+# Device: SolrNodeStats
+# ---------------------------------------------------------------------------
+
+class SolrNodeStats(SolrTelemetryDevice):
+ """
+ Collect OS, file-descriptor, HTTP, and query-handler metrics from Solr.
+
+ Metrics: cpu_usage_percent, os_memory_free_bytes, node_file_descriptors_open,
+ node_file_descriptors_max, node_http_requests_total,
+ query_handler_requests_total, query_handler_errors_total,
+ query_handler_avg_latency_ms
+ """
+
+ human_name = "Solr Node Stats"
+ help = "CPU usage, OS memory, file descriptors, HTTP requests, and query handler latency"
+
+ def _collect(self) -> None:
+ self._collect_system_stats()
+ self._collect_metrics_stats()
+
+ def _collect_system_stats(self) -> None:
try:
- return self.client.indices.stats(metric="_all", level="shards")
- except BaseException:
- self.logger.exception("Could not retrieve index stats.")
- return {}
-
- def index_times(self, stats, per_shard_stats=True):
- times = []
- self.index_time(times, stats, "merges_total_time", ["merges", "total_time_in_millis"], per_shard_stats)
- self.index_time(times, stats, "merges_total_throttled_time", ["merges", "total_throttled_time_in_millis"], per_shard_stats)
- self.index_time(times, stats, "indexing_total_time", ["indexing", "index_time_in_millis"], per_shard_stats)
- self.index_time(times, stats, "indexing_throttle_time", ["indexing", "throttle_time_in_millis"], per_shard_stats)
- self.index_time(times, stats, "refresh_total_time", ["refresh", "total_time_in_millis"], per_shard_stats)
- self.index_time(times, stats, "flush_total_time", ["flush", "total_time_in_millis"], per_shard_stats)
- return times
-
- def index_time(self, values, stats, name, path, per_shard_stats):
- primary_total_stats = self.extract_value(stats, ["_all", "primaries"], default_value={})
- value = self.extract_value(primary_total_stats, path)
- if value is not None:
- doc = {
- "name": name,
- "value": value,
- "unit": "ms",
- }
- if per_shard_stats:
- doc["per-shard"] = self.primary_shard_stats(stats, path)
- values.append(doc)
-
- def index_counts(self, stats):
- counts = []
- self.index_count(counts, stats, "merges_total_count", ["merges", "total"])
- self.index_count(counts, stats, "refresh_total_count", ["refresh", "total"])
- self.index_count(counts, stats, "flush_total_count", ["flush", "total"])
- return counts
-
- def index_count(self, values, stats, name, path):
- primary_total_stats = self.extract_value(stats, ["_all", "primaries"], default_value={})
- value = self.extract_value(primary_total_stats, path)
- if value is not None:
- doc = {
- "name": name,
- "value": value
- }
- values.append(doc)
-
- def primary_shard_stats(self, stats, path):
- shard_stats = []
+ resp = self._client._get("/api/node/system")
+ system = resp.json()
+ os_data = system.get("system", {})
+
+ cpu = os_data.get("processCpuLoad") or os_data.get("systemCpuLoad")
+ if cpu is not None:
+ self._put("cpu_usage_percent", cpu * 100.0, "%")
+
+ free_mem = os_data.get("freePhysicalMemorySize")
+ if free_mem is not None:
+ self._put("os_memory_free_bytes", free_mem, "bytes")
+
+ open_fds = os_data.get("openFileDescriptorCount")
+ max_fds = os_data.get("maxFileDescriptorCount")
+ if open_fds is not None:
+ self._put("node_file_descriptors_open", open_fds, "")
+ if max_fds is not None:
+ self._put("node_file_descriptors_max", max_fds, "")
+ except Exception as exc:
+ logging.getLogger(__name__).debug("SolrNodeStats: /api/node/system error: %s", exc)
+
+ def _collect_metrics_stats(self) -> None:
try:
- for shards in stats["indices"].values():
- for shard in shards["shards"].values():
- for shard_metrics in shard:
- if shard_metrics["routing"]["primary"]:
- shard_stats.append(self.extract_value(shard_metrics, path, default_value=0))
- except KeyError:
- self.logger.warning("Could not determine primary shard stats at path [%s].", ",".join(path))
- return shard_stats
-
- def add_metrics(self, value, metric_key, unit=None):
- if value is not None:
- if unit:
- self.metrics_store.put_value_cluster_level(metric_key, value, unit)
+ fmt, data = self._fetch_node_metrics_parsed()
+ if fmt == "prometheus":
+ self._collect_metrics_prometheus(data)
else:
- self.metrics_store.put_value_cluster_level(metric_key, value)
+ self._collect_metrics_json(data)
+ except Exception as exc:
+ logging.getLogger(__name__).debug("SolrNodeStats: metrics error: %s", exc)
+
+ def _collect_metrics_json(self, data: dict) -> None:
+ core = self._get_metric_json(data, "metrics", "solr.core") or {}
+
+ requests = core.get("QUERY./select.requests")
+ errors = core.get("QUERY./select.errors")
+ avg_latency = core.get("QUERY./select.requestTimes.mean")
+
+ if requests is not None:
+ self._put("query_handler_requests_total", requests, "")
+ if errors is not None:
+ self._put("query_handler_errors_total", errors, "")
+ if avg_latency is not None:
+ self._put("query_handler_avg_latency_ms", avg_latency, "ms")
+
+ jetty = self._get_metric_json(data, "metrics", "solr.jetty") or {}
+ http_requests = jetty.get(
+ "org.eclipse.jetty.server.handler.StatisticsHandler.requests"
+ )
+ if http_requests is not None:
+ self._put("node_http_requests_total", http_requests, "")
+
+ def _collect_metrics_prometheus(self, data: dict) -> None:
+ mapping = {
+ "solr_metrics_core_query_requests_total": ("query_handler_requests_total", ""),
+ "solr_metrics_core_query_errors_total": ("query_handler_errors_total", ""),
+ "solr_metrics_core_query_request_times_mean_ms": ("query_handler_avg_latency_ms", "ms"),
+ "solr_metrics_jetty_requests_total": ("node_http_requests_total", ""),
+ }
+ for prom_name, (osb_name, unit) in mapping.items():
+ val = self._get_metric_prometheus(data, prom_name)
+ if val is not None:
+ self._put(osb_name, val, unit)
- def extract_value(self, primaries, path, default_value=None):
- value = primaries
- try:
- for k in path:
- value = value[k]
- return value
- except KeyError:
- self.logger.warning("Could not determine value at path [%s]. Returning default value [%s]", ",".join(path), str(default_value))
- return default_value
+# ---------------------------------------------------------------------------
+# Device: SolrCollectionStats
+# ---------------------------------------------------------------------------
-class MlBucketProcessingTime(InternalTelemetryDevice):
- def __init__(self, client, metrics_store):
- super().__init__()
- self.client = client
- self.metrics_store = metrics_store
+class SolrCollectionStats(SolrTelemetryDevice):
+ """
+ Collect per-collection document count, index size, segment count, and deleted docs.
- def on_benchmark_stop(self):
+ Metrics (per collection): num_docs, index_size_bytes, segment_count, num_deleted_docs
+ """
+
+ human_name = "Solr Collection Stats"
+ help = "Per-collection: doc count, deleted docs, index size, and segment count (30 s interval)"
+
+ def __init__(self, admin_client, metrics_store,
+ collections: list = None, sample_interval_s: float = 30.0):
+ super().__init__(admin_client, metrics_store, sample_interval_s)
+ self._collections = collections
+
+ def _collect(self) -> None:
try:
- results = self.client.search(index=".ml-anomalies-*", body={
- "size": 0,
- "query": {
- "bool": {
- "must": [
- {"term": {"result_type": "bucket"}}
- ]
- }
- },
- "aggs": {
- "jobs": {
- "terms": {
- "field": "job_id"
- },
- "aggs": {
- "min_pt": {
- "min": {"field": "processing_time_ms"}
- },
- "max_pt": {
- "max": {"field": "processing_time_ms"}
- },
- "mean_pt": {
- "avg": {"field": "processing_time_ms"}
- },
- "median_pt": {
- "percentiles": {"field": "processing_time_ms", "percents": [50]}
- }
- }
- }
- }
- })
- except opensearchpy.TransportError:
- self.logger.exception("Could not retrieve ML bucket processing time.")
- return
+ cluster = self._client.get_cluster_status()
+ col_state = cluster.get("collections", {})
+ target_collections = self._collections or list(col_state.keys())
+
+ for col_name in target_collections:
+ self._collect_collection(col_name)
+ except Exception as exc:
+ logging.getLogger(__name__).debug("SolrCollectionStats: cluster status error: %s", exc)
+
+ def _collect_collection(self, collection: str) -> None:
try:
- for job in results["aggregations"]["jobs"]["buckets"]:
- ml_job_stats = collections.OrderedDict()
- ml_job_stats["name"] = "ml_processing_time"
- ml_job_stats["job"] = job["key"]
- ml_job_stats["min"] = job["min_pt"]["value"]
- ml_job_stats["mean"] = job["mean_pt"]["value"]
- ml_job_stats["median"] = job["median_pt"]["values"]["50.0"]
- ml_job_stats["max"] = job["max_pt"]["value"]
- ml_job_stats["unit"] = "ms"
- self.metrics_store.put_doc(doc=dict(ml_job_stats), level=MetaInfoScope.cluster)
- except KeyError:
- # no ML running
+ resp = self._client._get(f"/api/collections/{collection}/core-properties")
+ data = resp.json()
+ num_docs = 0
+ index_size = 0
+ for _core_name, props in data.get("core-properties", {}).items():
+ num_docs += props.get("numDocs", 0)
+ index_size += props.get("indexHeapUsageBytes", 0)
+
+ self._put("num_docs", num_docs, "docs", meta={"collection": collection})
+ if index_size:
+ self._put("index_size_bytes", index_size, "bytes",
+ meta={"collection": collection})
+ except Exception:
pass
+ self._fetch_luke_stats(collection)
-class IndexSize(InternalTelemetryDevice):
+ def _fetch_luke_stats(self, collection: str) -> None:
+ try:
+ resp = self._client._get(
+ f"/solr/{collection}/admin/luke?numTerms=0&wt=json"
+ )
+ info = resp.json().get("index", {})
+ num_docs = info.get("numDocs")
+ deleted_docs = info.get("deletedDocs") or info.get("numDeletedDocs")
+ segment_count = info.get("segmentCount")
+
+ if num_docs is not None:
+ self._put("num_docs", num_docs, "docs", meta={"collection": collection})
+ if deleted_docs is not None:
+ self._put("num_deleted_docs", deleted_docs, "docs",
+ meta={"collection": collection})
+ if segment_count is not None:
+ self._put("segment_count", segment_count, "",
+ meta={"collection": collection})
+ except Exception as exc:
+ logging.getLogger(__name__).debug("SolrCollectionStats: luke fallback failed for %s: %s",
+ collection, exc)
+
+
+# ---------------------------------------------------------------------------
+# Device: SolrQueryStats
+# ---------------------------------------------------------------------------
+
+class SolrQueryStats(SolrTelemetryDevice):
"""
- Measures the final size of the index
+ Collect query latency percentiles and cache hit ratio metrics from Solr.
+
+ Metrics: query_latency_p50_ms, query_latency_p99_ms, query_latency_p999_ms,
+ query_requests_total, query_errors_total, query_cache_hit_ratio
"""
- def __init__(self, data_paths):
- super().__init__()
- self.data_paths = data_paths
- self.attached = False
- self.index_size_bytes = None
- def attach_to_node(self, node):
- self.attached = True
+ human_name = "Solr Query Stats"
+ help = "Query latency percentiles (p50/p99/p999), cache hit ratio, request and error totals"
- def detach_from_node(self, node, running):
- # we need to gather the file size after the node has terminated so we can be sure that it has written all its buffers.
- if not running and self.attached and self.data_paths:
- self.attached = False
- index_size_bytes = 0
- for data_path in self.data_paths:
- index_size_bytes += io.get_size(data_path)
- self.index_size_bytes = index_size_bytes
+ def _collect(self) -> None:
+ fmt, data = self._fetch_node_metrics_parsed()
+ if fmt == "prometheus":
+ self._collect_prometheus(data)
+ else:
+ self._collect_json(data)
+
+ def _collect_json(self, data: dict) -> None:
+ core = self._get_metric_json(data, "metrics", "solr.core") or {}
+
+ mappings = [
+ ("QUERY./select.requestTimes.p_50", "query_latency_p50_ms", "ms"),
+ ("QUERY./select.requestTimes.p_99", "query_latency_p99_ms", "ms"),
+ ("QUERY./select.requestTimes.p_99_9", "query_latency_p999_ms", "ms"),
+ ("QUERY./select.requests", "query_requests_total", ""),
+ ("QUERY./select.errors", "query_errors_total", ""),
+ ("CACHE.searcher.filterCache.hitratio", "query_cache_hit_ratio", ""),
+ ]
+ for json_key, osb_name, unit in mappings:
+ val = core.get(json_key)
+ if val is None and json_key.endswith("p_99_9"):
+ val = core.get(json_key.replace("p_99_9", "p_999"))
+ if val is not None:
+ self._put(osb_name, val, unit)
... 29122 lines suppressed ...