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

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