Skip to content

Commit

Permalink
fix: One more attempt to return posthog (keephq#2387)
Browse files Browse the repository at this point in the history
  • Loading branch information
Matvey-Kuk authored Nov 4, 2024
1 parent 520c842 commit e5500b2
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 19 deletions.
2 changes: 2 additions & 0 deletions keep/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import keep.api.logging
from keep.api.api import AUTH_TYPE
from keep.api.core.db_on_start import migrate_db, try_create_single_tenant
from keep.api.core.report_uptime import launch_uptime_reporting
from keep.api.core.dependencies import SINGLE_TENANT_UUID
from keep.identitymanager.identitymanagerfactory import IdentityManagerTypes

Expand All @@ -18,6 +19,7 @@ def on_starting(server=None):
logger.info("Keep server starting")

migrate_db()
launch_uptime_reporting()

# Create single tenant if it doesn't exist
if AUTH_TYPE in [
Expand Down
45 changes: 45 additions & 0 deletions keep/api/core/posthog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import os
import uuid
import posthog
import requests
from posthog import Posthog
from importlib import metadata

try:
KEEP_VERSION = metadata.version("keep")
except metadata.PackageNotFoundError:
try:
KEEP_VERSION = metadata.version("keephq")
except metadata.PackageNotFoundError:
KEEP_VERSION = os.environ.get("KEEP_VERSION", "unknown")

POSTHOG_DISABLED = os.getenv("POSTHOG_DISABLED", "false") == "true"
RANDOM_TENANT_ID_PERSISTENT_WITHIN_LAUNCH = uuid.uuid4()

if POSTHOG_DISABLED:
posthog.disabled = True

POSTHOG_API_KEY = (
os.getenv("POSTHOG_API_KEY")
or "phc_muk9qE3TfZsX3SZ9XxX52kCGJBclrjhkP9JxAQcm1PZ" # It's a public PH API key, not a leaked secret ;)
)
posthog_client = Posthog(
api_key=POSTHOG_API_KEY,
host="https://app.posthog.com",
)


def is_posthog_reachable():
try:
Posthog(
api_key=POSTHOG_API_KEY,
host="https://app.posthog.com",
feature_flags_request_timeout_seconds=3,
sync_mode=True # Explicitly to trigger exception if it's not reachable.
).capture(
RANDOM_TENANT_ID_PERSISTENT_WITHIN_LAUNCH,
"connectivity_check",
)
return True
except requests.exceptions.ConnectionError:
return False
45 changes: 45 additions & 0 deletions keep/api/core/report_uptime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import asyncio
import logging
import threading
from keep.api.core.posthog import (
posthog_client,
is_posthog_reachable,
KEEP_VERSION,
POSTHOG_DISABLED,
RANDOM_TENANT_ID_PERSISTENT_WITHIN_LAUNCH
)

logger = logging.getLogger(__name__)
UPTIME_REPORTING_CADENCE = 60 * 60 # 1 hour

async def report_uptime_to_posthog():
"""
Reports uptime and current version to PostHog every hour.
Should be lunched in a separate thread.
"""
while True:
posthog_client.capture(
RANDOM_TENANT_ID_PERSISTENT_WITHIN_LAUNCH,
"backend_status",
properties={
"status": "up",
"keep_version": KEEP_VERSION,
},
)
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():
"""
Running async uptime reporting as a sub-thread.
"""
if not POSTHOG_DISABLED:
if is_posthog_reachable():
thread = threading.Thread(target=asyncio.run, args=(report_uptime_to_posthog(), ))
thread.start()
logger.info("Uptime Reporting to Posthog launched.")
else:
logger.info("Reporting to Posthog not launched because it's not reachable.")
else:
logger.info("Posthog reporting is disabled so no uptime reporting.")
18 changes: 1 addition & 17 deletions keep/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import sys
import typing
import uuid
import posthog
from collections import OrderedDict
from importlib import metadata

Expand All @@ -14,14 +13,14 @@
import yaml
from dotenv import find_dotenv, load_dotenv
from prettytable import PrettyTable
from posthog import Posthog

from keep.api.core.db_on_start import try_create_single_tenant
from keep.api.core.dependencies import SINGLE_TENANT_UUID
from keep.cli.click_extensions import NotRequiredIf
from keep.providers.providers_factory import ProvidersFactory
from keep.workflowmanager.workflowmanager import WorkflowManager
from keep.workflowmanager.workflowstore import WorkflowStore
from keep.api.core.posthog import posthog_client

load_dotenv(find_dotenv())

Expand All @@ -33,20 +32,6 @@
except metadata.PackageNotFoundError:
KEEP_VERSION = os.environ.get("KEEP_VERSION", "unknown")

POSTHOG_DISABLED = os.getenv("POSTHOG_DISABLED", "false") == "true"

if POSTHOG_DISABLED:
posthog.disabled = True

POSTHOG_API_KEY = (
os.getenv("POSTHOG_API_KEY")
or "phc_muk9qE3TfZsX3SZ9XxX52kCGJBclrjhkP9JxAQcm1PZ"
)
posthog_client = Posthog(
api_key=POSTHOG_API_KEY,
host="https://app.posthog.com",
)

logging_config = {
"version": 1,
"disable_existing_loggers": False,
Expand Down Expand Up @@ -1527,7 +1512,6 @@ def simulate(info: Info, provider_type: str, params: list[str]):
else:
click.echo(click.style("Alert simulated successfully", bold=True))


@cli.group()
@pass_info
def auth(info: Info):
Expand Down
2 changes: 0 additions & 2 deletions tests/fixtures/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

@pytest.fixture
def test_app(monkeypatch, request):
monkeypatch.setenv("POSTHOG_DISABLED", "true")

# Check if request.param is a dict or a string
if isinstance(request.param, dict):
# Set environment variables based on the provided dictionary
Expand Down

0 comments on commit e5500b2

Please sign in to comment.