Skip to content

Commit 449bdf3

Browse files
committed
Handle sigterm and sigints to shutdown faster on docker
1 parent 3378fff commit 449bdf3

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

langevals/server.py

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
from contextlib import asynccontextmanager
12
import os
3+
import signal
24
import sys
35
import dotenv
46

@@ -20,7 +22,20 @@
2022
from pydantic import BaseModel, ConfigDict, Field, ValidationError
2123
from mangum import Mangum
2224

23-
app = FastAPI()
25+
26+
def handle_sigterm(signum, frame):
27+
print("Received SIGTERM")
28+
raise SystemExit(0)
29+
30+
31+
@asynccontextmanager
32+
async def lifespan(app: FastAPI):
33+
signal.signal(signal.SIGTERM, handle_sigterm)
34+
signal.signal(signal.SIGINT, handle_sigterm)
35+
yield
36+
37+
38+
app = FastAPI(lifespan=lifespan)
2439

2540
original_env = os.environ.copy()
2641

@@ -52,7 +67,8 @@ class Request(BaseModel):
5267
json_schema_extra={"example": {}},
5368
)
5469

55-
evaluator_cls.preload()
70+
if not os.getenv("DISABLE_EVALUATORS_PRELOAD"):
71+
evaluator_cls.preload()
5672

5773
@app.post(
5874
f"/{module_name}/{evaluator_name}/evaluate",
@@ -115,27 +131,29 @@ def __init__(self, app, options=None):
115131
super().__init__()
116132

117133
def load_config(self):
118-
config = {key: value for key, value in self.options.items()
119-
if key in self.cfg.settings and value is not None} # type: ignore
134+
config = {
135+
key: value
136+
for key, value in self.options.items()
137+
if key in self.cfg.settings and value is not None
138+
} # type: ignore
120139
for key, value in config.items():
121-
self.cfg.set(key.lower(), value) # type: ignore
140+
self.cfg.set(key.lower(), value) # type: ignore
122141

123142
def load(self):
124143
return self.application
125144

126-
127145
host = "0.0.0.0"
128146
port = int(os.getenv("PORT", 8000))
129147
workers = get_cpu_count()
130148

131149
print(f"Starting server with {workers} workers")
132150

133151
options = {
134-
'bind': f'{host}:{port}',
135-
'workers': workers,
136-
'worker_class': 'uvicorn.workers.UvicornWorker',
137-
'preload_app': True,
138-
'forwarded_allow_ips': '*',
152+
"bind": f"{host}:{port}",
153+
"workers": workers,
154+
"worker_class": "uvicorn.workers.UvicornWorker",
155+
"preload_app": True,
156+
"forwarded_allow_ips": "*",
139157
}
140158

141159
StandaloneApplication(app, options).run()

0 commit comments

Comments
 (0)