]> AND Private Git Repository - loba.git/blob - process.cpp
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
Do not run a last data_send round on exit.
[loba.git] / process.cpp
1 #include <algorithm>
2 #include <functional>
3 #include <iterator>
4 #include <numeric>
5 #include <stdexcept>
6 #include <sstream>
7 #include <xbt/log.h>
8 #include <xbt/time.h>
9
10 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(proc);
11
12 #include "misc.h"
13 #include "options.h"
14 #include "tracing.h"
15
16 #include "process.h"
17
18 double process::total_load_init = 0.0;
19 double process::total_load_running = 0.0;
20 double process::total_load_exit = 0.0;
21
22 namespace {
23
24     void sleep_until_date(double& date, double duration)
25     {
26         double sleep_duration = date - MSG_get_clock();
27         if (sleep_duration > 0.0)
28             MSG_process_sleep(sleep_duration);
29         date = MSG_get_clock() + duration;
30     }
31
32 }
33
34 process::process(int argc, char* argv[])
35 {
36     if (argc < 2 || !(std::istringstream(argv[1]) >> real_load))
37         throw std::invalid_argument("bad or missing initial load parameter");
38
39     neigh.assign(argv + 2, argv + argc);
40
41     pneigh.reserve(neigh.size());
42     for (unsigned i = 0 ; i < neigh.size() ; i++) {
43         neighbor* ptr = &neigh[i];
44         m_host_t host = MSG_get_host_by_name(ptr->get_name());
45         pneigh.push_back(ptr);
46         rev_neigh.insert(std::make_pair(host, ptr));
47     }
48
49     prev_load_broadcast = -1;   // force sending of load on first send_all()
50     expected_load = real_load;
51     total_load_running += real_load;
52     total_load_init += real_load;
53
54     ctrl_close_pending = data_close_pending = neigh.size();
55     close_received = false;
56     finalizing = false;
57
58     comp_iter = lb_iter = 0;
59
60     lb_thread = new_msg_thread("loba",
61                                std::bind(&process::load_balance_loop, this));
62
63     e_xbt_log_priority_t logp = xbt_log_priority_verbose;
64     if (!LOG_ISENABLED(logp))
65         return;
66     std::ostringstream oss;
67     oss << neigh.size() << " neighbor";
68     if (!neigh.empty()) {
69         oss << ESSE(neigh.size()) << ": ";
70         std::transform(neigh.begin(), neigh.end() - 1,
71                        std::ostream_iterator<const char*>(oss, ", "),
72                        std::mem_fn(&neighbor::get_name));
73         oss << neigh.back().get_name();
74     }
75     XBT_LOG(logp, "Got %s.", oss.str().c_str());
76     print_loads(false, logp);
77 }
78
79 process::~process()
80 {
81     delete lb_thread;
82     total_load_exit += real_load;
83     if (opt::log_rate < 0)
84         return;
85     XBT_INFO("Final load after %d:%d iterations: %g",
86              lb_iter, comp_iter, real_load);
87     XBT_VERB("Expected load was: %g", expected_load);
88     XBT_VERB("Total computation for this process: %g", get_comp_amount());
89 }
90
91 int process::run()
92 {
93     if (opt::log_rate >= 0) {
94         XBT_INFO("Initial load: %g", real_load);
95         XBT_VERB("Initial expected load: %g", expected_load);
96     }
97     XBT_VERB("Starting...");
98     mutex.acquire();
99     lb_thread->start();
100     while (lb_iter <= opt::comp_iter_delay)
101         cond.wait(mutex);
102     mutex.release();
103     double sleep_duration = opt::comp_time_delay - MSG_get_clock();
104     if (sleep_duration > 0.0)
105         MSG_process_sleep(sleep_duration);
106     compute_loop();
107     lb_thread->wait();
108     XBT_VERB("Done.");
109     return 0;
110 }
111
112 void process::load_balance_loop()
113 {
114     using std::placeholders::_1;
115
116     double next_iter_after_date = MSG_get_clock() + opt::min_lb_iter_duration;
117     while (still_running()) {
118         if (lb_iter == opt::comp_iter_delay) {
119             mutex.acquire();
120             ++lb_iter;
121             cond.signal();
122             mutex.release();
123         } else {
124             ++lb_iter;
125         }
126
127         mutex.acquire();
128         if (!opt::bookkeeping)
129             expected_load = real_load - get_sum_of_to_send();
130         // nothing to do with opt::bookkeeping
131
132         if (opt::log_rate && lb_iter % opt::log_rate == 0) {
133             XBT_INFO("(%u:%u) current load: %g", lb_iter, comp_iter, real_load);
134             XBT_VERB("... expected load: %g", expected_load);
135         }
136
137         if (expected_load > 0.0)
138             load_balance();
139
140         print_loads(true, xbt_log_priority_debug);
141
142         // send
143         comm.ctrl_flush(false);
144         std::for_each(neigh.begin(), neigh.end(),
145                       std::bind(&process::ctrl_send, this, _1));
146         prev_load_broadcast = expected_load;
147         mutex.release();
148
149         sleep_until_date(next_iter_after_date, opt::min_lb_iter_duration);
150         ctrl_receive(0.0);
151     }
152
153     XBT_VERB("Going to finalize for %s...", __func__);
154     XBT_DEBUG("send CTRL_CLOSE to %zu neighbor%s",
155               neigh.size(), ESSE(neigh.size()));
156     std::for_each(neigh.begin(), neigh.end(),
157                   std::bind(&process::ctrl_close, this, _1));
158     while (ctrl_close_pending) {
159         comm.ctrl_flush(false);
160         XBT_DEBUG("waiting for %d CTRL_CLOSE", ctrl_close_pending);
161         ctrl_receive(-1.0);
162     }
163     comm.ctrl_flush(true);
164 }
165
166 void process::compute_loop()
167 {
168     using std::placeholders::_1;
169
170     double next_iter_after_date = MSG_get_clock() + opt::min_comp_iter_duration;
171     while (still_running()) {
172         // receive
173         mutex.acquire();
174         if (real_load > 0.0)
175             data_receive(0.0);
176         else
177             data_receive(opt::min_comp_iter_duration);
178         mutex.release();
179
180         // send
181         comm.data_flush(false);
182         mutex.acquire();
183         std::for_each(neigh.begin(), neigh.end(),
184                       std::bind(&process::data_send, this, _1));
185         mutex.release();
186
187         if (real_load == 0.0)
188             continue;
189
190         // compute
191         ++comp_iter;
192         double flops = opt::comp_cost(real_load);
193         m_task_t task = MSG_task_create("computation", flops, 0.0, NULL);
194         TRACE_msg_set_task_category(task, TRACE_CAT_COMP);
195         XBT_DEBUG("compute %g flop%s", flops, ESSE(flops));
196         MSG_task_execute(task);
197         add_comp_amount(flops);
198         MSG_task_destroy(task);
199
200         sleep_until_date(next_iter_after_date, opt::min_comp_iter_duration);
201     }
202
203     XBT_VERB("Going to finalize for %s...", __func__);
204     finalizing = true;
205     total_load_running -= real_load;
206     XBT_DEBUG("send DATA_CLOSE to %zu neighbor%s",
207               neigh.size(), ESSE(neigh.size()));
208     std::for_each(neigh.begin(), neigh.end(),
209                   std::bind(&process::data_close, this, _1));
210     while (data_close_pending) {
211         comm.data_flush(false);
212         XBT_DEBUG("waiting for %d DATA_CLOSE", data_close_pending);
213         data_receive(-1.0);
214     }
215     comm.data_flush(true);
216 }
217
218 bool process::still_running()
219 {
220     static bool last_status = true;
221
222     if (!last_status) {
223         /* nop */
224
225     } else if (opt::exit_request) {
226         XBT_VERB("Global exit requested");
227         last_status = false;
228
229     } else if (opt::time_limit && MSG_get_clock() >= opt::time_limit) {
230         XBT_VERB("Reached time limit: %g/%g", MSG_get_clock(), opt::time_limit);
231         last_status = false;
232
233     } else if (opt::lb_maxiter && lb_iter >= opt::lb_maxiter) {
234         XBT_VERB("Reached lb_maxiter: %d/%d", lb_iter, opt::lb_maxiter);
235         last_status = false;
236
237     } else if (opt::comp_maxiter && comp_iter >= opt::comp_maxiter) {
238         XBT_VERB("Reached comp_maxiter: %d/%d", comp_iter, opt::comp_maxiter);
239         last_status = false;
240
241     } else if (opt::exit_on_close && close_received) {
242         XBT_VERB("Close received");
243         last_status = false;
244
245     } else if (real_load == 0.0 && !data_close_pending) {
246         XBT_VERB("I'm a poor lonesome process, and I have no load...");
247         last_status = false;
248
249     } else if (100.0 * total_load_running / total_load_init <=
250                opt::load_ratio_threshold) {
251         // fixme: this check should be implemented with a distributed
252         // algorithm, and not a shared global variable!
253         XBT_VERB("No more load to balance in system.");
254         last_status = false;
255     }
256
257     return last_status;
258 }
259
260 double process::get_sum_of_to_send() const
261 {
262     using std::placeholders::_1;
263     using std::placeholders::_2;
264
265     return std::accumulate(neigh.begin(), neigh.end(), 0.0,
266                            std::bind(std::plus<double>(), _1,
267                                      std::bind(&neighbor::get_to_send, _2)));
268 }
269
270 void process::load_balance()
271 {
272     if (lb_iter == 1)           // warn only once
273         XBT_WARN("process::load_balance() is a no-op!");
274 }
275
276 void process::send(neighbor& nb, double amount)
277 {
278     expected_load -= amount;
279     nb.set_to_send(nb.get_to_send() + amount);
280     nb.set_load(nb.get_load() + amount);
281 }
282
283 void process::ctrl_send(neighbor& nb)
284 {
285     double info_to_send = expected_load;
286     double debt_to_send;
287     if (opt::bookkeeping) {     // bookkeeping
288         debt_to_send = nb.get_to_send();
289         if (debt_to_send > 0.0) {
290             nb.set_to_send(0.0);
291             nb.set_debt(nb.get_debt() + debt_to_send);
292         }
293     } else {                    // !bookkeeping
294         debt_to_send = 0.0;
295     }
296     if (info_to_send != prev_load_broadcast || debt_to_send > 0.0) {
297         message* msg = new message(message::CTRL, info_to_send, debt_to_send);
298         add_ctrl_send_mesg(msg->get_size());
299         comm.ctrl_send(nb.get_ctrl_mbox(), msg);
300     }
301 }
302
303 void process::data_send(neighbor& nb)
304 {
305     double load_to_send;
306     if (opt::bookkeeping) {
307         load_to_send = std::min(real_load, nb.get_debt());
308         if (load_to_send >= opt::min_transfer_amount) {
309             nb.set_debt(nb.get_debt() - load_to_send);
310             real_load -= load_to_send;
311         } else {
312             load_to_send = 0.0;
313         }
314     } else {
315         load_to_send = nb.get_to_send();
316         if (load_to_send >= opt::min_transfer_amount) {
317             nb.set_to_send(0.0);
318             real_load -= load_to_send;
319         } else {
320             load_to_send = 0.0;
321         }
322     }
323     while (load_to_send > 0.0) {
324         double amount;
325         if (opt::max_transfer_amount)
326             amount = std::min(load_to_send, opt::max_transfer_amount);
327         else
328             amount = load_to_send;
329         message* msg = new message(message::DATA, amount);
330         add_data_send_mesg(msg->get_size());
331         comm.data_send(nb.get_data_mbox(), msg);
332         load_to_send -= amount;
333     }
334 }
335
336 void process::ctrl_close(neighbor& nb)
337 {
338     comm.ctrl_send(nb.get_ctrl_mbox(), new message(message::CTRL_CLOSE, 0.0));
339 }
340
341 void process::data_close(neighbor& nb)
342 {
343     comm.data_send(nb.get_data_mbox(), new message(message::DATA_CLOSE, 0.0));
344 }
345
346 void process::ctrl_receive(double timeout)
347 {
348     message* msg;
349     m_host_t from;
350
351     XBT_DEBUG("%sblocking receive on ctrl (%g)", "\0non-" + !timeout, timeout);
352     while (ctrl_close_pending && comm.ctrl_recv(msg, from, timeout)) {
353         if (msg->get_type() != message::CTRL_CLOSE)
354             add_ctrl_recv_mesg(msg->get_size());
355         handle_message(msg, from);
356         timeout = 0.0;
357     }
358 }
359
360 void process::data_receive(double timeout)
361 {
362     message* msg;
363     m_host_t from;
364
365     XBT_DEBUG("%sblocking receive on data (%g)", "\0non-" + !timeout, timeout);
366     while (data_close_pending && comm.data_recv(msg, from, timeout)) {
367         if (msg->get_type() != message::DATA_CLOSE)
368             add_data_recv_mesg(msg->get_size());
369         handle_message(msg, from);
370         timeout = 0.0;
371     }
372 }
373
374 void process::handle_message(message* msg, m_host_t from)
375 {
376     switch (msg->get_type()) {
377     case message::CTRL: {
378         neighbor* n = rev_neigh[from];
379         n->set_load(msg->get_amount() + n->get_to_send());
380         expected_load += msg->get_credit(); // may be 0.0 if !opt::bookkeeping
381         break;
382     }
383     case message::DATA: {
384         double ld = msg->get_amount();
385         real_load += ld;
386         if (finalizing)
387             total_load_running -= ld;
388         break;
389     }
390     case message::CTRL_CLOSE:
391         ctrl_close_pending--;
392         close_received = true;
393         break;
394     case message::DATA_CLOSE:
395         data_close_pending--;
396         close_received = true;
397         break;
398     }
399     delete msg;
400 }
401
402 #define print_loads_generic(vec, verbose, logp, cat)                    \
403     if (_XBT_LOG_ISENABLEDV((*cat), logp)) {                            \
404         using std::placeholders::_1;                                    \
405         XBT_XCLOG(cat, logp, "My load: %g (real); %g (expected).  "     \
406                   "Neighbor loads:", real_load, expected_load);         \
407         std::for_each(vec.begin(), vec.end(),                           \
408                       std::bind(&neighbor::print, _1, verbose, logp, cat)); \
409     } else ((void)0)
410
411 void process::print_loads(bool verbose,
412                           e_xbt_log_priority_t logp,
413                           xbt_log_category_t cat) const
414 {
415     print_loads_generic(neigh, verbose, logp, cat);
416 }
417
418 void process::print_loads_p(bool verbose,
419                             e_xbt_log_priority_t logp,
420                             xbt_log_category_t cat) const
421 {
422     print_loads_generic(pneigh, verbose, logp, cat);
423 }
424
425 #undef print_loads_generic
426
427 // Local variables:
428 // mode: c++
429 // End: