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

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