Coverage Report

Created: 2024-10-22 12:33

/build/source/nativelink-worker/src/local_worker.rs
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (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
//    http://www.apache.org/licenses/LICENSE-2.0
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 std::pin::Pin;
16
use std::process::Stdio;
17
use std::str;
18
use std::sync::atomic::{AtomicU64, Ordering};
19
use std::sync::{Arc, Weak};
20
use std::time::Duration;
21
22
use futures::future::BoxFuture;
23
use futures::stream::FuturesUnordered;
24
use futures::{select, Future, FutureExt, StreamExt, TryFutureExt};
25
use nativelink_config::cas_server::LocalWorkerConfig;
26
use nativelink_error::{make_err, make_input_err, Code, Error, ResultExt};
27
use nativelink_metric::{MetricsComponent, RootMetricsComponent};
28
use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::update_for_worker::Update;
29
use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::worker_api_client::WorkerApiClient;
30
use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{
31
    execute_result, ExecuteResult, KeepAliveRequest, UpdateForWorker,
32
};
33
use nativelink_store::fast_slow_store::FastSlowStore;
34
use nativelink_util::action_messages::{ActionResult, ActionStage, OperationId};
35
use nativelink_util::common::fs;
36
use nativelink_util::digest_hasher::{DigestHasherFunc, ACTIVE_HASHER_FUNC};
37
use nativelink_util::metrics_utils::{AsyncCounterWrapper, CounterWithTime};
38
use nativelink_util::origin_context::ActiveOriginContext;
39
use nativelink_util::store_trait::Store;
40
use nativelink_util::{spawn, tls_utils};
41
use tokio::process;
42
use tokio::sync::mpsc;
43
use tokio::time::sleep;
44
use tokio_stream::wrappers::UnboundedReceiverStream;
45
use tonic::Streaming;
46
use tracing::{event, info_span, instrument, Level};
47
48
use crate::running_actions_manager::{
49
    ExecutionConfiguration, Metrics as RunningActionManagerMetrics, RunningAction,
50
    RunningActionsManager, RunningActionsManagerArgs, RunningActionsManagerImpl,
51
};
52
use crate::worker_api_client_wrapper::{WorkerApiClientTrait, WorkerApiClientWrapper};
53
use crate::worker_utils::make_supported_properties;
54
55
/// Amount of time to wait if we have actions in transit before we try to
56
/// consider an error to have occurred.
57
const ACTIONS_IN_TRANSIT_TIMEOUT_S: f32 = 10.;
58
59
/// If we loose connection to the worker api server we will wait this many seconds
60
/// before trying to connect.
61
const CONNECTION_RETRY_DELAY_S: f32 = 0.5;
62
63
/// Default endpoint timeout. If this value gets modified the documentation in
64
/// `cas_server.rs` must also be updated.
65
const DEFAULT_ENDPOINT_TIMEOUT_S: f32 = 5.;
66
67
/// Default maximum amount of time a task is allowed to run for.
68
/// If this value gets modified the documentation in `cas_server.rs` must also be updated.
69
const DEFAULT_MAX_ACTION_TIMEOUT: Duration = Duration::from_secs(1200); // 20 mins.
70
71
struct LocalWorkerImpl<'a, T: WorkerApiClientTrait, U: RunningActionsManager> {
72
    config: &'a LocalWorkerConfig,
73
    // According to the tonic documentation it is a cheap operation to clone this.
74
    grpc_client: T,
75
    worker_id: String,
76
    running_actions_manager: Arc<U>,
77
    // Number of actions that have been received in `Update::StartAction`, but
78
    // not yet processed by running_actions_manager's spawn. This number should
79
    // always be zero if there are no actions running and no actions being waited
80
    // on by the scheduler.
81
    actions_in_transit: Arc<AtomicU64>,
82
    metrics: Arc<Metrics>,
83
}
84
85
4
async fn preconditions_met(precondition_script: Option<String>) -> Result<(), Error> {
86
4
    let Some(
precondition_script1
) = &precondition_script else {
  Branch (86:9): [True: 1, False: 3]
  Branch (86:9): [Folded - Ignored]
  Branch (86:9): [Folded - Ignored]
87
        // No script means we are always ok to proceed.
88
3
        return Ok(());
89
    };
90
    // TODO: Might want to pass some information about the command to the
91
    //       script, but at this point it's not even been downloaded yet,
92
    //       so that's not currently possible.  Perhaps we'll move this in
93
    //       future to pass useful information through?  Or perhaps we'll
94
    //       have a pre-condition and a pre-execute script instead, although
95
    //       arguably entrypoint already gives us that.
96
1
    let precondition_process = process::Command::new(precondition_script)
97
1
        .kill_on_drop(true)
98
1
        .stdin(Stdio::null())
99
1
        .stdout(Stdio::piped())
100
1
        .stderr(Stdio::null())
101
1
        .env_clear()
102
1
        .spawn()
103
1
        .err_tip(|| 
format!("Could not execute precondition command {precondition_script:?}")0
)
?0
;
104
1
    let output = precondition_process.wait_with_output().await
?0
;
105
1
    if output.status.code() == Some(0) {
  Branch (105:8): [True: 0, False: 1]
  Branch (105:8): [Folded - Ignored]
  Branch (105:8): [Folded - Ignored]
106
0
        Ok(())
107
    } else {
108
1
        Err(make_err!(
109
1
            Code::ResourceExhausted,
110
1
            "Preconditions script returned status {} - {}",
111
1
            output.status,
112
1
            str::from_utf8(&output.stdout).unwrap_or("")
113
1
        ))
114
    }
115
4
}
116
117
impl<'a, T: WorkerApiClientTrait, U: RunningActionsManager> LocalWorkerImpl<'a, T, U> {
118
5
    fn new(
119
5
        config: &'a LocalWorkerConfig,
120
5
        grpc_client: T,
121
5
        worker_id: String,
122
5
        running_actions_manager: Arc<U>,
123
5
        metrics: Arc<Metrics>,
124
5
    ) -> Self {
125
5
        Self {
126
5
            config,
127
5
            grpc_client,
128
5
            worker_id,
129
5
            running_actions_manager,
130
5
            // Number of actions that have been received in `Update::StartAction`, but
131
5
            // not yet processed by running_actions_manager's spawn. This number should
132
5
            // always be zero if there are no actions running and no actions being waited
133
5
            // on by the scheduler.
134
5
            actions_in_transit: Arc::new(AtomicU64::new(0)),
135
5
            metrics,
136
5
        }
137
5
    }
138
139
    /// Starts a background spawn/thread that will send a message to the server every `timeout / 2`.
140
5
    async fn start_keep_alive(&self) -> Result<(), Error> {
141
5
        // According to tonic's documentation this call should be cheap and is the same stream.
142
5
        let mut grpc_client = self.grpc_client.clone();
143
144
        loop {
145
5
            let timeout = self
146
5
                .config
147
5
                .worker_api_endpoint
148
5
                .timeout
149
5
                .unwrap_or(DEFAULT_ENDPOINT_TIMEOUT_S);
150
5
            // We always send 2 keep alive requests per timeout. Http2 should manage most of our
151
5
            // timeout issues, this is a secondary check to ensure we can still send data.
152
5
            sleep(Duration::from_secs_f32(timeout / 2.)).
await0
;
153
0
            if let Err(e) = grpc_client
  Branch (153:20): [True: 0, False: 0]
  Branch (153:20): [Folded - Ignored]
  Branch (153:20): [Folded - Ignored]
154
0
                .keep_alive(KeepAliveRequest {
155
0
                    worker_id: self.worker_id.clone(),
156
0
                })
157
0
                .await
158
            {
159
0
                return Err(make_err!(
160
0
                    Code::Internal,
161
0
                    "Failed to send KeepAlive in LocalWorker : {:?}",
162
0
                    e
163
0
                ));
164
0
            }
165
        }
166
0
    }
167
168
5
    async fn run(
169
5
        &mut self,
170
5
        update_for_worker_stream: Streaming<UpdateForWorker>,
171
5
    ) -> Result<(), Error> {
172
5
        // This big block of logic is designed to help simplify upstream components. Upstream
173
5
        // components can write standard futures that return a `Result<(), Error>` and this block
174
5
        // will forward the error up to the client and disconnect from the scheduler.
175
5
        // It is a common use case that an item sent through update_for_worker_stream will always
176
5
        // have a response but the response will be triggered through a callback to the scheduler.
177
5
        // This can be quite tricky to manage, so what we have done here is given access to a
178
5
        // `futures` variable which because this is in a single thread as well as a channel that you
179
5
        // send a future into that makes it into the `futures` variable.
180
5
        // This means that if you want to perform an action based on the result of the future
181
5
        // you use the `.map()` method and the new action will always come to live in this spawn,
182
5
        // giving mutable access to stuff in this struct.
183
5
        // NOTE: If you ever return from this function it will disconnect from the scheduler.
184
5
        let mut futures = FuturesUnordered::new();
185
5
        futures.push(self.start_keep_alive().boxed());
186
5
187
5
        let (add_future_channel, add_future_rx) = mpsc::unbounded_channel();
188
5
        let mut add_future_rx = UnboundedReceiverStream::new(add_future_rx).fuse();
189
5
190
5
        let mut update_for_worker_stream = update_for_worker_stream.fuse();
191
192
        loop {
193
16
            select! {
194
16
                
maybe_update6
= update_for_worker_stream.next() => {
195
6
                    match maybe_update
196
6
                        .err_tip(|| 
"UpdateForWorker stream closed early"1
)
?1
197
5
                        .err_tip(|| 
"Got error in UpdateForWorker stream"0
)
?0
198
                        .update
199
5
                        .err_tip(|| 
"Expected update to exist in UpdateForWorker"0
)
?0
200
                    {
201
                        Update::ConnectionResult(_) => {
202
0
                            return Err(make_input_err!(
203
0
                                "Got ConnectionResult in LocalWorker::run which should never happen"
204
0
                            ));
205
                        }
206
                        // TODO(allada) We should possibly do something with this notification.
207
0
                        Update::Disconnect(()) => {
208
0
                            self.metrics.disconnects_received.inc();
209
0
                        }
210
0
                        Update::KeepAlive(()) => {
211
0
                            self.metrics.keep_alives_received.inc();
212
0
                        }
213
1
                        Update::KillOperationRequest(kill_operation_request) => {
214
1
                            let operation_id = OperationId::from(kill_operation_request.operation_id);
215
1
                            if let Err(
err0
) = self.running_actions_manager.kill_operation(&operation_id).
await0
{
  Branch (215:36): [True: 0, False: 1]
  Branch (215:36): [Folded - Ignored]
  Branch (215:36): [Folded - Ignored]
216
0
                                event!(
217
0
                                    Level::ERROR,
218
                                    ?operation_id,
219
                                    ?err,
220
0
                                    "Failed to send kill request for operation"
221
                                );
222
1
                            };
223
                        }
224
4
                        Update::StartAction(start_execute) => {
225
4
                            self.metrics.start_actions_received.inc();
226
4
227
4
                            let execute_request = start_execute.execute_request.as_ref();
228
4
                            let operation_id = start_execute.operation_id.clone();
229
4
                            let maybe_instance_name = execute_request.map(|v| v.instance_name.clone());
230
4
                            let action_digest = execute_request.and_then(|v| v.action_digest.clone());
231
4
                            let digest_hasher = execute_request
232
4
                                .ok_or(make_input_err!("Expected execute_request to be set"))
233
4
                                .and_then(|v| DigestHasherFunc::try_from(v.digest_function))
234
4
                                .err_tip(|| 
"In LocalWorkerImpl::new()"0
)
?0
;
235
236
4
                            let start_action_fut = {
237
4
                                let precondition_script_cfg = self.config.experimental_precondition_script.clone();
238
4
                                let actions_in_transit = self.actions_in_transit.clone();
239
4
                                let worker_id = self.worker_id.clone();
240
4
                                let running_actions_manager = self.running_actions_manager.clone();
241
4
                                self.metrics.clone().wrap(move |metrics| async move {
242
4
                                    metrics.preconditions.wrap(preconditions_met(precondition_script_cfg))
243
4
                                    .and_then(|_| 
running_actions_manager.create_and_add_action(worker_id, start_execute)3
)
244
4
                                    .map(move |r| {
245
4
                                        // Now that we either failed or registered our action, we can
246
4
                                        // consider the action to no longer be in transit.
247
4
                                        actions_in_transit.fetch_sub(1, Ordering::Release);
248
4
                                        r
249
4
                                    })
250
4
                                    .and_then(|action| {
251
3
                                        event!(
252
3
                                            Level::INFO,
253
0
                                            operation_id = ?action.get_operation_id(),
254
0
                                            "Received request to run action"
255
                                        );
256
3
                                        action
257
3
                                            .clone()
258
3
                                            .prepare_action()
259
3
                                            .and_then(RunningAction::execute)
260
3
                                            .and_then(RunningAction::upload_results)
261
3
                                            .and_then(RunningAction::get_finished_result)
262
3
                                            // Note: We need ensure we run cleanup even if one of the other steps fail.
263
3
                                            .then(|result| async move 
{2
264
2
                                                if let Err(
e0
) = action.cleanup().await {
  Branch (264:56): [True: 0, False: 2]
  Branch (264:56): [Folded - Ignored]
  Branch (264:56): [Folded - Ignored]
265
0
                                                    return Result::<ActionResult, Error>::Err(e).merge(result);
266
2
                                                }
267
2
                                                result
268
4
                                            })
269
14
                                    }
)4
.await
270
7
                                })
271
4
                            };
272
4
273
4
                            let make_publish_future = {
274
4
                                let mut grpc_client = self.grpc_client.clone();
275
4
276
4
                                let worker_id = self.worker_id.clone();
277
4
                                let running_actions_manager = self.running_actions_manager.clone();
278
3
                                move |res: Result<ActionResult, Error>| async move {
279
3
                                    let instance_name = maybe_instance_name
280
3
                                        .err_tip(|| 
"`instance_name` could not be resolved; this is likely an internal error in local_worker."0
)
?0
;
281
3
                                    match res {
282
2
                                        Ok(mut action_result) => {
283
                                            // Save in the action cache before notifying the scheduler that we've completed.
284
2
                                            if let Some(digest_info) = action_digest.clone().and_then(|action_digest| action_digest.try_into().ok()) {
  Branch (284:52): [True: 2, False: 0]
  Branch (284:52): [Folded - Ignored]
  Branch (284:52): [Folded - Ignored]
285
2
                                                if let Err(
err0
) = running_actions_manager.cache_action_result(digest_info, &mut action_result, digest_hasher).
await0
{
  Branch (285:56): [True: 0, False: 2]
  Branch (285:56): [Folded - Ignored]
  Branch (285:56): [Folded - Ignored]
286
0
                                                    event!(
287
0
                                                        Level::ERROR,
288
                                                        ?err,
289
                                                        ?action_digest,
290
0
                                                        "Error saving action in store",
291
                                                    );
292
2
                                                }
293
0
                                            }
294
2
                                            let action_stage = ActionStage::Completed(action_result);
295
2
                                            grpc_client.execution_response(
296
2
                                                ExecuteResult{
297
2
                                                    worker_id,
298
2
                                                    instance_name,
299
2
                                                    operation_id,
300
2
                                                    result: Some(execute_result::Result::ExecuteResponse(action_stage.into())),
301
2
                                                }
302
2
                                            )
303
0
                                            .await
304
0
                                            .err_tip(|| "Error while calling execution_response")?;
305
                                        },
306
1
                                        Err(e) => {
307
1
                                            grpc_client.execution_response(ExecuteResult{
308
1
                                                worker_id,
309
1
                                                instance_name,
310
1
                                                operation_id,
311
1
                                                result: Some(execute_result::Result::InternalError(e.into())),
312
1
                                            }).
await0
.
err_tip(0
||
"Error calling execution_response with error"0
)0
?0
;
313
                                        },
314
                                    }
315
0
                                    Ok(())
316
3
                                }
317
                            };
318
319
4
                            self.actions_in_transit.fetch_add(1, Ordering::Release);
320
4
                            let futures_ref = &futures;
321
4
322
4
                            let add_future_channel = add_future_channel.clone();
323
4
                            let mut ctx = ActiveOriginContext::fork().err_tip(|| 
"Expected ActiveOriginContext to be set in local_worker::run"0
)
?0
;
324
4
                            ctx.set_value(&ACTIVE_HASHER_FUNC, Arc::new(digest_hasher));
325
4
                            ctx.run(info_span!("worker_start_action_ctx"), move || {
326
4
                                futures_ref.push(
327
4
                                    spawn!("worker_start_action", start_action_fut).map(move |res| 
{3
328
3
                                        let res = res.err_tip(|| 
"Failed to launch spawn"0
)
?0
;
329
3
                                        if let Err(
err1
) = &res {
  Branch (329:48): [True: 1, False: 2]
  Branch (329:48): [Folded - Ignored]
  Branch (329:48): [Folded - Ignored]
330
1
                                            event!(
331
1
                                                Level::ERROR,
332
                                                ?err,
333
1
                                                "Error executing action",
334
                                            );
335
2
                                        }
336
3
                                        add_future_channel
337
3
                                            .send(make_publish_future(res).boxed())
338
3
                                            .map_err(|_| 
make_err!(Code::Internal, "LocalWorker could not send future")0
)
?0
;
339
3
                                        Ok(())
340
4
                                    
}3
)
341
4
                                    .boxed()
342
4
                                );
343
4
                            });
344
4
                        }
345
                    };
346
                },
347
16
                
res3
= add_future_rx.next() => {
348
3
                    let fut = res.err_tip(|| 
"New future stream receives should never be closed"0
)
?0
;
349
3
                    futures.push(fut);
350
                },
351
16
                
res3
= futures.next() =>
res.err_tip(3
||
"Keep-alive should always pending. Likely unable to send data to scheduler"0
)3
?0
?0
,
352
            };
353
        }
354
        // Unreachable.
355
1
    }
356
}
357
358
type ConnectionFactory<T> = Box<dyn Fn() -> BoxFuture<'static, Result<T, Error>> + Send + Sync>;
359
360
pub struct LocalWorker<T: WorkerApiClientTrait, U: RunningActionsManager> {
361
    config: Arc<LocalWorkerConfig>,
362
    running_actions_manager: Arc<U>,
363
    connection_factory: ConnectionFactory<T>,
364
    sleep_fn: Option<Box<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync>>,
365
    metrics: Arc<Metrics>,
366
}
367
368
/// Creates a new `LocalWorker`. The `cas_store` must be an instance of
369
/// `FastSlowStore` and will be checked at runtime.
370
2
pub async fn new_local_worker(
371
2
    config: Arc<LocalWorkerConfig>,
372
2
    cas_store: Store,
373
2
    ac_store: Option<Store>,
374
2
    historical_store: Store,
375
2
) -> Result<
376
2
    (
377
2
        LocalWorker<WorkerApiClientWrapper, RunningActionsManagerImpl>,
378
2
        Arc<Metrics>,
379
2
    ),
380
2
    Error,
381
2
> {
382
2
    let fast_slow_store = cas_store
383
2
        .downcast_ref::<FastSlowStore>(None)
384
2
        .err_tip(|| 
"Expected store for LocalWorker's store to be a FastSlowStore"0
)
?0
385
2
        .get_arc()
386
2
        .err_tip(|| 
"FastSlowStore's Arc doesn't exist"0
)
?0
;
387
388
2
    if let Ok(
path1
) = fs::canonicalize(&config.work_directory).await {
  Branch (388:12): [True: 1, False: 1]
  Branch (388:12): [Folded - Ignored]
  Branch (388:12): [Folded - Ignored]
389
1
        fs::remove_dir_all(path)
390
1
            .await
391
1
            .err_tip(|| 
"Could not remove work_directory in LocalWorker"0
)
?0
;
392
1
    }
393
394
2
    fs::create_dir_all(&config.work_directory)
395
2
        .await
396
2
        .err_tip(|| 
format!("Could not make work_directory : {}", config.work_directory)0
)
?0
;
397
2
    let entrypoint = if config.entrypoint.is_empty() {
  Branch (397:25): [True: 2, False: 0]
  Branch (397:25): [Folded - Ignored]
  Branch (397:25): [Folded - Ignored]
398
2
        None
399
    } else {
400
0
        Some(config.entrypoint.clone())
401
    };
402
2
    let max_action_timeout = if config.max_action_timeout == 0 {
  Branch (402:33): [True: 2, False: 0]
  Branch (402:33): [Folded - Ignored]
  Branch (402:33): [Folded - Ignored]
403
2
        DEFAULT_MAX_ACTION_TIMEOUT
404
    } else {
405
0
        Duration::from_secs(config.max_action_timeout as u64)
406
    };
407
2
    let running_actions_manager =
408
2
        Arc::new(RunningActionsManagerImpl::new(RunningActionsManagerArgs {
409
2
            root_action_directory: config.work_directory.clone(),
410
2
            execution_configuration: ExecutionConfiguration {
411
2
                entrypoint,
412
2
                additional_environment: config.additional_environment.clone(),
413
2
            },
414
2
            cas_store: fast_slow_store,
415
2
            ac_store,
416
2
            historical_store,
417
2
            upload_action_result_config: &config.upload_action_result,
418
2
            max_action_timeout,
419
2
            timeout_handled_externally: config.timeout_handled_externally,
420
2
        })
?0
);
421
2
    let local_worker = LocalWorker::new_with_connection_factory_and_actions_manager(
422
2
        config.clone(),
423
2
        running_actions_manager,
424
2
        Box::new(move || {
425
0
            let config = config.clone();
426
0
            Box::pin(async move {
427
0
                let timeout = config
428
0
                    .worker_api_endpoint
429
0
                    .timeout
430
0
                    .unwrap_or(DEFAULT_ENDPOINT_TIMEOUT_S);
431
0
                let timeout_duration = Duration::from_secs_f32(timeout);
432
0
                let tls_config =
433
0
                    tls_utils::load_client_config(&config.worker_api_endpoint.tls_config)
434
0
                        .err_tip(|| "Parsing local worker TLS configuration")?;
435
0
                let endpoint =
436
0
                    tls_utils::endpoint_from(&config.worker_api_endpoint.uri, tls_config)
437
0
                        .map_err(|e| make_input_err!("Invalid URI for worker endpoint : {e:?}"))?
438
0
                        .connect_timeout(timeout_duration)
439
0
                        .timeout(timeout_duration);
440
441
0
                let transport = endpoint.connect().await.map_err(|e| {
442
0
                    make_err!(
443
0
                        Code::Internal,
444
0
                        "Could not connect to endpoint {}: {e:?}",
445
0
                        config.worker_api_endpoint.uri
446
0
                    )
447
0
                })?;
448
0
                Ok(WorkerApiClient::new(transport).into())
449
0
            })
450
2
        }),
451
2
        Box::new(move |d| 
Box::pin(sleep(d))0
),
452
2
    );
453
2
    let metrics = local_worker.metrics.clone();
454
2
    Ok((local_worker, metrics))
455
2
}
456
457
impl<T: WorkerApiClientTrait, U: RunningActionsManager> LocalWorker<T, U> {
458
8
    pub fn new_with_connection_factory_and_actions_manager(
459
8
        config: Arc<LocalWorkerConfig>,
460
8
        running_actions_manager: Arc<U>,
461
8
        connection_factory: ConnectionFactory<T>,
462
8
        sleep_fn: Box<dyn Fn(Duration) -> BoxFuture<'static, ()> + Send + Sync>,
463
8
    ) -> Self {
464
8
        let metrics = Arc::new(Metrics::new(Arc::downgrade(
465
8
            running_actions_manager.metrics(),
466
8
        )));
467
8
        Self {
468
8
            config,
469
8
            running_actions_manager,
470
8
            connection_factory,
471
8
            sleep_fn: Some(sleep_fn),
472
8
            metrics,
473
8
        }
474
8
    }
475
476
0
    pub fn name(&self) -> &String {
477
0
        &self.config.name
478
0
    }
479
480
8
    async fn register_worker(
481
8
        &mut self,
482
8
        client: &mut T,
483
8
    ) -> Result<(String, Streaming<UpdateForWorker>), Error> {
484
8
        let supported_properties =
485
8
            make_supported_properties(&self.config.platform_properties).
await0
?0
;
486
8
        let 
mut update_for_worker_stream6
= client
487
8
            .connect_worker(supported_properties)
488
7
            .await
489
6
            .err_tip(|| 
"Could not call connect_worker() in worker"0
)
?0
490
6
            .into_inner();
491
492
6
        let 
first_msg_update5
= update_for_worker_stream
493
6
            .next()
494
0
            .await
495
6
            .err_tip(|| 
"Got EOF expected UpdateForWorker"1
)
?1
496
5
            .err_tip(|| 
"Got error when receiving UpdateForWorker"0
)
?0
497
            .update;
498
499
5
        let worker_id = match first_msg_update {
500
5
            Some(Update::ConnectionResult(connection_result)) => connection_result.worker_id,
501
0
            other => {
502
0
                return Err(make_input_err!(
503
0
                    "Expected first response from scheduler to be a ConnectResult got : {:?}",
504
0
                    other
505
0
                ))
506
            }
507
        };
508
5
        Ok((worker_id, update_for_worker_stream))
509
6
    }
510
511
12
    #[instrument(skip(self), level = 
Level::INFO6
)
]0
512
    pub async fn run(mut self) -> Result<(), Error> {
513
        let sleep_fn = self
514
            .sleep_fn
515
            .take()
516
0
            .err_tip(|| "Could not unwrap sleep_fn in LocalWorker::run")?;
517
        let sleep_fn_pin = Pin::new(&sleep_fn);
518
2
        let error_handler = Box::pin(move |err| async move {
519
2
            event!(Level::ERROR, ?err, "Error");
520
2
            (sleep_fn_pin)(Duration::from_secs_f32(CONNECTION_RETRY_DELAY_S)).
await0
;
521
4
        });
522
523
        loop {
524
            // First connect to our endpoint.
525
            let mut client = match (self.connection_factory)().await {
526
                Ok(client) => client,
527
                Err(e) => {
528
                    (error_handler)(e).await;
529
                    continue; // Try to connect again.
530
                }
531
            };
532
533
            // Next register our worker with the scheduler.
534
            let (mut inner, update_for_worker_stream) =
535
                match self.register_worker(&mut client).await {
536
                    Err(e) => {
537
                        (error_handler)(e).await;
538
                        continue; // Try to connect again.
539
                    }
540
                    Ok((worker_id, update_for_worker_stream)) => (
541
                        LocalWorkerImpl::new(
542
                            &self.config,
543
                            client,
544
                            worker_id,
545
                            self.running_actions_manager.clone(),
546
                            self.metrics.clone(),
547
                        ),
548
                        update_for_worker_stream,
549
                    ),
550
                };
551
            event!(
552
                Level::WARN,
553
                worker_id = %inner.worker_id,
554
                "Worker registered with scheduler"
555
            );
556
557
            // Now listen for connections and run all other services.
558
            if let Err(err) = inner.run(update_for_worker_stream).await {
559
                'no_more_actions: {
560
                    // Ensure there are no actions in transit before we try to kill
561
                    // all our actions.
562
                    const ITERATIONS: usize = 1_000;
563
                    let sleep_duration = ACTIONS_IN_TRANSIT_TIMEOUT_S / ITERATIONS as f32;
564
                    for _ in 0..ITERATIONS {
565
                        if inner.actions_in_transit.load(Ordering::Acquire) == 0 {
566
                            break 'no_more_actions;
567
                        }
568
                        (sleep_fn_pin)(Duration::from_secs_f32(sleep_duration)).await;
569
                    }
570
                    const ERROR_MSG: &str = "Actions in transit did not reach zero before we disconnected from the scheduler";
571
                    event!(Level::ERROR, ERROR_MSG);
572
                    return Err(err.append(ERROR_MSG));
573
                }
574
                event!(Level::ERROR, ?err, "Worker disconnected from scheduler");
575
                // Kill off any existing actions because if we re-connect, we'll
576
                // get some more and it might resource lock us.
577
                self.running_actions_manager.kill_all().await;
578
579
                (error_handler)(err).await;
580
                continue; // Try to connect again.
581
            }
582
        }
583
        // Unreachable.
584
    }
585
}
586
587
0
#[derive(MetricsComponent)]
588
pub struct Metrics {
589
    #[metric(
590
        help = "Total number of actions sent to this worker to process. This does not mean it started them, it just means it received a request to execute it."
591
    )]
592
    start_actions_received: CounterWithTime,
593
    #[metric(help = "Total number of disconnects received from the scheduler.")]
594
    disconnects_received: CounterWithTime,
595
    #[metric(help = "Total number of keep-alives received from the scheduler.")]
596
    keep_alives_received: CounterWithTime,
597
    #[metric(
598
        help = "Stats about the calls to check if an action satisfies the config supplied script."
599
    )]
600
    preconditions: AsyncCounterWrapper,
601
    #[metric]
602
    running_actions_manager_metrics: Weak<RunningActionManagerMetrics>,
603
}
604
605
impl RootMetricsComponent for Metrics {}
606
607
impl Metrics {
608
8
    fn new(running_actions_manager_metrics: Weak<RunningActionManagerMetrics>) -> Self {
609
8
        Self {
610
8
            start_actions_received: CounterWithTime::default(),
611
8
            disconnects_received: CounterWithTime::default(),
612
8
            keep_alives_received: CounterWithTime::default(),
613
8
            preconditions: AsyncCounterWrapper::default(),
614
8
            running_actions_manager_metrics,
615
8
        }
616
8
    }
617
}
618
619
impl Metrics {
620
4
    async fn wrap<U, T: Future<Output = U>, F: FnOnce(Arc<Self>) -> T>(
621
4
        self: Arc<Self>,
622
4
        fut: F,
623
4
    ) -> U {
624
14
        fut(self).await
625
3
    }
626
}