Skip to content

Commit

Permalink
feat: move config to global directory (keephq#582)
Browse files Browse the repository at this point in the history
  • Loading branch information
shahargl authored Nov 28, 2023
1 parent 572da57 commit 6bb895f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 28 deletions.
44 changes: 29 additions & 15 deletions keep/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import sys
import typing
import uuid
from collections import OrderedDict
from importlib import metadata

Expand All @@ -16,15 +17,13 @@
from keep.api.core.db import try_create_single_tenant
from keep.api.core.dependencies import SINGLE_TENANT_UUID
from keep.cli.click_extensions import NotRequiredIf
from keep.posthog.posthog import get_posthog_client, get_random_user_id
from keep.posthog.posthog import get_posthog_client
from keep.workflowmanager.workflowmanager import WorkflowManager
from keep.workflowmanager.workflowstore import WorkflowStore

load_dotenv(find_dotenv())
posthog_client = get_posthog_client()

RANDOM_USER_ID = get_random_user_id()


logging_config = {
"version": 1,
Expand Down Expand Up @@ -55,7 +54,12 @@
logger = logging.getLogger(__name__)


DEFAULT_CONF_FILE = ".keep.yaml"
def get_default_conf_file_path():
DEFAULT_CONF_FILE = ".keep.yaml"
from pathlib import Path

home = str(Path.home())
return os.path.join(home, DEFAULT_CONF_FILE)


def make_keep_request(method, url, **kwargs):
Expand Down Expand Up @@ -107,6 +111,13 @@ def set_config(self, keep_config: str):
or os.getenv("KEEP_API_URL")
or Info.KEEP_MANAGED_API_URL
)
self.random_user_id = self.config.get("random_user_id")
# if we don't have a random user id, we create one and keep it on the config file
if not self.random_user_id:
self.random_user_id = str(uuid.uuid4())
self.config["random_user_id"] = self.random_user_id
with open(file=keep_config, mode="w") as f:
yaml.dump(self.config, f)

arguments = sys.argv

Expand Down Expand Up @@ -158,18 +169,19 @@ def set_config(self, keep_config: str):
@click.option(
"--keep-config",
"-c",
help=f"The path to the keep config file (default {DEFAULT_CONF_FILE}",
help=f"The path to the keep config file (default {get_default_conf_file_path()}",
required=False,
default=f"{DEFAULT_CONF_FILE}",
default=f"{get_default_conf_file_path()}",
)
@pass_info
@click.pass_context
def cli(ctx, info: Info, verbose: int, json: bool, keep_config: str):
"""Run Keep CLI."""
# https://posthog.com/tutorials/identifying-users-guide#identifying-and-setting-user-ids-for-every-other-library
# random user id
info.set_config(keep_config)
posthog_client.capture(
RANDOM_USER_ID,
info.random_user_id,
"keep-cli-started",
properties={
"args": sys.argv,
Expand All @@ -184,7 +196,6 @@ def cli(ctx, info: Info, verbose: int, json: bool, keep_config: str):
logging_config["handlers"]["default"]["formatter"] = "json"
logging.config.dictConfig(logging_config)
info.verbose = verbose
info.set_config(keep_config)
info.json = json

@ctx.call_on_close
Expand Down Expand Up @@ -212,10 +223,13 @@ def config(info: Info):
)
if not api_key:
api_key = "localhost"
with open(f"{DEFAULT_CONF_FILE}", "w") as f:
with open(f"{get_default_conf_file_path()}", "w") as f:
f.write(f"api_key: {api_key}\n")
f.write(f"keep_api_url: {keep_url}\n")
click.echo(click.style(f"Config file created at {DEFAULT_CONF_FILE}", bold=True))
f.write(f"random_user_id: {info.random_user_id}\n")
click.echo(
click.style(f"Config file created at {get_default_conf_file_path()}", bold=True)
)


@cli.command()
Expand Down Expand Up @@ -319,7 +333,7 @@ def run(
"""Run a workflow."""
logger.debug(f"Running alert in {alerts_directory or alert_url}")
posthog_client.capture(
RANDOM_USER_ID,
info.random_user_id,
"keep-run-alert-started",
properties={
"args": sys.argv,
Expand All @@ -338,7 +352,7 @@ def run(
except KeyboardInterrupt:
logger.info("Keep stopped by user, stopping the scheduler")
posthog_client.capture(
RANDOM_USER_ID,
info.random_user_id,
"keep-run-stopped-by-user",
properties={
"args": sys.argv,
Expand All @@ -348,7 +362,7 @@ def run(
logger.info("Scheduler stopped")
except Exception as e:
posthog_client.capture(
RANDOM_USER_ID,
info.random_user_id,
"keep-run-unexpected-error",
properties={
"args": sys.argv,
Expand All @@ -360,7 +374,7 @@ def run(
raise e
sys.exit(1)
posthog_client.capture(
RANDOM_USER_ID,
info.random_user_id,
"keep-run-alert-finished",
properties={
"args": sys.argv,
Expand Down Expand Up @@ -1090,7 +1104,7 @@ def start(self):

api_key = api_key_resp.json().get("apiKey")
# keep it in the config file
with open(f"{DEFAULT_CONF_FILE}", "w") as f:
with open(f"{get_default_conf_file_path()}", "w") as f:
f.write(f"api_key: {api_key}\n")
# Authenticated successfully
print("Authenticated successfully!")
Expand Down
13 changes: 0 additions & 13 deletions keep/posthog/posthog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,6 @@
posthog.disabled = True


def get_random_user_id():
if os.path.exists("RANDOM_USER_ID"):
with open("RANDOM_USER_ID") as f:
return f.read()
else:
import uuid

random_user_id = str(uuid.uuid4())
with open("RANDOM_USER_ID", "w") as f:
f.write(random_user_id)
return random_user_id


def get_posthog_client():
posthog_api_key = (
os.getenv("POSTHOG_API_KEY")
Expand Down

0 comments on commit 6bb895f

Please sign in to comment.