timely-util 0.1.1

Utility abstractions on top of Timely Dataflow
Documentation
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
/*
    Abstractions for running experiments in Timely.
*/

use super::ec2;
use super::operators::save_to_file;
use super::perf::latency_throughput_meter;
use super::{Scope, Stream};
use crate::util::process_util::run_as_process;
use crate::util::string_to_static_str;
use crate::util::time_util::current_datetime_str;

use abomonation_derive::Abomonation;
use structopt::StructOpt;

use std::str::FromStr;

/* Constants */

// Results filenames
const RESULTS_DIR: &str = "results/";
const RESULTS_EXT: &str = ".out";
fn make_results_path<T: AsRef<str>>(
    exp_name: &str,
    args: &[T],
) -> &'static str {
    let mut out = RESULTS_DIR.to_owned() + &current_datetime_str() + "_";
    out += exp_name;
    for arg in args {
        out += "_";
        out += arg.as_ref();
    }
    out += RESULTS_EXT;
    string_to_static_str(out)
}

// Ports for distributed communication over EC2
const EC2_STARTING_PORT: u64 = 4000;
const LOCAL_STARTING_PORT: u64 = 4000;
const BARRIER_START_PORT: u16 = 5000;
/*
    Types of networks where Timely distributed experiments can be run
*/
#[derive(Abomonation, Copy, Clone, Debug, Eq, PartialEq)]
enum TimelyNetworkType {
    SingleNode,
    Local,
    EC2,
}
impl FromStr for TimelyNetworkType {
    type Err = &'static str;
    fn from_str(input: &str) -> Result<TimelyNetworkType, Self::Err> {
        match input {
            "s" => Ok(Self::SingleNode),
            "l" => Ok(Self::Local),
            "e" => Ok(Self::EC2),
            _ => Err("Invalid network type (choices: 's', 'l', 'e')"),
        }
    }
}

/*
    Distributed node information
    Network together with a node number.
    Used to run distributed experiments that can be either local
    (with a node number) or over EC2 (where node number will be derived).
*/
#[derive(Abomonation, Copy, Clone, Debug, Eq, PartialEq)]
pub enum TimelyNodeInfo {
    Local(u64), // node number
    EC2,
}
impl FromStr for TimelyNodeInfo {
    type Err = &'static str;
    fn from_str(input: &str) -> Result<TimelyNodeInfo, Self::Err> {
        if input == "e" {
            Ok(Self::EC2)
        } else if &input[0..1] == "l" {
            match u64::from_str(&input[1..]) {
                Ok(this_node) => Ok(Self::Local(this_node)),
                Err(_err) => Err("Node ID should be a u64. Example usage: l3"),
            }
        } else {
            Err("Invalid node info (choices: 'l<id>', 'e')")
        }
    }
}
impl TimelyNodeInfo {
    fn this_node(&self) -> u64 {
        match &self {
            TimelyNodeInfo::Local(this_node) => *this_node,
            TimelyNodeInfo::EC2 => ec2::get_ec2_node_number(),
        }
    }
    fn is_main_node(&self) -> bool {
        self.this_node() == 0
    }
}

/*
    Parameters to run a Timely dataflow between several
    parallel workers or nodes
*/
#[derive(Abomonation, Copy, Clone, Debug, StructOpt)]
pub struct TimelyParallelism {
    // Command line -w, should be >= 1
    workers: u64,
    // Command line -n, should be >= 1
    nodes: u64,
    // Command line -p, betwewen 0 and nodes-1 (unused if nodes=1)
    this_node: u64,
    // Type of network
    #[structopt(default_value = "s")]
    network: TimelyNetworkType,
    // Experiment number -- to disambiguate unique experiments,
    // in case multiple are going on at once so they don't interfere.
    // This is incorporated into the port number. If not needed can just
    // be set to 0.
    #[structopt(skip = 0u64)]
    experiment_num: u64,
}
impl TimelyParallelism {
    /* Constructors */
    fn new_single_node(workers: u64) -> TimelyParallelism {
        let result = TimelyParallelism {
            workers,
            nodes: 1,
            this_node: 0,
            network: TimelyNetworkType::SingleNode,
            experiment_num: 0,
        };
        result.validate();
        result
    }
    pub fn new_sequential() -> TimelyParallelism {
        Self::new_single_node(1)
    }
    pub fn new_distributed_local(
        workers: u64,
        nodes: u64,
        this_node: u64,
        experiment_num: u64,
    ) -> TimelyParallelism {
        let result = TimelyParallelism {
            workers,
            nodes,
            this_node,
            network: TimelyNetworkType::Local,
            experiment_num,
        };
        result.validate();
        result
    }
    pub fn new_distributed_ec2(
        workers: u64,
        nodes: u64,
        experiment_num: u64,
    ) -> TimelyParallelism {
        let result = TimelyParallelism {
            workers,
            nodes,
            this_node: ec2::get_ec2_node_number(),
            network: TimelyNetworkType::EC2,
            experiment_num,
        };
        result.validate();
        result
    }
    pub fn new_from_info(
        node_info: TimelyNodeInfo,
        workers: u64,
        nodes: u64,
        experiment_num: u64,
    ) -> TimelyParallelism {
        match node_info {
            TimelyNodeInfo::Local(this_node) => Self::new_distributed_local(
                workers,
                nodes,
                this_node,
                experiment_num,
            ),
            TimelyNodeInfo::EC2 => {
                Self::new_distributed_ec2(workers, nodes, experiment_num)
            }
        }
    }

