-
Notifications
You must be signed in to change notification settings - Fork 240
/
Copy pathclient.rs
2200 lines (1943 loc) · 74.5 KB
/
client.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 (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use std::collections::HashMap;
use std::env::VarError;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use anyhow::Context;
use buck2_re_configuration::Buck2OssReConfiguration;
use buck2_re_configuration::HttpHeader;
use dupe::Dupe;
use futures::future::BoxFuture;
use futures::future::Future;
use futures::stream::BoxStream;
use futures::stream::StreamExt;
use futures::stream::TryStreamExt;
use futures::Stream;
use gazebo::prelude::*;
use once_cell::sync::Lazy;
use prost::Message;
use re_grpc_proto::build::bazel::remote::execution::v2::action_cache_client::ActionCacheClient;
use re_grpc_proto::build::bazel::remote::execution::v2::batch_update_blobs_request::Request;
use re_grpc_proto::build::bazel::remote::execution::v2::capabilities_client::CapabilitiesClient;
use re_grpc_proto::build::bazel::remote::execution::v2::compressor;
use re_grpc_proto::build::bazel::remote::execution::v2::content_addressable_storage_client::ContentAddressableStorageClient;
use re_grpc_proto::build::bazel::remote::execution::v2::execution_client::ExecutionClient;
use re_grpc_proto::build::bazel::remote::execution::v2::execution_stage;
use re_grpc_proto::build::bazel::remote::execution::v2::ActionResult;
use re_grpc_proto::build::bazel::remote::execution::v2::BatchReadBlobsRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::BatchReadBlobsResponse;
use re_grpc_proto::build::bazel::remote::execution::v2::BatchUpdateBlobsRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::BatchUpdateBlobsResponse;
use re_grpc_proto::build::bazel::remote::execution::v2::Digest;
use re_grpc_proto::build::bazel::remote::execution::v2::ExecuteOperationMetadata;
use re_grpc_proto::build::bazel::remote::execution::v2::ExecuteRequest as GExecuteRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::ExecuteResponse as GExecuteResponse;
use re_grpc_proto::build::bazel::remote::execution::v2::FindMissingBlobsRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::FindMissingBlobsResponse;
use re_grpc_proto::build::bazel::remote::execution::v2::GetActionResultRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::GetCapabilitiesRequest;
use re_grpc_proto::build::bazel::remote::execution::v2::ResultsCachePolicy;
use re_grpc_proto::google::bytestream::byte_stream_client::ByteStreamClient;
use re_grpc_proto::google::bytestream::ReadRequest;
use re_grpc_proto::google::bytestream::ReadResponse;
use re_grpc_proto::google::bytestream::WriteRequest;
use re_grpc_proto::google::bytestream::WriteResponse;
use re_grpc_proto::google::longrunning::operation::Result as OpResult;
use re_grpc_proto::google::rpc::Code;
use re_grpc_proto::google::rpc::Status;
use regex::Regex;
use tokio::fs::OpenOptions;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tonic::codegen::InterceptedService;
use tonic::metadata;
use tonic::metadata::MetadataKey;
use tonic::metadata::MetadataValue;
use tonic::service::Interceptor;
use tonic::transport::channel::ClientTlsConfig;
use tonic::transport::Certificate;
use tonic::transport::Channel;
use tonic::transport::Identity;
use tonic::transport::Uri;
use crate::error::*;
use crate::metadata::*;
use crate::request::*;
use crate::response::*;
// RBE Services (e.g. Buildbarn) may not be robust against having too many files open at
// once. Limit to an arbitrary reasonable number since this information is not expressed
// in the Capabilities message query.
const CONCURRENT_UPLOAD_LIMIT: usize = 64;
const DEFAULT_MAX_MSG_SIZE: usize = 4 * 1000 * 1000;
fn tdigest_to(tdigest: TDigest) -> Digest {
Digest {
hash: tdigest.hash,
size_bytes: tdigest.size_in_bytes,
}
}
fn tdigest_from(digest: Digest) -> TDigest {
TDigest {
hash: digest.hash,
size_in_bytes: digest.size_bytes,
..Default::default()
}
}
fn tstatus_ok() -> TStatus {
TStatus {
code: TCode::OK,
message: "".to_owned(),
..Default::default()
}
}
fn check_status(status: Status) -> Result<(), REClientError> {
if status.code == 0 {
return Ok(());
}
Err(REClientError {
code: TCode(status.code),
message: status.message,
})
}
fn ttimestamp_from(ts: Option<::prost_types::Timestamp>) -> TTimestamp {
match ts {
Some(timestamp) => TTimestamp {
seconds: timestamp.seconds,
nanos: timestamp.nanos,
..Default::default()
},
None => TTimestamp::unix_epoch(),
}
}
async fn create_tls_config(opts: &Buck2OssReConfiguration) -> anyhow::Result<ClientTlsConfig> {
let config = ClientTlsConfig::new();
let config = match opts.tls_ca_certs.as_ref() {
Some(tls_ca_certs) => {
let tls_ca_certs =
substitute_env_vars(tls_ca_certs).context("Invalid `tls_ca_certs`")?;
let data = tokio::fs::read(&tls_ca_certs)
.await
.with_context(|| format!("Error reading `{}`", tls_ca_certs))?;
config.ca_certificate(Certificate::from_pem(data))
}
None => {
// We set the `tls-webpki-roots` feature so we'll get that default.
config
}
};
let config = match opts.tls_client_cert.as_ref() {
Some(tls_client_cert) => {
let tls_client_cert =
substitute_env_vars(tls_client_cert).context("Invalid `tls_client_cert`")?;
let data = tokio::fs::read(&tls_client_cert)
.await
.with_context(|| format!("Error reading `{}`", tls_client_cert))?;
config.identity(Identity::from_pem(&data, &data))
}
None => config,
};
Ok(config)
}
fn prepare_uri(uri: Uri, tls: bool) -> anyhow::Result<Uri> {
// Now do some awkward things with the protocol. Why do we do all this? The reason is
// because we'd like our configuration to not be super confusing. We don't want to e.g.
// allow setting the address to `https://foobar` without enabling TLS (or enabling tls
// and using `http://foobar`), so we restrict ourselves to schemes that are actually
// remotely valid in GRPC (which is more restrictive than what Tonic allows).
// This is the GRPC spec for naming: https://github.com/grpc/grpc/blob/master/doc/naming.md
// Many people (including Bazel), use grpc://, so we tolerate it.
match uri.scheme_str() {
Some("grpc") | Some("dns") | Some("ipv4") | Some("ipv6") | None => {}
Some(scheme) => {
return Err(anyhow::anyhow!(
"Invalid URI scheme: `{}` (you should omit it)",
scheme
));
}
};
// And now, let's put back a proper scheme for Tonic to be happy with. First, because
// Tonic will blow up if we don't. Second, so we get port inference.
let mut parts = uri.into_parts();
parts.scheme = Some(if tls {
http::uri::Scheme::HTTPS
} else {
http::uri::Scheme::HTTP
});
// Is this API actually designed to be unusable? If you've got a scheme, you must
// have a path_and_query. I'm sure there's a good reason, so we abide:
if parts.path_and_query.is_none() {
parts.path_and_query = Some(http::uri::PathAndQuery::from_static(""));
}
Ok(Uri::from_parts(parts)?)
}
/// Contains information queried from the the Remote Execution Capabilities service.
pub struct RECapabilities {
/// Largest size of a message before being uploaded using bytestream service.
/// 0 indicates no limit beyond constraint of underlying transport (which is unknown).
max_msg_size: usize,
/// Does the remote server support execution.
exec_enabled: bool,
}
struct InstanceName(Option<String>);
impl InstanceName {
fn as_str(&self) -> &str {
match &self.0 {
Some(instance_name) => instance_name,
None => "",
}
}
fn as_resource_prefix(&self) -> String {
match &self.0 {
Some(instance_name) => format!("{}/", instance_name),
None => "".to_owned(),
}
}
}
pub struct REClientBuilder;
impl REClientBuilder {
pub async fn build_and_connect(opts: &Buck2OssReConfiguration) -> anyhow::Result<REClient> {
// We just always create this just in case, so that we implicitly validate it if set.
let tls_config = create_tls_config(opts)
.await
.context("Invalid TLS config")?;
let tls_config = &tls_config;
let create_channel = |address: Option<String>| async move {
let address = address.as_ref().context("No address")?;
let address = substitute_env_vars(address).context("Invalid address")?;
let uri = address.parse().context("Invalid address")?;
let uri = prepare_uri(uri, opts.tls).context("Invalid URI")?;
let mut channel = Channel::builder(uri);
if opts.tls {
channel = channel.tls_config(tls_config.clone())?;
}
anyhow::Ok(
channel
.connect()
.await
.with_context(|| format!("Error connecting to `{}`", address))?,
)
};
let (cas, execution, action_cache, bytestream, capabilities) = futures::future::join5(
create_channel(opts.cas_address.clone()),
create_channel(opts.engine_address.clone()),
create_channel(opts.action_cache_address.clone()),
create_channel(opts.cas_address.clone()),
create_channel(opts.engine_address.clone()),
)
.await;
let interceptor = InjectHeadersInterceptor::new(&opts.http_headers)?;
let mut grpc_clients = GRPCClients {
cas_client: ContentAddressableStorageClient::with_interceptor(
cas.context("Error creating CAS client")?,
interceptor.dupe(),
),
execution_client: ExecutionClient::with_interceptor(
execution.context("Error creating Execution client")?,
interceptor.dupe(),
),
action_cache_client: ActionCacheClient::with_interceptor(
action_cache.context("Error creating ActionCache client")?,
interceptor.dupe(),
),
bytestream_client: ByteStreamClient::with_interceptor(
bytestream.context("Error creating Bytestream client")?,
interceptor.dupe(),
),
capabilities_client: CapabilitiesClient::with_interceptor(
capabilities.context("Error creating Capabilities client")?,
interceptor.dupe(),
),
};
let instance_name = InstanceName(opts.instance_name.clone());
let capabilities = if opts.capabilities.unwrap_or(true) {
Self::fetch_rbe_capabilities(&mut grpc_clients, &instance_name).await?
} else {
RECapabilities {
exec_enabled: true,
max_msg_size: DEFAULT_MAX_MSG_SIZE,
}
};
if !capabilities.exec_enabled {
return Err(anyhow::anyhow!("Server has remote execution disabled."));
}
Ok(REClient::new(grpc_clients, capabilities, instance_name))
}
async fn fetch_rbe_capabilities(
clients: &mut GRPCClients,
instance_name: &InstanceName,
) -> anyhow::Result<RECapabilities> {
// TODO use more of the capabilities of the remote build executor
let resp = clients
.capabilities_client
.get_capabilities(GetCapabilitiesRequest {
instance_name: instance_name.as_str().to_owned(),
})
.await
.context("Failed to query capabilities of remote")?
.into_inner();
// Default is a reasonable size for the gRPC transport
// with enough room for headers.
let mut max_msg_size = DEFAULT_MAX_MSG_SIZE;
let mut exec_enabled = true;
if let Some(cache_cap) = resp.cache_capabilities {
let size = cache_cap.max_batch_total_size_bytes as usize;
// A value of 0 means no limit is set
if size != 0 {
max_msg_size = size;
}
}
if let Some(exec_cap) = resp.execution_capabilities {
exec_enabled = exec_cap.exec_enabled;
}
Ok(RECapabilities {
max_msg_size,
exec_enabled,
})
}
}
#[derive(Clone, Dupe)]
struct InjectHeadersInterceptor {
headers: Arc<Vec<(MetadataKey<metadata::Ascii>, MetadataValue<metadata::Ascii>)>>,
}
impl InjectHeadersInterceptor {
pub fn new(headers: &[HttpHeader]) -> anyhow::Result<Self> {
let headers = headers
.iter()
.map(|h| {
// This means we can't have `$` in a header key or value, which isn't great. On the
// flip side, env vars are good for things like credentials, which those headers
// are likely to contain. In time, we should allow escaping.
let key = substitute_env_vars(&h.key)?;
let value = substitute_env_vars(&h.value)?;
let key = MetadataKey::<metadata::Ascii>::from_bytes(key.as_bytes())
.with_context(|| format!("Invalid key in header: `{}: {}`", key, value))?;
let value = MetadataValue::try_from(&value)
.with_context(|| format!("Invalid value in header: `{}: {}`", key, value))?;
anyhow::Ok((key, value))
})
.collect::<Result<_, _>>()
.context("Error converting headers")?;
Ok(Self {
headers: Arc::new(headers),
})
}
}
impl Interceptor for InjectHeadersInterceptor {
fn call(
&mut self,
mut request: tonic::Request<()>,
) -> Result<tonic::Request<()>, tonic::Status> {
for (k, v) in self.headers.iter() {
request.metadata_mut().insert(k.clone(), v.clone());
}
Ok(request)
}
}
pub struct GRPCClients {
cas_client:
ContentAddressableStorageClient<InterceptedService<Channel, InjectHeadersInterceptor>>,
execution_client: ExecutionClient<InterceptedService<Channel, InjectHeadersInterceptor>>,
action_cache_client: ActionCacheClient<InterceptedService<Channel, InjectHeadersInterceptor>>,
bytestream_client: ByteStreamClient<InterceptedService<Channel, InjectHeadersInterceptor>>,
capabilities_client: CapabilitiesClient<InterceptedService<Channel, InjectHeadersInterceptor>>,
}
#[derive(Default)]
pub struct REState {
// TODO(aloiscochard): Update those values
network_uploaded: i64, // in bytes
network_downloaded: i64, // in bytes
}
pub struct REClient {
grpc_clients: GRPCClients,
capabilities: RECapabilities,
instance_name: InstanceName,
state: Mutex<REState>,
}
impl Drop for REClient {
fn drop(&mut self) {
// Important we have a drop implementation since the real one does, and we
// don't want errors coming from the stub not having one
}
}
/// Information on components of a batch upload.
/// Used to defer reading of NamedDigest contents till
/// actual execution of upload and prevent opening too many
/// files at the same time.
enum BatchUploadRequest {
Blob(InlinedBlobWithDigest),
File(NamedDigest),
}
/// Builds up a vector of batch upload requests based upon the maximum allowed message size.
#[derive(Default)]
struct BatchUploadReqAggregator {
max_msg_size: i64,
curr_req: Vec<BatchUploadRequest>,
requests: Vec<Vec<BatchUploadRequest>>,
curr_request_size: i64,
}
impl BatchUploadReqAggregator {
pub fn new(max_msg_size: usize) -> Self {
BatchUploadReqAggregator {
max_msg_size: max_msg_size as i64,
..Default::default()
}
}
pub fn push(&mut self, req: BatchUploadRequest) {
let size_in_bytes = match &req {
BatchUploadRequest::Blob(blob) => blob.digest.size_in_bytes,
BatchUploadRequest::File(file) => file.digest.size_in_bytes,
};
self.curr_request_size += size_in_bytes;
if self.curr_request_size >= self.max_msg_size {
self.requests.push(std::mem::take(&mut self.curr_req));
self.curr_request_size = size_in_bytes;
}
self.curr_req.push(req);
}
pub fn done(mut self) -> Vec<Vec<BatchUploadRequest>> {
if !self.curr_req.is_empty() {
self.requests.push(std::mem::take(&mut self.curr_req));
}
self.requests
}
}
impl REClient {
fn new(
grpc_clients: GRPCClients,
capabilities: RECapabilities,
instance_name: InstanceName,
) -> Self {
REClient {
grpc_clients,
capabilities,
instance_name,
state: Mutex::new(REState::default()),
}
}
pub async fn get_action_result(
&self,
metadata: RemoteExecutionMetadata,
request: ActionResultRequest,
) -> anyhow::Result<ActionResultResponse> {
let mut client = self.grpc_clients.action_cache_client.clone();
let res = client
.get_action_result(with_internal_metadata(
GetActionResultRequest {
instance_name: self.instance_name.as_str().to_owned(),
action_digest: Some(tdigest_to(request.digest)),
..Default::default()
},
metadata,
))
.await?;
Ok(ActionResultResponse {
action_result: convert_action_result(res.into_inner())?,
ttl: 0,
})
}
pub async fn write_action_result(
&self,
_metadata: RemoteExecutionMetadata,
_request: WriteActionResultRequest,
) -> anyhow::Result<WriteActionResultResponse> {
Err(anyhow::anyhow!("Not supported"))
}
pub async fn execute_with_progress(
&self,
metadata: RemoteExecutionMetadata,
mut execute_request: ExecuteRequest,
) -> anyhow::Result<BoxStream<'static, anyhow::Result<ExecuteWithProgressResponse>>> {
// TODO(aloiscochard): Map those properly in the request
// use crate::proto::build::bazel::remote::execution::v2::ExecutionPolicy;
let mut client = self.grpc_clients.execution_client.clone();
let action_digest = tdigest_to(execute_request.action_digest.clone());
let request = GExecuteRequest {
instance_name: self.instance_name.as_str().to_owned(),
skip_cache_lookup: false,
execution_policy: None,
results_cache_policy: Some(ResultsCachePolicy { priority: 0 }),
action_digest: Some(action_digest.clone()),
};
let stream = client
.execute(with_internal_metadata(request, metadata))
.await?
.into_inner();
let stream = futures::stream::try_unfold(stream, move |mut stream| async {
let msg = match stream.try_next().await.context("RE channel error")? {
Some(msg) => msg,
None => return Ok(None),
};
let status = if msg.done {
match msg
.result
.context("Missing `result` when message was `done`")?
{
OpResult::Error(rpc_status) => {
return Err(REClientError {
code: TCode(rpc_status.code),
message: rpc_status.message,
}
.into());
}
OpResult::Response(any) => {
let execute_response_grpc: GExecuteResponse =
GExecuteResponse::decode(&any.value[..])?;
check_status(execute_response_grpc.status.unwrap_or_default())?;
let action_result = execute_response_grpc
.result
.with_context(|| "The action result is not defined.")?;
let action_result = convert_action_result(action_result)?;
let execute_response = ExecuteResponse {
action_result,
action_result_digest: TDigest::default(),
action_result_ttl: 0,
error: REError {
code: TCode::OK,
..Default::default()
},
cached_result: execute_response_grpc.cached_result,
action_digest: Default::default(), // Filled in below.
};
ExecuteWithProgressResponse {
stage: Stage::COMPLETED,
execute_response: Some(execute_response),
..Default::default()
}
}
}
} else {
let meta =
ExecuteOperationMetadata::decode(&msg.metadata.unwrap_or_default().value[..])?;
let stage = match execution_stage::Value::from_i32(meta.stage) {
Some(execution_stage::Value::Unknown) => Stage::UNKNOWN,
Some(execution_stage::Value::CacheCheck) => Stage::CACHE_CHECK,
Some(execution_stage::Value::Queued) => Stage::QUEUED,
Some(execution_stage::Value::Executing) => Stage::EXECUTING,
Some(execution_stage::Value::Completed) => Stage::COMPLETED,
_ => Stage::UNKNOWN,
};
ExecuteWithProgressResponse {
stage,
execute_response: None,
..Default::default()
}
};
anyhow::Ok(Some((status, stream)))
});
// We fill in the action digest a little later here. We do it this way so we don't have to
// clone the execute_request into every future we create above.
let stream = stream.map(move |mut r| {
match &mut r {
Ok(ExecuteWithProgressResponse {
execute_response: Some(ref mut response),
..
}) => {
response.action_digest = std::mem::take(&mut execute_request.action_digest);
}
_ => {}
};
r
});
Ok(stream.boxed())
}
pub async fn upload(
&self,
metadata: RemoteExecutionMetadata,
request: UploadRequest,
) -> anyhow::Result<UploadResponse> {
upload_impl(
&self.instance_name,
request,
self.capabilities.max_msg_size,
|re_request| async {
let metadata = metadata.clone();
let mut cas_client = self.grpc_clients.cas_client.clone();
let resp = cas_client
.batch_update_blobs(with_internal_metadata(re_request, metadata))
.await?;
Ok(resp.into_inner())
},
|segments| async {
let metadata = metadata.clone();
let mut bytestream_client = self.grpc_clients.bytestream_client.clone();
let requests = futures::stream::iter(segments);
let resp = bytestream_client
.write(with_internal_metadata(requests, metadata))
.await?;
Ok(resp.into_inner())
},
)
.await
}
pub async fn upload_blob(
&self,
_blob: Vec<u8>,
_metadata: RemoteExecutionMetadata,
) -> anyhow::Result<TDigest> {
// TODO(aloiscochard)
Err(anyhow::anyhow!("Not implemented (RE upload_blob)"))
}
pub async fn download(
&self,
metadata: RemoteExecutionMetadata,
request: DownloadRequest,
) -> anyhow::Result<DownloadResponse> {
download_impl(
&self.instance_name,
request,
self.capabilities.max_msg_size,
|re_request| async {
let metadata = metadata.clone();
let mut client = self.grpc_clients.cas_client.clone();
Ok(client
.batch_read_blobs(with_internal_metadata(re_request, metadata))
.await?
.into_inner())
},
|read_request| {
let metadata = metadata.clone();
async move {
let mut client = self.grpc_clients.bytestream_client.clone();
let response = client
.read(with_internal_metadata(read_request, metadata))
.await?
.into_inner();
Ok(Box::pin(response.into_stream()))
}
},
)
.await
}
pub async fn get_digests_ttl(
&self,
metadata: RemoteExecutionMetadata,
request: GetDigestsTtlRequest,
) -> anyhow::Result<GetDigestsTtlResponse> {
let mut cas_client = self.grpc_clients.cas_client.clone();
let mut remote_ttl: HashMap<TDigest, DigestWithTtl> = HashMap::new();
for digest_chunk in request.digests.chunks(100) {
for digest in digest_chunk {
// Assume that all digests are present on the remote because the API
// returns what is *not* present.
remote_ttl.insert(
digest.clone(),
DigestWithTtl {
digest: digest.clone(),
// NOTE: This is an arbitrary number because RBE does not return information
// on the TTL of the remote blob.
ttl: 60,
},
);
}
let missing_blobs = cas_client
.find_missing_blobs(with_internal_metadata(
FindMissingBlobsRequest {
instance_name: self.instance_name.as_str().to_owned(),
blob_digests: digest_chunk.map(|b| tdigest_to(b.clone())),
},
metadata.clone(),
))
.await
.context("Failed to request what blobs are not present on remote")?;
let resp: FindMissingBlobsResponse = missing_blobs.into_inner();
for digest in &resp.missing_blob_digests.map(|d| tdigest_from(d.clone())) {
// If it's present in the MissingBlobsResponse, it's expired on the remote and
// needs to be refetched.
remote_ttl.insert(
digest.clone(),
DigestWithTtl {
digest: digest.clone(),
ttl: 0,
},
);
}
}
Ok(GetDigestsTtlResponse {
digests_with_ttl: remote_ttl.values().cloned().collect::<Vec<DigestWithTtl>>(),
})
}
pub fn get_execution_client(&self) -> &Self {
self
}
pub fn get_cas_client(&self) -> &Self {
self
}
pub fn get_action_cache_client(&self) -> &Self {
self
}
pub fn get_metrics_client(&self) -> &Self {
self
}
pub fn get_session_id(&self) -> &str {
// TODO(aloiscochard): Return a unique ID, ideally from the GRPC client
"GRPC-SESSION-ID"
}
pub fn get_network_stats(&self) -> anyhow::Result<NetworkStatisticsResponse> {
let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
Ok(NetworkStatisticsResponse {
downloaded: state.network_downloaded,
uploaded: state.network_uploaded,
_dot_dot_default: (),
})
}
pub fn get_experiment_name(&self) -> anyhow::Result<Option<String>> {
Ok(None)
}
}
fn convert_action_result(action_result: ActionResult) -> anyhow::Result<TActionResult2> {
let execution_metadata = action_result
.execution_metadata
.with_context(|| "The execution metadata are not defined.")?;
let output_files = action_result.output_files.into_try_map(|output_file| {
let output_file_digest = output_file.digest.with_context(|| "Digest not found.")?;
anyhow::Ok(TFile {
digest: DigestWithStatus {
status: tstatus_ok(),
digest: tdigest_from(output_file_digest),
_dot_dot_default: (),
},
name: output_file.path,
existed: false,
executable: output_file.is_executable,
ttl: 0,
_dot_dot_default: (),
})
})?;
let output_directories = action_result
.output_directories
.into_try_map(|output_directory| {
let digest = tdigest_from(
output_directory
.tree_digest
.with_context(|| "Tree digest not defined.")?,
);
anyhow::Ok(TDirectory2 {
path: output_directory.path,
tree_digest: digest.clone(),
root_directory_digest: digest,
_dot_dot_default: (),
})
})?;
let action_result = TActionResult2 {
output_files,
output_directories,
exit_code: action_result.exit_code,
stdout_raw: Some(action_result.stdout_raw),
stdout_digest: action_result.stdout_digest.map(tdigest_from),
stderr_raw: Some(action_result.stderr_raw),
stderr_digest: action_result.stderr_digest.map(tdigest_from),
execution_metadata: TExecutedActionMetadata {
worker: execution_metadata.worker,
queued_timestamp: ttimestamp_from(execution_metadata.queued_timestamp),
worker_start_timestamp: ttimestamp_from(execution_metadata.worker_start_timestamp),
worker_completed_timestamp: ttimestamp_from(
execution_metadata.worker_completed_timestamp,
),
input_fetch_start_timestamp: ttimestamp_from(
execution_metadata.input_fetch_start_timestamp,
),
input_fetch_completed_timestamp: ttimestamp_from(
execution_metadata.input_fetch_completed_timestamp,
),
execution_start_timestamp: ttimestamp_from(
execution_metadata.execution_start_timestamp,
),
execution_completed_timestamp: ttimestamp_from(
execution_metadata.execution_completed_timestamp,
),
output_upload_start_timestamp: ttimestamp_from(
execution_metadata.output_upload_start_timestamp,
),
output_upload_completed_timestamp: ttimestamp_from(
execution_metadata.output_upload_completed_timestamp,
),
input_analyzing_start_timestamp: Default::default(),
input_analyzing_completed_timestamp: Default::default(),
execution_dir: "".to_owned(),
execution_attempts: 0,
last_queued_timestamp: Default::default(),
..Default::default()
},
..Default::default()
};
Ok(action_result)
}
async fn download_impl<Byt, BytRet, Cas>(
instance_name: &InstanceName,
request: DownloadRequest,
max_msg_size: usize,
cas_f: impl Fn(BatchReadBlobsRequest) -> Cas,
bystream_fut: impl Fn(ReadRequest) -> Byt + Sync + Send + Copy,
) -> anyhow::Result<DownloadResponse>
where
Byt: Future<Output = anyhow::Result<Pin<Box<BytRet>>>>,
BytRet: Stream<Item = Result<ReadResponse, tonic::Status>>,
Cas: Future<Output = anyhow::Result<BatchReadBlobsResponse>>,
{
let bystream_fut = |digest: TDigest| async move {
let hash = digest.hash;
let size_in_bytes = digest.size_in_bytes;
let resource_name = format!(
"{}blobs/{}/{}",
instance_name.as_resource_prefix(),
hash,
size_in_bytes
);
bystream_fut(ReadRequest {
resource_name: resource_name.clone(),
read_offset: 0,
read_limit: 0,
})
.await
.with_context(|| format!("Failed to read {} from Bytestream service", resource_name))
};
let inlined_digests = request.inlined_digests.unwrap_or_default();
let file_digests = request.file_digests.unwrap_or_default();
let mut curr_size = 0;
let mut requests = vec![];
let mut curr_digests = vec![];
for digest in file_digests
.iter()
.map(|req| &req.named_digest.digest)
.chain(inlined_digests.iter())
.map(|d| tdigest_to(d.clone()))
.filter(|d| d.size_bytes > 0)
{
if digest.size_bytes as usize >= max_msg_size {
// digest is too big to download in a BatchReadBlobsRequest
// need to use the bytstream api
continue;
}
curr_size += digest.size_bytes;
if curr_size >= max_msg_size as i64 {
let read_blob_req = BatchReadBlobsRequest {
instance_name: instance_name.as_str().to_owned(),
digests: std::mem::take(&mut curr_digests),
acceptable_compressors: vec![compressor::Value::Identity as i32],
};
requests.push(read_blob_req);
}
curr_digests.push(digest.clone());
}
if !curr_digests.is_empty() {
let read_blob_req = BatchReadBlobsRequest {
instance_name: instance_name.as_str().to_owned(),
digests: std::mem::take(&mut curr_digests),
acceptable_compressors: vec![compressor::Value::Identity as i32],
};
requests.push(read_blob_req);
}
let mut batched_blobs_response = HashMap::new();
for read_blob_req in requests {
let resp = cas_f(read_blob_req)
.await
.context("Failed to make BatchReadBlobs request")?;
for r in resp.responses.into_iter() {
let digest = tdigest_from(r.digest.context("Response digest not found.")?);
check_status(r.status.unwrap_or_default())?;
batched_blobs_response.insert(digest, r.data);
}
}
let get = |digest: &TDigest| -> anyhow::Result<Vec<u8>> {
if digest.size_in_bytes == 0 {
return Ok(Vec::new());
}
Ok(batched_blobs_response
.get(digest)
.with_context(|| format!("Did not receive digest data for `{}`", digest))?
.clone())
};
let mut inlined_blobs = vec![];
for digest in inlined_digests {
let data = if digest.size_in_bytes as usize >= max_msg_size {
let mut accum = vec![];
let mut responses = bystream_fut(digest.clone()).await?;
while let Some(resp) = responses.next().await {
let data = resp
.with_context(|| format!("Failed to fetch inline digest: {digest}"))?
.data;
accum.extend_from_slice(&data);
}
accum
} else {
get(&digest)?
};
inlined_blobs.push(InlinedDigestWithStatus {
digest,
status: tstatus_ok(),
blob: data,
})
}
let writes = file_digests.iter().map(|req| async {
let mut opts = OpenOptions::new();
opts.read(true).write(true).create_new(true);
#[cfg(unix)]
{
if req.is_executable {
opts.mode(0o755);
} else {