"lib/llm/src/entrypoint/input/common.rs" did not exist on "73fdfb8ab84c9f56982d7d6074ef4d2f2a214150"
client.rs 14.7 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3

4
5
6
7
8
9
10
11
use std::sync::Arc;
use std::{collections::HashMap, time::Duration};

use anyhow::Result;
use arc_swap::ArcSwap;
use futures::StreamExt;
use tokio::net::unix::pipe::Receiver;

12
use crate::{
13
14
    component::{Endpoint, Instance},
    pipeline::async_trait,
15
16
17
18
19
    pipeline::{
        AddressedPushRouter, AddressedRequest, AsyncEngine, Data, ManyOut, PushRouter, RouterMode,
        SingleIn,
    },
    storage::key_value_store::{KeyValueStoreManager, WatchEvent},
20
21
    traits::DistributedRuntimeProvider,
    transports::etcd::Client as EtcdClient,
Ryan Olson's avatar
Ryan Olson committed
22
23
};

24
25
26
27
#[derive(Clone, Debug)]
pub struct Client {
    // This is me
    pub endpoint: Endpoint,
28
29
    // These are the remotes I know about from watching key-value store
    pub instance_source: Arc<tokio::sync::watch::Receiver<Vec<Instance>>>,
30
    // These are the instance source ids less those reported as down from sending rpc
31
    instance_avail: Arc<ArcSwap<Vec<u64>>>,
32
    // These are the instance source ids less those reported as busy (above threshold)
33
    instance_free: Arc<ArcSwap<Vec<u64>>>,
34
35
36
37
    // Watch sender for available instance IDs (for sending updates)
    instance_avail_tx: Arc<tokio::sync::watch::Sender<Vec<u64>>>,
    // Watch receiver for available instance IDs (for cloning to external subscribers)
    instance_avail_rx: tokio::sync::watch::Receiver<Vec<u64>>,
38
39
}

40
impl Client {
41
42
    // Client with auto-discover instances using key-value store
    pub(crate) async fn new(endpoint: Endpoint) -> Result<Self> {
43
44
45
46
        tracing::debug!(
            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
            endpoint.path()
        );
47
        let instance_source = Self::get_or_create_dynamic_instance_source(&endpoint).await?;
48
49
50
51
        tracing::debug!(
            "Client::new_dynamic: Got instance source for endpoint: {}",
            endpoint.path()
        );
52

53
        let (avail_tx, avail_rx) = tokio::sync::watch::channel(vec![]);
54
        let client = Client {
55
            endpoint: endpoint.clone(),
56
            instance_source: instance_source.clone(),
57
            instance_avail: Arc::new(ArcSwap::from(Arc::new(vec![]))),
58
            instance_free: Arc::new(ArcSwap::from(Arc::new(vec![]))),
59
60
            instance_avail_tx: Arc::new(avail_tx),
            instance_avail_rx: avail_rx,
61
        };
62
63
64
65
        tracing::debug!(
            "Client::new_dynamic: Starting instance source monitor for endpoint: {}",
            endpoint.path()
        );
66
        client.monitor_instance_source();
67
68
69
70
        tracing::debug!(
            "Client::new_dynamic: Successfully created dynamic client for endpoint: {}",
            endpoint.path()
        );
71
        Ok(client)
72
73
74
75
76
77
78
79
80
81
82
    }

    pub fn path(&self) -> String {
        self.endpoint.path()
    }

    /// The root etcd path we watch in etcd to discover new instances to route to.
    pub fn etcd_root(&self) -> String {
        self.endpoint.etcd_root()
    }

83
    /// Instances available from watching key-value store
84
    pub fn instances(&self) -> Vec<Instance> {
85
        self.instance_source.borrow().clone()
86
87
    }

88
    pub fn instance_ids(&self) -> Vec<u64> {
89
90
91
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

92
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
93
94
95
        self.instance_avail.load()
    }

96
    pub fn instance_ids_free(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
97
98
99
        self.instance_free.load()
    }

100
101
102
103
104
    /// Get a watcher for available instance IDs
    pub fn instance_avail_watcher(&self) -> tokio::sync::watch::Receiver<Vec<u64>> {
        self.instance_avail_rx.clone()
    }

105
106
    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
107
108
109
110
        tracing::debug!(
            "wait_for_instances: Starting wait for endpoint: {}",
            self.endpoint.path()
        );
111
112
113
114
115
116
117
118
119
120
121
122
123
        let mut rx = self.instance_source.as_ref().clone();
        // wait for there to be 1 or more endpoints
        let mut iteration = 0;
        let mut instances: Vec<Instance>;
        loop {
            instances = rx.borrow_and_update().to_vec();
            tracing::debug!(
                "wait_for_instances: iteration={}, current_instance_count={}, endpoint={}",
                iteration,
                instances.len(),
                self.endpoint.path()
            );
            if instances.is_empty() {
124
                tracing::debug!(
125
126
127
128
129
130
131
132
133
134
135
                    "wait_for_instances: No instances yet, waiting for change notification for endpoint: {}",
                    self.endpoint.path()
                );
                rx.changed().await?;
                tracing::debug!(
                    "wait_for_instances: Change notification received for endpoint: {}",
                    self.endpoint.path()
                );
            } else {
                tracing::info!(
                    "wait_for_instances: Found {} instance(s) for endpoint: {}",
136
137
138
                    instances.len(),
                    self.endpoint.path()
                );
139
                break;
140
            }
141
            iteration += 1;
142
143
144
145
        }
        Ok(instances)
    }

