Skip to content

Commit

Permalink
Analytics from the backend
Browse files Browse the repository at this point in the history
  • Loading branch information
Matvey-Kuk committed Nov 20, 2024
1 parent 98810dd commit 7f293ca
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
24 changes: 24 additions & 0 deletions keep/api/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4502,3 +4502,27 @@ def get_or_creat_posthog_instance_id(
session.commit()
session.refresh(system)
return system.value

def get_activity_report(
session: Optional[Session] = None
):
from keep.api.models.db.user import User

last_24_hours = datetime.utcnow() - timedelta(hours=24)
activity_report = {}
with Session(engine) as session:
activity_report['tenant_count'] = session.query(Tenant).count()
activity_report['providers_count'] = session.query(Provider).count()
activity_report['users_count'] = session.query(User).count()
activity_report['last_24_hours_incident_count'] = session.query(Incident).filter(
Incident.creation_time >= last_24_hours).count()
activity_report['last_24_hours_alerts_count'] = session.query(Alert).filter(
Alert.timestamp >= last_24_hours).count()
activity_report['last_24_hours_rules_created'] = session.query(Rule).filter(
Rule.creation_time >= last_24_hours).count()
activity_report['last_24_hours_workflows_created'] = session.query(Workflow).filter(
Workflow.creation_time >= last_24_hours).count()
activity_report['last_24_hours_workflows_executed'] = session.query(WorkflowExecution).filter(
WorkflowExecution.started >= last_24_hours).count()

return activity_report
18 changes: 12 additions & 6 deletions keep/api/core/report_uptime.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
import logging
import threading
from keep.api.core.db import get_or_creat_posthog_instance_id
from keep.api.core.db import get_activity_report, get_or_creat_posthog_instance_id
from keep.api.core.posthog import (
posthog_client,
is_posthog_reachable,
Expand All @@ -18,16 +18,22 @@ async def report_uptime_to_posthog():
Should be lunched in a separate thread.
"""
while True:
start_time = asyncio.get_event_loop().time()
properties = {
"status": "up",
"keep_version": KEEP_VERSION,
**get_activity_report(),
}
end_time = asyncio.get_event_loop().time()
properties["db_request_duration_ms"] = int((end_time - start_time) * 1000)
posthog_client.capture(
get_or_creat_posthog_instance_id(),
"backend_status",
properties={
"status": "up",
"keep_version": KEEP_VERSION,
},
properties=properties,
)
posthog_client.flush()
logger.info("Uptime reported to PostHog.")
# Important to keep it async, otherwise will clog main gunicorn thread and cause timeouts.

await asyncio.sleep(UPTIME_REPORTING_CADENCE)

def launch_uptime_reporting_thread() -> threading.Thread | None:
Expand Down

0 comments on commit 7f293ca

Please sign in to comment.