Skip to content

Commit

Permalink
fix: workflow last run time (#2286)
Browse files Browse the repository at this point in the history
  • Loading branch information
shahargl authored Oct 24, 2024
1 parent 580b567 commit 28df747
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 9 deletions.
15 changes: 7 additions & 8 deletions examples/workflows/cron-digest-alerts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ workflow:
id: alerts-daily-digest
description: run alerts digest twice a day (on 11:00 and 14:00)
triggers:
- type: manual
- type: interval
cron: 0 11,14 * * *
steps:
Expand All @@ -10,18 +11,16 @@ workflow:
provider:
type: keep
with:
filters:
# filter out alerts that are closed
- key: status
value: open
version: 2
filter: "status == 'firing'"
timerange:
from: "{{ state.workflows.alerts-daily-digest.last_run_time }}"
from: "{{ last_workflow_run_time }}"
to: now
actions:
- name: send-digest
foreach: "{{ steps.get-alerts.results }}"
provider:
type: slack
config: "{{ providers.slack }}"
type: console
config: "{{ providers.console }}"
with:
message: "Open alert: {{ foreach.value.name }}"
message: "Open alerts: {{ foreach.value.name }}"
3 changes: 3 additions & 0 deletions keep/contextmanager/contextmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(self, tenant_id, workflow_id=None, workflow_execution_id=None):
self.click_context = {}
# last workflow context
self.last_workflow_execution_results = {}
self.last_workflow_run_time = None
if self.workflow_id:
try:
last_workflow_execution = get_last_workflow_execution_by_workflow_id(
Expand All @@ -44,6 +45,7 @@ def __init__(self, tenant_id, workflow_id=None, workflow_execution_id=None):
self.last_workflow_execution_results = (
last_workflow_execution.results
)
self.last_workflow_run_time = last_workflow_execution.started
except Exception:
self.logger.exception("Failed to get last workflow execution")
pass
Expand Down Expand Up @@ -130,6 +132,7 @@ def get_full_context(self, exclude_providers=False, exclude_env=False):
"foreach": self.foreach_context,
"event": self.event_context,
"last_workflow_results": self.last_workflow_execution_results,
"last_workflow_run_time": self.last_workflow_run_time,
"alert": self.event_context, # this is an alias so workflows will be able to use alert.source
"incident": self.incident_context, # this is an alias so workflows will be able to use alert.source
"consts": self.consts_context,
Expand Down
31 changes: 31 additions & 0 deletions keep/providers/keep_provider/keep_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import logging
from datetime import datetime, timezone

from keep.api.core.db import get_alerts_with_filters
from keep.api.models.alert import AlertDto
Expand All @@ -28,6 +29,31 @@ def dispose(self):
"""
pass

def _calculate_time_delta(self, timerange=None, default_time_range=1):
"""Calculate time delta in days from timerange dict."""
if not timerange or "from" not in timerange:
return default_time_range # default value

from_time_str = timerange["from"]
to_time_str = timerange.get("to", "now")

# Parse from_time and ensure it's timezone-aware
from_time = datetime.fromisoformat(from_time_str.replace("Z", "+00:00"))
if from_time.tzinfo is None:
from_time = from_time.replace(tzinfo=timezone.utc)

# Handle 'to' time
if to_time_str == "now":
to_time = datetime.now(timezone.utc)
else:
to_time = datetime.fromisoformat(to_time_str.replace("Z", "+00:00"))
if to_time.tzinfo is None:
to_time = to_time.replace(tzinfo=timezone.utc)

# Calculate difference in days
delta = (to_time - from_time).total_seconds() / (24 * 3600) # convert to days
return delta

def _query(self, filters=None, version=1, distinct=True, time_delta=1, **kwargs):
"""
Query Keep for alerts.
Expand All @@ -40,6 +66,11 @@ def _query(self, filters=None, version=1, distinct=True, time_delta=1, **kwargs)
"time_delta": time_delta,
},
)
# if timerange is provided, calculate time delta
if kwargs.get("timerange"):
time_delta = self._calculate_time_delta(
timerange=kwargs.get("timerange"), default_time_range=time_delta
)
if version == 1:
# filters are mandatory for version 1
if not filters:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "keep"
version = "0.27.4"
version = "0.27.5"
description = "Alerting. for developers, by developers."
authors = ["Keep Alerting LTD"]
readme = "README.md"
Expand Down

0 comments on commit 28df747

Please sign in to comment.