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

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