/build/source/nativelink-scheduler/src/grpc_scheduler.rs
Line | Count | Source |
1 | | // Copyright 2024 Trace Machina, Inc. All rights reserved. |
2 | | // |
3 | | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // See LICENSE file for details |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use core::future::Future; |
16 | | use core::time::Duration; |
17 | | use std::collections::HashMap; |
18 | | use std::sync::Arc; |
19 | | |
20 | | use async_trait::async_trait; |
21 | | use futures::stream::unfold; |
22 | | use futures::{StreamExt, TryFutureExt}; |
23 | | use nativelink_config::schedulers::GrpcSpec; |
24 | | use nativelink_error::{Code, Error, ResultExt, error_if, make_err}; |
25 | | use nativelink_metric::{MetricsComponent, RootMetricsComponent}; |
26 | | use nativelink_proto::build::bazel::remote::execution::v2::capabilities_client::CapabilitiesClient; |
27 | | use nativelink_proto::build::bazel::remote::execution::v2::execution_client::ExecutionClient; |
28 | | use nativelink_proto::build::bazel::remote::execution::v2::{ |
29 | | ExecuteRequest, ExecutionPolicy, GetCapabilitiesRequest, WaitExecutionRequest, |
30 | | }; |
31 | | use nativelink_proto::google::longrunning::Operation; |
32 | | use nativelink_util::action_messages::{ |
33 | | ActionInfo, ActionState, ActionUniqueQualifier, DEFAULT_EXECUTION_PRIORITY, OperationId, |
34 | | }; |
35 | | use nativelink_util::connection_manager::ConnectionManager; |
36 | | use nativelink_util::operation_state_manager::{ |
37 | | ActionStateResult, ActionStateResultStream, ClientStateManager, OperationFilter, |
38 | | }; |
39 | | use nativelink_util::origin_event::OriginMetadata; |
40 | | use nativelink_util::retry::{Retrier, RetryResult}; |
41 | | use nativelink_util::telemetry::{forward_client_headers, inject_context}; |
42 | | use nativelink_util::{background_spawn, tls_utils}; |
43 | | use parking_lot::Mutex; |
44 | | use tokio::select; |
45 | | use tokio::sync::watch; |
46 | | use tokio::time::sleep; |
47 | | use tonic::{Request, Streaming}; |
48 | | use tracing::{error, info, warn}; |
49 | | |
50 | | use crate::known_platform_property_provider::KnownPlatformPropertyProvider; |
51 | | |
52 | | struct GrpcActionStateResult { |
53 | | client_operation_id: OperationId, |
54 | | rx: watch::Receiver<Arc<ActionState>>, |
55 | | /// Why the upstream's stream ended, when it ended with an error. |
56 | | ended_by: Arc<Mutex<Option<Error>>>, |
57 | | } |
58 | | |
59 | | #[async_trait] |
60 | | impl ActionStateResult for GrpcActionStateResult { |
61 | 6 | async fn as_state(&self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> { |
62 | | let mut action_state = self.rx.borrow().clone(); |
63 | | Arc::make_mut(&mut action_state).client_operation_id = self.client_operation_id.clone(); |
64 | | // TODO(palfrey) We currently don't support OriginMetadata in this implementation, but |
65 | | // we should. |
66 | | Ok((action_state, None)) |
67 | 6 | } |
68 | | |
69 | 24 | async fn changed(&mut self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> { |
70 | | // The channel closes when the upstream's stream ends, which before |
71 | | // the operation finishes means the upstream scheduler went away. That |
72 | | // is `Unavailable`, so the client retries; `Internal` it would not. |
73 | | if self.rx.changed().await.is_err() { |
74 | | let err = make_err!( |
75 | | Code::Unavailable, |
76 | | "The upstream scheduler's stream ended before the operation finished" |
77 | | ); |
78 | | let upstream = self.ended_by.lock().take(); |
79 | | return Err(match upstream { |
80 | | Some(upstream) => err.append(format!( |
81 | | "upstream: {:?}: {}", |
82 | | upstream.code, |
83 | | upstream.message_string() |
84 | | )), |
85 | | None => err, |
86 | | }); |
87 | | } |
88 | | let mut action_state = self.rx.borrow().clone(); |
89 | | Arc::make_mut(&mut action_state).client_operation_id = self.client_operation_id.clone(); |
90 | | // TODO(palfrey) We currently don't support OriginMetadata in this implementation, but |
91 | | // we should. |
92 | | Ok((action_state, None)) |
93 | 24 | } |
94 | | |
95 | 0 | async fn as_action_info(&self) -> Result<(Arc<ActionInfo>, Option<OriginMetadata>), Error> { |
96 | | // TODO(palfrey) We should probably remove as_action_info() |
97 | | // or implement it properly. |
98 | | return Err(make_err!( |
99 | | Code::Unimplemented, |
100 | | "as_action_info not implemented for GrpcActionStateResult::as_action_info" |
101 | | )); |
102 | 0 | } |
103 | | } |
104 | | |
105 | | #[derive(Debug, MetricsComponent)] |
106 | | pub struct GrpcScheduler { |
107 | | #[metric(group = "property_managers")] |
108 | | supported_props: Mutex<HashMap<String, Vec<String>>>, |
109 | | retrier: Retrier, |
110 | | connection_manager: ConnectionManager, |
111 | | forward_headers: Vec<String>, |
112 | | } |
113 | | |
114 | | impl GrpcScheduler { |
115 | 11 | pub fn new(spec: &GrpcSpec) -> Result<Self, Error> { |
116 | 11 | Self::new_with_jitter(spec, spec.retry.make_jitter_fn()) |
117 | 11 | } |
118 | | |
119 | 11 | pub fn new_with_jitter( |
120 | 11 | spec: &GrpcSpec, |
121 | 11 | jitter_fn: Arc<dyn Fn(Duration) -> Duration + Send + Sync>, |
122 | 11 | ) -> Result<Self, Error> { |
123 | 11 | let endpoint = tls_utils::endpoint(&spec.endpoint)?0 ; |
124 | | Ok(Self { |
125 | 11 | supported_props: Mutex::new(HashMap::new()), |
126 | 11 | retrier: Retrier::new( |
127 | 11 | Arc::new(|duration| Box::pin0 (sleep0 (duration0 ))), |
128 | 11 | jitter_fn.clone(), |
129 | 11 | spec.retry.clone(), |
130 | | ) |
131 | 11 | .with_client("grpc_scheduler"), |
132 | 11 | connection_manager: ConnectionManager::new( |
133 | 11 | core::iter::once(endpoint), |
134 | 11 | spec.connections_per_endpoint, |
135 | 11 | spec.max_concurrent_requests, |
136 | 11 | spec.retry.clone(), |
137 | 11 | jitter_fn, |
138 | | ), |
139 | 11 | forward_headers: spec |
140 | 11 | .forward_headers |
141 | 11 | .iter() |
142 | 11 | .map(|name| name1 .to_lowercase1 ()) |
143 | 11 | .collect(), |
144 | | }) |
145 | 11 | } |
146 | | |
147 | | /// Wraps a message for the upstream with what this server was handed: the |
148 | | /// client's nominated headers, the trace and the baggage. The upstream |
149 | | /// reads the identity and the build metadata from the baggage as this |
150 | | /// server did; a bare request would leave its origin events anonymous and |
151 | | /// its buck2 isolation off. |
152 | 12 | fn enrich_request<T>(&self, message: T) -> Request<T> { |
153 | 12 | let mut request = Request::new(message); |
154 | 12 | forward_client_headers(&mut request, &self.forward_headers); |
155 | 12 | inject_context(&mut request); |
156 | 12 | request |
157 | 12 | } |
158 | | |
159 | 12 | async fn perform_request<F, Fut, R, I>(&self, input: I, mut request: F) -> Result<R, Error> |
160 | 12 | where |
161 | 12 | F: FnMut(I) -> Fut + Send + Copy, |
162 | 12 | Fut: Future<Output = Result<R, Error>> + Send, |
163 | 12 | R: Send, |
164 | 12 | I: Send + Clone, |
165 | 12 | { |
166 | 12 | self.retrier |
167 | 12 | .retry(unfold(input, move |input| async move { |
168 | 12 | let input_clone = input.clone(); |
169 | | Some(( |
170 | 12 | request(input_clone) |
171 | 12 | .await |
172 | 12 | .map_or_else(RetryResult::Retry, RetryResult::Ok), |
173 | 12 | input, |
174 | | )) |
175 | 24 | })) |
176 | 12 | .await |
177 | 12 | } |
178 | | |
179 | 11 | async fn stream_state( |
180 | 11 | mut result_stream: Streaming<Operation>, |
181 | 11 | ) -> Result<Box<dyn ActionStateResult>, Error> { |
182 | 11 | if let Some(initial_response) = result_stream |
183 | 11 | .message() |
184 | 11 | .await |
185 | 11 | .err_tip(|| "Receiving response from upstream scheduler")?0 |
186 | | { |
187 | 11 | let client_operation_id = OperationId::from(initial_response.name.as_str()); |
188 | | // Our operation_id is not needed here is just a place holder to recycle existing object. |
189 | | // The only thing that actually matters is the operation_id. |
190 | 11 | let operation_id = OperationId::default(); |
191 | 11 | let action_state = |
192 | 11 | ActionState::try_from_operation(initial_response, operation_id.clone()) |
193 | 11 | .err_tip(|| "In GrpcScheduler::stream_state")?0 ; |
194 | 11 | let (tx, mut rx) = watch::channel(Arc::new(action_state)); |
195 | 11 | rx.mark_changed(); |
196 | 11 | let ended_by = Arc::new(Mutex::new(None)); |
197 | 11 | let stream_ended_by = ended_by.clone(); |
198 | 11 | background_spawn!("grpc_scheduler_stream_state", async move {10 |
199 | | loop { |
200 | 22 | select!( |
201 | 22 | () = tx.closed() => { |
202 | 4 | info!( |
203 | | "Client disconnected in GrpcScheduler" |
204 | | ); |
205 | 4 | return; |
206 | | } |
207 | 22 | response17 = result_stream.message() => { |
208 | | // When the upstream closes the channel, close the |
209 | | // downstream too, saying why if it said. |
210 | 14 | let response12 = match response { |
211 | 12 | Ok(Some(response)) => response, |
212 | 2 | Ok(None) => return, |
213 | 3 | Err(status) => { |
214 | 3 | *stream_ended_by.lock() = Some(status.into()); |
215 | 3 | return; |
216 | | } |
217 | | }; |
218 | 12 | let maybe_action_state = ActionState::try_from_operation(response, operation_id.clone()); |
219 | 12 | match maybe_action_state { |
220 | 12 | Ok(response) => { |
221 | 12 | if let Err(err0 ) = tx.send(Arc::new(response)) { |
222 | 0 | info!( |
223 | | ?err, |
224 | | "Client error in GrpcScheduler" |
225 | | ); |
226 | 0 | return; |
227 | 12 | } |
228 | | } |
229 | 0 | Err(err) => { |
230 | 0 | error!( |
231 | | ?err, |
232 | | "Error converting response to ActionState in GrpcScheduler" |
233 | | ); |
234 | | }, |
235 | | } |
236 | | } |
237 | | ); |
238 | | } |
239 | 9 | }); |
240 | | |
241 | 11 | return Ok(Box::new(GrpcActionStateResult { |
242 | 11 | client_operation_id, |
243 | 11 | rx, |
244 | 11 | ended_by, |
245 | 11 | })); |
246 | 0 | } |
247 | | // Closed before its first message: the upstream went away. |
248 | 0 | Err(make_err!( |
249 | 0 | Code::Unavailable, |
250 | 0 | "Upstream scheduler closed the stream before answering" |
251 | 0 | )) |
252 | 11 | } |
253 | | |
254 | 1 | async fn inner_get_known_properties(&self, instance_name: &str) -> Result<Vec<String>, Error> { |
255 | 1 | if let Some(supported_props0 ) = self.supported_props.lock().get(instance_name) { |
256 | 0 | return Ok(supported_props.clone()); |
257 | 1 | } |
258 | | |
259 | 1 | self.perform_request(instance_name, |instance_name| async move { |
260 | | // Not in the cache, lookup the capabilities with the upstream. |
261 | 1 | let channel = self |
262 | 1 | .connection_manager |
263 | 1 | .connection("get_known_properties".into()) |
264 | 1 | .await |
265 | 1 | .err_tip(|| "in get_platform_property_manager()")?0 ; |
266 | 1 | let capabilities_result = CapabilitiesClient::new(channel) |
267 | 1 | .get_capabilities(self.enrich_request(GetCapabilitiesRequest { |
268 | 1 | instance_name: instance_name.to_string(), |
269 | 1 | })) |
270 | 1 | .await |
271 | 1 | .err_tip(|| "Retrieving upstream GrpcScheduler capabilities"); |
272 | 1 | let capabilities = capabilities_result?0 .into_inner(); |
273 | 1 | let supported_props = capabilities |
274 | 1 | .execution_capabilities |
275 | 1 | .err_tip(|| "Unable to get execution properties in GrpcScheduler")?0 |
276 | | .supported_node_properties |
277 | 1 | .into_iter() |
278 | 1 | .collect::<Vec<String>>(); |
279 | | |
280 | 1 | self.supported_props |
281 | 1 | .lock() |
282 | 1 | .insert(instance_name.to_string(), supported_props.clone()); |
283 | 1 | Ok(supported_props) |
284 | 2 | }) |
285 | 1 | .await |
286 | 1 | } |
287 | | |
288 | 6 | async fn inner_add_action( |
289 | 6 | &self, |
290 | 6 | _client_operation_id: OperationId, |
291 | 6 | action_info: Arc<ActionInfo>, |
292 | 6 | ) -> Result<Box<dyn ActionStateResult>, Error> { |
293 | 6 | let execution_policy = if action_info.priority == DEFAULT_EXECUTION_PRIORITY { |
294 | 6 | None |
295 | | } else { |
296 | 0 | Some(ExecutionPolicy { |
297 | 0 | priority: action_info.priority, |
298 | 0 | }) |
299 | | }; |
300 | 6 | let skip_cache_lookup = match action_info.unique_qualifier { |
301 | 6 | ActionUniqueQualifier::Cacheable(_) => false, |
302 | 0 | ActionUniqueQualifier::Uncacheable(_) => true, |
303 | | }; |
304 | 6 | let request = ExecuteRequest { |
305 | 6 | instance_name: action_info.instance_name().clone(), |
306 | 6 | skip_cache_lookup, |
307 | 6 | action_digest: Some(action_info.digest().into()), |
308 | 6 | execution_policy, |
309 | 6 | // TODO: Get me from the original request, not very important as we ignore it. |
310 | 6 | results_cache_policy: None, |
311 | 6 | digest_function: action_info |
312 | 6 | .unique_qualifier |
313 | 6 | .digest_function() |
314 | 6 | .proto_digest_func() |
315 | 6 | .into(), |
316 | 6 | // Hints only (REAPI v2.9), and not carried in `ActionInfo`, so a |
317 | 6 | // forwarded request does not ask the upstream to inline outputs. |
318 | 6 | inline_stdout: false, |
319 | 6 | inline_stderr: false, |
320 | 6 | inline_output_files: Vec::new(), |
321 | 6 | }; |
322 | 6 | let result_stream = self |
323 | 6 | .perform_request(request, |request| async move { |
324 | 6 | let channel = self |
325 | 6 | .connection_manager |
326 | 6 | .connection(format!("add_action: {:?}", request.action_digest)) |
327 | 6 | .await |
328 | 6 | .err_tip(|| "in add_action()")?0 ; |
329 | 6 | ExecutionClient::new(channel) |
330 | 6 | .execute(self.enrich_request(request)) |
331 | 6 | .await |
332 | 6 | .err_tip(|| "Sending action to upstream scheduler") |
333 | 12 | }) |
334 | 6 | .await?0 |
335 | 6 | .into_inner(); |
336 | 6 | Self::stream_state(result_stream).await |
337 | 6 | } |
338 | | |
339 | 5 | async fn inner_filter_operations( |
340 | 5 | &self, |
341 | 5 | filter: OperationFilter, |
342 | 5 | ) -> Result<ActionStateResultStream<'_>, Error> { |
343 | 0 | error_if!( |
344 | 5 | filter |
345 | 5 | != OperationFilter { |
346 | 5 | client_operation_id: filter.client_operation_id.clone(), |
347 | 5 | ..Default::default() |
348 | 5 | }, |
349 | | "Unsupported filter in GrpcScheduler::filter_operations. Only client_operation_id is supported - {filter:?}" |
350 | | ); |
351 | 5 | let client_operation_id = filter.client_operation_id.ok_or_else(|| {0 |
352 | 0 | make_err!(Code::InvalidArgument, "`client_operation_id` is the only supported filter in GrpcScheduler::filter_operations") |
353 | 0 | })?; |
354 | 5 | let request = WaitExecutionRequest { |
355 | 5 | name: client_operation_id.to_string(), |
356 | 5 | }; |
357 | 5 | let result_stream = self |
358 | 5 | .perform_request(request, |request| async move { |
359 | 5 | let channel = self |
360 | 5 | .connection_manager |
361 | 5 | .connection(format!("filter_operations: {}", request.name)) |
362 | 5 | .await |
363 | 5 | .err_tip(|| "in find_by_client_operation_id()")?0 ; |
364 | 5 | ExecutionClient::new(channel) |
365 | 5 | .wait_execution(self.enrich_request(request)) |
366 | 5 | .await |
367 | 5 | .err_tip(|| "While getting wait_execution stream") |
368 | 10 | }) |
369 | 5 | .and_then(|result_stream| Self::stream_state(result_stream.into_inner())) |
370 | 5 | .await; |
371 | 5 | match result_stream { |
372 | 5 | Ok(result_stream) => Ok(unfold( |
373 | 5 | Some(result_stream), |
374 | 10 | |maybe_result_stream| async move {5 maybe_result_stream5 .map5 (|v| (v5 , None5 )) }, |
375 | | ) |
376 | 5 | .boxed()), |
377 | 0 | Err(err) => { |
378 | 0 | warn!(?err, "Error looking up action with upstream scheduler"); |
379 | 0 | Ok(futures::stream::empty().boxed()) |
380 | | } |
381 | | } |
382 | 5 | } |
383 | | } |
384 | | |
385 | | #[async_trait] |
386 | | impl ClientStateManager for GrpcScheduler { |
387 | | async fn add_action( |
388 | | &self, |
389 | | client_operation_id: OperationId, |
390 | | action_info: Arc<ActionInfo>, |
391 | 6 | ) -> Result<Box<dyn ActionStateResult>, Error> { |
392 | | self.inner_add_action(client_operation_id, action_info) |
393 | | .await |
394 | 6 | } |
395 | | |
396 | | async fn filter_operations<'a>( |
397 | | &'a self, |
398 | | filter: OperationFilter, |
399 | 5 | ) -> Result<ActionStateResultStream<'a>, Error> { |
400 | | self.inner_filter_operations(filter).await |
401 | 5 | } |
402 | | } |
403 | | |
404 | | #[async_trait] |
405 | | impl KnownPlatformPropertyProvider for GrpcScheduler { |
406 | 1 | async fn get_known_properties(&self, instance_name: &str) -> Result<Vec<String>, Error> { |
407 | | self.inner_get_known_properties(instance_name).await |
408 | 1 | } |
409 | | } |
410 | | |
411 | | impl RootMetricsComponent for GrpcScheduler {} |