146
    /// Mark an instance as down/unavailable
147
    pub fn report_instance_down(&self, instance_id: u64) {
148
149
150
151
152
        let filtered = self
            .instance_ids_avail()
            .iter()
            .filter_map(|&id| if id == instance_id { None } else { Some(id) })
            .collect::<Vec<_>>();
153
154
155
156
        self.instance_avail.store(Arc::new(filtered.clone()));

        // Notify watch channel subscribers about the change
        let _ = self.instance_avail_tx.send(filtered);
157
158
159
160

        tracing::debug!("inhibiting instance {instance_id}");
    }

161
    /// Update the set of free instances based on busy instance IDs
162
    pub fn update_free_instances(&self, busy_instance_ids: &[u64]) {
163
        let all_instance_ids = self.instance_ids();
164
        let free_ids: Vec<u64> = all_instance_ids
165
166
167
168
169
170
            .into_iter()
            .filter(|id| !busy_instance_ids.contains(id))
            .collect();
        self.instance_free.store(Arc::new(free_ids));
    }

171
    /// Monitor the key-value instance source and update instance_avail.
172
173
174
    fn monitor_instance_source(&self) {
        let cancel_token = self.endpoint.drt().primary_token();
        let client = self.clone();
175
176
177
178
179
        let endpoint_path = self.endpoint.path();
        tracing::debug!(
            "monitor_instance_source: Starting monitor for endpoint: {}",
            endpoint_path
        );
180
        tokio::task::spawn(async move {
181
            let mut rx = client.instance_source.as_ref().clone();
182
            let mut iteration = 0;
183
            while !cancel_token.is_cancelled() {
184
                let instance_ids: Vec<u64> = rx
185
186
187
188
                    .borrow_and_update()
                    .iter()
                    .map(|instance| instance.id())
                    .collect();
189

190
191
192
193
194
195
196
197
                tracing::debug!(
                    "monitor_instance_source: iteration={}, instance_count={}, instance_ids={:?}, endpoint={}",
                    iteration,
                    instance_ids.len(),
                    instance_ids,
                    endpoint_path
                );

198
199
                // TODO: this resets both tracked available and free instances
                client.instance_avail.store(Arc::new(instance_ids.clone()));
200
                client.instance_free.store(Arc::new(instance_ids.clone()));
201

202
203
204
                // Send update to watch channel subscribers
                let _ = client.instance_avail_tx.send(instance_ids);

205
206
207
208
                tracing::debug!(
                    "monitor_instance_source: instance source updated, endpoint={}",
                    endpoint_path
                );
209
210

                if let Err(err) = rx.changed().await {
211
212
213
214
215
                    tracing::error!(
                        "monitor_instance_source: The Sender is dropped: {}, endpoint={}",
                        err,
                        endpoint_path
                    );
216
217
                    cancel_token.cancel();
                }
218
                iteration += 1;
219
            }
220
221
222
223
            tracing::debug!(
                "monitor_instance_source: Monitor loop exiting for endpoint: {}",
                endpoint_path
            );
224
        });
225
226
227
228
    }

    async fn get_or_create_dynamic_instance_source(
        endpoint: &Endpoint,
229
    ) -> Result<Arc<tokio::sync::watch::Receiver<Vec<Instance>>>> {
230
231
232
233
        let drt = endpoint.drt();
        let instance_sources = drt.instance_sources();
        let mut instance_sources = instance_sources.lock().await;

234
235
236
237
238
        tracing::debug!(
            "get_or_create_dynamic_instance_source: Checking cache for endpoint: {}",
            endpoint.path()
        );

239
240
        if let Some(instance_source) = instance_sources.get(endpoint) {
            if let Some(instance_source) = instance_source.upgrade() {
241
242
243
244
                tracing::debug!(
                    "get_or_create_dynamic_instance_source: Found cached instance source for endpoint: {}",
                    endpoint.path()
                );
245
246
                return Ok(instance_source);
            } else {
247
248
249
250
                tracing::debug!(
                    "get_or_create_dynamic_instance_source: Cached instance source was dropped, removing for endpoint: {}",
                    endpoint.path()
                );
251
252
253
254
                instance_sources.remove(endpoint);
            }
        }

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        tracing::debug!(
            "get_or_create_dynamic_instance_source: Creating new instance source for endpoint: {}",
            endpoint.path()
        );

        let discovery = drt.discovery();
        let discovery_query = crate::discovery::DiscoveryQuery::Endpoint {
            namespace: endpoint.component.namespace.name.clone(),
            component: endpoint.component.name.clone(),
            endpoint: endpoint.name.clone(),
        };

        tracing::debug!(
            "get_or_create_dynamic_instance_source: Calling discovery.list_and_watch for query: {:?}",
            discovery_query
        );

        let mut discovery_stream = discovery
            .list_and_watch(discovery_query.clone(), None)
            .await?;

        tracing::debug!(
            "get_or_create_dynamic_instance_source: Got discovery stream for query: {:?}",
            discovery_query
        );

Ryan Olson's avatar
Ryan Olson committed
281
282
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

283
        let secondary = endpoint.component.drt.runtime().secondary().clone();
Ryan Olson's avatar
Ryan Olson committed
284
285

        secondary.spawn(async move {
286
287
288
            tracing::debug!("endpoint_watcher: Starting for discovery query: {:?}", discovery_query);
            let mut map: HashMap<u64, Instance> = HashMap::new();
            let mut event_count = 0;
Ryan Olson's avatar
Ryan Olson committed
289
290

            loop {
291
                let discovery_event = tokio::select! {
Ryan Olson's avatar
Ryan Olson committed
292
                    _ = watch_tx.closed() => {
293
                        tracing::debug!("endpoint_watcher: all watchers have closed; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
294
295
                        break;
                    }
296
297
298
299
300
301
302
303
304
305
306
                    discovery_event = discovery_stream.next() => {
                        tracing::debug!("endpoint_watcher: Received stream event for discovery query: {:?}", discovery_query);
                        match discovery_event {
                            Some(Ok(event)) => {
                                tracing::debug!("endpoint_watcher: Got Ok event: {:?}", event);
                                event
                            },
                            Some(Err(e)) => {
                                tracing::error!("endpoint_watcher: discovery stream error: {}; shutting down for discovery query: {:?}", e, discovery_query);
                                break;
                            }
Ryan Olson's avatar
Ryan Olson committed
307
                            None => {
308
                                tracing::debug!("endpoint_watcher: watch stream has closed; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
309
310
311
312
313
314
                                break;
                            }
                        }
                    }
                };

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
                event_count += 1;
                tracing::debug!("endpoint_watcher: Processing event #{} for discovery query: {:?}", event_count, discovery_query);

                match discovery_event {
                    crate::discovery::DiscoveryEvent::Added(discovery_instance) => {
                        match discovery_instance {
                            crate::discovery::DiscoveryInstance::Endpoint(instance) => {
                                tracing::debug!(
                                    "endpoint_watcher: Added endpoint instance_id={}, namespace={}, component={}, endpoint={}",
                                    instance.instance_id,
                                    instance.namespace,
                                    instance.component,
                                    instance.endpoint
                                );
                                map.insert(instance.instance_id, instance);
                            }
                            _ => {
                                tracing::debug!("endpoint_watcher: Ignoring non-endpoint instance (Model, etc.) for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
333
334
                            }
                        }
335
336
337
338
339
340
341
342
                    }
                    crate::discovery::DiscoveryEvent::Removed(instance_id) => {
                        tracing::debug!(
                            "endpoint_watcher: Removed instance_id={} for discovery query: {:?}",
                            instance_id,
                            discovery_query
                        );
                        map.remove(&instance_id);
Ryan Olson's avatar
Ryan Olson committed
343
344
345
                    }
                }

346
                let instances: Vec<Instance> = map.values().cloned().collect();
347
348
349
350
351
                tracing::debug!(
                    "endpoint_watcher: Current map size={}, sending update for discovery query: {:?}",
                    instances.len(),
                    discovery_query
                );
Ryan Olson's avatar
Ryan Olson committed
352

353
                if watch_tx.send(instances).is_err() {
354
                    tracing::debug!("endpoint_watcher: Unable to send watch updates; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
355
356
357
358
                    break;
                }
            }

359
            tracing::debug!("endpoint_watcher: Completed for discovery query: {:?}, total events processed: {}", discovery_query, event_count);
Ryan Olson's avatar
Ryan Olson committed
360
361
362
            let _ = watch_tx.send(vec![]);
        });

363
        let instance_source = Arc::new(watch_rx);
364
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
365
366
367
368
        tracing::debug!(
            "get_or_create_dynamic_instance_source: Successfully created and cached instance source for endpoint: {}",
            endpoint.path()
        );
369
        Ok(instance_source)
370
    }
Ryan Olson's avatar
Ryan Olson committed
371
}