metrics_aggregator.rs 7.54 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

16
17
use std::sync::Once;

18
pub use crate::kv_router::protocols::{ForwardPassMetrics, LoadMetrics, PredictiveLoadMetrics};
19
use crate::kv_router::KV_METRICS_ENDPOINT;
20

21
use crate::kv_router::scoring::Endpoint;
22
use crate::kv_router::ProcessedEndpoints;
Neelay Shah's avatar
Neelay Shah committed
23
use dynamo_runtime::component::Component;
24
use dynamo_runtime::{service::EndpointInfo, utils::Duration, Result};
25
use tokio::sync::watch;
26
27
use tokio_util::sync::CancellationToken;

28
29
30
static METRICS_WAITING_MESSAGE: Once = Once::new();
static METRICS_FOUND_MESSAGE: Once = Once::new();

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
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()
    }
}

62
63
pub struct KvMetricsAggregator {
    pub service_name: String,
64
    pub endpoints_rx: watch::Receiver<ProcessedEndpoints>,
65
66
67
68
}

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

71
72
        tokio::spawn(collect_endpoints_task(
            component.clone(),
73
            watch_tx,
74
            cancellation_token.clone(),
75
            KV_METRICS_ENDPOINT.to_string(),
76
77
78
79
        ));

        Self {
            service_name: component.service_name(),
80
            endpoints_rx: watch_rx,
81
82
83
84
        }
    }

    pub fn get_endpoints(&self) -> ProcessedEndpoints {
85
86
87
88
89
        self.endpoints_rx.borrow().clone()
    }

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

93
94
95
96
/// [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
97
pub async fn collect_endpoints(
98
99
100
101
102
103
104
105
106
107
108
109
110
    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() {
111
112
113
114
115
116
117
118
        // 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");
        });
119
120
121
122
123
124
125
    }

    Ok(endpoints)
}

pub async fn collect_endpoints_task(
    component: Component,
126
    watch_tx: watch::Sender<ProcessedEndpoints>,
127
    cancel: CancellationToken,
128
    subject: String,
129
) {
130
    let backoff_delay = Duration::from_millis(100);
131
    let scrape_timeout = Duration::from_millis(300);
132
    let endpoint = component.endpoint(&subject);
133
    let service_subject = endpoint.subject();
134

135
136
137
    // Keep track of the last sent value to avoid unnecessary updates
    let mut last_sent: Option<ProcessedEndpoints> = None;

138
139
140
141
142
    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                break;
            }
143
            _ = tokio::time::sleep(backoff_delay) => {
144
145
146
147
148
                tracing::trace!("collecting endpoints for service: {}", service_subject);
                let unfiltered_endpoints =
                    match collect_endpoints(&component, &service_subject, scrape_timeout).await
                    {
                        Ok(v) => v,
149
                        Err(e) => {
150
151
                            tracing::warn!("Failed to retrieve endpoints for {}: {:?}", service_subject, e);
                            continue;
152
                        }
153
                    };
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

                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()
                };

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

187
                let processed = ProcessedEndpoints::new(endpoints);
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
                // 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}");
206
207
                }
            }
208
209
210
        }
    }
}