client.rs 10.5 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

use crate::pipeline::{
5
6
    AddressedPushRouter, AddressedRequest, AsyncEngine, Data, ManyOut, PushRouter, RouterMode,
    SingleIn,
Ryan Olson's avatar
Ryan Olson committed
7
};
8
use arc_swap::ArcSwap;
Ryan Olson's avatar
Ryan Olson committed
9
10
use rand::Rng;
use std::collections::HashMap;
11
use std::sync::RwLock;
Ryan Olson's avatar
Ryan Olson committed
12
13
use std::sync::{
    atomic::{AtomicU64, Ordering},
14
    Arc, Mutex,
Ryan Olson's avatar
Ryan Olson committed
15
};
16
17
use std::time::Instant;
use tokio::net::unix::pipe::Receiver;
Ryan Olson's avatar
Ryan Olson committed
18

19
20
21
22
use crate::{
    pipeline::async_trait,
    transports::etcd::{Client as EtcdClient, WatchEvent},
};
Ryan Olson's avatar
Ryan Olson committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

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 {
    Put(String, i64),
    Delete(String),
}

45
46
47
48
#[derive(Clone, Debug)]
pub struct Client {
    // This is me
    pub endpoint: Endpoint,
49
    // These are the remotes I know about from watching etcd
50
    pub instance_source: Arc<InstanceSource>,
51
    // These are the instances that are reported as down from sending rpc
52
53
54
    instance_inhibited: Arc<Mutex<HashMap<i64, Instant>>>,
    // The current active IDs
    instance_cache: Arc<ArcSwap<Vec<i64>>>,
55
56
57
}

#[derive(Clone, Debug)]
58
pub enum InstanceSource {
59
    Static,
60
    Dynamic(tokio::sync::watch::Receiver<Vec<Instance>>),
Ryan Olson's avatar
Ryan Olson committed
61
62
}

63
64
// TODO: Avoid returning a full clone of `Vec<Instance>` everytime from Client
//       See instances() and instances_avail() methods
65
impl Client {
66
67
68
69
    // Client will only talk to a single static endpoint
    pub(crate) async fn new_static(endpoint: Endpoint) -> Result<Self> {
        Ok(Client {
            endpoint,
70
            instance_source: Arc::new(InstanceSource::Static),
71
            instance_inhibited: Arc::new(Mutex::new(HashMap::new())),
72
            instance_cache: Arc::new(ArcSwap::from(Arc::new(vec![]))),
73
74
        })
    }
Ryan Olson's avatar
Ryan Olson committed
75

76
    // Client with auto-discover instances using etcd
77
    pub(crate) async fn new_dynamic(endpoint: Endpoint) -> Result<Self> {
78
79
        const INSTANCE_REFRESH_PERIOD: Duration = Duration::from_secs(1);

Ryan Olson's avatar
Ryan Olson committed
80
        // create live endpoint watcher
81
82
83
        let Some(etcd_client) = &endpoint.component.drt.etcd_client else {
            anyhow::bail!("Attempt to create a dynamic client on a static endpoint");
        };
84
85
86
87

        let instance_source =
            Self::get_or_create_dynamic_instance_source(etcd_client, &endpoint).await?;

88
89
        let cancel_token = endpoint.drt().primary_token();
        let client = Client {
90
91
            endpoint,
            instance_source,
92
            instance_inhibited: Arc::new(Mutex::new(HashMap::new())),
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
            instance_cache: Arc::new(ArcSwap::from(Arc::new(vec![]))),
        };

        let instance_source_c = client.instance_source.clone();
        let instance_inhibited_c = Arc::clone(&client.instance_inhibited);
        let instance_cache_c = Arc::clone(&client.instance_cache);
        tokio::task::spawn(async move {
            while !cancel_token.is_cancelled() {
                refresh_instances(&instance_source_c, &instance_inhibited_c, &instance_cache_c);
                tokio::select! {
                    _ = cancel_token.cancelled() => {}
                    _ = tokio::time::sleep(INSTANCE_REFRESH_PERIOD) => {}
                }
            }
        });
        Ok(client)
109
110
111
112
113
114
115
116
117
118
119
    }

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

120
    /// Instances available from watching etcd
121
    pub fn instances(&self) -> Vec<Instance> {
122
        instances_inner(self.instance_source.as_ref())
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    }

    pub fn instance_ids(&self) -> Vec<i64> {
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
        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
            loop {
                instances = rx.borrow_and_update().to_vec();
                if instances.is_empty() {
                    rx.changed().await?;
                } else {
                    break;
                }
            }
        }
        Ok(instances)
    }

146
    /// Instances available from watching etcd minus those reported as down
147
148
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<i64>>> {
        self.instance_cache.load()
149
150
151
    }

    /// Mark an instance as down/unavailable
