-
Notifications
You must be signed in to change notification settings - Fork 241
/
mod.rs
2262 lines (2080 loc) · 94.6 KB
/
mod.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 petgraph::graph::NodeIndex;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time;
use std::collections::hash_map::Entry;
use std::rc::Rc;
use std::io::{BufRead, BufReader, ErrorKind};
use std::fs::File;
use std::net::SocketAddr;
use Readers;
use channel::TcpSender;
use channel::poll::{KeepPolling, PollEvent, PollingLoop, StopPolling};
use prelude::*;
use payload::{ControlReplyPacket, ReplayPieceContext, ReplayTransactionState, TransactionState};
use statistics;
use transactions;
use persistence;
use debug;
use checktable;
use serde_json;
use itertools::Itertools;
use slog::Logger;
use timekeeper::{RealTime, SimpleTracker, ThreadTime, Timer, TimerSet};
use tarpc::sync::client::{self, ClientExt};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
pub concurrent_replays: usize,
pub replay_batch_timeout: time::Duration,
pub replay_batch_size: usize,
}
const BATCH_SIZE: usize = 256;
const RECOVERY_BATCH_SIZE: usize = 512;
const NANOS_PER_SEC: u64 = 1_000_000_000;
macro_rules! dur_to_ns {
($d:expr) => {{
let d = $d;
d.as_secs() * NANOS_PER_SEC + d.subsec_nanos() as u64
}}
}
#[allow(missing_docs)]
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Index(usize);
impl From<usize> for Index {
fn from(i: usize) -> Self {
Index(i)
}
}
impl Into<usize> for Index {
fn into(self) -> usize {
self.0
}
}
#[allow(missing_docs)]
impl Index {
pub fn index(&self) -> usize {
self.0
}
}
#[derive(Debug)]
enum DomainMode {
Forwarding,
Replaying {
to: LocalNodeIndex,
buffered: VecDeque<Box<Packet>>,
passes: usize,
},
}
impl PartialEq for DomainMode {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&DomainMode::Forwarding, &DomainMode::Forwarding) => true,
_ => false,
}
}
}
enum TriggerEndpoint {
None,
Start(Vec<usize>),
End(Vec<TcpSender<Box<Packet>>>),
Local(Vec<usize>),
}
struct ReplayPath {
source: Option<LocalNodeIndex>,
path: Vec<ReplayPathSegment>,
notify_done: bool,
trigger: TriggerEndpoint,
}
type Hole = (usize, DataType);
type Redo = (Tag, DataType);
/// When a replay misses while being processed, it triggers a replay to backfill the hole that it
/// missed in. We need to ensure that when this happens, we re-run the original replay to fill the
/// hole we *originally* were trying to fill.
///
/// This comes with some complexity:
///
/// - If two replays both hit the *same* hole, we should only request a backfill of it once, but
/// need to re-run *both* replays when the hole is filled.
/// - If one replay hits two *different* holes, we should backfill both holes, but we must ensure
/// that we only re-run the replay once when both holes have been filled.
///
/// To keep track of this, we use the `Waiting` structure below. One is created for every node with
/// at least one outstanding backfill, and contains the necessary bookkeeping to ensure the two
/// behaviors outlined above.
///
/// Note that in the type aliases above, we have chosen to use Vec<usize> instead of Tag to
/// identify a hole. This is because there may be more than one Tag used to fill a given hole, and
/// the set of columns uniquely identifies the set of tags.
#[derive(Debug, Default)]
struct Waiting {
/// For each eventual redo, how many holes are we waiting for?
holes: HashMap<Redo, usize>,
/// For each hole, which redos do we expect we'll have to do?
redos: HashMap<Hole, HashSet<Redo>>,
}
/// Struct sent to a worker to start a domain.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DomainBuilder {
/// The domain's index.
pub index: Index,
/// The shard ID represented by this `DomainBuilder`.
pub shard: usize,
/// The number of shards in the domain.
pub nshards: usize,
/// The nodes in the domain.
pub nodes: DomainNodes,
/// The domain's persistence setting.
pub persistence_parameters: persistence::Parameters,
/// The starting timestamp.
pub ts: i64,
/// The socket address at which this domain receives control messages.
pub control_addr: SocketAddr,
/// The socket address over which this domain communicates with the checktable service.
pub checktable_addr: SocketAddr,
/// The socket address for debug interactions with this domain.
pub debug_addr: Option<SocketAddr>,
/// Configuration parameters for the domain.
pub config: Config,
}
impl DomainBuilder {
/// Starts up the domain represented by this `DomainBuilder`.
pub fn boot(
self,
log: Logger,
readers: Readers,
channel_coordinator: Arc<ChannelCoordinator>,
listen_addr: SocketAddr,
) -> (thread::JoinHandle<()>, SocketAddr) {
// initially, all nodes are not ready
let not_ready = self.nodes
.values()
.map(|n| *n.borrow().local_addr())
.collect();
let shard = if self.nshards == 1 {
None
} else {
Some(self.shard)
};
let debug_tx = self.debug_addr
.as_ref()
.map(|addr| TcpSender::connect(addr, None).unwrap());
let mut control_reply_tx = TcpSender::connect(&self.control_addr, None).unwrap();
// Create polling loop and tell the controller what port we are listening on.
let polling_loop = PollingLoop::<Packet>::new(listen_addr);
// We extract this here because `listen_addr` may not specify a port and rely on
// auto-assignment
let addr = polling_loop.get_listener_addr().unwrap();
control_reply_tx
.send(ControlReplyPacket::Booted(shard.unwrap_or(0), addr.clone()))
.unwrap();
info!(log, "booting domain"; "nodes" => self.nodes.iter().count());
let name = match shard {
Some(shard) => format!("domain{}.{}", self.index.0, shard),
None => format!("domain{}", self.index.0),
};
let jh = thread::Builder::new()
.name(name)
.spawn(move || {
let checktable = Rc::new(
checktable::CheckTableClient::connect(
self.checktable_addr,
client::Options::default(),
).unwrap(),
);
Domain {
index: self.index,
shard,
nshards: self.nshards,
transaction_state: transactions::DomainState::new(
self.index,
checktable,
self.ts,
),
persistence_parameters: self.persistence_parameters,
nodes: self.nodes,
state: StateMap::default(),
log,
not_ready,
mode: DomainMode::Forwarding,
waiting: local::Map::new(),
reader_triggered: local::Map::new(),
replay_paths: HashMap::new(),
addr,
readers,
inject: None,
_debug_tx: debug_tx,
control_reply_tx,
channel_coordinator,
buffered_replay_requests: HashMap::new(),
has_buffered_replay_requests: false,
replay_batch_size: self.config.replay_batch_size,
replay_batch_timeout: self.config.replay_batch_timeout,
concurrent_replays: 0,
max_concurrent_replays: self.config.concurrent_replays,
replay_request_queue: Default::default(),
total_time: Timer::new(),
total_ptime: Timer::new(),
wait_time: Timer::new(),
process_times: TimerSet::new(),
process_ptimes: TimerSet::new(),
}.run(polling_loop)
})
.unwrap();
(jh, addr)
}
}
pub struct Domain {
index: Index,
shard: Option<usize>,
nshards: usize,
nodes: DomainNodes,
state: StateMap,
log: Logger,
not_ready: HashSet<LocalNodeIndex>,
transaction_state: transactions::DomainState,
persistence_parameters: persistence::Parameters,
mode: DomainMode,
waiting: local::Map<Waiting>,
replay_paths: HashMap<Tag, ReplayPath>,
reader_triggered: local::Map<HashSet<DataType>>,
concurrent_replays: usize,
max_concurrent_replays: usize,
replay_request_queue: VecDeque<(Tag, Vec<DataType>)>,
addr: SocketAddr,
readers: Readers,
inject: Option<Box<Packet>>,
_debug_tx: Option<TcpSender<debug::DebugEvent>>,
control_reply_tx: TcpSender<ControlReplyPacket>,
channel_coordinator: Arc<ChannelCoordinator>,
buffered_replay_requests: HashMap<Tag, (time::Instant, HashSet<Vec<DataType>>)>,
has_buffered_replay_requests: bool,
replay_batch_timeout: time::Duration,
replay_batch_size: usize,
total_time: Timer<SimpleTracker, RealTime>,
total_ptime: Timer<SimpleTracker, ThreadTime>,
wait_time: Timer<SimpleTracker, RealTime>,
process_times: TimerSet<LocalNodeIndex, SimpleTracker, RealTime>,
process_ptimes: TimerSet<LocalNodeIndex, SimpleTracker, ThreadTime>,
}
impl Domain {
fn on_replay_miss(
&mut self,
miss_in: LocalNodeIndex,
miss_columns: &[usize],
replay_key: Vec<DataType>,
miss_key: Vec<DataType>,
needed_for: Tag,
) {
use std::ops::AddAssign;
use std::collections::hash_map::Entry;
// when the replay eventually succeeds, we want to re-do the replay.
let mut w = self.waiting.remove(&miss_in).unwrap_or_default();
assert_eq!(miss_columns.len(), 1);
assert_eq!(replay_key.len(), 1);
assert_eq!(miss_key.len(), 1);
let mut redundant = false;
let redo = (needed_for, replay_key[0].clone());
match w.redos.entry((miss_columns[0], miss_key[0].clone())) {
Entry::Occupied(e) => {
// we have already requested backfill of this key
// remember to notify this Redo when backfill completes
if e.into_mut().insert(redo.clone()) {
// this Redo should wait for this backfill to complete before redoing
w.holes.entry(redo).or_default().add_assign(1);
}
redundant = true;
}
Entry::Vacant(e) => {
// we haven't already requested backfill of this key
let mut redos = HashSet::new();
// remember to notify this Redo when backfill completes
redos.insert(redo.clone());
e.insert(redos);
// this Redo should wait for this backfill to complete before redoing
w.holes.entry(redo).or_default().add_assign(1);
}
}
self.waiting.insert(miss_in, w);
if redundant {
return;
}
let mut found = false;
let tags: Vec<Tag> = self.replay_paths.keys().cloned().collect();
for tag in tags {
if let TriggerEndpoint::Start(..) = self.replay_paths[&tag].trigger {
continue;
}
{
let p = self.replay_paths[&tag].path.last().unwrap();
if p.node != miss_in {
continue;
}
assert!(p.partial_key.is_some());
assert_eq!(miss_columns.len(), 1);
if p.partial_key.unwrap() != miss_columns[0] {
continue;
}
}
// send a message to the source domain(s) responsible
// for the chosen tag so they'll start replay.
let key = miss_key.clone(); // :(
if let TriggerEndpoint::Local(..) = self.replay_paths[&tag].trigger {
if self.already_requested(&tag, &key[..]) {
return;
}
trace!(self.log,
"got replay request";
"tag" => tag.id(),
"key" => format!("{:?}", key)
);
self.seed_replay(tag, &key[..], None);
found = true;
continue;
}
// NOTE: due to max_concurrent_replays, it may be that we only replay from *some* of
// these ancestors now, and some later. this will cause more of the replay to be
// buffered up at the union above us, but that's probably fine.
self.request_partial_replay(tag, key);
found = true;
continue;
}
if !found {
unreachable!(format!(
"no tag found to fill missing value {:?} in {}.{:?}",
miss_key,
miss_in,
miss_columns
));
}
}
fn send_partial_replay_request(&mut self, tag: Tag, key: Vec<DataType>) {
debug_assert!(self.concurrent_replays < self.max_concurrent_replays);
if let TriggerEndpoint::End(ref mut triggers) =
self.replay_paths.get_mut(&tag).unwrap().trigger
{
// find right shard. it's important that we only request a replay from the right
// shard, because otherwise all the other shard domains will miss, and then request
// replays themselves for the miss key. however, the response to that request will
// never be routed to them, leading to infinite loops and whatnot.
let shard = if triggers.len() == 1 {
0
} else {
assert!(key.len() == 1);
::shard_by(&key[0], triggers.len())
};
self.concurrent_replays += 1;
trace!(self.log, "sending replay request";
"tag" => ?tag,
"key" => ?key,
"buffered" => self.replay_request_queue.len(),
"concurrent" => self.concurrent_replays,
);
if triggers[shard]
.send(box Packet::RequestPartialReplay { tag, key })
.is_err()
{
// we're shutting down -- it's fine.
}
} else {
unreachable!("asked to replay along non-existing path")
}
}
fn request_partial_replay(&mut self, tag: Tag, key: Vec<DataType>) {
if self.concurrent_replays < self.max_concurrent_replays {
assert_eq!(self.replay_request_queue.len(), 0);
self.send_partial_replay_request(tag, key);
} else {
trace!(self.log, "buffering replay request";
"tag" => ?tag,
"key" => ?key,
"buffered" => self.replay_request_queue.len(),
);
self.replay_request_queue.push_back((tag, key));
}
}
fn finished_partial_replay(&mut self, tag: &Tag, num: usize) {
match self.replay_paths[tag].trigger {
TriggerEndpoint::End(..) => {
// A backfill request we made to another domain was just satisfied!
// We can now issue another request from the concurrent replay queue.
// However, since unions require multiple backfill requests, but produce only one
// backfill reply, we need to check how many requests we're now free to issue. If
// we just naively release one slot here, a union with two parents would mean that
// `self.concurrent_replays` constantly grows by +1 (+2 for the backfill requests,
// -1 when satisfied), which would lead to a deadlock!
let mut requests_satisfied = {
let last = self.replay_paths[tag].path.last().unwrap();
self.replay_paths
.iter()
.filter(|&(_, p)| if let TriggerEndpoint::End(..) = p.trigger {
let p = p.path.last().unwrap();
p.node == last.node && p.partial_key == last.partial_key
} else {
false
})
.count()
};
// we also sent that many requests *per key*.
requests_satisfied *= num;
// TODO: figure out why this can underflow
self.concurrent_replays =
self.concurrent_replays.saturating_sub(requests_satisfied);
trace!(self.log, "notified of finished replay";
"#done" => requests_satisfied,
"ongoing" => self.concurrent_replays,
);
debug_assert!(self.concurrent_replays < self.max_concurrent_replays);
while self.concurrent_replays < self.max_concurrent_replays {
if let Some((tag, key)) = self.replay_request_queue.pop_front() {
trace!(self.log, "releasing replay request";
"tag" => ?tag,
"key" => ?key,
"left" => self.replay_request_queue.len(),
"ongoing" => self.concurrent_replays,
);
self.send_partial_replay_request(tag, key);
} else {
return;
}
}
}
TriggerEndpoint::Local(..) => {
// didn't count against our quote, so we're also not decementing
}
TriggerEndpoint::Start(..) | TriggerEndpoint::None => {
unreachable!();
}
}
}
fn dispatch(
m: Box<Packet>,
not_ready: &HashSet<LocalNodeIndex>,
mode: &mut DomainMode,
waiting: &mut local::Map<Waiting>,
states: &mut StateMap,
nodes: &DomainNodes,
shard: Option<usize>,
paths: &mut HashMap<Tag, ReplayPath>,
process_times: &mut TimerSet<LocalNodeIndex, SimpleTracker, RealTime>,
process_ptimes: &mut TimerSet<LocalNodeIndex, SimpleTracker, ThreadTime>,
enable_output: bool,
) -> HashMap<LocalNodeIndex, Vec<Record>> {
let me = m.link().dst;
let mut output_messages = HashMap::new();
match *mode {
DomainMode::Forwarding => (),
DomainMode::Replaying {
ref to,
ref mut buffered,
..
} if to == &me =>
{
buffered.push_back(m);
return output_messages;
}
DomainMode::Replaying { .. } => (),
}
if !not_ready.is_empty() && not_ready.contains(&me) {
return output_messages;
}
let mut n = nodes[&me].borrow_mut();
process_times.start(me);
process_ptimes.start(me);
let mut m = Some(m);
n.process(&mut m, None, states, nodes, shard, true);
process_ptimes.stop();
process_times.stop();
drop(n);
if m.is_none() {
// no need to deal with our children if we're not sending them anything
return output_messages;
}
// ignore misses during regular forwarding
match m.as_ref().unwrap() {
m @ &box Packet::Message { .. } if m.is_empty() => {
// no need to deal with our children if we're not sending them anything
return output_messages;
}
&box Packet::Message { .. } => {}
&box Packet::Transaction { .. } => {
// Any message with a timestamp (ie part of a transaction) must flow through the
// entire graph, even if there are no updates associated with it.
}
&box Packet::ReplayPiece { .. } => {
unreachable!("replay should never go through dispatch");
}
ref m => unreachable!("dispatch process got {:?}", m),
}
let n = nodes[&me].borrow();
for i in 0..n.nchildren() {
// avoid cloning if we can
let mut m = if i == n.nchildren() - 1 {
m.take().unwrap()
} else {
m.as_ref().map(|m| box m.clone_data()).unwrap()
};
if enable_output || !nodes[n.child(i)].borrow().is_output() {
if n.is_shard_merger() {
// we need to preserve the egress src (which includes shard identifier)
} else {
m.link_mut().src = me;
}
m.link_mut().dst = *n.child(i);
for (k, mut v) in Self::dispatch(
m,
not_ready,
mode,
waiting,
states,
nodes,
shard,
paths,
process_times,
process_ptimes,
enable_output,
) {
use std::collections::hash_map::Entry;
match output_messages.entry(k) {
Entry::Occupied(mut rs) => rs.get_mut().append(&mut v),
Entry::Vacant(slot) => {
slot.insert(v);
}
}
}
} else {
let mut data = m.take_data();
match output_messages.entry(*n.child(i)) {
Entry::Occupied(entry) => {
entry.into_mut().append(&mut data);
}
Entry::Vacant(entry) => {
entry.insert(data.into());
}
};
}
}
output_messages
}
fn dispatch_(
&mut self,
m: Box<Packet>,
enable_output: bool,
) -> HashMap<LocalNodeIndex, Vec<Record>> {
Self::dispatch(
m,
&self.not_ready,
&mut self.mode,
&mut self.waiting,
&mut self.state,
&self.nodes,
self.shard,
&mut self.replay_paths,
&mut self.process_times,
&mut self.process_ptimes,
enable_output,
)
}
pub fn transactional_dispatch(&mut self, messages: Vec<Box<Packet>>) {
assert!(!messages.is_empty());
let mut egress_messages = HashMap::new();
let (ts, tracer) = if let Packet::Transaction {
state: ref ts @ TransactionState::Committed(..),
ref tracer,
..
} = *messages[0]
{
(ts.clone(), tracer.clone())
} else {
unreachable!();
};
for m in messages {
let new_messages = self.dispatch_(m, false);
for (key, mut value) in new_messages {
egress_messages
.entry(key)
.or_insert_with(Vec::new)
.append(&mut value);
}
}
let base = if let TransactionState::Committed(_, base, _) = ts {
base
} else {
unreachable!()
};
for n in self.transaction_state.egress_for(base) {
let n = &self.nodes[n];
let data = match egress_messages.entry(*n.borrow().local_addr()) {
Entry::Occupied(entry) => entry.remove().into(),
_ => Records::default(),
};
let addr = *n.borrow().local_addr();
// TODO: message should be from actual parent, not self.
let m = if n.borrow().is_transactional() {
box Packet::Transaction {
link: Link::new(addr, addr),
data: data,
state: ts.clone(),
tracer: tracer.clone(),
}
} else {
// The packet is about to hit a non-transactional output node (which could be an
// egress node), so it must be converted to a normal normal message.
box Packet::Message {
link: Link::new(addr, addr),
data: data,
tracer: tracer.clone(),
}
};
if !self.not_ready.is_empty() && self.not_ready.contains(&addr) {
continue;
}
self.process_times.start(addr);
self.process_ptimes.start(addr);
let mut m = Some(m);
self.nodes[&addr].borrow_mut().process(
&mut m,
None,
&mut self.state,
&self.nodes,
self.shard,
true,
);
self.process_ptimes.stop();
self.process_times.stop();
assert_eq!(n.borrow().nchildren(), 0);
}
}
fn process_transactions(&mut self) {
loop {
match self.transaction_state.get_next_event() {
transactions::Event::Transaction(m) => self.transactional_dispatch(m),
transactions::Event::StartMigration => {
self.control_reply_tx
.send(ControlReplyPacket::ack())
.unwrap();
}
transactions::Event::CompleteMigration => {}
transactions::Event::SeedReplay(tag, key, rts) => {
self.seed_replay(tag, &key[..], Some(rts))
}
transactions::Event::Replay(m) => self.handle_replay(m),
transactions::Event::None => break,
}
}
}
fn already_requested(&mut self, tag: &Tag, key: &[DataType]) -> bool {
match self.replay_paths.get(tag).unwrap() {
&ReplayPath {
trigger: TriggerEndpoint::End(..),
ref path,
..
} |
&ReplayPath {
trigger: TriggerEndpoint::Local(..),
ref path,
..
} => {
// a miss in a reader! make sure we don't re-do work
let addr = path.last().unwrap().node;
let n = self.nodes[&addr].borrow();
let mut already_replayed = false;
n.with_reader(|r| {
if let Some(wh) = r.writer() {
if wh.try_find_and(&key[0], |_| ()).unwrap().0.is_some() {
// key has already been replayed!
already_replayed = true;
}
}
});
if already_replayed {
return true;
}
let mut had = false;
if let Some(ref mut prev) = self.reader_triggered.get_mut(&addr) {
if prev.contains(&key[0]) {
// we've already requested a replay of this key
return true;
}
prev.insert(key[0].clone());
had = true;
}
if !had {
self.reader_triggered.insert(addr, HashSet::new());
}
false
}
_ => false,
}
}
fn handle(&mut self, m: Box<Packet>) {
m.trace(PacketEvent::Handle);
match *m {
Packet::Message { .. } => {
self.dispatch_(m, true);
}
Packet::Transaction { .. } |
Packet::StartMigration { .. } |
Packet::CompleteMigration { .. } |
Packet::ReplayPiece {
transaction_state: Some(_),
..
} => {
self.transaction_state.handle(m);
self.process_transactions();
}
Packet::ReplayPiece { .. } => {
self.handle_replay(m);
}
Packet::StartRecovery { .. } => {
self.handle_recovery();
}
consumed => {
match consumed {
// workaround #16223
Packet::AddNode { node, parents } => {
use std::cell;
let addr = *node.local_addr();
self.not_ready.insert(addr);
for p in parents {
self.nodes
.get_mut(&p)
.unwrap()
.borrow_mut()
.add_child(*node.local_addr());
}
self.nodes.insert(addr, cell::RefCell::new(node));
trace!(self.log, "new node incorporated"; "local" => addr.id());
}
Packet::AddBaseColumn {
node,
field,
default,
} => {
let mut n = self.nodes[&node].borrow_mut();
n.add_column(&field);
n.get_base_mut()
.expect("told to add base column to non-base node")
.add_column(default);
self.control_reply_tx
.send(ControlReplyPacket::ack())
.unwrap();
}
Packet::DropBaseColumn { node, column } => {
let mut n = self.nodes[&node].borrow_mut();
n.get_base_mut()
.expect("told to drop base column from non-base node")
.drop_column(column);
self.control_reply_tx
.send(ControlReplyPacket::ack())
.unwrap();
}
Packet::UpdateEgress {
node,
new_tx,
new_tag,
} => {
let channel = new_tx.as_ref().map(|&(_, _, ref k)| {
let mut tx = None;
// The `UpdateEgress` message can race with the channel
// coordinator finding out about a parent domain. Thus, we need to
// spin here to ensure that the parent is indeed connected.
while tx.is_none() {
tx = self.channel_coordinator.get_tx(k);
}
tx.unwrap()
});
let mut n = self.nodes[&node].borrow_mut();
n.with_egress_mut(move |e| {
if let (Some(new_tx), Some((channel, is_local))) = (new_tx, channel) {
e.add_tx(new_tx.0, new_tx.1, channel, is_local);
}
if let Some(new_tag) = new_tag {
e.add_tag(new_tag.0, new_tag.1);
}
});
}
Packet::UpdateSharder { node, new_txs } => {
let new_channels: Vec<_> = new_txs
.1
.iter()
.filter_map(|ntx| self.channel_coordinator.get_tx(ntx))
.collect();
let mut n = self.nodes[&node].borrow_mut();
n.with_sharder_mut(move |s| {
s.add_sharded_child(new_txs.0, new_channels);
});
}
Packet::AddStreamer { node, new_streamer } => {
let mut n = self.nodes[&node].borrow_mut();
n.with_reader_mut(|r| r.add_streamer(new_streamer).unwrap());
}
Packet::StateSizeProbe { node } => {
let size = self.state.get(&node).map(|state| state.len()).unwrap_or(0);
self.control_reply_tx
.send(ControlReplyPacket::StateSize(size))
.unwrap();
}
Packet::PrepareState { node, state } => {
use payload::InitialState;
match state {
InitialState::PartialLocal(index) => {
if !self.state.contains_key(&node) {
self.state.insert(node, State::default());
}
let state = self.state.get_mut(&node).unwrap();
for (key, tags) in index {
info!(self.log, "told to prepare partial state";
"key" => ?key,
"tags" => ?tags);
state.add_key(&key[..], Some(tags));
}
}
InitialState::IndexedLocal(index) => {
if !self.state.contains_key(&node) {
self.state.insert(node, State::default());
}
let state = self.state.get_mut(&node).unwrap();
for idx in index {
info!(self.log, "told to prepare full state";
"key" => ?idx);
state.add_key(&idx[..], None);
}
}
InitialState::PartialGlobal {
gid,
cols,
key,
tag,
trigger_domain: (trigger_domain, shards),
} => {
use backlog;
let txs = Mutex::new(
(0..shards)
.map(|shard| {
self.channel_coordinator
.get_unbounded_tx(&(trigger_domain, shard))
.unwrap()
})
.collect::<Vec<_>>(),
);
let (r_part, w_part) =
backlog::new_partial(cols, key, move |key| {
let mut txs = txs.lock().unwrap();
let tx = if txs.len() == 1 {
&mut txs[0]
} else {
let n = txs.len();
&mut txs[::shard_by(key, n)]
};
let mut m = box Packet::RequestPartialReplay {
key: vec![key.clone()],
tag: tag,
};
if tx.1 {
m = m.make_local();
}
tx.0.send(m).unwrap();
});
let mut n = self.nodes[&node].borrow_mut();
n.with_reader_mut(|r| {
let token_generator = r.token_generator().cloned();
assert!(
self.readers
.lock()
.unwrap()
.insert(
(gid, *self.shard.as_ref().unwrap_or(&0)),
(r_part, token_generator)
)
.is_none()
);
// make sure Reader is actually prepared to receive state
r.set_write_handle(w_part)
});
}
InitialState::Global { gid, cols, key } => {
use backlog;
let (r_part, w_part) = backlog::new(cols, key);
let mut n = self.nodes[&node].borrow_mut();
n.with_reader_mut(|r| {
let token_generator = r.token_generator().cloned();
assert!(
self.readers
.lock()
.unwrap()
.insert(
(gid, *self.shard.as_ref().unwrap_or(&0)),
(r_part, token_generator)
)
.is_none()
);
// make sure Reader is actually prepared to receive state
r.set_write_handle(w_part)
});
}
}
}
Packet::SetupReplayPath {