-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathsimple_scheduler_test.rs
More file actions
2628 lines (2404 loc) · 96 KB
/
simple_scheduler_test.rs
File metadata and controls
2628 lines (2404 loc) · 96 KB
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 2024 The NativeLink Authors. All rights reserved.
//
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// See LICENSE file for details
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::future::Future;
use core::ops::Bound;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use async_lock::Mutex;
use futures::task::Poll;
use futures::{Stream, StreamExt, poll};
use mock_instant::thread_local::{MockClock, SystemTime as MockSystemTime};
use nativelink_config::schedulers::{PropertyType, SimpleSpec};
use nativelink_error::{Code, Error, ResultExt, make_err};
use nativelink_macro::nativelink_test;
use nativelink_metric::MetricsComponent;
use nativelink_proto::build::bazel::remote::execution::v2::{
ExecuteRequest, Platform, digest_function,
};
use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{
ConnectionResult, StartExecute, UpdateForWorker, update_for_worker,
};
use nativelink_scheduler::awaited_action_db::{
AwaitedAction, AwaitedActionDb, AwaitedActionSubscriber, SortedAwaitedAction,
SortedAwaitedActionState,
};
use nativelink_scheduler::default_scheduler_factory::memory_awaited_action_db_factory;
use nativelink_scheduler::simple_scheduler::SimpleScheduler;
use nativelink_scheduler::worker::Worker;
use nativelink_scheduler::worker_scheduler::WorkerScheduler;
use nativelink_util::action_messages::{
ActionInfo, ActionResult, ActionStage, ActionState, DirectoryInfo, ExecutionMetadata, FileInfo,
INTERNAL_ERROR_EXIT_CODE, NameOrPath, OperationId, SymlinkInfo, WorkerId,
};
use nativelink_util::common::DigestInfo;
use nativelink_util::instant_wrapper::MockInstantWrapped;
use nativelink_util::operation_state_manager::{
ActionStateResult, ClientStateManager, OperationFilter, OperationStageFlags,
UpdateOperationType,
};
use nativelink_util::platform_properties::{PlatformProperties, PlatformPropertyValue};
use pretty_assertions::assert_eq;
use tokio::sync::{Notify, mpsc};
use utils::scheduler_utils::{INSTANCE_NAME, make_base_action_info, update_eq};
mod utils {
pub(crate) mod scheduler_utils;
}
async fn verify_initial_connection_message(
worker_id: WorkerId,
rx: &mut mpsc::UnboundedReceiver<UpdateForWorker>,
) {
// Worker should have been sent an execute command.
let expected_msg_for_worker = UpdateForWorker {
update: Some(update_for_worker::Update::ConnectionResult(
ConnectionResult {
worker_id: worker_id.into(),
},
)),
};
let msg_for_worker = rx.recv().await.unwrap();
assert_eq!(msg_for_worker, expected_msg_for_worker);
}
const NOW_TIME: u64 = 10000;
fn make_system_time(add_time: u64) -> SystemTime {
UNIX_EPOCH
.checked_add(Duration::from_secs(NOW_TIME + add_time))
.unwrap()
}
async fn setup_new_worker(
scheduler: &SimpleScheduler,
worker_id: WorkerId,
props: PlatformProperties,
) -> Result<mpsc::UnboundedReceiver<UpdateForWorker>, Error> {
let (tx, mut rx) = mpsc::unbounded_channel();
let worker = Worker::new(worker_id.clone(), props, tx, NOW_TIME, 0);
scheduler
.add_worker(worker)
.await
.err_tip(|| "Failed to add worker")?;
tokio::task::yield_now().await; // Allow task<->worker matcher to run.
verify_initial_connection_message(worker_id, &mut rx).await;
Ok(rx)
}
async fn setup_action(
scheduler: &SimpleScheduler,
action_digest: DigestInfo,
platform_properties: HashMap<String, String>,
insert_timestamp: SystemTime,
) -> Result<Box<dyn ActionStateResult>, Error> {
let mut action_info = make_base_action_info(insert_timestamp, action_digest);
Arc::make_mut(&mut action_info).platform_properties = platform_properties;
let client_id = OperationId::default();
let result = scheduler.add_action(client_id, action_info).await;
tokio::task::yield_now().await; // Allow task<->worker matcher to run.
result
}
const WORKER_TIMEOUT_S: u64 = 100;
#[nativelink_test]
async fn basic_add_action_with_one_worker_test() -> Result<(), Error> {
let worker_id = WorkerId("worker_id".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec::default(),
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let mut rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
let insert_timestamp = make_system_time(1);
let mut action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp)
.await
.unwrap();
{
// Worker should have been sent an execute command.
let expected_msg_for_worker = UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "Unknown Generated internally".to_string(),
queued_timestamp: Some(insert_timestamp.into()),
platform: Some(Platform::default()),
worker_id: worker_id.into(),
})),
};
let msg_for_worker = rx_from_worker.recv().await.unwrap();
// Operation ID is random so we ignore it.
assert!(update_eq(expected_msg_for_worker, msg_for_worker, true));
}
{
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Executing,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
Ok(())
}
#[nativelink_test]
async fn bad_worker_match_logging_interval() -> Result<(), Error> {
let task_change_notify = Arc::new(Notify::new());
let (_scheduler, _worker_scheduler) = SimpleScheduler::new(
&SimpleSpec {
worker_match_logging_interval_s: -2,
..Default::default()
},
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
task_change_notify,
None,
);
assert!(logs_contain(
"nativelink_scheduler::simple_scheduler: Valid values for worker_match_logging_interval_s are -1, 0, or a positive integer, setting to disabled worker_match_logging_interval_s=-2"
));
Ok(())
}
#[nativelink_test]
async fn client_does_not_receive_update_timeout() -> Result<(), Error> {
async fn advance_time<T>(duration: Duration, poll_fut: &mut Pin<&mut impl Future<Output = T>>) {
const STEP_AMOUNT: Duration = Duration::from_millis(100);
for _ in 0..(duration.as_millis() / STEP_AMOUNT.as_millis()) {
MockClock::advance(STEP_AMOUNT);
tokio::task::yield_now().await;
assert!(poll!(&mut *poll_fut).is_pending());
}
}
MockClock::set_time(Duration::from_secs(NOW_TIME));
let worker_id = WorkerId("worker_id".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec {
worker_timeout_s: WORKER_TIMEOUT_S,
worker_match_logging_interval_s: 1,
..Default::default()
},
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify.clone(),
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let _rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
let mut action_listener = setup_action(
&scheduler,
action_digest,
HashMap::new(),
make_system_time(1),
)
.await
.unwrap();
// Trigger a do_try_match to ensure we get a state change.
scheduler.do_try_match_for_test().await?;
assert_eq!(
action_listener.changed().await.unwrap().0.stage,
ActionStage::Executing
);
let changed_fut = action_listener.changed();
tokio::pin!(changed_fut);
{
// No update should have been received yet.
assert_eq!(poll!(&mut changed_fut).is_ready(), false);
}
// Advance our time by just under the timeout.
advance_time(Duration::from_secs(WORKER_TIMEOUT_S - 1), &mut changed_fut).await;
{
// Still no update should have been received yet.
assert_eq!(poll!(&mut changed_fut).is_ready(), false);
}
// Advance it by just over the timeout.
MockClock::advance(Duration::from_secs(2));
{
// Now we should have received a timeout and the action should have been
// put back in the queue.
assert_eq!(changed_fut.await.unwrap().0.stage, ActionStage::Queued);
}
Ok(())
}
#[nativelink_test]
async fn find_executing_action() -> Result<(), Error> {
let worker_id = WorkerId("worker_id".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec::default(),
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let mut rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
let insert_timestamp = make_system_time(1);
let action_listener = setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp)
.await
.unwrap();
let client_operation_id = action_listener
.as_state()
.await
.unwrap()
.0
.client_operation_id
.clone();
// Drop our receiver and look up a new one.
drop(action_listener);
let mut action_listener = scheduler
.filter_operations(OperationFilter {
client_operation_id: Some(client_operation_id.clone()),
..Default::default()
})
.await
.unwrap()
.next()
.await
.expect("Action not found");
{
// Worker should have been sent an execute command.
let expected_msg_for_worker = UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "Unknown Generated internally".to_string(),
queued_timestamp: Some(insert_timestamp.into()),
platform: Some(Platform::default()),
worker_id: worker_id.into(),
})),
};
let msg_for_worker = rx_from_worker.recv().await.unwrap();
// Operation ID is random so we ignore it.
assert!(update_eq(expected_msg_for_worker, msg_for_worker, true));
}
{
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Executing,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
Ok(())
}
#[nativelink_test]
async fn remove_worker_reschedules_multiple_running_job_test() -> Result<(), Error> {
let worker_id1 = WorkerId("worker1".to_string());
let worker_id2 = WorkerId("worker2".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec {
worker_timeout_s: WORKER_TIMEOUT_S,
..Default::default()
},
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest1 = DigestInfo::new([99u8; 32], 512);
let action_digest2 = DigestInfo::new([88u8; 32], 512);
let mut rx_from_worker1 = setup_new_worker(
&scheduler,
worker_id1.clone(),
PlatformProperties::default(),
)
.await?;
let insert_timestamp1 = make_system_time(1);
let mut client1_action_listener = setup_action(
&scheduler,
action_digest1,
HashMap::new(),
insert_timestamp1,
)
.await?;
let insert_timestamp2 = make_system_time(2);
let mut client2_action_listener = setup_action(
&scheduler,
action_digest2,
HashMap::new(),
insert_timestamp2,
)
.await?;
let mut expected_start_execute_for_worker1 = StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest1.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "WILL BE SET BELOW".to_string(),
queued_timestamp: Some(insert_timestamp1.into()),
platform: Some(Platform::default()),
worker_id: worker_id1.to_string(),
};
let mut expected_start_execute_for_worker2 = StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest2.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "WILL BE SET BELOW".to_string(),
queued_timestamp: Some(insert_timestamp2.into()),
platform: Some(Platform::default()),
worker_id: worker_id1.to_string(),
};
let operation_id1 = {
// Worker1 should now see first execution request.
let update_for_worker = rx_from_worker1
.recv()
.await
.expect("Worker terminated stream")
.update
.expect("`update` should be set on UpdateForWorker");
let (operation_id, rx_start_execute) = match update_for_worker {
update_for_worker::Update::StartAction(start_execute) => (
OperationId::from(start_execute.operation_id.as_str()),
start_execute,
),
v => panic!("Expected StartAction, got : {v:?}"),
};
expected_start_execute_for_worker1.operation_id = operation_id.to_string();
assert_eq!(expected_start_execute_for_worker1, rx_start_execute);
operation_id
};
let operation_id2 = {
// Worker1 should now see second execution request.
let update_for_worker = rx_from_worker1
.recv()
.await
.expect("Worker terminated stream")
.update
.expect("`update` should be set on UpdateForWorker");
let (operation_id, rx_start_execute) = match update_for_worker {
update_for_worker::Update::StartAction(start_execute) => (
OperationId::from(start_execute.operation_id.as_str()),
start_execute,
),
v => panic!("Expected StartAction, got : {v:?}"),
};
expected_start_execute_for_worker2.operation_id = operation_id.to_string();
assert_eq!(expected_start_execute_for_worker2, rx_start_execute);
operation_id
};
// Add a second worker that can take jobs if the first dies.
let mut rx_from_worker2 = setup_new_worker(
&scheduler,
worker_id2.clone(),
PlatformProperties::default(),
)
.await?;
{
let expected_action_stage = ActionStage::Executing;
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) =
client1_action_listener.changed().await.unwrap();
// We now know the name of the action so populate it.
assert_eq!(&action_state.stage, &expected_action_stage);
}
{
let expected_action_stage = ActionStage::Executing;
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) =
client2_action_listener.changed().await.unwrap();
// We now know the name of the action so populate it.
assert_eq!(&action_state.stage, &expected_action_stage);
}
// Now remove worker.
drop(scheduler.remove_worker(&worker_id1).await);
tokio::task::yield_now().await; // Allow task<->worker matcher to run.
{
// Worker1 should have received a disconnect message.
let msg_for_worker = rx_from_worker1.recv().await.unwrap();
assert_eq!(
msg_for_worker,
UpdateForWorker {
update: Some(update_for_worker::Update::Disconnect(()))
}
);
}
{
let expected_action_stage = ActionStage::Executing;
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) =
client1_action_listener.changed().await.unwrap();
// We now know the name of the action so populate it.
assert_eq!(&action_state.stage, &expected_action_stage);
}
{
let expected_action_stage = ActionStage::Executing;
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) =
client2_action_listener.changed().await.unwrap();
// We now know the name of the action so populate it.
assert_eq!(&action_state.stage, &expected_action_stage);
}
{
// Worker2 should now see execution request.
let msg_for_worker = rx_from_worker2.recv().await.unwrap();
expected_start_execute_for_worker1.operation_id = operation_id1.to_string();
expected_start_execute_for_worker1.worker_id = worker_id2.to_string();
assert_eq!(
msg_for_worker,
UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(
expected_start_execute_for_worker1
)),
}
);
}
{
// Worker2 should now see execution request.
let msg_for_worker = rx_from_worker2.recv().await.unwrap();
expected_start_execute_for_worker2.operation_id = operation_id2.to_string();
expected_start_execute_for_worker2.worker_id = worker_id2.to_string();
assert_eq!(
msg_for_worker,
UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(
expected_start_execute_for_worker2
)),
}
);
}
Ok(())
}
#[nativelink_test]
async fn set_drain_worker_pauses_and_resumes_worker_test() -> Result<(), Error> {
let worker_id = WorkerId("worker_id".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec::default(),
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let mut rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
let insert_timestamp = make_system_time(1);
let mut action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp).await?;
let _operation_id = {
// Other tests check full data. We only care if we got StartAction.
let operation_id = match rx_from_worker.recv().await.unwrap().update {
Some(update_for_worker::Update::StartAction(start_execute)) => {
OperationId::from(start_execute.operation_id)
}
v => panic!("Expected StartAction, got : {v:?}"),
};
// Other tests check full data. We only care if client thinks we are Executing.
assert_eq!(
action_listener.changed().await.unwrap().0.stage,
ActionStage::Executing
);
operation_id
};
// Set the worker draining.
scheduler.set_drain_worker(&worker_id, true).await?;
tokio::task::yield_now().await;
let action_digest = DigestInfo::new([88u8; 32], 512);
let insert_timestamp = make_system_time(14);
let mut action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp).await?;
{
// Client should get notification saying it's been queued.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Queued,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
// Set the worker not draining.
scheduler.set_drain_worker(&worker_id, false).await?;
tokio::task::yield_now().await;
{
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Executing,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
Ok(())
}
#[nativelink_test]
async fn worker_should_not_queue_if_properties_dont_match_test() -> Result<(), Error> {
let worker_id1 = WorkerId("worker1".to_string());
let worker_id2 = WorkerId("worker2".to_string());
let mut prop_defs = HashMap::new();
prop_defs.insert("prop".to_string(), PropertyType::Exact);
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec {
supported_platform_properties: Some(prop_defs),
..Default::default()
},
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let mut platform_properties = HashMap::new();
platform_properties.insert("prop".to_string(), "1".to_string());
let mut worker1_properties = PlatformProperties::default();
worker1_properties.properties.insert(
"prop".to_string(),
PlatformPropertyValue::Exact("2".to_string()),
);
let mut rx_from_worker1 =
setup_new_worker(&scheduler, worker_id1, worker1_properties.clone()).await?;
let insert_timestamp = make_system_time(1);
let mut action_listener = setup_action(
&scheduler,
action_digest,
platform_properties,
insert_timestamp,
)
.await?;
{
// Client should get notification saying it's been queued.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Queued,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
let mut worker2_properties = PlatformProperties::default();
worker2_properties.properties.insert(
"prop".to_string(),
PlatformPropertyValue::Exact("1".to_string()),
);
let mut rx_from_worker2 =
setup_new_worker(&scheduler, worker_id2.clone(), worker2_properties.clone()).await?;
{
// Worker should have been sent an execute command.
let expected_msg_for_worker = UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "Unknown Generated internally".to_string(),
queued_timestamp: Some(insert_timestamp.into()),
platform: Some((&worker2_properties).into()),
worker_id: worker_id2.to_string(),
})),
};
let msg_for_worker = rx_from_worker2.recv().await.unwrap();
assert!(update_eq(expected_msg_for_worker, msg_for_worker, true));
}
{
// Client should get notification saying it's being executed.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Executing,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
// Our first worker should have no updates over this test.
assert_eq!(
rx_from_worker1.try_recv(),
Err(mpsc::error::TryRecvError::Empty)
);
Ok(())
}
#[nativelink_test]
async fn cacheable_items_join_same_action_queued_test() -> Result<(), Error> {
let worker_id = WorkerId("worker_id".to_string());
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec::default(),
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let action_digest = DigestInfo::new([99u8; 32], 512);
let client_operation_id = OperationId::default();
let mut expected_action_state = ActionState {
client_operation_id,
stage: ActionStage::Queued,
action_digest,
last_transition_timestamp: SystemTime::now(),
};
let insert_timestamp1 = make_system_time(1);
let insert_timestamp2 = make_system_time(2);
let mut client1_action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp1).await?;
let mut client2_action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp2).await?;
let (operation_id1, operation_id2) = {
// Clients should get notification saying it's been queued.
let (action_state1, _maybe_origin_metadata) =
client1_action_listener.changed().await.unwrap();
let (action_state2, _maybe_origin_metadata) =
client2_action_listener.changed().await.unwrap();
let operation_id1 = action_state1.client_operation_id.clone();
let operation_id2 = action_state2.client_operation_id.clone();
// Name is random so we set force it to be the same.
expected_action_state.client_operation_id = operation_id1.clone();
assert_eq!(action_state1.as_ref(), &expected_action_state);
expected_action_state.client_operation_id = operation_id2.clone();
assert_eq!(action_state2.as_ref(), &expected_action_state);
// Both clients should have unique operation ID.
assert_ne!(
action_state2.client_operation_id,
action_state1.client_operation_id
);
(operation_id1, operation_id2)
};
let mut rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
{
// Worker should have been sent an execute command.
let expected_msg_for_worker = UpdateForWorker {
update: Some(update_for_worker::Update::StartAction(StartExecute {
execute_request: Some(ExecuteRequest {
instance_name: INSTANCE_NAME.to_string(),
action_digest: Some(action_digest.into()),
digest_function: digest_function::Value::Sha256.into(),
..Default::default()
}),
operation_id: "Unknown Generated internally".to_string(),
queued_timestamp: Some(insert_timestamp1.into()),
platform: Some(Platform::default()),
worker_id: worker_id.into(),
})),
};
let msg_for_worker = rx_from_worker.recv().await.unwrap();
// Operation ID is random so we ignore it.
assert!(update_eq(expected_msg_for_worker, msg_for_worker, true));
}
// Action should now be executing.
expected_action_state.stage = ActionStage::Executing;
expected_action_state.last_transition_timestamp = SystemTime::now();
{
// Both client1 and client2 should be receiving the same updates.
// Most importantly the `name` (which is random) will be the same.
expected_action_state.client_operation_id = operation_id1.clone();
assert_eq!(
client1_action_listener.changed().await.unwrap().0.as_ref(),
&expected_action_state
);
expected_action_state.client_operation_id = operation_id2.clone();
assert_eq!(
client2_action_listener.changed().await.unwrap().0.as_ref(),
&expected_action_state
);
}
{
// Now if another action is requested it should also join with executing action.
let insert_timestamp3 = make_system_time(2);
let mut client3_action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp3).await?;
let (action_state, _maybe_origin_metadata) =
client3_action_listener.changed().await.unwrap();
expected_action_state.client_operation_id = action_state.client_operation_id.clone();
assert_eq!(action_state.as_ref(), &expected_action_state);
}
Ok(())
}
#[nativelink_test]
async fn worker_disconnects_does_not_schedule_for_execution_test() -> Result<(), Error> {
let task_change_notify = Arc::new(Notify::new());
let (scheduler, _worker_scheduler) = SimpleScheduler::new_with_callback(
&SimpleSpec::default(),
memory_awaited_action_db_factory(
0,
&task_change_notify.clone(),
MockInstantWrapped::default,
),
|| async move {},
task_change_notify,
MockInstantWrapped::default,
None,
);
let worker_id = WorkerId("worker_id".to_string());
let action_digest = DigestInfo::new([99u8; 32], 512);
let rx_from_worker =
setup_new_worker(&scheduler, worker_id.clone(), PlatformProperties::default()).await?;
// Now act like the worker disconnected.
drop(rx_from_worker);
let insert_timestamp = make_system_time(1);
let mut action_listener =
setup_action(&scheduler, action_digest, HashMap::new(), insert_timestamp).await?;
{
// Client should get notification saying it's being queued not executed.
let (action_state, _maybe_origin_metadata) = action_listener.changed().await.unwrap();
let expected_action_state = ActionState {
// Name is a random string, so we ignore it and just make it the same.
client_operation_id: action_state.client_operation_id.clone(),
stage: ActionStage::Queued,
action_digest: action_state.action_digest,
last_transition_timestamp: SystemTime::now(),
};
assert_eq!(action_state.as_ref(), &expected_action_state);
}
Ok(())
}
// TODO(palfrey) These should be gneralized and expanded for more tests.
struct MockAwaitedActionSubscriber {}
impl AwaitedActionSubscriber for MockAwaitedActionSubscriber {
async fn changed(&mut self) -> Result<AwaitedAction, Error> {
unreachable!();
}
async fn borrow(&self) -> Result<AwaitedAction, Error> {
Ok(AwaitedAction::new(
OperationId::default(),
make_base_action_info(SystemTime::UNIX_EPOCH, DigestInfo::zero_digest()),
MockSystemTime::now().into(),
))
}
}
struct TxMockSenders {
get_awaited_action_by_id:
mpsc::UnboundedSender<Result<Option<MockAwaitedActionSubscriber>, Error>>,
get_by_operation_id: mpsc::UnboundedSender<Result<Option<MockAwaitedActionSubscriber>, Error>>,
get_range_of_actions: mpsc::UnboundedSender<Vec<Result<MockAwaitedActionSubscriber, Error>>>,
update_awaited_action: mpsc::UnboundedSender<Result<(), Error>>,
}
#[derive(MetricsComponent)]
struct RxMockAwaitedAction {
get_awaited_action_by_id:
Mutex<mpsc::UnboundedReceiver<Result<Option<MockAwaitedActionSubscriber>, Error>>>,
get_by_operation_id:
Mutex<mpsc::UnboundedReceiver<Result<Option<MockAwaitedActionSubscriber>, Error>>>,
get_range_of_actions:
Mutex<mpsc::UnboundedReceiver<Vec<Result<MockAwaitedActionSubscriber, Error>>>>,
update_awaited_action: Mutex<mpsc::UnboundedReceiver<Result<(), Error>>>,
}
impl RxMockAwaitedAction {
fn new() -> (TxMockSenders, Self) {
let (tx_get_awaited_action_by_id, rx_get_awaited_action_by_id) = mpsc::unbounded_channel();
let (tx_get_by_operation_id, rx_get_by_operation_id) = mpsc::unbounded_channel();
let (tx_get_range_of_actions, rx_get_range_of_actions) = mpsc::unbounded_channel();
let (tx_update_awaited_action, rx_update_awaited_action) = mpsc::unbounded_channel();
(
TxMockSenders {
get_awaited_action_by_id: tx_get_awaited_action_by_id,
get_by_operation_id: tx_get_by_operation_id,
get_range_of_actions: tx_get_range_of_actions,
update_awaited_action: tx_update_awaited_action,
},
Self {
get_awaited_action_by_id: Mutex::new(rx_get_awaited_action_by_id),
get_by_operation_id: Mutex::new(rx_get_by_operation_id),
get_range_of_actions: Mutex::new(rx_get_range_of_actions),
update_awaited_action: Mutex::new(rx_update_awaited_action),
},
)
}
}
impl AwaitedActionDb for RxMockAwaitedAction {
type Subscriber = MockAwaitedActionSubscriber;
async fn get_awaited_action_by_id(
&self,
_client_operation_id: &OperationId,
) -> Result<Option<Self::Subscriber>, Error> {
let mut rx_get_awaited_action_by_id = self.get_awaited_action_by_id.lock().await;
rx_get_awaited_action_by_id
.try_recv()
.expect("Could not receive msg in mpsc")
}
async fn get_all_awaited_actions(
&self,
) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>> + Send, Error> {
Ok(futures::stream::empty())
}
async fn get_by_operation_id(
&self,
_operation_id: &OperationId,
) -> Result<Option<Self::Subscriber>, Error> {
let mut rx_get_by_operation_id = self.get_by_operation_id.lock().await;
rx_get_by_operation_id
.try_recv()
.expect("Could not receive msg in mpsc")
}
async fn get_range_of_actions(
&self,
_state: SortedAwaitedActionState,
_start: Bound<SortedAwaitedAction>,
_end: Bound<SortedAwaitedAction>,
_desc: bool,
) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>> + Send, Error> {
let mut rx_get_range_of_actions = self.get_range_of_actions.lock().await;
let items = rx_get_range_of_actions
.try_recv()
.expect("Could not receive msg in mpsc");
Ok(futures::stream::iter(items))
}