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

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