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

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