Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
Use bigger chunk allocations in sync_queue.
[loba.git] / process.cpp
index 4ee3647d6895c4eef6586f92f29ffc498b45b14e..b36b000f385309ee102c283c7139244d4c3e8a26 100644 (file)
 #include <algorithm>
 #include <functional>
 #include <iterator>
 #include <algorithm>
 #include <functional>
 #include <iterator>
+#include <numeric>
 #include <stdexcept>
 #include <sstream>
 #include <xbt/log.h>
 #include <xbt/time.h>
 #include <stdexcept>
 #include <sstream>
 #include <xbt/log.h>
 #include <xbt/time.h>
+
+XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(proc);
+
 #include "misc.h"
 #include "options.h"
 #include "misc.h"
 #include "options.h"
+#include "tracing.h"
+
 #include "process.h"
 
 #include "process.h"
 
-XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simu);
+double process::total_load_init = 0.0;
+double process::total_load_running = 0.0;
+double process::total_load_exit = 0.0;
+
+namespace {
+
+    void sleep_until_date(double& date, double duration)
+    {
+        double sleep_duration = date - MSG_get_clock();
+        if (sleep_duration > 0.0)
+            MSG_process_sleep(sleep_duration);
+        date = MSG_get_clock() + duration;
+    }
+
+}
 
 process::process(int argc, char* argv[])
 {
 
 process::process(int argc, char* argv[])
 {
-    if (argc < 2 || !(std::istringstream(argv[1]) >> load))
-        throw std::invalid_argument("bad or missing initial load");
+    if (argc < 2 || !(std::istringstream(argv[1]) >> real_load))
+        throw std::invalid_argument("bad or missing initial load parameter");
+
     neigh.assign(argv + 2, argv + argc);
     neigh.assign(argv + 2, argv + argc);
-    expected_load = load;
+
+    pneigh.reserve(neigh.size());
+    for (unsigned i = 0 ; i < neigh.size() ; i++) {
+        neighbor* ptr = &neigh[i];
+        m_host_t host = MSG_get_host_by_name(ptr->get_name());
+        pneigh.push_back(ptr);
+        rev_neigh.insert(std::make_pair(host, ptr));
+    }
+
+    prev_load_broadcast = -1;   // force sending of load on first send_all()
+    expected_load = real_load;
+    total_load_running += real_load;
+    total_load_init += real_load;
+
+    ctrl_close_pending = data_close_pending = neigh.size();
+    close_received = false;
+    finalizing = false;
+
+    comp_iter = lb_iter = 0;
+
+    lb_thread = new_msg_thread("loba",
+                               std::bind(&process::load_balance_loop, this));
+
     e_xbt_log_priority_t logp = xbt_log_priority_verbose;
     if (!LOG_ISENABLED(logp))
         return;
     e_xbt_log_priority_t logp = xbt_log_priority_verbose;
     if (!LOG_ISENABLED(logp))
         return;
-    LOG1(logp, "My initial load is: %g", load);
     std::ostringstream oss;
     oss << neigh.size() << " neighbor";
     if (!neigh.empty()) {
     std::ostringstream oss;
     oss << neigh.size() << " neighbor";
     if (!neigh.empty()) {
-        oss << (neigh.size() > 1 ? "s: " : ": ");
+        oss << ESSE(neigh.size()) << ": ";
         std::transform(neigh.begin(), neigh.end() - 1,
                        std::ostream_iterator<const char*>(oss, ", "),
         std::transform(neigh.begin(), neigh.end() - 1,
                        std::ostream_iterator<const char*>(oss, ", "),
-                       std::mem_fun_ref(&neighbor::get_name));
+                       std::mem_fn(&neighbor::get_name));
         oss << neigh.back().get_name();
     }
         oss << neigh.back().get_name();
     }
-    LOG1(logp, "Got %s.", oss.str().c_str());
-    print_loads(logp);
+    XBT_LOG(logp, "Got %s.", oss.str().c_str());
+    print_loads(false, logp);
+}
+
+process::~process()
+{
+    delete lb_thread;
+    total_load_exit += real_load;
+    if (opt::log_rate < 0)
+        return;
+    XBT_INFO("Final load after %d:%d iterations: %g",
+             lb_iter, comp_iter, real_load);
+    XBT_VERB("Expected load was: %g", expected_load);
+    XBT_VERB("Total computation for this process: %g", get_comp_amount());
 }
 
 int process::run()
 {
 }
 
 int process::run()
 {
-    INFO0("Coucou !");
+    if (opt::log_rate >= 0) {
+        XBT_INFO("Initial load: %g", real_load);
+        XBT_VERB("Initial expected load: %g", expected_load);
+    }
+    XBT_VERB("Starting...");
+    mutex.acquire();
+    lb_thread->start();
+    while (lb_iter <= opt::comp_iter_delay)
+        cond.wait(mutex);
+    mutex.release();
+    double sleep_duration = opt::comp_time_delay - MSG_get_clock();
+    if (sleep_duration > 0.0)
+        MSG_process_sleep(sleep_duration);
+    compute_loop();
+    lb_thread->wait();
+    XBT_VERB("Done.");
+    return 0;
+}
+
+void process::load_balance_loop()
+{
+    using std::placeholders::_1;
+
+    double next_iter_after_date = MSG_get_clock() + opt::min_lb_iter_duration;
+    while (still_running()) {
+        if (lb_iter == opt::comp_iter_delay) {
+            mutex.acquire();
+            ++lb_iter;
+            cond.signal();
+            mutex.release();
+        } else {
+            ++lb_iter;
+        }
+
+        mutex.acquire();
+        if (!opt::bookkeeping)
+            expected_load = real_load - get_sum_of_to_send();
+        // nothing to do with opt::bookkeeping
 
 
-    int n = 100;
-    while (n--) {
-        if (load > 0)
-            compute();
+        if (opt::log_rate && lb_iter % opt::log_rate == 0) {
+            XBT_INFO("(%u:%u) current load: %g", lb_iter, comp_iter, real_load);
+            XBT_VERB("... expected load: %g", expected_load);
+        }
+
+        if (expected_load > 0.0)
+            load_balance();
+
+        print_loads(true, xbt_log_priority_debug);
+
+        // send
+        comm.ctrl_flush(false);
+        std::for_each(neigh.begin(), neigh.end(),
+                      std::bind(&process::ctrl_send, this, _1));
+        prev_load_broadcast = expected_load;
+        mutex.release();
+
+        sleep_until_date(next_iter_after_date, opt::min_lb_iter_duration);
+        ctrl_receive(0.0);
+    }
+
+    XBT_VERB("Going to finalize for %s...", __func__);
+    XBT_DEBUG("send CTRL_CLOSE to %zu neighbor%s",
+              neigh.size(), ESSE(neigh.size()));
+    std::for_each(neigh.begin(), neigh.end(),
+                  std::bind(&process::ctrl_close, this, _1));
+    while (ctrl_close_pending) {
+        comm.ctrl_flush(false);
+        XBT_DEBUG("waiting for %d CTRL CLOSE", ctrl_close_pending);
+        ctrl_receive(-1.0);
+    }
+    comm.ctrl_flush(true);
+}
+
+void process::compute_loop()
+{
+    using std::placeholders::_1;
+
+    double next_iter_after_date = MSG_get_clock() + opt::min_comp_iter_duration;
+    while (still_running()) {
+        // receive
+        mutex.acquire();
+        if (real_load > 0.0)
+            data_receive(0.0);
         else
         else
-            xbt_sleep(0.5);     // fixme
-        receive();
-    }
-    //    MSG_process_sleep(100.0);   // xxx
-    /* xxx:
-     * while (there is something to do) {
-     *    compute some task;
-     *    get received tasks;
-     *    compute load balancing;
-     *    send tasks to neighbors;
-     * }
-     */
-
-    /* Open Questions :
-     * - definition of load on heterogeneous hosts ?
-     * - how to detect convergence ?
-     * - how to manage link failures ?
-     */
-
-    // xxx: shall we retrieve pending tasks?
+            data_receive(opt::min_comp_iter_duration);
+        mutex.release();
 
 
-    return 0;
+        // send
+        comm.data_flush(false);
+        mutex.acquire();
+        std::for_each(neigh.begin(), neigh.end(),
+                      std::bind(&process::data_send, this, _1));
+        mutex.release();
+
+        if (real_load == 0.0)
+            continue;
+
+        // compute
+        ++comp_iter;
+        double flops = opt::comp_cost(real_load);
+        m_task_t task = MSG_task_create("computation", flops, 0.0, NULL);
+        TRACE_msg_set_task_category(task, TRACE_CAT_COMP);
+        XBT_DEBUG("compute %g flop%s", flops, ESSE(flops));
+        MSG_task_execute(task);
+        add_comp_amount(flops);
+        MSG_task_destroy(task);
+
+        sleep_until_date(next_iter_after_date, opt::min_comp_iter_duration);
+    }
+
+    XBT_VERB("Going to finalize for %s...", __func__);
+    // last send, for not losing load scheduled to be sent
+    std::for_each(neigh.begin(), neigh.end(),
+                  std::bind(&process::data_send, this, _1));
+    finalizing = true;
+    total_load_running -= real_load;
+    XBT_DEBUG("send DATA_CLOSE to %zu neighbor%s",
+              neigh.size(), ESSE(neigh.size()));
+    std::for_each(neigh.begin(), neigh.end(),
+                  std::bind(&process::data_close, this, _1));
+    while (data_close_pending) {
+        comm.data_flush(false);
+        XBT_DEBUG("waiting for %d DATA CLOSE", data_close_pending);
+        data_receive(-1.0);
+    }
+    comm.data_flush(true);
 }
 
 }
 