    /* Private methods */
    fn validate(&self) {
        assert!(self.workers >= 1 && self.nodes >= 1);
        if self.network == TimelyNetworkType::SingleNode {
            assert!(self.nodes == 1);
        }
    }
    fn is_participating(&self) -> bool {
        self.this_node < self.nodes
    }
    fn prepare_host_file(&self) -> &'static str {
        match self.network {
            TimelyNetworkType::SingleNode => unreachable!(),
            TimelyNetworkType::Local => {
                let port = LOCAL_STARTING_PORT + self.experiment_num;
                ec2::prepare_local_host_file(port)
            }
            TimelyNetworkType::EC2 => {
                let port = EC2_STARTING_PORT + self.experiment_num * self.nodes;
                ec2::prepare_ec2_host_file(port)
            }
        }
    }

    /* Data summaries */
    pub fn to_csv(self) -> String {
        self.validate();
        format!("{} wkrs, {} nodes", self.workers, self.nodes)
    }
    pub fn to_vec(self) -> Vec<String> {
        self.validate();
        vec![self.workers.to_string(), self.nodes.to_string()]
    }

    /* Compute arguments to pass to Timely */
    // Note 1: call only once per experiment. Creates/initializes a host file
    // specific to that experiment.
    // Note 2: returns None if this node is not involved in this experiment
    // (i.e. node # is larger than number of nodes)
    pub fn timely_args(&self) -> Option<Vec<String>> {
        self.validate();
        if !self.is_participating() {
            None
        } else {
            let mut vec = vec!["-w".to_string(), self.workers.to_string()];
            if self.nodes > 1 {
                vec.push("-n".to_string());
                vec.push(self.nodes.to_string());
                vec.push("-p".to_string());
                vec.push(self.this_node.to_string());

                let hostfile = self.prepare_host_file();
                vec.push("-h".to_string());
                vec.push(hostfile.to_string());
            }
            Some(vec)
        }
    }

    /* Main node (used for restricting output so it is less noisy) */
    fn is_main_node(&self) -> bool {
        self.this_node == 0
    }
    /* Barrier (used for synchronizing experiments) */
    fn barrier(&self) {
        match self.network {
            TimelyNetworkType::SingleNode => (),
            TimelyNetworkType::Local => {
                let port = BARRIER_START_PORT
                    + ((self.experiment_num * 2 * self.nodes) as u16);
                ec2::local_barrier(self.nodes, self.this_node, port);
            }
            TimelyNetworkType::EC2 => {
                let port = BARRIER_START_PORT
                    + ((self.experiment_num * 2 * self.nodes) as u16);
                ec2::ec2_barrier(self.nodes, self.this_node, port);
            }
        }
    }
}

/*
    Trait to capture parameters that form the input to a Timely experiment.

    to_csv should output the parameters separated by commas.
    to_vec should output the parameters as strings in a list.
    get_exp_duration_secs is the total time that the experiment runs (in secs).
    set_rate should vary one or more of the parameters to set the
    input throughput (in events / ms), which can be used to test throughput.

    ExperimentParams should be immutable and implement the Copy trait.
    For example, set_rate returns a new object.
*/
pub trait ExperimentParams: Copy + StructOpt + timely::ExchangeData {
    fn to_csv(self) -> String;
    fn to_vec(self) -> Vec<String>;
    fn get_exp_duration_secs(&self) -> u64;
    fn set_rate(self, rate_per_milli: u64) -> Self;
}

