-
Notifications
You must be signed in to change notification settings - Fork 296
/
receiver.rs
1890 lines (1788 loc) · 72 KB
/
receiver.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 crate::{
metrics::{
ConsensusManagerMetrics, DOWNLOAD_TASK_RESULT_ALL_PEERS_DELETED,
DOWNLOAD_TASK_RESULT_COMPLETED, DOWNLOAD_TASK_RESULT_DROP,
},
uri_prefix, AdvertUpdate, CommitId, SlotNumber, Update,
};
use axum::{
extract::State,
http::{Request, StatusCode},
routing::any,
Extension, Router,
};
use backoff::{backoff::Backoff, ExponentialBackoffBuilder};
use bytes::Bytes;
use crossbeam_channel::Sender as CrossbeamSender;
use ic_interfaces::p2p::consensus::{PriorityFnAndFilterProducer, ValidatedPoolReader};
use ic_logger::{error, warn, ReplicaLogger};
use ic_protobuf::{p2p::v1 as pb, proxy::ProtoProxy};
use ic_quic_transport::{ConnId, SubnetTopology, Transport};
use ic_types::artifact::{ArtifactKind, Priority, PriorityFn, UnvalidatedArtifactMutation};
use ic_types::NodeId;
use rand::{rngs::SmallRng, seq::IteratorRandom, SeedableRng};
use std::{
collections::{hash_map::Entry, HashMap, HashSet},
sync::{Arc, RwLock},
time::Duration,
};
use tokio::{
runtime::Handle,
select,
sync::{
mpsc::{Receiver, Sender},
watch,
},
task::JoinSet,
time::{self, sleep_until, timeout_at, Instant, MissedTickBehavior},
};
const MIN_ARTIFACT_RPC_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_ARTIFACT_RPC_TIMEOUT: Duration = Duration::from_secs(120);
const PRIORITY_FUNCTION_UPDATE_INTERVAL: Duration = Duration::from_secs(3);
type ValidatedPoolReaderRef<T> = Arc<RwLock<dyn ValidatedPoolReader<T> + Send + Sync>>;
type ReceivedAdvertSender<A> = Sender<(AdvertUpdate<A>, NodeId, ConnId)>;
#[allow(unused)]
pub fn build_axum_router<Artifact: ArtifactKind>(
log: ReplicaLogger,
pool: ValidatedPoolReaderRef<Artifact>,
) -> (Router, Receiver<(AdvertUpdate<Artifact>, NodeId, ConnId)>) {
let (update_tx, update_rx) = tokio::sync::mpsc::channel(100);
let router = Router::new()
.route(
&format!("/{}/rpc", uri_prefix::<Artifact>()),
any(rpc_handler),
)
.with_state(pool)
.route(
&format!("/{}/update", uri_prefix::<Artifact>()),
any(update_handler),
)
.with_state((log, update_tx));
(router, update_rx)
}
async fn rpc_handler<Artifact: ArtifactKind>(
State(pool): State<ValidatedPoolReaderRef<Artifact>>,
payload: Bytes,
) -> Result<Bytes, StatusCode> {
let jh = tokio::task::spawn_blocking(move || {
let id: Artifact::Id =
Artifact::PbId::proxy_decode(&payload).map_err(|_| StatusCode::BAD_REQUEST)?;
let artifact = pool
.read()
.unwrap()
.get_validated_by_identifier(&id)
.ok_or(StatusCode::NO_CONTENT)?;
Ok::<_, StatusCode>(Bytes::from(Artifact::PbMessage::proxy_encode(artifact)))
});
let bytes = jh.await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??;
Ok(bytes)
}
async fn update_handler<Artifact: ArtifactKind>(
State((log, sender)): State<(ReplicaLogger, ReceivedAdvertSender<Artifact>)>,
Extension(peer): Extension<NodeId>,
Extension(conn_id): Extension<ConnId>,
payload: Bytes,
) -> Result<(), StatusCode> {
let update: AdvertUpdate<Artifact> =
pb::AdvertUpdate::proxy_decode(&payload).map_err(|_| StatusCode::BAD_REQUEST)?;
if sender.send((update, peer, conn_id)).await.is_err() {
error!(
log,
"Failed to send advert update from handler to event loop"
)
}
Ok(())
}
#[derive(Debug)]
pub struct PeerCounter(HashMap<NodeId, u32>);
impl PeerCounter {
pub fn new() -> Self {
Self(HashMap::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn peers(&self) -> impl Iterator<Item = &NodeId> {
self.0.keys()
}
/// Returns true if value is newly inserted
pub fn insert(&mut self, node: NodeId) -> bool {
match self.0.entry(node) {
Entry::Occupied(mut entry) => {
*entry.get_mut() += 1;
false
}
Entry::Vacant(entry) => {
entry.insert(1);
true
}
}
}
/// Returns true if removed key was present and counter got to zero
pub fn remove(&mut self, node: NodeId) -> bool {
match self.0.entry(node) {
Entry::Occupied(mut entry) => {
assert!(*entry.get() != 0);
if *entry.get() == 1 {
entry.remove();
true
} else {
*entry.get_mut() -= 1;
false
}
}
Entry::Vacant(_) => false,
}
}
}
#[allow(unused)]
pub(crate) struct ConsensusManagerReceiver<Artifact: ArtifactKind, Pool, ReceivedAdvert> {
log: ReplicaLogger,
metrics: ConsensusManagerMetrics,
rt_handle: Handle,
transport: Arc<dyn Transport>,
// Receive side:
adverts_received: Receiver<ReceivedAdvert>,
pool_reader: Arc<RwLock<dyn ValidatedPoolReader<Artifact> + Send + Sync>>,
raw_pool: Arc<RwLock<Pool>>,
priority_fn_producer: Arc<dyn PriorityFnAndFilterProducer<Artifact, Pool>>,
current_priority_fn: watch::Sender<PriorityFn<Artifact::Id, Artifact::Attribute>>,
sender: CrossbeamSender<UnvalidatedArtifactMutation<Artifact>>,
slot_table: HashMap<NodeId, HashMap<SlotNumber, SlotEntry<Artifact::Id>>>,
active_downloads: HashMap<Artifact::Id, watch::Sender<PeerCounter>>,
#[allow(clippy::type_complexity)]
artifact_processor_tasks: JoinSet<(
watch::Receiver<PeerCounter>,
Artifact::Id,
Artifact::Attribute,
)>,
topology_watcher: watch::Receiver<SubnetTopology>,
}
#[allow(unused)]
impl<Artifact, Pool>
ConsensusManagerReceiver<Artifact, Pool, (AdvertUpdate<Artifact>, NodeId, ConnId)>
where
Pool: 'static + Send + Sync + ValidatedPoolReader<Artifact>,
Artifact: ArtifactKind,
{
pub(crate) fn run(
log: ReplicaLogger,
metrics: ConsensusManagerMetrics,
rt_handle: Handle,
adverts_received: Receiver<(AdvertUpdate<Artifact>, NodeId, ConnId)>,
raw_pool: Arc<RwLock<Pool>>,
priority_fn_producer: Arc<dyn PriorityFnAndFilterProducer<Artifact, Pool>>,
sender: CrossbeamSender<UnvalidatedArtifactMutation<Artifact>>,
transport: Arc<dyn Transport>,
topology_watcher: watch::Receiver<SubnetTopology>,
) {
let priority_fn = priority_fn_producer.get_priority_function(&raw_pool.read().unwrap());
let (current_priority_fn, _) = watch::channel(priority_fn);
let receive_manager = Self {
log,
metrics,
rt_handle: rt_handle.clone(),
adverts_received,
pool_reader: raw_pool.clone() as Arc<_>,
raw_pool,
priority_fn_producer,
current_priority_fn,
sender,
transport,
active_downloads: HashMap::new(),
slot_table: HashMap::new(),
artifact_processor_tasks: JoinSet::new(),
topology_watcher,
};
rt_handle.spawn(receive_manager.start_event_loop());
}
/// Event loop that processes advert updates and artifact downloads.
/// The event loop preserves the invariants checked with `debug_assert`.
async fn start_event_loop(mut self) {
let mut priority_fn_interval = time::interval(PRIORITY_FUNCTION_UPDATE_INTERVAL);
priority_fn_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
select! {
_ = priority_fn_interval.tick() => {
self.handle_pfn_timer_tick();
}
Some((advert_update, peer_id, conn_id)) = self.adverts_received.recv() => {
self.handle_advert_receive(advert_update, peer_id, conn_id);
}
Some(result) = self.artifact_processor_tasks.join_next() => {
match result {
Ok((receiver, id, attr)) => {
self.handle_artifact_processor_joined(receiver, id, attr);
}
Err(err) => {
// If the task panics we propagate the panic. But we allow tasks to be canceled.
// Task can be cancelled if someone calls .abort()
if err.is_panic() {
std::panic::resume_unwind(err.into_panic());
}
}
}
}
Ok(()) = self.topology_watcher.changed() => {
self.handle_topology_update();
}
}
debug_assert_eq!(
self.active_downloads.len(),
self.artifact_processor_tasks.len(),
"Number of artifact processing tasks differs from the available number of channels that communicate with the processing tasks"
);
debug_assert!(
self.artifact_processor_tasks.len()
>= HashSet::<Artifact::Id>::from_iter(
self.slot_table
.iter()
.flat_map(|(k, v)| v.iter())
.map(|(_, s)| s.id.clone())
)
.len(),
"Number of download tasks should always be the same or exceed the number of distinct ids stored."
);
debug_assert!(
self.active_downloads
.iter()
.all(|(k, v)| { v.receiver_count() == 1 }),
"Some download task has two node receivers or it was dropped."
);
}
}
pub(crate) fn handle_pfn_timer_tick(&mut self) {
let pool = &self.raw_pool.read().unwrap();
let priority_fn = self.priority_fn_producer.get_priority_function(pool);
self.current_priority_fn.send_replace(priority_fn);
}
pub(crate) fn handle_artifact_processor_joined(
&mut self,
peer_rx: watch::Receiver<PeerCounter>,
id: Artifact::Id,
attr: Artifact::Attribute,
) {
self.metrics.download_task_finished_total.inc();
// Invariant: Peer sender should only be dropped in this task..
debug_assert!(peer_rx.has_changed().is_ok());
// peer advertised after task finished.
if !peer_rx.borrow().is_empty() {
self.metrics.download_task_restart_after_join_total.inc();
self.metrics.download_task_started_total.inc();
self.artifact_processor_tasks.spawn_on(
Self::process_advert(
self.log.clone(),
id,
attr,
None,
peer_rx,
self.current_priority_fn.subscribe(),
self.sender.clone(),
self.transport.clone(),
self.metrics.clone(),
),
&self.rt_handle,
);
} else {
self.active_downloads.remove(&id);
}
debug_assert!(
self.slot_table
.iter()
.flat_map(|(k, v)| v.iter())
.all(|(k, v)| self.active_downloads.contains_key(&v.id)),
"Every entry in the slot table should have an active download task."
);
}
pub(crate) fn handle_advert_receive(
&mut self,
advert_update: AdvertUpdate<Artifact>,
peer_id: NodeId,
connection_id: ConnId,
) {
self.metrics.slot_table_updates_total.inc();
let AdvertUpdate {
slot_number,
commit_id,
update,
} = advert_update;
let (id, attribute, artifact) = match update {
Update::Artifact(artifact) => {
let advert = Artifact::message_to_advert(&artifact);
(advert.id, advert.attribute, Some(artifact))
}
Update::Advert((id, attribute)) => (id, attribute, None),
};
if artifact.is_some() {
self.metrics.slot_table_updates_with_artifact_total.inc();
}
let new_slot_entry: SlotEntry<Artifact::Id> = SlotEntry {
commit_id,
conn_id: connection_id,
id: id.clone(),
};
let (to_add, to_remove) = match self
.slot_table
.entry(peer_id)
.or_default()
.entry(slot_number)
{
Entry::Occupied(mut slot_entry_mut) => {
if slot_entry_mut.get().should_be_replaced(&new_slot_entry) {
self.metrics.slot_table_overwrite_total.inc();
let to_remove = slot_entry_mut.insert(new_slot_entry).id;
(true, Some(to_remove))
} else {
self.metrics.slot_table_stale_total.inc();
(false, None)
}
}
Entry::Vacant(empty_slot) => {
empty_slot.insert(new_slot_entry);
self.metrics
.slot_table_new_entry_total
.with_label_values(&[peer_id.to_string().as_str()])
.inc();
(true, None)
}
};
if to_add {
match self.active_downloads.get(&id) {
Some(sender) => {
self.metrics.slot_table_seen_id_total.inc();
sender.send_if_modified(|h| h.insert(peer_id));
}
None => {
self.metrics.download_task_started_total.inc();
let mut peer_counter = PeerCounter::new();
let (tx, rx) = watch::channel(peer_counter);
tx.send_if_modified(|h| h.insert(peer_id));
self.active_downloads.insert(id.clone(), tx);
self.artifact_processor_tasks.spawn_on(
Self::process_advert(
self.log.clone(),
id.clone(),
attribute,
artifact.map(|a| (a, peer_id)),
rx,
self.current_priority_fn.subscribe(),
self.sender.clone(),
self.transport.clone(),
self.metrics.clone(),
),
&self.rt_handle,
);
}
}
}
if let Some(to_remove) = to_remove {
match self.active_downloads.get_mut(&to_remove) {
Some(sender) => {
sender.send_if_modified(|h| h.remove(peer_id));
self.metrics.slot_table_removals_total.inc();
}
None => {
error!(
self.log,
"Slot table contains an artifact ID that is not present in the `active_downloads`. This should never happen."
);
if cfg!(debug_assertions) {
panic!("Invariant violated");
}
}
};
}
}
/// Waits until advert resolves to fetch. If all peers are removed or priority becomes drop `DownloadStopped` is returned.
async fn wait_fetch(
id: &Artifact::Id,
attr: &Artifact::Attribute,
artifact: &mut Option<(Artifact::Message, NodeId)>,
metrics: &ConsensusManagerMetrics,
mut peer_rx: &mut watch::Receiver<PeerCounter>,
mut priority_fn_watcher: &mut watch::Receiver<
PriorityFn<Artifact::Id, Artifact::Attribute>,
>,
) -> Result<(), DownloadStopped> {
let mut priority = priority_fn_watcher.borrow_and_update()(id, attr);
// Clear the artifact from memory if it was pushed.
if let Priority::Stash = priority {
artifact.take();
metrics.download_task_stashed_total.inc();
}
while let Priority::Stash = priority {
select! {
Ok(_) = priority_fn_watcher.changed() => {
priority = priority_fn_watcher.borrow_and_update()(id, attr);
}
res = peer_rx.changed() => {
match res {
Ok(()) if peer_rx.borrow().is_empty() => {
return Err(DownloadStopped::AllPeersDeletedTheArtifact);
},
Ok(()) => {},
Err(_) => {
return Err(DownloadStopped::AllPeersDeletedTheArtifact);
}
}
}
}
}
if let Priority::Drop = priority {
return Err(DownloadStopped::PriorityIsDrop);
}
Ok(())
}
/// Downloads a given artifact.
///
/// The download will be scheduled based on the given priority function, `priority_fn_watcher`.
///
/// The download fails iff:
/// - The priority function evaluates the advert to [`Priority::Drop`] -> [`DownloadStopped::PriorityIsDrop`]
/// - The set of peers advertising the artifact, `peer_rx`, becomes empty -> [`DownloadStopped::AllPeersDeletedTheArtifact`]
/// and the failure condition is reported in the error variant of the returned result.
async fn download_artifact(
log: ReplicaLogger,
id: &Artifact::Id,
attr: &Artifact::Attribute,
// Only first peer for specific artifact ID is considered for push
mut artifact: Option<(Artifact::Message, NodeId)>,
mut peer_rx: &mut watch::Receiver<PeerCounter>,
mut priority_fn_watcher: watch::Receiver<PriorityFn<Artifact::Id, Artifact::Attribute>>,
transport: Arc<dyn Transport>,
metrics: ConsensusManagerMetrics,
) -> Result<(Artifact::Message, NodeId), DownloadStopped> {
// Evaluate priority and wait until we should fetch.
Self::wait_fetch(
id,
attr,
&mut artifact,
&metrics,
peer_rx,
&mut priority_fn_watcher,
)
.await?;
let mut artifact_download_timeout = ExponentialBackoffBuilder::new()
.with_initial_interval(MIN_ARTIFACT_RPC_TIMEOUT)
.with_max_interval(MAX_ARTIFACT_RPC_TIMEOUT)
.with_max_elapsed_time(None)
.build();
match artifact {
// Artifact was pushed by peer. In this case we don't need check that the artifact ID corresponds
// to the artifact because we earlier derived the ID from the artifact.
Some((artifact, peer_id)) => Ok((artifact, peer_id)),
// Fetch artifact
None => {
let mut result = Err(DownloadStopped::AllPeersDeletedTheArtifact);
let timer = metrics
.download_task_artifact_download_duration
.start_timer();
let mut rng = SmallRng::from_entropy();
while let Some(peer) = {
let peer = peer_rx.borrow().peers().choose(&mut rng).copied();
peer
} {
let bytes = Bytes::from(Artifact::PbId::proxy_encode(id.clone()));
let request = Request::builder()
.uri(format!("/{}/rpc", uri_prefix::<Artifact>()))
.body(bytes)
.unwrap();
if peer_rx.has_changed().unwrap_or(false) {
artifact_download_timeout.reset();
}
let next_request_at = Instant::now()
+ artifact_download_timeout
.next_backoff()
.unwrap_or(MAX_ARTIFACT_RPC_TIMEOUT);
match timeout_at(next_request_at, transport.rpc(&peer, request)).await {
Ok(Ok(response)) if response.status() == StatusCode::OK => {
let body = response.into_body();
if let Ok(message) = Artifact::PbMessage::proxy_decode(&body) {
if &Artifact::message_to_advert(&message).id == id {
result = Ok((message, peer));
break;
} else {
warn!(
log,
"Peer {} responded with wrong artifact for advert", peer
);
}
}
}
_ => {
metrics.download_task_artifact_download_errors_total.inc();
}
}
// Wait before checking the priority so we might be able to avoid an unnecessary download.
sleep_until(next_request_at).await;
Self::wait_fetch(
id,
attr,
&mut artifact,
&metrics,
peer_rx,
&mut priority_fn_watcher,
)
.await?;
}
timer.stop_and_record();
result
}
}
}
/// Tries to download the given artifact, and insert it into the unvalidated pool.
///
/// This future waits for all peers that advertise the artifact to delete it.
/// The artifact is deleted from the unvalidated pool upon completion.
async fn process_advert(
log: ReplicaLogger,
id: Artifact::Id,
attr: Artifact::Attribute,
// Only first peer for specific artifact ID is considered for push
mut artifact: Option<(Artifact::Message, NodeId)>,
mut peer_rx: watch::Receiver<PeerCounter>,
mut priority_fn_watcher: watch::Receiver<PriorityFn<Artifact::Id, Artifact::Attribute>>,
sender: CrossbeamSender<UnvalidatedArtifactMutation<Artifact>>,
transport: Arc<dyn Transport>,
metrics: ConsensusManagerMetrics,
) -> (
watch::Receiver<PeerCounter>,
Artifact::Id,
Artifact::Attribute,
) {
let _timer = metrics.download_task_duration.start_timer();
let download_result = Self::download_artifact(
log,
&id,
&attr,
artifact,
&mut peer_rx,
priority_fn_watcher,
transport,
metrics.clone(),
)
.await;
match download_result {
Ok((artifact, peer_id)) => {
// Send artifact to pool
sender.send(UnvalidatedArtifactMutation::Insert((artifact, peer_id)));
// wait for deletion from peers
peer_rx.wait_for(|p| p.is_empty()).await;
// Purge from the unvalidated pool
sender.send(UnvalidatedArtifactMutation::Remove(id.clone()));
metrics
.download_task_result_total
.with_label_values(&[DOWNLOAD_TASK_RESULT_COMPLETED])
.inc();
}
Err(DownloadStopped::PriorityIsDrop) => {
// wait for deletion from peers
peer_rx.wait_for(|p| p.is_empty()).await;
metrics
.download_task_result_total
.with_label_values(&[DOWNLOAD_TASK_RESULT_DROP])
.inc();
}
Err(DownloadStopped::AllPeersDeletedTheArtifact) => {
metrics
.download_task_result_total
.with_label_values(&[DOWNLOAD_TASK_RESULT_ALL_PEERS_DELETED])
.inc();
}
}
(peer_rx, id, attr)
}
/// Notifies all running tasks about the topology update.
fn handle_topology_update(&mut self) {
self.metrics.topology_updates_total.inc();
let new_topology = self.topology_watcher.borrow().clone();
let mut nodes_leaving_topology = HashSet::new();
self.slot_table.retain(|node_id, _| {
if !new_topology.is_member(node_id) {
nodes_leaving_topology.insert(*node_id);
self.metrics
.slot_table_new_entry_total
.remove_label_values(&[node_id.to_string().as_str()]);
false
} else {
true
}
});
for peers_sender in self.active_downloads.values() {
peers_sender.send_if_modified(|set| {
nodes_leaving_topology
.iter()
.map(|n| set.remove(*n))
.any(|r| r)
});
}
debug_assert!(
self.slot_table.len() <= self.topology_watcher.borrow().iter().count(),
"Slot table contains more nodes than nodes in subnet after pruning"
);
}
}
#[derive(Debug, PartialEq, Eq)]
enum DownloadStopped {
AllPeersDeletedTheArtifact,
PriorityIsDrop,
}
#[derive(PartialEq, Eq, Debug)]
struct SlotEntry<T> {
conn_id: ConnId,
commit_id: CommitId,
id: T,
}
impl<T> SlotEntry<T> {
fn should_be_replaced(&self, other: &SlotEntry<T>) -> bool {
if other.conn_id != self.conn_id {
return other.conn_id > self.conn_id;
}
// connection ids are the same
other.commit_id > self.commit_id
}
}
#[cfg(test)]
mod tests {
use std::{backtrace::Backtrace, sync::Mutex};
use axum::http::Response;
use ic_logger::replica_logger::no_op_logger;
use ic_metrics::MetricsRegistry;
use ic_p2p_test_utils::{
consensus::U64Artifact,
mocks::{MockPriorityFnAndFilterProducer, MockTransport, MockValidatedPoolReader},
};
use ic_test_utilities_logger::with_test_replica_logger;
use ic_types::RegistryVersion;
use ic_types_test_utils::ids::{NODE_1, NODE_2};
use mockall::Sequence;
use tokio::time::timeout;
use super::*;
const PROCESS_ARTIFACT_TIMEOUT: Duration = Duration::from_millis(1000);
fn create_receive_manager(
log: ReplicaLogger,
metrics: ConsensusManagerMetrics,
rt_handle: Handle,
// Adverts received from peers
adverts_received: Receiver<(AdvertUpdate<U64Artifact>, NodeId, ConnId)>,
raw_pool: Arc<RwLock<MockValidatedPoolReader>>,
priority_fn_producer: Arc<
dyn PriorityFnAndFilterProducer<U64Artifact, MockValidatedPoolReader>,
>,
sender: CrossbeamSender<UnvalidatedArtifactMutation<U64Artifact>>,
transport: Arc<dyn Transport>,
topology_watcher: watch::Receiver<SubnetTopology>,
) -> ConsensusManagerReceiver<
U64Artifact,
MockValidatedPoolReader,
(AdvertUpdate<U64Artifact>, NodeId, ConnId),
> {
let priority_fn = priority_fn_producer.get_priority_function(&raw_pool.read().unwrap());
let (current_priority_fn, _) = watch::channel(priority_fn);
ConsensusManagerReceiver {
log,
metrics,
rt_handle: rt_handle.clone(),
adverts_received,
pool_reader: raw_pool.clone() as Arc<_>,
raw_pool,
priority_fn_producer,
current_priority_fn,
sender,
transport,
active_downloads: HashMap::new(),
slot_table: HashMap::new(),
artifact_processor_tasks: JoinSet::new(),
topology_watcher,
}
}
/// Check that all variants of stale adverts to not get added to the slot table.
#[test]
fn receiving_stale_advert_updates() {
// Abort process if a thread panics. This catches detached tokio tasks that panic.
// https://github.com/tokio-rs/tokio/issues/4516
std::panic::set_hook(Box::new(|info| {
let stacktrace = Backtrace::force_capture();
println!("Got panic. @info:{}\n@stackTrace:{}", info, stacktrace);
std::process::abort();
}));
with_test_replica_logger(|log| {
let rt = tokio::runtime::Runtime::new().unwrap();
let mock_reader = MockValidatedPoolReader::new();
let mut mock_pfn = MockPriorityFnAndFilterProducer::new();
mock_pfn
.expect_get_priority_function()
.returning(|_| Box::new(|_, _| Priority::Stash));
let mock_transport = MockTransport::new();
let (_tx, rx) = tokio::sync::mpsc::channel(100);
let (cb_tx, _cb_rx) = crossbeam_channel::unbounded();
let (_pfn_tx, pfn_rx) = watch::channel(SubnetTopology::default());
let mut mgr = create_receive_manager(
log,
ConsensusManagerMetrics::new::<U64Artifact>(&MetricsRegistry::default()),
rt.handle().clone(),
rx,
Arc::new(RwLock::new(mock_reader)),
Arc::new(mock_pfn),
cb_tx,
Arc::new(mock_transport),
pfn_rx,
);
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(1),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(1),
);
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
assert_eq!(mgr.slot_table.len(), 1);
assert_eq!(mgr.slot_table.get(&NODE_1).unwrap().len(), 1);
assert_eq!(mgr.active_downloads.len(), 1);
assert_eq!(mgr.artifact_processor_tasks.len(), 1);
// Send stale advert with lower commit id.
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(0),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(1),
);
// Check that slot table did not get updated.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
// Send stale advert with lower conn id
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(0),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(0),
);
// Check that slot table did not get updated.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
// Send stale advert with lower conn id but higher commit id
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(10),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(0),
);
// Check that slot table did not get updated.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
// Send stale advert with lower conn id and lower commit id
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(0),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(0),
);
// Check that slot table did not get updated.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
assert_eq!(mgr.slot_table.len(), 1);
assert_eq!(mgr.slot_table.get(&NODE_1).unwrap().len(), 1);
assert_eq!(mgr.active_downloads.len(), 1);
assert_eq!(mgr.artifact_processor_tasks.len(), 1);
});
}
/// Check that adverts updates with higher connection ids take precedence.
#[test]
fn overwrite_slot() {
// Abort process if a thread panics. This catches detached tokio tasks that panic.
// https://github.com/tokio-rs/tokio/issues/4516
std::panic::set_hook(Box::new(|info| {
let stacktrace = Backtrace::force_capture();
println!("Got panic. @info:{}\n@stackTrace:{}", info, stacktrace);
std::process::abort();
}));
with_test_replica_logger(|log| {
let rt = tokio::runtime::Runtime::new().unwrap();
let mock_reader = MockValidatedPoolReader::new();
let mut mock_pfn = MockPriorityFnAndFilterProducer::new();
mock_pfn
.expect_get_priority_function()
.returning(|_| Box::new(|_, _| Priority::Stash));
let mock_transport = MockTransport::new();
let (_tx, rx) = tokio::sync::mpsc::channel(100);
let (cb_tx, _cb_rx) = crossbeam_channel::unbounded();
let (_pfn_tx, pfn_rx) = watch::channel(SubnetTopology::default());
let mut mgr = create_receive_manager(
log,
ConsensusManagerMetrics::new::<U64Artifact>(&MetricsRegistry::default()),
rt.handle().clone(),
rx,
Arc::new(RwLock::new(mock_reader)),
Arc::new(mock_pfn),
cb_tx,
Arc::new(mock_transport),
pfn_rx,
);
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(1),
update: Update::Advert((0, ())),
},
NODE_1,
ConnId::from(1),
);
// Verify that advert is correctly inserted into slot table.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),
&SlotEntry {
conn_id: ConnId::from(1),
commit_id: CommitId::from(1),
id: 0,
}
);
assert_eq!(mgr.slot_table.len(), 1);
assert_eq!(mgr.slot_table.get(&NODE_1).unwrap().len(), 1);
assert_eq!(mgr.active_downloads.len(), 1);
assert_eq!(mgr.artifact_processor_tasks.len(), 1);
// Send advert with higher conn id.
mgr.handle_advert_receive(
AdvertUpdate {
slot_number: SlotNumber::from(1),
commit_id: CommitId::from(0),
update: Update::Advert((1, ())),
},
NODE_1,
ConnId::from(2),
);
// Verify that slot table now only contains newer entry.
assert_eq!(
mgr.slot_table
.get(&NODE_1)
.unwrap()
.get(&SlotNumber::from(1))
.unwrap(),