-void process::receive()
+bool process::still_running()
 {
 {
-    bool received;
-    do {
-        double amount;
-        m_host_t from;
-        received = false;
-        if (comm.recv_info(amount, from)) {
-            // fixme: update neighbor
-            received = true;
+    static bool last_status = true;
+
+    if (!last_status) {
+        /* nop */
+
+    } else if (opt::exit_request) {
+        XBT_VERB("Global exit requested");
+        last_status = false;
+
+    } else if (opt::time_limit && MSG_get_clock() >= opt::time_limit) {
+        XBT_VERB("Reached time limit: %g/%g", MSG_get_clock(), opt::time_limit);
+        last_status = false;
+
+    } else if (opt::lb_maxiter && lb_iter >= opt::lb_maxiter) {
+        XBT_VERB("Reached lb_maxiter: %d/%d", lb_iter, opt::lb_maxiter);
+        last_status = false;
+
+    } else if (opt::comp_maxiter && comp_iter >= opt::comp_maxiter) {
+        XBT_VERB("Reached comp_maxiter: %d/%d", comp_iter, opt::comp_maxiter);
+        last_status = false;
+
+    } else if (opt::exit_on_close && close_received) {
+        XBT_VERB("Close received");
+        last_status = false;
+
+    } else if (real_load == 0.0 && !data_close_pending) {
+        XBT_VERB("I'm a poor lonesome process, and I have no load...");
+        last_status = false;
+
+    } else if (100.0 * total_load_running / total_load_init <=
+               opt::load_ratio_threshold) {
+        // fixme: this check should be implemented with a distributed
+        // algorithm, and not a shared global variable!
+        XBT_VERB("No more load to balance in system.");
+        last_status = false;
+    }
+
+    return last_status;
+}
+
+double process::get_sum_of_to_send() const
+{
+    using std::placeholders::_1;
+    using std::placeholders::_2;
+
+    return std::accumulate(neigh.begin(), neigh.end(), 0.0,
+                           std::bind(std::plus<double>(), _1,
+                                     std::bind(&neighbor::get_to_send, _2)));
+}
+
+void process::load_balance()
+{
+    if (lb_iter == 1)           // warn only once
+        XBT_WARN("process::load_balance() is a no-op!");
+}
+
+void process::send(neighbor& nb, double amount)
+{
+    expected_load -= amount;
+    nb.set_to_send(nb.get_to_send() + amount);
+    nb.set_load(nb.get_load() + amount);
+}
+
+void process::ctrl_send(neighbor& nb)
+{
+    double info_to_send = expected_load;
+    if (info_to_send != prev_load_broadcast) {
+        message* msg = new message(message::INFO, info_to_send);
+        add_ctrl_send_mesg(msg->get_size());
+        comm.ctrl_send(nb.get_ctrl_mbox(), msg);
+    }
+    if (opt::bookkeeping) {
+        double debt_to_send = nb.get_to_send();
+        if (debt_to_send > 0.0) {
+            nb.set_to_send(0.0);
+            nb.set_debt(nb.get_debt() + debt_to_send);
+            message* msg = new message(message::CREDIT, debt_to_send);
+            add_ctrl_send_mesg(msg->get_size());
+            comm.ctrl_send(nb.get_ctrl_mbox(), msg);
         }
         }
-        if (comm.recv_credit(amount, from)) {
-            expected_load += amount;
-            received = true;
+    }
+}
+
+void process::data_send(neighbor& nb)
+{
+    double load_to_send;
+    if (opt::bookkeeping) {
+        load_to_send = std::min(real_load, nb.get_debt());
+        if (load_to_send >= opt::min_transfer_amount) {
+            nb.set_debt(nb.get_debt() - load_to_send);
+            real_load -= load_to_send;
+        } else {
+            load_to_send = 0.0;
         }
         }
-        if (comm.recv_load(amount, from)) {
-            load += amount;
-            received = true;
+    } else {
+        load_to_send = nb.get_to_send();
+        if (load_to_send >= opt::min_transfer_amount) {
+            nb.set_to_send(0.0);
+            real_load -= load_to_send;
+        } else {
+            load_to_send = 0.0;
         }
         }
-    } while (received);
+    }
+    while (load_to_send > 0.0) {
+        double amount;
+        if (opt::max_transfer_amount)
+            amount = std::min(load_to_send, opt::max_transfer_amount);
+        else
+            amount = load_to_send;
+        message* msg = new message(message::LOAD, amount);
+        add_data_send_mesg(msg->get_size());
+        comm.data_send(nb.get_data_mbox(), msg);
+        load_to_send -= amount;
+    }
 }
 
 }
 