/*
    Trait to capture the full executable experiment.

    To use, implement the get_name and build_dataflow methods.

    One reason this trait is needed is in order to hide the top-level scope
    parameter passed by run_dataflow to build the dataflow, which is instead made
    generic in the build_dataflow method. This
    is necessary because Rust generics are weird -- see
    https://stackoverflow.com/questions/37606035/pass-generic-function-as-argument
*/
pub trait LatencyThroughputExperiment<P, I, O>: timely::ExchangeData
where
    P: ExperimentParams,
    I: std::fmt::Debug + Clone + timely::Data,
    O: std::fmt::Debug + Clone + timely::Data,
{
    /* Functionality to implement */
    fn get_name(&self) -> String;
    fn build_dataflow<G: Scope<Timestamp = u128>>(
        &self,
        params: P,
        scope: &mut G,
        worker_index: usize,
    ) -> (Stream<G, I>, Stream<G, O>);

    /* Functionality provided, but mostly considered private */
    // The core dataflow to be run
    fn run_dataflow<G: Scope<Timestamp = u128>>(
        &self,
        scope: &mut G,
        params: P,
        parallelism: TimelyParallelism,
        worker_index: usize,
        output_filename: &'static str,
    ) {
        let (input, output) = self.build_dataflow(params, scope, worker_index);
        // Optional other meters, uncomment for testing
        // volume_meter(&input);
        // completion_meter(&output);
        // latency_meter(&output);
        // throughput_meter(&input, &output);
        let latency_throughput = latency_throughput_meter(&input, &output);
        let parallelism_csv = parallelism.to_csv();
        let params_csv = params.to_csv();
        save_to_file(
            &latency_throughput,
            output_filename,
            move |(latency, throughput)| {
                format!(
                    "{}, {}, {} ms, {} events/ms",
                    parallelism_csv, params_csv, latency, throughput
                )
            },
        );
    }
    // Run an experiment with a filename
    // Only necessary if the user wants a custom filename
    fn run_with_filename(
        &'static self,
        params: P,
        parallelism: TimelyParallelism,
        output_filename: &'static str,
    ) {
        if parallelism.is_main_node() {
            println!(
                "{} Experiment Parameters: {}, Parallelism: {}",
                self.get_name(),
                params.to_csv(),
                parallelism.to_csv(),
            );
        }
        let opt_args = parallelism.timely_args();
        let node_index = parallelism.this_node;
        match opt_args {
            Some(mut args) => {
                // Barrier to make sure different experiments don't overlap!
                parallelism.barrier();

                println!("[node {}] initializing experiment", node_index);
                println!("[node {}] timely args: {:?}", node_index, args);
                let func = move || {
                    timely::execute_from_args(args.drain(0..), move |worker| {
                        let worker_index = worker.index();
                        worker.dataflow(move |scope| {
                            self.run_dataflow(
                                scope,
                                params,
                                parallelism,
                                worker_index,
                                output_filename,
                            );
                            println!(
                                "[worker {}] setup complete",
                                worker_index
                            );
                        });
                    })
                    .unwrap();
                };
                run_as_process(func);
            }
            None => {
                println!(
                    "[node {}] skipping experiment between nodes {:?}",
                    node_index,
                    (0..parallelism.nodes).collect::<Vec<u64>>()
                );
                // Old -- no longer necessary, it was just a hack not as general
                // as using the barrier to synchronize experiments
                // let sleep_dur = params.get_exp_duration_secs();
                // println!("[node {}] sleeping for {}", node_index, sleep_dur);
                // sleep_for_secs(sleep_dur);
            }
        }
    }

    /* Functionality provided and exposed as the main options */
    // Run a single experiment.
    fn run_single(&'static self, params: P, parallelism: TimelyParallelism) {
        let mut args = Vec::new();
        args.append(&mut params.to_vec());
        args.append(&mut parallelism.to_vec());
        let results_path = make_results_path(&self.get_name(), &args[..]);
        self.run_with_filename(params, parallelism, results_path);
    }
    // Run many experiments
    fn run_all(
        &'static self,
        node_info: TimelyNodeInfo,
        default_params: P,
        rates_per_milli: &[u64],
        par_workers: &[u64],
        par_nodes: &[u64],
    ) {
        // Run experiment for all different configurations
        let mut exp_num = 0;
        for &par_w in par_workers {
            for &par_n in par_nodes {
                if node_info.is_main_node() {
                    println!(
                        "===== Parallelism: {} w, {} n =====",
                        par_w, par_n
                    );
                }
                let results_path = make_results_path(
                    &self.get_name(),
                    &[
                        &("w".to_owned() + &par_w.to_string()),
                        &("n".to_owned() + &par_n.to_string()),
                    ],
                );
                for &rate in rates_per_milli {
                    if node_info.is_main_node() {
                        println!("=== Input Rate (events/ms): {} ===", rate);
                    }
                    let params = default_params.set_rate(rate);
                    let parallelism = TimelyParallelism::new_from_info(
                        node_info, par_w, par_n, exp_num,
                    );
                    self.run_with_filename(params, parallelism, results_path);
                    exp_num += 1;
                }
            }
        }
    }
}