-
Notifications
You must be signed in to change notification settings - Fork 241
/
mod.rs
1507 lines (1311 loc) · 53.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 channel::poll::{PollEvent, PollingLoop, ProcessResult, RpcPollEvent, RpcPollingLoop};
use channel::tcp::TcpSender;
use channel;
use dataflow::prelude::*;
use dataflow::{backlog, checktable, node, payload, DomainConfig, PersistenceParameters, Readers};
use dataflow::ops::base::Base;
use dataflow::statistics::GraphStats;
use worker::Worker;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::error::Error;
use std::io::Write;
use std::net::{IpAddr, SocketAddr};
use std::time::{Duration, Instant};
use std::sync::{Arc, Barrier, Mutex};
use std::sync::mpsc;
use std::{fmt, io, thread, time};
use futures::{Future, Stream};
use hyper::Client;
use mio::net::TcpListener;
use petgraph;
use petgraph::visit::Bfs;
use petgraph::graph::NodeIndex;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json;
use slog;
use tarpc::sync::client::{self, ClientExt};
use tokio_core::reactor::Core;
pub mod domain_handle;
pub mod keys;
pub mod migrate;
pub(crate) mod recipe;
pub(crate) mod sql;
mod getter;
mod mir_to_flow;
mod mutator;
mod web;
use self::domain_handle::DomainHandle;
use coordination::{CoordinationMessage, CoordinationPayload};
pub use self::mutator::{Mutator, MutatorBuilder, MutatorError};
pub use self::getter::{Getter, ReadQuery, ReadReply, RemoteGetter, RemoteGetterBuilder};
use self::payload::{EgressForBase, IngressFromBase};
pub type WorkerIdentifier = SocketAddr;
pub type WorkerEndpoint = Arc<Mutex<TcpSender<CoordinationMessage>>>;
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
}}
}
#[derive(Clone)]
struct WorkerStatus {
healthy: bool,
last_heartbeat: Instant,
sender: Arc<Mutex<TcpSender<CoordinationMessage>>>,
}
impl WorkerStatus {
pub fn new(sender: Arc<Mutex<TcpSender<CoordinationMessage>>>) -> Self {
WorkerStatus {
healthy: true,
last_heartbeat: Instant::now(),
sender,
}
}
}
/// Used to construct a controller.
pub struct ControllerBuilder {
sharding_enabled: bool,
domain_config: DomainConfig,
persistence: PersistenceParameters,
materializations: migrate::materialization::Materializations,
listen_addr: IpAddr,
heartbeat_every: Duration,
healthcheck_every: Duration,
nworkers: usize,
internal_port: u16,
external_port: u16,
log: slog::Logger,
}
impl Default for ControllerBuilder {
fn default() -> Self {
let log = slog::Logger::root(slog::Discard, o!());
Self {
sharding_enabled: true,
domain_config: DomainConfig {
concurrent_replays: 512,
replay_batch_timeout: time::Duration::from_millis(1),
replay_batch_size: 32,
},
persistence: Default::default(),
materializations: migrate::materialization::Materializations::new(&log),
listen_addr: "127.0.0.1".parse().unwrap(),
heartbeat_every: Duration::from_secs(1),
healthcheck_every: Duration::from_secs(10),
internal_port: if cfg!(test) { 0 } else { 8000 },
external_port: if cfg!(test) { 0 } else { 9000 },
nworkers: 0,
log,
}
}
}
impl ControllerBuilder {
/// Set the maximum number of concurrent partial replay requests a domain can have outstanding
/// at any given time.
///
/// Note that this number *must* be greater than the width (in terms of number of ancestors) of
/// the widest union in the graph, otherwise a deadlock will occur.
pub fn set_max_concurrent_replay(&mut self, n: usize) {
self.domain_config.concurrent_replays = n;
}
/// Set the maximum number of partial replay responses that can be aggregated into a single
/// replay batch.
pub fn set_partial_replay_batch_size(&mut self, n: usize) {
self.domain_config.replay_batch_size = n;
}
/// Set the longest time a partial replay response can be delayed.
pub fn set_partial_replay_batch_timeout(&mut self, t: time::Duration) {
self.domain_config.replay_batch_timeout = t;
}
/// Set the persistence parameters used by the system.
pub fn set_persistence(&mut self, p: PersistenceParameters) {
self.persistence = p;
}
/// Disable partial materialization for all subsequent migrations
pub fn disable_partial(&mut self) {
self.materializations.disable_partial();
}
/// Disable sharding for all subsequent migrations
pub fn disable_sharding(&mut self) {
self.sharding_enabled = false;
}
/// Set how many workers the controller should wait for before starting. More workers can join
/// later, but they won't be assigned any of the initial domains.
pub fn set_nworkers(&mut self, workers: usize) {
self.nworkers = workers;
}
#[cfg(test)]
pub fn build_inner(self) -> ControllerInner {
ControllerInner::from_builder(self)
}
/// Build a controller, and return a Blender to provide access to it.
pub fn build(self) -> Blender {
// TODO(fintelia): Don't hard code addresses in this function.
let internal_addr = SocketAddr::new("127.0.0.1".parse().unwrap(), self.internal_port);
let external_addr = SocketAddr::new("127.0.0.1".parse().unwrap(), self.external_port);
let nworkers = self.nworkers;
let inner = Arc::new(Mutex::new(ControllerInner::from_builder(self)));
let addr = ControllerInner::listen_external(inner.clone(), external_addr);
ControllerInner::listen_internal(inner, internal_addr, nworkers);
Blender {
url: format!("http://{}", addr),
}
}
}
/// `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 struct ControllerInner {
ingredients: petgraph::Graph<node::Node, Edge>,
source: NodeIndex,
ndomains: usize,
checktable: checktable::CheckTableClient,
checktable_addr: SocketAddr,
sharding_enabled: bool,
domain_config: DomainConfig,
/// Parameters for persistence code.
persistence: PersistenceParameters,
materializations: migrate::materialization::Materializations,
domains: HashMap<DomainIndex, DomainHandle>,
channel_coordinator: Arc<ChannelCoordinator>,
debug_channel: Option<SocketAddr>,
listen_addr: IpAddr,
read_listen_addr: SocketAddr,
readers: Readers,
/// Map from worker address to the address the worker is listening on for reads.
read_addrs: HashMap<WorkerIdentifier, SocketAddr>,
workers: HashMap<WorkerIdentifier, WorkerStatus>,
/// State between migrations
deps: HashMap<DomainIndex, (IngressFromBase, EgressForBase)>,
remap: HashMap<DomainIndex, HashMap<NodeIndex, IndexPair>>,
heartbeat_every: Duration,
healthcheck_every: Duration,
last_checked_workers: Instant,
log: slog::Logger,
}
impl ControllerInner {
/// Listen for messages from clients.
pub fn listen_external(
controller: Arc<Mutex<ControllerInner>>,
addr: SocketAddr,
) -> SocketAddr {
use rustful::{Context, Handler, Response, Server, TreeRouter};
enum C<Q, R> {
OpMut(Box<Fn(&mut ControllerInner, Q) -> R + Send + Sync>),
Op(Box<Fn(&ControllerInner, Q) -> R + Send + Sync>),
}
impl<Q: DeserializeOwned + 'static, R: Serialize + 'static> Handler for C<Q, R> {
fn handle_request(&self, ctx: Context, res: Response) {
let controller = ctx.global.get::<Arc<Mutex<ControllerInner>>>().unwrap();
let mut controller = controller.lock().unwrap();
let q = serde_json::from_reader(ctx.body).unwrap();
let r = match *self {
C::Op(ref f) => f(&mut controller, q),
C::OpMut(ref f) => f(&mut controller, q),
};
res.send(serde_json::to_string(&r).unwrap());
}
}
impl<Q: DeserializeOwned + 'static, R: Serialize + 'static> C<Q, R> {
fn handler(self) -> Box<Handler> {
Box::new(self) as Box<Handler>
}
}
let handlers = insert_routes!{
TreeRouter::new() => {
"inputs" => Post: C::Op(Box::new(Self::inputs)).handler(),
"outputs" => Post: C::Op(Box::new(Self::outputs)).handler(),
"mutator_builder" => Post: C::Op(Box::new(Self::get_mutator_builder)).handler(),
"getter_builder" => Post: C::Op(Box::new(Self::get_getter_builder)).handler(),
"recover" => Post: C::OpMut(Box::new(Self::recover)).handler(),
"get_statistics" => Post: C::OpMut(Box::new(Self::get_statistics)).handler(),
"install_recipe" => Post: C::OpMut(Box::new(Self::install_recipe)).handler(),
"graphviz" => Post: C::Op(Box::new(Self::graphviz)).handler(),
}
};
let listen = Server {
handlers,
host: addr.into(),
server: "netsoup".to_owned(),
threads: Some(1),
content_type: "application/json".parse().unwrap(),
global: Box::new(controller).into(),
..Server::default()
}.run()
.unwrap();
// Bit of a dance to return socket while keeping the server running in another thread.
let socket = listen.socket.clone();
thread::spawn(move || drop(listen));
socket
}
/// Listen for messages from workers.
pub fn listen_internal(
controller: Arc<Mutex<ControllerInner>>,
addr: SocketAddr,
nworkers: usize,
) {
use channel::poll::ProcessResult;
use mio::net::TcpListener;
use std::str::FromStr;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let mut workers_arrived = false;
let mut pl: PollingLoop<CoordinationMessage> = PollingLoop::new(addr);
pl.run_polling_loop(|e| {
let mut inner = controller.lock().unwrap();
match e {
PollEvent::Process(ref msg) => {
trace!(inner.log, "Received {:?}", msg);
let process = match msg.payload {
CoordinationPayload::Register {
ref addr,
ref read_listen_addr,
} => inner.handle_register(msg, addr, read_listen_addr.clone()),
CoordinationPayload::Heartbeat => inner.handle_heartbeat(msg),
CoordinationPayload::DomainBooted(ref domain, ref addr) => Ok(()),
_ => unimplemented!(),
};
match process {
Ok(_) => (),
Err(e) => {
error!(inner.log, "failed to handle message {:?}: {:?}", msg, e)
}
}
}
PollEvent::ResumePolling(timeout) => *timeout = Some(inner.healthcheck_every),
PollEvent::Timeout => (),
}
// TODO(fintelia): Avoid checking worker liveness more frequently than
// inner.healthcheck_every.
inner.check_worker_liveness();
if !workers_arrived && inner.workers.len() == nworkers {
workers_arrived = true;
tx.send(());
}
ProcessResult::KeepPolling
});
});
// Wait for enough workers to join.
let _ = rx.recv();
}
fn handle_register(
&mut self,
msg: &CoordinationMessage,
remote: &SocketAddr,
read_listen_addr: SocketAddr,
) -> Result<(), io::Error> {
info!(
self.log,
"new worker registered from {:?}, which listens on {:?}",
msg.source,
remote
);
let sender = Arc::new(Mutex::new(TcpSender::connect(remote, None)?));
let ws = WorkerStatus::new(sender.clone());
self.workers.insert(msg.source.clone(), ws);
self.read_addrs.insert(msg.source.clone(), read_listen_addr);
Ok(())
}
fn check_worker_liveness(&mut self) {
if self.last_checked_workers.elapsed() > self.healthcheck_every {
for (addr, ws) in self.workers.iter_mut() {
if ws.healthy && ws.last_heartbeat.elapsed() > self.heartbeat_every * 3 {
warn!(self.log, "worker at {:?} has failed!", addr);
ws.healthy = false;
}
}
self.last_checked_workers = Instant::now();
}
}
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();
}
}
Ok(())
}
/// Construct `Controller` with a specified listening interface
pub fn from_builder(builder: ControllerBuilder) -> Self {
let mut g = petgraph::Graph::new();
let source = g.add_node(node::Node::new(
"source",
&["because-type-inference"],
node::special::Source,
true,
));
let addr = SocketAddr::new(builder.listen_addr.clone(), 0);
let checktable_addr = checktable::service::CheckTableServer::start(addr.clone());
let checktable =
checktable::CheckTableClient::connect(checktable_addr, client::Options::default())
.unwrap();
let readers: Readers = Arc::default();
let readers_clone = readers.clone();
let read_polling_loop = RpcPollingLoop::new(addr.clone());
let read_listen_addr = read_polling_loop.get_listener_addr().unwrap();
thread::spawn(move || {
Worker::serve_reads(read_polling_loop, readers_clone)
});
ControllerInner {
ingredients: g,
source: source,
ndomains: 0,
checktable,
checktable_addr,
sharding_enabled: builder.sharding_enabled,
materializations: builder.materializations,
domain_config: builder.domain_config,
persistence: builder.persistence,
listen_addr: builder.listen_addr,
heartbeat_every: builder.heartbeat_every,
healthcheck_every: builder.healthcheck_every,
log: builder.log,
domains: Default::default(),
channel_coordinator: Arc::new(ChannelCoordinator::new()),
debug_channel: None,
deps: HashMap::default(),
remap: HashMap::default(),
readers,
read_listen_addr,
read_addrs: HashMap::default(),
workers: HashMap::default(),
last_checked_workers: Instant::now(),
}
}
/// Use a debug channel. This function may only be called once because the receiving end it
/// returned.
pub fn create_debug_channel(&mut self) -> TcpListener {
assert!(self.debug_channel.is_none());
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let listener = TcpListener::bind(&addr).unwrap();
self.debug_channel = Some(listener.local_addr().unwrap());
listener
}
/// 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.
pub fn with_persistence_options(&mut self, params: PersistenceParameters) {
assert_eq!(self.ndomains, 0);
self.persistence = params;
}
/// Set the `Logger` to use for internal log messages.
///
/// By default, all log messages are discarded.
pub fn log_with(&mut self, log: slog::Logger) {
self.log = log;
self.materializations.set_logger(&self.log);
}
/// Start setting up a new `Migration`.
#[deprecated]
pub fn start_migration(&mut self) -> Migration {
info!(self.log, "starting migration");
let miglog = self.log.new(o!());
Migration {
mainline: self,
added: Default::default(),
columns: Default::default(),
readers: Default::default(),
start: time::Instant::now(),
log: miglog,
}
}
/// Perform a new query schema migration.
pub 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(),
start: time::Instant::now(),
log: miglog,
};
let r = f(&mut m);
m.commit();
r
}
/// Initiaties log recovery by sending a
/// StartRecovery packet to each base node domain.
pub fn recover(&mut self, _: ()) {
info!(self.log, "Recovering from log");
for (_name, index) in self.inputs(()).iter() {
let node = &self.ingredients[*index];
let domain = self.domains.get_mut(&node.domain()).unwrap();
domain.send(box payload::Packet::StartRecovery).unwrap();
domain.wait_for_ack().unwrap();
}
}
/// Get a boxed function which can be used to validate tokens.
pub fn get_validator(&self) -> Box<Fn(&checktable::Token) -> bool> {
let checktable =
checktable::CheckTableClient::connect(self.checktable_addr, client::Options::default())
.unwrap();
Box::new(move |t: &checktable::Token| {
checktable.validate_token(t.clone()).unwrap()
})
}
#[cfg(test)]
pub fn graph(&self) -> &Graph {
&self.ingredients
}
/// Get a Vec of all known input nodes.
///
/// Input nodes are here all nodes of type `Base`. 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.
pub 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_internal());
assert!(base.get_base().is_some());
(base.name().to_owned(), n.into())
})
.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.
pub 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())
})
})
.collect()
}
fn find_getter_for(&self, node: NodeIndex) -> 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.
// presumably only
let mut bfs = Bfs::new(&self.ingredients, node);
let mut reader = None;
while let Some(child) = bfs.next(&self.ingredients) {
if self.ingredients[child]
.with_reader(|r| r.is_for() == node)
.unwrap_or(false)
{
reader = Some(child);
break;
}
}
reader
}
/// Obtain a `RemoteGetterBuilder` that can be sent to a client and then used to query a given
/// (already maintained) reader node.
pub fn get_getter_builder(&self, node: NodeIndex) -> Option<RemoteGetterBuilder> {
self.find_getter_for(node).map(|r| {
let domain = self.ingredients[r].domain();
let shards = (0..self.domains[&domain].shards())
.map(|i| match self.domains[&domain].assignment(i) {
Some(worker) => self.read_addrs[&worker].clone(),
None => self.read_listen_addr.clone(),
})
.collect();
RemoteGetterBuilder { node: r, shards }
})
}
/// Obtain a MutatorBuild that can be used to construct a Mutator to perform writes and deletes
/// from the given base node.
pub fn get_mutator_builder(&self, base: NodeIndex) -> MutatorBuilder {
let node = &self.ingredients[base];
trace!(self.log, "creating mutator"; "for" => base.index());
let mut key = self.ingredients[base]
.suggest_indexes(base)
.remove(&base)
.map(|(c, _)| c)
.unwrap_or_else(Vec::new);
let mut is_primary = false;
if key.is_empty() {
if let Sharding::ByColumn(col) = self.ingredients[base].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 num_fields = node.fields().len();
let base_operator = node.get_base()
.expect("asked to get mutator for non-base node");
MutatorBuilder {
txs,
addr: (*node.local_addr()).into(),
key: key,
key_is_primary: is_primary,
transactional: self.ingredients[base].is_transactional(),
dropped: base_operator.get_dropped(),
expected_columns: num_fields - base_operator.get_dropped().len(),
is_local: true,
}
}
/// Get statistics about the time spent processing different parts of the graph.
pub fn get_statistics(&mut self, _: ()) -> GraphStats {
// TODO: request stats from domains in parallel.
let domains = self.domains
.iter_mut()
.flat_map(|(di, s)| {
s.send(box payload::Packet::GetStatistics).unwrap();
s.wait_for_statistics()
.unwrap()
.into_iter()
.enumerate()
.map(move |(i, (domain_stats, node_stats))| {
let node_map = node_stats
.into_iter()
.map(|(ni, ns)| (ni.into(), ns))
.collect();
((di.clone(), i), (domain_stats, node_map))
})
})
.collect();
GraphStats { domains: domains }
}
pub fn install_recipe(&mut self, r_txt: String) {
self.migrate(|mig| {
use controller::recipe::Recipe;
let mut r = Recipe::from_str(&r_txt, None).unwrap();
assert!(r.activate(mig, false).is_ok());
});
}
#[cfg(test)]
pub fn get_mutator(&self, base: NodeIndex) -> Mutator {
self.get_mutator_builder(base)
.build("127.0.0.1:0".parse().unwrap())
}
#[cfg(test)]
pub fn get_getter(&self, node: NodeIndex) -> Option<RemoteGetter> {
self.get_getter_builder(node).map(|g| g.build())
}
pub fn graphviz(&self, _: ()) -> 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);
s.push_str("node [shape=record, fontsize=10]\n");
// node descriptions.
for index in self.ingredients.node_indices() {
indentln(&mut s);
s.push_str(&format!("{}", index.index()));
s.push_str(&self.ingredients[index].describe(index));
}
// edges.
for (_, edge) in self.ingredients.raw_edges().iter().enumerate() {
indentln(&mut s);
s.push_str(&format!(
"{} -> {}",
edge.source().index(),
edge.target().index()
));
s.push_str("\n");
}
// footer.
s.push_str("}}");
s
}
}
#[derive(Clone)]
enum ColumnChange {
Add(String, DataType),
Drop(usize),
}
/// A `Migration` encapsulates a number of changes to the Soup data flow graph.
///
/// Only one `Migration` can be in effect at any point in time. No changes are made to the running
/// graph until the `Migration` is committed (using `Migration::commit`).
pub struct Migration<'a> {
mainline: &'a mut ControllerInner,
added: Vec<NodeIndex>,
columns: Vec<(NodeIndex, ColumnChange)>,
readers: HashMap<NodeIndex, NodeIndex>,
start: time::Instant,
log: slog::Logger,
}
impl<'a> Migration<'a> {
/// Add the given `Ingredient` to the Soup.
///
/// The returned identifier can later be used to refer to the added ingredient.
/// Edges in the data flow graph are automatically added based on the ingredient's reported
/// `ancestors`.
pub fn add_ingredient<S1, FS, S2, I>(&mut self, name: S1, fields: FS, mut i: I) -> NodeIndex
where
S1: ToString,
S2: ToString,
FS: IntoIterator<Item = S2>,
I: Ingredient + Into<NodeOperator>,
{
i.on_connected(&self.mainline.ingredients);
let parents = i.ancestors();
let transactional = !parents.is_empty()
&& parents
.iter()
.all(|&p| self.mainline.ingredients[p].is_transactional());
// add to the graph
let ni = self.mainline.ingredients.add_node(node::Node::new(
name.to_string(),
fields,
i.into(),
transactional,
));
info!(self.log,
"adding new node";
"node" => ni.index(),
"type" => format!("{:?}", self.mainline.ingredients[ni])
);
// keep track of the fact that it's new
self.added.push(ni);
// insert it into the graph
if parents.is_empty() {
self.mainline
.ingredients
.add_edge(self.mainline.source, ni, ());
} else {
for parent in parents {
self.mainline.ingredients.add_edge(parent, ni, ());
}
}
// and tell the caller its id
ni.into()
}
/// Add a transactional base node to the graph
pub fn add_transactional_base<S1, FS, S2>(
&mut self,
name: S1,
fields: FS,
mut b: Base,
) -> NodeIndex
where
S1: ToString,
S2: ToString,
FS: IntoIterator<Item = S2>,
{
b.on_connected(&self.mainline.ingredients);
let b: NodeOperator = b.into();
// add to the graph
let ni = self.mainline
.ingredients
.add_node(node::Node::new(name.to_string(), fields, b, true));
info!(self.log,
"adding new node";
"node" => ni.index(),
"type" => format!("{:?}", self.mainline.ingredients[ni])
);
// keep track of the fact that it's new
self.added.push(ni);
// insert it into the graph
self.mainline
.ingredients
.add_edge(self.mainline.source, ni, ());
// and tell the caller its id
ni.into()
}
/// Add a new column to a base node.
///
/// Note that a default value must be provided such that old writes can be converted into this
/// new type.
pub fn add_column<S: ToString>(
&mut self,
node: NodeIndex,
field: S,
default: DataType,
) -> usize {
// not allowed to add columns to new nodes
assert!(!self.added.iter().any(|&ni| ni == node));
let field = field.to_string();
let base = &mut self.mainline.ingredients[node];
assert!(base.is_internal() && base.get_base().is_some());
// we need to tell the base about its new column and its default, so that old writes that
// do not have it get the additional value added to them.
let col_i1 = base.add_column(&field);
// we can't rely on DerefMut, since it disallows mutating Taken nodes
{
let col_i2 = base.inner_mut()
.get_base_mut()
.unwrap()
.add_column(default.clone());
assert_eq!(col_i1, col_i2);
}
// also eventually propagate to domain clone
self.columns.push((node, ColumnChange::Add(field, default)));
col_i1
}
/// Drop a column from a base node.
pub fn drop_column(&mut self, node: NodeIndex, column: usize) {
// not allowed to drop columns from new nodes
assert!(!self.added.iter().any(|&ni| ni == node));
let base = &mut self.mainline.ingredients[node];
assert!(base.is_internal() && base.get_base().is_some());
// we need to tell the base about the dropped column, so that old writes that contain that
// column will have it filled in with default values (this is done in Mutator).
// we can't rely on DerefMut, since it disallows mutating Taken nodes
base.inner_mut().get_base_mut().unwrap().drop_column(column);
// also eventually propagate to domain clone
self.columns.push((node, ColumnChange::Drop(column)));
}
#[cfg(test)]
pub fn graph(&self) -> &Graph {
self.mainline.graph()
}
fn ensure_reader_for(&mut self, n: NodeIndex, name: Option<String>) {
if !self.readers.contains_key(&n) {
// make a reader
let r = node::special::Reader::new(n);
let r = if let Some(name) = name {
self.mainline.ingredients[n].named_mirror(r, name)
} else {
self.mainline.ingredients[n].mirror(r)
};
let r = self.mainline.ingredients.add_node(r);
self.mainline.ingredients.add_edge(n, r, ());
self.readers.insert(n, r);
}
}
fn ensure_token_generator(&mut self, n: NodeIndex, key: usize) {
let ri = self.readers[&n];
if self.mainline.ingredients[ri]
.with_reader(|r| r.token_generator().is_some())
.expect("tried to add token generator to non-reader node")
{
return;
}
// A map from base node to the column in that base node whose value must match the value of
// this node's column to cause a conflict. Is None for a given base node if any write to
// that base node might cause a conflict.
let base_columns: Vec<(_, Option<_>)> =
keys::provenance_of(&self.mainline.ingredients, n, key, |_, _, _| None)
.into_iter()
.map(|path| {
// we want the base node corresponding to each path
path.into_iter().last().unwrap()
})
.collect();
let coarse_parents = base_columns
.iter()
.filter_map(|&(ni, o)| if o.is_none() { Some(ni) } else { None })
.collect();
let granular_parents = base_columns
.into_iter()
.filter_map(|(ni, o)| {
if o.is_some() {
Some((ni, o.unwrap()))
} else {
None
}
})
.collect();
let token_generator = checktable::TokenGenerator::new(coarse_parents, granular_parents);
self.mainline
.checktable
.track(token_generator.clone())
.unwrap();
self.mainline.ingredients[ri].with_reader_mut(|r| {
r.set_token_generator(token_generator);
});
}
/// Set up the given node such that its output can be efficiently queried.
///
/// To query into the maintained state, use `ControllerInner::get_getter` or
/// `ControllerInner::get_transactional_getter`
#[cfg(test)]
pub fn maintain_anonymous(&mut self, n: NodeIndex, key: usize) {
self.ensure_reader_for(n, None);
if self.mainline.ingredients[n].is_transactional() {
self.ensure_token_generator(n, key);
}
let ri = self.readers[&n];
self.mainline.ingredients[ri].with_reader_mut(|r| r.set_key(key));
}
/// Set up the given node such that its output can be efficiently queried.
///
/// To query into the maintained state, use `ControllerInner::get_getter` or
/// `ControllerInner::get_transactional_getter`
pub fn maintain(&mut self, name: String, n: NodeIndex, key: usize) {
self.ensure_reader_for(n, Some(name));
if self.mainline.ingredients[n].is_transactional() {
self.ensure_token_generator(n, key);
}
let ri = self.readers[&n];
self.mainline.ingredients[ri].with_reader_mut(|r| r.set_key(key));
}