Skip to content

Commit

Permalink
Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Matvey-Kuk committed Dec 26, 2024
1 parent 42abec3 commit 7efd63d
Showing 1 changed file with 45 additions and 26 deletions.
71 changes: 45 additions & 26 deletions keep/api/routes/workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from sqlmodel import Session

from keep.api.core.db import (
get_alert_by_event_id,
get_installed_providers,
get_last_workflow_workflow_to_alert_executions,
get_session,
Expand All @@ -36,6 +37,7 @@
WorkflowExecutionLogsDTO,
WorkflowToAlertExecutionDTO,
)
from keep.api.utils.enrichment_helpers import convert_db_alerts_to_dto_alerts
from keep.api.utils.pagination import WorkflowExecutionsPaginatedResultsDto
from keep.identitymanager.authenticatedentity import AuthenticatedEntity
from keep.identitymanager.identitymanagerfactory import IdentityManagerFactory
Expand Down Expand Up @@ -169,6 +171,8 @@ def export_workflows(
)
async def run_workflow(
workflow_id: str,
event_type: Optional[str] = Query(None),
event_id: Optional[str] = Query(None),
body: Optional[Dict[Any, Any]] = Body(None),
authenticated_entity: AuthenticatedEntity = Depends(
IdentityManagerFactory.get_auth_verifier(["write:workflows"])
Expand All @@ -182,41 +186,55 @@ async def run_workflow(
if not validators.uuid(workflow_id):
logger.info("Workflow ID is not a UUID, trying to get the ID by name")
workflow_id = getattr(get_workflow_by_name(tenant_id, workflow_id), "id", None)

workflowmanager = WorkflowManager.get_instance()

# Finally, run it
try:

if body.get("type", "alert") == "alert":
event_class = AlertDto
# Handle replay from query parameters
if event_type and event_id:
if event_type == "alert":
# Fetch alert from your alert store
alert_db = get_alert_by_event_id(tenant_id, event_id)
event = convert_db_alerts_to_dto_alerts([alert_db])[0]
elif event_type == "incident":
# SHAHAR: TODO
raise NotImplementedError("Incident replay is not supported yet")
else:
raise HTTPException(
status_code=400,
detail=f"Invalid event type: {event_type}",
)
else:
event_class = IncidentDto

event_body = body.get("body", {}) or body

# if its event that was triggered by the UI with the Modal
fingerprint = event_body.get("fingerprint", "")
if (fingerprint and "test-workflow" in fingerprint) or not body:
# some random
event_body["id"] = event_body.get("fingerprint", "manual-run")
event_body["name"] = event_body.get("fingerprint", "manual-run")
event_body["lastReceived"] = datetime.datetime.now(
tz=datetime.timezone.utc
).isoformat()
if "source" in event_body and not isinstance(event_body["source"], list):
event_body["source"] = [event_body["source"]]
try:
event = event_class(**event_body)
except TypeError:
raise HTTPException(
status_code=400,
detail="Invalid event format",
# Handle regular run from body
event_body = body.get("body", {}) or body
event_class = (
AlertDto if body.get("type", "alert") == "alert" else IncidentDto
)

# Handle UI triggered events
fingerprint = event_body.get("fingerprint", "")
if (fingerprint and "test-workflow" in fingerprint) or not body:
event_body["id"] = event_body.get("fingerprint", "manual-run")
event_body["name"] = event_body.get("fingerprint", "manual-run")
event_body["lastReceived"] = datetime.datetime.now(
tz=datetime.timezone.utc
).isoformat()
if "source" in event_body and not isinstance(
event_body["source"], list
):
event_body["source"] = [event_body["source"]]

try:
event = event_class(**event_body)
except TypeError:
raise HTTPException(
status_code=400,
detail="Invalid event format",
)

workflow_execution_id = await workflowmanager.scheduler.handle_manual_event_workflow(
workflow_id, tenant_id, created_by, event
)

except Exception as e:
logger.exception(
"Failed to run workflow",
Expand All @@ -226,6 +244,7 @@ async def run_workflow(
status_code=500,
detail=f"Failed to run workflow {workflow_id}: {e}",
)

logger.info(
"Workflow ran successfully",
extra={
Expand Down

0 comments on commit 7efd63d

Please sign in to comment.