152
153
154
155
156
    pub fn report_instance_down(&self, instance_id: i64) {
        self.instance_inhibited
            .lock()
            .unwrap()
            .insert(instance_id, Instant::now());
157
158
159
160

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

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    /// 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)
    }

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

        if let Some(instance_source) = instance_sources.get(endpoint) {
            if let Some(instance_source) = instance_source.upgrade() {
                return Ok(instance_source);
            } else {
                instance_sources.remove(endpoint);
            }
        }

182
        let prefix_watcher = etcd_client
183
            .kv_get_and_watch_prefix(endpoint.etcd_root())
Ryan Olson's avatar
Ryan Olson committed
184
185
186
187
188
189
190
191
192
193
194
195
            .await?;

        let (prefix, _watcher, mut kv_event_rx) = prefix_watcher.dissolve();

        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

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

        // this task should be included in the registry
        // currently this is created once per client, but this object/task should only be instantiated
        // once per worker/instance
        secondary.spawn(async move {
196
            tracing::debug!("Starting endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
197
198
199
200
201
            let mut map = HashMap::new();

            loop {
                let kv_event = tokio::select! {
                    _ = watch_tx.closed() => {
202
                        tracing::debug!("all watchers have closed; shutting down endpoint watcher for prefix: {prefix}");
Ryan Olson's avatar
Ryan Olson committed
203
204
205
206
207
208
                        break;
                    }
                    kv_event = kv_event_rx.recv() => {
                        match kv_event {
                            Some(kv_event) => kv_event,
                            None => {
209
                                tracing::debug!("watch stream has closed; shutting down endpoint watcher for prefix: {prefix}");
Ryan Olson's avatar
Ryan Olson committed
210
211
212
213
214
215
216
217
218
                                break;
                            }
                        }
                    }
                };

                match kv_event {
                    WatchEvent::Put(kv) => {
                        let key = String::from_utf8(kv.key().to_vec());
219
                        let val = serde_json::from_slice::<Instance>(kv.value());
Ryan Olson's avatar
Ryan Olson committed
220
                        if let (Ok(key), Ok(val)) = (key, val) {
221
                            map.insert(key.clone(), val);
Ryan Olson's avatar
Ryan Olson committed
222
                        } else {
223
                            tracing::error!("Unable to parse put endpoint event; shutting down endpoint watcher for prefix: {prefix}");
Ryan Olson's avatar
Ryan Olson committed
224
225
226
227
228
229
230
                            break;
                        }
                    }
                    WatchEvent::Delete(kv) => {
                        match String::from_utf8(kv.key().to_vec()) {
                            Ok(key) => { map.remove(&key); }
                            Err(_) => {
231
                                tracing::error!("Unable to parse delete endpoint event; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
232
233
234
235
236
237
                                break;
                            }
                        }
                    }
                }

238
                let instances: Vec<Instance> = map.values().cloned().collect();
Ryan Olson's avatar
Ryan Olson committed
239

240
                if watch_tx.send(instances).is_err() {
241
                    tracing::debug!("Unable to send watch updates; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
242
243
244
245
246
                    break;
                }

            }

247
            tracing::debug!("Completed endpoint watcher for prefix: {prefix}");
Ryan Olson's avatar
Ryan Olson committed
248
249
250
            let _ = watch_tx.send(vec![]);
        });

251
252
253
        let instance_source = Arc::new(InstanceSource::Dynamic(watch_rx));
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
        Ok(instance_source)
254
    }
Ryan Olson's avatar
Ryan Olson committed
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

/// Update the instance id cache
fn refresh_instances(
    instance_source: &InstanceSource,
    instance_inhibited: &Arc<Mutex<HashMap<i64, Instant>>>,
    instance_cache: &Arc<ArcSwap<Vec<i64>>>,
) {
    const ETCD_LEASE_TTL: u64 = 10; // seconds

    // TODO: Can we get the remaining TTL from the lease for the instance?
    let now = Instant::now();

    let instances = instances_inner(instance_source);
    let mut inhibited = instance_inhibited.lock().unwrap();

    // 1. Remove inhibited instances that are no longer in `self.instances()`
    // 2. Remove inhibited instances that have expired
    // 3. Only return instances that are not inhibited after removals
    let mut new_inhibited = HashMap::<i64, Instant>::new();
    let filtered: Vec<i64> = instances
        .into_iter()
        .filter_map(|instance| {
            let id = instance.id();
            if let Some(&timestamp) = inhibited.get(&id) {
                if now.duration_since(timestamp).as_secs() > ETCD_LEASE_TTL {
                    Some(id)
                } else {
                    new_inhibited.insert(id, timestamp);
                    None
                }
            } else {
                Some(id)
            }
        })
        .collect();

    *inhibited = new_inhibited;
    instance_cache.store(Arc::new(filtered));
}

fn instances_inner(instance_source: &InstanceSource) -> Vec<Instance> {
    match instance_source {
        InstanceSource::Static => vec![],
        InstanceSource::Dynamic(watch_rx) => watch_rx.borrow().clone(),
    }
}