Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: one more attempt to return posthog #2386

Closed
Closed
Show file tree
Hide file tree
Changes from all 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: 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"
)
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
47 changes: 47 additions & 0 deletions keep/api/core/report_uptime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import time
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 = 5

def report_uptime_to_posthog_blocking():
"""
It's a blocking function that 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.")
time.sleep(UPTIME_REPORTING_CADENCE)

def launch_uptime_reporting():
"""
Running uptime reporting as a sub-thread. Important to avoid
Launching at app.on_start() caused misterious isses on production, see:
Check: https://github.com/keephq/keep/pull/2366
Reverted: https://github.com/keephq/keep/pull/2384
"""
if not POSTHOG_DISABLED:
if is_posthog_reachable():
thread = threading.Thread(target=report_uptime_to_posthog_blocking)
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.")
2 changes: 1 addition & 1 deletion keep/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
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 Down Expand Up @@ -1527,7 +1528,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
Loading