Skip to content

Commit e6e457f

Browse files
Merge pull request #95 from CausalInferenceLab/feature/94-add-logging-divide-gms-server-check
CLI 로깅 추가 및 Datahub GMS 연결체크 기능 분리
2 parents 4333383 + cc60e43 commit e6e457f

File tree

3 files changed

+100
-5
lines changed

3 files changed

+100
-5
lines changed

cli/__init__.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,21 @@
22
Datahub GMS 서버 URL을 설정하고, 필요 시 Streamlit 인터페이스를 실행하는 CLI 프로그램입니다.
33
"""
44

5+
import logging
56
import subprocess
67

78
import click
89

10+
from llm_utils.check_server import CheckServer
911
from llm_utils.tools import set_gms_server
1012

13+
logging.basicConfig(
14+
level=logging.INFO,
15+
format="%(asctime)s [%(levelname)s] %(message)s",
16+
datefmt="%Y-%m-%d %H:%M:%S",
17+
)
18+
logger = logging.getLogger(__name__)
19+
1120

1221
@click.group()
1322
@click.version_option(version="0.1.4")
@@ -64,11 +73,20 @@ def cli(
6473
'set_gms_server' 함수에서 ValueError가 발생할 경우, 프로그램은 비정상 종료(exit code 1)합니다.
6574
"""
6675

67-
try:
76+
logger.info(
77+
"Initialization started: GMS server = %s, run_streamlit = %s, port = %d",
78+
datahub_server,
79+
run_streamlit,
80+
port,
81+
)
82+
83+
if CheckServer.is_gms_server_healthy(url=datahub_server):
6884
set_gms_server(datahub_server)
69-
except ValueError as e:
70-
click.secho(f"GMS 서버 URL 설정 실패: {str(e)}", fg="red")
85+
logger.info("GMS server URL successfully set: %s", datahub_server)
86+
else:
87+
logger.error("GMS server health check failed. URL: %s", datahub_server)
7188
ctx.exit(1)
89+
7290
if run_streamlit:
7391
run_streamlit_command(port)
7492

@@ -89,6 +107,8 @@ def run_streamlit_command(port: int) -> None:
89107
- subprocess 호출 실패 시 예외가 발생할 수 있습니다.
90108
"""
91109

110+
logger.info("Starting Streamlit application on port %d...", port)
111+
92112
try:
93113
subprocess.run(
94114
[
@@ -100,8 +120,9 @@ def run_streamlit_command(port: int) -> None:
100120
],
101121
check=True,
102122
)
123+
logger.info("Streamlit application started successfully.")
103124
except subprocess.CalledProcessError as e:
104-
click.echo(f"Streamlit 실행 실패: {e}")
125+
logger.error("Failed to start Streamlit application: %s", e)
105126
raise
106127

107128

@@ -132,4 +153,5 @@ def run_streamlit_cli_command(port: int) -> None:
132153
- Streamlit 실행에 실패할 경우 subprocess 호출에서 예외가 발생할 수 있습니다.
133154
"""
134155

156+
logger.info("Executing 'run-streamlit' command on port %d...", port)
135157
run_streamlit_command(port)

data_utils/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
# data_utils 패키지 초기화 파일

llm_utils/check_server.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
서버 상태 확인 및 연결 관련 기능을 제공하는 유틸리티 클래스입니다.
3+
4+
이 모듈은 HTTP 기반의 서버에 대해 다음과 같은 기능을 제공합니다:
5+
- `/health` 엔드포인트를 통한 서버 헬스 체크
6+
- 향후 서버 연결 또는 상태 점검과 관련된 기능 추가 예정
7+
8+
각 기능은 요청 실패, 타임아웃, 연결 오류 등의 다양한 예외 상황을 포괄적으로 처리하며,
9+
로깅을 통해 상세한 실패 원인을 기록하고 결과를 boolean 또는 적절한 형태로 반환합니다.
10+
"""
11+
12+
import logging
13+
from urllib.parse import urljoin
14+
15+
import requests
16+
17+
logging.basicConfig(
18+
level=logging.INFO,
19+
format="%(asctime)s [%(levelname)s] %(message)s",
20+
datefmt="%Y-%m-%d %H:%M:%S",
21+
)
22+
logger = logging.getLogger(__name__)
23+
24+
25+
class CheckServer:
26+
"""
27+
서버의 상태를 확인하거나 연결을 테스트하는 유틸리티 메서드를 제공하는 클래스입니다.
28+
29+
현재는 GMS 서버의 `/health` 엔드포인트에 대한 헬스 체크 기능을 포함하고 있으며,
30+
향후에는 다양한 서버 연결 확인 및 상태 점검 기능이 추가될 수 있도록 확장 가능한 구조로 설계되었습니다.
31+
모든 기능은 네트워크 오류 및 서버 응답 상태에 따라 예외를 로깅하며, 호출자가 결과를 판단할 수 있도록 boolean 값을 반환합니다.
32+
"""
33+
34+
@staticmethod
35+
def is_gms_server_healthy(*, url: str) -> bool:
36+
"""
37+
지정된 GMS 서버의 `/health` 엔드포인트에 요청을 보내 상태를 확인합니다.
38+
39+
서버가 HTTP 200 응답을 반환하면 True를 반환하며,
40+
요청 실패, 타임아웃, 연결 오류 등의 예외 발생 시 False를 반환하고,
41+
로깅을 통해 상세한 에러 정보를 출력합니다.
42+
43+
Args:
44+
url (str): 헬스 체크를 수행할 GMS 서버의 기본 URL (예: "http://localhost:8080")
45+
46+
Returns:
47+
bool: 서버가 정상적으로 응답하면 True, 예외 발생 시 False
48+
"""
49+
50+
health_url = urljoin(url, "/health")
51+
52+
try:
53+
response = requests.get(
54+
health_url,
55+
timeout=3,
56+
)
57+
response.raise_for_status()
58+
logger.info("GMS server is healthy: %s", url)
59+
return True
60+
except (
61+
requests.exceptions.ConnectTimeout,
62+
requests.exceptions.ReadTimeout,
63+
) as e:
64+
logger.error(
65+
"Timeout while connecting to GMS server: %s | %s", health_url, e
66+
)
67+
except requests.exceptions.ConnectionError as e:
68+
logger.error("Failed to connect to GMS server: %s | %s", health_url, e)
69+
except requests.exceptions.HTTPError as e:
70+
logger.error("GMS server returned HTTP error: %s | %s", health_url, e)
71+
except requests.exceptions.RequestException as e:
72+
logger.exception("Unexpected request error to GMS server: %s", health_url)
73+
74+
return False

0 commit comments

Comments
 (0)