Skip to content

Commit 054e88c

Browse files
Remove refinery-config (#266)
* Initial config addition * adjust services * edits * Adjust config route * remove check_config_service * move implementation * Change order of config * Access values directly * adjust fastapi * Add new routes for config * edit * edit * add direct default route for base_config * Fix: outdated lines * Fix: unnecessary async * Remove unused service * Moves change config to misc routing * remove org createino endpoint for os version * Removes unused config parts * remove unused notify services * Removes auto notify on startup --------- Co-authored-by: JWittmeyer <jens.wittmeyer@kern.ai>
1 parent 8007116 commit 054e88c

26 files changed

+208
-395
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,4 +143,6 @@ project_export*
143143
tmp/*
144144
!tmp/.gitkeep
145145

146-
logs/*
146+
logs/*
147+
148+
current_config.json

api/misc.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
1-
from controller.misc import config_service
21
from starlette.endpoints import HTTPEndpoint
32
from starlette.responses import JSONResponse
4-
from starlette import status
3+
from fastapi import Request
54

5+
from config_handler import (
6+
full_config_json,
7+
)
68

7-
class IsManagedRest(HTTPEndpoint):
8-
def get(self, request) -> JSONResponse:
9-
is_managed = config_service.get_config_value("is_managed")
10-
return JSONResponse(is_managed, status_code=status.HTTP_200_OK)
119

12-
class IsDemoRest(HTTPEndpoint):
13-
def get(self, request) -> JSONResponse:
14-
is_managed = config_service.get_config_value("is_demo")
15-
return JSONResponse(is_managed, status_code=status.HTTP_200_OK)
10+
class FullConfigRest(HTTPEndpoint):
11+
def get(self, request: Request) -> JSONResponse:
12+
return full_config_json()

api/transfer.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
from controller.upload_task import manager as upload_task_manager
2929
from controller.auth import manager as auth_manager
3030
from controller.transfer import association_transfer_manager
31-
from controller.auth import manager as auth
3231
from controller.project import manager as project_manager
3332
from controller.attribute import manager as attribute_manager
3433

@@ -135,7 +134,6 @@ def get(self, request) -> JSONResponse:
135134

136135
class PrepareFileImport(HTTPEndpoint):
137136
async def post(self, request) -> JSONResponse:
138-
auth.check_is_demo_without_info()
139137
project_id = request.path_params["project_id"]
140138
request_body = await request.json()
141139

@@ -168,7 +166,6 @@ async def post(self, request) -> JSONResponse:
168166

169167
class JSONImport(HTTPEndpoint):
170168
async def post(self, request) -> JSONResponse:
171-
auth.check_is_demo_without_info()
172169
project_id = request.path_params["project_id"]
173170
request_body = await request.json()
174171
user_id = request_body["user_id"]
@@ -272,7 +269,6 @@ async def post(self, request) -> JSONResponse:
272269

273270
class UploadTaskInfo(HTTPEndpoint):
274271
def get(self, request) -> JSONResponse:
275-
auth.check_is_demo_without_info()
276272
project_id = request.path_params["project_id"]
277273
task_id = request.path_params["task_id"]
278274
user_id = request.query_params["user_id"]

app.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import logging
2-
32
from fastapi import FastAPI
43
from api.healthcheck import Healthcheck
54
from starlette.middleware import Middleware
6-
from api.misc import IsDemoRest, IsManagedRest
5+
from api.misc import (
6+
FullConfigRest,
7+
)
78
from api.project import ProjectDetails
89
from api.transfer import (
910
AssociationsImport,
@@ -16,6 +17,9 @@
1617
CognitionImport,
1718
CognitionPrepareProject,
1819
)
20+
from config_handler import (
21+
init_config,
22+
)
1923
from fast_api.routes.organization import router as org_router
2024
from fast_api.routes.project import router as project_router
2125
from fast_api.routes.project_setting import router as project_setting_router
@@ -65,8 +69,10 @@
6569
logging.basicConfig(level=logging.DEBUG)
6670
logger = logging.getLogger(__name__)
6771

72+
init_config()
6873
fastapi_app = FastAPI()
6974

75+
7076
fastapi_app.include_router(
7177
org_router, prefix=PREFIX_ORGANIZATION, tags=["organization"]
7278
)
@@ -110,7 +116,9 @@
110116
fastapi_app_internal.include_router(
111117
task_execution_router, prefix=PREFIX_TASK_EXECUTION, tags=["task-execution"]
112118
)
119+
113120
routes = [
121+
Route("/full_config", FullConfigRest),
114122
Route("/notify/{path:path}", Notify),
115123
Route("/healthcheck", Healthcheck),
116124
Route("/project/{project_id:str}", ProjectDetails),
@@ -130,8 +138,6 @@
130138
CognitionPrepareProject,
131139
),
132140
Route("/project/{project_id:str}/import/task/{task_id:str}", UploadTaskInfo),
133-
Route("/is_managed", IsManagedRest),
134-
Route("/is_demo", IsDemoRest),
135141
Mount("/api", app=fastapi_app, name="REST API"),
136142
Mount(
137143
"/internal/api", app=fastapi_app_internal, name="INTERNAL REST API"

base_config.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"s3_region": null,
3+
"KERN_S3_ENDPOINT": null,
4+
"spacy_downloads": [
5+
"en_core_web_sm",
6+
"de_core_news_sm"
7+
]
8+
}

check_config_service

Lines changed: 0 additions & 31 deletions
This file was deleted.

config/.gitkeep

Whitespace-only changes.

config_handler.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
from typing import Dict, Any, Optional, Union
2+
import os
3+
import json
4+
from notify_handler import notify_others_about_change_thread
5+
from fastapi import responses, status
6+
7+
__config = None
8+
9+
BASE_CONFIG_PATH = "base_config.json"
10+
CURRENT_CONFIG_PATH = "/config/current_config.json"
11+
12+
SERVICES_TO_NOTIFY = {
13+
"TOKENIZER": "http://refinery-tokenizer:80",
14+
}
15+
16+
17+
def get_config_value(
18+
key: str, subkey: Optional[str] = None
19+
) -> Union[str, Dict[str, str]]:
20+
if key not in __config:
21+
raise ValueError(f"Key {key} coudn't be found in config")
22+
value = __config[key]
23+
24+
if not subkey:
25+
return value
26+
27+
if isinstance(value, dict) and subkey in value:
28+
return value[subkey]
29+
else:
30+
raise ValueError(f"Subkey {subkey} coudn't be found in config[{key}]")
31+
32+
33+
def __read_and_change_base_config():
34+
print("reading base config file", flush=True)
35+
global __config
36+
f = open(BASE_CONFIG_PATH)
37+
__config = json.load(f)
38+
__config["s3_region"] = os.getenv("S3_REGION", "eu-west-1")
39+
__save_current_config()
40+
41+
42+
def change_config(changes: Dict[str, Any]) -> bool:
43+
global __config
44+
something_changed = False
45+
for key in changes:
46+
if key == "KERN_S3_ENDPOINT":
47+
continue
48+
if key in __config:
49+
if isinstance(changes[key], dict):
50+
for subkey in changes[key]:
51+
if subkey in __config[key]:
52+
__config[key][subkey] = changes[key][subkey]
53+
something_changed = True
54+
else:
55+
__config[key] = changes[key]
56+
something_changed = True
57+
if something_changed:
58+
__save_current_config()
59+
else:
60+
print("nothing was changed with input", changes, flush=True)
61+
return something_changed
62+
63+
64+
def __save_current_config() -> None:
65+
print("saving config file", flush=True)
66+
with open(CURRENT_CONFIG_PATH, "w") as f:
67+
json.dump(__config, f, indent=4)
68+
69+
70+
def init_config() -> None:
71+
if not os.path.exists(CURRENT_CONFIG_PATH):
72+
__read_and_change_base_config()
73+
else:
74+
__load_and_remove_outdated_config_keys()
75+
# this one is to be set on every start to ensure its up to date
76+
print("setting s3 endpoint", flush=True)
77+
__config["KERN_S3_ENDPOINT"] = os.getenv("KERN_S3_ENDPOINT")
78+
79+
80+
def __load_and_remove_outdated_config_keys():
81+
if not os.path.exists(CURRENT_CONFIG_PATH):
82+
return
83+
84+
global __config
85+
with open(CURRENT_CONFIG_PATH) as f:
86+
__config = json.load(f)
87+
88+
with open(BASE_CONFIG_PATH) as f:
89+
base_config = json.load(f)
90+
91+
to_remove = [key for key in __config if key not in base_config]
92+
93+
if len(to_remove) > 0:
94+
print("removing outdated config keys", to_remove, flush=True)
95+
for key in to_remove:
96+
del __config[key]
97+
__save_current_config()
98+
99+
100+
def get_config() -> Dict[str, Any]:
101+
global __config
102+
return __config
103+
104+
105+
def change_json(config_data) -> responses.PlainTextResponse:
106+
try:
107+
has_changed = change_config(config_data)
108+
109+
if has_changed:
110+
notify_others_about_change_thread(SERVICES_TO_NOTIFY)
111+
112+
return responses.PlainTextResponse(
113+
f"Did update: {has_changed}", status_code=status.HTTP_200_OK
114+
)
115+
116+
except Exception as e:
117+
return responses.PlainTextResponse(
118+
f"Error: {str(e)}", status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
119+
)
120+
121+
122+
def full_config_json() -> responses.JSONResponse:
123+
return responses.JSONResponse(status_code=status.HTTP_200_OK, content=get_config())

controller/auth/manager.py

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
from typing import Any, Dict
22

33
from fastapi import Request
4-
from controller.misc import config_service
54
from exceptions.exceptions import (
65
AuthManagerError,
7-
NotAllowedInDemoError,
86
ProjectAccessError,
97
)
108
import jwt
@@ -14,7 +12,6 @@
1412
from submodules.model import enums, exceptions
1513
from submodules.model.business_objects import organization
1614
from submodules.model.models import Organization, Project, User
17-
from controller.misc import manager as misc_manager
1815
import sqlalchemy
1916

2017
DEV_USER_ID = "741df1c2-a531-43b6-b259-df23bc78e9a2"
@@ -127,28 +124,6 @@ def check_is_admin(request: Any) -> bool:
127124
return False
128125

129126

130-
def check_demo_access(info: Any) -> None:
131-
if not check_is_admin(info.context["request"]) and config_service.get_config_value(
132-
"is_demo"
133-
):
134-
check_black_white(info)
135-
136-
137-
def check_black_white(info: Any):
138-
black_white = misc_manager.get_black_white_demo()
139-
if str(info.parent_type) == "Mutation":
140-
if info.field_name not in black_white["mutations"]:
141-
raise NotAllowedInDemoError
142-
elif str(info.parent_type) == "Query":
143-
if info.field_name in black_white["queries"]:
144-
raise NotAllowedInDemoError
145-
146-
147-
def check_is_demo_without_info() -> None:
148-
if config_service.get_config_value("is_demo"):
149-
raise NotAllowedInDemoError
150-
151-
152127
def check_is_single_organization() -> bool:
153128
return len(organization_manager.get_all_organizations()) == 1
154129

controller/embedding/manager.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,11 @@ def get_current_terms_text(
4242
return term_text
4343

4444

45-
def get_recommended_encoders(is_managed: bool) -> List[Any]:
46-
# only use is_managed if it is really managed
45+
def get_recommended_encoders() -> List[Any]:
4746
# can run into circular import problems if directly resolved here by helper method
4847
recommendations = connector.request_listing_recommended_encoders()
49-
if is_managed:
50-
existing_models = model_manager.get_model_provider_info()
51-
else:
52-
existing_models = []
48+
existing_models = model_manager.get_model_provider_info()
49+
5350
for model in existing_models:
5451
not_yet_known = (
5552
len(

controller/information_source/manager.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
information_source,
88
payload,
99
)
10-
from controller.misc import config_service
1110
from controller.labeling_access_link import manager as link_manager
1211
from submodules.model import daemon
1312

@@ -86,7 +85,6 @@ def delete_information_source(project_id: str, source_id: str) -> None:
8685
if (
8786
information_source_item.type
8887
== enums.InformationSourceType.ACTIVE_LEARNING.value
89-
and config_service.get_config_value("is_managed")
9088
):
9189
daemon.run_without_db_token(
9290
__delete_active_learner_from_inference_dir, project_id, source_id

0 commit comments

Comments
 (0)