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

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