main.rs 5.18 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
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
// 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.

//! Count is a metrics aggregator designed to operate within a namespace and collect
//! metrics from all workers.
//!
//! Metrics will collect for now:
//!
//! - LLM Worker Load:Capacity
//!   - These metrics will be scraped by the LLM NATS Service API's stats request
//!   - Request Slots: [Active, Total]
//!   - KV Cache Blocks: [Active, Total]

26
use clap::Parser;
27
use dynemo_runtime::{
Ryan Olson's avatar
Ryan Olson committed
28
29
30
31
32
33
    error, logging,
    traits::events::EventPublisher,
    utils::{Duration, Instant},
    DistributedRuntime, ErrorContext, Result, Runtime, Worker,
};

34
35
36
37
38
39
// Import from our library
use count::{
    collect_endpoints, extract_metrics, postprocess_metrics, LLMWorkerLoadCapacityConfig,
    PrometheusMetricsServer,
};

40
41
42
43
44
45
46
47
48
49
50
51
52
/// CLI arguments for the count application
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Component to scrape metrics from
    #[arg(long)]
    component: String,

    /// Endpoint to scrape metrics from
    #[arg(long)]
    endpoint: String,

    /// Namespace to operate in
53
    #[arg(long, env = "DYN_NAMESPACE", default_value = "dynemo")]
54
55
56
57
58
59
    namespace: String,

    /// Polling interval in seconds (minimum 1 second)
    #[arg(long, default_value = "2")]
    poll_interval: u64,
}
Ryan Olson's avatar
Ryan Olson committed
60

61
62
63
64
fn get_config(args: &Args) -> Result<LLMWorkerLoadCapacityConfig> {
    if args.component.is_empty() {
        return Err(error!("Component name cannot be empty"));
    }
Ryan Olson's avatar
Ryan Olson committed
65

66
67
    if args.endpoint.is_empty() {
        return Err(error!("Endpoint name cannot be empty"));
Ryan Olson's avatar
Ryan Olson committed
68
69
    }

70
71
    if args.poll_interval < 1 {
        return Err(error!("Polling interval must be at least 1 second"));
Ryan Olson's avatar
Ryan Olson committed
72
73
74
    }

    Ok(LLMWorkerLoadCapacityConfig {
75
76
        component_name: args.component.clone(),
        endpoint_name: args.endpoint.clone(),
Ryan Olson's avatar
Ryan Olson committed
77
78
79
    })
}

80
81
async fn app(runtime: Runtime) -> Result<()> {
    let args = Args::parse();
82
83
    let config = get_config(&args)?;
    tracing::info!("Config: {config:?}");
Ryan Olson's avatar
Ryan Olson committed
84
85
86

    let drt = DistributedRuntime::from_settings(runtime.clone()).await?;

87
    let namespace = drt.namespace(args.namespace)?;
Ryan Olson's avatar
Ryan Olson committed
88
89
    let component = namespace.component("count")?;

90
    // Create unique instance of Count
Ryan Olson's avatar
Ryan Olson committed
91
    let key = format!("{}/instance", component.etcd_path());
92
    tracing::info!("Creating unique instance of Count at {key}");
Ryan Olson's avatar
Ryan Olson committed
93
94
95
96
97
98
99
100
101
    drt.etcd_client()
        .kv_create(
            key,
            serde_json::to_vec_pretty(&config)?,
            Some(drt.primary_lease().id()),
        )
        .await
        .context("Unable to create unique instance of Count; possibly one already exists")?;

102
103
    let target_component = namespace.component(&config.component_name)?;
    let target_endpoint = target_component.endpoint(&config.endpoint_name);
Ryan Olson's avatar
Ryan Olson committed
104

105
    let service_name = target_component.service_name();
Ryan Olson's avatar
Ryan Olson committed
106
    let service_subject = target_endpoint.subject();
107
    tracing::info!("Scraping service {service_name} and filtering on subject {service_subject}");
Ryan Olson's avatar
Ryan Olson committed
108
109

    let token = drt.primary_lease().child_token();
110
    let event_name = format!("l2c.{}.{}", config.component_name, config.endpoint_name);
Ryan Olson's avatar
Ryan Olson committed
111

112
113
114
115
    // TODO: Make metrics host/port configurable
    // Initialize Prometheus metrics and start server
    let mut metrics_server = PrometheusMetricsServer::new()?;
    metrics_server.start(9091);
Ryan Olson's avatar
Ryan Olson committed
116
117

    loop {
118
        let next = Instant::now() + Duration::from_secs(args.poll_interval);
Ryan Olson's avatar
Ryan Olson committed
119

120
121
122
123
124
125
126
        // Collect and process metrics
        let scrape_timeout = Duration::from_secs(1);
        let endpoints =
            collect_endpoints(&target_component, &service_subject, scrape_timeout).await?;
        let metrics = extract_metrics(&endpoints);
        let processed = postprocess_metrics(&metrics, &endpoints);
        tracing::info!("Aggregated metrics: {processed:?}");
Ryan Olson's avatar
Ryan Olson committed
127

128
129
        // Update Prometheus metrics
        metrics_server.update(&config, &processed);
130

131
132
        // TODO: Who needs to consume these events?
        // Publish metrics event
Ryan Olson's avatar
Ryan Olson committed
133
134
        namespace.publish(&event_name, &processed).await?;

135
        // Wait until cancelled or the next tick
Ryan Olson's avatar
Ryan Olson committed
136
137
        match tokio::time::timeout_at(next, token.cancelled()).await {
            Ok(_) => break,
138
            Err(_) => continue,
Ryan Olson's avatar
Ryan Olson committed
139
140
141
142
143
144
        }
    }

    Ok(())
}

145
146
147
148
fn main() -> Result<()> {
    logging::init();
    let worker = Worker::from_settings()?;
    worker.execute(app)
Ryan Olson's avatar
Ryan Olson committed
149
}
150
151
152
153
154
155
156
157

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn test_namespace_from_env() {
158
        env::set_var("DYN_NAMESPACE", "test-namespace");
159
160
161
162
        let args = Args::parse_from(["count", "--component", "comp", "--endpoint", "end"]);
        assert_eq!(args.namespace, "test-namespace");
    }
}