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

4
5
use std::sync::Once;

6
use crate::kv_router::KV_METRICS_ENDPOINT;
7
pub use crate::kv_router::protocols::{ForwardPassMetrics, LoadMetrics, PredictiveLoadMetrics};
8
9

use crate::kv_router::ProcessedEndpoints;
10
use crate::kv_router::scoring::Endpoint;
Neelay Shah's avatar
Neelay Shah committed
11
use dynamo_runtime::component::Component;
12
use dynamo_runtime::{Result, service::EndpointInfo, utils::Duration};
13
use tokio::sync::watch;
14
15
use tokio_util::sync::CancellationToken;

16
17
18
static METRICS_WAITING_MESSAGE: Once = Once::new();
static METRICS_FOUND_MESSAGE: Once = Once::new();

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
pub struct EndpointCollector {
    pub service_name: String,
    pub endpoints_rx: watch::Receiver<ProcessedEndpoints>,
}

impl EndpointCollector {
    pub async fn new(component: Component, cancellation_token: CancellationToken) -> Self {
        let (watch_tx, watch_rx) = watch::channel(ProcessedEndpoints::default());

        tokio::spawn(collect_endpoints_task(
            component.clone(),
            watch_tx,
            cancellation_token.clone(),
            "generate".to_string(),
        ));

        Self {
            service_name: component.service_name(),
            endpoints_rx: watch_rx,
        }
    }

    pub fn get_endpoints(&self) -> ProcessedEndpoints {
        self.endpoints_rx.borrow().clone()
    }

    pub fn endpoints_watcher(&self) -> watch::Receiver<ProcessedEndpoints> {
        self.endpoints_rx.clone()
    }
}

50
51
pub struct KvMetricsAggregator {
    pub service_name: String,
52
    pub endpoints_rx: watch::Receiver<ProcessedEndpoints>,
53
54
55
56
}

impl KvMetricsAggregator {
    pub async fn new(component: Component, cancellation_token: CancellationToken) -> Self {
57
        let (watch_tx, watch_rx) = watch::channel(ProcessedEndpoints::default());
58

59
60
        tokio::spawn(collect_endpoints_task(
            component.clone(),
61
            watch_tx,
62
            cancellation_token.clone(),
63
            KV_METRICS_ENDPOINT.to_string(),
64
65
66
67
        ));

        Self {
            service_name: component.service_name(),
68
            endpoints_rx: watch_rx,
69
70
71
72
        }
    }

    pub fn get_endpoints(&self) -> ProcessedEndpoints {
73
74
75
76
77
        self.endpoints_rx.borrow().clone()
    }

    pub fn endpoints_watcher(&self) -> watch::Receiver<ProcessedEndpoints> {
        self.endpoints_rx.clone()
78
79
80
    }
}

81
82
83
84
/// [gluo TODO] 'collect_endpoints' is from component/metrics,
/// should consolidate these functions into generic metrics aggregator
/// functions and shared by KvMetricsAggregator and component/metrics.
/// Collect endpoints from a component
85
pub async fn collect_endpoints(
86
87
88
89
90
91
92
93
94
95
96
97
98
    component: &Component,
    subject: &str,
    timeout: Duration,
) -> Result<Vec<EndpointInfo>> {
    // Collect stats from each backend
    let stream = component.scrape_stats(timeout).await?;

    // Filter the stats by the service subject
    let endpoints = stream
        .into_endpoints()
        .filter(|e| e.subject.starts_with(subject))
        .collect::<Vec<_>>();
    if endpoints.is_empty() {
99
100
101
102
103
104
105
106
        // Only print it once, we poll while the worker starts
        METRICS_WAITING_MESSAGE.call_once(|| {
            tracing::debug!("Waiting for metrics endpoint..");
        });
    } else {
        METRICS_FOUND_MESSAGE.call_once(|| {
            tracing::debug!("Found metrics endpoint");
        });
107
108
109
110
111
112
113
    }

    Ok(endpoints)
}

pub async fn collect_endpoints_task(
    component: Component,
114
    watch_tx: watch::Sender<ProcessedEndpoints>,
115
    cancel: CancellationToken,
116
    subject: String,
117
) {
118
    let backoff_delay = Duration::from_millis(100);
119
    let scrape_timeout = Duration::from_millis(300);
120
    let endpoint = component.endpoint(&subject);
121
    let service_subject = endpoint.subject();
122

123
124
125
    // Keep track of the last sent value to avoid unnecessary updates
    let mut last_sent: Option<ProcessedEndpoints> = None;

126
127
128
129
130
    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                break;
            }
131
            _ = tokio::time::sleep(backoff_delay) => {
132
133
134
135
136
                tracing::trace!("collecting endpoints for service: {}", service_subject);
                let unfiltered_endpoints =
                    match collect_endpoints(&component, &service_subject, scrape_timeout).await
                    {
                        Ok(v) => v,
137
                        Err(e) => {
138
139
                            tracing::warn!("Failed to retrieve endpoints for {}: {:?}", service_subject, e);
                            continue;
140
                        }
141
                    };
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

                let endpoints: Vec<Endpoint> = if subject == KV_METRICS_ENDPOINT {
                    // Original filtering behavior
                    unfiltered_endpoints
                        .into_iter()
                        .filter_map(|s| {
                            s.data?
                                .decode::<ForwardPassMetrics>()
                                .map(|data| Endpoint {
                                    name: s.name,
                                    subject: s.subject,
                                    data: LoadMetrics::EngineLoadMetrics(data),
                                })
                                .inspect_err(|e| {
                                    tracing::warn!("skip endpoint data that can't be parsed as ForwardPassMetrics: {:?}", e);
                                })
                                .ok()
                        })
                        .collect()
                } else {
                    // No filtering - just use default LoadMetrics
                    unfiltered_endpoints
                        .into_iter()
                        .map(|s| Endpoint {
                            name: s.name,
                            subject: s.subject,
                            data: LoadMetrics::default(),
                        })
                        .collect()
                };

173
                tracing::trace!("Found {} endpoints for service: {service_subject}", endpoints.len());
174

175
                let processed = ProcessedEndpoints::new(endpoints);
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
                // Only send if different from last sent value
                // This is necessary because the watch channel does not track changes
                // https://docs.rs/tokio/latest/tokio/sync/watch/struct.Receiver.html#method.has_changed
                let should_send = match &last_sent {
                    Some(last) => last != &processed,
                    None => true,
                };

                if should_send {
                    tracing::trace!("Endpoints changed, sending update for service: {service_subject}");
                    if watch_tx.send(processed.clone()).is_err() {
                        tracing::error!("failed to send processed endpoints; shutting down");
                        break;
                    }
                    last_sent = Some(processed);
                } else {
                    tracing::trace!("Endpoints unchanged, skipping update for service: {service_subject}");
194
195
                }
            }
196
197
198
        }
    }
}