-
-
Notifications
You must be signed in to change notification settings - Fork 606
/
remote.rs
1686 lines (1537 loc) · 56.9 KB
/
remote.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::convert::TryInto;
use std::fmt::{self, Debug, Write};
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use async_oncecell::OnceCell;
use async_trait::async_trait;
use bytes::Bytes;
use futures::future::{self, BoxFuture, TryFutureExt};
use futures::{FutureExt, Stream, StreamExt};
use log::{debug, trace, warn, Level};
use prost::Message;
use protos::gen::build::bazel::remote::execution::v2 as remexec;
use protos::gen::google::longrunning::{
operations_client::OperationsClient, CancelOperationRequest, Operation,
};
use protos::gen::google::rpc::{PreconditionFailure, Status as StatusProto};
use protos::require_digest;
use rand::{thread_rng, Rng};
use remexec::{
capabilities_client::CapabilitiesClient, execution_client::ExecutionClient,
execution_stage::Value as ExecutionStageValue, Action, Command, ExecuteRequest, ExecuteResponse,
ExecutedActionMetadata, ServerCapabilities, WaitExecutionRequest,
};
use tonic::metadata::BinaryMetadataValue;
use tonic::{Code, Request, Status};
use tryfuture::try_future;
use uuid::Uuid;
use concrete_time::TimeSpan;
use fs::{self, DirectoryDigest, File, PathStat, RelativePath, EMPTY_DIRECTORY_DIGEST};
use grpc_util::headers_to_http_header_map;
use grpc_util::prost::MessageExt;
use grpc_util::{layered_service, status_to_str, LayeredService};
use hashing::{Digest, Fingerprint};
use store::{Snapshot, SnapshotOps, Store, StoreError, StoreFileByDigest};
use task_executor::Executor;
use workunit_store::{
in_workunit, Metric, ObservationMetric, RunId, RunningWorkunit, SpanId, UserMetadataItem,
WorkunitMetadata, WorkunitStore,
};
use crate::{
CacheName, Context, FallibleProcessResultWithPlatform, Platform, Process, ProcessCacheScope,
ProcessError, ProcessExecutionStrategy, ProcessResultMetadata, ProcessResultSource,
};
// Environment variable which is exclusively used for cache key invalidation.
// This may be not specified in an Process, and may be populated only by the
// CommandRunner.
pub const CACHE_KEY_GEN_VERSION_ENV_VAR_NAME: &str = "PANTS_CACHE_KEY_GEN_VERSION";
// Environment variable which is used to differentiate between running in Docker vs. local vs.
// remote execution.
pub const CACHE_KEY_EXECUTION_STRATEGY: &str = "PANTS_CACHE_KEY_EXECUTION_STRATEGY";
// Environment variable which is used to include a unique value for cache busting of processes that
// have indicated that they should never be cached.
pub const CACHE_KEY_SALT_ENV_VAR_NAME: &str = "PANTS_CACHE_KEY_SALT";
// Environment variable which is exclusively used for cache key invalidation.
// This may be not specified in an Process, and may be populated only by the
// CommandRunner.
pub const CACHE_KEY_TARGET_PLATFORM_ENV_VAR_NAME: &str = "PANTS_CACHE_KEY_TARGET_PLATFORM";
#[derive(Debug)]
pub enum OperationOrStatus {
Operation(Operation),
Status(StatusProto),
}
#[derive(Debug, PartialEq, Eq)]
pub enum ExecutionError {
Fatal(ProcessError),
// Digests are Files and Directories which have been reported to be missing remotely (unlike
// `{Process,Store}Error::MissingDigest`, which indicates that a digest doesn't exist anywhere
// in the configured Stores). May be incomplete.
MissingRemoteDigests(Vec<Digest>),
// The server indicated that the request hit a timeout. Generally this is the timeout that the
// client has pushed down on the ExecutionRequest.
Timeout,
// String is the error message.
Retryable(String),
}
/// Implementation of CommandRunner that runs a command via the Bazel Remote Execution API
/// (https://docs.google.com/document/d/1AaGk7fOPByEvpAbqeXIyE8HX_A3_axxNnvroblTZ_6s/edit).
///
/// Results are streamed from the output stream of the Execute function (and possibly the
/// WaitExecution function if `CommandRunner` needs to reconnect).
///
/// If the CommandRunner has a Store, files will be uploaded to the remote CAS as needed.
/// Note that it does not proactively upload files to a remote CAS. This is because if we will
/// get a cache hit, uploading the files was wasted time and bandwidth, and if the remote CAS
/// already has some files, uploading them all is a waste. Instead, we look at the responses we
/// get back from the server, and upload the files it says it's missing.
///
/// In the future, we may want to do some clever things like proactively upload files which the
/// user has changed, or files which aren't known to the local git repository, but these are
/// optimizations to shave off a round-trip in the future.
#[derive(Clone)]
pub struct CommandRunner {
instance_name: Option<String>,
process_cache_namespace: Option<String>,
append_only_caches_base_path: Option<String>,
store: Store,
executor: Executor,
execution_client: Arc<ExecutionClient<LayeredService>>,
operations_client: Arc<OperationsClient<LayeredService>>,
overall_deadline: Duration,
retry_interval_duration: Duration,
capabilities_cell: Arc<OnceCell<ServerCapabilities>>,
capabilities_client: Arc<CapabilitiesClient<LayeredService>>,
}
enum StreamOutcome {
Complete(OperationOrStatus),
StreamClosed,
}
enum OperationStreamItem {
Running(ExecutionStageValue),
Outcome(StreamOutcome),
}
/// A single remote Operation, with a `Drop` implementation to cancel the work if our client goes
/// away.
struct RunningOperation {
name: Option<String>,
operations_client: Arc<OperationsClient<LayeredService>>,
executor: Executor,
process_level: Level,
process_description: String,
}
impl RunningOperation {
fn new(
operations_client: Arc<OperationsClient<LayeredService>>,
executor: Executor,
process_level: Level,
process_description: String,
) -> Self {
Self {
name: None,
operations_client,
executor,
process_level,
process_description,
}
}
/// Marks the operation completed, which will avoid attempts to cancel it when this struct is
/// dropped.
fn completed(&mut self) {
let _ = self.name.take();
}
}
impl Drop for RunningOperation {
fn drop(&mut self) {
if let Some(operation_name) = self.name.take() {
debug!("Canceling remote operation {operation_name}");
let mut operations_client = self.operations_client.as_ref().clone();
let _ = self.executor.spawn(async move {
operations_client
.cancel_operation(CancelOperationRequest {
name: operation_name,
})
.await
});
}
}
}
impl CommandRunner {
/// Construct a new CommandRunner
pub fn new(
execution_address: &str,
instance_name: Option<String>,
process_cache_namespace: Option<String>,
append_only_caches_base_path: Option<String>,
root_ca_certs: Option<Vec<u8>>,
headers: BTreeMap<String, String>,
store: Store,
executor: Executor,
overall_deadline: Duration,
retry_interval_duration: Duration,
execution_concurrency_limit: usize,
capabilities_cell_opt: Option<Arc<OnceCell<ServerCapabilities>>>,
) -> Result<Self, String> {
let execution_use_tls = execution_address.starts_with("https://");
let tls_client_config = if execution_use_tls {
Some(grpc_util::tls::Config::new_without_mtls(root_ca_certs).try_into()?)
} else {
None
};
let mut execution_headers = headers;
let execution_endpoint = grpc_util::create_endpoint(
execution_address,
tls_client_config.as_ref().filter(|_| execution_use_tls),
&mut execution_headers,
)?;
let execution_http_headers = headers_to_http_header_map(&execution_headers)?;
let execution_channel = layered_service(
tonic::transport::Channel::balance_list(vec![execution_endpoint].into_iter()),
execution_concurrency_limit,
execution_http_headers,
);
let execution_client = Arc::new(ExecutionClient::new(execution_channel.clone()));
let operations_client = Arc::new(OperationsClient::new(execution_channel.clone()));
let capabilities_client = Arc::new(CapabilitiesClient::new(execution_channel));
let command_runner = CommandRunner {
instance_name,
process_cache_namespace,
append_only_caches_base_path,
execution_client,
operations_client,
store,
executor,
overall_deadline,
retry_interval_duration,
capabilities_cell: capabilities_cell_opt.unwrap_or_else(|| Arc::new(OnceCell::new())),
capabilities_client,
};
Ok(command_runner)
}
async fn get_capabilities(&self) -> Result<&remexec::ServerCapabilities, String> {
let capabilities_fut = async {
let mut request = remexec::GetCapabilitiesRequest::default();
if let Some(s) = self.instance_name.as_ref() {
request.instance_name = s.clone();
}
let request = apply_headers(Request::new(request), "");
let mut client = self.capabilities_client.as_ref().clone();
client
.get_capabilities(request)
.await
.map(|r| r.into_inner())
.map_err(status_to_str)
};
self
.capabilities_cell
.get_or_try_init(capabilities_fut)
.await
}
async fn wait_on_operation_stream_item<S>(
stream: &mut S,
context: &Context,
running_operation: &mut RunningOperation,
start_time_opt: &mut Option<Instant>,
) -> OperationStreamItem
where
S: Stream<Item = Result<Operation, Status>> + Unpin,
{
let item = stream.next().await;
if let Some(start_time) = start_time_opt.take() {
let timing: Result<u64, _> = Instant::now()
.duration_since(start_time)
.as_micros()
.try_into();
if let Ok(obs) = timing {
context.workunit_store.record_observation(
ObservationMetric::RemoteExecutionRPCFirstResponseTimeMicros,
obs,
);
}
}
match item {
Some(Ok(operation)) => {
trace!(
"wait_on_operation_stream (build_id={}): got operation: {:?}",
&context.build_id,
&operation
);
// Extract the operation name.
// Note: protobuf can return empty string for an empty field so convert empty strings
// to None.
running_operation.name = Some(operation.name.clone()).filter(|s| !s.trim().is_empty());
if operation.done {
// Continue monitoring if the operation is not complete.
OperationStreamItem::Outcome(StreamOutcome::Complete(OperationOrStatus::Operation(
operation,
)))
} else {
// Otherwise, return to the main loop with the operation as the result.
OperationStreamItem::Running(
Self::maybe_extract_execution_stage(&operation).unwrap_or(ExecutionStageValue::Unknown),
)
}
}
Some(Err(err)) => {
debug!("wait_on_operation_stream: got error: {:?}", err);
let status_proto = StatusProto {
code: err.code() as i32,
message: err.message().to_string(),
..StatusProto::default()
};
OperationStreamItem::Outcome(StreamOutcome::Complete(OperationOrStatus::Status(
status_proto,
)))
}
None => {
// Stream disconnected unexpectedly.
debug!("wait_on_operation_stream: unexpected disconnect from RE server");
OperationStreamItem::Outcome(StreamOutcome::StreamClosed)
}
}
}
/// Monitors the operation stream returned by the REv2 Execute and WaitExecution methods.
/// Outputs progress reported by the server and returns the next actionable operation
/// or gRPC status back to the main loop (plus the operation name so the main loop can
/// reconnect).
async fn wait_on_operation_stream<S>(
mut stream: S,
context: &Context,
running_operation: &mut RunningOperation,
) -> StreamOutcome
where
S: Stream<Item = Result<Operation, Status>> + Unpin + Send,
{
let mut start_time_opt = Some(Instant::now());
trace!(
"wait_on_operation_stream (build_id={}): monitoring stream",
&context.build_id
);
// If the server returns an `ExecutionStage` other than `Unknown`, then we assume that it
// implements reporting when the operation actually begins `Executing` (as opposed to being
// `Queued`, etc), and will wait to create a workunit until we see the `Executing` stage.
//
// We start by consuming the prefix of the stream before we receive an `Executing` or `Unknown` stage.
loop {
match Self::wait_on_operation_stream_item(
&mut stream,
context,
running_operation,
&mut start_time_opt,
)
.await
{
OperationStreamItem::Running(
ExecutionStageValue::Unknown | ExecutionStageValue::Executing,
) => {
// Either the server doesn't know how to report the stage, or the operation has
// actually begun executing serverside: proceed to the suffix.
break;
}
OperationStreamItem::Running(_) => {
// The operation has not reached an ExecutionStage that we recognize as
// "executing" (likely: it is queued, doing a cache lookup, etc): keep waiting.
continue;
}
OperationStreamItem::Outcome(outcome) => return outcome,
}
}
// Start a workunit to represent the execution of the work, and consume the rest of the stream.
in_workunit!(
"run_remote_process",
// NB: See engine::nodes::NodeKey::workunit_level for more information on why this workunit
// renders at the Process's level.
running_operation.process_level,
desc = Some(running_operation.process_description.clone()),
|_workunit| async move {
loop {
match Self::wait_on_operation_stream_item(
&mut stream,
context,
running_operation,
&mut start_time_opt,
)
.await
{
OperationStreamItem::Running(
ExecutionStageValue::Queued | ExecutionStageValue::CacheCheck,
) => {
// The server must have cancelled and requeued the work: although this isn't an error
// per-se, it is much easier for us to re-open the stream than to treat this as a
// nested loop. In particular:
// 1. we can't break/continue out of a workunit
// 2. the stream needs to move into the workunit, and can't move back out
break StreamOutcome::StreamClosed;
}
OperationStreamItem::Running(_) => {
// The operation is still running.
continue;
}
OperationStreamItem::Outcome(outcome) => break outcome,
}
}
}
)
.await
}
// Store the remote timings into the workunit store.
fn save_workunit_timings(
&self,
execute_response: &ExecuteResponse,
metadata: &ExecutedActionMetadata,
) {
let workunit_thread_handle = workunit_store::expect_workunit_store_handle();
let workunit_store = workunit_thread_handle.store;
let parent_id = workunit_thread_handle.parent_id;
let result_cached = execute_response.cached_result;
if let (Some(queued_timestamp), Some(worker_start_timestamp)) = (
metadata.queued_timestamp.as_ref(),
metadata.worker_start_timestamp.as_ref(),
) {
let span_result =
TimeSpan::from_start_and_end(queued_timestamp, worker_start_timestamp, "remote queue");
match span_result {
Ok(time_span) => maybe_add_workunit(
result_cached,
"remote execution action scheduling",
Level::Trace,
time_span,
parent_id,
&workunit_store,
WorkunitMetadata::default(),
),
Err(s) => warn!("{}", s),
}
}
if let (Some(input_fetch_start_timestamp), Some(input_fetch_completed_timestamp)) = (
metadata.input_fetch_start_timestamp.as_ref(),
metadata.input_fetch_completed_timestamp.as_ref(),
) {
let span_result = TimeSpan::from_start_and_end(
input_fetch_start_timestamp,
input_fetch_completed_timestamp,
"remote input fetch",
);
match span_result {
Ok(time_span) => maybe_add_workunit(
result_cached,
"remote execution worker input fetching",
Level::Trace,
time_span,
parent_id,
&workunit_store,
WorkunitMetadata::default(),
),
Err(s) => warn!("{}", s),
}
}
if let (Some(execution_start_timestamp), Some(execution_completed_timestamp)) = (
metadata.execution_start_timestamp.as_ref(),
metadata.execution_completed_timestamp.as_ref(),
) {
let span_result = TimeSpan::from_start_and_end(
execution_start_timestamp,
execution_completed_timestamp,
"remote execution",
);
match span_result {
Ok(time_span) => maybe_add_workunit(
result_cached,
"remote execution worker command executing",
Level::Trace,
time_span,
parent_id,
&workunit_store,
WorkunitMetadata::default(),
),
Err(s) => warn!("{}", s),
}
}
if let (Some(output_upload_start_timestamp), Some(output_upload_completed_timestamp)) = (
metadata.output_upload_start_timestamp.as_ref(),
metadata.output_upload_completed_timestamp.as_ref(),
) {
let span_result = TimeSpan::from_start_and_end(
output_upload_start_timestamp,
output_upload_completed_timestamp,
"remote output store",
);
match span_result {
Ok(time_span) => maybe_add_workunit(
result_cached,
"remote execution worker output uploading",
Level::Trace,
time_span,
parent_id,
&workunit_store,
WorkunitMetadata::default(),
),
Err(s) => warn!("{}", s),
}
}
}
fn extract_missing_digests(&self, precondition_failure: &PreconditionFailure) -> ExecutionError {
let mut missing_digests = Vec::with_capacity(precondition_failure.violations.len());
for violation in &precondition_failure.violations {
if violation.r#type != "MISSING" {
return ExecutionError::Fatal(
format!("Unknown PreconditionFailure violation: {:?}", violation).into(),
);
}
let parts: Vec<_> = violation.subject.split('/').collect();
if parts.len() != 3 || parts[0] != "blobs" {
return ExecutionError::Fatal(
format!(
"Received FailedPrecondition MISSING but didn't recognize subject {}",
violation.subject
)
.into(),
);
}
let fingerprint = match Fingerprint::from_hex_string(parts[1]) {
Ok(f) => f,
Err(e) => {
return ExecutionError::Fatal(
format!("Bad digest in missing blob: {}: {}", parts[1], e).into(),
)
}
};
let size = match parts[2].parse::<usize>() {
Ok(s) => s,
Err(e) => {
return ExecutionError::Fatal(
format!("Missing blob had bad size: {}: {}", parts[2], e).into(),
)
}
};
missing_digests.push(Digest::new(fingerprint, size));
}
if missing_digests.is_empty() {
return ExecutionError::Fatal(
"Error from remote execution: FailedPrecondition, but no details"
.to_owned()
.into(),
);
}
ExecutionError::MissingRemoteDigests(missing_digests)
}
/// If set, extract `ExecuteOperationMetadata` from the `Operation`.
fn maybe_extract_execution_stage(operation: &Operation) -> Option<ExecutionStageValue> {
let metadata = operation.metadata.as_ref()?;
let eom = remexec::ExecuteOperationMetadata::decode(&metadata.value[..])
.map(Some)
.unwrap_or_else(|e| {
log::warn!("Invalid ExecuteOperationMetadata from server: {e:?}");
None
})?;
ExecutionStageValue::from_i32(eom.stage)
}
// pub(crate) for testing
pub(crate) async fn extract_execute_response(
&self,
run_id: RunId,
platform: Platform,
operation_or_status: OperationOrStatus,
) -> Result<FallibleProcessResultWithPlatform, ExecutionError> {
trace!("Got operation response: {:?}", operation_or_status);
let status = match operation_or_status {
OperationOrStatus::Operation(operation) => {
assert!(operation.done, "operation was not marked done");
use protos::gen::google::longrunning::operation::Result as OperationResult;
let execute_response = match operation.result {
Some(OperationResult::Response(response_any)) => {
remexec::ExecuteResponse::decode(&response_any.value[..]).map_err(|e| {
ExecutionError::Fatal(format!("Invalid ExecuteResponse: {:?}", e).into())
})?
}
Some(OperationResult::Error(rpc_status)) => {
// Infrastructure error. Retry it.
let msg = format_error(&rpc_status);
debug!("got operation error for runid {:?}: {}", &run_id, &msg);
return Err(ExecutionError::Retryable(msg));
}
None => {
return Err(ExecutionError::Fatal(
"Operation finished but no response supplied"
.to_owned()
.into(),
));
}
};
debug!("Got (nested) execute response: {:?}", execute_response);
if let Some(ref metadata) = execute_response
.result
.as_ref()
.and_then(|ar| ar.execution_metadata.clone())
{
self.save_workunit_timings(&execute_response, metadata);
}
let rpc_status = execute_response.status.unwrap_or_default();
if rpc_status.code == Code::Ok as i32 {
let action_result = if let Some(ref action_result) = execute_response.result {
action_result
} else {
warn!("REv2 protocol violation: action result not set");
return Err(ExecutionError::Fatal(
"REv2 protocol violation: action result not set"
.to_owned()
.into(),
));
};
return populate_fallible_execution_result(
self.store.clone(),
run_id,
action_result,
platform,
false,
if execute_response.cached_result {
ProcessResultSource::HitRemotely
} else {
ProcessResultSource::RanRemotely
},
)
.await
.map_err(|e| ExecutionError::Fatal(e.into()));
}
rpc_status
}
OperationOrStatus::Status(status) => status,
};
match Code::from_i32(status.code) {
Code::Ok => unreachable!(),
Code::DeadlineExceeded => Err(ExecutionError::Timeout),
Code::FailedPrecondition => {
let details = if status.details.is_empty() {
return Err(ExecutionError::Fatal(status.message.into()));
} else if status.details.len() > 1 {
// TODO(tonic): Should we be able to handle multiple details protos?
return Err(ExecutionError::Fatal(
"too many detail protos for precondition failure"
.to_owned()
.into(),
));
} else {
&status.details[0]
};
let full_name = format!("type.googleapis.com/{}", "google.rpc.PreconditionFailure");
if details.type_url != full_name {
return Err(ExecutionError::Fatal(
format!(
"Received PreconditionFailure, but didn't know how to resolve it: {}, protobuf type {}",
status.message, details.type_url
)
.into(),
));
}
// Decode the precondition failure.
let precondition_failure = PreconditionFailure::decode(Cursor::new(&details.value))
.map_err(|e| {
ExecutionError::Fatal(
format!("Error deserializing PreconditionFailure proto: {:?}", e).into(),
)
})?;
Err(self.extract_missing_digests(&precondition_failure))
}
Code::Aborted
| Code::Internal
| Code::ResourceExhausted
| Code::Unavailable
| Code::Unknown => Err(ExecutionError::Retryable(status.message)),
code => Err(ExecutionError::Fatal(
format!(
"Error from remote execution: {:?}: {:?}",
code, status.message,
)
.into(),
)),
}
}
// Main loop: This function connects to the RE server and submits the given remote execution
// request via the REv2 Execute method. It then monitors the operation stream until the
// request completes. It will reconnect using the REv2 WaitExecution method if the connection
// is dropped.
//
// The `run` method on CommandRunner uses this function to implement the bulk of the
// processing for remote execution requests. The `run` method wraps the call with the method
// with an overall deadline timeout.
async fn run_execute_request(
&self,
execute_request: ExecuteRequest,
process: Process,
context: &Context,
workunit: &mut RunningWorkunit,
) -> Result<FallibleProcessResultWithPlatform, ProcessError> {
const MAX_RETRIES: u32 = 5;
const MAX_BACKOFF_DURATION: Duration = Duration::from_secs(10);
let start_time = Instant::now();
let mut running_operation = RunningOperation::new(
self.operations_client.clone(),
self.executor.clone(),
process.level,
process.description.clone(),
);
let mut num_retries = 0;
loop {
// If we are currently retrying a request, then delay using an exponential backoff.
if num_retries > 0 {
workunit.increment_counter(Metric::RemoteExecutionRPCRetries, 1);
let multiplier = thread_rng().gen_range(0..2_u32.pow(num_retries) + 1);
let sleep_time = self.retry_interval_duration * multiplier;
let sleep_time = sleep_time.min(MAX_BACKOFF_DURATION);
debug!("delaying {:?} before retry", sleep_time);
tokio::time::sleep(sleep_time).await;
}
let rpc_result = match running_operation.name {
None => {
// The request has not been submitted yet. Submit the request using the REv2
// Execute method.
debug!(
"no current operation: submitting execute request: build_id={}; execute_request={:?}",
context.build_id, &execute_request
);
workunit.increment_counter(Metric::RemoteExecutionRPCExecute, 1);
let mut client = self.execution_client.as_ref().clone();
let request = apply_headers(Request::new(execute_request.clone()), &context.build_id);
client.execute(request).await
}
Some(ref operation_name) => {
// The request has been submitted already. Reconnect to the status stream
// using the REv2 WaitExecution method.
debug!(
"existing operation: reconnecting to operation stream: build_id={}; operation_name={}",
context.build_id, operation_name
);
workunit.increment_counter(Metric::RemoteExecutionRPCWaitExecution, 1);
let wait_execution_request = WaitExecutionRequest {
name: operation_name.to_owned(),
};
let mut client = self.execution_client.as_ref().clone();
let request = apply_headers(Request::new(wait_execution_request), &context.build_id);
client.wait_execution(request).await
}
};
// Take action based on whether we received an output stream or whether there is an
// error to resolve.
let actionable_result = match rpc_result {
Ok(operation_stream_response) => {
// Monitor the operation stream until there is an actionable operation
// or status to interpret.
let operation_stream = operation_stream_response.into_inner();
let stream_outcome =
Self::wait_on_operation_stream(operation_stream, context, &mut running_operation).await;
match stream_outcome {
StreamOutcome::Complete(status) => {
trace!(
"wait_on_operation_stream (build_id={}) returned completion={:?}",
context.build_id,
status
);
// We completed this operation.
running_operation.completed();
status
}
StreamOutcome::StreamClosed => {
trace!(
"wait_on_operation_stream (build_id={}) returned stream close, \
will retry operation_name={:?}",
context.build_id,
running_operation.name
);
// Check if the number of request attempts sent thus far have exceeded the number
// of retries allowed since the last successful connection. (There is no point in
// continually submitting a request if ultimately futile.)
if num_retries >= MAX_RETRIES {
workunit.increment_counter(Metric::RemoteExecutionRPCErrors, 1);
return Err(
"Too many failures from server. The last event was the server disconnecting with no error given.".to_owned().into(),
);
} else {
// Increment the retry counter and allow loop to retry.
num_retries += 1;
}
// Iterate the loop to reconnect to the operation.
continue;
}
}
}
Err(status) => {
let status_proto = StatusProto {
code: status.code() as i32,
message: status.message().to_owned(),
..StatusProto::default()
};
// `OperationOrStatus` always represents a completed operation, so this operation
// is completed.
running_operation.completed();
OperationOrStatus::Status(status_proto)
}
};
match self
.extract_execute_response(context.run_id, process.platform, actionable_result)
.await
{
Ok(result) => return Ok(result),
Err(err) => match err {
ExecutionError::Fatal(e) => {
workunit.increment_counter(Metric::RemoteExecutionRPCErrors, 1);
return Err(e);
}
ExecutionError::Retryable(e) => {
// Check if the number of request attempts sent thus far have exceeded the number
// of retries allowed since the last successful connection. (There is no point in
// continually submitting a request if ultimately futile.)
trace!("retryable error: {}", e);
if num_retries >= MAX_RETRIES {
workunit.increment_counter(Metric::RemoteExecutionRPCErrors, 1);
return Err(
format!("Too many failures from server. The last error was: {}", e).into(),
);
} else {
// Increment the retry counter and allow loop to retry.
num_retries += 1;
}
}
ExecutionError::MissingRemoteDigests(missing_digests) => {
trace!(
"Server reported missing digests; trying to upload: {:?}",
missing_digests,
);
let _ = self
.store
.ensure_remote_has_recursive(missing_digests)
.await?;
}
ExecutionError::Timeout => {
workunit.increment_counter(Metric::RemoteExecutionTimeouts, 1);
let result = populate_fallible_execution_result_for_timeout(
&self.store,
context,
&process.description,
process.timeout,
start_time.elapsed(),
process.platform,
)
.await?;
return Ok(result);
}
},
}
}
}
}
impl Debug for CommandRunner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("remote::CommandRunner")
.finish_non_exhaustive()
}
}
#[async_trait]
impl crate::CommandRunner for CommandRunner {
/// Run the given Process via the Remote Execution API.
async fn run(
&self,
context: Context,
_workunit: &mut RunningWorkunit,
request: Process,
) -> Result<FallibleProcessResultWithPlatform, ProcessError> {
// Retrieve capabilities for this server.
let capabilities = self.get_capabilities().await?;
trace!("RE capabilities: {:?}", &capabilities);
// Construct the REv2 ExecuteRequest and related data for this execution request.
let EntireExecuteRequest {
action,
command,
execute_request,
input_root_digest,
} = make_execute_request(
&request,
self.instance_name.clone(),
self.process_cache_namespace.clone(),
&self.store,
self
.append_only_caches_base_path
.as_ref()
.map(|s| s.as_ref()),
)
.await?;
let build_id = context.build_id.clone();
debug!("Remote execution: {}", request.description);
debug!(
"built REv2 request (build_id={}): action={:?}; command={:?}; execute_request={:?}",
&build_id, action, command, execute_request
);
// Record the time that we started to process this request, then compute the ultimate
// deadline for execution of this request.
let deadline_duration = self.overall_deadline + request.timeout.unwrap_or_default();
// Ensure the action and command are stored locally.
let (command_digest, action_digest) =
ensure_action_stored_locally(&self.store, &command, &action).await?;
// Upload the action (and related data, i.e. the embedded command and input files).
ensure_action_uploaded(
&self.store,
command_digest,
action_digest,
Some(input_root_digest),
)
.await?;
// Submit the execution request to the RE server for execution.
let context2 = context.clone();
in_workunit!(
"run_execute_request",
// NB: The process has not actually started running until the server has notified us that it
// has: see `wait_on_operation_stream`.
Level::Debug,
user_metadata = vec![(
"action_digest".to_owned(),
UserMetadataItem::String(format!("{action_digest:?}")),
)],
|workunit| async move {
workunit.increment_counter(Metric::RemoteExecutionRequests, 1);
let result_fut = self.run_execute_request(execute_request, request, &context2, workunit);
// Detect whether the operation ran or hit the deadline timeout.
match tokio::time::timeout(deadline_duration, result_fut).await {
Ok(Ok(result)) => {
workunit.increment_counter(Metric::RemoteExecutionSuccess, 1);
Ok(result)
}
Ok(Err(err)) => {
workunit.increment_counter(Metric::RemoteExecutionErrors, 1);
Err(err.enrich(&format!("For action {action_digest:?}")))
}
Err(tokio::time::error::Elapsed { .. }) => {
// The Err in this match arm originates from the timeout future.
debug!(
"remote execution for build_id={} timed out after {:?}",
&build_id, deadline_duration
);