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
use std::thread;
use std::io::BufRead;
use getopts;
use std::sync::Arc;
use allocator::{Thread, Process, Generic};
use networking::initialize_networking;
pub enum Configuration {
Thread,
Process(usize),
Cluster(usize, usize, Vec<String>, bool)
}
impl Configuration {
pub fn from_args<I: Iterator<Item=String>>(args: I) -> Result<Configuration,String> {
let mut opts = getopts::Options::new();
opts.optopt("w", "threads", "number of per-process worker threads", "NUM");
opts.optopt("p", "process", "identity of this process", "IDX");
opts.optopt("n", "processes", "number of processes", "NUM");
opts.optopt("h", "hostfile", "text file whose lines are process addresses", "FILE");
opts.optflag("r", "report", "reports connection progress");
opts.parse(args)
.map_err(|e| format!("{:?}", e))
.map(|matches| {
let threads = matches.opt_str("w").map(|x| x.parse().unwrap_or(1)).unwrap_or(1);
let process = matches.opt_str("p").map(|x| x.parse().unwrap_or(0)).unwrap_or(0);
let processes = matches.opt_str("n").map(|x| x.parse().unwrap_or(1)).unwrap_or(1);
let report = matches.opt_present("report");
assert!(process < processes);
if processes > 1 {
let mut addresses = Vec::new();
if let Some(hosts) = matches.opt_str("h") {
let reader = ::std::io::BufReader::new(::std::fs::File::open(hosts.clone()).unwrap());
for x in reader.lines().take(processes) {
addresses.push(x.unwrap());
}
if addresses.len() < processes {
panic!("could only read {} addresses from {}, but -n: {}", addresses.len(), hosts, processes);
}
}
else {
for index in 0..processes {
addresses.push(format!("localhost:{}", 2101 + index));
}
}
assert!(processes == addresses.len());
Configuration::Cluster(threads, process, addresses, report)
}
else {
if threads > 1 { Configuration::Process(threads) }
else { Configuration::Thread }
}
})
}
}
fn create_allocators(config: Configuration, logger: Arc<Fn(::logging::CommsSetup)->::logging::CommsLogger+Send+Sync>) -> Result<Vec<Generic>,String> {
match config {
Configuration::Thread => Ok(vec![Generic::Thread(Thread)]),
Configuration::Process(threads) => Ok(Process::new_vector(threads).into_iter().map(|x| Generic::Process(x)).collect()),
Configuration::Cluster(threads, process, addresses, report) => {
if let Ok(stuff) = initialize_networking(addresses, process, threads, report, logger) {
Ok(stuff.into_iter().map(|x| Generic::Binary(x)).collect())
}
else {
Err("failed to initialize networking".to_owned())
}
},
}
}
pub fn initialize<T:Send+'static, F: Fn(Generic)->T+Send+Sync+'static>(
config: Configuration,
log_sender: Arc<Fn(::logging::CommsSetup)->::logging::CommsLogger+Send+Sync>,
func: F,
) -> Result<WorkerGuards<T>,String> {
let allocators = try!(create_allocators(config, log_sender));
let logic = Arc::new(func);
let mut guards = Vec::new();
for allocator in allocators.into_iter() {
let clone = logic.clone();
guards.push(try!(thread::Builder::new()
.name(format!("worker thread {}", allocator.index()))
.spawn(move || {
(*clone)(allocator)
})
.map_err(|e| format!("{:?}", e))));
}
Ok(WorkerGuards { guards: guards })
}
pub struct WorkerGuards<T:Send+'static> {
guards: Vec<::std::thread::JoinHandle<T>>
}
impl<T:Send+'static> WorkerGuards<T> {
pub fn join(mut self) -> Vec<Result<T,String>> {
self.guards.drain(..)
.map(|guard| guard.join().map_err(|e| format!("{:?}", e)))
.collect()
}
}
impl<T:Send+'static> Drop for WorkerGuards<T> {
fn drop(&mut self) {
for guard in self.guards.drain(..) {
guard.join().unwrap();
}
}
}