-void process::compute()
+void process::ctrl_close(neighbor& nb)
 {
 {
-    double duration = opt::comp_cost(load);
-    m_task_t task = MSG_task_create("computation", duration, 0.0, NULL);
-    DEBUG2("Compute %g flop%s.", duration, duration > 1 ? "s" : "");
-    MSG_task_execute(task);
-    MSG_task_destroy(task);
+    comm.ctrl_send(nb.get_ctrl_mbox(), new message(message::CTRL_CLOSE, 0.0));
 }
 
 }
 
-void process::print_loads(e_xbt_log_priority_t logp)
+void process::data_close(neighbor& nb)
 {
 {
-    if (!LOG_ISENABLED(logp))
-        return;
-    std::ostringstream oss;
-    if (neigh.empty()) {
-        oss << "no neighbor!";
-    } else {
-        std::transform(neigh.begin(), neigh.end() - 1,
-                       std::ostream_iterator<double>(oss, ", "),
-                       std::mem_fun_ref(&neighbor::get_load));
-        oss << neigh.back().get_load();
+    comm.data_send(nb.get_data_mbox(), new message(message::DATA_CLOSE, 0.0));
+}
+
+void process::ctrl_receive(double timeout)
+{
+    message* msg;
+    m_host_t from;
+
+    XBT_DEBUG("%sblocking receive on ctrl (%g)", "\0non-" + !timeout, timeout);
+    while (ctrl_close_pending && comm.ctrl_recv(msg, from, timeout)) {
+        if (msg->get_type() != message::CTRL_CLOSE)
+            add_ctrl_recv_mesg(msg->get_size());
+        handle_message(msg, from);
+        timeout = 0.0;
     }
     }
-    LOG1(logp, "Neighbor loads: %s", oss.str().c_str());
 }
 
 }
 
