client.rs 15.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
use crate::{
    pipeline::{
        AddressedPushRouter, AddressedRequest, AsyncEngine, Data, ManyOut, PushRouter, RouterMode,
        SingleIn,
    },
    storage::key_value_store::{KeyValueStoreManager, WatchEvent},
Ryan Olson's avatar
Ryan Olson committed
10
};
11
use arc_swap::ArcSwap;
12
use futures::StreamExt;
Ryan Olson's avatar
Ryan Olson committed
13
use std::collections::HashMap;
14
use std::sync::Arc;
15
use tokio::net::unix::pipe::Receiver;
Ryan Olson's avatar
Ryan Olson committed
16

17
use crate::{pipeline::async_trait, transports::etcd::Client as EtcdClient};
Ryan Olson's avatar
Ryan Olson committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

use super::*;

/// Each state will be have a nonce associated with it
/// The state will be emitted in a watch channel, so we can observe the
/// critical state transitions.
enum MapState {
    /// The map is empty; value = nonce
    Empty(u64),

    /// The map is not-empty; values are (nonce, count)
    NonEmpty(u64, u64),

    /// The watcher has finished, no more events will be emitted
    Finished,
}

enum EndpointEvent {
36
    Put(String, u64),
Ryan Olson's avatar
Ryan Olson committed
37
38
39
    Delete(String),
}

40
41
42
43
#[derive(Clone, Debug)]
pub struct Client {
    // This is me
    pub endpoint: Endpoint,
44
    // These are the remotes I know about from watching etcd
45
    pub instance_source: Arc<InstanceSource>,
46
    // These are the instance source ids less those reported as down from sending rpc
47
    instance_avail: Arc<ArcSwap<Vec<u64>>>,
48
    // These are the instance source ids less those reported as busy (above threshold)
49
    instance_free: Arc<ArcSwap<Vec<u64>>>,
50
51
52
}

#[derive(Clone, Debug)]
53
pub enum InstanceSource {
54
    Static,
55
    Dynamic(tokio::sync::watch::Receiver<Vec<Instance>>),
Ryan Olson's avatar
Ryan Olson committed
56
57
}

58
impl Client {
59
60
61
62
    // Client will only talk to a single static endpoint
    pub(crate) async fn new_static(endpoint: Endpoint) -> Result<Self> {
        Ok(Client {
            endpoint,
63
            instance_source: Arc::new(InstanceSource::Static),
64
            instance_avail: Arc::new(ArcSwap::from(Arc::new(vec![]))),
65
            instance_free: Arc::new(ArcSwap::from(Arc::new(vec![]))),
66
67
        })
    }
Ryan Olson's avatar
Ryan Olson committed
68

69
    // Client with auto-discover instances using etcd
70
    pub(crate) async fn new_dynamic(endpoint: Endpoint) -> Result<Self> {
71
72
73
74
        tracing::debug!(
            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
            endpoint.path()
        );
75
76
        const INSTANCE_REFRESH_PERIOD: Duration = Duration::from_secs(1);

77
        let instance_source = Self::get_or_create_dynamic_instance_source(&endpoint).await?;
78
79
80
81
        tracing::debug!(
            "Client::new_dynamic: Got instance source for endpoint: {}",
            endpoint.path()
        );
82

83
        let client = Client {
84
            endpoint: endpoint.clone(),
85
            instance_source: instance_source.clone(),
86
            instance_avail: Arc::new(ArcSwap::from(Arc::new(vec![]))),
87
            instance_free: Arc::new(ArcSwap::from(Arc::new(vec![]))),
88
        };
89
90
91
92
        tracing::debug!(
            "Client::new_dynamic: Starting instance source monitor for endpoint: {}",
            endpoint.path()
        );
93
        client.monitor_instance_source();
94
95
96
97
        tracing::debug!(
            "Client::new_dynamic: Successfully created dynamic client for endpoint: {}",
            endpoint.path()
        );
98
        Ok(client)
99
100
101
102
103
104
105
106
107
108
109
    }

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

110
    /// Instances available from watching etcd
111
    pub fn instances(&self) -> Vec<Instance> {
112
113
114
115
        match self.instance_source.as_ref() {
            InstanceSource::Static => vec![],
            InstanceSource::Dynamic(watch_rx) => watch_rx.borrow().clone(),
        }
116
117
    }

118
    pub fn instance_ids(&self) -> Vec<u64> {
119
120
121
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

122
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
123
124
125
        self.instance_avail.load()
    }

126
    pub fn instance_ids_free(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
127
128
129
        self.instance_free.load()
    }

130
131
    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
132
133
134
135
        tracing::debug!(
            "wait_for_instances: Starting wait for endpoint: {}",
            self.endpoint.path()
        );
136
137
138
        let mut instances: Vec<Instance> = vec![];
        if let InstanceSource::Dynamic(mut rx) = self.instance_source.as_ref().clone() {
            // wait for there to be 1 or more endpoints
139
            let mut iteration = 0;
140
141
            loop {
                instances = rx.borrow_and_update().to_vec();
142
143
144
145
146
147
                tracing::debug!(
                    "wait_for_instances: iteration={}, current_instance_count={}, endpoint={}",
                    iteration,
                    instances.len(),
                    self.endpoint.path()
                );
148
                if instances.is_empty() {
149
150
151
152
                    tracing::debug!(
                        "wait_for_instances: No instances yet, waiting for change notification for endpoint: {}",
                        self.endpoint.path()
                    );
153
                    rx.changed().await?;
154
155
156
157
                    tracing::debug!(
                        "wait_for_instances: Change notification received for endpoint: {}",
                        self.endpoint.path()
                    );
158
                } else {
159
160
161
162
163
                    tracing::info!(
                        "wait_for_instances: Found {} instance(s) for endpoint: {}",
                        instances.len(),
                        self.endpoint.path()
                    );
164
165
                    break;
                }
166
                iteration += 1;
167
            }
168
169
170
171
172
        } else {
            tracing::debug!(
                "wait_for_instances: Static instance source, no dynamic discovery for endpoint: {}",
                self.endpoint.path()
            );
173
174
175
176
        }
        Ok(instances)
    }

177
178
179
    /// Is this component know at startup and not discovered via etcd?
    pub fn is_static(&self) -> bool {
        matches!(self.instance_source.as_ref(), InstanceSource::Static)
180
181
182
    }

    /// Mark an instance as down/unavailable
183
    pub fn report_instance_down(&self, instance_id: u64) {
184
185
186
187
188
189
        let filtered = self
            .instance_ids_avail()
            .iter()
            .filter_map(|&id| if id == instance_id { None } else { Some(id) })
            .collect::<Vec<_>>();
        self.instance_avail.store(Arc::new(filtered));
190
191
192
193

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

194
    /// Update the set of free instances based on busy instance IDs
195
    pub fn update_free_instances(&self, busy_instance_ids: &[u64]) {
196
        let all_instance_ids = self.instance_ids();
197
        let free_ids: Vec<u64> = all_instance_ids
198
199
200
201
202
203
            .into_iter()
            .filter(|id| !busy_instance_ids.contains(id))
            .collect();
        self.instance_free.store(Arc::new(free_ids));
    }

204
205
206
207
    /// Monitor the ETCD instance source and update instance_avail.
    fn monitor_instance_source(&self) {
        let cancel_token = self.endpoint.drt().primary_token();
        let client = self.clone();
208
209
210
211
212
        let endpoint_path = self.endpoint.path();
        tracing::debug!(
            "monitor_instance_source: Starting monitor for endpoint: {}",
            endpoint_path
        );
213
214
215
        tokio::task::spawn(async move {
            let mut rx = match client.instance_source.as_ref() {
                InstanceSource::Static => {
216
217
218
                    tracing::error!(
                        "monitor_instance_source: Static instance source is not watchable"
                    );
219
220
221
222
                    return;
                }
                InstanceSource::Dynamic(rx) => rx.clone(),
            };
223
            let mut iteration = 0;
224
            while !cancel_token.is_cancelled() {
225
                let instance_ids: Vec<u64> = rx
226
227
228
229
                    .borrow_and_update()
                    .iter()
                    .map(|instance| instance.id())
                    .collect();
230

231
232
233
234
235
236
237
238
                tracing::debug!(
                    "monitor_instance_source: iteration={}, instance_count={}, instance_ids={:?}, endpoint={}",
                    iteration,
                    instance_ids.len(),
                    instance_ids,
                    endpoint_path
                );

239
240
                // TODO: this resets both tracked available and free instances
                client.instance_avail.store(Arc::new(instance_ids.clone()));
241
                client.instance_free.store(Arc::new(instance_ids.clone()));
242

243
244
245
246
                tracing::debug!(
                    "monitor_instance_source: instance source updated, endpoint={}",
                    endpoint_path
                );
247
248

                if let Err(err) = rx.changed().await {
249
250
251
252
253
                    tracing::error!(
                        "monitor_instance_source: The Sender is dropped: {}, endpoint={}",
                        err,
                        endpoint_path
                    );
254
255
                    cancel_token.cancel();
                }
256
                iteration += 1;
257
            }
258
259
260
261
            tracing::debug!(
                "monitor_instance_source: Monitor loop exiting for endpoint: {}",
                endpoint_path
            );
262
        });
263
264
265
266
267
268
269
270
271
    }

    async fn get_or_create_dynamic_instance_source(
        endpoint: &Endpoint,
    ) -> Result<Arc<InstanceSource>> {
        let drt = endpoint.drt();
        let instance_sources = drt.instance_sources();
        let mut instance_sources = instance_sources.lock().await;

272
273
274
275
276
        tracing::debug!(
            "get_or_create_dynamic_instance_source: Checking cache for endpoint: {}",
            endpoint.path()
        );

277
278
        if let Some(instance_source) = instance_sources.get(endpoint) {
            if let Some(instance_source) = instance_source.upgrade() {
279
280
281
282
                tracing::debug!(
                    "get_or_create_dynamic_instance_source: Found cached instance source for endpoint: {}",
                    endpoint.path()
                );
283
284
                return Ok(instance_source);
            } else {
285
286
287
288
                tracing::debug!(
                    "get_or_create_dynamic_instance_source: Cached instance source was dropped, removing for endpoint: {}",
                    endpoint.path()
                );
289
290
291
292
                instance_sources.remove(endpoint);
            }
        }

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        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
319
320
321
322
323
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

        let secondary = endpoint.component.drt.runtime.secondary().clone();

        secondary.spawn(async move {
324
325
326
            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
327
328

            loop {
329
                let discovery_event = tokio::select! {
Ryan Olson's avatar
Ryan Olson committed
330
                    _ = watch_tx.closed() => {
331
                        tracing::debug!("endpoint_watcher: all watchers have closed; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
332
333
                        break;
                    }
334
335
336
337
338
339
340
341
342
343
344
                    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
345
                            None => {
346
                                tracing::debug!("endpoint_watcher: watch stream has closed; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
347
348
349
350
351
352
                                break;
                            }
                        }
                    }
                };

353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
                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
371
372
                            }
                        }
373
374
375
376
377
378
379
380
                    }
                    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
381
382
383
                    }
                }

384
                let instances: Vec<Instance> = map.values().cloned().collect();
385
386
387
388
389
                tracing::debug!(
                    "endpoint_watcher: Current map size={}, sending update for discovery query: {:?}",
                    instances.len(),
                    discovery_query
                );
Ryan Olson's avatar
Ryan Olson committed
390

391
                if watch_tx.send(instances).is_err() {
392
                    tracing::debug!("endpoint_watcher: Unable to send watch updates; shutting down for discovery query: {:?}", discovery_query);
Ryan Olson's avatar
Ryan Olson committed
393
394
395
396
                    break;
                }
            }

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

401
402
        let instance_source = Arc::new(InstanceSource::Dynamic(watch_rx));
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
403
404
405
406
        tracing::debug!(
            "get_or_create_dynamic_instance_source: Successfully created and cached instance source for endpoint: {}",
            endpoint.path()
        );
407
        Ok(instance_source)
408
    }
Ryan Olson's avatar
Ryan Olson committed
409
}