forked from pantsbuild/pants
/
remote.rs
2935 lines (2682 loc) · 95.1 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
use std::collections::HashMap;
use std::mem::drop;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use bazel_protos;
use boxfuture::{try_future, BoxFuture, Boxable};
use bytes::Bytes;
use digest::{Digest as DigestTrait, FixedOutput};
use fs::{self, File, PathStat};
use futures::{future, Future, Stream};
use grpcio;
use hashing::{Digest, Fingerprint};
use log::{debug, trace, warn};
use protobuf::{self, Message, ProtobufEnum};
use sha2::Sha256;
use store::{Snapshot, Store, StoreFileByDigest};
use time;
use time::Timespec;
use tokio_timer::Delay;
use super::{
ExecuteProcessRequest, ExecuteProcessRequestMetadata, ExecutionStats,
FallibleExecuteProcessResult,
};
use std;
use std::cmp::min;
use workunit_store::{generate_random_64bit_string, get_parent_id, WorkUnit, WorkUnitStore};
// Environment variable which is exclusively used for cache key invalidation.
// This may be not specified in an ExecuteProcessRequest, and may be populated only by the
// CommandRunner.
const CACHE_KEY_GEN_VERSION_ENV_VAR_NAME: &str = "PANTS_CACHE_KEY_GEN_VERSION";
#[derive(Debug)]
enum OperationOrStatus {
Operation(bazel_protos::operations::Operation),
Status(bazel_protos::status::Status),
}
#[derive(Clone)]
pub struct CommandRunner {
metadata: ExecuteProcessRequestMetadata,
authorization_header: Option<String>,
channel: grpcio::Channel,
env: Arc<grpcio::Environment>,
execution_client: Arc<bazel_protos::remote_execution_grpc::ExecutionClient>,
operations_client: Arc<bazel_protos::operations_grpc::OperationsClient>,
store: Store,
}
#[derive(Debug, PartialEq)]
enum ExecutionError {
// String is the error message.
Fatal(String),
// Digests are Files and Directories which have been reported to be missing. May be incomplete.
MissingDigests(Vec<Digest>),
// String is the operation name which can be used to poll the GetOperation gRPC API.
NotFinished(String),
}
#[derive(Default)]
struct ExecutionHistory {
attempts: Vec<ExecutionStats>,
current_attempt: ExecutionStats,
}
impl CommandRunner {
// The Execute API used to be unary, and became streaming. The contract of the streaming API is
// that if the client closes the stream after one request, it should continue to function exactly
// like the unary API.
// For maximal compatibility with servers, we fall back to this unary-like behavior, and control
// our own polling rates.
// In the future, we may want to remove this behavior if servers reliably support the full stream
// behavior.
fn oneshot_execute(
&self,
execute_request: &Arc<bazel_protos::remote_execution::ExecuteRequest>,
) -> BoxFuture<OperationOrStatus, String> {
let stream = try_future!(self
.execution_client
.execute_opt(&execute_request, self.call_option())
.map_err(rpcerror_to_string));
stream
.take(1)
.into_future()
// If there was a response, drop the _stream to disconnect so that the server doesn't keep
// the connection alive and continue sending on it.
.map(|(maybe_operation, stream)| {
drop(stream);
maybe_operation
})
// If there was an error, drop the _stream to disconnect so that the server doesn't keep the
// connection alive and continue sending on it.
.map_err(|(error, stream)| {
drop(stream);
error
})
.then(|maybe_operation_result| match maybe_operation_result {
Ok(Some(operation)) => Ok(OperationOrStatus::Operation(operation)),
Ok(None) => {
Err("Didn't get proper stream response from server during remote execution".to_owned())
}
Err(err) => rpcerror_to_status_or_string(err).map(OperationOrStatus::Status),
})
.to_boxed()
}
}
// TODO(pantsbuild/pants#8039) Need to impl Drop on command runner so that when the BoxFuture goes out of scope
// we cancel a potential RPC. So we need to distinguish local vs. remote
// requests and save enough state to BoxFuture or another abstraction around our execution results
impl super::CommandRunner for CommandRunner {
///
/// Runs a command via a gRPC service implementing the Bazel Remote Execution API
/// (https://docs.google.com/document/d/1AaGk7fOPByEvpAbqeXIyE8HX_A3_axxNnvroblTZ_6s/edit).
///
/// 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.
///
/// Loops until the server gives a response, either successful or error. Does not have any
/// timeout: polls in a tight loop.
///
/// TODO: Request jdk_home be created if set.
///
fn run(
&self,
req: ExecuteProcessRequest,
workunit_store: WorkUnitStore,
) -> BoxFuture<FallibleExecuteProcessResult, String> {
let operations_client = self.operations_client.clone();
let store = self.store.clone();
let execute_request_result = make_execute_request(&req, self.metadata.clone());
let ExecuteProcessRequest {
description,
timeout,
input_files,
..
} = req;
let description2 = description.clone();
match execute_request_result {
Ok((action, command, execute_request)) => {
let command_runner = self.clone();
let command_runner2 = self.clone();
let command_runner3 = self.clone();
let execute_request = Arc::new(execute_request);
let execute_request2 = execute_request.clone();
let store2 = store.clone();
let mut history = ExecutionHistory::default();
self
.store_proto_locally(&command)
.join(self.store_proto_locally(&action))
.and_then(move |(command_digest, action_digest)| {
store2.ensure_remote_has_recursive(vec![command_digest, action_digest, input_files])
})
.and_then(move |summary| {
history.current_attempt += summary;
trace!(
"Executing remotely request: {:?} (command: {:?})",
execute_request,
command
);
command_runner
.oneshot_execute(&execute_request)
.join(future::ok(history))
})
.and_then(move |(operation, history)| {
let start_time = Instant::now();
future::loop_fn(
(history, operation, 0),
move |(mut history, operation, iter_num)| {
let description = description.clone();
let execute_request2 = execute_request2.clone();
let store = store.clone();
let operations_client = operations_client.clone();
let command_runner2 = command_runner2.clone();
let command_runner3 = command_runner3.clone();
let f = command_runner2.extract_execute_response(
operation,
&mut history,
workunit_store.clone(),
);
f.map(future::Loop::Break).or_else(move |value| {
match value {
ExecutionError::Fatal(err) => future::err(err).to_boxed(),
ExecutionError::MissingDigests(missing_digests) => {
let ExecutionHistory {
mut attempts,
current_attempt,
} = history;
trace!(
"Server reported missing digests ({:?}); trying to upload: {:?}",
current_attempt,
missing_digests,
);
attempts.push(current_attempt);
let history = ExecutionHistory {
attempts,
current_attempt: ExecutionStats::default(),
};
let execute_request = execute_request2.clone();
store
.ensure_remote_has_recursive(missing_digests)
.and_then(move |summary| {
let mut history = history;
history.current_attempt += summary;
command_runner2
.oneshot_execute(&execute_request)
.join(future::ok(history))
})
// Reset `iter_num` on `MissingDigests`
.map(|(operation, history)| future::Loop::Continue((history, operation, 0)))
.to_boxed()
}
ExecutionError::NotFinished(operation_name) => {
let mut operation_request =
bazel_protos::operations::GetOperationRequest::new();
operation_request.set_name(operation_name.clone());
let backoff_period = min(
CommandRunner::BACKOFF_MAX_WAIT_MILLIS,
(1 + iter_num) * CommandRunner::BACKOFF_INCR_WAIT_MILLIS,
);
// take the grpc result and cancel the op if too much time has passed.
let elapsed = start_time.elapsed();
if elapsed > timeout {
future::err(format!(
"Exceeded time out of {:?} with {:?} for operation {}, {}",
timeout, elapsed, operation_name, description
))
.to_boxed()
} else {
// maybe the delay here should be the min of remaining time and the backoff period
Delay::new(Instant::now() + Duration::from_millis(backoff_period))
.map_err(move |e| {
format!(
"Future-Delay errored at operation result polling for {}, {}: {}",
operation_name, description, e
)
})
.and_then(move |_| {
future::done(
operations_client
.get_operation_opt(
&operation_request,
command_runner3.call_option(),
)
.or_else(move |err| {
rpcerror_recover_cancelled(operation_request.take_name(), err)
})
.map(OperationOrStatus::Operation)
.map_err(rpcerror_to_string),
)
.map(move |operation| {
future::Loop::Continue((history, operation, iter_num + 1))
})
.to_boxed()
})
.to_boxed()
}
}
}
})
},
)
})
.map(move |resp| {
let mut attempts = String::new();
for (i, attempt) in resp.execution_attempts.iter().enumerate() {
attempts += &format!("\nAttempt {}: {:?}", i, attempt);
}
debug!(
"Finished remote exceution of {} after {} attempts: Stats: {}",
description2,
resp.execution_attempts.len(),
attempts
);
resp
})
.to_boxed()
}
Err(err) => future::err(err).to_boxed(),
}
}
}
impl CommandRunner {
const BACKOFF_INCR_WAIT_MILLIS: u64 = 500;
const BACKOFF_MAX_WAIT_MILLIS: u64 = 5000;
pub fn new(
address: &str,
metadata: ExecuteProcessRequestMetadata,
root_ca_certs: Option<Vec<u8>>,
oauth_bearer_token: Option<String>,
store: Store,
) -> CommandRunner {
let env = Arc::new(grpcio::EnvBuilder::new().build());
let channel = {
let builder = grpcio::ChannelBuilder::new(env.clone());
if let Some(root_ca_certs) = root_ca_certs {
let creds = grpcio::ChannelCredentialsBuilder::new()
.root_cert(root_ca_certs)
.build();
builder.secure_connect(address, creds)
} else {
builder.connect(address)
}
};
let execution_client = Arc::new(bazel_protos::remote_execution_grpc::ExecutionClient::new(
channel.clone(),
));
let operations_client = Arc::new(bazel_protos::operations_grpc::OperationsClient::new(
channel.clone(),
));
CommandRunner {
metadata,
authorization_header: oauth_bearer_token.map(|t| format!("Bearer {}", t)),
channel,
env,
execution_client,
operations_client,
store,
}
}
fn call_option(&self) -> grpcio::CallOption {
let mut call_option = grpcio::CallOption::default();
if let Some(ref authorization_header) = self.authorization_header {
let mut builder = grpcio::MetadataBuilder::with_capacity(1);
builder
.add_str("authorization", &authorization_header)
.unwrap();
call_option = call_option.headers(builder.build());
}
call_option
}
fn store_proto_locally<P: protobuf::Message>(
&self,
proto: &P,
) -> impl Future<Item = Digest, Error = String> {
let store = self.store.clone();
future::done(
proto
.write_to_bytes()
.map_err(|e| format!("Error serializing proto {:?}", e)),
)
.and_then(move |command_bytes| store.store_file_bytes(Bytes::from(command_bytes), true))
.map_err(|e| format!("Error saving proto to local store: {:?}", e))
}
fn extract_execute_response(
&self,
operation_or_status: OperationOrStatus,
attempts: &mut ExecutionHistory,
workunit_store: WorkUnitStore,
) -> BoxFuture<FallibleExecuteProcessResult, ExecutionError> {
trace!("Got operation response: {:?}", operation_or_status);
let status = match operation_or_status {
OperationOrStatus::Operation(mut operation) => {
if !operation.get_done() {
return future::err(ExecutionError::NotFinished(operation.take_name())).to_boxed();
}
if operation.has_error() {
return future::err(ExecutionError::Fatal(format_error(&operation.get_error())))
.to_boxed();
}
if !operation.has_response() {
return future::err(ExecutionError::Fatal(
"Operation finished but no response supplied".to_string(),
))
.to_boxed();
}
let mut execute_response = bazel_protos::remote_execution::ExecuteResponse::new();
try_future!(execute_response
.merge_from_bytes(operation.get_response().get_value())
.map_err(|e| ExecutionError::Fatal(format!("Invalid ExecuteResponse: {:?}", e))));
trace!("Got (nested) execute response: {:?}", execute_response);
if execute_response.get_result().has_execution_metadata() {
let metadata = execute_response.get_result().get_execution_metadata();
let enqueued = timespec_from(metadata.get_queued_timestamp());
let worker_start = timespec_from(metadata.get_worker_start_timestamp());
let input_fetch_start = timespec_from(metadata.get_input_fetch_start_timestamp());
let input_fetch_completed = timespec_from(metadata.get_input_fetch_completed_timestamp());
let execution_start = timespec_from(metadata.get_execution_start_timestamp());
let execution_completed = timespec_from(metadata.get_execution_completed_timestamp());
let output_upload_start = timespec_from(metadata.get_output_upload_start_timestamp());
let output_upload_completed =
timespec_from(metadata.get_output_upload_completed_timestamp());
let parent_id = get_parent_id();
let result_cached = execute_response.get_cached_result();
match (worker_start - enqueued).to_std() {
Ok(duration) => {
attempts.current_attempt.remote_queue = Some(duration);
maybe_add_workunit(
result_cached,
"remote execution action scheduling",
enqueued,
worker_start,
parent_id.clone(),
&workunit_store,
);
}
Err(err) => warn!("Got negative remote queue time: {}", err),
}
match (input_fetch_completed - input_fetch_start).to_std() {
Ok(duration) => {
attempts.current_attempt.remote_input_fetch = Some(duration);
maybe_add_workunit(
result_cached,
"remote execution worker input fetching",
input_fetch_start,
input_fetch_completed,
parent_id.clone(),
&workunit_store,
);
}
Err(err) => warn!("Got negative remote input fetch time: {}", err),
}
match (execution_completed - execution_start).to_std() {
Ok(duration) => {
attempts.current_attempt.remote_execution = Some(duration);
maybe_add_workunit(
result_cached,
"remote execution worker command executing",
execution_start,
execution_completed,
parent_id.clone(),
&workunit_store,
);
}
Err(err) => warn!("Got negative remote execution time: {}", err),
}
match (output_upload_completed - output_upload_start).to_std() {
Ok(duration) => {
attempts.current_attempt.remote_output_store = Some(duration);
maybe_add_workunit(
result_cached,
"remote execution worker output uploading",
output_upload_start,
output_upload_completed,
parent_id,
&workunit_store,
);
}
Err(err) => warn!("Got negative remote output store time: {}", err),
}
attempts.current_attempt.was_cache_hit = execute_response.cached_result;
}
let mut execution_attempts = std::mem::replace(&mut attempts.attempts, vec![]);
execution_attempts.push(attempts.current_attempt);
let status = execute_response.take_status();
if grpcio::RpcStatusCode::from(status.get_code()) == grpcio::RpcStatusCode::Ok {
return populate_fallible_execution_result(
self.store.clone(),
execute_response,
execution_attempts,
)
.map_err(ExecutionError::Fatal)
.to_boxed();
}
status
}
OperationOrStatus::Status(status) => status,
};
match grpcio::RpcStatusCode::from(status.get_code()) {
grpcio::RpcStatusCode::Ok => unreachable!(),
grpcio::RpcStatusCode::FailedPrecondition => {
if status.get_details().len() != 1 {
return future::err(ExecutionError::Fatal(format!(
"Received multiple details in FailedPrecondition ExecuteResponse's status field: {:?}",
status.get_details()
)))
.to_boxed();
}
let details = status.get_details().get(0).unwrap();
let mut precondition_failure = bazel_protos::error_details::PreconditionFailure::new();
if details.get_type_url()
!= format!(
"type.googleapis.com/{}",
precondition_failure.descriptor().full_name()
)
{
return future::err(ExecutionError::Fatal(format!(
"Received FailedPrecondition, but didn't know how to resolve it: {},\
protobuf type {}",
status.get_message(),
details.get_type_url()
)))
.to_boxed();
}
try_future!(precondition_failure
.merge_from_bytes(details.get_value())
.map_err(|e| ExecutionError::Fatal(format!(
"Error deserializing FailedPrecondition proto: {:?}",
e
))));
let mut missing_digests = Vec::with_capacity(precondition_failure.get_violations().len());
for violation in precondition_failure.get_violations() {
if violation.get_field_type() != "MISSING" {
return future::err(ExecutionError::Fatal(format!(
"Didn't know how to process PreconditionFailure violation: {:?}",
violation
)))
.to_boxed();
}
let parts: Vec<_> = violation.get_subject().split('/').collect();
if parts.len() != 3 || parts[0] != "blobs" {
return future::err(ExecutionError::Fatal(format!(
"Received FailedPrecondition MISSING but didn't recognize subject {}",
violation.get_subject()
)))
.to_boxed();
}
let digest = Digest(
try_future!(Fingerprint::from_hex_string(parts[1]).map_err(|e| {
ExecutionError::Fatal(format!("Bad digest in missing blob: {}: {}", parts[1], e))
})),
try_future!(parts[2]
.parse::<usize>()
.map_err(|e| ExecutionError::Fatal(format!(
"Missing blob had bad size: {}: {}",
parts[2], e
)))),
);
missing_digests.push(digest);
}
if missing_digests.is_empty() {
return future::err(ExecutionError::Fatal(
"Error from remote execution: FailedPrecondition, but no details".to_owned(),
))
.to_boxed();
}
future::err(ExecutionError::MissingDigests(missing_digests)).to_boxed()
}
code => future::err(ExecutionError::Fatal(format!(
"Error from remote execution: {:?}: {:?}",
code,
status.get_message()
)))
.to_boxed(),
}
.to_boxed()
}
}
fn maybe_add_workunit(
result_cached: bool,
name: &str,
start_time: Timespec,
end_time: Timespec,
parent_id: Option<String>,
workunit_store: &WorkUnitStore,
) {
// TODO: workunits for scheduling, fetching, executing and uploading should be recorded
// only if '--reporting-zipkin-trace-v2' is set
if !result_cached {
let workunit = WorkUnit {
name: String::from(name),
start_timestamp: start_time,
end_timestamp: end_time,
span_id: generate_random_64bit_string(),
parent_id,
};
workunit_store.add_workunit(workunit);
}
}
pub fn make_execute_request(
req: &ExecuteProcessRequest,
metadata: ExecuteProcessRequestMetadata,
) -> Result<
(
bazel_protos::remote_execution::Action,
bazel_protos::remote_execution::Command,
bazel_protos::remote_execution::ExecuteRequest,
),
String,
> {
let mut command = bazel_protos::remote_execution::Command::new();
command.set_arguments(protobuf::RepeatedField::from_vec(req.argv.clone()));
for (ref name, ref value) in &req.env {
if name.as_str() == CACHE_KEY_GEN_VERSION_ENV_VAR_NAME {
return Err(format!(
"Cannot set env var with name {} as that is reserved for internal use by pants",
CACHE_KEY_GEN_VERSION_ENV_VAR_NAME
));
}
let mut env = bazel_protos::remote_execution::Command_EnvironmentVariable::new();
env.set_name(name.to_string());
env.set_value(value.to_string());
command.mut_environment_variables().push(env);
}
let ExecuteProcessRequestMetadata {
instance_name,
cache_key_gen_version,
mut platform_properties,
} = metadata;
if let Some(cache_key_gen_version) = cache_key_gen_version {
let mut env = bazel_protos::remote_execution::Command_EnvironmentVariable::new();
env.set_name(CACHE_KEY_GEN_VERSION_ENV_VAR_NAME.to_string());
env.set_value(cache_key_gen_version);
command.mut_environment_variables().push(env);
}
let mut output_files = req
.output_files
.iter()
.map(|p| {
p.to_str()
.map(str::to_owned)
.ok_or_else(|| format!("Non-UTF8 output file path: {:?}", p))
})
.collect::<Result<Vec<String>, String>>()?;
output_files.sort();
command.set_output_files(protobuf::RepeatedField::from_vec(output_files));
let mut output_directories = req
.output_directories
.iter()
.map(|p| {
p.to_str()
.map(str::to_owned)
.ok_or_else(|| format!("Non-UTF8 output directory path: {:?}", p))
})
.collect::<Result<Vec<String>, String>>()?;
output_directories.sort();
command.set_output_directories(protobuf::RepeatedField::from_vec(output_directories));
if req.jdk_home.is_some() {
// Ideally, the JDK would be brought along as part of the input directory, but we don't
// currently have support for that. Scoot supports this property, and will symlink .jdk to a
// system-installed JDK https://github.com/twitter/scoot/pull/391 - we should probably come to
// some kind of consensus across tools as to how this should work; RBE appears to work by
// allowing you to specify a jdk-version platform property, and it will put a JDK at a
// well-known path in the docker container you specify in which to run.
platform_properties.insert("JDK_SYMLINK".to_owned(), ".jdk".to_owned());
}
for (name, value) in platform_properties {
command.mut_platform().mut_properties().push({
let mut property = bazel_protos::remote_execution::Platform_Property::new();
property.set_name(name.clone());
property.set_value(value.clone());
property
});
}
let mut action = bazel_protos::remote_execution::Action::new();
action.set_command_digest((&digest(&command)?).into());
action.set_input_root_digest((&req.input_files).into());
let mut execute_request = bazel_protos::remote_execution::ExecuteRequest::new();
if let Some(instance_name) = instance_name {
execute_request.set_instance_name(instance_name);
}
execute_request.set_action_digest((&digest(&action)?).into());
Ok((action, command, execute_request))
}
pub fn populate_fallible_execution_result(
store: Store,
execute_response: bazel_protos::remote_execution::ExecuteResponse,
execution_attempts: Vec<ExecutionStats>,
) -> impl Future<Item = FallibleExecuteProcessResult, Error = String> {
extract_stdout(&store, &execute_response)
.join(extract_stderr(&store, &execute_response))
.join(extract_output_files(store, &execute_response))
.and_then(move |((stdout, stderr), output_directory)| {
Ok(FallibleExecuteProcessResult {
stdout: stdout,
stderr: stderr,
exit_code: execute_response.get_result().get_exit_code(),
output_directory: output_directory,
execution_attempts: execution_attempts,
})
})
}
fn extract_stdout(
store: &Store,
execute_response: &bazel_protos::remote_execution::ExecuteResponse,
) -> BoxFuture<Bytes, String> {
if execute_response.get_result().has_stdout_digest() {
let stdout_digest_result: Result<Digest, String> =
execute_response.get_result().get_stdout_digest().into();
let stdout_digest =
try_future!(stdout_digest_result.map_err(|err| format!("Error extracting stdout: {}", err)));
store
.load_file_bytes_with(stdout_digest, |v| v)
.map_err(move |error| {
format!(
"Error fetching stdout digest ({:?}): {:?}",
stdout_digest, error
)
})
.and_then(move |maybe_value| {
maybe_value.ok_or_else(|| {
format!(
"Couldn't find stdout digest ({:?}), when fetching.",
stdout_digest
)
})
})
.map(|(bytes, _metadata)| bytes)
.to_boxed()
} else {
let stdout_raw = Bytes::from(execute_response.get_result().get_stdout_raw());
let stdout_copy = stdout_raw.clone();
store
.store_file_bytes(stdout_raw, true)
.map_err(move |error| format!("Error storing raw stdout: {:?}", error))
.map(|_| stdout_copy)
.to_boxed()
}
}
fn extract_stderr(
store: &Store,
execute_response: &bazel_protos::remote_execution::ExecuteResponse,
) -> BoxFuture<Bytes, String> {
if execute_response.get_result().has_stderr_digest() {
let stderr_digest_result: Result<Digest, String> =
execute_response.get_result().get_stderr_digest().into();
let stderr_digest =
try_future!(stderr_digest_result.map_err(|err| format!("Error extracting stderr: {}", err)));
store
.load_file_bytes_with(stderr_digest, |v| v)
.map_err(move |error| {
format!(
"Error fetching stderr digest ({:?}): {:?}",
stderr_digest, error
)
})
.and_then(move |maybe_value| {
maybe_value.ok_or_else(|| {
format!(
"Couldn't find stderr digest ({:?}), when fetching.",
stderr_digest
)
})
})
.map(|(bytes, _metadata)| bytes)
.to_boxed()
} else {
let stderr_raw = Bytes::from(execute_response.get_result().get_stderr_raw());
let stderr_copy = stderr_raw.clone();
store
.store_file_bytes(stderr_raw, true)
.map_err(move |error| format!("Error storing raw stderr: {:?}", error))
.map(|_| stderr_copy)
.to_boxed()
}
}
fn extract_output_files(
store: Store,
execute_response: &bazel_protos::remote_execution::ExecuteResponse,
) -> BoxFuture<Digest, String> {
// Get Digests of output Directories.
// Then we'll make a Directory for the output files, and merge them.
let mut directory_digests =
Vec::with_capacity(execute_response.get_result().get_output_directories().len() + 1);
// TODO: Maybe take rather than clone
let output_directories = execute_response
.get_result()
.get_output_directories()
.to_owned();
for dir in output_directories {
let digest_result: Result<Digest, String> = dir.get_tree_digest().into();
let mut digest = future::done(digest_result).to_boxed();
if !dir.get_path().is_empty() {
for component in dir.get_path().rsplit('/') {
let component = component.to_owned();
let store = store.clone();
digest = digest
.and_then(move |digest| {
let mut directory = bazel_protos::remote_execution::Directory::new();
directory.mut_directories().push({
let mut node = bazel_protos::remote_execution::DirectoryNode::new();
node.set_name(component);
node.set_digest((&digest).into());
node
});
store.record_directory(&directory, true)
})
.to_boxed();
}
}
directory_digests
.push(digest.map_err(|err| format!("Error saving remote output directory: {}", err)));
}
// Make a directory for the files
let mut path_map = HashMap::new();
let path_stats_result: Result<Vec<PathStat>, String> = execute_response
.get_result()
.get_output_files()
.iter()
.map(|output_file| {
let output_file_path_buf = PathBuf::from(output_file.get_path());
let digest: Result<Digest, String> = output_file.get_digest().into();
path_map.insert(output_file_path_buf.clone(), digest?);
Ok(PathStat::file(
output_file_path_buf.clone(),
File {
path: output_file_path_buf,
is_executable: output_file.get_is_executable(),
},
))
})
.collect();
let path_stats = try_future!(path_stats_result);
#[derive(Clone)]
struct StoreOneOffRemoteDigest {
map_of_paths_to_digests: HashMap<PathBuf, Digest>,
}
impl StoreOneOffRemoteDigest {
fn new(map: HashMap<PathBuf, Digest>) -> StoreOneOffRemoteDigest {
StoreOneOffRemoteDigest {
map_of_paths_to_digests: map,
}
}
}
impl StoreFileByDigest<String> for StoreOneOffRemoteDigest {
fn store_by_digest(&self, file: File) -> BoxFuture<Digest, String> {
match self.map_of_paths_to_digests.get(&file.path) {
Some(digest) => future::ok(*digest),
None => future::err(format!(
"Didn't know digest for path in remote execution response: {:?}",
file.path
)),
}
.to_boxed()
}
}
let store = store.clone();
Snapshot::digest_from_path_stats(
store.clone(),
&StoreOneOffRemoteDigest::new(path_map),
&path_stats,
)
.map_err(move |error| {
format!(
"Error when storing the output file directory info in the remote CAS: {:?}",
error
)
})
.join(future::join_all(directory_digests))
.and_then(|(files_digest, mut directory_digests)| {
directory_digests.push(files_digest);
Snapshot::merge_directories(store, directory_digests)
.map_err(|err| format!("Error when merging output files and directories: {}", err))
})
.to_boxed()
}
fn format_error(error: &bazel_protos::status::Status) -> String {
let error_code_enum = bazel_protos::code::Code::from_i32(error.get_code());
let error_code = match error_code_enum {
Some(x) => format!("{:?}", x),
None => format!("{:?}", error.get_code()),
};
format!("{}: {}", error_code, error.get_message())
}
///
/// If the given operation represents a cancelled request, recover it into
/// ExecutionError::NotFinished.
///
fn rpcerror_recover_cancelled(
operation_name: String,
err: grpcio::Error,
) -> Result<bazel_protos::operations::Operation, grpcio::Error> {
// If the error represented cancellation, return an Operation for the given Operation name.
match &err {
&grpcio::Error::RpcFailure(ref rs) if rs.status == grpcio::RpcStatusCode::Cancelled => {
let mut next_operation = bazel_protos::operations::Operation::new();
next_operation.set_name(operation_name);
return Ok(next_operation);
}
_ => {}
}
// Did not represent cancellation.
Err(err)
}
fn rpcerror_to_status_or_string(
error: grpcio::Error,
) -> Result<bazel_protos::status::Status, String> {
match error {
grpcio::Error::RpcFailure(grpcio::RpcStatus {
status_proto_bytes: Some(status_proto_bytes),
..
}) => {
let mut status_proto = bazel_protos::status::Status::new();
status_proto.merge_from_bytes(&status_proto_bytes).unwrap();
Ok(status_proto)
}
grpcio::Error::RpcFailure(grpcio::RpcStatus {
status, details, ..
}) => Err(format!(
"{:?}: {:?}",
status,
details.unwrap_or_else(|| "[no message]".to_string())
)),
err => Err(format!("{:?}", err)),
}
}
fn rpcerror_to_string(error: grpcio::Error) -> String {
match error {
grpcio::Error::RpcFailure(status) => format!(
"{:?}: {:?}",
status.status,
status.details.unwrap_or_else(|| "[no message]".to_string())
),
err => format!("{:?}", err),
}
}
fn digest(message: &dyn Message) -> Result<Digest, String> {
let bytes = message.write_to_bytes().map_err(|e| format!("{:?}", e))?;
let mut hasher = Sha256::default();
hasher.input(&bytes);
Ok(Digest(
Fingerprint::from_bytes_unsafe(&hasher.fixed_result()),
bytes.len(),
))
}
fn timespec_from(timestamp: &protobuf::well_known_types::Timestamp) -> time::Timespec {
time::Timespec::new(timestamp.seconds, timestamp.nanos)
}
#[cfg(test)]
pub mod tests {
use bazel_protos;
use bazel_protos::operations::Operation;
use bazel_protos::remote_execution::ExecutedActionMetadata;
use bytes::Bytes;
use futures::Future;
use grpcio;
use hashing::{Digest, Fingerprint, EMPTY_DIGEST};
use mock;
use protobuf::{self, Message, ProtobufEnum};
use store::Store;
use tempfile::TempDir;
use testutil::data::{TestData, TestDirectory};
use testutil::{as_bytes, owned_string_vec};
use super::super::CommandRunner as CommandRunnerTrait;
use super::{
CommandRunner, ExecuteProcessRequest, ExecuteProcessRequestMetadata, ExecutionError,
ExecutionHistory, FallibleExecuteProcessResult,
};
use maplit::hashset;
use mock::execution_server::MockOperation;
use protobuf::well_known_types::Timestamp;
use std::collections::{BTreeMap, BTreeSet};
use std::iter::{self, FromIterator};