+void process::data_receive(double timeout)
+{
+    message* msg;
+    m_host_t from;
+
+    XBT_DEBUG("%sblocking receive on data (%g)", "\0non-" + !timeout, timeout);
+    while (data_close_pending && comm.data_recv(msg, from, timeout)) {
+        if (msg->get_type() != message::DATA_CLOSE)
+            add_data_recv_mesg(msg->get_size());
+        handle_message(msg, from);
+        timeout = 0.0;
+    }
+}
+
+void process::handle_message(message* msg, m_host_t from)
+{
+    switch (msg->get_type()) {
+    case message::INFO: {
+        neighbor* n = rev_neigh[from];
+        n->set_load(msg->get_amount() + n->get_to_send());
+        break;
+    }
+    case message::CREDIT:
+        expected_load += msg->get_amount();
+        break;
+    case message::LOAD: {
+        double ld = msg->get_amount();
+        real_load += ld;
+        if (finalizing)
+            total_load_running -= ld;
+        break;
+    }
+    case message::CTRL_CLOSE:
+        ctrl_close_pending--;
+        close_received = true;
+        break;
+    case message::DATA_CLOSE:
+        data_close_pending--;
+        close_received = true;
+        break;
+    }
+    delete msg;
+}
+
+#define print_loads_generic(vec, verbose, logp, cat)                    \
+    if (_XBT_LOG_ISENABLEDV((*cat), logp)) {                            \
+        using std::placeholders::_1;                                    \
+        XBT_XCLOG(cat, logp, "My load: %g (real); %g (expected).  "     \
+                  "Neighbor loads:", real_load, expected_load);         \
+        std::for_each(vec.begin(), vec.end(),                           \
+                      std::bind(&neighbor::print, _1, verbose, logp, cat)); \
+    } else ((void)0)
+
+void process::print_loads(bool verbose,
+                          e_xbt_log_priority_t logp,
+                          xbt_log_category_t cat) const
+{
+    print_loads_generic(neigh, verbose, logp, cat);
+}
+
+void process::print_loads_p(bool verbose,
+                            e_xbt_log_priority_t logp,
+                            xbt_log_category_t cat) const
+{
+    print_loads_generic(pneigh, verbose, logp, cat);
+}
+
+#undef print_loads_generic
+
 // Local variables:
 // mode: c++
 // End:
 // Local variables:
 // mode: c++
 // End: