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

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