From 5362a7221c9d0d2ae405b64deb823b81863a59d1 Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Sun, 31 May 2026 11:27:26 +0300 Subject: [PATCH 01/11] Fix OAuth token exchange for IdPs that require client_secret_post Slack's MCP token endpoint advertises client_secret_post only and returns HTTP 200 with {"ok": false, "error": ...} on auth failure. The existing Basic-Auth-then-body fallback in exchange_code_for_tokens only retried on non-success status, so the body retry never fired and exchanges failed with "Response missing 'access_token'". Retry with client_secret in the POST body whenever the first response lacks an access_token, not just when the status is non-2xx. Also surface OAuth config drift on MCP tool-load failures: if the cached token's client_id/token_url no longer match the toolset's config (or, for servers like Slack that gate per workspace, the token was issued in a different workspace), log a hint pointing to re-authentication. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: avi@robusta.dev --- holmes/core/oauth_config.py | 13 +++- .../core/tools_utils/oauth_tool_connector.py | 55 +++++++++++++++ tests/test_mcp_oauth.py | 69 +++++++++++++++++++ 3 files changed, 135 insertions(+), 2 deletions(-) diff --git a/holmes/core/oauth_config.py b/holmes/core/oauth_config.py index 30cd54eb01..4b81068b24 100644 --- a/holmes/core/oauth_config.py +++ b/holmes/core/oauth_config.py @@ -76,8 +76,17 @@ def exchange_code_for_tokens( except httpx.HTTPError as e: raise OAuthTokenExchangeError(0, f"Token request to {token_url} failed: {e}") from e - # If Basic Auth failed, retry with client_secret in POST body - if client_secret and not resp.is_success: + # Retry with client_secret in POST body if Basic Auth failed, OR if the IdP + # returned 200 with a non-token body (e.g. Slack responds HTTP 200 + + # {"ok": false, "error": "bad_client_secret"} when it only accepts + # client_secret_post). + def _has_access_token(r: httpx.Response) -> bool: + try: + return "access_token" in r.json() + except Exception: + return False + + if client_secret and (not resp.is_success or not _has_access_token(resp)): data["client_secret"] = client_secret try: resp = httpx.post( diff --git a/holmes/core/tools_utils/oauth_tool_connector.py b/holmes/core/tools_utils/oauth_tool_connector.py index 5f622751d5..98f5f3c69e 100644 --- a/holmes/core/tools_utils/oauth_tool_connector.py +++ b/holmes/core/tools_utils/oauth_tool_connector.py @@ -131,6 +131,7 @@ def load_tools_for_user( "Failed to load OAuth tools for user %s on toolset %s: %s", user_id, toolset.name, self._extract_error_message(e), ) + self._log_token_config_mismatch(user_id, toolset) return [] def store_user_tools(self, user_id: str, toolset_name: str, tools: List[Tool]) -> None: @@ -224,6 +225,60 @@ def _extract_error_message(exc: BaseException) -> str: current = current.exceptions[0] return str(current) + @staticmethod + def _log_token_config_mismatch(user_id: str, toolset: Any) -> None: + """On MCP failure, log if the stored token was issued under a different + client_id / token_url than the toolset's current OAuth config. + + Catches config drift that would otherwise be invisible: rotated + client_id, two toolsets sharing a provider URL with different client + configs, or a stale cached token after credentials were changed. + Also surfaces the workspace/team the token belongs to for servers + that gate access per workspace (e.g. Slack), so users can spot + wrong-workspace auth. + """ + try: + oauth_cfg = getattr(getattr(toolset, "_mcp_config", None), "oauth", None) + if oauth_cfg is None: + return + store = getattr(_get_token_manager(), "_store", None) + if store is None: + return + provider = getattr(oauth_cfg, "authorization_url", None) or "unknown" + try: + tok = store.get_token(provider, user_id=user_id) + except TypeError: + tok = store.get_token(provider) + if not isinstance(tok, dict): + return + + cfg_client_id = getattr(oauth_cfg, "client_id", None) + cfg_token_url = getattr(oauth_cfg, "token_url", None) + tok_client_id = tok.get("client_id") + tok_token_url = tok.get("token_url") + tok_team = tok.get("team") + + mismatches = [] + if cfg_client_id and tok_client_id and cfg_client_id != tok_client_id: + mismatches.append(f"client_id: stored={tok_client_id} config={cfg_client_id}") + if cfg_token_url and tok_token_url and cfg_token_url != tok_token_url: + mismatches.append(f"token_url: stored={tok_token_url} config={cfg_token_url}") + + if mismatches: + logger.warning( + "MCP token/config mismatch for user %s on toolset %s — %s. " + "The cached token was issued under a different OAuth config; re-authenticate.", + user_id, toolset.name, "; ".join(mismatches), + ) + elif tok_team: + logger.warning( + "MCP failure for user %s on toolset %s — token was issued in workspace %s. " + "If the server gates access per workspace, the user may have authenticated in the wrong one.", + user_id, toolset.name, tok_team, + ) + except Exception: + logger.debug("Failed to log token/config mismatch", exc_info=True) + @staticmethod def _evict_expired_token(user_id: str, toolset: Any) -> None: """Remove an expired/revoked token from cache and disk (CLI only). diff --git a/tests/test_mcp_oauth.py b/tests/test_mcp_oauth.py index bf066215e4..1c09453b68 100644 --- a/tests/test_mcp_oauth.py +++ b/tests/test_mcp_oauth.py @@ -32,7 +32,9 @@ OAuthDecisionCode, OAuthEndpoints, OAuthExchangeManager, + OAuthTokenExchangeError, _get_exchange_manager, + exchange_code_for_tokens, parse_oauth_decision, ) from holmes.core.oauth_utils import ( @@ -370,6 +372,73 @@ def test_missing_exchange_does_not_crash(self): _get_exchange_manager().complete_exchange("nonexistent-id", oauth_code, None) # Should log error but not raise + def test_client_secret_post_falls_back_when_idp_returns_200_on_error(self): + """Regression: Slack (and other client_secret_post-only IdPs) return HTTP 200 + with {"ok": false, "error": ...} when the secret is sent via Basic Auth. + + The exchange must detect a 200 response without an access_token and retry + with client_secret in the POST body. + """ + basic_auth_resp = MagicMock() + basic_auth_resp.status_code = 200 + basic_auth_resp.is_success = True + basic_auth_resp.json.return_value = {"ok": False, "error": "bad_client_secret"} + + body_auth_resp = MagicMock() + body_auth_resp.status_code = 200 + body_auth_resp.is_success = True + body_auth_resp.json.return_value = { + "ok": True, + "access_token": "xoxp-slack-token", + "token_type": "Bearer", + } + + with patch( + "holmes.core.oauth_config.httpx.post", + side_effect=[basic_auth_resp, body_auth_resp], + ) as mock_post: + token_data = exchange_code_for_tokens( + token_url="https://slack.com/api/oauth.v2.user.access", + code="slack-auth-code", + redirect_uri="http://frontend/callback", + client_id="slack-client-id", + code_verifier="slack-pkce-verifier", + client_secret="slack-client-secret", + ) + + assert token_data["access_token"] == "xoxp-slack-token" + assert mock_post.call_count == 2 + + first_call_kwargs = mock_post.call_args_list[0].kwargs + assert isinstance(first_call_kwargs.get("auth"), httpx.BasicAuth) + + second_call_kwargs = mock_post.call_args_list[1].kwargs + assert second_call_kwargs.get("auth") is None + assert second_call_kwargs["data"]["client_secret"] == "slack-client-secret" + + def test_client_secret_post_raises_when_body_retry_also_fails(self): + """If even the POST-body retry returns 200 without access_token, the function + must still raise OAuthTokenExchangeError (no silent success).""" + bad_resp = MagicMock() + bad_resp.status_code = 200 + bad_resp.is_success = True + bad_resp.text = '{"ok": false, "error": "bad_client_secret"}' + bad_resp.json.return_value = {"ok": False, "error": "bad_client_secret"} + + with patch( + "holmes.core.oauth_config.httpx.post", + side_effect=[bad_resp, bad_resp], + ): + with pytest.raises(OAuthTokenExchangeError) as excinfo: + exchange_code_for_tokens( + token_url="https://slack.com/api/oauth.v2.user.access", + code="slack-auth-code", + redirect_uri="http://frontend/callback", + client_id="slack-client-id", + client_secret="slack-client-secret", + ) + assert "access_token" in str(excinfo.value.detail) + class TestParseOAuthDecision: def test_valid_oauth_decision(self): From e5fd49f8015289c17313546f6a76875b4335bcd2 Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 13:46:32 +0300 Subject: [PATCH 02/11] Add generic multi-instance toolset wrapper; convert ServiceNow and Datadog Introduce holmes/plugins/toolsets/multi_instance.py: a composition wrapper that makes any single-instance toolset multi-instance without changing the toolset. Wrap a toolset at registration with `multi_instance(ToolsetClass)` and it: - accepts the child's flat config OR `{, instances: [...]}` - builds one child toolset per instance, running each child's own prerequisites_callable (real validation + health) on a per-instance flat config (top-level globals merged in; auth-as-a-unit and mTLS-as-a-pair preserved) - exposes the union of children's tools as routing proxies that strip the generic `instance` param and delegate to the selected child's tool (approval, coercion and transformers run on the child untouched) - adds a `_list_instances` tool only when >1 instance is configured - aggregates health tolerantly (loads if any instance is reachable) Converting a toolset is one line at registration and the toolset file is unchanged. Convert ServiceNow and the four Datadog toolsets as the first examples. Backwards compatible: a flat config becomes a single `default` instance with no `instance` param and no list tool. Tests exercise the wrapped path end-to-end (routed calls asserted on the wire), not directly-constructed toolsets. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 11 +- holmes/plugins/toolsets/multi_instance.py | 359 ++++++++++++++++++ .../datadog/test_datadog_multi_instance.py | 122 ++++++ tests/plugins/toolsets/test_multi_instance.py | 228 +++++++++++ .../test_servicenow_multi_instance.py | 120 ++++++ 5 files changed, 835 insertions(+), 5 deletions(-) create mode 100644 holmes/plugins/toolsets/multi_instance.py create mode 100644 tests/plugins/toolsets/datadog/test_datadog_multi_instance.py create mode 100644 tests/plugins/toolsets/test_multi_instance.py create mode 100644 tests/plugins/toolsets/test_servicenow_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index f9d8324421..b13267c03f 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -57,6 +57,7 @@ from holmes.plugins.toolsets.kubectl_run.kubectl_run_toolset import KubectlRunToolset from holmes.plugins.toolsets.kubernetes_logs import KubernetesLogsToolset from holmes.plugins.toolsets.mcp.toolset_mcp import RemoteMCPToolset +from holmes.plugins.toolsets.multi_instance import multi_instance from holmes.plugins.toolsets.newrelic.newrelic import NewRelicToolset from holmes.plugins.toolsets.rabbitmq.toolset_rabbitmq import RabbitMQToolset from holmes.plugins.toolsets.robusta.robusta import RobustaToolset @@ -112,10 +113,10 @@ def load_python_toolsets( GrafanaToolset(), NotionToolset(), KafkaToolset(), - DatadogLogsToolset(), - DatadogGeneralToolset(), - DatadogMetricsToolset(), - DatadogTracesToolset(), + multi_instance(DatadogLogsToolset), + multi_instance(DatadogGeneralToolset), + multi_instance(DatadogMetricsToolset), + multi_instance(DatadogTracesToolset), OpenSearchQueryAssistToolset(), CoralogixToolset(), RabbitMQToolset(), @@ -125,7 +126,7 @@ def load_python_toolsets( MongoDBAtlasToolset(), SkillsToolset(dal=dal, additional_search_paths=additional_search_paths), AzureSQLToolset(), - ServiceNowTablesToolset(), + multi_instance(ServiceNowTablesToolset), VictoriaLogsToolset(), DatabaseToolset(), ElasticsearchDataToolset(), diff --git a/holmes/plugins/toolsets/multi_instance.py b/holmes/plugins/toolsets/multi_instance.py new file mode 100644 index 0000000000..34cc471c4e --- /dev/null +++ b/holmes/plugins/toolsets/multi_instance.py @@ -0,0 +1,359 @@ +"""Generic multi-instance support via composition (delegation), not inheritance. + +A toolset stays a plain *single-instance* toolset — it knows how to talk to ONE +endpoint and nothing about "instances". To let a single HolmesGPT deployment talk +to several endpoints of the same kind (prod-eu vs prod-us, a Grafana per cluster, …) +you wrap the toolset: + + from holmes.plugins.toolsets.multi_instance import multi_instance + ... + multi_instance(ServiceNowTablesToolset), # <- the entire conversion + +`multi_instance(cls)` returns a `MultiInstanceToolset` that: + +- mirrors the child's `name`, `description`, `icon_url`, `docs_url`, `tags`, etc., so + it registers transparently under the same toolset name; +- accepts either the child's normal flat config **or** `{, instances: [...]}`; +- builds one child toolset per configured instance, running each child's own + `prerequisites_callable` (its real validation + health check) against a per-instance + flat config (top-level globals merged in); +- exposes the union of the children's tools as routing proxies that strip the generic + `instance` parameter and delegate to the chosen child's identically-named tool; +- adds a `_list_instances` discovery tool **only** when >1 instance is configured; +- aggregates health tolerantly (loads if any instance is reachable). + +Design rule (where new functionality goes): **single-endpoint concern → the toolset; +choosing/combining endpoints → here, in the wrapper.** + +Backwards compatibility: a flat config (no `instances:`) becomes a single instance named +`default` with no `instance` param and no list tool — byte-for-byte the child's normal +surface. Existing `instances:` configs keep working, including auth-as-a-unit and +mTLS-as-a-pair global fall-through (see `_ATOMIC_GROUPS`). +""" + +import logging +from typing import Any, Dict, List, Optional, Tuple, Type + +from pydantic import ConfigDict + +from holmes.core.tools import ( + CallablePrerequisite, + StructuredToolResult, + StructuredToolResultStatus, + Tool, + ToolInvokeContext, + ToolParameter, + Toolset, +) +from holmes.plugins.toolsets.utils import toolset_name_for_one_liner +from holmes.utils.pydantic_utils import build_config_example + +logger = logging.getLogger(__name__) + +INSTANCE_PARAM_NAME = "instance" +INSTANCE_PARAM = ToolParameter( + description=( + "Name of the instance to target. Required when more than one instance is " + "configured (see the `*_list_instances` tool). Leave empty when a single " + "instance is configured." + ), + type="string", + required=False, +) + +# Field groups inherited from the top-level globals as an atomic unit: if an +# instance sets ANY field in a group, it inherits NONE of that group. This +# reproduces the existing fall-through semantics generically — auth methods are +# mutually exclusive (api_key XOR basic XOR bearer) and mTLS is a cert/key pair — +# so a global default never gets cross-wired into an instance that picked another. +_ATOMIC_GROUPS: List[set] = [ + {"api_key", "username", "password", "bearer_token"}, + {"client_cert", "client_key"}, +] + +# Non-secret fields surfaced by the list-instances tool when present on an instance. +_IDENTIFYING_FIELDS = ("api_url", "url", "prometheus_url", "connection_url") + + +def _merge_instance_config(globals_: Dict[str, Any], entry: Dict[str, Any]) -> Dict[str, Any]: + """Merge top-level globals into one instance entry (entry wins per key). + + Atomic groups (auth, mTLS) are dropped from the inherited globals when the + instance sets any member of the group, preserving the original fall-through. + """ + inherited = dict(globals_) + for group in _ATOMIC_GROUPS: + if any(key in entry for key in group): + for key in group: + inherited.pop(key, None) + return {**inherited, **entry} + + +def _parse_instances(config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: + """Decompose a wrapper config into ordered (instance_name, flat_child_config) pairs. + + Flat config (no `instances:`) → one instance named `default`. + """ + raw = config.get("instances") + if not raw: + flat = {k: v for k, v in config.items() if k != "instances"} + return [("default", flat)] + if not isinstance(raw, list): + raise ValueError("`instances` must be a list") + globals_ = {k: v for k, v in config.items() if k != "instances"} + seen: set = set() + out: List[Tuple[str, Dict[str, Any]]] = [] + for idx, entry in enumerate(raw): + if not isinstance(entry, dict): + raise ValueError(f"`instances[{idx}]` must be a dict, got {type(entry).__name__}") + name = entry.get("name") or f"instance-{idx}" + if name in seen: + raise ValueError(f"Duplicate instance name: '{name}'") + seen.add(name) + # `name` is the wrapper's routing key, not part of the child config. + child_entry = {k: v for k, v in entry.items() if k != "name"} + out.append((name, _merge_instance_config(globals_, child_entry))) + return out + + +class _RoutingTool(Tool): + """Proxy tool: strips `instance`, picks the child, delegates to its same-named tool. + + Delegating to `child_tool.invoke(...)` preserves the child's approval, parameter + coercion, transformers and logging untouched. `toolset` points at the wrapper so + wrapper-level `restricted_tools` filtering still applies during tool listing. + """ + + model_config = ConfigDict(arbitrary_types_allowed=True) + + def __init__(self, wrapper: "MultiInstanceToolset", template: Tool, add_instance_param: bool): + params = dict(template.parameters) + if add_instance_param: + params.setdefault(INSTANCE_PARAM_NAME, INSTANCE_PARAM) + super().__init__( + name=template.name, + description=template.description, + parameters=params, + user_description=template.user_description, + icon_url=template.icon_url, + ) + self._wrapper = wrapper + self._template = template + + @property + def toolset(self): + return self._wrapper + + def invoke(self, params: Dict, context: ToolInvokeContext) -> StructuredToolResult: + call_params = dict(params) + requested = call_params.pop(INSTANCE_PARAM_NAME, None) + try: + child = self._wrapper._resolve_child(requested) + except ValueError as e: + return StructuredToolResult( + status=StructuredToolResultStatus.ERROR, error=str(e), params=params + ) + child_tool = self._wrapper._child_tool(child, self.name) + if child_tool is None: + return StructuredToolResult( + status=StructuredToolResultStatus.ERROR, + error=( + f"Tool '{self.name}' is not available on instance " + f"'{requested or 'default'}'." + ), + params=params, + ) + return child_tool.invoke(call_params, context) + + def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: + # `invoke` is overridden to delegate; `_invoke` is never reached. + raise NotImplementedError + + def get_parameterized_one_liner(self, params: Dict) -> str: + try: + return self._template.get_parameterized_one_liner(params) + except Exception: + return f"{toolset_name_for_one_liner(self._wrapper.name)}: {self.name}" + + +class ListInstancesTool(Tool): + """Lets the LLM discover configured instances. Added only when >1 instance.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + def __init__(self, wrapper: "MultiInstanceToolset"): + scoped = wrapper.name.replace("/", "_") + super().__init__( + name=f"{scoped}_list_instances", + description=( + f"List the instances configured for the `{wrapper.name}` toolset. " + f"Returns each instance's name so subsequent calls can target the " + f"right one via the `{INSTANCE_PARAM_NAME}` parameter." + ), + parameters={}, + ) + self._wrapper = wrapper + + @property + def toolset(self): + return self._wrapper + + def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: + return StructuredToolResult( + status=StructuredToolResultStatus.SUCCESS, + data={"instances": self._wrapper._instance_summaries()}, + params=params, + ) + + def get_parameterized_one_liner(self, params: Dict) -> str: + return f"{toolset_name_for_one_liner(self._wrapper.name)}: List instances" + + +class MultiInstanceToolset(Toolset): + """Wraps a single-instance toolset class and routes calls across N instances.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + def __init__(self, child_cls: Type[Toolset]): + template = child_cls() + super().__init__( + name=template.name, + description=template.description, + icon_url=template.icon_url, + docs_url=template.docs_url, + tags=list(template.tags), + prerequisites=[CallablePrerequisite(callable=self.prerequisites_callable)], + tools=[], + enabled=False, + experimental=template.experimental, + ) + # Mirror display metadata from the child so the wrapper is transparent. + self.llm_instructions = template.llm_instructions + self._child_cls = child_cls + self._children: Dict[str, Toolset] = {} + self._instance_configs: Dict[str, Dict[str, Any]] = {} + + # Config schema/example come from the child's config classes (the wrapper's own + # `config_classes` ClassVar stays empty). The `instances:` shape is documented; + # the flat child schema drives the UI form and stays backwards compatible. + def get_config_schema(self) -> Optional[Dict[str, Any]]: + classes = self._child_cls.config_classes + if not classes: + return None + return {cls.__name__: cls.build_schema_entry() for cls in classes} # type: ignore[attr-defined] + + def get_config_example(self) -> Optional[Dict[str, Any]]: + classes = self._child_cls.config_classes + return build_config_example(classes[0]) if classes else None + + # --- prerequisites: build children, run their health checks, build tools --- + + def prerequisites_callable(self, config: Dict[str, Any]) -> Tuple[bool, str]: + try: + instances = _parse_instances(config or {}) + except Exception as e: + return False, f"Invalid {self.name} configuration: {e}" + + self._children = {} + self._instance_configs = {} + failures: List[str] = [] + successes: List[str] = [] + + for name, flat in instances: + child = self._child_cls() + self._forward_overrides(child) + ok, msg = self._run_child_prerequisites(child, flat) + self._children[name] = child + self._instance_configs[name] = flat + label = f"[{name}] {msg}".strip() + (successes if ok else failures).append(label) + + self._build_tools() + return self._aggregate(failures, successes) + + def _forward_overrides(self, child: Toolset) -> None: + """Propagate toolset-level overrides so the child enforces them too.""" + child.restricted_tools = self.restricted_tools + child.approval_required_tools = self.approval_required_tools + + def _run_child_prerequisites( + self, child: Toolset, flat_config: Dict[str, Any] + ) -> Tuple[bool, str]: + """Run the child's own callable prerequisite (validation + health) on a flat config.""" + callable_prereq = next( + (p for p in child.prerequisites if isinstance(p, CallablePrerequisite)), None + ) + if callable_prereq is None: + child.config = flat_config + return True, "" + try: + ok, msg = callable_prereq.callable(flat_config) + return bool(ok), msg or "" + except Exception as e: + return False, str(e) + + def _build_tools(self) -> None: + """Expose the union of children's tools as routing proxies (+ list tool when >1).""" + multi = len(self._children) > 1 + templates: Dict[str, Tool] = {} + for child in self._children.values(): + for tool in child.tools: + templates.setdefault(tool.name, tool) + tools: List[Tool] = [ + _RoutingTool(self, tmpl, add_instance_param=multi) for tmpl in templates.values() + ] + if multi: + tools.append(ListInstancesTool(self)) + self.tools = tools + + def _aggregate(self, failures: List[str], successes: List[str]) -> Tuple[bool, str]: + """Tolerant: succeed if at least one instance is healthy; surface every failure.""" + if not successes: + return False, "\n".join(failures) or f"No instances configured for {self.name}" + if failures: + total = len(failures) + len(successes) + logger.warning( + "%s: %d/%d instance(s) healthy. Failed: %s", + self.name, + len(successes), + total, + failures, + ) + return True, "; ".join(successes) + "; failed: " + " | ".join(failures) + return True, "; ".join(successes) + + # --- routing helpers used by the proxy tools --- + + def _resolve_child(self, requested: Optional[str]) -> Toolset: + configured = sorted(self._children) + if not requested: + if len(self._children) == 1: + return next(iter(self._children.values())) + raise ValueError( + f"`{INSTANCE_PARAM_NAME}` is required (configured: {configured})" + ) + if requested not in self._children: + raise ValueError( + f"Unknown {INSTANCE_PARAM_NAME} '{requested}'. Configured: {configured}" + ) + return self._children[requested] + + @staticmethod + def _child_tool(child: Toolset, name: str) -> Optional[Tool]: + return next((t for t in child.tools if t.name == name), None) + + def _instance_summaries(self) -> List[Dict[str, Any]]: + summaries: List[Dict[str, Any]] = [] + for name, flat in self._instance_configs.items(): + summary: Dict[str, Any] = {"name": name} + for field in _IDENTIFYING_FIELDS: + if flat.get(field): + summary[field] = flat[field] + break + summaries.append(summary) + return summaries + + +def multi_instance(child_cls: Type[Toolset]) -> MultiInstanceToolset: + """Wrap a single-instance toolset class to make it multi-instance capable.""" + return MultiInstanceToolset(child_cls) diff --git a/tests/plugins/toolsets/datadog/test_datadog_multi_instance.py b/tests/plugins/toolsets/datadog/test_datadog_multi_instance.py new file mode 100644 index 0000000000..352067888d --- /dev/null +++ b/tests/plugins/toolsets/datadog/test_datadog_multi_instance.py @@ -0,0 +1,122 @@ +"""Multi-instance proof for Datadog through the actual wrapper. + +These tests exercise `multi_instance(DatadogLogsToolset)` — i.e. exactly what +`load_builtin_toolsets()` registers — NOT a directly-constructed toolset. Datadog +uses dual-key auth (`api_key` + `app_key`), so this also covers the generic +global-`app_key` fall-through. HTTP is mocked (no patching of internals): the real +health check runs, and a routed tool call is asserted on the wire. +""" + +import re + +import responses + +from holmes.core.tools import StructuredToolResultStatus +from holmes.plugins.toolsets.datadog.toolset_datadog_logs import DatadogLogsToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + +US = "https://api.datadoghq.com" +EU = "https://api.datadoghq.eu" +SEARCH = "/api/v2/logs/events/search" +_OK_BODY = {"data": [], "meta": {"page": {"after": None}}} + + +def _register_search(rsps, host): + # api_url is a pydantic AnyUrl (trailing slash), so the real URL has a double + # slash before /api. Match host + path tolerant of slash count, and matches + # both the health probe and later routed calls. + rsps.add( + responses.POST, + re.compile(re.escape(host) + r"/+api/v2/logs/events/search"), + json=_OK_BODY, + status=200, + ) + + +class TestDatadogFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(DatadogLogsToolset) + with responses.RequestsMock() as rsps: + _register_search(rsps, US) + ok, _ = ts.prerequisites_callable( + {"api_key": "k", "app_key": "a", "api_url": US} + ) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestDatadogMultiInstance: + def _build(self, rsps): + _register_search(rsps, US) + _register_search(rsps, EU) + ts = multi_instance(DatadogLogsToolset) + ok, _ = ts.prerequisites_callable( + { + "app_key": "GLOBAL_APP", # shared across instances + "instances": [ + {"name": "us", "api_url": US, "api_key": "k_us"}, + {"name": "eu", "api_url": EU, "api_key": "k_eu", "app_key": "eu_app"}, + ], + } + ) + assert ok is True + return ts + + def test_decomposition_and_global_fallthrough(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + us = ts._children["us"].dd_config + eu = ts._children["eu"].dd_config + assert us.api_key == "k_us" + assert us.app_key == "GLOBAL_APP" # inherited global + assert eu.api_key == "k_eu" + assert eu.app_key == "eu_app" # per-instance override + + def test_tool_surface(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + assert any(t.name == "datadog_logs_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + def test_routed_call_hits_selected_instance_on_the_wire(self): + """The real meaningful check: a call routed to `eu` must POST to the EU + host with EU's credentials — proving the wrapper delegates to the right + child end-to-end (not a directly-constructed toolset).""" + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + fetch = next(t for t in ts.tools if t.name == "fetch_datadog_logs") + result = fetch.invoke( + {"query": "service:web", INSTANCE_PARAM_NAME: "eu"}, + create_mock_tool_invoke_context(), + ) + # routing must not have errored on instance resolution + assert result.status in ( + StructuredToolResultStatus.SUCCESS, + StructuredToolResultStatus.NO_DATA, + ) + last = rsps.calls[-1].request + assert last.url.startswith(EU) + assert last.headers.get("DD-API-KEY") == "k_eu" + assert last.headers.get("DD-APPLICATION-KEY") == "eu_app" + + def test_routed_call_to_us_uses_us_credentials(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + fetch = next(t for t in ts.tools if t.name == "fetch_datadog_logs") + fetch.invoke( + {"query": "*", INSTANCE_PARAM_NAME: "us"}, + create_mock_tool_invoke_context(), + ) + last = rsps.calls[-1].request + assert last.url.startswith(US) + assert last.headers.get("DD-API-KEY") == "k_us" + assert last.headers.get("DD-APPLICATION-KEY") == "GLOBAL_APP" diff --git a/tests/plugins/toolsets/test_multi_instance.py b/tests/plugins/toolsets/test_multi_instance.py new file mode 100644 index 0000000000..a09f8b30a5 --- /dev/null +++ b/tests/plugins/toolsets/test_multi_instance.py @@ -0,0 +1,228 @@ +"""Tests for the generic multi-instance delegation wrapper. + +Uses a tiny fake single-instance toolset so the wrapper's behavior (config +decomposition, global fall-through, routing, param/list-tool injection, tolerant +health) is verified independently of any real toolset. +""" + +from typing import ClassVar, List, Optional, Type + +from holmes.core.tools import ( + CallablePrerequisite, + StructuredToolResult, + StructuredToolResultStatus, + Tool, + ToolParameter, + Toolset, + ToolsetTag, +) +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from holmes.utils.pydantic_utils import ToolsetConfig +from tests.conftest import create_mock_tool_invoke_context + + +class _FakeConfig(ToolsetConfig): + api_url: str + api_key: Optional[str] = None + username: Optional[str] = None + password: Optional[str] = None + + +class _FakeTool(Tool): + model_config = {"arbitrary_types_allowed": True} + + def __init__(self, toolset): + super().__init__( + name="fake_do", + description="do a thing", + parameters={"q": ToolParameter(type="string", required=False)}, + ) + self._toolset = toolset + + def _invoke(self, params, context) -> StructuredToolResult: + cfg = self._toolset.config + return StructuredToolResult( + status=StructuredToolResultStatus.SUCCESS, + data={ + "api_url": cfg.get("api_url"), + "api_key": cfg.get("api_key"), + "username": cfg.get("username"), + "q": params.get("q"), + }, + params=params, + ) + + def get_parameterized_one_liner(self, params) -> str: + return "fake" + + +class _FakeToolset(Toolset): + config_classes: ClassVar[List[Type]] = [_FakeConfig] + + def __init__(self): + super().__init__( + name="fake/svc", + description="fake", + tools=[], + prerequisites=[CallablePrerequisite(callable=self.prerequisites_callable)], + tags=[ToolsetTag.CORE], + enabled=False, + ) + self.tools = [_FakeTool(self)] + + def prerequisites_callable(self, config): + # Validate + "health check" (no network): require api_url. + if not config.get("api_url"): + return False, "missing api_url" + self.config = config + return True, f"connected to {config['api_url']}" + + +def _wrap(config: dict): + ts = multi_instance(_FakeToolset) + ts.prerequisites_callable(config) + return ts + + +def _call(ts, params): + tool = next(t for t in ts.tools if t.name == "fake_do") + return tool.invoke(params, create_mock_tool_invoke_context()) + + +class TestFlatShape: + def test_flat_config_single_default_instance(self): + ts = _wrap({"api_url": "http://one"}) + assert list(ts._children) == ["default"] + assert [t.name for t in ts.tools] == ["fake_do"] + # no instance param, no list tool + assert INSTANCE_PARAM_NAME not in ts.tools[0].parameters + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + + def test_flat_routes_to_default(self): + ts = _wrap({"api_url": "http://one"}) + r = _call(ts, {}) + assert r.status is StructuredToolResultStatus.SUCCESS + assert r.data["api_url"] == "http://one" + + def test_wrapper_mirrors_child_metadata(self): + ts = multi_instance(_FakeToolset) + assert ts.name == "fake/svc" + # schema comes from the child's config class + schema = ts.get_config_schema() + assert "_FakeConfig" in schema + + +class TestMultiShape: + def test_instances_expose_param_and_list_tool(self): + ts = _wrap( + {"instances": [ + {"name": "a", "api_url": "http://a"}, + {"name": "b", "api_url": "http://b"}, + ]} + ) + names = [t.name for t in ts.tools] + assert "fake_do" in names + assert "fake_svc_list_instances" in names + fake = next(t for t in ts.tools if t.name == "fake_do") + assert INSTANCE_PARAM_NAME in fake.parameters + + def test_routing_selects_the_named_child(self): + ts = _wrap( + {"instances": [ + {"name": "a", "api_url": "http://a"}, + {"name": "b", "api_url": "http://b"}, + ]} + ) + r = _call(ts, {INSTANCE_PARAM_NAME: "b"}) + assert r.data["api_url"] == "http://b" + + def test_missing_instance_param_errors(self): + ts = _wrap( + {"instances": [ + {"name": "a", "api_url": "http://a"}, + {"name": "b", "api_url": "http://b"}, + ]} + ) + r = _call(ts, {}) + assert r.status is StructuredToolResultStatus.ERROR + assert "instance" in r.error + + def test_unknown_instance_errors(self): + ts = _wrap({"instances": [{"name": "a", "api_url": "http://a"}]}) + # single instance -> auto-selects, so force >1 to require the param + ts = _wrap( + {"instances": [ + {"name": "a", "api_url": "http://a"}, + {"name": "b", "api_url": "http://b"}, + ]} + ) + r = _call(ts, {INSTANCE_PARAM_NAME: "zzz"}) + assert r.status is StructuredToolResultStatus.ERROR + assert "Unknown" in r.error + + def test_list_instances_returns_summaries(self): + ts = _wrap( + {"instances": [ + {"name": "a", "api_url": "http://a"}, + {"name": "b", "api_url": "http://b"}, + ]} + ) + tool = next(t for t in ts.tools if isinstance(t, ListInstancesTool)) + r = tool._invoke({}, create_mock_tool_invoke_context()) + got = {i["name"]: i.get("api_url") for i in r.data["instances"]} + assert got == {"a": "http://a", "b": "http://b"} + + def test_duplicate_names_rejected(self): + ts = multi_instance(_FakeToolset) + ok, msg = ts.prerequisites_callable( + {"instances": [ + {"name": "dup", "api_url": "http://a"}, + {"name": "dup", "api_url": "http://b"}, + ]} + ) + assert ok is False + assert "Duplicate instance name" in msg + + +class TestGlobalFallthrough: + def test_global_inherited_when_instance_omits(self): + ts = _wrap( + {"api_key": "GLOBAL", "instances": [{"name": "a", "api_url": "http://a"}]} + ) + r = _call(ts, {}) # single instance -> auto-select + assert r.data["api_key"] == "GLOBAL" + + def test_auth_atomic_group_not_cross_wired(self): + # Global api_key must NOT land on an instance that picked basic auth. + ts = _wrap( + { + "api_key": "GLOBAL", + "instances": [ + {"name": "a", "api_url": "http://a", "username": "u", "password": "p"}, + ], + } + ) + r = _call(ts, {}) + assert r.data["username"] == "u" + assert r.data["api_key"] is None # atomic group dropped the global api_key + + +class TestHealthAggregation: + def test_fails_only_when_all_unhealthy(self): + ts = multi_instance(_FakeToolset) + ok, msg = ts.prerequisites_callable( + {"instances": [{"name": "a"}, {"name": "b"}]} # no api_url -> both fail + ) + assert ok is False + + def test_passes_when_any_healthy(self): + ts = multi_instance(_FakeToolset) + ok, msg = ts.prerequisites_callable( + {"instances": [{"name": "a", "api_url": "http://a"}, {"name": "b"}]} + ) + assert ok is True + assert "failed:" in msg diff --git a/tests/plugins/toolsets/test_servicenow_multi_instance.py b/tests/plugins/toolsets/test_servicenow_multi_instance.py new file mode 100644 index 0000000000..cd7510ef36 --- /dev/null +++ b/tests/plugins/toolsets/test_servicenow_multi_instance.py @@ -0,0 +1,120 @@ +"""End-to-end multi-instance proof on the real ServiceNow toolset. + +ServiceNow's own file is unchanged from master (single-instance); it becomes +multi-instance purely by being wrapped with `multi_instance(...)`. These tests +prove the flat config still works (backwards compatible) and an `instances:` +config routes to the right endpoint. +""" + +import pytest +import responses + +from holmes.core.tools import StructuredToolResultStatus +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from holmes.plugins.toolsets.servicenow_tables.servicenow_tables import ( + ServiceNowTablesToolset, +) +from tests.conftest import create_mock_tool_invoke_context + + +def _health(rsps, api_url): + rsps.add( + responses.GET, + f"{api_url}/api/now/v2/table/sys_user", + json={"result": [{"sys_id": "1"}]}, + status=200, + ) + + +class TestServiceNowFlat: + def test_flat_config_is_backwards_compatible(self): + ts = multi_instance(ServiceNowTablesToolset) + with responses.RequestsMock() as rsps: + _health(rsps, "https://acme.service-now.com") + ok, _ = ts.prerequisites_callable( + {"api_url": "https://acme.service-now.com", "api_key": "k"} + ) + assert ok is True + names = {t.name for t in ts.tools} + assert names == {"servicenow_get_records", "servicenow_get_record"} + # single instance -> no routing affordances + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + records = next(t for t in ts.tools if t.name == "servicenow_get_records") + assert INSTANCE_PARAM_NAME not in records.parameters + + +class TestServiceNowMultiInstance: + def _build(self, rsps): + _health(rsps, "https://prod.service-now.com") + _health(rsps, "https://dev.service-now.com") + ts = multi_instance(ServiceNowTablesToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + {"name": "prod", "api_url": "https://prod.service-now.com", "api_key": "kp"}, + {"name": "dev", "api_url": "https://dev.service-now.com", "api_key": "kd"}, + ] + } + ) + assert ok is True + return ts + + def test_exposes_routing_param_and_list_tool(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + assert any(t.name == "servicenow_tables_list_instances" for t in ts.tools) + records = next(t for t in ts.tools if t.name == "servicenow_get_records") + assert INSTANCE_PARAM_NAME in records.parameters + + @pytest.mark.parametrize( + "instance,expected_host,expected_key", + [ + ("prod", "https://prod.service-now.com", "kp"), + ("dev", "https://dev.service-now.com", "kd"), + ], + ) + def test_each_instance_calls_its_own_endpoint_with_its_own_params( + self, instance, expected_host, expected_key + ): + """Invoking with a given instance must hit THAT instance's URL with THAT + instance's credentials, and forward the tool's params (table + query).""" + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + rsps.add( + responses.GET, + f"{expected_host}/api/now/v2/table/incident", + json={"result": [{"number": "INC42"}]}, + status=200, + ) + records = next(t for t in ts.tools if t.name == "servicenow_get_records") + result = records.invoke( + { + "table_name": "incident", + "sysparm_query": "active=true", + INSTANCE_PARAM_NAME: instance, + }, + create_mock_tool_invoke_context(), + ) + assert result.status is StructuredToolResultStatus.SUCCESS + call = rsps.calls[-1].request + # correct instance endpoint + assert call.url.startswith(f"{expected_host}/api/now/v2/table/incident") + # correct per-instance credential + assert call.headers.get("x-sn-apikey") == expected_key + # tool params forwarded on the wire + assert "sysparm_query=active%3Dtrue" in call.url or "active=true" in call.url + + def test_list_instances_reports_both(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if isinstance(t, ListInstancesTool)) + result = tool._invoke({}, create_mock_tool_invoke_context()) + got = {i["name"]: i.get("api_url") for i in result.data["instances"]} + assert got == { + "prod": "https://prod.service-now.com", + "dev": "https://dev.service-now.com", + } From 267933e37cf0e4ddaf9e123ad81ab0dd0da1e2e2 Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 14:03:33 +0300 Subject: [PATCH 03/11] Convert VictoriaLogs and Coralogix to multi-instance via the wrapper Wrap both toolsets with `multi_instance(...)` at registration (toolset files unchanged from master). Add `domain` to the list-instances identifying fields so Coralogix (no api_url) reports a useful summary. Each gets the standard 3-part test through the actual wrapper: flat config is backwards compatible (no instance param / list tool); an `instances:` config exposes the `instance` param + `_list_instances`; and a routed call for each instance is asserted on the wire (VictoriaLogs: bearer vs no-auth per host; Coralogix: per-instance domain + Bearer api_key). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 4 +- holmes/plugins/toolsets/multi_instance.py | 2 +- .../toolsets/test_coralogix_multi_instance.py | 106 ++++++++++++++++++ .../test_victorialogs_multi_instance.py | 88 +++++++++++++++ 4 files changed, 197 insertions(+), 3 deletions(-) create mode 100644 tests/plugins/toolsets/test_coralogix_multi_instance.py create mode 100644 tests/plugins/toolsets/test_victorialogs_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index b13267c03f..a1478c3346 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -118,7 +118,7 @@ def load_python_toolsets( multi_instance(DatadogMetricsToolset), multi_instance(DatadogTracesToolset), OpenSearchQueryAssistToolset(), - CoralogixToolset(), + multi_instance(CoralogixToolset), RabbitMQToolset(), BashExecutorToolset(), KubectlRunToolset(), @@ -127,7 +127,7 @@ def load_python_toolsets( SkillsToolset(dal=dal, additional_search_paths=additional_search_paths), AzureSQLToolset(), multi_instance(ServiceNowTablesToolset), - VictoriaLogsToolset(), + multi_instance(VictoriaLogsToolset), DatabaseToolset(), ElasticsearchDataToolset(), ElasticsearchClusterToolset(), diff --git a/holmes/plugins/toolsets/multi_instance.py b/holmes/plugins/toolsets/multi_instance.py index 34cc471c4e..a352885161 100644 --- a/holmes/plugins/toolsets/multi_instance.py +++ b/holmes/plugins/toolsets/multi_instance.py @@ -72,7 +72,7 @@ ] # Non-secret fields surfaced by the list-instances tool when present on an instance. -_IDENTIFYING_FIELDS = ("api_url", "url", "prometheus_url", "connection_url") +_IDENTIFYING_FIELDS = ("api_url", "url", "prometheus_url", "connection_url", "domain") def _merge_instance_config(globals_: Dict[str, Any], entry: Dict[str, Any]) -> Dict[str, Any]: diff --git a/tests/plugins/toolsets/test_coralogix_multi_instance.py b/tests/plugins/toolsets/test_coralogix_multi_instance.py new file mode 100644 index 0000000000..17986289b0 --- /dev/null +++ b/tests/plugins/toolsets/test_coralogix_multi_instance.py @@ -0,0 +1,106 @@ +"""Multi-instance proof for Coralogix through the actual wrapper. + +Coralogix is unchanged from master; `multi_instance(CoralogixToolset)` makes it +multi-instance. It has no `api_url` (region via `domain`) and Bearer auth. HTTP +is mocked; routed calls are asserted on the wire. +""" + +import re + +import pytest +import responses + +from holmes.plugins.toolsets.coralogix.toolset_coralogix import CoralogixToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + +EU = "eu2.coralogix.com" +US = "cx498.coralogix.com" + + +def _query_url(domain): + return f"https://ng-api-http.{domain}/api/v1/dataprime/query" + + +def _mock_query(rsps, domain): + # One registration matches both the health probe and routed calls. + rsps.add( + responses.POST, + re.compile(re.escape(_query_url(domain))), + json={"result": {"results": []}}, + status=200, + ) + + +class TestCoralogixFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(CoralogixToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _mock_query(rsps, EU) + ok, _ = ts.prerequisites_callable({"domain": EU, "api_key": "k"}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestCoralogixMultiInstance: + def _build(self, rsps): + _mock_query(rsps, EU) + _mock_query(rsps, US) + ts = multi_instance(CoralogixToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + {"name": "eu", "domain": EU, "api_key": "k_eu"}, + {"name": "us", "domain": US, "api_key": "k_us"}, + ] + } + ) + assert ok is True + return ts + + def test_tool_surface_and_list_instances(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "coralogix_list_instances" for t in ts.tools) + list_tool = next(t for t in ts.tools if isinstance(t, ListInstancesTool)) + got = { + i["name"]: i.get("domain") + for i in list_tool._invoke({}, create_mock_tool_invoke_context()).data[ + "instances" + ] + } + assert got == {"eu": EU, "us": US} + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize( + "instance,domain,key", + [("eu", EU, "k_eu"), ("us", US, "k_us")], + ) + def test_each_instance_calls_its_own_endpoint(self, instance, domain, key): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next( + t for t in ts.tools if t.name == "coralogix_execute_dataprime_query" + ) + tool.invoke( + { + "query": "source logs | limit 1", + "description": "fetch one log line", + "query_type": "Logs", + "start_date": "2026-01-01T00:00:00Z", + "end_date": "2026-01-01T01:00:00Z", + INSTANCE_PARAM_NAME: instance, + }, + create_mock_tool_invoke_context(), + ) + last = rsps.calls[-1].request + assert last.url.startswith(f"https://ng-api-http.{domain}/") + assert last.headers.get("Authorization") == f"Bearer {key}" diff --git a/tests/plugins/toolsets/test_victorialogs_multi_instance.py b/tests/plugins/toolsets/test_victorialogs_multi_instance.py new file mode 100644 index 0000000000..b67027b160 --- /dev/null +++ b/tests/plugins/toolsets/test_victorialogs_multi_instance.py @@ -0,0 +1,88 @@ +"""Multi-instance proof for VictoriaLogs through the actual wrapper. + +VictoriaLogs is unchanged from master (single-instance); it becomes multi-instance +purely by `multi_instance(VictoriaLogsToolset)` at registration. Auth is bearer +token OR basic. HTTP is mocked; routed calls are asserted on the wire. +""" + +import pytest +import responses + +from holmes.core.tools import StructuredToolResultStatus +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from holmes.plugins.toolsets.victorialogs.victorialogs import VictoriaLogsToolset +from tests.conftest import create_mock_tool_invoke_context + +PROD = "https://vl-prod.example.com" +DEV = "http://vl-dev.svc:9428" + + +def _health(rsps, api_url): + rsps.add(responses.GET, f"{api_url}/health", body="OK", status=200) + + +class TestVictoriaLogsFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(VictoriaLogsToolset) + with responses.RequestsMock() as rsps: + _health(rsps, PROD) + ok, _ = ts.prerequisites_callable({"api_url": PROD}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestVictoriaLogsMultiInstance: + def _build(self, rsps): + _health(rsps, PROD) + _health(rsps, DEV) + ts = multi_instance(VictoriaLogsToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + {"name": "prod", "api_url": PROD, "bearer_token": "tok_prod"}, + {"name": "dev", "api_url": DEV}, + ] + } + ) + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + assert any(t.name == "victorialogs_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize( + "instance,host,expect_auth", + [ + ("prod", PROD, "Bearer tok_prod"), + ("dev", DEV, None), + ], + ) + def test_each_instance_calls_its_own_endpoint(self, instance, host, expect_auth): + with responses.RequestsMock() as rsps: + ts = self._build(rsps) + rsps.add( + responses.POST, f"{host}/select/logsql/query", body="", status=200 + ) + query = next(t for t in ts.tools if t.name == "victorialogs_query") + result = query.invoke( + {"query": "*", INSTANCE_PARAM_NAME: instance}, + create_mock_tool_invoke_context(), + ) + assert result.status in ( + StructuredToolResultStatus.SUCCESS, + StructuredToolResultStatus.NO_DATA, + ) + last = rsps.calls[-1].request + assert last.url.startswith(f"{host}/select/logsql/query") + assert last.headers.get("Authorization") == expect_auth From c2241aafe5aee2a4787421e599bd6534388ce29b Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 15:26:30 +0300 Subject: [PATCH 04/11] Convert MongoDB Atlas to multi-instance via the wrapper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wrap MongoDBAtlasToolset with `multi_instance(...)` (toolset file unchanged). Instances differ by Atlas project + API keys (same host). The test asserts each child has its own isolated digest session (own keys, distinct Session objects — catching any credential cross-wiring) and that a routed call targets the selected project on the wire. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 2 +- .../test_mongodb_atlas_multi_instance.py | 77 +++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 tests/plugins/toolsets/test_mongodb_atlas_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index a1478c3346..efc09b458d 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -123,7 +123,7 @@ def load_python_toolsets( BashExecutorToolset(), KubectlRunToolset(), ConfluenceToolset(), - MongoDBAtlasToolset(), + multi_instance(MongoDBAtlasToolset), SkillsToolset(dal=dal, additional_search_paths=additional_search_paths), AzureSQLToolset(), multi_instance(ServiceNowTablesToolset), diff --git a/tests/plugins/toolsets/test_mongodb_atlas_multi_instance.py b/tests/plugins/toolsets/test_mongodb_atlas_multi_instance.py new file mode 100644 index 0000000000..0f26aa8fbd --- /dev/null +++ b/tests/plugins/toolsets/test_mongodb_atlas_multi_instance.py @@ -0,0 +1,77 @@ +"""Multi-instance proof for MongoDB Atlas through the actual wrapper. + +Instances differ by Atlas project + API keys (same host, cloud.mongodb.com). This +verifies per-instance credential ISOLATION (each child must have its own digest +session) and that a routed call targets the selected project on the wire. +""" + +import re + +import pytest +import responses + +from holmes.plugins.toolsets.atlas_mongodb.mongodb_atlas import MongoDBAtlasToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + +P1 = {"public_key": "pk1", "private_key": "sk1", "project_id": "PROJ1"} +P2 = {"public_key": "pk2", "private_key": "sk2", "project_id": "PROJ2"} + + +class TestAtlasFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(MongoDBAtlasToolset) + ok, _ = ts.prerequisites_callable(dict(P1)) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestAtlasMultiInstance: + def _build(self): + ts = multi_instance(MongoDBAtlasToolset) + ok, _ = ts.prerequisites_callable( + {"instances": [{"name": "a", **P1}, {"name": "b", **P2}]} + ) + assert ok is True + return ts + + def test_tool_surface(self): + ts = self._build() + assert any(t.name == "MongoDBAtlas_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + def test_each_instance_has_its_own_isolated_credentials(self): + """Catches credential cross-wiring: each child must carry its OWN Atlas + keys simultaneously (a shared session would leave both with the last + instance's credentials).""" + ts = self._build() + assert ts._children["a"]._session.auth.username == "pk1" + assert ts._children["b"]._session.auth.username == "pk2" + # distinct session objects, not a single shared one + assert ts._children["a"]._session is not ts._children["b"]._session + + @pytest.mark.parametrize( + "instance,project", + [("a", "PROJ1"), ("b", "PROJ2")], + ) + def test_routed_call_targets_selected_project(self, instance, project): + ts = self._build() + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + rsps.add( + responses.GET, + re.compile(r"https://cloud\.mongodb\.com/api/atlas/v2/groups/[^/]+/alerts"), + json={"results": []}, + status=200, + ) + tool = next(t for t in ts.tools if t.name == "atlas_return_project_alerts") + tool.invoke({INSTANCE_PARAM_NAME: instance}, create_mock_tool_invoke_context()) + last = rsps.calls[-1].request + assert f"/groups/{project}/alerts" in last.url From ce9e872a14b27e6dfd6a216b3d67929d7767520b Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 15:31:56 +0300 Subject: [PATCH 05/11] Convert Confluence to multi-instance via the wrapper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wrap ConfluenceToolset with `multi_instance(...)` (toolset file unchanged). Each instance builds its own internal HTTP toolset bound to that Confluence server, so routing a `confluence_request` to an instance hits THAT server with THAT instance's Bearer PAT — asserted on the wire for both Data-Center PAT instances. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 2 +- .../test_confluence_multi_instance.py | 92 +++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 tests/plugins/toolsets/test_confluence_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index efc09b458d..3bfee020f2 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -122,7 +122,7 @@ def load_python_toolsets( RabbitMQToolset(), BashExecutorToolset(), KubectlRunToolset(), - ConfluenceToolset(), + multi_instance(ConfluenceToolset), multi_instance(MongoDBAtlasToolset), SkillsToolset(dal=dal, additional_search_paths=additional_search_paths), AzureSQLToolset(), diff --git a/tests/plugins/toolsets/test_confluence_multi_instance.py b/tests/plugins/toolsets/test_confluence_multi_instance.py new file mode 100644 index 0000000000..1087375fdf --- /dev/null +++ b/tests/plugins/toolsets/test_confluence_multi_instance.py @@ -0,0 +1,92 @@ +"""Multi-instance proof for Confluence through the actual wrapper. + +Confluence is unchanged from master; `multi_instance(ConfluenceToolset)` makes it +multi-instance. Each instance builds its own internal HTTP toolset bound to that +Confluence server. Uses Data-Center PAT instances (Bearer auth, no cloud gateway). +HTTP is mocked; the routed call is asserted on the wire. +""" + +import re + +import pytest +import responses + +from holmes.plugins.toolsets.confluence.confluence import ConfluenceToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + +A = "https://confluence-a.example.com" +B = "https://confluence-b.example.com" + + +def _pat_instance(name, url, key): + return {"name": name, "api_url": url, "api_key": key, "auth_type": "bearer"} + + +def _mock_rest(rsps): + # Matches health probes (/rest/api/space) and routed calls (/rest/api/*) on any host. + rsps.add( + responses.GET, + re.compile(r"https://confluence-[ab]\.example\.com/rest/api/.*"), + json={"results": [], "size": 0}, + status=200, + ) + + +class TestConfluenceFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(ConfluenceToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _mock_rest(rsps) + ok, _ = ts.prerequisites_callable( + {"api_url": A, "api_key": "pat", "auth_type": "bearer"} + ) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestConfluenceMultiInstance: + def _build(self, rsps): + _mock_rest(rsps) + ts = multi_instance(ConfluenceToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + _pat_instance("a", A, "pat_a"), + _pat_instance("b", B, "pat_b"), + ] + } + ) + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "confluence_list_instances" for t in ts.tools) + assert any(t.name == "confluence_request" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize( + "instance,host,token", + [("a", A, "pat_a"), ("b", B, "pat_b")], + ) + def test_each_instance_calls_its_own_server(self, instance, host, token): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "confluence_request") + tool.invoke( + {"url": f"{host}/rest/api/content/123", INSTANCE_PARAM_NAME: instance}, + create_mock_tool_invoke_context(), + ) + last = rsps.calls[-1].request + assert last.url.startswith(f"{host}/rest/api/content/123") + assert last.headers.get("Authorization") == f"Bearer {token}" From 2d08a5332fb0b463dfa1e3cc2cd784cbc42b0fcc Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 15:34:14 +0300 Subject: [PATCH 06/11] Convert Prometheus to multi-instance via the wrapper Wrap PrometheusToolset with `multi_instance(...)` (toolset file unchanged). Instances differ by prometheus_url + additional_headers; a routed query for each instance hits THAT Prometheus with THAT instance's headers (asserted on the wire, e.g. per-instance X-Scope-OrgID). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 2 +- .../test_prometheus_multi_instance.py | 90 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 tests/plugins/toolsets/test_prometheus_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index 3bfee020f2..ceb7645403 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -136,7 +136,7 @@ def load_python_toolsets( if not DISABLE_PROMETHEUS_TOOLSET: from holmes.plugins.toolsets.prometheus.prometheus import PrometheusToolset - toolsets.append(PrometheusToolset()) + toolsets.append(multi_instance(PrometheusToolset)) if not USE_LEGACY_KUBERNETES_LOGS: toolsets.append(KubernetesLogsToolset()) diff --git a/tests/plugins/toolsets/test_prometheus_multi_instance.py b/tests/plugins/toolsets/test_prometheus_multi_instance.py new file mode 100644 index 0000000000..404d39ab04 --- /dev/null +++ b/tests/plugins/toolsets/test_prometheus_multi_instance.py @@ -0,0 +1,90 @@ +"""Multi-instance proof for Prometheus through the actual wrapper. + +Prometheus is unchanged from master; `multi_instance(PrometheusToolset)` makes it +multi-instance. Instances differ by `prometheus_url` + `additional_headers`. HTTP +is mocked; the routed call is asserted on the wire (host + per-instance headers). +""" + +import re + +import pytest +import responses + +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from holmes.plugins.toolsets.prometheus.prometheus import PrometheusToolset +from tests.conftest import create_mock_tool_invoke_context + +A = "http://prom-a.svc:9090/" +B = "http://prom-b.svc:9090/" + + +def _mock_prom(rsps): + # Health (/api/v1/query?query=up) + tool calls (/api/v1/rules etc.) on both hosts. + rsps.add( + responses.GET, + re.compile(r"http://prom-[ab]\.svc:9090/api/v1/.*"), + json={"status": "success", "data": {"groups": [], "result": []}}, + status=200, + ) + rsps.add( + responses.POST, + re.compile(r"http://prom-[ab]\.svc:9090/api/v1/.*"), + json={"status": "success", "data": {"result": []}}, + status=200, + ) + + +class TestPrometheusFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(PrometheusToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _mock_prom(rsps) + ok, _ = ts.prerequisites_callable({"prometheus_url": A}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestPrometheusMultiInstance: + def _build(self, rsps): + _mock_prom(rsps) + ts = multi_instance(PrometheusToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + {"name": "a", "prometheus_url": A, + "additional_headers": {"X-Scope-OrgID": "team-a"}}, + {"name": "b", "prometheus_url": B, + "additional_headers": {"X-Scope-OrgID": "team-b"}}, + ] + } + ) + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "prometheus_metrics_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize( + "instance,host,org", + [("a", "http://prom-a.svc:9090", "team-a"), + ("b", "http://prom-b.svc:9090", "team-b")], + ) + def test_each_instance_calls_its_own_prometheus(self, instance, host, org): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "list_prometheus_rules") + tool.invoke({INSTANCE_PARAM_NAME: instance}, create_mock_tool_invoke_context()) + last = rsps.calls[-1].request + assert last.url.startswith(f"{host}/api/v1/rules") + assert last.headers.get("X-Scope-OrgID") == org From b35b0391e78769d58c6ed4b67ec9765e68b56ab6 Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 15:38:00 +0300 Subject: [PATCH 07/11] Convert Azure SQL to multi-instance via the wrapper Wrap AzureSQLToolset with `multi_instance(...)` (toolset file unchanged). Uses the Azure SDK, so the test patches the credential + API client and asserts per-instance isolation (each child builds its own ClientSecretCredential, AzureSQLAPIClient with its own subscription, and database config) and that a routed call goes through the selected instance's API client querying that instance's subscription/server. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 2 +- .../test_azure_sql_multi_instance.py | 98 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 tests/plugins/toolsets/azure_sql/test_azure_sql_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index ceb7645403..29f5ae41b9 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -125,7 +125,7 @@ def load_python_toolsets( multi_instance(ConfluenceToolset), multi_instance(MongoDBAtlasToolset), SkillsToolset(dal=dal, additional_search_paths=additional_search_paths), - AzureSQLToolset(), + multi_instance(AzureSQLToolset), multi_instance(ServiceNowTablesToolset), multi_instance(VictoriaLogsToolset), DatabaseToolset(), diff --git a/tests/plugins/toolsets/azure_sql/test_azure_sql_multi_instance.py b/tests/plugins/toolsets/azure_sql/test_azure_sql_multi_instance.py new file mode 100644 index 0000000000..0900f1c1d0 --- /dev/null +++ b/tests/plugins/toolsets/azure_sql/test_azure_sql_multi_instance.py @@ -0,0 +1,98 @@ +"""Multi-instance proof for Azure SQL through the actual wrapper. + +Azure SQL is unchanged from master; `multi_instance(AzureSQLToolset)` makes it +multi-instance. It uses the Azure SDK (no plain HTTP), so the Azure credential and +API client are patched. Verifies per-instance credential/client/database ISOLATION +and that a routed call uses the selected instance's API client. +""" + +from unittest.mock import MagicMock, patch + +from holmes.plugins.toolsets.azure_sql.azure_sql_toolset import AzureSQLToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + + +def _cfg(tenant, client, secret, sub, rg, server, db): + return { + "tenant_id": tenant, + "client_id": client, + "client_secret": secret, + "database": { + "subscription_id": sub, + "resource_group": rg, + "server_name": server, + "database_name": db, + }, + } + + +A = _cfg("ten_a", "cli_a", "sec_a", "sub_a", "rg_a", "server_a", "db_a") +B = _cfg("ten_b", "cli_b", "sec_b", "sub_b", "rg_b", "server_b", "db_b") + + +def _api_factory(*args, **kwargs): + m = MagicMock() + m._subscription = args[1] if len(args) > 1 else kwargs.get("subscription_id") + return m + + +@patch( + "holmes.plugins.toolsets.azure_sql.azure_sql_toolset.AzureSQLAPIClient", + side_effect=_api_factory, +) +@patch("holmes.plugins.toolsets.azure_sql.azure_sql_toolset.ClientSecretCredential") +class TestAzureSqlMultiInstance: + def _build(self): + ts = multi_instance(AzureSQLToolset) + ok, _ = ts.prerequisites_callable( + {"instances": [{"name": "a", **A}, {"name": "b", **B}]} + ) + assert ok is True + return ts + + def test_flat_config_backwards_compatible(self, mock_cred, mock_api): + ts = multi_instance(AzureSQLToolset) + ok, _ = ts.prerequisites_callable(dict(A)) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + def test_tool_surface(self, mock_cred, mock_api): + ts = self._build() + assert any(t.name == "azure_sql_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + def test_per_instance_credential_and_client_isolation(self, mock_cred, mock_api): + ts = self._build() + # Each instance built its own service-principal credential. + tenants = {c.kwargs.get("tenant_id") for c in mock_cred.call_args_list} + assert {"ten_a", "ten_b"} <= tenants + # Each child has its own API client built with its own subscription + db config. + a, b = ts._children["a"], ts._children["b"] + assert a._api_client._subscription == "sub_a" + assert b._api_client._subscription == "sub_b" + assert a._api_client is not b._api_client + assert a._database_config.server_name == "server_a" + assert b._database_config.server_name == "server_b" + + def test_routed_call_uses_selected_instance_client(self, mock_cred, mock_api): + ts = self._build() + a, b = ts._children["a"], ts._children["b"] + a._api_client.reset_mock() + b._api_client.reset_mock() + tool = next(t for t in ts.tools if t.name == "analyze_database_health_status") + tool.invoke({INSTANCE_PARAM_NAME: "a"}, create_mock_tool_invoke_context()) + # The routed call went through instance a's API client, not b's. + assert a._api_client.method_calls, "expected instance a's API client to be used" + assert not b._api_client.method_calls, "instance b's API client must be untouched" + # and it queried instance a's subscription/server on the wire-equivalent call. + all_args = str(a._api_client.method_calls) + assert "sub_a" in all_args and "server_a" in all_args From f3fb2e8e974d31722f109108256a1468d0479ddd Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 15:53:28 +0300 Subject: [PATCH 08/11] Revert hand-rolled ES/Grafana multi-instance; use the generic wrapper instead MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Elasticsearch (#2087) and Grafana dashboards (#2080) previously grew their own bespoke multi-instance implementations (per-toolset `instances` config, `_get_instance`, `elasticsearch_instance`/`grafana_instance` params, list tools). Revert those toolsets to plain single-instance and make all of them multi-instance the same way as every other toolset — by wrapping at registration: multi_instance(ElasticsearchDataToolset) multi_instance(ElasticsearchClusterToolset) multi_instance(GrafanaToolset) # dashboards multi_instance(GrafanaLokiToolset) multi_instance(GrafanaTempoToolset) The toolset files are now single-instance (identical to pre-#2087/#2080); all multi-instance behavior lives in the shared wrapper. New tests verify, through the wrapper, that flat configs stay backwards compatible and that routing to each instance hits THAT instance's endpoint with its own credentials on the wire (ES: per-instance _cluster/health + ApiKey; Grafana dashboards/loki/tempo: per-instance host + Bearer). The hand-rolled multi-instance tests/docs are removed. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- .../builtin-toolsets/elasticsearch.md | 114 ---- .../builtin-toolsets/grafanadashboards.md | 97 --- holmes/plugins/toolsets/__init__.py | 10 +- .../toolsets/elasticsearch/elasticsearch.py | 522 +++------------ .../toolsets/grafana/base_grafana_toolset.py | 114 +--- holmes/plugins/toolsets/grafana/common.py | 184 +----- .../toolsets/grafana/toolset_grafana.py | 304 ++++----- .../test_elasticsearch_multi_instance.py | 607 +++--------------- .../grafana/test_grafana_multi_instance.py | 367 ++++------- .../toolsets/test_elasticsearch_mtls.py | 86 ++- .../toolsets/test_json_filter_mixin.py | 16 +- .../plugins/toolsets/test_verify_tool_urls.py | 10 +- 12 files changed, 482 insertions(+), 1949 deletions(-) diff --git a/docs/data-sources/builtin-toolsets/elasticsearch.md b/docs/data-sources/builtin-toolsets/elasticsearch.md index 08e84aa685..b66ab08917 100644 --- a/docs/data-sources/builtin-toolsets/elasticsearch.md +++ b/docs/data-sources/builtin-toolsets/elasticsearch.md @@ -134,118 +134,6 @@ Enable only the toolset(s) you need. Most users who just want to search logs onl !!! tip "Enable only what you need" You can enable just `elasticsearch/data` or `elasticsearch/cluster` depending on your needs. Most users who just want to search logs only need `elasticsearch/data`. -## Multiple Elasticsearch Instances - -If you run a dedicated Elasticsearch cluster per Kubernetes cluster (or want a single HolmesGPT deployment to query several clusters), set `instances` instead of the single-cluster `api_url`/`api_key` fields. The LLM picks the right instance per tool call via the `elasticsearch_instance` parameter (call `elasticsearch_data_list_instances` or `elasticsearch_cluster_list_instances` to see configured names). - -Top-level credentials act as **global defaults**. Per-instance settings override them. Use either `api_key` **or** `username` + `password` — they're mutually exclusive both at the top level and per instance. When overriding basic auth on an instance, set both `username` and `password` together. - -=== "Holmes CLI" - - ```yaml - toolsets: - elasticsearch/cluster: - enabled: true - config: - # Global defaults — applied to every instance unless overridden - username: elastic - password: "{{ env.ES_GLOBAL_PASSWORD }}" - timeout_seconds: 15 - verify_ssl: true - - instances: - - name: prod-eu - api_url: https://prod-eu.es.internal:9200 - # Inherits global username + password - - name: prod-us - api_url: https://prod-us.es.internal:9200 - # Per-instance override (uses a different basic auth password) - username: elastic - password: "{{ env.ES_US_PASSWORD }}" - - name: staging - api_url: https://staging.es.internal:9200 - # Per-instance override (uses an API key instead of basic auth) - api_key: "{{ env.STAGING_ES_API_KEY }}" - elasticsearch/data: - enabled: true - config: - username: elastic - password: "{{ env.ES_GLOBAL_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://prod-eu.es.internal:9200 - - name: prod-us - api_url: https://prod-us.es.internal:9200 - username: elastic - password: "{{ env.ES_US_PASSWORD }}" - ``` - -=== "Holmes Helm Chart" - - ```yaml - additionalEnvVars: - - name: ES_GLOBAL_PASSWORD - valueFrom: - secretKeyRef: - name: elasticsearch-credentials - key: global-password - - name: ES_US_PASSWORD - valueFrom: - secretKeyRef: - name: elasticsearch-credentials - key: us-password - - name: STAGING_ES_API_KEY - valueFrom: - secretKeyRef: - name: elasticsearch-credentials - key: staging-api-key - - toolsets: - elasticsearch/cluster: - enabled: true - config: - username: elastic - password: "{{ env.ES_GLOBAL_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://prod-eu.es.internal:9200 - - name: prod-us - api_url: https://prod-us.es.internal:9200 - username: elastic - password: "{{ env.ES_US_PASSWORD }}" - - name: staging - api_url: https://staging.es.internal:9200 - api_key: "{{ env.STAGING_ES_API_KEY }}" - ``` - -=== "Robusta Helm Chart" - - ```yaml - holmes: - additionalEnvVars: - - name: ES_GLOBAL_PASSWORD - valueFrom: - secretKeyRef: - name: elasticsearch-credentials - key: global-password - toolsets: - elasticsearch/cluster: - enabled: true - config: - username: elastic - password: "{{ env.ES_GLOBAL_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://prod-eu.es.internal:9200 - - name: prod-us - api_url: https://prod-us.es.internal:9200 - ``` - -**Health check is tolerant**: if some instances are unreachable at startup, the toolset still loads with the healthy ones. The unreachable instances are listed in the toolset status string and discoverable via `elasticsearch_data_list_instances` / `elasticsearch_cluster_list_instances`. - -!!! note "Backwards compatibility" - Existing single-cluster configs (with a top-level `api_url`) continue to work unchanged — they're treated as a single instance named `default`, and the `elasticsearch_instance` parameter is auto-selected. - ## Authentication The toolsets support multiple authentication methods: @@ -367,11 +255,9 @@ If Elasticsearch uses a private CA, use the global [`certificate`](../../referen | Toolset | Tool Name | Description | |---------|-----------|-------------| -| `elasticsearch/data` | elasticsearch_data_list_instances | List configured Elasticsearch instances on the data toolset (multi-instance discovery) | | `elasticsearch/data` | elasticsearch_search | Search documents using Elasticsearch Query DSL | | `elasticsearch/data` | elasticsearch_mappings | Get field mappings for an index | | `elasticsearch/data` | elasticsearch_list_indices | List indices matching a pattern | -| `elasticsearch/cluster` | elasticsearch_cluster_list_instances | List configured Elasticsearch instances on the cluster toolset (multi-instance discovery) | | `elasticsearch/cluster` | elasticsearch_cat | Query _cat APIs (indices, shards, nodes, etc.) | | `elasticsearch/cluster` | elasticsearch_cluster_health | Get cluster health status | | `elasticsearch/cluster` | elasticsearch_allocation_explain | Explain shard allocation decisions | diff --git a/docs/data-sources/builtin-toolsets/grafanadashboards.md b/docs/data-sources/builtin-toolsets/grafanadashboards.md index 3c31b16d61..76f36a734d 100644 --- a/docs/data-sources/builtin-toolsets/grafanadashboards.md +++ b/docs/data-sources/builtin-toolsets/grafanadashboards.md @@ -104,103 +104,6 @@ For visual rendering, the [Grafana Image Renderer](https://grafana.com/grafana/p --8<-- "snippets/helm_upgrade_command.md" -## Multiple Grafana Instances - -If you run a Grafana instance in each Kubernetes cluster (or want a single Holmes deployment to query several Grafana servers), set `instances` instead of the single-instance `api_url`/`api_key` fields. The LLM picks the right instance per tool call via the `grafana_instance` parameter (run `grafana_list_instances` to see configured names). - -Top-level credentials act as **global defaults**. Per-instance settings override them. Use either `api_key` (Bearer) **or** `username` + `password` (HTTP Basic) — they're mutually exclusive per instance. - -=== "Holmes CLI" - - ```yaml - toolsets: - grafana/dashboards: - enabled: true - config: - # Global defaults — applied to every instance unless overridden - username: holmes - password: "{{ env.GRAFANA_PASSWORD }}" - timeout_seconds: 30 - - instances: - - name: prod-eu - api_url: https://grafana.eu-west-1.internal - - name: prod-us - api_url: https://grafana.us-east-1.internal - - name: staging - api_url: https://grafana.staging.internal - # Per-instance override (uses an API key instead of the global basic auth) - api_key: "{{ env.STAGING_GRAFANA_API_KEY }}" - ``` - -=== "Holmes Helm Chart" - - ```yaml - additionalEnvVars: - - name: GRAFANA_PASSWORD - valueFrom: - secretKeyRef: - name: grafana-credentials - key: password - - name: STAGING_GRAFANA_API_KEY - valueFrom: - secretKeyRef: - name: grafana-credentials - key: staging-api-key - - toolsets: - grafana/dashboards: - enabled: true - config: - username: holmes - password: "{{ env.GRAFANA_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://grafana.eu-west-1.internal - - name: prod-us - api_url: https://grafana.us-east-1.internal - - name: staging - api_url: https://grafana.staging.internal - api_key: "{{ env.STAGING_GRAFANA_API_KEY }}" - ``` - -=== "Robusta Helm Chart" - - ```yaml - holmes: - additionalEnvVars: - - name: GRAFANA_PASSWORD - valueFrom: - secretKeyRef: - name: grafana-credentials - key: password - toolsets: - grafana/dashboards: - enabled: true - config: - username: holmes - password: "{{ env.GRAFANA_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://grafana.eu-west-1.internal - - name: prod-us - api_url: https://grafana.us-east-1.internal - ``` - -**Health check is tolerant**: if some instances are unreachable at startup, the toolset still loads with the healthy ones. The unreachable instances are listed in the toolset status string and via `grafana_list_instances`. - -### Username/password authentication (single instance) - -If you just want HTTP Basic auth without multi-instance, set `username`/`password` at the top level: - - toolsets: - grafana/dashboards: - enabled: true - config: - api_url: https://grafana.internal - username: holmes - password: "{{ env.GRAFANA_PASSWORD }}" - ## Visual Rendering When the Grafana Image Renderer is available, HolmesGPT can take screenshots of dashboards and panels and analyze them using the LLM's vision capabilities. This is useful for: diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index 29f5ae41b9..adb029cc80 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -107,10 +107,10 @@ def load_python_toolsets( InternetToolset(), ConnectivityCheckToolset(), RobustaToolset(dal), - GrafanaLokiToolset(), - GrafanaTempoToolset(), + multi_instance(GrafanaLokiToolset), + multi_instance(GrafanaTempoToolset), NewRelicToolset(), - GrafanaToolset(), + multi_instance(GrafanaToolset), NotionToolset(), KafkaToolset(), multi_instance(DatadogLogsToolset), @@ -129,8 +129,8 @@ def load_python_toolsets( multi_instance(ServiceNowTablesToolset), multi_instance(VictoriaLogsToolset), DatabaseToolset(), - ElasticsearchDataToolset(), - ElasticsearchClusterToolset(), + multi_instance(ElasticsearchDataToolset), + multi_instance(ElasticsearchClusterToolset), ] if not DISABLE_PROMETHEUS_TOOLSET: diff --git a/holmes/plugins/toolsets/elasticsearch/elasticsearch.py b/holmes/plugins/toolsets/elasticsearch/elasticsearch.py index 3d73c19b46..368c60876d 100644 --- a/holmes/plugins/toolsets/elasticsearch/elasticsearch.py +++ b/holmes/plugins/toolsets/elasticsearch/elasticsearch.py @@ -1,11 +1,9 @@ import json -import logging from abc import ABC -from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type +from typing import Any, ClassVar, Dict, Optional, Tuple, Type import requests # type: ignore[import-untyped] -from pydantic import ConfigDict, Field, ValidationError, model_validator -from requests.auth import HTTPBasicAuth +from pydantic import ConfigDict, Field, model_validator from holmes.core.tools import ( CallablePrerequisite, @@ -21,98 +19,28 @@ from holmes.plugins.toolsets.utils import toolset_name_for_one_liner from holmes.utils.pydantic_utils import ToolsetConfig -logger = logging.getLogger(__name__) - -ELASTICSEARCH_INSTANCE_PARAM_DESCRIPTION = ( - "Name of the Elasticsearch instance to query. Required when more than one " - "instance is configured. Leave empty when only a single instance is configured." -) -ELASTICSEARCH_INSTANCE_PARAM = ToolParameter( - description=ELASTICSEARCH_INSTANCE_PARAM_DESCRIPTION, - type="string", - required=False, -) - - -class ElasticsearchInstance(ToolsetConfig): - """Connection details for a single Elasticsearch/OpenSearch target. - - Used when configuring multiple clusters via `ElasticsearchConfig.instances`. - Auth and SSL/timeout fields default to `None` so the multi-instance - config can detect whether the user explicitly set them on this instance - vs inheriting the top-level global default. - """ - - _deprecated_mappings: ClassVar[Dict[str, Optional[str]]] = { - "url": "api_url", - } - - name: str = Field( - title="Name", - description="Stable identifier the LLM uses to select this instance", - examples=["prod-eu", "staging-us"], - ) - api_url: str = Field( - title="API URL", - description="Elasticsearch/OpenSearch base URL for this instance", - ) - api_key: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - username: Optional[str] = None - password: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - client_cert: Optional[str] = None - client_key: Optional[str] = None - # `None` means "inherit from the top-level global". - verify_ssl: Optional[bool] = None - timeout_seconds: Optional[int] = Field(default=None, gt=0) - - @model_validator(mode="after") - def validate_auth_and_mtls(self) -> "ElasticsearchInstance": - if self.api_key and (self.username or self.password): - raise ValueError( - f"Elasticsearch instance '{self.name}': use `api_key` OR `username` + `password`, not both" - ) - if bool(self.username) != bool(self.password): - raise ValueError( - f"Elasticsearch instance '{self.name}': `username` and `password` must be set together" - ) - if self.client_cert and not self.client_key: - raise ValueError( - f"Elasticsearch instance '{self.name}': `client_key` is required when `client_cert` is set" - ) - if self.client_key and not self.client_cert: - raise ValueError( - f"Elasticsearch instance '{self.name}': `client_cert` is required when `client_key` is set" - ) - return self - - -def build_auth(instance: ElasticsearchInstance) -> Optional[HTTPBasicAuth]: - if instance.username and instance.password: - return HTTPBasicAuth(instance.username, instance.password) - return None - class ElasticsearchConfig(ToolsetConfig): """Configuration for Elasticsearch/OpenSearch API access. - Single-instance (legacy) configuration: + Example configuration: ```yaml api_url: "https://your-cluster.es.cloud.io" api_key: "base64_encoded_api_key" ``` - Multi-instance configuration: + Or with basic auth: + ```yaml + api_url: "https://your-cluster.es.cloud.io" + username: "elastic" + password: "your_password" + ``` + + Or with mTLS (mutual TLS / client certificate): ```yaml - # Top-level fields act as global defaults inherited by any instance - # that doesn't override them. - username: elastic - password: "{{ env.ES_GLOBAL_PASSWORD }}" - instances: - - name: prod-eu - api_url: https://prod-eu.es.internal:9200 - - name: prod-us - api_url: https://prod-us.es.internal:9200 - password: "{{ env.ES_US_PASSWORD }}" # per-instance override + api_url: "https://your-cluster:9200" + client_cert: "/path/to/client.crt" + client_key: "/path/to/client.key" ``` """ @@ -122,10 +50,9 @@ class ElasticsearchConfig(ToolsetConfig): "ca_cert": None, } - api_url: Optional[str] = Field( - default=None, + api_url: str = Field( title="API URL", - description="Elasticsearch/OpenSearch base URL (single-instance shape). Omit when using `instances`.", + description="Elasticsearch/OpenSearch base URL", examples=["https://your-cluster.es.cloud.io"], ) api_key: Optional[str] = Field( @@ -166,111 +93,13 @@ class ElasticsearchConfig(ToolsetConfig): title="Timeout Seconds", description="Default request timeout in seconds", ) - instances: Optional[List[ElasticsearchInstance]] = Field( - default=None, - title="Instances", - description=( - "List of Elasticsearch instances for multi-cluster routing. " - "When set, top-level connection fields act as global defaults inherited " - "by any instance that doesn't override them." - ), - ) - - @model_validator(mode="before") - @classmethod - def _coerce_instances(cls, data: Any) -> Any: - if not isinstance(data, dict): - return data - raw = data.get("instances") - if not raw: - return data - coerced: List[ElasticsearchInstance] = [] - for idx, item in enumerate(raw): - if isinstance(item, ElasticsearchInstance): - coerced.append(item) - continue - if not isinstance(item, dict): - raise ValueError( - f"`instances[{idx}]` must be a dict, got {type(item).__name__}" - ) - try: - coerced.append(ElasticsearchInstance(**item)) - except ValidationError as e: - raise ValueError( - f"Elasticsearch instance '{item.get('name', idx)}' is invalid: {e}" - ) from e - data["instances"] = coerced - return data @model_validator(mode="after") - def _normalize_and_resolve_globals(self) -> "ElasticsearchConfig": - # Top-level auth must follow the same XOR rule as per-instance auth so - # mixed credentials are rejected up front rather than silently letting - # api_key win over username/password in the fall-through below. - if self.api_key and (self.username or self.password): - raise ValueError( - "Elasticsearch config: use top-level `api_key` OR `username` + `password`, not both" - ) - if bool(self.username) != bool(self.password): - raise ValueError( - "Elasticsearch config: top-level `username` and `password` must be set together" - ) + def validate_mtls_fields(self) -> "ElasticsearchConfig": if self.client_cert and not self.client_key: raise ValueError("client_key is required when client_cert is set") if self.client_key and not self.client_cert: raise ValueError("client_cert is required when client_key is set") - - if not self.instances: - if not self.api_url: - raise ValueError( - "Either `instances` or top-level `api_url` is required for the Elasticsearch toolset" - ) - # Backwards compat: synthesize a single "default" instance so the - # rest of the toolset only has to deal with the multi-instance code - # path. - self.instances = [ - ElasticsearchInstance( - name="default", - api_url=self.api_url, - api_key=self.api_key, - username=self.username, - password=self.password, - client_cert=self.client_cert, - client_key=self.client_key, - verify_ssl=self.verify_ssl, - timeout_seconds=self.timeout_seconds, - ) - ] - return self - - if self.api_url: - logger.warning( - "ElasticsearchConfig: top-level `api_url` is ignored when `instances` is set. " - "Move connection fields into an entry under `instances`." - ) - - seen: set[str] = set() - for inst in self.instances: - if inst.name in seen: - raise ValueError(f"Duplicate Elasticsearch instance name: '{inst.name}'") - seen.add(inst.name) - if inst.verify_ssl is None: - inst.verify_ssl = self.verify_ssl - if inst.timeout_seconds is None: - inst.timeout_seconds = self.timeout_seconds - # mTLS fall-through: instances without their own client cert inherit - # the global cert/key pair. - if not inst.client_cert and self.client_cert and self.client_key: - inst.client_cert = self.client_cert - inst.client_key = self.client_key - # Auth fall-through: instances without their own auth inherit the - # global credentials. - if not (inst.api_key or inst.username or inst.password): - if self.api_key: - inst.api_key = self.api_key - elif self.username and self.password: - inst.username = self.username - inst.password = self.password return self @@ -292,181 +121,109 @@ def __init__(self, name: str, description: str, tools: list, **kwargs): tags=[ToolsetTag.CORE], **kwargs, ) - self._instances: Dict[str, ElasticsearchInstance] = {} def prerequisites_callable(self, config: Dict[str, Any]) -> Tuple[bool, str]: """Check if the Elasticsearch configuration is valid and the cluster is reachable.""" try: config_class = self.config_classes[0] if self.config_classes else ElasticsearchConfig self.config = config_class(**config) + return self._perform_health_check() except Exception as e: return False, f"Failed to validate Elasticsearch configuration: {str(e)}" - # `_normalize_and_resolve_globals` guarantees a non-empty `instances` - # list (synthesizing a single "default" for the legacy flat shape). - instances = self.elasticsearch_config.instances or [] - self._instances = {i.name: i for i in instances} - self._prune_tools_for_single_instance() - return self._perform_health_check() - - def _prune_tools_for_single_instance(self) -> None: - """Hide the multi-instance affordances when only one instance is configured. - - When there's a single instance, the `elasticsearch_instance` parameter - and the `elasticsearch_{data,cluster}_list_instances` discovery tool - add no value and cost tokens on every tool call. Drop them so the - LLM's tool surface matches the simpler config. - """ - if len(self._instances) != 1: - return - self.tools = [t for t in self.tools if not isinstance(t, ElasticsearchListInstances)] - for tool in self.tools: - tool.parameters.pop("elasticsearch_instance", None) - def _perform_health_check(self) -> Tuple[bool, str]: - """Probe `_cluster/health` on each configured instance. - - Tolerant: succeeds as long as at least one instance is reachable; the - toolset still loads with the healthy ones. Each failure is captured - with the instance name, status code, and response body so the LLM (and - any human reading the status string) can self-correct. - """ - failures: List[str] = [] - successes: List[str] = [] - for instance in self._instances.values(): - ok, msg = self._health_check_instance(instance) - if ok: - successes.append(msg) - else: - failures.append(msg) - return self._aggregate_health_results(failures, successes) - - def _health_check_instance( - self, instance: ElasticsearchInstance - ) -> Tuple[bool, str]: + """Perform a health check by querying cluster health.""" try: - data = self._make_request(instance, "GET", "_cluster/health", timeout=10) - cluster_name = data.get("cluster_name", "unknown") - status = data.get("status", "unknown") + response = self._make_request("GET", "_cluster/health", timeout=10) + cluster_name = response.get("cluster_name", "unknown") + status = response.get("status", "unknown") return ( True, - f"[{instance.name}] Connected to '{cluster_name}' (status: {status})", + f"Connected to Elasticsearch cluster '{cluster_name}' (status: {status})", ) except requests.exceptions.HTTPError as e: - status_code = e.response.status_code - body = e.response.text[:500] if e.response is not None else "" - if status_code == 401: + if e.response.status_code == 401: return ( False, - f"[{instance.name}] Authentication failed for {instance.api_url}. " - "Check api_key or username/password.", + "Elasticsearch authentication failed. Check your API key or credentials.", ) - if status_code == 403: + elif e.response.status_code == 403: return ( False, - f"[{instance.name}] Access denied at {instance.api_url}. " - "Credentials lack cluster access.", + "Elasticsearch access denied. Ensure your credentials have cluster access.", + ) + else: + return ( + False, + f"Elasticsearch API error: {e.response.status_code} - {e.response.text}", ) - return ( - False, - f"[{instance.name}] HTTP {status_code} from {instance.api_url}: {body}", - ) except requests.exceptions.SSLError as e: error_msg = str(e) - if ( - "certificate required" in error_msg.lower() - or "sslcertverificationerror" in error_msg.lower() - ): + if "certificate required" in error_msg.lower() or "sslcertverificationerror" in error_msg.lower(): return ( False, - f"[{instance.name}] SSL/TLS error at {instance.api_url}: {error_msg}. " + f"Elasticsearch SSL/TLS error: {error_msg}. " "If the server requires mTLS, configure client_cert and client_key. " "If using a private CA, set the CERTIFICATE env var (base64-encoded CA cert).", ) - return False, f"[{instance.name}] SSL error at {instance.api_url}: {error_msg}" - except requests.exceptions.ConnectionError as e: + return False, f"Elasticsearch SSL error: {error_msg}" + except requests.exceptions.ConnectionError: return ( False, - f"[{instance.name}] Failed to connect to {instance.api_url}: {e}", + f"Failed to connect to Elasticsearch at {self.elasticsearch_config.api_url}", ) except requests.exceptions.Timeout: - return False, f"[{instance.name}] Health check timed out for {instance.api_url}" + return False, "Elasticsearch health check timed out" except Exception as e: - return False, f"[{instance.name}] Health check failed: {str(e)}" - - def _aggregate_health_results( - self, failures: List[str], successes: List[str] - ) -> Tuple[bool, str]: - """Tolerant aggregation: succeed if any instance is reachable. - - Returns `(True, summary)` when at least one instance is healthy; the - summary lists healthy connections and notes any failures so they're - visible in the toolset status. Returns `(False, joined_errors)` only - when every instance failed. - """ - total = len(failures) + len(successes) - if not successes: - return False, "\n".join(failures) or "No Elasticsearch instances configured" - if failures: - logger.warning( - f"{self.name}: {len(successes)}/{total} instance(s) healthy. " - f"Failed: {failures}" - ) - return True, ( - "; ".join(successes) - + "; failed: " - + " | ".join(failures) - ) - return True, "; ".join(successes) - - def _get_instance(self, params: Dict[str, Any]) -> ElasticsearchInstance: - """Resolve which Elasticsearch instance a tool call should target. - - Auto-selects when only one is configured. Otherwise requires - `elasticsearch_instance` in params. Raises `ValueError` with a helpful - message listing the configured names when missing or unknown. - """ - configured = sorted(self._instances) - requested = params.get("elasticsearch_instance") - if not requested: - if len(self._instances) == 1: - return next(iter(self._instances.values())) - raise ValueError( - f"`elasticsearch_instance` is required (configured: {configured})" - ) - if requested not in self._instances: - raise ValueError( - f"Unknown elasticsearch_instance '{requested}'. Configured: {configured}" - ) - return self._instances[requested] + return False, f"Elasticsearch health check failed: {str(e)}" @property def elasticsearch_config(self) -> ElasticsearchConfig: return self.config # type: ignore - def _build_headers(self, instance: ElasticsearchInstance) -> Dict[str, str]: - """Build request headers with authentication for the given instance.""" + def _get_headers(self) -> Dict[str, str]: + """Build request headers with authentication.""" headers = { "Accept": "application/json", "Content-Type": "application/json", } - if instance.api_key: - headers["Authorization"] = f"ApiKey {instance.api_key}" + if self.elasticsearch_config.api_key: + headers["Authorization"] = f"ApiKey {self.elasticsearch_config.api_key}" return headers + def _get_auth(self) -> Optional[Tuple[str, str]]: + """Return basic auth tuple if username/password configured.""" + if self.elasticsearch_config.username and self.elasticsearch_config.password: + return ( + self.elasticsearch_config.username, + self.elasticsearch_config.password, + ) + return None + + def _get_client_cert(self) -> Optional[Tuple[str, str]]: + """Return client certificate tuple for mTLS if configured.""" + if self.elasticsearch_config.client_cert and self.elasticsearch_config.client_key: + return ( + self.elasticsearch_config.client_cert, + self.elasticsearch_config.client_key, + ) + return None + + def _get_verify(self) -> bool: + """Return SSL verification setting.""" + return self.elasticsearch_config.verify_ssl + def _make_request( self, - instance: ElasticsearchInstance, method: str, endpoint: str, params: Optional[Dict[str, Any]] = None, body: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, ) -> Dict[str, Any]: - """Make HTTP request to a specific Elasticsearch instance. + """Make HTTP request to Elasticsearch. Args: - instance: The target Elasticsearch instance (resolved via `_get_instance`). method: HTTP method (GET, POST, etc.) endpoint: API endpoint (e.g., "_cluster/health") params: Query parameters @@ -481,35 +238,24 @@ def _make_request( requests.exceptions.ConnectionError: For connection problems requests.exceptions.Timeout: For timeout errors """ - url = f"{instance.api_url.rstrip('/')}/{endpoint.lstrip('/')}" - effective_timeout = timeout or instance.timeout_seconds or 10 - cert: Optional[Tuple[str, str]] = ( - (instance.client_cert, instance.client_key) - if instance.client_cert and instance.client_key - else None - ) + url = f"{self.elasticsearch_config.api_url.rstrip('/')}/{endpoint.lstrip('/')}" + timeout = timeout or self.elasticsearch_config.timeout_seconds response = requests.request( method=method, url=url, - headers=self._build_headers(instance), - auth=build_auth(instance), - cert=cert, + headers=self._get_headers(), + auth=self._get_auth(), + cert=self._get_client_cert(), params=params, json=body, - timeout=effective_timeout, - verify=bool(instance.verify_ssl), + timeout=timeout, + verify=self._get_verify(), ) response.raise_for_status() return response.json() -def _instance_error_result(params: dict, err: Exception) -> StructuredToolResult: - return StructuredToolResult( - status=StructuredToolResultStatus.ERROR, error=str(err), params=params - ) - - class BaseElasticsearchTool(Tool, ABC): """Base class for Elasticsearch tools.""" @@ -525,7 +271,6 @@ def toolset(self) -> ElasticsearchBaseToolset: def _make_request( self, - instance: ElasticsearchInstance, method: str, endpoint: str, params: dict, @@ -533,10 +278,9 @@ def _make_request( body: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, ) -> StructuredToolResult: - """Make a request to a specific Elasticsearch instance and return a structured result.""" + """Make a request to Elasticsearch and return structured result.""" try: data = self._toolset._make_request( - instance, method=method, endpoint=endpoint, params=query_params, @@ -559,31 +303,25 @@ def _make_request( return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Elasticsearch request failed for endpoint " - f"'{endpoint}': {error_detail}" - ), + error=f"Elasticsearch request failed for endpoint '{endpoint}': {error_detail}", params=params, ) except requests.exceptions.Timeout: return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Elasticsearch request timed out for endpoint " - f"'{endpoint}'" - ), + error=f"Elasticsearch request timed out for endpoint '{endpoint}'", params=params, ) except requests.exceptions.ConnectionError as e: return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=f"[{instance.name}] Failed to connect to Elasticsearch: {str(e)}", + error=f"Failed to connect to Elasticsearch: {str(e)}", params=params, ) except Exception as e: return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=f"[{instance.name}] Unexpected error querying Elasticsearch: {str(e)}", + error=f"Unexpected error querying Elasticsearch: {str(e)}", params=params, ) @@ -601,7 +339,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "IMPORTANT: Always use the 'index' parameter when querying shards to filter by specific index." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "endpoint": ToolParameter( description=( "The _cat endpoint to query. Valid values: " @@ -642,11 +379,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - endpoint = params["endpoint"] index = params.get("index") @@ -674,7 +406,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("health") and endpoint == "indices": query_params["health"] = params["health"] - return self._make_request(instance, "GET", path, params, query_params=query_params) + return self._make_request("GET", path, params, query_params=query_params) def get_parameterized_one_liner(self, params: Dict) -> str: endpoint = params.get("endpoint", "") @@ -698,7 +430,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "Returns up to 100 documents by default (configurable via size parameter)." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "index": ToolParameter( description=( "Index name or pattern to search. Supports wildcards (e.g., 'logs-*'). " @@ -772,11 +503,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - index = params["index"] path = f"{index}/_search" @@ -803,7 +529,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("profile"): body["profile"] = True - return self._make_request(instance, "POST", path, params, body=body) + return self._make_request("POST", path, params, body=body) def get_parameterized_one_liner(self, params: Dict) -> str: index = params.get("index", "") @@ -822,7 +548,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "node count, shard counts, and pending tasks." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "index": ToolParameter( description="Optional: Get health for specific index or pattern", type="string", @@ -840,11 +565,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - index = params.get("index") path = f"_cluster/health/{index}" if index else "_cluster/health" @@ -852,7 +572,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("level"): query_params["level"] = params["level"] - return self._make_request(instance, "GET", path, params, query_params=query_params) + return self._make_request("GET", path, params, query_params=query_params) def get_parameterized_one_liner(self, params: Dict) -> str: index = params.get("index", "") @@ -878,7 +598,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ), parameters=JsonFilterMixin.extend_parameters( { - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "index": ToolParameter( description="Index name or pattern to get mappings for", type="string", @@ -889,14 +608,9 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - index = params["index"] path = f"{index}/_mapping" - result = self._make_request(instance, "GET", path, params) + result = self._make_request("GET", path, params) return self.filter_result(result, params) def get_parameterized_one_liner(self, params: Dict) -> str: @@ -916,7 +630,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "store size, indexing rate, and search rate." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "index": ToolParameter( description="Index name or pattern. Use '_all' for all indices.", type="string", @@ -935,11 +648,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - index = params["index"] metrics = params.get("metrics") @@ -948,7 +656,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes else: path = f"{index}/_stats" - return self._make_request(instance, "GET", path, params) + return self._make_request("GET", path, params) def get_parameterized_one_liner(self, params: Dict) -> str: index = params.get("index", "") @@ -968,7 +676,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "or specify index/shard to explain a specific shard." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "index": ToolParameter( description="Index name for specific shard explanation", type="string", @@ -988,11 +695,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - body: Optional[Dict[str, Any]] = None if params.get("index") is not None and params.get("shard") is not None: @@ -1003,7 +705,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes } return self._make_request( - instance, "GET", "_cluster/allocation/explain", params, body=body + "GET", "_cluster/allocation/explain", params, body=body ) def get_parameterized_one_liner(self, params: Dict) -> str: @@ -1026,7 +728,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): "thread pool, filesystem, transport, and HTTP metrics." ), parameters={ - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "node_id": ToolParameter( description="Specific node ID or name. Use '_local' for current node, '_all' for all nodes.", type="string", @@ -1044,11 +745,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - node_id = params.get("node_id", "_all") metrics = params.get("metrics") @@ -1057,7 +753,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes else: path = f"_nodes/{node_id}/stats" - return self._make_request(instance, "GET", path, params) + return self._make_request("GET", path, params) def get_parameterized_one_liner(self, params: Dict) -> str: node_id = params.get("node_id", "_all") @@ -1080,7 +776,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ), parameters=JsonFilterMixin.extend_parameters( { - "elasticsearch_instance": ELASTICSEARCH_INSTANCE_PARAM, "pattern": ToolParameter( description=( "Index name pattern to match. Supports wildcards (e.g., 'logs-*', 'app-*'). " @@ -1132,11 +827,6 @@ def __init__(self, toolset: ElasticsearchBaseToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - pattern = params.get("pattern", "*") path = f"_cat/indices/{pattern}" @@ -1166,7 +856,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("expand_wildcards"): query_params["expand_wildcards"] = params["expand_wildcards"] - result = self._make_request(instance, "GET", path, params, query_params=query_params) + result = self._make_request("GET", path, params, query_params=query_params) return self.filter_result(result, params) def get_parameterized_one_liner(self, params: Dict) -> str: @@ -1174,44 +864,6 @@ def get_parameterized_one_liner(self, params: Dict) -> str: return f"{toolset_name_for_one_liner(self._toolset.name)}: List indices ({pattern})" -class ElasticsearchListInstances(Tool): - """List configured Elasticsearch instances for the LLM to discover routing targets.""" - - model_config = ConfigDict(arbitrary_types_allowed=True) - - def __init__(self, toolset: ElasticsearchBaseToolset): - # Scope the tool name to the toolset (`elasticsearch/data` → - # `elasticsearch_data_list_instances`) so the data and cluster - # toolsets register distinct discovery tools instead of colliding - # on a single shared name when both are multi-instance. - toolset_suffix = toolset.name.split("/")[-1] - super().__init__( - name=f"elasticsearch_{toolset_suffix}_list_instances", - description=( - f"List the Elasticsearch instances configured for the " - f"`{toolset.name}` toolset. Returns each instance's name and " - f"api_url so subsequent tool calls can target the right one via " - f"the `elasticsearch_instance` parameter." - ), - parameters={}, - ) - self._toolset = toolset - - def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - instances = [ - {"name": inst.name, "api_url": inst.api_url} - for inst in self._toolset._instances.values() - ] - return StructuredToolResult( - status=StructuredToolResultStatus.SUCCESS, - data={"instances": instances}, - params=params, - ) - - def get_parameterized_one_liner(self, params: Dict) -> str: - return f"{toolset_name_for_one_liner(self._toolset.name)}: List instances" - - # ============================================================================= # Toolset Definitions (must be after all tool classes) # ============================================================================= @@ -1232,7 +884,6 @@ def __init__(self): ) # Initialize tools after super().__init__() - update the pydantic field self.tools = [ - ElasticsearchListInstances(self), ElasticsearchSearch(self), ElasticsearchMappings(self), ElasticsearchListIndices(self), @@ -1254,7 +905,6 @@ def __init__(self): ) # Initialize tools after super().__init__() - update the pydantic field self.tools = [ - ElasticsearchListInstances(self), ElasticsearchCat(self), ElasticsearchClusterHealth(self), ElasticsearchIndexStats(self), diff --git a/holmes/plugins/toolsets/grafana/base_grafana_toolset.py b/holmes/plugins/toolsets/grafana/base_grafana_toolset.py index 6fc137ab5e..9c9b38c4fd 100644 --- a/holmes/plugins/toolsets/grafana/base_grafana_toolset.py +++ b/holmes/plugins/toolsets/grafana/base_grafana_toolset.py @@ -1,21 +1,12 @@ import logging from abc import abstractmethod -from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type +from typing import Any, ClassVar, Optional, Tuple, Type from pydantic import ValidationError from holmes.core.tools import CallablePrerequisite, Tool, Toolset, ToolsetTag from holmes.plugins.toolsets.consts import TOOLSET_CONFIG_MISSING_ERROR -from holmes.plugins.toolsets.grafana.common import ( - GrafanaConfig, - GrafanaInstance, - MultiInstanceGrafanaConfig, -) - -GRAFANA_INSTANCE_PARAM_DESCRIPTION = ( - "Name of the Grafana instance to query. Required when more than one instance " - "is configured. Leave empty when only a single instance is configured." -) +from holmes.plugins.toolsets.grafana.common import GrafanaConfig class BaseGrafanaToolset(Toolset): @@ -92,104 +83,3 @@ def health_check(self) -> Tuple[bool, str]: Tuple[bool, str]: (True, "") on success, (False, "error message") on failure. """ raise NotImplementedError("Subclasses must implement health_check()") - - -class BaseMultiInstanceGrafanaToolset(BaseGrafanaToolset): - """Base for Grafana toolsets that route across multiple configured instances. - - Subclasses (currently only dashboards) get an `_instances` dict keyed by - name, a `_get_instance(params)` resolver that auto-selects when only one - instance is configured, and `_aggregate_health_results` for tolerant - health checks (succeed if any instance is reachable). - """ - - config_classes: ClassVar[list[Type[GrafanaConfig]]] = [MultiInstanceGrafanaConfig] - - def __init__( - self, - name: str, - description: str, - icon_url: str, - tools: list[Tool], - docs_url: str, - ): - super().__init__( - name=name, - description=description, - icon_url=icon_url, - tools=tools, - docs_url=docs_url, - ) - self._instances: Dict[str, GrafanaInstance] = {} - - def prerequisites_callable(self, config: dict[str, Any]) -> Tuple[bool, str]: - if not config: - logging.debug(f"Grafana config not provided {self.name}") - return False, TOOLSET_CONFIG_MISSING_ERROR - - config_classes = list(self.config_classes or [MultiInstanceGrafanaConfig]) - last_error: Optional[Exception] = None - for config_class in config_classes: - try: - self._grafana_config = config_class(**config) - break - except ValidationError as e: - last_error = e - logging.debug( - f"Config {config_class.__name__} did not validate for {self.name}: {e}" - ) - continue - except Exception as e: - logging.exception(f"Failed to set up grafana toolset {self.name}") - return False, f"Failed to set up {self.name}: {e}" - else: - if last_error: - return False, f"Invalid {self.name} configuration: {last_error}" - return ( - False, - "No config variant matched the provided fields — check the docs for required fields per variant.", - ) - - # MultiInstanceGrafanaConfig guarantees a non-empty `instances` list. - instances = getattr(self._grafana_config, "instances", None) or [] - self._instances = {i.name: i for i in instances} - return self.health_check() - - def _aggregate_health_results( - self, failures: List[str], total: int - ) -> Tuple[bool, str]: - """Tolerant aggregation: succeed if any instance is reachable. - - `failures` is a list of `"[instance.name] error"` strings collected by the - subclass's `health_check`. Returns `(True, "")` when at least one instance - is healthy; `(False, joined_errors)` only when every instance failed. - """ - if len(failures) == total: - return False, "\n".join(failures) - if failures: - logging.warning( - f"{self.name}: {total - len(failures)} healthy instance(s), " - f"{len(failures)} failed: {failures}" - ) - return True, "" - - def _get_instance(self, params: Dict[str, Any]) -> GrafanaInstance: - """Resolve which Grafana instance a tool call should target. - - Auto-selects when only one is configured. Otherwise requires - `grafana_instance` in params. Raises `ValueError` with a helpful message - when missing or unknown. - """ - configured = sorted(self._instances) - requested = params.get("grafana_instance") - if not requested: - if len(self._instances) == 1: - return next(iter(self._instances.values())) - raise ValueError( - f"`grafana_instance` is required (configured: {configured})" - ) - if requested not in self._instances: - raise ValueError( - f"Unknown grafana_instance '{requested}'. Configured: {configured}" - ) - return self._instances[requested] diff --git a/holmes/plugins/toolsets/grafana/common.py b/holmes/plugins/toolsets/grafana/common.py index 7daaad5070..97d96e80f7 100644 --- a/holmes/plugins/toolsets/grafana/common.py +++ b/holmes/plugins/toolsets/grafana/common.py @@ -1,13 +1,9 @@ -import logging -from typing import Any, ClassVar, Dict, List, Optional, Type, Union +from typing import ClassVar, Dict, List, Optional -from pydantic import Field, ValidationError, model_validator -from requests.auth import HTTPBasicAuth +from pydantic import Field from holmes.utils.pydantic_utils import ToolsetConfig -logger = logging.getLogger(__name__) - GRAFANA_ICON_URL = "https://raw.githubusercontent.com/gilbarbara/logos/de2c1f96ff6e74ea7ea979b43202e8d4b863c655/logos/grafana.svg" LOKI_ICON_URL = "https://raw.githubusercontent.com/gilbarbara/logos/de2c1f96ff6e74ea7ea979b43202e8d4b863c655/logos/grafana.svg" TEMPO_ICON_URL = "https://raw.githubusercontent.com/gilbarbara/logos/de2c1f96ff6e74ea7ea979b43202e8d4b863c655/logos/grafana.svg" @@ -87,11 +83,11 @@ def build_headers(api_key: Optional[str], additional_headers: Optional[Dict[str, return headers -def get_base_url(target: Union["GrafanaConfig", "GrafanaInstance"]) -> str: - if target.grafana_datasource_uid: - return f"{target.api_url}/api/datasources/proxy/uid/{target.grafana_datasource_uid}" +def get_base_url(config: GrafanaConfig) -> str: + if config.grafana_datasource_uid: + return f"{config.api_url}/api/datasources/proxy/uid/{config.grafana_datasource_uid}" else: - return target.api_url + return config.api_url class GrafanaLokiProxyConfig(GrafanaConfig): @@ -304,171 +300,3 @@ class GrafanaCloudTempoConfig(GrafanaTempoConfig): description="UID of the Tempo datasource configured in your Grafana Cloud Grafana", examples=["grafanacloud-traces"], ) - - -# --- Multi-instance support (dashboards-only) --- - - -class GrafanaInstance(ToolsetConfig): - """Connection details for a single Grafana target in a multi-instance setup.""" - - _deprecated_mappings: ClassVar[Dict[str, Optional[str]]] = { - "url": "api_url", - "headers": "additional_headers", - } - - name: str = Field( - title="Name", - description="Stable identifier the LLM uses to select this instance", - examples=["prod-eu"], - ) - api_url: str = Field(title="URL") - api_key: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - username: Optional[str] = None - password: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - additional_headers: Optional[Dict[str, str]] = None - grafana_datasource_uid: Optional[str] = None - external_url: Optional[str] = None - # `None` on the per-instance level means "inherit from the top-level global". - verify_ssl: Optional[bool] = None - timeout_seconds: Optional[int] = Field(default=None, gt=0) - max_retries: Optional[int] = Field(default=None, ge=1) - - @model_validator(mode="after") - def validate_auth(self) -> "GrafanaInstance": - if self.api_key and (self.username or self.password): - raise ValueError( - f"Grafana instance '{self.name}': use `api_key` OR `username` + `password`, not both" - ) - if bool(self.username) != bool(self.password): - raise ValueError( - f"Grafana instance '{self.name}': `username` and `password` must be set together" - ) - return self - - -def build_auth(instance: GrafanaInstance) -> Optional[HTTPBasicAuth]: - if instance.username and instance.password: - return HTTPBasicAuth(instance.username, instance.password) - return None - - -class MultiInstanceGrafanaConfig(GrafanaConfig): - """Grafana config that accepts an `instances` list for multi-target routing. - - If `instances` is set, each entry is a `GrafanaInstance` and the top-level - connection fields act as global defaults inherited by any instance that - doesn't override them. - - If `instances` is unset, the top-level fields synthesize a single instance - named `"default"` (the legacy single-instance shape). - """ - - # Per-toolset subclasses can register `GrafanaInstance` variants their - # entries can match. The matcher tries each in order and picks the first - # one that validates. - instance_classes: ClassVar[List[Type[GrafanaInstance]]] = [GrafanaInstance] - - api_url: Optional[str] = None # type: ignore[assignment] - api_key: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - username: Optional[str] = None - password: Optional[str] = Field(default=None, json_schema_extra={"format": "password"}) - - instances: Optional[List[GrafanaInstance]] = None - - @model_validator(mode="before") - @classmethod - def _coerce_instances_against_variants(cls, data: Any) -> Any: - if not isinstance(data, dict): - return data - raw = data.get("instances") - if not raw: - return data - variants = cls.instance_classes or [GrafanaInstance] - coerced: List[GrafanaInstance] = [] - for idx, item in enumerate(raw): - if isinstance(item, GrafanaInstance): - coerced.append(item) - continue - if not isinstance(item, dict): - raise ValueError( - f"`instances[{idx}]` must be a dict, got {type(item).__name__}" - ) - last_err: Optional[Exception] = None - for variant in variants: - try: - coerced.append(variant(**item)) - break - except ValidationError as e: - last_err = e - continue - else: - raise ValueError( - f"Grafana instance '{item.get('name', idx)}' did not match any variant " - f"({[v.__name__ for v in variants]}). Last error: {last_err}" - ) - data["instances"] = coerced - return data - - @model_validator(mode="after") - def _normalize_and_resolve_globals(self) -> "MultiInstanceGrafanaConfig": - # Top-level auth must follow the same XOR rule as per-instance auth so - # mixed credentials are rejected up front rather than silently letting - # `api_key` win over `username`/`password` in the fall-through below. - if self.api_key and (self.username or self.password): - raise ValueError( - "Grafana config: use top-level `api_key` OR `username` + `password`, not both" - ) - if bool(self.username) != bool(self.password): - raise ValueError( - "Grafana config: top-level `username` and `password` must be set together" - ) - - if not self.instances: - if not self.api_url: - raise ValueError( - "Either `instances` or top-level `api_url` is required for the Grafana toolset" - ) - instance_cls = (self.instance_classes or [GrafanaInstance])[0] - self.instances = [ - instance_cls( - name="default", - api_url=self.api_url, - api_key=self.api_key, - username=self.username, - password=self.password, - ) - ] - elif self.api_url: - logger.warning( - "MultiInstanceGrafanaConfig: top-level `api_url` is ignored when `instances` is set. " - "Move connection fields into an entry under `instances`." - ) - - seen: set[str] = set() - for inst in self.instances: - if inst.name in seen: - raise ValueError(f"Duplicate Grafana instance name: '{inst.name}'") - seen.add(inst.name) - if inst.verify_ssl is None: - inst.verify_ssl = self.verify_ssl - if inst.timeout_seconds is None: - inst.timeout_seconds = self.timeout_seconds - if inst.max_retries is None: - inst.max_retries = self.max_retries - if inst.additional_headers is None and self.additional_headers is not None: - inst.additional_headers = self.additional_headers - if inst.grafana_datasource_uid is None and self.grafana_datasource_uid: - inst.grafana_datasource_uid = self.grafana_datasource_uid - if inst.external_url is None and self.external_url: - inst.external_url = self.external_url - # Auth-only fall-through: instances without their own auth inherit - # the global credentials. - if not (inst.api_key or inst.username or inst.password): - if self.api_key: - inst.api_key = self.api_key - elif self.username and self.password: - inst.username = self.username - inst.password = self.password - inst.validate_auth() - return self diff --git a/holmes/plugins/toolsets/grafana/toolset_grafana.py b/holmes/plugins/toolsets/grafana/toolset_grafana.py index 29c570b493..2495bf4b01 100644 --- a/holmes/plugins/toolsets/grafana/toolset_grafana.py +++ b/holmes/plugins/toolsets/grafana/toolset_grafana.py @@ -2,7 +2,7 @@ import logging import os from abc import ABC -from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, cast +from typing import Any, ClassVar, Dict, Optional, Tuple, Type, cast from urllib.parse import urlencode, urljoin import backoff @@ -16,15 +16,9 @@ ToolInvokeContext, ToolParameter, ) -from holmes.plugins.toolsets.grafana.base_grafana_toolset import ( - GRAFANA_INSTANCE_PARAM_DESCRIPTION, - BaseGrafanaToolset, # noqa: F401 — re-exported for legacy loki import path - BaseMultiInstanceGrafanaToolset, -) +from holmes.plugins.toolsets.grafana.base_grafana_toolset import BaseGrafanaToolset from holmes.plugins.toolsets.grafana.common import ( - GrafanaInstance, - MultiInstanceGrafanaConfig, - build_auth, + GrafanaConfig, build_headers, get_base_url, ) @@ -34,14 +28,7 @@ logger = logging.getLogger(__name__) -GRAFANA_INSTANCE_PARAM = ToolParameter( - type="string", - description=GRAFANA_INSTANCE_PARAM_DESCRIPTION, - required=False, -) - - -class GrafanaDashboardConfig(MultiInstanceGrafanaConfig): +class GrafanaDashboardConfig(GrafanaConfig): """Configuration specific to Grafana Dashboard toolset.""" timeout_seconds: int = Field( @@ -70,12 +57,12 @@ class GrafanaDashboardConfig(MultiInstanceGrafanaConfig): def _build_grafana_dashboard_url( - instance: GrafanaInstance, + config: GrafanaDashboardConfig, uid: Optional[str] = None, query_params: Optional[Dict[str, Any]] = None, ) -> Optional[str]: try: - base_url = instance.external_url or instance.api_url + base_url = config.external_url or config.api_url if uid: return f"{base_url.rstrip('/')}/d/{uid}" else: @@ -88,20 +75,7 @@ def _build_grafana_dashboard_url( return None -def _attach_grafana_url(data: Any, url: Optional[str]) -> Any: - """Wrap tool result data so the Grafana UI URL is visible to the LLM. - - The LLM only sees `StructuredToolResult.data`, not `.url` — so the link must - live inside the data payload for the LLM to cite it back in responses. - """ - if not url: - return data - if isinstance(data, dict): - return {"grafana_url": url, **data} - return {"grafana_url": url, "results": data} - - -class GrafanaToolset(BaseMultiInstanceGrafanaToolset): +class GrafanaToolset(BaseGrafanaToolset): config_classes: ClassVar[list[Type[GrafanaDashboardConfig]]] = [ GrafanaDashboardConfig ] @@ -125,42 +99,43 @@ def __init__(self): ) def prerequisites_callable(self, config: dict[str, Any]) -> Tuple[bool, str]: + # Base class validates config and calls health_check() ok, msg = super().prerequisites_callable(config) if not ok: logger.info(f"Grafana health check failed: {msg}") return ok, msg - # Render-tool registration succeeds if any configured instance exposes - # the renderer. + # After health check passes, conditionally add render tools if self.grafana_config.enable_rendering: - for instance in self._instances.values(): - logger.info( - f"Rendering enabled, probing for image renderer at {get_base_url(instance)}..." - ) - self._try_add_render_tools(instance) - if any(isinstance(t, RenderPanel) for t in self.tools): - break + logger.info( + f"Rendering enabled, probing for image renderer at {get_base_url(self.grafana_config)}..." + ) + self._try_add_render_tools() tool_names = [t.name for t in self.tools] logger.info(f"Grafana toolset tools after renderer probe: {tool_names}") return ok, msg - def _try_add_render_tools(self, instance: GrafanaInstance) -> None: + def _try_add_render_tools(self) -> None: """Check if Grafana Image Renderer is available and add render tools.""" + # Skip re-probing if render tools are already registered if any(isinstance(t, RenderPanel) for t in self.tools): return - base_url = get_base_url(instance) - headers = build_headers(instance.api_key, instance.additional_headers) - auth = build_auth(instance) + config = self.grafana_config + base_url = get_base_url(config) + headers = build_headers( + api_key=config.api_key, + additional_headers=config.additional_headers, + ) renderer_detected = False try: + # Try the rendering version API first resp = requests.get( f"{base_url}/api/rendering/version", headers=headers, - auth=auth, timeout=10, - verify=bool(instance.verify_ssl), + verify=config.verify_ssl, ) if resp.status_code == 200: logger.info( @@ -175,15 +150,19 @@ def _try_add_render_tools(self, instance: GrafanaInstance) -> None: except Exception as e: logger.debug(f"Failed to check renderer version API: {e}") + # Fallback: try a small render request. Some Grafana versions don't expose the version API + # but still support rendering. if not renderer_detected: try: resp = requests.get( f"{base_url}/render/d-solo/nonexistent/_?panelId=1&width=100&height=100", headers=headers, - auth=auth, timeout=10, - verify=bool(instance.verify_ssl), + verify=config.verify_ssl, ) + # If renderer is configured, we get a 200 (rendered image) or + # 500 (dashboard not found but renderer is present). + # If not configured, we get 404 (route not found). if resp.status_code in (200, 500): logger.info( f"Grafana Image Renderer detected (render probe returned {resp.status_code}). " @@ -208,28 +187,19 @@ def _try_add_render_tools(self, instance: GrafanaInstance) -> None: self.tools.append(RenderDashboard(self)) def health_check(self) -> Tuple[bool, str]: - """Probe `/api/dashboards/tags` on each configured instance.""" + """Test connectivity by invoking GetDashboardTags tool.""" tool = GetDashboardTags(self) - failures: List[str] = [] - for instance in self._instances.values(): - result = tool._make_grafana_request(instance, "api/dashboards/tags", {}) - if result.status is not StructuredToolResultStatus.SUCCESS: - # `_make_grafana_request` already prefixes errors with the - # instance name and includes URL + status + response body. - failures.append(result.error or f"[{instance.name}] Unknown error") - return self._aggregate_health_results(failures, len(self._instances)) + try: + _ = tool._make_grafana_request("api/dashboards/tags", {}) + return True, "" + except Exception as e: + return False, f"Failed to connect to Grafana {str(e)}" @property def grafana_config(self) -> GrafanaDashboardConfig: return cast(GrafanaDashboardConfig, self._grafana_config) -def _instance_error_result(params: dict, err: Exception) -> StructuredToolResult: - return StructuredToolResult( - status=StructuredToolResultStatus.ERROR, error=str(err), params=params - ) - - class BaseGrafanaTool(Tool, ABC): """Base class for Grafana tools with common HTTP request functionality.""" @@ -239,20 +209,33 @@ def __init__(self, toolset: GrafanaToolset, *args, **kwargs): def _make_grafana_request( self, - instance: GrafanaInstance, endpoint: str, params: dict, query_params: Optional[Dict] = None, timeout: Optional[int] = None, ) -> StructuredToolResult: - effective_timeout = timeout if timeout is not None else instance.timeout_seconds - retries = instance.max_retries or 3 - base_url = get_base_url(instance) + """Make a GET request to Grafana API and return structured result. + + Args: + endpoint: API endpoint path (e.g., "/api/search") + params: Original parameters passed to the tool + query_params: Optional query parameters for the request + timeout: Request timeout in seconds (defaults to config.timeout_seconds) + + Returns: + StructuredToolResult with the API response data + """ + config = self._toolset.grafana_config + timeout = timeout if timeout is not None else config.timeout_seconds + retries = config.max_retries + base_url = get_base_url(config) if not base_url.endswith("/"): base_url += "/" url = urljoin(base_url, endpoint) - headers = build_headers(instance.api_key, instance.additional_headers) - auth = build_auth(instance) + headers = build_headers( + api_key=config.api_key, + additional_headers=config.additional_headers, + ) @backoff.on_exception( backoff.expo, @@ -266,51 +249,15 @@ def _do_request() -> requests.Response: response = requests.get( url, headers=headers, - auth=auth, params=query_params, - timeout=effective_timeout, - verify=bool(instance.verify_ssl), + timeout=timeout, + verify=config.verify_ssl, ) response.raise_for_status() return response - full_url = ( - f"{url}?{urlencode(query_params, doseq=True)}" if query_params else url - ) - try: - response = _do_request() - data = response.json() - except requests.HTTPError as e: - status_code = ( - e.response.status_code if e.response is not None else "unknown" - ) - response_text = e.response.text[:500] if e.response is not None else "" - return StructuredToolResult( - status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Grafana API returned HTTP {status_code}. " - f"GET {full_url}. Response: {response_text}" - ), - params=params, - url=full_url, - ) - except requests.Timeout: - return StructuredToolResult( - status=StructuredToolResultStatus.ERROR, - error=f"[{instance.name}] Grafana API timed out. GET {full_url}", - params=params, - url=full_url, - ) - except requests.ConnectionError as e: - return StructuredToolResult( - status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Failed to connect to Grafana. " - f"GET {full_url}. Error: {e}" - ), - params=params, - url=full_url, - ) + response = _do_request() + data = response.json() return StructuredToolResult( status=StructuredToolResultStatus.SUCCESS, @@ -327,7 +274,6 @@ def __init__(self, toolset: GrafanaToolset): name="grafana_search_dashboards", description="Search for Grafana dashboards and folders using the /api/search endpoint", parameters={ - "grafana_instance": GRAFANA_INSTANCE_PARAM, "query": ToolParameter( description="Search text to filter dashboards", type="string", @@ -377,11 +323,6 @@ def __init__(self, toolset: GrafanaToolset): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - query_params = {} if params.get("query"): query_params["query"] = params["query"] @@ -390,6 +331,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("type"): query_params["type"] = params["type"] if params.get("dashboardIds"): + # Check if dashboardIds also needs to be passed as multiple params dashboard_ids = params["dashboardIds"].split(",") query_params["dashboardIds"] = [ dashboard_id.strip() @@ -397,11 +339,13 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if dashboard_id.strip() ] if params.get("dashboardUIDs"): + # Handle dashboardUIDs as a list - split comma-separated values dashboard_uids = params["dashboardUIDs"].split(",") query_params["dashboardUIDs"] = [ uid.strip() for uid in dashboard_uids if uid.strip() ] if params.get("folderUIDs"): + # Check if folderUIDs also needs to be passed as multiple params folder_uids = params["folderUIDs"].split(",") query_params["folderUIDs"] = [ uid.strip() for uid in folder_uids if uid.strip() @@ -413,20 +357,21 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes if params.get("page"): query_params["page"] = params["page"] - result = self._make_grafana_request(instance, "api/search", params, query_params) + result = self._make_grafana_request("api/search", params, query_params) - search_url = _build_grafana_dashboard_url(instance, query_params=query_params) + config = self._toolset.grafana_config + search_url = _build_grafana_dashboard_url(config, query_params=query_params) if params.get("dashboardUIDs"): uids = [ uid.strip() for uid in params["dashboardUIDs"].split(",") if uid.strip() ] if len(uids) == 1: - search_url = _build_grafana_dashboard_url(instance, uid=uids[0]) + search_url = _build_grafana_dashboard_url(config, uid=uids[0]) return StructuredToolResult( status=result.status, - data=_attach_grafana_url(result.data, search_url), + data=result.data, params=result.params, url=search_url if search_url else None, ) @@ -443,29 +388,24 @@ def __init__(self, toolset: GrafanaToolset): description="Get a dashboard by its UID using the /api/dashboards/uid/:uid endpoint", parameters=self.extend_parameters( { - "grafana_instance": GRAFANA_INSTANCE_PARAM, "uid": ToolParameter( description="The unique identifier of the dashboard", type="string", required=True, - ), + ) } ), ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - uid = params["uid"] - result = self._make_grafana_request(instance, f"api/dashboards/uid/{uid}", params) + result = self._make_grafana_request(f"api/dashboards/uid/{uid}", params) - dashboard_url = _build_grafana_dashboard_url(instance, uid=uid) + dashboard_url = _build_grafana_dashboard_url( + self._toolset.grafana_config, uid=uid + ) filtered_result = self.filter_result(result, params) - filtered_result.data = _attach_grafana_url(filtered_result.data, dashboard_url) filtered_result.url = dashboard_url if dashboard_url else result.url return filtered_result @@ -479,26 +419,19 @@ def __init__(self, toolset: GrafanaToolset): toolset=toolset, name="grafana_get_home_dashboard", description="Get the home dashboard using the /api/dashboards/home endpoint", - parameters=self.extend_parameters( - {"grafana_instance": GRAFANA_INSTANCE_PARAM} - ), + parameters=self.extend_parameters({}), ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - - result = self._make_grafana_request(instance, "api/dashboards/home", params) + result = self._make_grafana_request("api/dashboards/home", params) + config = self._toolset.grafana_config dashboard_url = None if isinstance(result.data, dict): uid = result.data.get("dashboard", {}).get("uid") if uid: - dashboard_url = _build_grafana_dashboard_url(instance, uid=uid) + dashboard_url = _build_grafana_dashboard_url(config, uid=uid) filtered_result = self.filter_result(result, params) - filtered_result.data = _attach_grafana_url(filtered_result.data, dashboard_url) filtered_result.url = dashboard_url if dashboard_url else None return filtered_result @@ -512,22 +445,18 @@ def __init__(self, toolset: GrafanaToolset): toolset=toolset, name="grafana_get_dashboard_tags", description="Get all tags used across dashboards using the /api/dashboards/tags endpoint", - parameters={"grafana_instance": GRAFANA_INSTANCE_PARAM}, + parameters={}, ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - - result = self._make_grafana_request(instance, "api/dashboards/tags", params) + result = self._make_grafana_request("api/dashboards/tags", params) - tags_url = _build_grafana_dashboard_url(instance) + config = self._toolset.grafana_config + tags_url = _build_grafana_dashboard_url(config) return StructuredToolResult( status=result.status, - data=_attach_grafana_url(result.data, tags_url), + data=result.data, params=result.params, url=tags_url, ) @@ -626,20 +555,37 @@ def __init__(self, toolset: "GrafanaToolset", *args, **kwargs): def _make_render_request( self, - instance: GrafanaInstance, render_path: str, query_params: Dict[str, Any], timeout: Optional[int] = None, ) -> bytes: + """Make a GET request to Grafana render API and return PNG bytes. + + Args: + render_path: Render URL path (e.g. "render/d-solo/uid/slug") + query_params: Query parameters for the render request + timeout: Request timeout in seconds. Defaults to config.timeout_seconds + (60s by default on GrafanaDashboardConfig — rendering can be slow). + + Returns: + PNG image bytes + + Raises: + requests.HTTPError: If the request fails + """ + config = self._toolset.grafana_config if timeout is None: - timeout = instance.timeout_seconds or self._toolset.grafana_config.timeout_seconds - retries = instance.max_retries or self._toolset.grafana_config.max_retries - base_url = get_base_url(instance) + timeout = config.timeout_seconds + retries = config.max_retries + base_url = get_base_url(config) if not base_url.endswith("/"): base_url += "/" url = urljoin(base_url, render_path) - headers = build_headers(instance.api_key, instance.additional_headers) - auth = build_auth(instance) + headers = build_headers( + api_key=config.api_key, + additional_headers=config.additional_headers, + ) + # Render API returns PNG, not JSON headers["Accept"] = "image/png" @backoff.on_exception( @@ -654,10 +600,9 @@ def _do_render_request() -> requests.Response: response = requests.get( url, headers=headers, - auth=auth, params=query_params, timeout=timeout, - verify=bool(instance.verify_ssl), + verify=config.verify_ssl, ) response.raise_for_status() return response @@ -667,46 +612,39 @@ def _do_render_request() -> requests.Response: def _render_to_result( self, - instance: GrafanaInstance, render_path: str, params: dict, query_params: Dict[str, Any], description: str, dashboard_url: Optional[str] = None, ) -> StructuredToolResult: + """Render a panel/dashboard and return a StructuredToolResult with the image.""" try: - png_bytes = self._make_render_request(instance, render_path, query_params) + png_bytes = self._make_render_request(render_path, query_params) except requests.HTTPError as e: status_code = ( e.response.status_code if e.response is not None else "unknown" ) - response_text = e.response.text[:500] if e.response is not None else "" query_string = urlencode(query_params, doseq=True) return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Grafana render API returned HTTP {status_code}. " - f"Render path: {render_path}?{query_string}. " - f"Response: {response_text}. " - f"Ensure the grafana-image-renderer plugin is installed and running." - ), + error=f"Grafana render API returned HTTP {status_code}: {e}. " + f"Render path: {render_path}?{query_string}. " + f"Ensure the grafana-image-renderer plugin is installed and running.", params=params, ) except requests.ConnectionError as e: return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=f"[{instance.name}] Failed to connect to Grafana render API at {render_path}: {e}", + error=f"Failed to connect to Grafana render API at {render_path}: {e}", params=params, ) except requests.Timeout: query_string = urlencode(query_params, doseq=True) return StructuredToolResult( status=StructuredToolResultStatus.ERROR, - error=( - f"[{instance.name}] Grafana render request timed out for " - f"{render_path}?{query_string}. " - f"The panel may be too complex or the renderer is overloaded." - ), + error=f"Grafana render request timed out for {render_path}?{query_string}. " + f"The panel may be too complex or the renderer is overloaded.", params=params, ) @@ -724,7 +662,6 @@ def _render_to_result( class RenderPanel(BaseGrafanaRenderTool): def __init__(self, toolset: "GrafanaToolset"): panel_params: Dict[str, ToolParameter] = { - "grafana_instance": GRAFANA_INSTANCE_PARAM, "dashboard_uid": ToolParameter( description="The UID of the dashboard containing the panel", type="string", @@ -747,11 +684,6 @@ def __init__(self, toolset: "GrafanaToolset"): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - config = self._toolset.grafana_config dashboard_uid = params["dashboard_uid"] panel_id = params["panel_id"] @@ -764,7 +696,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes query_params["panelId"] = panel_id render_path = f"render/d-solo/{dashboard_uid}/_" - dashboard_url = _build_grafana_dashboard_url(instance, uid=dashboard_uid) + dashboard_url = _build_grafana_dashboard_url(config, uid=dashboard_uid) description = ( f"Rendered screenshot of panel {panel_id} from dashboard {dashboard_uid}. " @@ -773,7 +705,6 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes ) return self._render_to_result( - instance=instance, render_path=render_path, params=params, query_params=query_params, @@ -791,7 +722,6 @@ def get_parameterized_one_liner(self, params: Dict) -> str: class RenderDashboard(BaseGrafanaRenderTool): def __init__(self, toolset: "GrafanaToolset"): dashboard_params: Dict[str, ToolParameter] = { - "grafana_instance": GRAFANA_INSTANCE_PARAM, "dashboard_uid": ToolParameter( description="The UID of the dashboard to render", type="string", @@ -810,11 +740,6 @@ def __init__(self, toolset: "GrafanaToolset"): ) def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolResult: - try: - instance = self._toolset._get_instance(params) - except ValueError as e: - return _instance_error_result(params, e) - config = self._toolset.grafana_config dashboard_uid = params["dashboard_uid"] @@ -824,7 +749,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes default_height=config.default_render_height, ) render_path = f"render/d/{dashboard_uid}/_" - dashboard_url = _build_grafana_dashboard_url(instance, uid=dashboard_uid) + dashboard_url = _build_grafana_dashboard_url(config, uid=dashboard_uid) height_desc = f"{query_params['height']}px" description = ( @@ -834,7 +759,6 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes ) return self._render_to_result( - instance=instance, render_path=render_path, params=params, query_params=query_params, diff --git a/tests/plugins/toolsets/elasticsearch/test_elasticsearch_multi_instance.py b/tests/plugins/toolsets/elasticsearch/test_elasticsearch_multi_instance.py index c8c08a67df..9e1f0441a0 100644 --- a/tests/plugins/toolsets/elasticsearch/test_elasticsearch_multi_instance.py +++ b/tests/plugins/toolsets/elasticsearch/test_elasticsearch_multi_instance.py @@ -1,539 +1,102 @@ -"""Tests for multi-instance Elasticsearch configuration and basic-auth support.""" +"""Multi-instance proof for Elasticsearch via the NEW wrapper. -import base64 -import logging -from typing import Any -from unittest.mock import MagicMock, patch +The previously hand-rolled multi-instance support was reverted; Elasticsearch is +now a plain single-instance toolset made multi-instance by `multi_instance(...)`. +Verifies flat backwards-compat, routing surface, and per-instance wire calls. +""" + +import re import pytest -import requests import responses -from pydantic import ValidationError -from requests.auth import HTTPBasicAuth from holmes.core.tools import StructuredToolResultStatus from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( ElasticsearchClusterToolset, - ElasticsearchConfig, - ElasticsearchInstance, - build_auth, + ElasticsearchDataToolset, ) - - -def _toolset_with(**config: Any) -> ElasticsearchClusterToolset: - """Build a toolset with state populated directly (no network probe).""" - ts = ElasticsearchClusterToolset() - ts.config = ElasticsearchConfig(**config) - ts._instances = {i.name: i for i in (ts.elasticsearch_config.instances or [])} - return ts - - -class TestLegacySingleInstanceShape: - """Backwards-compatibility: the flat `api_url` shape still works.""" - - def test_top_level_api_url_synthesizes_default_instance(self): - cfg = ElasticsearchConfig(api_url="http://es:9200", api_key="k1") - assert cfg.instances is not None - assert len(cfg.instances) == 1 - inst = cfg.instances[0] - assert inst.name == "default" - assert inst.api_url == "http://es:9200" - assert inst.api_key == "k1" - # Globals applied to the default instance. - assert inst.verify_ssl is True - assert inst.timeout_seconds == 10 - - def test_legacy_url_alias_still_works(self): - # The deprecated `url` field still maps to `api_url`. - cfg = ElasticsearchConfig(url="http://es:9200") # type: ignore[call-arg] - assert cfg.instances[0].api_url == "http://es:9200" - - def test_missing_api_url_and_instances_rejected(self): - with pytest.raises(ValidationError, match="instances.+api_url"): - ElasticsearchConfig() - - def test_legacy_basic_auth(self): - cfg = ElasticsearchConfig( - api_url="http://es:9200", username="elastic", password="pw" - ) - inst = cfg.instances[0] - assert inst.username == "elastic" - assert inst.password == "pw" - - def test_legacy_mtls_synthesizes_default_with_cert_pair(self): - cfg = ElasticsearchConfig( - api_url="https://es:9200", - client_cert="/c.crt", - client_key="/c.key", - ) - inst = cfg.instances[0] - assert inst.client_cert == "/c.crt" - assert inst.client_key == "/c.key" - - -class TestMultiInstanceShape: - def test_basic_multi_instance(self): - cfg = ElasticsearchConfig( - instances=[ - {"name": "prod-eu", "api_url": "http://eu:9200"}, - {"name": "prod-us", "api_url": "http://us:9200"}, - ] - ) - assert [i.name for i in cfg.instances] == ["prod-eu", "prod-us"] - - def test_global_credentials_inherited(self): - cfg = ElasticsearchConfig( - username="admin", - password="pw", - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - # Instance with its own auth doesn't inherit username/password. - {"name": "b", "api_url": "http://b:9200", "api_key": "k"}, - ], - ) - assert cfg.instances[0].username == "admin" - assert cfg.instances[0].password == "pw" - assert cfg.instances[1].username is None - assert cfg.instances[1].api_key == "k" - - def test_global_password_overridden_per_instance(self): - cfg = ElasticsearchConfig( - username="elastic", - password="global-pw", - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - # Instance b sets its own password but inherits the global username. - { - "name": "b", - "api_url": "http://b:9200", - "username": "elastic", - "password": "b-pw", - }, - ], - ) - assert cfg.instances[0].password == "global-pw" - assert cfg.instances[1].password == "b-pw" - - def test_global_timeout_inherited_unless_overridden(self): - cfg = ElasticsearchConfig( - timeout_seconds=45, - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200", "timeout_seconds": 120}, - ], - ) - assert cfg.instances[0].timeout_seconds == 45 - assert cfg.instances[1].timeout_seconds == 120 - - def test_global_verify_ssl_inherited_unless_overridden(self): - cfg = ElasticsearchConfig( - verify_ssl=False, - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200", "verify_ssl": True}, - ], - ) - assert cfg.instances[0].verify_ssl is False - assert cfg.instances[1].verify_ssl is True - - def test_global_mtls_inherited(self): - cfg = ElasticsearchConfig( - client_cert="/global.crt", - client_key="/global.key", - instances=[ - {"name": "a", "api_url": "https://a:9200"}, - { - "name": "b", - "api_url": "https://b:9200", - "client_cert": "/b.crt", - "client_key": "/b.key", - }, - ], - ) - assert cfg.instances[0].client_cert == "/global.crt" - assert cfg.instances[0].client_key == "/global.key" - assert cfg.instances[1].client_cert == "/b.crt" - assert cfg.instances[1].client_key == "/b.key" - - def test_duplicate_names_rejected(self): - with pytest.raises(ValidationError, match="Duplicate Elasticsearch instance name"): - ElasticsearchConfig( - instances=[ - {"name": "dup", "api_url": "http://a:9200"}, - {"name": "dup", "api_url": "http://b:9200"}, - ] - ) - - def test_top_level_api_url_with_instances_logs_warning(self, caplog): - with caplog.at_level(logging.WARNING): - ElasticsearchConfig( - api_url="http://ignored:9200", - instances=[{"name": "real", "api_url": "http://real:9200"}], - ) - assert any("top-level `api_url` is ignored" in m for m in caplog.messages) - - -class TestAuthXor: - def test_per_instance_api_key_and_basic_auth_rejected(self): - with pytest.raises(ValidationError, match="api_key.+username.+password"): - ElasticsearchConfig( - instances=[ - { - "name": "bad", - "api_url": "http://x:9200", - "api_key": "k", - "username": "u", - "password": "p", - } - ] - ) - - def test_per_instance_username_without_password_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - ElasticsearchConfig( - instances=[{"name": "bad", "api_url": "http://x:9200", "username": "u"}] - ) - - def test_per_instance_password_without_username_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - ElasticsearchConfig( - instances=[{"name": "bad", "api_url": "http://x:9200", "password": "p"}] - ) - - def test_top_level_api_key_and_basic_auth_rejected(self): - with pytest.raises(ValidationError, match="api_key.+username.+password"): - ElasticsearchConfig( - api_url="http://x:9200", - api_key="k", - username="u", - password="p", - ) - - def test_top_level_username_without_password_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - ElasticsearchConfig( - api_url="http://x:9200", - username="u", - ) - - def test_top_level_password_without_username_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - ElasticsearchConfig( - api_url="http://x:9200", - password="p", - ) - - -class TestBuildAuth: - def test_basic_auth_returned_when_creds_set(self): - inst = ElasticsearchInstance( - name="x", api_url="http://x:9200", username="u", password="p" - ) - auth = build_auth(inst) - assert isinstance(auth, HTTPBasicAuth) - assert auth.username == "u" - assert auth.password == "p" - - def test_none_when_no_basic_auth(self): - inst = ElasticsearchInstance(name="x", api_url="http://x:9200", api_key="k") - assert build_auth(inst) is None - - -class TestRequestConstruction: - def test_basic_auth_on_the_wire(self): - cfg = ElasticsearchConfig( - username="u", - password="p", - instances=[{"name": "x", "api_url": "http://x.example:9200"}], - ) - inst = cfg.instances[0] - with responses.RequestsMock() as rsps: - rsps.add(responses.GET, "http://x.example:9200/probe", json={}) - requests.get( - "http://x.example:9200/probe", auth=build_auth(inst) - ) - auth_header = rsps.calls[0].request.headers["Authorization"] - assert auth_header.startswith("Basic ") - decoded = base64.b64decode(auth_header.split(maxsplit=1)[1]).decode() - assert decoded == "u:p" - - -class TestGetInstance: - def test_auto_select_single_instance(self): - ts = _toolset_with(api_url="http://x:9200") - inst = ts._get_instance({}) - assert inst.name == "default" - - def test_multi_instance_requires_param(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - ) - with pytest.raises(ValueError, match="required"): - ts._get_instance({}) - - def test_unknown_name_rejected(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - ) - with pytest.raises(ValueError, match="Unknown.+'c'.+Configured.+a.+b"): - ts._get_instance({"elasticsearch_instance": "c"}) - - def test_resolves_to_requested_instance(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - ) - inst = ts._get_instance({"elasticsearch_instance": "b"}) - assert inst.name == "b" - assert inst.api_url == "http://b:9200" - - -class TestToolPathThreading: - @patch("holmes.plugins.toolsets.elasticsearch.elasticsearch.requests.request") - def test_tool_routes_to_requested_instance(self, mock_request): - mock_response = MagicMock() - mock_response.json.return_value = {"status": "green"} - mock_response.raise_for_status = MagicMock() - mock_request.return_value = mock_response - - ts = _toolset_with( - username="elastic", - password="global-pw", - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - # Instance b overrides with its own complete basic-auth pair. - { - "name": "b", - "api_url": "http://b:9200", - "username": "elastic", - "password": "b-pw", - }, - ], - ) - # Find the cluster_health tool and invoke it targeting instance "b". - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchClusterHealth, - ) - - tool = next(t for t in ts.tools if isinstance(t, ElasticsearchClusterHealth)) - result = tool._invoke({"elasticsearch_instance": "b"}, context=None) - - assert result.status is StructuredToolResultStatus.SUCCESS - called_url = mock_request.call_args[1]["url"] - assert called_url.startswith("http://b:9200/") - called_auth = mock_request.call_args[1]["auth"] - # The per-instance override password should have been used, not the global. - assert isinstance(called_auth, HTTPBasicAuth) - assert called_auth.password == "b-pw" - - @patch("holmes.plugins.toolsets.elasticsearch.elasticsearch.requests.request") - def test_tool_uses_global_creds_for_instance_without_override(self, mock_request): - """Wire-level: instance with no auth gets the global creds on the - actual HTTP Authorization header, not the per-instance override.""" - mock_response = MagicMock() - mock_response.json.return_value = {"status": "green"} - mock_response.raise_for_status = MagicMock() - mock_request.return_value = mock_response - - ts = _toolset_with( - username="elastic", - password="global-pw", - instances=[ - # Inherits the global creds. - {"name": "a", "api_url": "http://a:9200"}, - # Has its own override. - { - "name": "b", - "api_url": "http://b:9200", - "username": "elastic", - "password": "b-pw", - }, - ], - ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchClusterHealth, - ) - - tool = next(t for t in ts.tools if isinstance(t, ElasticsearchClusterHealth)) - result = tool._invoke({"elasticsearch_instance": "a"}, context=None) - - assert result.status is StructuredToolResultStatus.SUCCESS - called_url = mock_request.call_args[1]["url"] - assert called_url.startswith("http://a:9200/") - called_auth = mock_request.call_args[1]["auth"] - assert isinstance(called_auth, HTTPBasicAuth) - # Global creds, not the override that lives on instance "b". - assert called_auth.username == "elastic" - assert called_auth.password == "global-pw" - - @patch("holmes.plugins.toolsets.elasticsearch.elasticsearch.requests.request") - def test_tool_uses_global_api_key_for_instance_without_override(self, mock_request): - """Wire-level: instance with no auth gets the global API key on the - Authorization header.""" - mock_response = MagicMock() - mock_response.json.return_value = {"status": "green"} - mock_response.raise_for_status = MagicMock() - mock_request.return_value = mock_response - - ts = _toolset_with( - api_key="global-key", - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200", "api_key": "b-key"}, - ], - ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchClusterHealth, - ) - - tool = next(t for t in ts.tools if isinstance(t, ElasticsearchClusterHealth)) - result = tool._invoke({"elasticsearch_instance": "a"}, context=None) - - assert result.status is StructuredToolResultStatus.SUCCESS - called_headers = mock_request.call_args[1]["headers"] - # Inherited global key, not "b-key". - assert called_headers.get("Authorization") == "ApiKey global-key" - # No basic auth when the instance is authenticating via api_key. - assert mock_request.call_args[1]["auth"] is None - - @patch("holmes.plugins.toolsets.elasticsearch.elasticsearch.requests.request") - def test_tool_errors_clearly_when_instance_missing(self, mock_request): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchClusterHealth, - ) - - tool = next(t for t in ts.tools if isinstance(t, ElasticsearchClusterHealth)) - result = tool._invoke({}, context=None) - - assert result.status is StructuredToolResultStatus.ERROR - assert "elasticsearch_instance" in result.error - mock_request.assert_not_called() - - -class TestListInstancesTool: - def test_lists_configured_instances(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchListInstances, - ) - - tool = next(t for t in ts.tools if isinstance(t, ElasticsearchListInstances)) - result = tool._invoke({}, context=None) - assert result.status is StructuredToolResultStatus.SUCCESS - names = [i["name"] for i in result.data["instances"]] - assert names == ["a", "b"] - - def test_data_and_cluster_names_do_not_collide(self): - """When both toolsets are multi-instance, their discovery tools have - distinct names so neither overrides the other in the tool registry.""" - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchClusterToolset, - ElasticsearchDataToolset, - ElasticsearchListInstances, - ) - - cfg = { - "instances": [ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - } - cluster_ts = ElasticsearchClusterToolset() - cluster_ts.prerequisites_callable(cfg) - data_ts = ElasticsearchDataToolset() - data_ts.prerequisites_callable(cfg) - - cluster_tool = next( - t for t in cluster_ts.tools if isinstance(t, ElasticsearchListInstances) - ) - data_tool = next( - t for t in data_ts.tools if isinstance(t, ElasticsearchListInstances) - ) - assert cluster_tool.name != data_tool.name - assert {cluster_tool.name, data_tool.name} == { - "elasticsearch_cluster_list_instances", - "elasticsearch_data_list_instances", - } - - -class TestSingleInstancePruning: - """When only one instance is configured, the multi-instance affordances - (the `elasticsearch_instance` parameter and the `elasticsearch_list_instances` - discovery tool) are pruned to keep the LLM's tool surface lean. - """ - - def test_single_instance_hides_list_instances_tool(self): - ts = ElasticsearchClusterToolset() - # `prerequisites_callable` is where pruning happens. - ok, _ = ts.prerequisites_callable({"api_url": "http://nope:9200"}) - # We don't care if the health check succeeds — pruning runs before it. - del ok - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchListInstances, - ) - - assert not any(isinstance(t, ElasticsearchListInstances) for t in ts.tools) - - def test_single_instance_strips_param_from_every_tool(self): - ts = ElasticsearchClusterToolset() - ts.prerequisites_callable({"api_url": "http://nope:9200"}) - for tool in ts.tools: - assert "elasticsearch_instance" not in tool.parameters, ( - f"{tool.name} still exposes elasticsearch_instance" - ) - - def test_multi_instance_keeps_list_instances_tool(self): - ts = ElasticsearchClusterToolset() - ts.prerequisites_callable( - { - "instances": [ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, - ] - } - ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchListInstances, - ) - - assert any(isinstance(t, ElasticsearchListInstances) for t in ts.tools) - - def test_multi_instance_keeps_param_on_every_tool(self): - ts = ElasticsearchClusterToolset() - ts.prerequisites_callable( +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context + +EU = "https://es-eu.internal:9200" +US = "https://es-us.internal:9200" + + +def _health(rsps, url): + rsps.add( + responses.GET, + re.compile(re.escape(url) + r"/_cluster/health.*"), + json={"cluster_name": "c", "status": "green"}, + status=200, + ) + + +class TestElasticsearchFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(ElasticsearchClusterToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _health(rsps, EU) + ok, _ = ts.prerequisites_callable({"api_url": EU, "api_key": "k"}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestElasticsearchMultiInstance: + def _build_cluster(self, rsps): + _health(rsps, EU) + _health(rsps, US) + ts = multi_instance(ElasticsearchClusterToolset) + ok, _ = ts.prerequisites_callable( { "instances": [ - {"name": "a", "api_url": "http://a:9200"}, - {"name": "b", "api_url": "http://b:9200"}, + {"name": "eu", "api_url": EU, "api_key": "k_eu"}, + {"name": "us", "api_url": US, "api_key": "k_us"}, ] } ) - from holmes.plugins.toolsets.elasticsearch.elasticsearch import ( - ElasticsearchListInstances, - ) + assert ok is True + return ts + def test_cluster_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build_cluster(rsps) + assert any(t.name == "elasticsearch_cluster_list_instances" for t in ts.tools) for tool in ts.tools: - if isinstance(tool, ElasticsearchListInstances): - continue # this tool deliberately has no instance param - assert "elasticsearch_instance" in tool.parameters, ( - f"{tool.name} is missing elasticsearch_instance" + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + def test_data_toolset_has_its_own_scoped_list_tool(self): + # Distinct list-tool name per ES toolset so they don't collide. + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _health(rsps, EU) + _health(rsps, US) + ts = multi_instance(ElasticsearchDataToolset) + ts.prerequisites_callable( + {"instances": [ + {"name": "eu", "api_url": EU, "api_key": "k_eu"}, + {"name": "us", "api_url": US, "api_key": "k_us"}, + ]} + ) + assert any(t.name == "elasticsearch_data_list_instances" for t in ts.tools) + + @pytest.mark.parametrize( + "instance,host,key", + [("eu", EU, "k_eu"), ("us", US, "k_us")], + ) + def test_each_instance_calls_its_own_cluster(self, instance, host, key): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build_cluster(rsps) + tool = next(t for t in ts.tools if t.name == "elasticsearch_cluster_health") + result = tool.invoke( + {INSTANCE_PARAM_NAME: instance}, create_mock_tool_invoke_context() ) + assert result.status is StructuredToolResultStatus.SUCCESS + last = rsps.calls[-1].request + assert last.url.startswith(f"{host}/_cluster/health") + assert last.headers.get("Authorization") == f"ApiKey {key}" diff --git a/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py b/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py index 0a6a6a81d2..d70c95ca65 100644 --- a/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py +++ b/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py @@ -1,247 +1,152 @@ -"""Tests for multi-instance Grafana configuration and basic-auth support.""" +"""Multi-instance proof for Grafana (dashboards/loki/tempo) via the NEW wrapper. -import base64 -import logging -from typing import Any -from unittest.mock import MagicMock +The previously hand-rolled Grafana dashboard multi-instance support was reverted; +all three Grafana toolsets are now plain single-instance toolsets made +multi-instance by `multi_instance(...)`. Verifies flat backwards-compat, routing +surface, and per-instance wire calls (each instance → its own host + Bearer key). +""" + +import re import pytest -import requests import responses -from pydantic import ValidationError -from requests.auth import HTTPBasicAuth - -from holmes.core.llm import LLM -from holmes.core.tools import StructuredToolResultStatus, ToolInvokeContext -from holmes.plugins.toolsets.grafana.common import ( - GrafanaInstance, - MultiInstanceGrafanaConfig as GrafanaConfig, - build_auth, - build_headers, -) -from holmes.plugins.toolsets.grafana.toolset_grafana import ( - GrafanaDashboardConfig, - GrafanaToolset, -) +from holmes.plugins.toolsets.grafana.loki.toolset_grafana_loki import GrafanaLokiToolset +from holmes.plugins.toolsets.grafana.toolset_grafana import GrafanaToolset +from holmes.plugins.toolsets.grafana.toolset_grafana_tempo import GrafanaTempoToolset +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from tests.conftest import create_mock_tool_invoke_context -def _ctx() -> ToolInvokeContext: - return ToolInvokeContext( - llm=MagicMock(spec=LLM), - max_token_count=100_000, - tool_call_id="t1", - tool_name="x", - ) - - -class TestLegacySingleInstanceShape: - def test_top_level_api_url_synthesizes_default_instance(self): - cfg = GrafanaConfig(api_url="http://grafana", api_key="k1") - assert cfg.instances is not None - assert len(cfg.instances) == 1 - inst = cfg.instances[0] - assert inst.name == "default" - assert inst.api_url == "http://grafana" - assert inst.api_key == "k1" - # Globals applied - assert inst.verify_ssl is True - assert inst.timeout_seconds == 30 - assert inst.max_retries == 3 - - def test_legacy_url_alias_still_works(self): - # The deprecated `url` field still maps to `api_url` at the top level. - cfg = GrafanaConfig(url="http://grafana") # type: ignore[call-arg] - assert cfg.instances[0].api_url == "http://grafana" - - def test_missing_api_url_and_instances_rejected(self): - with pytest.raises(ValidationError, match="instances.+api_url"): - GrafanaConfig() - - -class TestMultiInstanceShape: - def test_basic_multi_instance(self): - cfg = GrafanaConfig( - instances=[ - {"name": "prod-eu", "api_url": "http://eu"}, - {"name": "prod-us", "api_url": "http://us"}, - ] - ) - assert [i.name for i in cfg.instances] == ["prod-eu", "prod-us"] - - def test_global_credentials_inherited(self): - cfg = GrafanaConfig( - username="admin", - password="pw", - instances=[ - {"name": "a", "api_url": "http://a"}, - {"name": "b", "api_url": "http://b", "api_key": "k"}, # own auth - ], - ) - assert cfg.instances[0].username == "admin" - assert cfg.instances[0].password == "pw" - # Instance with its own auth doesn't inherit username/password - assert cfg.instances[1].username is None - assert cfg.instances[1].api_key == "k" - - def test_global_timeout_inherited_unless_overridden(self): - cfg = GrafanaConfig( - timeout_seconds=45, - instances=[ - {"name": "a", "api_url": "http://a"}, - {"name": "b", "api_url": "http://b", "timeout_seconds": 120}, - ], - ) - assert cfg.instances[0].timeout_seconds == 45 - assert cfg.instances[1].timeout_seconds == 120 - - def test_duplicate_names_rejected(self): - with pytest.raises(ValidationError, match="Duplicate Grafana instance name"): - GrafanaConfig( - instances=[ - {"name": "dup", "api_url": "http://a"}, - {"name": "dup", "api_url": "http://b"}, - ] - ) - def test_top_level_api_url_with_instances_logs_warning(self, caplog): - with caplog.at_level(logging.WARNING): - GrafanaConfig( - api_url="http://ignored", - instances=[{"name": "real", "api_url": "http://real"}], - ) - assert any("top-level `api_url` is ignored" in m for m in caplog.messages) - - -class TestAuthXor: - def test_api_key_and_basic_auth_rejected_together(self): - with pytest.raises(ValidationError, match="api_key.+username.+password"): - GrafanaConfig( - instances=[ - { - "name": "bad", - "api_url": "http://x", - "api_key": "k", - "username": "u", - "password": "p", - } - ] - ) +def _reg(rsps, method, url_regex, body): + rsps.add(method, re.compile(url_regex), json=body, status=200) - def test_username_without_password_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - GrafanaConfig( - instances=[{"name": "bad", "api_url": "http://x", "username": "u"}] - ) - def test_password_without_username_rejected(self): - with pytest.raises(ValidationError, match="username.+password.+together"): - GrafanaConfig( - instances=[{"name": "bad", "api_url": "http://x", "password": "p"}] - ) +class TestGrafanaDashboards: + EU = "https://graf-eu.example.com" + US = "https://graf-us.example.com" + def _mock(self, rsps): + # health (/api/dashboards/tags) + search (/api/search) on both hosts + _reg(rsps, responses.GET, r"https://graf-(eu|us)\.example\.com/api/(dashboards/tags|search).*", []) -class TestBuildAuth: - def test_basic_auth_returned_when_creds_set(self): - inst = GrafanaInstance( - name="x", api_url="http://x", username="u", password="p" + def _build(self, rsps): + self._mock(rsps) + ts = multi_instance(GrafanaToolset) + ok, _ = ts.prerequisites_callable( + {"instances": [ + {"name": "eu", "api_url": self.EU, "api_key": "k_eu"}, + {"name": "us", "api_url": self.US, "api_key": "k_us"}, + ]} ) - auth = build_auth(inst) - assert isinstance(auth, HTTPBasicAuth) - assert auth.username == "u" - assert auth.password == "p" - - def test_none_when_no_basic_auth(self): - inst = GrafanaInstance(name="x", api_url="http://x", api_key="k") - assert build_auth(inst) is None - - -class TestRequestConstruction: - def test_basic_auth_on_the_wire(self): - cfg = GrafanaConfig( - username="u", password="p", - instances=[{"name": "x", "api_url": "http://x.example"}], + assert ok is True + return ts + + def test_flat_backwards_compatible(self): + ts = multi_instance(GrafanaToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + self._mock(rsps) + ok, _ = ts.prerequisites_callable({"api_url": self.EU, "api_key": "k"}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "grafana_dashboards_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize("instance,host,key", [("eu", EU, "k_eu"), ("us", US, "k_us")]) + def test_each_instance_calls_its_own_grafana(self, instance, host, key): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "grafana_search_dashboards") + tool.invoke({"query": "x", INSTANCE_PARAM_NAME: instance}, create_mock_tool_invoke_context()) + last = rsps.calls[-1].request + assert last.url.startswith(f"{host}/api/search") + assert last.headers.get("Authorization") == f"Bearer {key}" + + +class TestGrafanaLoki: + EU = "http://loki-eu.svc:3100" + US = "http://loki-us.svc:3100" + + def _mock(self, rsps): + _reg(rsps, responses.GET, r"http://loki-(eu|us)\.svc:3100/loki/api/v1/.*", {"data": {"result": []}}) + _reg(rsps, responses.POST, r"http://loki-(eu|us)\.svc:3100/loki/api/v1/.*", {"data": {"result": []}}) + + def _build(self, rsps): + self._mock(rsps) + ts = multi_instance(GrafanaLokiToolset) + ok, _ = ts.prerequisites_callable( + {"instances": [ + {"name": "eu", "api_url": self.EU, "api_key": "k_eu"}, + {"name": "us", "api_url": self.US, "api_key": "k_us"}, + ]} ) - inst = cfg.instances[0] - with responses.RequestsMock() as rsps: - rsps.add(responses.GET, "http://x.example/probe", json={}) - requests.get( - "http://x.example/probe", - headers=build_headers(inst.api_key, inst.additional_headers), - auth=build_auth(inst), + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "grafana_loki_list_instances" for t in ts.tools) + + @pytest.mark.parametrize("instance,host,key", [("eu", EU, "k_eu"), ("us", US, "k_us")]) + def test_each_instance_calls_its_own_loki(self, instance, host, key): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "grafana_loki_query") + tool.invoke( + {"query": '{job="x"}', INSTANCE_PARAM_NAME: instance}, + create_mock_tool_invoke_context(), ) - auth_header = rsps.calls[0].request.headers["Authorization"] - assert auth_header.startswith("Basic ") - decoded = base64.b64decode(auth_header.split(maxsplit=1)[1]).decode() - assert decoded == "u:p" - - -def _toolset_with(**config: Any) -> GrafanaToolset: - """Build a GrafanaToolset with state populated directly (no network probe).""" - ts = GrafanaToolset() - ts._grafana_config = GrafanaDashboardConfig(**config) - ts._instances = {i.name: i for i in ts._grafana_config.instances} - return ts - - -class TestGetInstance: - def test_auto_select_single_instance(self): - ts = _toolset_with(api_url="http://x") - inst = ts._get_instance({}) - assert inst.name == "default" - - def test_multi_instance_requires_param(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a"}, - {"name": "b", "api_url": "http://b"}, - ] - ) - with pytest.raises(ValueError, match="required"): - ts._get_instance({}) - - def test_unknown_name_rejected(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a"}, - {"name": "b", "api_url": "http://b"}, - ] - ) - with pytest.raises(ValueError, match="Unknown grafana_instance"): - ts._get_instance({"grafana_instance": "missing"}) - - def test_known_name_resolves(self): - ts = _toolset_with( - instances=[ - {"name": "a", "api_url": "http://a"}, - {"name": "b", "api_url": "http://b"}, - ] - ) - inst = ts._get_instance({"grafana_instance": "b"}) - assert inst.api_url == "http://b" - - -class TestToolPathThreading: - """End-to-end: a tool call uses the resolved instance's auth and URL.""" - - def test_dashboard_tool_threads_basic_auth(self): - ts = _toolset_with( - username="admin", - password="admin", - instances=[{"name": "prod", "api_url": "http://prod.example"}], - ) - - get_dashboard_tags = next( - t for t in ts.tools if t.name == "grafana_get_dashboard_tags" + hosts = [c.request.url for c in rsps.calls if c.request.url.startswith(f"{host}/loki")] + assert hosts, f"no call to {host}" + assert rsps.calls[-1].request.headers.get("Authorization") == f"Bearer {key}" + + +class TestGrafanaTempo: + EU = "http://tempo-eu.svc:3200" + US = "http://tempo-us.svc:3200" + + def _mock(self, rsps): + _reg(rsps, responses.GET, r"http://tempo-(eu|us)\.svc:3200/api/.*", {"traces": []}) + + def _build(self, rsps): + self._mock(rsps) + ts = multi_instance(GrafanaTempoToolset) + ok, _ = ts.prerequisites_callable( + {"instances": [ + {"name": "eu", "api_url": self.EU, "api_key": "k_eu"}, + {"name": "us", "api_url": self.US, "api_key": "k_us"}, + ]} ) - with responses.RequestsMock() as rsps: - rsps.add( - responses.GET, - "http://prod.example/api/dashboards/tags", - json=[{"term": "production"}], + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "grafana_tempo_list_instances" for t in ts.tools) + + @pytest.mark.parametrize("instance,host,key", [("eu", EU, "k_eu"), ("us", US, "k_us")]) + def test_each_instance_calls_its_own_tempo(self, instance, host, key): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "tempo_search_traces_by_query") + tool.invoke( + {"q": '{ .service.name = "x" }', INSTANCE_PARAM_NAME: instance}, + create_mock_tool_invoke_context(), ) - r = get_dashboard_tags._invoke({"grafana_instance": "prod"}, _ctx()) - assert r.status == StructuredToolResultStatus.SUCCESS - auth_header = rsps.calls[0].request.headers["Authorization"] - assert auth_header.startswith("Basic ") - decoded = base64.b64decode(auth_header.split(maxsplit=1)[1]).decode() - assert decoded == "admin:admin" + calls = [c.request for c in rsps.calls if c.request.url.startswith(f"{host}/api")] + assert calls, f"no call to {host}" + assert calls[-1].headers.get("Authorization") == f"Bearer {key}" diff --git a/tests/plugins/toolsets/test_elasticsearch_mtls.py b/tests/plugins/toolsets/test_elasticsearch_mtls.py index c4f6b95d24..adba078b8d 100644 --- a/tests/plugins/toolsets/test_elasticsearch_mtls.py +++ b/tests/plugins/toolsets/test_elasticsearch_mtls.py @@ -10,14 +10,6 @@ ) -def _toolset_with(config: ElasticsearchConfig) -> ElasticsearchClusterToolset: - """Construct a toolset and populate _instances from the config (skipping the network probe).""" - toolset = ElasticsearchClusterToolset() - toolset.config = config - toolset._instances = {i.name: i for i in (config.instances or [])} - return toolset - - class TestElasticsearchMTLSConfig: """Tests for mTLS configuration validation.""" @@ -30,9 +22,6 @@ def test_mtls_config_valid(self): ) assert config.client_cert == "/path/to/client.crt" assert config.client_key == "/path/to/client.key" - # Synthesized default instance also carries the mTLS pair. - assert config.instances[0].client_cert == "/path/to/client.crt" - assert config.instances[0].client_key == "/path/to/client.key" def test_mtls_config_cert_without_key_fails(self): """Test that client_cert without client_key raises error.""" @@ -70,36 +59,44 @@ def test_config_without_mtls(self): class TestElasticsearchMTLSRequest: - """Tests for mTLS request handling on the resolved instance.""" + """Tests for mTLS request handling.""" - def test_instance_carries_cert_pair(self): - """The synthesized default instance carries the mTLS cert/key pair.""" - config = ElasticsearchConfig( + def test_get_client_cert_returns_tuple(self): + """Test that _get_client_cert returns cert/key tuple when configured.""" + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( api_url="https://es:9200", client_cert="/path/to/client.crt", client_key="/path/to/client.key", ) - toolset = _toolset_with(config) - inst = toolset._instances["default"] - assert inst.client_cert == "/path/to/client.crt" - assert inst.client_key == "/path/to/client.key" - - def test_instance_has_no_cert_when_unset(self): - config = ElasticsearchConfig(api_url="https://es:9200", api_key="test-key") - toolset = _toolset_with(config) - inst = toolset._instances["default"] - assert inst.client_cert is None - assert inst.client_key is None - - def test_instance_verify_ssl_propagated(self): - config = ElasticsearchConfig(api_url="https://es:9200", verify_ssl=False) - toolset = _toolset_with(config) - assert toolset._instances["default"].verify_ssl is False - - def test_instance_verify_ssl_defaults_true(self): - config = ElasticsearchConfig(api_url="https://es:9200") - toolset = _toolset_with(config) - assert toolset._instances["default"].verify_ssl is True + result = toolset._get_client_cert() + assert result == ("/path/to/client.crt", "/path/to/client.key") + + def test_get_client_cert_returns_none(self): + """Test that _get_client_cert returns None when not configured.""" + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( + api_url="https://es:9200", + api_key="test-key", + ) + assert toolset._get_client_cert() is None + + def test_get_verify_returns_bool(self): + """Test that _get_verify returns verify_ssl boolean.""" + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( + api_url="https://es:9200", + verify_ssl=False, + ) + assert toolset._get_verify() is False + + def test_get_verify_defaults_true(self): + """Test that _get_verify defaults to True.""" + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( + api_url="https://es:9200", + ) + assert toolset._get_verify() is True @patch("holmes.plugins.toolsets.elasticsearch.elasticsearch.requests.request") def test_make_request_passes_mtls_params(self, mock_request): @@ -109,15 +106,14 @@ def test_make_request_passes_mtls_params(self, mock_request): mock_response.raise_for_status = MagicMock() mock_request.return_value = mock_response - config = ElasticsearchConfig( + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( api_url="https://es:9200", client_cert="/path/to/client.crt", client_key="/path/to/client.key", ) - toolset = _toolset_with(config) - instance = toolset._instances["default"] - toolset._make_request(instance, "GET", "_cluster/health") + toolset._make_request("GET", "_cluster/health") mock_request.assert_called_once() call_kwargs = mock_request.call_args[1] @@ -132,11 +128,13 @@ def test_make_request_without_mtls(self, mock_request): mock_response.raise_for_status = MagicMock() mock_request.return_value = mock_response - config = ElasticsearchConfig(api_url="https://es:9200", api_key="test-key") - toolset = _toolset_with(config) - instance = toolset._instances["default"] + toolset = ElasticsearchClusterToolset() + toolset.config = ElasticsearchConfig( + api_url="https://es:9200", + api_key="test-key", + ) - toolset._make_request(instance, "GET", "_cluster/health") + toolset._make_request("GET", "_cluster/health") call_kwargs = mock_request.call_args[1] assert call_kwargs["cert"] is None diff --git a/tests/plugins/toolsets/test_json_filter_mixin.py b/tests/plugins/toolsets/test_json_filter_mixin.py index 0f91a890e6..6ea06143dd 100644 --- a/tests/plugins/toolsets/test_json_filter_mixin.py +++ b/tests/plugins/toolsets/test_json_filter_mixin.py @@ -10,9 +10,8 @@ def _build_tool(data): toolset = GrafanaToolset() toolset._grafana_config = GrafanaDashboardConfig(url="http://example.com") - toolset._instances = {i.name: i for i in toolset._grafana_config.instances} tool = GetDashboardByUID(toolset) - tool._make_grafana_request = lambda instance, endpoint, params: StructuredToolResult( + tool._make_grafana_request = lambda endpoint, params: StructuredToolResult( status=StructuredToolResultStatus.SUCCESS, data=data, params=params, @@ -37,11 +36,7 @@ def test_jq_filter_applies_before_returning_data(): ) assert result.status is StructuredToolResultStatus.SUCCESS - # GetDashboardByUID wraps non-dict filter results with the Grafana UI URL. - assert result.data == { - "grafana_url": "http://example.com/d/abc", - "results": "CPU", - } + assert result.data == "CPU" def test_invalid_jq_returns_error(): @@ -92,10 +87,9 @@ def test_max_depth_zero_preserves_upstream_error(): """If upstream already failed, the guard must not clobber the original error field.""" toolset = GrafanaToolset() toolset._grafana_config = GrafanaDashboardConfig(url="http://example.com") - toolset._instances = {i.name: i for i in toolset._grafana_config.instances} tool = GetDashboardByUID(toolset) upstream_error = "HTTP 503: Elasticsearch cluster unreachable" - tool._make_grafana_request = lambda instance, endpoint, params: StructuredToolResult( + tool._make_grafana_request = lambda endpoint, params: StructuredToolResult( status=StructuredToolResultStatus.ERROR, error=upstream_error, data={"status_code": 503, "body": "unreachable"}, @@ -110,14 +104,14 @@ def test_max_depth_zero_preserves_upstream_error(): def test_max_depth_omitted_returns_full_data(): - """Omitting max_depth must return the full, untouched payload (plus the Grafana UI URL).""" + """Omitting max_depth must return the full, untouched payload.""" data = {"dashboard": {"panels": [{"id": 1, "title": "CPU"}]}} tool = _build_tool(data) result = tool._invoke({"uid": "abc"}, context=None) assert result.status is StructuredToolResultStatus.SUCCESS - assert result.data == {"grafana_url": "http://example.com/d/abc", **data} + assert result.data == data def test_max_depth_description_does_not_lure_zero(): diff --git a/tests/plugins/toolsets/test_verify_tool_urls.py b/tests/plugins/toolsets/test_verify_tool_urls.py index b79fb610b4..966cd912e4 100644 --- a/tests/plugins/toolsets/test_verify_tool_urls.py +++ b/tests/plugins/toolsets/test_verify_tool_urls.py @@ -1,6 +1,5 @@ import base64 import json -from typing import Any, Dict, Optional from unittest.mock import MagicMock, patch from urllib.parse import parse_qs, unquote, urlparse @@ -419,13 +418,7 @@ class TestDashboardURLs: @staticmethod def setup_mocks(): - def mock_make_request( - instance: Any, - endpoint: str, - params: Dict[str, Any], - query_params: Optional[Dict[str, Any]] = None, - timeout: int = 30, - ) -> MagicMock: + def mock_make_request(endpoint, params, query_params=None, timeout=30): if "home" in endpoint: data = get_mock_home_dashboard() elif "tags" in endpoint: @@ -459,7 +452,6 @@ def config(self): def toolset(self, config): toolset = GrafanaToolset() toolset._grafana_config = config - toolset._instances = {i.name: i for i in config.instances} return toolset TEST_CASES = [ From 50669d61d4cb3c0f10065333c87225917ea3c51a Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 16:16:27 +0300 Subject: [PATCH 09/11] Convert New Relic to multi-instance via the wrapper Wrap NewRelicToolset with `multi_instance(...)` (toolset file unchanged). Each instance carries its own API key + account; `enable_multi_account` stays an in-instance feature. A routed NRQL query for each instance uses that instance's Api-Key header and account id (asserted on the wire). OpenSearch query-assist is intentionally NOT wrapped: it has no connection config and makes no API call (it only generates PPL query strings, gated by the OPENSEARCH_URL env var), so multi-instance doesn't apply. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/__init__.py | 2 +- .../newrelic/test_newrelic_multi_instance.py | 84 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 tests/plugins/toolsets/newrelic/test_newrelic_multi_instance.py diff --git a/holmes/plugins/toolsets/__init__.py b/holmes/plugins/toolsets/__init__.py index adb029cc80..9118d11ff3 100644 --- a/holmes/plugins/toolsets/__init__.py +++ b/holmes/plugins/toolsets/__init__.py @@ -109,7 +109,7 @@ def load_python_toolsets( RobustaToolset(dal), multi_instance(GrafanaLokiToolset), multi_instance(GrafanaTempoToolset), - NewRelicToolset(), + multi_instance(NewRelicToolset), multi_instance(GrafanaToolset), NotionToolset(), KafkaToolset(), diff --git a/tests/plugins/toolsets/newrelic/test_newrelic_multi_instance.py b/tests/plugins/toolsets/newrelic/test_newrelic_multi_instance.py new file mode 100644 index 0000000000..9f63512448 --- /dev/null +++ b/tests/plugins/toolsets/newrelic/test_newrelic_multi_instance.py @@ -0,0 +1,84 @@ +"""Multi-instance proof for New Relic via the wrapper. + +New Relic is single-instance on master (its `enable_multi_account` is a separate +axis). `multi_instance(NewRelicToolset)` makes it multi-instance. Each instance has +its own API key + account; a routed NRQL query uses the selected instance's +Api-Key header and account id on the wire. +""" + +import re + +import pytest +import responses + +from holmes.plugins.toolsets.multi_instance import ( + INSTANCE_PARAM_NAME, + ListInstancesTool, + multi_instance, +) +from holmes.plugins.toolsets.newrelic.newrelic import NewRelicToolset +from tests.conftest import create_mock_tool_invoke_context + +GRAPHQL = "https://api.newrelic.com/graphql" +_NRQL_OK = {"data": {"actor": {"account": {"nrql": {"results": [{"count": 1}]}}}}} + + +def _mock(rsps): + rsps.add(responses.POST, re.compile(re.escape(GRAPHQL)), json=_NRQL_OK, status=200) + + +class TestNewRelicFlat: + def test_flat_config_backwards_compatible(self): + ts = multi_instance(NewRelicToolset) + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + _mock(rsps) + ok, _ = ts.prerequisites_callable({"api_key": "NRAK-1", "account_id": "111"}) + assert ok is True + assert list(ts._children) == ["default"] + assert not any(isinstance(t, ListInstancesTool) for t in ts.tools) + assert all(INSTANCE_PARAM_NAME not in t.parameters for t in ts.tools) + + +class TestNewRelicMultiInstance: + def _build(self, rsps): + _mock(rsps) + ts = multi_instance(NewRelicToolset) + ok, _ = ts.prerequisites_callable( + { + "instances": [ + {"name": "team-a", "api_key": "NRAK-a", "account_id": "111"}, + {"name": "team-b", "api_key": "NRAK-b", "account_id": "222"}, + ] + } + ) + assert ok is True + return ts + + def test_tool_surface(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + assert any(t.name == "newrelic_list_instances" for t in ts.tools) + for tool in ts.tools: + if not isinstance(tool, ListInstancesTool): + assert INSTANCE_PARAM_NAME in tool.parameters + + @pytest.mark.parametrize( + "instance,api_key,account", + [("team-a", "NRAK-a", "111"), ("team-b", "NRAK-b", "222")], + ) + def test_each_instance_uses_its_own_key_and_account(self, instance, api_key, account): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "newrelic_execute_nrql_query") + tool.invoke( + { + "query": "SELECT count(*) FROM Transaction", + "description": "count transactions test", + "query_type": "Other", + INSTANCE_PARAM_NAME: instance, + }, + create_mock_tool_invoke_context(), + ) + last = rsps.calls[-1].request + assert last.headers.get("Api-Key") == api_key + assert f"account(id: {account})" in last.body.decode() From d8c24e2b7d070f359293b4bcbf4b21e328d6850e Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 16:29:38 +0300 Subject: [PATCH 10/11] docs: add reusable multi-instance fence + central page Add a 'multi-instance' SuperFence (docs/custom_fences.py) that renders the standard Multiple Instances section for a toolset from a one-line import: the fence body supplies the toolset key + a single-instance config example, and it emits the instances: example, the auto-injected 'instance' param and '_list_instances' tool note, and a link to the central page. Add the central docs/data-sources/multi-instance-toolsets.md page (config shape, shared defaults, instance param, discovery tool, health, backwards compat, supported-toolset list) and register it in the nav. Include the fence in all 16 converted toolset pages (Elasticsearch, Grafana dashboards/loki/tempo, Prometheus, Datadog, Coralogix, VictoriaLogs, New Relic, Azure SQL, MongoDB Atlas, ServiceNow, Confluence). Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- docs/custom_fences.py | 86 +++++++++++++++ docs/data-sources/.nav.yml | 1 + .../builtin-toolsets/azure-sql.md | 11 ++ .../builtin-toolsets/confluence.md | 9 ++ .../builtin-toolsets/coralogix-logs.md | 8 ++ docs/data-sources/builtin-toolsets/datadog.md | 9 ++ .../builtin-toolsets/elasticsearch.md | 8 ++ .../builtin-toolsets/grafanadashboards.md | 8 ++ .../builtin-toolsets/grafanaloki.md | 9 ++ .../builtin-toolsets/grafanatempo.md | 9 ++ .../builtin-toolsets/mongodb-atlas.md | 9 ++ .../data-sources/builtin-toolsets/newrelic.md | 8 ++ .../builtin-toolsets/prometheus.md | 7 ++ .../builtin-toolsets/servicenow.md | 8 ++ .../builtin-toolsets/victorialogs.md | 7 ++ docs/data-sources/multi-instance-toolsets.md | 100 ++++++++++++++++++ mkdocs.yml | 3 + 17 files changed, 300 insertions(+) create mode 100644 docs/data-sources/multi-instance-toolsets.md diff --git a/docs/custom_fences.py b/docs/custom_fences.py index d1b3bd5c71..0b9a557f9c 100644 --- a/docs/custom_fences.py +++ b/docs/custom_fences.py @@ -12,6 +12,8 @@ import re import uuid +import yaml # type: ignore + ROBUSTA_REGIONS = (("US", ""), ("EU", "eu"), ("AP", "ap")) ROBUSTA_DOMAIN_RE = re.compile(r"\b(api|platform)\.robusta\.dev\b") MARKDOWN_LINK_RE = re.compile(r"^\[([^\]]+)\]\(([^)\s]+)\)(\{[^}]*\})?$") @@ -215,3 +217,87 @@ def robusta_region_fence_format(source, language, css_class, options, md, **kwar f'
\n{blocks_html}
\n' "" ) + + +# Central page that documents how multi-instance toolsets work. Linked from every +# rendered ``multi-instance`` block so each toolset page doesn't repeat the prose. +MULTI_INSTANCE_DOC_URL = "/data-sources/multi-instance-toolsets/" + + +def _reindent(text: str, spaces: int) -> str: + """Dedent ``text`` to its common leading whitespace, then indent every + non-empty line by ``spaces``. Used to nest a flat config example under + ``instances:`` at the correct YAML depth.""" + lines = text.strip("\n").split("\n") + nonempty = [ln for ln in lines if ln.strip()] + base = min((len(ln) - len(ln.lstrip()) for ln in nonempty), default=0) + pad = " " * spaces + return "\n".join(pad + ln[base:] if ln.strip() else "" for ln in lines) + + +def multi_instance_fence_format(source, language, css_class, options, md, **kwargs): + """Render the standard "Multiple Instances" section for a toolset. + + The fence body is YAML with three keys: + + ```multi-instance + toolset: grafana/dashboards # the toolset key used in config examples + name: Grafana # human-readable name (optional; derived from toolset) + config: | # a single-instance config example for this toolset + api_url: + api_key: + ``` + + It emits a note admonition that: + - explains the toolset can connect to several instances via ``instances:``; + - shows the supplied config example nested under ``instances:`` (two entries); + - notes the auto-injected ``instance`` parameter and ``_list_instances`` + tool that appear when more than one instance is configured; + - links to the central Multiple Instances page for the full behaviour. + + The same component renders identically for every toolset, so each page imports + it in one fenced block instead of repeating the prose. + """ + spec = yaml.safe_load(source) or {} + toolset = str(spec.get("toolset", "")).strip() + name = str(spec.get("name") or toolset or "this").strip() + config = str(spec.get("config", "")).strip() + if not toolset or not config: + raise ValueError( + "multi-instance fence requires 'toolset' and 'config' keys in its YAML body" + ) + + # The wrapper names the discovery tool by replacing '/' with '_' in the toolset name. + list_tool = spec.get("list_tool") or (toolset.replace("/", "_") + "_list_instances") + + fields = _reindent(config, 10) + yaml_example = ( + "toolsets:\n" + f" {toolset}:\n" + " enabled: true\n" + " config:\n" + " instances:\n" + f" - name: prod\n{fields}\n" + f" - name: staging\n{fields}\n" + ) + + name_e = html.escape(name) + list_tool_e = html.escape(str(list_tool)) + return ( + '
\n' + '

Multiple Instances

\n' + f"

The {name_e} toolset can connect to more than one {name_e} instance. " + "List each one under instances: with a unique name. " + "Any config field set outside instances: becomes a default that " + "every instance inherits, so shared settings only need to be written once.

\n" + f'
{html.escape(yaml_example)}
\n' + "

When more than one instance is configured, HolmesGPT automatically adds an " + f"instance parameter to every {name_e} tool (so it can pick which " + f"instance to query) and a {list_tool_e} tool to list the configured " + "instances. With a single instance — including the flat config without " + "instances: — the tools are unchanged and fully backwards " + "compatible.

\n" + f'

See Multiple Instances for the full ' + "behaviour, including global defaults and health reporting.

\n" + "
" + ) diff --git a/docs/data-sources/.nav.yml b/docs/data-sources/.nav.yml index dc9fd443bd..20537bc6e5 100644 --- a/docs/data-sources/.nav.yml +++ b/docs/data-sources/.nav.yml @@ -2,6 +2,7 @@ nav: - index.md - Recommended Setup: recommended-setup.md - Built-in Toolsets: builtin-toolsets + - Multiple Instances: multi-instance-toolsets.md - HTTP Connectors: api-toolsets.md - Database Connectors: database-connectors.md - Custom Toolsets: custom-toolsets.md diff --git a/docs/data-sources/builtin-toolsets/azure-sql.md b/docs/data-sources/builtin-toolsets/azure-sql.md index b0f7fb13a9..c964a5b877 100644 --- a/docs/data-sources/builtin-toolsets/azure-sql.md +++ b/docs/data-sources/builtin-toolsets/azure-sql.md @@ -190,6 +190,17 @@ By enabling this toolset, HolmesGPT can analyze Azure SQL Database performance, --8<-- "snippets/helm_upgrade_command.md" +```multi-instance +toolset: azure/sql +name: Azure SQL +config: | + database: + subscription_id: "your-subscription-id" + resource_group: "your-resource-group" + server_name: "your-azure-sql-server-name" + database_name: "your-azure-sql-database-name" +``` + ## Roles / Access controls The service principal requires these roles: diff --git a/docs/data-sources/builtin-toolsets/confluence.md b/docs/data-sources/builtin-toolsets/confluence.md index f4a14c66f2..985a163837 100644 --- a/docs/data-sources/builtin-toolsets/confluence.md +++ b/docs/data-sources/builtin-toolsets/confluence.md @@ -314,6 +314,15 @@ HolmesGPT authenticates to a self-hosted Confluence Data Center (or Server) inst --8<-- "snippets/helm_upgrade_command.md" +```multi-instance +toolset: confluence +name: Confluence +config: | + api_url: "https://yourcompany.atlassian.net" + user: "your-email@example.com" + api_key: "your-api-token" +``` + ## Configuration Reference `subtype` is set at the toolset level (sibling of `enabled:` and `config:`); the rest of the fields below go inside `config:`. diff --git a/docs/data-sources/builtin-toolsets/coralogix-logs.md b/docs/data-sources/builtin-toolsets/coralogix-logs.md index 5c32eff349..5672acf14b 100644 --- a/docs/data-sources/builtin-toolsets/coralogix-logs.md +++ b/docs/data-sources/builtin-toolsets/coralogix-logs.md @@ -122,6 +122,14 @@ Configure both the Coralogix DataPrime toolset (for logs/traces) and the Prometh **Note**: Both toolsets use the same API key. Helm-tab users only need to create one Kubernetes secret — the env var feeds both the `coralogix` toolset's `api_key` field and the Prometheus toolset's `Authorization` header. +```multi-instance +toolset: coralogix +name: Coralogix +config: | + api_key: "" + domain: "eu2.coralogix.com" +``` + ## Recommended: Customize Coralogix Instructions By specifying details about your Coralogix metrics, logs, and traces, you can significantly speed up and improve investigations. This allows Holmes to work with your environment directly, rather than spending time discovering labels, mappings, and metric names on its own. diff --git a/docs/data-sources/builtin-toolsets/datadog.md b/docs/data-sources/builtin-toolsets/datadog.md index 3d62e24a3c..f586ae8c41 100644 --- a/docs/data-sources/builtin-toolsets/datadog.md +++ b/docs/data-sources/builtin-toolsets/datadog.md @@ -186,6 +186,15 @@ holmes ask "list Datadog monitors" That's it! You're now connected to Datadog with all toolsets enabled. +```multi-instance +toolset: datadog/logs +name: Datadog +config: | + api_key: "{{ env.DATADOG_API_KEY }}" + app_key: "{{ env.DATADOG_APP_KEY }}" + api_url: https://api.datadoghq.com +``` + ## Available Toolsets HolmesGPT provides four specialized Datadog toolsets: diff --git a/docs/data-sources/builtin-toolsets/elasticsearch.md b/docs/data-sources/builtin-toolsets/elasticsearch.md index b66ab08917..acaaa01deb 100644 --- a/docs/data-sources/builtin-toolsets/elasticsearch.md +++ b/docs/data-sources/builtin-toolsets/elasticsearch.md @@ -134,6 +134,14 @@ Enable only the toolset(s) you need. Most users who just want to search logs onl !!! tip "Enable only what you need" You can enable just `elasticsearch/data` or `elasticsearch/cluster` depending on your needs. Most users who just want to search logs only need `elasticsearch/data`. +```multi-instance +toolset: elasticsearch/data +name: Elasticsearch +config: | + api_url: "https://your-cluster.es.cloud.io:443" + api_key: "your-api-key" +``` + ## Authentication The toolsets support multiple authentication methods: diff --git a/docs/data-sources/builtin-toolsets/grafanadashboards.md b/docs/data-sources/builtin-toolsets/grafanadashboards.md index 76f36a734d..54ab0610d0 100644 --- a/docs/data-sources/builtin-toolsets/grafanadashboards.md +++ b/docs/data-sources/builtin-toolsets/grafanadashboards.md @@ -104,6 +104,14 @@ For visual rendering, the [Grafana Image Renderer](https://grafana.com/grafana/p --8<-- "snippets/helm_upgrade_command.md" +```multi-instance +toolset: grafana/dashboards +name: Grafana +config: | + api_url: + api_key: +``` + ## Visual Rendering When the Grafana Image Renderer is available, HolmesGPT can take screenshots of dashboards and panels and analyze them using the LLM's vision capabilities. This is useful for: diff --git a/docs/data-sources/builtin-toolsets/grafanaloki.md b/docs/data-sources/builtin-toolsets/grafanaloki.md index b133fa1228..08f5523b74 100644 --- a/docs/data-sources/builtin-toolsets/grafanaloki.md +++ b/docs/data-sources/builtin-toolsets/grafanaloki.md @@ -96,6 +96,15 @@ toolsets: grafana_datasource_uid: ``` +```multi-instance +toolset: grafana/loki +name: Grafana Loki +config: | + api_url: http://grafana.monitoring.svc.cluster.local + api_key: + grafana_datasource_uid: +``` + ## Advanced Configuration ### SSL Verification diff --git a/docs/data-sources/builtin-toolsets/grafanatempo.md b/docs/data-sources/builtin-toolsets/grafanatempo.md index 36b408c16b..03727431a6 100644 --- a/docs/data-sources/builtin-toolsets/grafanatempo.md +++ b/docs/data-sources/builtin-toolsets/grafanatempo.md @@ -277,6 +277,15 @@ curl -s -H "Authorization: Bearer " https://. --8<-- "snippets/helm_upgrade_command.md" +```multi-instance +toolset: grafana/tempo +name: Grafana Tempo +config: | + api_url: + api_key: + grafana_datasource_uid: +``` + ## Advanced Configuration ### SSL Verification diff --git a/docs/data-sources/builtin-toolsets/mongodb-atlas.md b/docs/data-sources/builtin-toolsets/mongodb-atlas.md index c5e9e9ab07..ab38c6f0e2 100644 --- a/docs/data-sources/builtin-toolsets/mongodb-atlas.md +++ b/docs/data-sources/builtin-toolsets/mongodb-atlas.md @@ -58,6 +58,15 @@ By enabling this toolset, HolmesGPT can access MongoDB Atlas projects and proces project_id: "" ``` +```multi-instance +toolset: MongoDBAtlas +name: MongoDB Atlas +config: | + public_key: "" + private_key: "" + project_id: "" +``` + ## Setting up MongoDB Atlas API Keys 1. **Log into MongoDB Atlas** and navigate to your organization diff --git a/docs/data-sources/builtin-toolsets/newrelic.md b/docs/data-sources/builtin-toolsets/newrelic.md index adc4941efd..dd27da11c7 100644 --- a/docs/data-sources/builtin-toolsets/newrelic.md +++ b/docs/data-sources/builtin-toolsets/newrelic.md @@ -107,6 +107,14 @@ In the same UI, click your profile icon (bottom-left) → **Administration** → --8<-- "snippets/helm_upgrade_command.md" +```multi-instance +toolset: newrelic +name: New Relic +config: | + api_key: "" + account_id: "" +``` + ## Configuration Reference | Option | Default | Description | diff --git a/docs/data-sources/builtin-toolsets/prometheus.md b/docs/data-sources/builtin-toolsets/prometheus.md index 60086890d4..bd41aedaf1 100644 --- a/docs/data-sources/builtin-toolsets/prometheus.md +++ b/docs/data-sources/builtin-toolsets/prometheus.md @@ -50,6 +50,13 @@ kubectl get svc --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{ This will print all possible Prometheus service URLs in your cluster. Pick the one that matches your deployment. +```multi-instance +toolset: prometheus/metrics +name: Prometheus +config: | + prometheus_url: http://:9090 +``` + ## Specific Providers ### Coralogix Prometheus diff --git a/docs/data-sources/builtin-toolsets/servicenow.md b/docs/data-sources/builtin-toolsets/servicenow.md index 846049d192..fd42fa20a4 100644 --- a/docs/data-sources/builtin-toolsets/servicenow.md +++ b/docs/data-sources/builtin-toolsets/servicenow.md @@ -188,6 +188,14 @@ You should receive a JSON response. If you get an authentication error, check yo | `health_check_table` | `sys_user` | Table queried on startup to verify connectivity and permissions. Change this if your API key doesn't have access to the default table. | | `api_version` | `v2` | Table API version segment. Defaults to `v2` (`api/now/v2/table/...`). Set to empty string to use the unversioned path (`api/now/table/...`) if your instance doesn't support v2. | +```multi-instance +toolset: servicenow/tables +name: ServiceNow +config: | + api_url: + api_key: +``` + ## Capabilities | Tool Name | Description | diff --git a/docs/data-sources/builtin-toolsets/victorialogs.md b/docs/data-sources/builtin-toolsets/victorialogs.md index af924e141b..1919fb4e10 100644 --- a/docs/data-sources/builtin-toolsets/victorialogs.md +++ b/docs/data-sources/builtin-toolsets/victorialogs.md @@ -79,6 +79,13 @@ toolsets: external_url: https://logs.example.com ``` +```multi-instance +toolset: victorialogs +name: VictoriaLogs +config: | + api_url: http://victorialogs.monitoring.svc:9428 +``` + ## Common Use Cases ```text diff --git a/docs/data-sources/multi-instance-toolsets.md b/docs/data-sources/multi-instance-toolsets.md new file mode 100644 index 0000000000..efedc9772e --- /dev/null +++ b/docs/data-sources/multi-instance-toolsets.md @@ -0,0 +1,100 @@ +# Multiple Instances + +Many built-in toolsets can connect to **more than one instance** of the same system — for example two Grafana stacks (prod and staging), several Elasticsearch clusters, or per-team Datadog accounts. HolmesGPT queries the right one during an investigation, and you can ask it to compare across them. + +This page describes the shared behaviour. Each toolset's own page shows a ready-to-copy example in its **Multiple Instances** section. + +## Configuring instances + +A toolset that supports multiple instances accepts either a single flat config (the original format) **or** a list of `instances:`, each with a unique `name`: + +=== "Single instance (flat)" + + ```yaml + toolsets: + grafana/dashboards: + enabled: true + config: + api_url: https://prod-grafana.example.com + api_key: + ``` + +=== "Multiple instances" + + ```yaml + toolsets: + grafana/dashboards: + enabled: true + config: + instances: + - name: prod + api_url: https://prod-grafana.example.com + api_key: + - name: staging + api_url: https://staging-grafana.example.com + api_key: + ``` + +The fields allowed inside each `instances:` entry are exactly the toolset's normal config fields — see the toolset's own page for the full list. + +## Shared defaults + +Any config field set **outside** `instances:` (at the top level of `config:`) becomes a default that every instance inherits unless the instance overrides it. This keeps settings that are common to all instances in one place: + +```yaml +toolsets: + grafana/dashboards: + enabled: true + config: + verify_ssl: false # inherited by every instance below + instances: + - name: prod + api_url: https://prod-grafana.example.com + api_key: + - name: staging + api_url: https://staging-grafana.example.com + api_key: + verify_ssl: true # overrides the default for this instance only +``` + +Credentials are kept per-instance: a field group like `api_key` / `username` / `password` is only inherited from the top level when an instance provides none of them, so one instance's credentials never leak into another. + +## The `instance` parameter + +When **more than one** instance is configured, HolmesGPT adds an `instance` parameter to every tool of that toolset. The model chooses which instance to query and HolmesGPT routes the call to that instance's connection and credentials. You can steer it in your question: + +```bash +holmes ask "Check the prod Grafana for dashboards tagged 'kubernetes'" +``` + +With a **single** instance — whether configured flat or as a one-entry `instances:` list — no `instance` parameter is added and the tools behave exactly as before. + +## Discovering instances + +When more than one instance is configured, HolmesGPT also exposes a `_list_instances` tool (for example `grafana_dashboards_list_instances`) so the model can discover the configured instance names and their health before querying. + +## Health reporting + +Each instance is health-checked independently when the toolset loads. The toolset is considered available if **at least one** instance is healthy; instances that fail are reported individually so a single misconfigured or unreachable instance doesn't disable the others. + +## Backwards compatibility + +Existing single-instance configs keep working unchanged — `instances:` is purely additive. Upgrading to multiple instances only requires moving your existing fields into an `instances:` entry with a `name`. + +## Toolsets that support multiple instances + +- [Elasticsearch](builtin-toolsets/elasticsearch.md) (data and cluster) +- [Grafana Dashboards](builtin-toolsets/grafanadashboards.md), [Grafana Loki](builtin-toolsets/grafanaloki.md), [Grafana Tempo](builtin-toolsets/grafanatempo.md) +- [Prometheus](builtin-toolsets/prometheus.md) +- [Datadog](builtin-toolsets/datadog.md) (logs, metrics, traces, general) +- [Coralogix](builtin-toolsets/coralogix-logs.md) +- [VictoriaLogs](builtin-toolsets/victorialogs.md) +- [New Relic](builtin-toolsets/newrelic.md) +- [Azure SQL](builtin-toolsets/azure-sql.md) +- [MongoDB Atlas](builtin-toolsets/mongodb-atlas.md) +- [ServiceNow](builtin-toolsets/servicenow.md) +- [Confluence](builtin-toolsets/confluence.md) + +!!! note "RabbitMQ and Kafka" + + The [RabbitMQ](builtin-toolsets/rabbitmq.md) and [Kafka](builtin-toolsets/kafka.md) toolsets have their own multi-cluster configuration using a `clusters:` list (with a `cluster_id` / `kafka_cluster_name` tool parameter) rather than the generic `instances:` format described here. diff --git a/mkdocs.yml b/mkdocs.yml index ba14678456..cdccb42075 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -248,6 +248,9 @@ markdown_extensions: - name: robusta-region class: robusta-region format: !!python/name:docs.custom_fences.robusta_region_fence_format + - name: multi-instance + class: multi-instance + format: !!python/name:docs.custom_fences.multi_instance_fence_format - pymdownx.tabbed: alternate_style: true combine_header_slug: true From 904e97ea1244af29b11beefe685bf90c26d92e4d Mon Sep 17 00:00:00 2001 From: "avi@robusta.dev" Date: Mon, 1 Jun 2026 16:52:48 +0300 Subject: [PATCH 11/11] Restore Grafana username/password basic auth (lost in wrapper revert) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Grafana was reduced to single-instance for the generic multi_instance wrapper, master's HTTP basic-auth support was dropped — only api_key (Bearer) remained, so username/password configs silently sent no auth and got 401. Port basic auth from master onto the single-instance GrafanaConfig: - add username/password fields + validator (api_key XOR basic; user/pass together) - add build_auth() -> HTTPBasicAuth helper - thread auth= through dashboards (toolset_grafana), loki (loki_api) and tempo (grafana_tempo_api) request paths The wrapper's atomic auth group already merges a top-level username/password into each instance (or lets a per-instance api_key win). Adds basic-auth wire tests; updates tempo_api assertions for the new auth= kwarg. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: avi@robusta.dev --- holmes/plugins/toolsets/grafana/common.py | 37 ++++++++++++- .../toolsets/grafana/grafana_tempo_api.py | 4 ++ .../grafana/loki/toolset_grafana_loki.py | 3 ++ holmes/plugins/toolsets/grafana/loki_api.py | 3 ++ .../toolsets/grafana/toolset_grafana.py | 5 ++ .../grafana/test_grafana_multi_instance.py | 52 +++++++++++++++++++ .../grafana/test_grafana_tempo_api.py | 11 ++++ 7 files changed, 114 insertions(+), 1 deletion(-) diff --git a/holmes/plugins/toolsets/grafana/common.py b/holmes/plugins/toolsets/grafana/common.py index 97d96e80f7..b04df28fab 100644 --- a/holmes/plugins/toolsets/grafana/common.py +++ b/holmes/plugins/toolsets/grafana/common.py @@ -1,6 +1,7 @@ from typing import ClassVar, Dict, List, Optional -from pydantic import Field +from pydantic import Field, model_validator +from requests.auth import HTTPBasicAuth from holmes.utils.pydantic_utils import ToolsetConfig @@ -33,6 +34,17 @@ class GrafanaConfig(ToolsetConfig): description="Grafana API key for authentication", examples=["YOUR API KEY"], ) + username: Optional[str] = Field( + default=None, + title="Username", + description="Username for HTTP basic auth (use instead of api_key)", + ) + password: Optional[str] = Field( + default=None, + title="Password", + description="Password for HTTP basic auth (must be set together with username)", + json_schema_extra={"format": "password"}, + ) additional_headers: Optional[Dict[str, str]] = Field( default=None, title="Additional Headers", @@ -68,6 +80,29 @@ class GrafanaConfig(ToolsetConfig): description="Maximum number of retry attempts for failed Grafana API requests", ) + @model_validator(mode="after") + def _validate_grafana_auth(self) -> "GrafanaConfig": + if self.api_key and (self.username or self.password): + raise ValueError( + "Grafana config: use `api_key` OR `username` + `password`, not both" + ) + if bool(self.username) != bool(self.password): + raise ValueError( + "Grafana config: `username` and `password` must be set together" + ) + return self + + +def build_auth(config: "GrafanaConfig") -> Optional[HTTPBasicAuth]: + """Return HTTP basic auth from a config's username/password, or None. + + Used for Grafana instances that authenticate with basic auth instead of an + `api_key` Bearer token. + """ + if config.username and config.password: + return HTTPBasicAuth(config.username, config.password) + return None + def build_headers(api_key: Optional[str], additional_headers: Optional[Dict[str, str]]): headers = { diff --git a/holmes/plugins/toolsets/grafana/grafana_tempo_api.py b/holmes/plugins/toolsets/grafana/grafana_tempo_api.py index 4d963ff5b1..4a65178c54 100644 --- a/holmes/plugins/toolsets/grafana/grafana_tempo_api.py +++ b/holmes/plugins/toolsets/grafana/grafana_tempo_api.py @@ -9,6 +9,7 @@ from holmes.plugins.toolsets.grafana.common import ( GrafanaTempoConfig, + build_auth, build_headers, get_base_url, ) @@ -57,6 +58,7 @@ def __init__(self, config: GrafanaTempoConfig): self.config = config self.base_url = get_base_url(config) self.headers = build_headers(config.api_key, config.additional_headers) + self.auth = build_auth(config) def _make_request( self, @@ -104,6 +106,7 @@ def make_request(): response = requests.get( url, headers=self.headers, + auth=self.auth, params=params, timeout=timeout, verify=self.config.verify_ssl, @@ -156,6 +159,7 @@ def _do_request() -> requests.Response: response = requests.get( url, headers=self.headers, + auth=self.auth, timeout=self.config.timeout_seconds, verify=self.config.verify_ssl, ) diff --git a/holmes/plugins/toolsets/grafana/loki/toolset_grafana_loki.py b/holmes/plugins/toolsets/grafana/loki/toolset_grafana_loki.py index f7903b6fcc..238a8f12af 100644 --- a/holmes/plugins/toolsets/grafana/loki/toolset_grafana_loki.py +++ b/holmes/plugins/toolsets/grafana/loki/toolset_grafana_loki.py @@ -18,6 +18,7 @@ GrafanaCloudLokiConfig, GrafanaConfig, GrafanaLokiProxyConfig, + build_auth, get_base_url, ) from holmes.plugins.toolsets.grafana.loki_api import ( @@ -105,6 +106,7 @@ def health_check(self) -> Tuple[bool, str]: verify_ssl=c.verify_ssl, timeout=c.timeout_seconds, max_retries=c.max_retries, + auth=build_auth(c), ) except Exception as e: return False, f"Unable to connect to Loki.\n{str(e)}" @@ -179,6 +181,7 @@ def _invoke(self, params: dict, context: ToolInvokeContext) -> StructuredToolRes verify_ssl=config.verify_ssl, timeout=config.timeout_seconds, max_retries=config.max_retries, + auth=build_auth(config), ) explore_url = _build_grafana_loki_explore_url( diff --git a/holmes/plugins/toolsets/grafana/loki_api.py b/holmes/plugins/toolsets/grafana/loki_api.py index ac1bc3ca65..ea810e0b10 100644 --- a/holmes/plugins/toolsets/grafana/loki_api.py +++ b/holmes/plugins/toolsets/grafana/loki_api.py @@ -2,6 +2,7 @@ import backoff import requests # type: ignore +from requests.auth import HTTPBasicAuth from holmes.plugins.toolsets.grafana.common import build_headers @@ -38,6 +39,7 @@ def execute_loki_query( verify_ssl: bool = True, timeout: Optional[int] = None, max_retries: Optional[int] = None, + auth: Optional[HTTPBasicAuth] = None, ) -> List[Dict]: params = {"query": query, "limit": limit, "start": start, "end": end} effective_timeout = timeout if timeout is not None else 30 @@ -56,6 +58,7 @@ def _make_request(): response = requests.get( url, headers=build_headers(api_key=api_key, additional_headers=headers), + auth=auth, params=params, # type: ignore verify=verify_ssl, timeout=effective_timeout, diff --git a/holmes/plugins/toolsets/grafana/toolset_grafana.py b/holmes/plugins/toolsets/grafana/toolset_grafana.py index 2495bf4b01..deb67e0f8c 100644 --- a/holmes/plugins/toolsets/grafana/toolset_grafana.py +++ b/holmes/plugins/toolsets/grafana/toolset_grafana.py @@ -19,6 +19,7 @@ from holmes.plugins.toolsets.grafana.base_grafana_toolset import BaseGrafanaToolset from holmes.plugins.toolsets.grafana.common import ( GrafanaConfig, + build_auth, build_headers, get_base_url, ) @@ -134,6 +135,7 @@ def _try_add_render_tools(self) -> None: resp = requests.get( f"{base_url}/api/rendering/version", headers=headers, + auth=build_auth(config), timeout=10, verify=config.verify_ssl, ) @@ -157,6 +159,7 @@ def _try_add_render_tools(self) -> None: resp = requests.get( f"{base_url}/render/d-solo/nonexistent/_?panelId=1&width=100&height=100", headers=headers, + auth=build_auth(config), timeout=10, verify=config.verify_ssl, ) @@ -249,6 +252,7 @@ def _do_request() -> requests.Response: response = requests.get( url, headers=headers, + auth=build_auth(config), params=query_params, timeout=timeout, verify=config.verify_ssl, @@ -600,6 +604,7 @@ def _do_render_request() -> requests.Response: response = requests.get( url, headers=headers, + auth=build_auth(config), params=query_params, timeout=timeout, verify=config.verify_ssl, diff --git a/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py b/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py index d70c95ca65..39bf213c17 100644 --- a/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py +++ b/tests/plugins/toolsets/grafana/test_grafana_multi_instance.py @@ -114,6 +114,58 @@ def test_each_instance_calls_its_own_loki(self, instance, host, key): assert rsps.calls[-1].request.headers.get("Authorization") == f"Bearer {key}" +class TestGrafanaBasicAuth: + """Basic auth (username/password) restored from master. + + The Grafana toolset authenticates via `api_key` (Bearer) OR `username`+`password` + (HTTP basic auth). Verifies a top-level username/password falls through to every + instance and is sent as `Authorization: Basic ...` on the wire, while a per-instance + api_key still wins for the instance that sets it. + """ + + import base64 + + EU = "https://gba-eu.example.com" + US = "https://gba-us.example.com" + + def _mock(self, rsps): + _reg(rsps, responses.GET, r"https://gba-(eu|us)\.example\.com/api/(dashboards/tags|search).*", []) + + def _build(self, rsps): + self._mock(rsps) + ts = multi_instance(GrafanaToolset) + ok, _ = ts.prerequisites_callable( + { + "username": "admin", + "password": "prom-operator", + "instances": [ + {"name": "eu", "api_url": self.EU}, + {"name": "us", "api_url": self.US, "api_key": "tok_us"}, + ], + } + ) + assert ok is True + return ts + + def test_global_basic_auth_falls_through(self): + expected = "Basic " + self.base64.b64encode(b"admin:prom-operator").decode() + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "grafana_search_dashboards") + tool.invoke({"query": "x", INSTANCE_PARAM_NAME: "eu"}, create_mock_tool_invoke_context()) + last = rsps.calls[-1].request + assert last.headers.get("Authorization") == expected + + def test_per_instance_api_key_overrides_global_basic_auth(self): + with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: + ts = self._build(rsps) + tool = next(t for t in ts.tools if t.name == "grafana_search_dashboards") + tool.invoke({"query": "x", INSTANCE_PARAM_NAME: "us"}, create_mock_tool_invoke_context()) + last = rsps.calls[-1].request + # instance set its own api_key -> Bearer, NOT inherited basic auth + assert last.headers.get("Authorization") == "Bearer tok_us" + + class TestGrafanaTempo: EU = "http://tempo-eu.svc:3200" US = "http://tempo-us.svc:3200" diff --git a/tests/plugins/toolsets/grafana/test_grafana_tempo_api.py b/tests/plugins/toolsets/grafana/test_grafana_tempo_api.py index db29dde870..6d2a214b4b 100644 --- a/tests/plugins/toolsets/grafana/test_grafana_tempo_api.py +++ b/tests/plugins/toolsets/grafana/test_grafana_tempo_api.py @@ -54,6 +54,7 @@ def test_query_echo_endpoint(self, mock_get, api): mock_get.assert_called_once_with( f"{api.base_url}/api/echo", headers=api.headers, + auth=None, timeout=30, verify=True, ) @@ -84,6 +85,7 @@ def test_query_trace_by_id_v2(self, mock_get, api): f"{api.base_url}/api/v2/traces/123abc", headers=api.headers, params={"start": "1000", "end": "2000"}, + auth=None, timeout=30, verify=True, ) @@ -103,6 +105,7 @@ def test_query_trace_by_id_v2_no_time_params(self, mock_get, api): f"{api.base_url}/api/v2/traces/123abc", headers=api.headers, params={}, + auth=None, timeout=30, verify=True, ) @@ -139,6 +142,7 @@ def test_search_traces_by_tags(self, mock_get, api): f"{api.base_url}/api/search", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -171,6 +175,7 @@ def test_search_traces_by_query(self, mock_get, api): f"{api.base_url}/api/search", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -205,6 +210,7 @@ def test_search_tag_names_v2(self, mock_get, api): f"{api.base_url}/api/v2/search/tags", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -240,6 +246,7 @@ def test_search_tag_values_v2(self, mock_get, api): f"{api.base_url}/api/v2/search/tag/resource.service.name/values", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -270,6 +277,7 @@ def test_query_metrics_instant(self, mock_get, api): f"{api.base_url}/api/metrics/query", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -306,6 +314,7 @@ def test_query_metrics_range(self, mock_get, api): f"{api.base_url}/api/metrics/query_range", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -330,6 +339,7 @@ def test_query_metrics_instant_required_only(self, mock_get, api): f"{api.base_url}/api/metrics/query", headers=api.headers, params=expected_params, + auth=None, timeout=30, verify=True, ) @@ -378,6 +388,7 @@ def test_special_characters_in_path_params(self, mock_get, api): expected_url, headers=api.headers, params={}, + auth=None, timeout=30, verify=True, )