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

Private GIT Repository
Handle timeout exception in condition_t::timedwait().
[loba.git] / process.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <functional>
4 #include <iterator>
5 #include <numeric>
6 #include <stdexcept>
7 #include <sstream>
8 #include <xbt/log.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 mutex_t *process::proc_mutex;
19
20 double process::total_load_init = 0.0;
21 double process::total_load_running = 0.0;
22 double process::total_load_exit = 0.0;
23
24 int process::process_counter = 0;
25 double process::total_load_average;
26 double process::average_load_ratio;
27 double process::load_diff_threshold;
28
29 std::atomic<int> process::convergence_counter(0);
30
31 namespace {
32
33     void sleep_until_date(double& date, double duration)
34     {
35         double sleep_duration = date - MSG_get_clock();
36         if (sleep_duration > 0.0)
37             MSG_process_sleep(sleep_duration);
38         date = MSG_get_clock() + duration;
39     }
40
41 }
42
43 process::process(int argc, char* argv[])
44 {
45     if (argc < 2 || !(std::istringstream(argv[1]) >> real_load))
46         throw std::invalid_argument("bad or missing initial load parameter");
47
48     double iload = std::trunc(real_load);
49     if (opt::integer_transfer && real_load != iload) {
50         XBT_WARN("Initial load %g is not an integer.  Truncate it.",
51                  real_load);
52         real_load = iload;
53     }
54
55     neigh.assign(argv + 2, argv + argc);
56
57     pneigh.reserve(neigh.size());
58     for (unsigned i = 0 ; i < neigh.size() ; i++) {
59         neighbor* ptr = &neigh[i];
60         msg_host_t host = MSG_get_host_by_name(ptr->get_name());
61         pneigh.push_back(ptr);
62         rev_neigh.insert(std::make_pair(host, ptr));
63     }
64
65     prev_load_broadcast = -1;   // force sending of load on first send_all()
66     expected_load = real_load;
67     received_load = 0.0;
68
69     idle_duration = 0.0;
70     convergence = -1.0;
71
72     proc_mutex->acquire();
73     process_counter++;
74     convergence_counter++;
75     total_load_init += real_load;
76     total_load_running += real_load;
77     total_load_average = total_load_running / process_counter;
78     if (opt::avg_load_ratio >= 0.0)
79         average_load_ratio = opt::avg_load_ratio;
80     else
81         average_load_ratio = 100.0 *
82             (process_counter / -opt::avg_load_ratio) / total_load_average;
83     load_diff_threshold = (opt::load_ratio_threshold +
84                            average_load_ratio * total_load_average) / 100.0;
85     proc_mutex->release();
86
87     ctrl_close_pending = data_close_pending = neigh.size();
88     close_received = false;
89     finalizing = false;
90
91     all_comp_iter = comp_iter = lb_iter = 0;
92
93     lb_thread = new_msg_thread("loba",
94                                std::bind(&process::load_balance_loop, this));
95
96     e_xbt_log_priority_t logp = xbt_log_priority_verbose;
97     if (!LOG_ISENABLED(logp))
98         return;
99     std::ostringstream oss;
100     oss << neigh.size() << " neighbor";
101     if (!neigh.empty()) {
102         oss << ESSE(neigh.size()) << ": ";
103         std::transform(neigh.begin(), neigh.end() - 1,
104                        std::ostream_iterator<const char*>(oss, ", "),
105                        std::mem_fn(&neighbor::get_name));
106         oss << neigh.back().get_name();
107     }
108     XBT_LOG(logp, "Got %s.", oss.str().c_str());
109     print_loads(false, logp);
110 }
111
112 process::~process()
113 {
114     delete lb_thread;
115     proc_mutex->acquire();
116     total_load_exit += real_load;
117     proc_mutex->release();
118     xbt_assert(received_load == 0.0,
119                "received_load is %g, but should be 0.0 !", received_load);
120     if (opt::log_rate < 0)
121         return;
122     XBT_INFO("Final load after %d:%d:%d iterations: %g",
123              lb_iter, comp_iter, all_comp_iter, real_load);
124     if (convergence >= 0.0)
125         XBT_INFO("Convergence within %g%% was achieved at time %g",
126                  average_load_ratio, convergence);
127     else
128         XBT_INFO("Convergence within %g%% was not achieved",
129                  average_load_ratio);
130     XBT_VERB("Expected load was: %g", expected_load);
131     XBT_VERB("Total computation for this process: %g", get_comp_amount());
132     print_loads(true, xbt_log_priority_debug);
133 }
134
135 double process::get_iter_deviation() const
136 {
137     double average_cost = opt::comp_cost(total_load_average); // fixme: get locked?
138     // Do not count idle periods
139     double comp_iter_opt = acc.comp_amount / average_cost;
140 /*
141     // Add iterations that could have been achieved while beeing idle
142     // (kept for documentation)
143     double self_speed = MSG_get_host_speed(MSG_host_self());
144     double average_duration = average_cost / self_speed;
145     comp_iter_opt += idle_duration / average_duration;
146 */
147     return comp_iter - comp_iter_opt;
148 }
149
150 int process::run()
151 {
152     if (opt::log_rate >= 0) {
153         XBT_INFO("Initial load: %g", real_load);
154         XBT_VERB("Initial expected load: %g", expected_load);
155     }
156     XBT_VERB("Starting...");
157     mutex.acquire();
158     lb_thread->start();
159     while (lb_iter <= opt::comp_iter_delay)
160         cond.wait(mutex);
161     mutex.release();
162     double sleep_duration = opt::comp_time_delay - MSG_get_clock();
163     if (sleep_duration > 0.0)
164         MSG_process_sleep(sleep_duration);
165     compute_loop();
166     lb_thread->wait();
167     XBT_VERB("Done.");
168     return 0;
169 }
170
171 void process::load_balance_loop()
172 {
173     using std::placeholders::_1;
174
175     double next_iter_after_date = MSG_get_clock() + opt::min_lb_iter_duration;
176     while (still_running()) {
177         if (lb_iter == opt::comp_iter_delay) {
178             mutex.acquire();
179             ++lb_iter;
180             cond.signal();
181             mutex.release();
182         } else {
183             ++lb_iter;
184         }
185
186         ctrl_receive(0.0);
187
188         mutex.acquire();
189         if (!opt::bookkeeping)
190             expected_load = real_load - get_sum_of_to_send();
191         // nothing to do with opt::bookkeeping
192
193         if (opt::log_rate && lb_iter % opt::log_rate == 0) {
194             XBT_INFO("(%u:%u:%u) current load: %g",
195                      lb_iter, comp_iter, all_comp_iter, real_load);
196             XBT_VERB("... expected load: %g", expected_load);
197         }
198
199         if (expected_load > 0.0)
200             load_balance();
201
202         print_loads(true, xbt_log_priority_debug);
203
204         // send
205         comm.ctrl_flush(false);
206         std::for_each(neigh.begin(), neigh.end(),
207                       std::bind(&process::ctrl_send, this, _1));
208         prev_load_broadcast = expected_load;
209         mutex.release();
210
211         sleep_until_date(next_iter_after_date, opt::min_lb_iter_duration);
212     }
213
214     XBT_VERB("Going to finalize for %s...", __func__);
215     XBT_DEBUG("send CTRL_CLOSE to %zu neighbor%s",
216               neigh.size(), ESSE(neigh.size()));
217     std::for_each(neigh.begin(), neigh.end(),
218                   std::bind(&process::ctrl_close, this, _1));
219     while (ctrl_close_pending) {
220         comm.ctrl_flush(false);
221         XBT_DEBUG("waiting for %d CTRL_CLOSE", ctrl_close_pending);
222         ctrl_receive(-1.0);
223     }
224     comm.ctrl_flush(true);
225 }
226
227 void process::compute_loop()
228 {
229     using std::placeholders::_1;
230
231     double next_iter_after_date = MSG_get_clock() + opt::min_comp_iter_duration;
232     double idle_since_date = 0.0;
233     while (still_running()) {
234         // receive
235         // if there is something to compute, do not block
236         // else, block the duration of an *lb* iteration
237         data_receive(real_load > 0.0 ? 0.0 : opt::min_lb_iter_duration);
238
239         // send
240         comm.data_flush(false);
241         mutex.acquire();
242         real_load += received_load;
243         received_load = 0.0;
244         std::for_each(neigh.begin(), neigh.end(),
245                       std::bind(&process::data_send, this, _1));
246         mutex.release();
247
248         ++all_comp_iter;
249         if (real_load == 0.0)
250             continue;
251
252         convergence_check();
253
254         // compute
255         idle_duration += MSG_get_clock() - idle_since_date;
256         ++comp_iter;
257         double flops = opt::comp_cost(real_load);
258         msg_task_t task = MSG_task_create("computation", flops, 0.0, NULL);
259         // MSG_task_set_category(task, TRACE_CAT_COMP);
260         XBT_DEBUG("compute %g flop%s", flops, ESSE(flops));
261         MSG_task_execute(task);
262         add_comp_amount(flops);
263         MSG_task_destroy(task);
264
265         idle_since_date = MSG_get_clock();
266
267         sleep_until_date(next_iter_after_date, opt::min_comp_iter_duration);
268     }
269
270     XBT_VERB("Going to finalize for %s...", __func__);
271     // Note: idle duration is not counted during finalization
272     finalizing = true;
273     XBT_DEBUG("send DATA_CLOSE to %zu neighbor%s",
274               neigh.size(), ESSE(neigh.size()));
275     std::for_each(neigh.begin(), neigh.end(),
276                   std::bind(&process::data_close, this, _1));
277     while (data_close_pending) {
278         comm.data_flush(false);
279         XBT_DEBUG("waiting for %d DATA_CLOSE", data_close_pending);
280         data_receive(-1.0);
281     }
282     real_load += received_load;
283     received_load = 0.0;
284     proc_mutex->acquire();
285     total_load_running -= real_load;
286     proc_mutex->release();
287     convergence_check();
288     comm.data_flush(true);
289 }
290
291 void process::convergence_check()
292 {
293     double average = total_load_average; // fixme: get locked?
294     double load_diff = std::fabs(real_load - average);
295     bool converged = load_diff <= load_diff_threshold;
296
297     if (converged) {
298         if (convergence < 0) {
299             XBT_VERB("current load has converged: %g (%.4g%%)",
300                      real_load,  100.0 * load_diff / average);
301             convergence = MSG_get_clock();
302             local_convergence_counter = opt::exit_on_convergence;
303         }
304         if (local_convergence_counter > 0 && --local_convergence_counter == 0)
305                 --convergence_counter;
306     } else {
307         if (convergence >= 0.0) {
308             XBT_VERB("current load has diverged: %g (%.4g%%)",
309                      real_load, 100.0 * load_diff / average);
310             convergence = -1.0;
311             if (local_convergence_counter == 0)
312                 ++convergence_counter;
313         }
314     }
315 }
316
317 bool process::still_running()
318 {
319     static bool last_status = true;
320
321     if (!last_status) {
322         /* nop */
323
324     } else if (opt::exit_request) {
325         XBT_VERB("Global exit requested");
326         last_status = false;
327
328     } else if (opt::time_limit && MSG_get_clock() >= opt::time_limit) {
329         XBT_VERB("Reached time limit: %g/%g", MSG_get_clock(), opt::time_limit);
330         last_status = false;
331
332     } else if (opt::lb_maxiter && lb_iter >= opt::lb_maxiter) {
333         XBT_VERB("Reached lb_maxiter: %d/%d", lb_iter, opt::lb_maxiter);
334         last_status = false;
335
336     } else if (opt::comp_maxiter && comp_iter >= opt::comp_maxiter) {
337         XBT_VERB("Reached comp_maxiter: %d/%d", comp_iter, opt::comp_maxiter);
338         last_status = false;
339
340     } else if (opt::exit_on_convergence && convergence_counter == 0) {
341         XBT_VERB("Global convergence detected");
342         last_status = false;
343
344     } else if (opt::exit_on_close && close_received) {
345         XBT_VERB("Close received");
346         last_status = false;
347
348     } else if (real_load == 0.0 && !data_close_pending) {
349         XBT_VERB("I'm a poor lonesome process, and I have no load...");
350         last_status = false;
351
352     } else if (100.0 * total_load_running / total_load_init <=
353                opt::load_ratio_threshold) { // fixme: get locked?
354         // fixme: this check should be implemented with a distributed
355         // algorithm, and not a shared global variable!
356         XBT_VERB("No more load to balance in system.");
357         last_status = false;
358     }
359
360     return last_status;
361 }
362
363 double process::get_sum_of_to_send() const
364 {
365     using std::placeholders::_1;
366     using std::placeholders::_2;
367
368     return std::accumulate(neigh.begin(), neigh.end(), 0.0,
369                            std::bind(std::plus<double>(), _1,
370                                      std::bind(&neighbor::get_to_send, _2)));
371 }
372
373 void process::load_balance()
374 {
375     if (lb_iter == 1)           // warn only once
376         XBT_WARN("process::load_balance() is a no-op!");
377 }
378
379 void process::send(neighbor& nb, double amount)
380 {
381     expected_load -= amount;
382     nb.set_to_send(nb.get_to_send() + amount);
383     nb.set_load(nb.get_load() + amount);
384 }
385
386 void process::ctrl_send(neighbor& nb)
387 {
388     double info_to_send = expected_load;
389     double debt_to_send;
390     if (opt::bookkeeping) {     // bookkeeping
391         debt_to_send = nb.get_to_send();
392         if (debt_to_send > 0.0) {
393             nb.set_to_send(0.0);
394             nb.set_debt(nb.get_debt() + debt_to_send);
395         }
396     } else {                    // !bookkeeping
397         debt_to_send = 0.0;
398     }
399     if (info_to_send != prev_load_broadcast || debt_to_send > 0.0) {
400         message* msg = new message(message::CTRL, info_to_send, debt_to_send);
401         add_ctrl_send_mesg(msg->get_size());
402         comm.ctrl_send(nb.get_ctrl_mbox(), msg);
403     }
404 }
405
406 double process::compute_load_to_send(double desired)
407 {
408     if (opt::integer_transfer)
409         desired = std::floor(desired);
410     return desired >= opt::min_transfer_amount ? desired : 0.0;
411 }
412
413 void process::data_send(neighbor& nb)
414 {
415     double load_to_send;
416     if (opt::bookkeeping) {     // bookkeeping
417         double excess_load;     // load amount we are able to send
418         if (opt::egocentric)
419             excess_load = std::max(0.0, real_load - expected_load);
420         else
421             excess_load = real_load;
422
423         double balance;
424         if (nb.get_credit() > 0.0)
425             balance = nb.get_debt() - nb.get_credit();
426         else
427             balance = nb.get_debt();
428         load_to_send = std::min(excess_load,
429                                 std::max(0.0, balance));
430
431         // adjust load to send (rounding, truncation, etc.)
432         load_to_send = compute_load_to_send(load_to_send);
433         if (load_to_send > 0.0)
434             nb.set_debt(nb.get_debt() - load_to_send);
435     } else {                    // !bookkeeping
436         load_to_send = compute_load_to_send(nb.get_to_send());
437         if (load_to_send > 0.0)
438             nb.set_to_send(nb.get_to_send() - load_to_send);
439     }
440     real_load -= load_to_send;
441     while (load_to_send > 0.0) {
442         double amount;
443         if (opt::max_transfer_amount)
444             amount = std::min(load_to_send, opt::max_transfer_amount);
445         else
446             amount = load_to_send;
447         message* msg = new message(message::DATA, amount);
448         add_data_send_mesg(msg->get_size());
449         comm.data_send(nb.get_data_mbox(), msg);
450         load_to_send -= amount;
451     }
452 }
453
454 void process::ctrl_close(neighbor& nb)
455 {
456     comm.ctrl_send(nb.get_ctrl_mbox(), new message(message::CTRL_CLOSE, 0.0));
457 }
458
459 void process::data_close(neighbor& nb)
460 {
461     comm.data_send(nb.get_data_mbox(), new message(message::DATA_CLOSE, 0.0));
462 }
463
464 void process::ctrl_receive(double timeout)
465 {
466     message* msg;
467     msg_host_t from;
468
469     XBT_DEBUG("%sblocking receive on ctrl (%g)", "\0non-" + !timeout, timeout);
470     while (ctrl_close_pending && comm.ctrl_recv(msg, from, timeout)) {
471         if (msg->get_type() != message::CTRL_CLOSE)
472             add_ctrl_recv_mesg(msg->get_size());
473         handle_message(msg, from);
474         timeout = 0.0;
475     }
476 }
477
478 void process::data_receive(double timeout)
479 {
480     message* msg;
481     msg_host_t from;
482
483     XBT_DEBUG("%sblocking receive on data (%g)", "\0non-" + !timeout, timeout);
484     while (data_close_pending && comm.data_recv(msg, from, timeout)) {
485         if (msg->get_type() != message::DATA_CLOSE)
486             add_data_recv_mesg(msg->get_size());
487         handle_message(msg, from);
488         timeout = 0.0;
489     }
490 }
491
492 void process::handle_message(message* msg, msg_host_t from)
493 {
494     switch (msg->get_type()) {
495     case message::CTRL: {
496         neighbor* n = rev_neigh[from];
497         n->set_load(msg->get_amount() + n->get_to_send());
498         if (opt::bookkeeping) {
499             double credit = msg->get_credit();
500             expected_load += credit;
501             n->set_credit(n->get_credit() + credit);
502         }
503         break;
504     }
505     case message::DATA: {
506         neighbor* n = rev_neigh[from];
507         double ld = msg->get_amount();
508         received_load += ld;
509         n->set_credit(n->get_credit() - ld);
510         break;
511     }
512     case message::CTRL_CLOSE:
513         ctrl_close_pending--;
514         close_received = true;
515         break;
516     case message::DATA_CLOSE:
517         data_close_pending--;
518         close_received = true;
519         break;
520     }
521     delete msg;
522 }
523
524 #define print_loads_generic(vec, verbose, logp, cat)                    \
525     if (_XBT_LOG_ISENABLEDV((*cat), logp)) {                            \
526         using std::placeholders::_1;                                    \
527         XBT_XCLOG(cat, logp, "My load: %g (real); %g (expected).  "     \
528                   "Neighbor loads:", real_load, expected_load);         \
529         std::for_each(vec.begin(), vec.end(),                           \
530                       std::bind(&neighbor::print, _1, verbose, logp, cat)); \
531     } else ((void)0)
532
533 void process::print_loads(bool verbose,
534                           e_xbt_log_priority_t logp,
535                           xbt_log_category_t cat) const
536 {
537     print_loads_generic(neigh, verbose, logp, cat);
538 }
539
540 void process::print_loads_p(bool verbose,
541                             e_xbt_log_priority_t logp,
542                             xbt_log_category_t cat) const
543 {
544     print_loads_generic(pneigh, verbose, logp, cat);
545 }
546
547 #undef print_loads_generic
548
549 // Local variables:
550 // mode: c++
551 // End: