Repository navigation
Expand file tree
/
Copy pathapi_server_gen.py
More file actions
61 lines (53 loc) · 1.73 KB
/
Copy pathapi_server_gen.py
File metadata and controls
61 lines (53 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from contextlib import contextmanager
import multiprocessing as mp
from typing import Generator, Callable
import time
import requests
from requests.exceptions import RequestException
@contextmanager
def api_server(
health_check_url: str, api_start_func: Callable[[], None]
) -> Generator[None, None, None]:
# 1
def __abort(error_message: str = "unknown error occurred") -> None:
print(f"API Server Error: {error_message}")
# guard to ensure api_process is a process and not none
if api_process:
api_process.terminate()
exit(-1)
try:
start_up_timeout_in_seconds = 1
api_process = mp.Process(target=api_start_func)
api_process.start()
start_health_check = time.time()
while True:
try:
requests.get(health_check_url, timeout=2)
break
except ConnectionError:
if (
time.time() - start_health_check
> start_up_timeout_in_seconds
):
__abort(
f"failed to start within "
f"{start_up_timeout_in_seconds} second"
)
continue
except RequestException:
if (
time.time() - start_health_check
> start_up_timeout_in_seconds
):
__abort(
f"failed to start within "
f"{start_up_timeout_in_seconds} second"
)
continue
# 2
yield
# 5
except Exception as exc:
print(f"API Server Error: {exc}")
finally:
api_process.terminate()