-
Notifications
You must be signed in to change notification settings - Fork 242
/
inner.rs
1339 lines (1207 loc) · 49 KB
/
inner.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::controller::domain_handle::{DomainHandle, DomainShardHandle};
use crate::controller::migrate::materialization::Materializations;
use crate::controller::recipe::Schema;
use crate::controller::schema;
use crate::controller::{ControllerState, Migration, Recipe};
use crate::controller::{Worker, WorkerIdentifier};
use crate::coordination::{CoordinationMessage, CoordinationPayload, DomainDescriptor};
use dataflow::prelude::*;
use dataflow::{node, payload::ControlReplyPacket, prelude::Packet, DomainBuilder, DomainConfig};
use futures_util::stream::StreamExt;
use hyper::{self, Method, StatusCode};
use nom_sql::ColumnSpecification;
use noria::builders::*;
use noria::channel::tcp::{SendError, TcpSender};
use noria::consensus::{Authority, Epoch, STATE_KEY};
use noria::debug::stats::{DomainStats, GraphStats, NodeStats};
use noria::ActivationResult;
use petgraph::visit::Bfs;
use slog::Logger;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::mem;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{cell, io, time};
/// `Controller` is the core component of the alternate Soup implementation.
///
/// It keeps track of the structure of the underlying data flow graph and its domains. `Controller`
/// does not allow direct manipulation of the graph. Instead, changes must be instigated through a
/// `Migration`, which can be performed using `ControllerInner::migrate`. Only one `Migration` can
/// occur at any given point in time.
pub(super) struct ControllerInner {
pub(super) ingredients: Graph,
pub(super) source: NodeIndex,
pub(super) ndomains: usize,
pub(super) sharding: Option<usize>,
pub(super) domain_config: DomainConfig,
/// Parameters for persistence code.
pub(super) persistence: PersistenceParameters,
pub(super) materializations: Materializations,
/// Current recipe
recipe: Recipe,
pub(super) domains: HashMap<DomainIndex, DomainHandle>,
pub(in crate::controller) domain_nodes: HashMap<DomainIndex, Vec<NodeIndex>>,
pub(super) channel_coordinator: Arc<ChannelCoordinator>,
/// Map from worker address to the address the worker is listening on for reads.
read_addrs: HashMap<WorkerIdentifier, SocketAddr>,
pub(super) workers: HashMap<WorkerIdentifier, Worker>,
/// State between migrations
pub(super) remap: HashMap<DomainIndex, HashMap<NodeIndex, IndexPair>>,
pub(super) epoch: Epoch,
pending_recovery: Option<(Vec<String>, usize)>,
quorum: usize,
heartbeat_every: Duration,
healthcheck_every: Duration,
last_checked_workers: Instant,
log: slog::Logger,
pub(in crate::controller) replies: DomainReplies,
}
pub(in crate::controller) struct DomainReplies(
tokio::sync::mpsc::UnboundedReceiver<ControlReplyPacket>,
);
impl DomainReplies {
async fn read_n_domain_replies(&mut self, n: usize) -> Vec<ControlReplyPacket> {
let crps: Vec<_> = (&mut self.0).take(n).collect().await;
if crps.len() != n {
unreachable!(
"got unexpected EOF from domain reply channel after {} replies",
crps.len()
);
}
crps
}
pub(in crate::controller) async fn wait_for_acks(&mut self, d: &DomainHandle) {
for r in self.read_n_domain_replies(d.shards()).await {
match r {
ControlReplyPacket::Ack(_) => {}
r => unreachable!("got unexpected non-ack control reply: {:?}", r),
}
}
}
async fn wait_for_statistics(
&mut self,
d: &DomainHandle,
) -> Vec<(DomainStats, HashMap<NodeIndex, NodeStats>)> {
let mut stats = Vec::with_capacity(d.shards());
for r in self.read_n_domain_replies(d.shards()).await {
match r {
ControlReplyPacket::Statistics(d, s) => stats.push((d, s)),
r => unreachable!("got unexpected non-stats control reply: {:?}", r),
}
}
stats
}
}
pub(super) fn graphviz(
graph: &Graph,
detailed: bool,
materializations: &Materializations,
) -> String {
let mut s = String::new();
let indentln = |s: &mut String| s.push_str(" ");
// header.
s.push_str("digraph {{\n");
// global formatting.
indentln(&mut s);
if detailed {
s.push_str("node [shape=record, fontsize=10]\n");
} else {
s.push_str("graph [ fontsize=24 fontcolor=\"#0C6fA9\", outputorder=edgesfirst ]\n");
s.push_str("edge [ color=\"#0C6fA9\", style=bold ]\n");
s.push_str("node [ color=\"#0C6fA9\", shape=box, style=\"rounded,bold\" ]\n");
}
// node descriptions.
for index in graph.node_indices() {
let node = &graph[index];
let materialization_status = materializations.get_status(index, node);
indentln(&mut s);
s.push_str(&format!("n{}", index.index()));
s.push_str(&node.describe(index, detailed, materialization_status));
}
// edges.
for (_, edge) in graph.raw_edges().iter().enumerate() {
indentln(&mut s);
s.push_str(&format!(
"n{} -> n{} [ {} ]",
edge.source().index(),
edge.target().index(),
if graph[edge.source()].is_egress() {
"color=\"#CCCCCC\""
} else if graph[edge.source()].is_source() {
"style=invis"
} else {
""
}
));
s.push_str("\n");
}
// footer.
s.push_str("}}");
s
}
impl ControllerInner {
pub(in crate::controller) fn topo_order(&self, new: &HashSet<NodeIndex>) -> Vec<NodeIndex> {
let mut topo_list = Vec::with_capacity(new.len());
let mut topo = petgraph::visit::Topo::new(&self.ingredients);
while let Some(node) = topo.next(&self.ingredients) {
if node == self.source {
continue;
}
if self.ingredients[node].is_dropped() {
continue;
}
if !new.contains(&node) {
continue;
}
topo_list.push(node);
}
topo_list
}
pub(super) fn external_request<A: Authority + 'static>(
&mut self,
method: hyper::Method,
path: String,
query: Option<String>,
body: hyper::body::Bytes,
authority: &Arc<A>,
) -> Result<Result<String, String>, StatusCode> {
use serde_json as json;
match (&method, path.as_ref()) {
(&Method::GET, "/simple_graph") => return Ok(Ok(self.graphviz(false))),
(&Method::POST, "/simple_graphviz") => {
return Ok(Ok(json::to_string(&self.graphviz(false)).unwrap()));
}
(&Method::GET, "/graph") => return Ok(Ok(self.graphviz(true))),
(&Method::POST, "/graphviz") => {
return Ok(Ok(json::to_string(&self.graphviz(true)).unwrap()));
}
(&Method::GET, "/get_statistics") => {
return Ok(Ok(json::to_string(&self.get_statistics()).unwrap()));
}
(&Method::POST, "/get_statistics") => {
return Ok(Ok(json::to_string(&self.get_statistics()).unwrap()));
}
_ => {}
}
if self.pending_recovery.is_some() || self.workers.len() < self.quorum {
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
match (method, path.as_ref()) {
(Method::GET, "/flush_partial") => {
Ok(Ok(json::to_string(&self.flush_partial()).unwrap()))
}
(Method::POST, "/inputs") => Ok(Ok(json::to_string(&self.inputs()).unwrap())),
(Method::POST, "/outputs") => Ok(Ok(json::to_string(&self.outputs()).unwrap())),
(Method::GET, "/instances") => Ok(Ok(json::to_string(&self.get_instances()).unwrap())),
(Method::GET, "/nodes") => {
// TODO(malte): this is a pretty yucky hack, but hyper doesn't provide easy access
// to individual query variables unfortunately. We'll probably want to factor this
// out into a helper method.
let nodes = if let Some(query) = query {
let vars: Vec<_> = query.split('&').map(String::from).collect();
if let Some(n) = &vars.into_iter().find(|v| v.starts_with("w=")) {
self.nodes_on_worker(Some(&n[2..].parse().unwrap()))
} else {
self.nodes_on_worker(None)
}
} else {
// all data-flow nodes
self.nodes_on_worker(None)
};
Ok(Ok(json::to_string(
&nodes
.into_iter()
.filter_map(|ni| {
let n = &self.ingredients[ni];
if n.is_internal() {
Some((ni, n.name(), n.description(true)))
} else if n.is_base() {
Some((ni, n.name(), "Base table".to_owned()))
} else if n.is_reader() {
Some((ni, n.name(), "Leaf view".to_owned()))
} else {
None
}
})
.collect::<Vec<_>>(),
)
.unwrap()))
}
(Method::POST, "/table_builder") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| Ok(json::to_string(&self.table_builder(args)).unwrap())),
(Method::POST, "/view_builder") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| Ok(json::to_string(&self.view_builder(args)).unwrap())),
(Method::POST, "/extend_recipe") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| {
self.extend_recipe(authority, args)
.map(|r| json::to_string(&r).unwrap())
}),
(Method::POST, "/install_recipe") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| {
self.install_recipe(authority, args)
.map(|r| json::to_string(&r).unwrap())
}),
(Method::POST, "/set_security_config") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| {
self.set_security_config(args)
.map(|r| json::to_string(&r).unwrap())
}),
(Method::POST, "/create_universe") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| {
self.create_universe(args)
.map(|r| json::to_string(&r).unwrap())
}),
(Method::POST, "/remove_node") => json::from_slice(&body)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|args| {
self.remove_nodes(vec![args].as_slice())
.map(|r| json::to_string(&r).unwrap())
}),
_ => Err(StatusCode::NOT_FOUND),
}
}
pub(super) fn handle_register(&mut self, msg: CoordinationMessage) -> Result<(), io::Error> {
let (remote, read_listen_addr) = if let CoordinationPayload::Register {
addr: remote,
read_listen_addr,
..
} = msg.payload
{
(remote, read_listen_addr)
} else {
unreachable!();
};
info!(
self.log,
"new worker registered from {:?}, which listens on {:?}", msg.source, remote
);
let sender = TcpSender::connect(&remote)?;
let ws = Worker::new(sender);
self.workers.insert(msg.source, ws);
self.read_addrs.insert(msg.source, read_listen_addr);
if self.workers.len() >= self.quorum {
if let Some((recipes, recipe_version)) = self.pending_recovery.take() {
assert_eq!(self.workers.len(), self.quorum);
assert_eq!(self.recipe.version(), 0);
assert!(recipe_version + 1 >= recipes.len());
info!(self.log, "Restoring graph configuration");
self.recipe = Recipe::with_version(
recipe_version + 1 - recipes.len(),
Some(self.log.clone()),
);
for r in recipes {
self.apply_recipe(self.recipe.clone().extend(&r).unwrap())
.unwrap();
}
}
}
Ok(())
}
fn check_worker_liveness(&mut self) {
let mut any_failed = false;
// check if there are any newly failed workers
if self.last_checked_workers.elapsed() > self.healthcheck_every {
for (_addr, ws) in self.workers.iter() {
if ws.healthy && ws.last_heartbeat.elapsed() > self.heartbeat_every * 4 {
any_failed = true;
}
}
self.last_checked_workers = Instant::now();
}
// if we have newly failed workers, iterate again to find all workers that have missed >= 3
// heartbeats. This is necessary so that we correctly handle correlated failures of
// workers.
if any_failed {
let mut failed = Vec::new();
for (addr, ws) in self.workers.iter_mut() {
if ws.healthy && ws.last_heartbeat.elapsed() > self.heartbeat_every * 3 {
error!(self.log, "worker at {:?} has failed!", addr);
ws.healthy = false;
failed.push(addr.clone());
}
}
self.handle_failed_workers(failed);
}
}
fn handle_failed_workers(&mut self, failed: Vec<WorkerIdentifier>) {
// first, translate from the affected workers to affected data-flow nodes
let mut affected_nodes = Vec::new();
for wi in failed {
info!(self.log, "handling failure of worker {:?}", wi);
affected_nodes.extend(self.get_failed_nodes(&wi));
}
// then, figure out which queries are affected (and thus must be removed and added again in
// a migration)
let affected_queries = self.recipe.queries_for_nodes(affected_nodes);
let (recovery, mut original) = self.recipe.make_recovery(affected_queries);
// activate recipe
self.apply_recipe(recovery.clone())
.expect("failed to apply recovery recipe");
// we must do this *after* the migration, since the migration itself modifies the recipe in
// `recovery`, and we currently need to clone it here.
let tmp = self.recipe.clone();
original.set_prior(tmp.clone());
// somewhat awkward, but we must replace the stale `SqlIncorporator` state in `original`
original.set_sql_inc(tmp.sql_inc().clone());
// back to original recipe, which should add the query again
self.apply_recipe(original)
.expect("failed to activate original recipe");
}
pub(super) fn handle_heartbeat(&mut self, msg: CoordinationMessage) -> Result<(), io::Error> {
match self.workers.get_mut(&msg.source) {
None => crit!(
self.log,
"got heartbeat for unknown worker {:?}",
msg.source
),
Some(ref mut ws) => {
ws.last_heartbeat = Instant::now();
}
}
self.check_worker_liveness();
Ok(())
}
/// Construct `ControllerInner` with a specified listening interface
pub(super) fn new(
log: slog::Logger,
state: ControllerState,
drx: tokio::sync::mpsc::UnboundedReceiver<ControlReplyPacket>,
) -> Self {
let mut g = petgraph::Graph::new();
let source = g.add_node(node::Node::new(
"source",
&["because-type-inference"],
node::special::Source,
));
let mut materializations = Materializations::new(&log);
if !state.config.partial_enabled {
materializations.disable_partial()
}
materializations.set_frontier_strategy(state.config.frontier_strategy);
let cc = Arc::new(ChannelCoordinator::new());
assert_ne!(state.config.quorum, 0);
let pending_recovery = if !state.recipes.is_empty() {
Some((state.recipes, state.recipe_version))
} else {
None
};
let mut recipe = Recipe::blank(Some(log.clone()));
recipe.enable_reuse(state.config.reuse);
ControllerInner {
ingredients: g,
source,
ndomains: 0,
materializations,
sharding: state.config.sharding,
domain_config: state.config.domain_config,
persistence: state.config.persistence,
heartbeat_every: state.config.heartbeat_every,
healthcheck_every: state.config.healthcheck_every,
recipe,
quorum: state.config.quorum,
log,
domains: Default::default(),
domain_nodes: Default::default(),
channel_coordinator: cc,
epoch: state.epoch,
remap: HashMap::default(),
read_addrs: HashMap::default(),
workers: HashMap::default(),
pending_recovery,
last_checked_workers: Instant::now(),
replies: DomainReplies(drx),
}
}
/// Controls the persistence mode, and parameters related to persistence.
///
/// Three modes are available:
///
/// 1. `DurabilityMode::Permanent`: all writes to base nodes should be written to disk.
/// 2. `DurabilityMode::DeleteOnExit`: all writes are written to disk, but the log is
/// deleted once the `Controller` is dropped. Useful for tests.
/// 3. `DurabilityMode::MemoryOnly`: no writes to disk, store all writes in memory.
/// Useful for baseline numbers.
///
/// `queue_capacity` indicates the number of packets that should be buffered until
/// flushing, and `flush_timeout` indicates the length of time to wait before flushing
/// anyway.
///
/// Must be called before any domains have been created.
#[allow(unused)]
fn with_persistence_options(&mut self, params: PersistenceParameters) {
assert_eq!(self.ndomains, 0);
self.persistence = params;
}
pub(in crate::controller) fn place_domain(
&mut self,
idx: DomainIndex,
num_shards: Option<usize>,
log: &Logger,
nodes: Vec<(NodeIndex, bool)>,
) -> DomainHandle {
// TODO: can we just redirect all domain traffic through the worker's connection?
let mut assignments = Vec::new();
let mut nodes = Some(
nodes
.into_iter()
.map(|(ni, _)| {
let node = self.ingredients.node_weight_mut(ni).unwrap().take();
node.finalize(&self.ingredients)
})
.map(|nd| (nd.local_addr(), cell::RefCell::new(nd)))
.collect(),
);
// TODO(malte): simple round-robin placement for the moment
let mut wi = self.workers.iter_mut();
// Send `AssignDomain` to each shard of the given domain
for i in 0..num_shards.unwrap_or(1) {
let nodes = if i == num_shards.unwrap_or(1) - 1 {
nodes.take().unwrap()
} else {
nodes.clone().unwrap()
};
let domain = DomainBuilder {
index: idx,
shard: if num_shards.is_some() { Some(i) } else { None },
nshards: num_shards.unwrap_or(1),
config: self.domain_config.clone(),
nodes,
persistence_parameters: self.persistence.clone(),
};
let (identifier, w) = loop {
if let Some((i, w)) = wi.next() {
if w.healthy {
break (*i, w);
}
} else {
wi = self.workers.iter_mut();
}
};
// send domain to worker
info!(
log,
"sending domain {}.{} to worker {:?}",
domain.index.index(),
domain.shard.unwrap_or(0),
w.sender.peer_addr()
);
let src = w.sender.local_addr().unwrap();
w.sender
.send(CoordinationMessage {
epoch: self.epoch,
source: src,
payload: CoordinationPayload::AssignDomain(domain),
})
.unwrap();
assignments.push(identifier);
}
// Wait for all the domains to acknowledge.
let mut txs = HashMap::new();
let mut announce = Vec::new();
let fut = self.replies.read_n_domain_replies(num_shards.unwrap_or(1));
let replies = futures_executor::block_on(fut);
for r in replies {
match r {
ControlReplyPacket::Booted(shard, addr) => {
self.channel_coordinator.insert_remote((idx, shard), addr);
announce.push(DomainDescriptor::new(idx, shard, addr));
txs.insert(
shard,
self.channel_coordinator
.builder_for(&(idx, shard))
.unwrap()
.build_sync()
.unwrap(),
);
}
crp => {
unreachable!("got unexpected control reply packet: {:?}", crp);
}
}
}
// Tell all workers about the new domain(s)
// TODO(jon): figure out how much of the below is still true
// TODO(malte): this is a hack, and not an especially neat one. In response to a
// domain boot message, we broadcast information about this new domain to all
// workers, which inform their ChannelCoordinators about it. This is required so
// that domains can find each other when starting up.
// Moreover, it is required for us to do this *here*, since this code runs on
// the thread that initiated the migration, and which will query domains to ask
// if they're ready. No domain will be ready until it has found its neighbours,
// so by sending out the information here, we ensure that we cannot deadlock
// with the migration waiting for a domain to become ready when trying to send
// the information. (We used to do this in the controller thread, with the
// result of a nasty deadlock.)
for endpoint in self.workers.values_mut() {
for &dd in &announce {
endpoint
.sender
.send(CoordinationMessage {
epoch: self.epoch,
source: endpoint.sender.local_addr().unwrap(),
payload: CoordinationPayload::DomainBooted(dd),
})
.unwrap();
}
}
let shards = assignments
.into_iter()
.enumerate()
.map(|(i, worker)| {
let tx = txs.remove(&i).unwrap();
DomainShardHandle { worker, tx }
})
.collect();
DomainHandle {
idx,
shards,
log: log.clone(),
}
}
/// Set the `Logger` to use for internal log messages.
///
/// By default, all log messages are discarded.
#[allow(unused)]
fn log_with(&mut self, log: slog::Logger) {
self.log = log;
self.materializations.set_logger(&self.log);
}
/// Adds a new user universe.
/// User universes automatically enforce security policies.
fn add_universe<F, T>(&mut self, context: HashMap<String, DataType>, f: F) -> T
where
F: FnOnce(&mut Migration) -> T,
{
info!(self.log, "starting migration: new soup universe");
let miglog = self.log.new(o!());
let mut m = Migration {
mainline: self,
added: Default::default(),
columns: Default::default(),
readers: Default::default(),
context,
start: time::Instant::now(),
log: miglog,
};
let r = f(&mut m);
m.commit();
r
}
/// Perform a new query schema migration.
// crate viz for tests
pub(crate) fn migrate<F, T>(&mut self, f: F) -> T
where
F: FnOnce(&mut Migration) -> T,
{
info!(self.log, "starting migration");
let miglog = self.log.new(o!());
let mut m = Migration {
mainline: self,
added: Default::default(),
columns: Default::default(),
readers: Default::default(),
context: Default::default(),
start: time::Instant::now(),
log: miglog,
};
let r = f(&mut m);
m.commit();
r
}
#[cfg(test)]
pub(crate) fn graph(&self) -> &Graph {
&self.ingredients
}
/// Get a Vec of all known input nodes.
///
/// Input nodes are here all nodes of type `Table`. The addresses returned by this function will
/// all have been returned as a key in the map from `commit` at some point in the past.
fn inputs(&self) -> BTreeMap<String, NodeIndex> {
self.ingredients
.neighbors_directed(self.source, petgraph::EdgeDirection::Outgoing)
.map(|n| {
let base = &self.ingredients[n];
assert!(base.is_base());
(base.name().to_owned(), n)
})
.collect()
}
/// Get a Vec of all known output nodes.
///
/// Output nodes here refers to nodes of type `Reader`, which is the nodes created in response
/// to calling `.maintain` or `.stream` for a node during a migration.
fn outputs(&self) -> BTreeMap<String, NodeIndex> {
self.ingredients
.externals(petgraph::EdgeDirection::Outgoing)
.filter_map(|n| {
let name = self.ingredients[n].name().to_owned();
self.ingredients[n]
.with_reader(|r| {
// we want to give the the node address that is being materialized not that of
// the reader node itself.
(name, r.is_for())
})
.ok()
})
.collect()
}
fn find_view_for(&self, node: NodeIndex, name: &str) -> Option<NodeIndex> {
// reader should be a child of the given node. however, due to sharding, it may not be an
// *immediate* child. furthermore, once we go beyond depth 1, we may accidentally hit an
// *unrelated* reader node. to account for this, readers keep track of what node they are
// "for", and we simply search for the appropriate reader by that metric. since we know
// that the reader must be relatively close, a BFS search is the way to go.
let mut bfs = Bfs::new(&self.ingredients, node);
while let Some(child) = bfs.next(&self.ingredients) {
if self.ingredients[child]
.with_reader(|r| r.is_for() == node)
.unwrap_or(false)
&& self.ingredients[child].name() == name
{
return Some(child);
}
}
None
}
/// Obtain a `ViewBuilder` that can be sent to a client and then used to query a given
/// (already maintained) reader node called `name`.
fn view_builder(&self, name: &str) -> Option<ViewBuilder> {
// first try to resolve the node via the recipe, which handles aliasing between identical
// queries.
let node = match self.recipe.node_addr_for(name) {
Ok(ni) => ni,
Err(_) => {
// if the recipe doesn't know about this query, traverse the graph.
// we need this do deal with manually constructed graphs (e.g., in tests).
*self.outputs().get(name)?
}
};
let name = match self.recipe.resolve_alias(name) {
None => name,
Some(alias) => alias,
};
self.find_view_for(node, name).map(|r| {
let domain = self.ingredients[r].domain();
let columns = self.ingredients[r].fields().to_vec();
let schema = self.view_schema(r);
let shards = (0..self.domains[&domain].shards())
.map(|i| self.read_addrs[&self.domains[&domain].assignment(i)])
.collect();
ViewBuilder {
node: r,
columns,
schema,
shards,
}
})
}
fn view_schema(&self, view_ni: NodeIndex) -> Option<Vec<ColumnSpecification>> {
let n = &self.ingredients[view_ni];
let schema: Vec<_> = (0..n.fields().len())
.map(|i| schema::column_schema(&self.ingredients, view_ni, &self.recipe, i, &self.log))
.collect();
if schema.iter().any(Option::is_none) {
None
} else {
Some(schema.into_iter().map(Option::unwrap).collect())
}
}
/// Obtain a TableBuild that can be used to construct a Table to perform writes and deletes
/// from the given named base node.
fn table_builder(&self, base: &str) -> Option<TableBuilder> {
let ni = match self.recipe.node_addr_for(base) {
Ok(ni) => ni,
Err(_) => *self.inputs().get(base)?,
};
let node = &self.ingredients[ni];
trace!(self.log, "creating table"; "for" => base);
let mut key = self.ingredients[ni]
.suggest_indexes(ni)
.remove(&ni)
.unwrap_or_else(Vec::new);
let mut is_primary = false;
if key.is_empty() {
if let Sharding::ByColumn(col, _) = self.ingredients[ni].sharded_by() {
key = vec![col];
}
} else {
is_primary = true;
}
let txs = (0..self.domains[&node.domain()].shards())
.map(|i| {
self.channel_coordinator
.get_addr(&(node.domain(), i))
.unwrap()
})
.collect();
let base_operator = node
.get_base()
.expect("asked to get table for non-base node");
let columns: Vec<String> = node
.fields()
.iter()
.enumerate()
.filter(|&(n, _)| !base_operator.get_dropped().contains_key(n))
.map(|(_, s)| s.clone())
.collect();
assert_eq!(
columns.len(),
node.fields().len() - base_operator.get_dropped().len()
);
let schema = self.recipe.schema_for(base).map(|s| match s {
Schema::Table(s) => s,
_ => panic!("non-base schema {:?} returned for table '{}'", s, base),
});
Some(TableBuilder {
txs,
ni: node.global_addr(),
addr: node.local_addr(),
key,
key_is_primary: is_primary,
dropped: base_operator.get_dropped(),
table_name: node.name().to_owned(),
columns,
schema,
})
}
/// Get statistics about the time spent processing different parts of the graph.
fn get_statistics(&mut self) -> GraphStats {
trace!(self.log, "asked to get statistics");
let log = &self.log;
let workers = &self.workers;
let replies = &mut self.replies;
// TODO: request stats from domains in parallel.
let domains = self
.domains
.iter_mut()
.flat_map(|(&di, s)| {
trace!(log, "requesting stats from domain"; "di" => di.index());
s.send_to_healthy(Box::new(Packet::GetStatistics), workers)
.unwrap();
futures_executor::block_on(replies.wait_for_statistics(&s))
.into_iter()
.enumerate()
.map(move |(i, s)| ((di, i), s))
})
.collect();
GraphStats { domains }
}
fn get_instances(&self) -> Vec<(WorkerIdentifier, bool, Duration)> {
self.workers
.iter()
.map(|(&id, ref status)| (id, status.healthy, status.last_heartbeat.elapsed()))
.collect()
}
fn flush_partial(&mut self) -> u64 {
// get statistics for current domain sizes
// and evict all state from partial nodes
let workers = &self.workers;
let replies = &mut self.replies;
let to_evict: Vec<_> = self
.domains
.iter_mut()
.map(|(di, s)| {
s.send_to_healthy(Box::new(Packet::GetStatistics), workers)
.unwrap();
let to_evict: Vec<(NodeIndex, u64)> =
futures_executor::block_on(replies.wait_for_statistics(&s))
.into_iter()
.flat_map(move |(_, node_stats)| {
node_stats
.into_iter()
.filter_map(|(ni, ns)| match ns.materialized {
MaterializationStatus::Partial { .. } => {
Some((ni, ns.mem_size))
}
_ => None,
})
})
.collect();
(*di, to_evict)
})
.collect();
let mut total_evicted = 0;
for (di, nodes) in to_evict {
for (ni, bytes) in nodes {
let na = self.ingredients[ni].local_addr();
self.domains
.get_mut(&di)
.unwrap()
.send_to_healthy(
Box::new(Packet::Evict {
node: Some(na),
num_bytes: bytes as usize,
}),
workers,
)
.expect("failed to send domain flush message");
total_evicted += bytes;
}
}
warn!(
self.log,
"flushed {} bytes of partial domain state", total_evicted
);
total_evicted
}
pub(super) fn create_universe(
&mut self,
context: HashMap<String, DataType>,
) -> Result<(), String> {
let log = self.log.clone();
let mut r = self.recipe.clone();
let groups = self.recipe.security_groups();
let mut universe_groups = HashMap::new();
let uid = context
.get("id")
.expect("Universe context must have id")
.clone();
let uid = &[uid];
if context.get("group").is_none() {
let x = Arc::new(Mutex::new(HashMap::new()));
for g in groups {
// TODO: this should use external APIs through noria::ControllerHandle
// TODO: can this move to the client entirely?
let rgb: Option<ViewBuilder> = self.view_builder(&g);
// TODO: using block_on here _only_ works because View::lookup just waits on a
// channel, which doesn't use anything except the pure executor
let mut view = rgb.map(|rgb| rgb.build(x.clone()).unwrap()).unwrap();
let my_groups: Vec<DataType> = futures_executor::block_on(view.lookup(uid, true))
.unwrap()
.iter()
.map(|v| v[1].clone())
.collect();
universe_groups.insert(g, my_groups);
}
}
self.add_universe(context.clone(), |mut mig| {
r.next();
match r.create_universe(&mut mig, universe_groups) {
Ok(ar) => {
info!(log, "{} expressions added", ar.expressions_added);
info!(log, "{} expressions removed", ar.expressions_removed);
Ok(())
}
Err(e) => {
crit!(log, "failed to create universe: {:?}", e);
Err("failed to create universe".to_owned())
}
}
.unwrap();
});
self.recipe = r;