health.rs 2.56 KB
Newer Older
1
2
3
4
5
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::{service_v2, RouteDoc};
use axum::{http::Method, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
6
use dynamo_runtime::instances::list_all_instances;
7
8
9
10
11
12
13
use serde_json::json;
use std::sync::Arc;

pub fn health_check_router(
    state: Arc<service_v2::State>,
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
14
    let health_path = path.unwrap_or_else(|| "/health".to_string());
15

16
    let docs: Vec<RouteDoc> = vec![RouteDoc::new(Method::GET, &health_path)];
17
18

    let router = Router::new()
19
        .route(&health_path, get(health_handler))
20
21
22
23
24
        .with_state(state);

    (docs, router)
}

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
pub fn live_check_router(
    state: Arc<service_v2::State>,
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    let live_path = path.unwrap_or_else(|| "/live".to_string());

    let docs: Vec<RouteDoc> = vec![RouteDoc::new(Method::GET, &live_path)];

    let router = Router::new()
        .route(&live_path, get(live_handler))
        .with_state(state);

    (docs, router)
}

async fn live_handler(
    axum::extract::State(_state): axum::extract::State<Arc<service_v2::State>>,
) -> impl IntoResponse {
    (
        StatusCode::OK,
        Json(json!({
            "status": "live",
            "message": "Service is live"
        })),
    )
}

52
53
54
55
async fn health_handler(
    axum::extract::State(state): axum::extract::State<Arc<service_v2::State>>,
) -> impl IntoResponse {
    let model_entries = state.manager().get_model_entries();
56
57
58
59
60
61
62
63
64
65
66
    let instances = if let Some(etcd_client) = state.etcd_client() {
        match list_all_instances(etcd_client).await {
            Ok(instances) => instances,
            Err(err) => {
                tracing::warn!("Failed to fetch instances from etcd: {}", err);
                vec![]
            }
        }
    } else {
        vec![]
    };
67
68
69
70
71
72

    if model_entries.is_empty() {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({
                "status": "unhealthy",
73
74
                "message": "No endpoints available",
                "instances": instances
75
76
77
78
79
            })),
        )
    } else {
        let endpoints: Vec<String> = model_entries
            .iter()
80
            .map(|entry| entry.endpoint_id.as_url())
81
82
83
84
85
            .collect();
        (
            StatusCode::OK,
            Json(json!({
                "status": "healthy",
86
87
                "endpoints": endpoints,
                "instances": instances
88
89
90
91
            })),
        )
    }
}