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

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