Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion keep/providers/keep_provider/keep_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def _query(
raise ValueError("Filter is required for version 2")
try:
alerts = search_engine.search_alerts_by_cel(
cel_query=filter, limit=limit or 100, timeframe=int(time_delta)
cel_query=filter, limit=limit or 100, timeframe=float(time_delta)
)
except Exception as e:
self.logger.exception(
Expand Down
19 changes: 16 additions & 3 deletions keep/searchengine/searchengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from keep.api.models.time_stamp import TimeStampFilter
from keep.api.utils.enrichment_helpers import convert_db_alerts_to_dto_alerts
from keep.rulesengine.rulesengine import RulesEngine

from datetime import datetime, timezone

class SearchMode(enum.Enum):
"""The search mode for the search engine"""
Expand Down Expand Up @@ -84,9 +84,8 @@ def _get_last_alerts(
def search_alerts_by_cel(
self,
cel_query: str,
alerts: list[AlertDto] = None,
limit: int = 1000,
timeframe: int = 0,
timeframe: float = 0,
) -> list[AlertDto]:
"""Search for alerts based on a CEL query

Expand All @@ -97,6 +96,20 @@ def search_alerts_by_cel(
Returns:
list[AlertDto]: The list of alerts that match the query
"""
cel_query = (cel_query or "").strip()

if timeframe:
timeframe_in_seconds = timeframe * 24 * 60 * 60
time_ago = datetime.fromtimestamp(
datetime.now().timestamp() - timeframe_in_seconds
)
iso_utc_date = time_ago.astimezone(timezone.utc).isoformat()
cel_list = [
f"lastReceived >= '{iso_utc_date}'",
cel_query,
]
cel_query = " && ".join(f"({cel})" for cel in cel_list if cel)

self.logger.info("Searching alerts by CEL")
db_alerts, _ = query_last_alerts(
tenant_id=self.tenant_id,
Expand Down
42 changes: 42 additions & 0 deletions tests/test_search_alerts.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import datetime
import os
import time
from unittest.mock import patch
import freezegun

import pytest

Expand All @@ -9,6 +12,7 @@
from keep.api.models.alert import AlertDto
from keep.api.models.db.mapping import MappingRule
from keep.api.models.db.preset import PresetSearchQuery as SearchQuery
from keep.api.models.query import QueryDto
from keep.searchengine.searchengine import SearchEngine
from tests.fixtures.client import client, setup_api_key, test_app # noqa

Expand Down Expand Up @@ -1441,6 +1445,44 @@ def test_alerts_enrichment_in_search(db_session, client, test_app, elastic_clien
assert sorted(db_filtered_alert["enriched_fields"]) == ["note", "service"]


@freezegun.freeze_time("2025-06-18 17:51:23")
@patch("keep.searchengine.searchengine.query_last_alerts", return_value=([], 0))
@pytest.mark.parametrize(
"cel_query, timeframe, limit, expected_cel",
[
(None, 0.1667, 223, "(lastReceived >= '2025-06-18T11:51:20.120000+00:00')"),
(
"providerType != 'gcp'",
0.1667,
500,
"(lastReceived >= '2025-06-18T11:51:20.120000+00:00') && (providerType != 'gcp')",
),
("providerType != 'gcp'", None, 2, "providerType != 'gcp'"),
(" providerType != 'gcp' ", None, 2, "providerType != 'gcp'"),
(
"name.contains('CPU')",
0.5,
2,
"(lastReceived >= '2025-06-18T03:51:23+00:00') && (name.contains('CPU'))",
),
],
)
def test_search_alerts_by_cel(
mock_query_last_alerts, cel_query, timeframe, limit, expected_cel
):
actual_alerts = SearchEngine(tenant_id=SINGLE_TENANT_UUID).search_alerts_by_cel(
cel_query=cel_query, timeframe=timeframe, limit=limit
)
assert actual_alerts == []
mock_query_last_alerts.assert_called_once_with(
tenant_id=SINGLE_TENANT_UUID,
query=QueryDto(
cel=expected_cel,
limit=limit,
),
)


"""
COMMENTED OUT UNTIL WE FIGURE ' something in list'

Expand Down
Loading