-
-
Notifications
You must be signed in to change notification settings - Fork 606
/
execution_server.rs
526 lines (473 loc) · 15.7 KB
/
execution_server.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
// Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::any::type_name;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::iter::FromIterator;
use std::net::SocketAddr;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use futures::{FutureExt, Stream};
use grpc_util::hyper::AddrIncomingWithStream;
use hashing::Digest;
use parking_lot::Mutex;
use protos::gen::build::bazel::remote::execution::v2 as remexec;
use protos::gen::build::bazel::semver::SemVer;
use protos::gen::google::longrunning::{
operations_server::Operations, operations_server::OperationsServer, CancelOperationRequest,
DeleteOperationRequest, GetOperationRequest, ListOperationsRequest, ListOperationsResponse,
Operation,
};
use protos::require_digest;
use remexec::{
action_cache_server::ActionCache, action_cache_server::ActionCacheServer,
capabilities_server::Capabilities, capabilities_server::CapabilitiesServer,
execution_server::Execution, execution_server::ExecutionServer, ActionResult, CacheCapabilities,
ExecuteRequest, ExecutionCapabilities, GetActionResultRequest, GetCapabilitiesRequest,
ServerCapabilities, UpdateActionResultRequest, WaitExecutionRequest,
};
use tonic::metadata::MetadataMap;
use tonic::transport::Server;
use tonic::{Request, Response, Status};
///
/// Represents an expected API call from the REv2 client. The data carried by each enum
/// variant are the parameters to verify and the results to return to the client.
///
#[derive(Debug)]
#[allow(clippy::large_enum_variant)] // GetActionResult variant is larger than others
pub enum ExpectedAPICall {
Execute {
execute_request: ExecuteRequest,
stream_responses: Result<Vec<MockOperation>, Status>,
},
WaitExecution {
operation_name: String,
stream_responses: Result<Vec<MockOperation>, Status>,
},
GetOperation {
operation_name: String,
operation: MockOperation,
},
GetActionResult {
action_digest: Digest,
response: Result<ActionResult, Status>,
},
}
///
/// A MockOperation to be used with MockExecution.
///
/// If the op is None, the MockExecution will drop the channel, triggering cancelation on the
/// client. If the duration is not None, it represents a delay before either responding or
/// canceling for the operation.
///
#[derive(Debug)]
pub struct MockOperation {
pub op: Result<Option<Operation>, Status>,
pub duration: Option<Duration>,
}
impl MockOperation {
pub fn new(op: Operation) -> MockOperation {
MockOperation {
op: Ok(Some(op)),
duration: None,
}
}
}
#[derive(Clone, Debug)]
pub struct MockExecution {
expected_api_calls: Arc<Mutex<VecDeque<ExpectedAPICall>>>,
}
impl MockExecution {
///
/// # Arguments:
/// * `name` - The name of the operation. It is assumed that all operation_responses use this
/// name.
/// * `expected_api_calls` - Vec of ExpectedAPICall instances representing the API calls
/// to expect from the client. Will be returned in order.
///
pub fn new(expected_api_calls: Vec<ExpectedAPICall>) -> MockExecution {
MockExecution {
expected_api_calls: Arc::new(Mutex::new(VecDeque::from(expected_api_calls))),
}
}
}
///
/// A server which will answer Execute/WaitExecution and GetOperation/CancelOperation gRPC
/// requests with pre-canned responses.
///
pub struct TestServer {
pub mock_responder: MockResponder,
local_addr: SocketAddr,
shutdown_sender: Option<tokio::sync::oneshot::Sender<()>>,
}
impl TestServer {
///
/// # Arguments
/// * `mock_execution` - The canned responses to issue. Returns the MockExecution's
/// operation_responses in order to any ExecuteRequest or GetOperation
/// requests.
/// If an ExecuteRequest request is received which is not equal to this
/// MockExecution's execute_request, an error will be returned.
/// If a GetOperation request is received whose name is not equal to this
/// MockExecution's name, or more requests are received than stub responses
/// are available for, an error will be returned.
pub fn new(mock_execution: MockExecution, port: Option<u16>) -> TestServer {
let mock_responder = MockResponder::new(mock_execution);
let mock_responder2 = mock_responder.clone();
let addr = format!("127.0.0.1:{}", port.unwrap_or(0))
.parse()
.expect("failed to parse IP address");
let incoming = hyper::server::conn::AddrIncoming::bind(&addr).expect("failed to bind port");
let local_addr = incoming.local_addr();
let incoming = AddrIncomingWithStream(incoming);
let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
let mut server = Server::builder();
let router = server
.add_service(ExecutionServer::new(mock_responder2.clone()))
.add_service(OperationsServer::new(mock_responder2.clone()))
.add_service(CapabilitiesServer::new(mock_responder2.clone()))
.add_service(ActionCacheServer::new(mock_responder2));
router
.serve_with_incoming_shutdown(incoming, shutdown_receiver.map(drop))
.await
.unwrap();
});
TestServer {
mock_responder,
local_addr,
shutdown_sender: Some(shutdown_sender),
}
}
///
/// The address on which this server is listening over insecure HTTP transport.
///
pub fn address(&self) -> String {
format!("http://{}", self.local_addr)
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.shutdown_sender.take().unwrap().send(()).unwrap();
let remaining_expected_responses = self
.mock_responder
.mock_execution
.expected_api_calls
.lock()
.len();
if remaining_expected_responses != 0 {
let message = format!(
"Expected {} more requests. Remaining expected responses:\n{}\nReceived requests:\n{}",
remaining_expected_responses,
MockResponder::display_all(&Vec::from_iter(
self
.mock_responder
.mock_execution
.expected_api_calls
.lock()
.deref(),
)),
MockResponder::display_all(&self.mock_responder.received_messages.deref().lock())
);
if std::thread::panicking() {
eprintln!(
"TestServer missing requests, but not panicking because caller is already panicking: {}",
message
);
} else {
assert_eq!(remaining_expected_responses, 0, "{}", message,);
}
}
}
}
#[derive(Debug)]
pub struct ReceivedMessage {
pub message_type: String,
pub message: Box<dyn prost::Message>,
pub received_at: Instant,
pub headers: MetadataMap,
}
#[derive(Clone, Debug)]
pub struct MockResponder {
mock_execution: MockExecution,
pub received_messages: Arc<Mutex<Vec<ReceivedMessage>>>,
pub cancelation_requests: Arc<Mutex<Vec<CancelOperationRequest>>>,
}
impl MockResponder {
fn new(mock_execution: MockExecution) -> MockResponder {
MockResponder {
mock_execution,
received_messages: Arc::new(Mutex::new(vec![])),
cancelation_requests: Arc::new(Mutex::new(vec![])),
}
}
fn log<T: prost::Message + Clone + Sized + 'static>(&self, request: &Request<T>) {
let headers = request.metadata().clone();
let message = request.get_ref().clone();
self.received_messages.lock().push(ReceivedMessage {
message_type: type_name::<T>().to_string(),
message: Box::new(message),
received_at: Instant::now(),
headers,
});
}
fn display_all<D: Debug>(items: &[D]) -> String {
items
.iter()
.map(|i| format!("{:?}\n", i))
.collect::<Vec<_>>()
.concat()
}
fn stream_from_mock_operations(
operations: Vec<MockOperation>,
) -> Pin<Box<dyn Stream<Item = Result<Operation, Status>> + Send + Sync>> {
let stream = async_stream::stream! {
for op in operations {
if let Some(d) = op.duration {
tokio::time::sleep(d).await;
}
if let Ok(Some(op)) = op.op {
yield Ok(op);
} else if let Err(status) = op.op {
yield Err(status);
break;
}
}
};
Box::pin(stream)
}
}
#[tonic::async_trait]
impl Execution for MockResponder {
type ExecuteStream = Pin<Box<dyn Stream<Item = Result<Operation, Status>> + Send + Sync>>;
async fn execute(
&self,
request: Request<ExecuteRequest>,
) -> Result<Response<Self::ExecuteStream>, Status> {
self.log(&request);
let request = request.into_inner();
let expected_api_call = self.mock_execution.expected_api_calls.lock().pop_front();
match expected_api_call {
Some(ExpectedAPICall::Execute {
execute_request,
stream_responses,
}) => {
if request == execute_request {
match stream_responses {
Ok(operations) => {
return Ok(Response::new(Self::stream_from_mock_operations(operations)));
}
Err(rpc_status) => Err(rpc_status),
}
} else {
return Err(Status::invalid_argument(format!(
"Did not expect this request. Expected: {:?}, Got: {:?}",
execute_request, request
)));
}
}
Some(api_call) => {
return Err(Status::invalid_argument(format!(
"Execute endpoint called. Expected: {:?}",
api_call
)));
}
None => Err(Status::invalid_argument(
"Execute endpoint called. Did not expect this call.".to_owned(),
)),
}
}
type WaitExecutionStream = Pin<Box<dyn Stream<Item = Result<Operation, Status>> + Send + Sync>>;
async fn wait_execution(
&self,
request: Request<WaitExecutionRequest>,
) -> Result<Response<Self::WaitExecutionStream>, Status> {
self.log(&request);
let request = request.into_inner();
let expected_api_call = self.mock_execution.expected_api_calls.lock().pop_front();
match expected_api_call {
Some(ExpectedAPICall::WaitExecution {
operation_name,
stream_responses,
}) => {
if request.name == operation_name {
match stream_responses {
Ok(operations) => {
return Ok(Response::new(Self::stream_from_mock_operations(operations)));
}
Err(rpc_status) => Err(rpc_status),
}
} else {
return Err(Status::invalid_argument(format!(
"Did not expect WaitExecution for this operation. Expected: {:?}, Got: {:?}",
operation_name, request.name
)));
}
}
Some(api_call) => {
return Err(Status::invalid_argument(format!(
"WaitExecution endpoint called. Expected: {:?}",
api_call,
)));
}
None => Err(Status::invalid_argument(
"WaitExecution endpoint called. Did not expect this call.".to_owned(),
)),
}
}
}
#[tonic::async_trait]
impl Operations for MockResponder {
async fn list_operations(
&self,
_: Request<ListOperationsRequest>,
) -> Result<Response<ListOperationsResponse>, Status> {
Err(Status::unimplemented("".to_owned()))
}
async fn get_operation(
&self,
request: Request<GetOperationRequest>,
) -> Result<Response<Operation>, Status> {
self.log(&request);
let request = request.into_inner();
let expected_api_call = self.mock_execution.expected_api_calls.lock().pop_front();
match expected_api_call {
Some(ExpectedAPICall::GetOperation {
operation_name,
operation,
}) => {
if request.name == operation_name {
if let Some(d) = operation.duration {
tokio::time::sleep(d).await;
}
if let Ok(Some(op)) = operation.op {
// Complete the channel with the op.
Ok(Response::new(op))
} else if let Err(status) = operation.op {
Err(status)
} else {
Err(Status::internal(
"Test setup did not specify an error or operation".to_owned(),
))
}
} else {
Err(Status::invalid_argument(format!(
"Did not expect GetOperation for this operation. Expected: {:?}, Got: {:?}",
operation_name, request.name
)))
}
}
Some(api_call) => Err(Status::invalid_argument(format!(
"GetOperation endpoint called. Expected: {:?}",
api_call,
))),
None => Err(Status::invalid_argument(
"GetOperation endpoint called. Did not expect this call.".to_owned(),
)),
}
}
async fn delete_operation(
&self,
_: Request<DeleteOperationRequest>,
) -> Result<Response<()>, Status> {
Err(Status::unimplemented("".to_owned()))
}
async fn cancel_operation(
&self,
request: Request<CancelOperationRequest>,
) -> Result<Response<()>, Status> {
self.log(&request);
let request = request.into_inner();
self.cancelation_requests.lock().push(request);
Ok(Response::new(()))
}
}
#[tonic::async_trait]
impl ActionCache for MockResponder {
async fn get_action_result(
&self,
request: Request<GetActionResultRequest>,
) -> Result<Response<ActionResult>, Status> {
self.log(&request);
let request = request.into_inner();
let expected_api_call = self.mock_execution.expected_api_calls.lock().pop_front();
match expected_api_call {
Some(ExpectedAPICall::GetActionResult {
action_digest,
response,
}) => {
let action_digest_from_request: Digest =
match require_digest(request.action_digest.as_ref()) {
Ok(d) => d,
Err(e) => {
return Err(Status::invalid_argument(format!(
"GetActionResult endpoint called with bad digest: {:?}",
e,
)));
}
};
if action_digest_from_request == action_digest {
match response {
Ok(action_result) => Ok(Response::new(action_result)),
Err(status) => Err(status),
}
} else {
Err(Status::invalid_argument(format!(
"Did not expect request with this action digest. Expected: {:?}, Got: {:?}",
action_digest, request.action_digest
)))
}
}
Some(api_call) => Err(Status::invalid_argument(format!(
"GetActionResult endpoint called. Expected: {:?}",
api_call,
))),
None => Err(Status::invalid_argument(
"GetActionResult endpoint called. Did not expect this call.".to_owned(),
)),
}
}
async fn update_action_result(
&self,
_: Request<UpdateActionResultRequest>,
) -> Result<Response<ActionResult>, Status> {
Err(Status::unimplemented("".to_owned()))
}
}
#[tonic::async_trait]
impl Capabilities for MockResponder {
async fn get_capabilities(
&self,
_: Request<GetCapabilitiesRequest>,
) -> Result<Response<ServerCapabilities>, Status> {
let response = ServerCapabilities {
cache_capabilities: Some(CacheCapabilities {
digest_function: vec![remexec::digest_function::Value::Sha256 as i32],
max_batch_total_size_bytes: 0,
..CacheCapabilities::default()
}),
execution_capabilities: Some(ExecutionCapabilities {
digest_function: remexec::digest_function::Value::Sha256 as i32,
exec_enabled: true,
..ExecutionCapabilities::default()
}),
low_api_version: Some(SemVer {
major: 2,
minor: 0,
patch: 0,
..SemVer::default()
}),
high_api_version: Some(SemVer {
major: 2,
minor: 0,
patch: 0,
..SemVer::default()
}),
..ServerCapabilities::default()
};
Ok(Response::new(response))
}
}