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

Private GIT Repository
ea84f78d28f4396568d036d7d540ace6fa447374
[loba.git] / main.cpp
1 #include <cerrno>
2 #include <cmath>
3 #include <csignal>
4 #include <cstring>              // strchr
5 #include <iostream>
6 #include <stdexcept>
7 #include <msg/msg.h>
8 #include <xbt/log.h>
9
10 // Creates log categories
11 XBT_LOG_NEW_CATEGORY(simu, "Root of simulation messages");
12 XBT_LOG_NEW_SUBCATEGORY(main, simu, "Messages from global infrastructure");
13 XBT_LOG_NEW_SUBCATEGORY(depl, main, "Messages from auto deployment");
14 XBT_LOG_NEW_SUBCATEGORY(comm, simu, "Messages from asynchronous pipes");
15 XBT_LOG_NEW_SUBCATEGORY(proc, simu, "Messages from base process class");
16 XBT_LOG_NEW_SUBCATEGORY(loba, simu, "Messages from load-balancer");
17 XBT_LOG_NEW_SUBCATEGORY(thrd, simu, "Messages from thread wrapper class");
18
19 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(main);
20
21 #include "deployment.h"
22 #include "hostdata.h"
23 #include "misc.h"
24 #include "options.h"
25 #include "process.h"
26 #include "statistics.h"
27 #include "synchro.h"
28 #include "timer.h"
29 #include "tracing.h"
30 #include "version.h"
31
32 #define DATA_DESCR_WIDTH 37
33
34 namespace {
35     // Failure exit status
36     enum {
37         EXIT_NO_FAILURE    = 0x00,  // no error
38         EXIT_FAILURE_ARGS  = 0x01,  // bad arguments
39         EXIT_FAILURE_INIT  = 0x02,  // failed to initialize simulator
40         EXIT_FAILURE_SIMU  = 0x04,  // simulation failed
41         EXIT_FAILURE_CLEAN = 0x08,  // error at cleanup
42         EXIT_FAILURE_INTR  = 0x10,  // interrupted by user
43         EXIT_FAILURE_LOAD  = 0x20,  // lost load on exit
44         EXIT_FAILURE_OTHER = 0x40,  // other error
45     };
46
47     // Cannot be globally initialized...
48     mutex_t* proc_mutex;
49     condition_t* proc_cond;
50     unsigned proc_counter = 0;
51
52     statistics loads;
53     statistics comps;
54     statistics comp_iterations;
55     statistics data_send_amount;
56     statistics data_recv_amount;
57     statistics data_send_count;
58     statistics data_recv_count;
59     statistics ctrl_send_amount;
60     statistics ctrl_recv_amount;
61     statistics ctrl_send_count;
62     statistics ctrl_recv_count;
63
64 }
65
66 static int simulation_main(int argc, char* argv[])
67 {
68     int result;
69     process* proc;
70     try {
71         proc = opt::loba_algorithms.new_instance(opt::loba_algo, argc, argv);
72
73         proc_mutex->acquire();
74         ++proc_counter;
75         proc_mutex->release();
76
77         result = proc->run();
78
79         proc_mutex->acquire();
80         loads.push(proc->get_real_load());
81         comps.push(proc->get_comp_amount());
82         comp_iterations.push(proc->get_comp_iter());
83         data_send_amount.push(proc->get_data_send_amount());
84         data_recv_amount.push(proc->get_data_recv_amount());
85         data_send_count.push(proc->get_data_send_count());
86         data_recv_count.push(proc->get_data_recv_count());
87         ctrl_send_amount.push(proc->get_ctrl_send_amount());
88         ctrl_recv_amount.push(proc->get_ctrl_recv_amount());
89         ctrl_send_count.push(proc->get_ctrl_send_count());
90         ctrl_recv_count.push(proc->get_ctrl_recv_count());
91
92         // Synchronization barrier...
93         // The goal is to circumvent a limitation in SimGrid (at least
94         // in version 3.5): a process must be alive when another one
95         // destroys a communication they had together.
96
97         --proc_counter;
98         proc_cond->broadcast();
99         while (proc_counter > 0)
100             proc_cond->wait(*proc_mutex);
101         proc_mutex->release();
102
103         delete proc;
104     }
105     catch (const std::invalid_argument& e) {
106         THROWF(arg_error, 0, "%s", e.what());
107     }
108     catch (const std::exception& e) {
109         THROWF(0, 0, "%s", e.what());
110     }
111     return result;
112 }
113
114 static bool check_for_lost_load()
115 {
116     bool res = true;
117     double total_init = process::get_total_load_init();
118     double total_exit = process::get_total_load_exit();
119     double lost = total_init - total_exit;
120     double lost_ratio = 100.0 * lost / total_init;
121     if (lost_ratio < -opt::load_ratio_threshold) {
122         XBT_ERROR("Gained load at exit! %g (%g%%) <============",
123                   -lost, -lost_ratio);
124         res = false;
125     } else if (lost_ratio > opt::load_ratio_threshold) {
126         XBT_ERROR("Lost load at exit! %g (%g%%) <============",
127                   lost, lost_ratio);
128         res = false;
129     } else
130         XBT_VERB("Total load at exit looks good: %g (%g%%)", lost, lost_ratio);
131
132     double total_running = process::get_total_load_running();
133     double running_ratio = 100.0 * total_running / total_init;
134     if (running_ratio < -opt::load_ratio_threshold) {
135         XBT_ERROR("Negative running load at exit! %g (%g%%) <============",
136                   total_running, running_ratio);
137         res = false;
138     } else if (running_ratio > opt::load_ratio_threshold) {
139         XBT_ERROR("Remaining running load at exit! %g (%g%%) <============",
140                   total_running, running_ratio);
141         res = false;
142     } else
143         XBT_VERB("Running load at exit looks good: %g (%g%%)",
144                  total_running, running_ratio);
145     return res;
146 }
147
148 static void signal_handler(int /*sig*/)
149 {
150     if (!opt::exit_request) {
151         XBT_CRITICAL(">>>>>>>>>>"
152                      " caught CTRL-C: global exit requested "
153                      "<<<<<<<<<<");
154         opt::exit_request = 1;
155     } else {
156         XBT_CRITICAL(">>>>>>>>>>"
157                      " caught CTRL-C for the 2nd time: exit immediately "
158                      "<<<<<<<<<<");
159         exit(EXIT_FAILURE_INTR);
160     }
161 }
162
163 static void install_signal_handler()
164 {
165     struct sigaction action;
166     action.sa_handler = signal_handler;
167     sigemptyset(&action.sa_mask);
168     action.sa_flags = SA_RESTART;
169     if (sigaction(SIGINT, &action, NULL) == -1) {
170         std::cerr << "sigaction: " << strerror(errno) << "\n";
171         exit(EXIT_FAILURE_OTHER);
172     }
173 }
174
175 #define PR_STATS(descr, st)                                             \
176     XBT_INFO("| %.*s: %g / %g / %g", DATA_DESCR_WIDTH,                  \
177              descr " (total/avg./stddev)................................", \
178              st.get_sum(), st.get_mean(), st.get_stddev())
179
180 int main(int argc, char* argv[])
181 {
182     // Note: variables used after THROW must be declared as volatile.
183     volatile int exit_status = 0;   // global exit status
184     volatile double simulated_time = -1.0;
185     timestamp elapsed_time(timestamp::wallclock_time);
186     timestamp simulation_time(timestamp::cpu_time);
187     xbt_ex_t ex;
188     MSG_error_t res;
189
190     elapsed_time.start();
191     simulation_time.start();
192
193     // Set default logging parameters
194     bool do_log_control_set = true;
195     for (int i = 1 ; do_log_control_set && i < argc ; i++)
196         do_log_control_set = !(argv[i][0] == '-' && argv[i][1] != '-' &&
197                                strchr(argv[i] + 1, 'v'));
198     if (do_log_control_set) {
199         // xbt_log_control_set("simu.thres:verbose");
200         xbt_log_control_set("simu.fmt:'[%h %r] [%c/%p] %m%n'");
201         xbt_log_control_set("main.fmt:'[%c/%p] %m%n'");
202     }
203
204     // Initialize some MSG internal data.
205     // Note: MSG_global_init() may throw an exception, but it seems
206     // impossible to catch it correctly :-(
207     MSG_global_init(&argc, argv);
208     install_signal_handler();
209
210     // Parse global parameters
211     bool parse_res = opt::parse_args(&argc, argv);
212     if (!parse_res
213         || opt::version_requested || opt::help_requested) {
214         if (opt::version_requested)
215             std::clog << version::name << " (" << opt::program_name << ")"
216                       << " version " << version::num << "\n"
217                       << version::copyright << "\n"
218                 "Compiled on " << version::date << "\n\n";
219         if (!parse_res || opt::help_requested)
220             opt::usage();
221         MSG_clean();
222         exit(parse_res ? EXIT_NO_FAILURE : EXIT_FAILURE_ARGS);
223     }
224     XBT_INFO("%s v%s (%s)", opt::program_name.c_str(), version::num.c_str(),
225           version::date.c_str());
226     opt::print();
227
228     TRY {
229         exit_status = EXIT_FAILURE_INIT; // =====
230
231         // Register the default function of an agent
232         // MSG_function_register("simulation_main", simulation_main);
233         MSG_function_register_default(simulation_main);
234
235         // Create the platform and the application.
236         XBT_DEBUG("Loading platform file...");
237         MSG_create_environment(opt::platform_file.c_str());
238         XBT_DEBUG("Creating hostdata...");
239         hostdata::create();
240         XBT_INFO("Loaded description of %zd hosts.", hostdata::size());
241         XBT_DEBUG("Deploying processes...");
242         if (opt::auto_depl::enabled) {
243             if (!opt::auto_depl::nhosts)
244                 opt::auto_depl::nhosts = hostdata::size();
245             if (opt::auto_depl::nhosts > hostdata::size()) {
246                 XBT_WARN("%u hosts is too much: limiting to %zu",
247                          opt::auto_depl::nhosts, hostdata::size());
248                 opt::auto_depl::nhosts = hostdata::size();
249             }
250             if (opt::auto_depl::load == 0.0) {
251                 XBT_WARN("Initial load is zero!  "
252                          "Falling back on old behaviour (load = nhosts).");
253                 opt::auto_depl::load = opt::auto_depl::nhosts;
254             } else if (opt::auto_depl::load < 0.0)
255                 opt::auto_depl::load =
256                     -opt::auto_depl::load * opt::auto_depl::nhosts;
257             double iload = std::trunc(opt::auto_depl::load);
258             if (opt::integer_transfer && opt::auto_depl::load != iload) {
259                 XBT_WARN("Total load %g is not an integer.  Truncate it.",
260                          opt::auto_depl::load);
261                 opt::auto_depl::load = iload;
262             }
263             MY_launch_application(); // it is already opt::* aware...
264         } else {
265             MSG_launch_application(opt::deployment_file.c_str());
266         }
267
268         // Register tracing categories
269         TRACE_category_with_color(TRACE_CAT_COMP, TRACE_COLOR_COMP);
270         TRACE_category_with_color(TRACE_CAT_CTRL, TRACE_COLOR_CTRL);
271         TRACE_category_with_color(TRACE_CAT_DATA, TRACE_COLOR_DATA);
272
273         exit_status = EXIT_FAILURE_SIMU; // =====
274
275         proc_mutex = new mutex_t();
276         proc_cond = new condition_t();
277
278         // Launch the MSG simulation.
279         XBT_INFO("Starting simulation at %f...", MSG_get_clock());
280         res = MSG_main();
281         simulated_time = MSG_get_clock();
282         XBT_INFO("Simulation ended at %f.", simulated_time);
283
284         delete proc_cond;
285         delete proc_mutex;
286
287         if (res != MSG_OK)
288             THROWF(0, 0, "MSG_main() failed with status %#x", res);
289
290         exit_status = EXIT_NO_FAILURE; // =====
291     }
292     CATCH (ex) {
293         int len = strlen(ex.msg);
294         if (len > 0 && ex.msg[len - 1] == '\n')
295             ex.msg[len - 1] = '\0'; // strip the ending '\n'
296         XBT_ERROR("%s", ex.msg);
297         XBT_DEBUG("Error from %s() in %s:%d", ex.func, ex.file, ex.line);
298         xbt_ex_free(ex);
299     }
300
301     // Clean the MSG simulation.
302     hostdata::destroy();
303     res = MSG_clean();
304     if (res != MSG_OK) {
305         XBT_ERROR("MSG_clean() failed with status %#x", res);
306         exit_status |= EXIT_FAILURE_CLEAN;
307     }
308
309     // Report final simulation status.
310     if (simulated_time >= 0.0) {
311         simulation_time.stop();
312         elapsed_time.stop();
313         if (!check_for_lost_load())
314             exit_status |= EXIT_FAILURE_LOAD;
315         XBT_INFO(",----[ Results ]");
316         PR_STATS("Load", loads);
317         PR_STATS("Computation", comps);
318         PR_STATS("Comp. iterations", comp_iterations);
319         PR_STATS("Data send amount", data_send_amount);
320         PR_STATS("Data recv amount", data_recv_amount);
321         PR_STATS("Data send count", data_send_count);
322         PR_STATS("Data recv count", data_recv_count);
323         PR_STATS("Ctrl send amount", ctrl_send_amount);
324         PR_STATS("Ctrl recv amount", ctrl_recv_amount);
325         PR_STATS("Ctrl send count", ctrl_send_count);
326         PR_STATS("Ctrl recv count", ctrl_recv_count);
327         XBT_INFO("| %.*s: %g", DATA_DESCR_WIDTH,
328                  "Total simulated time..................................",
329                  simulated_time);
330         XBT_INFO("| %.*s: %g", DATA_DESCR_WIDTH,
331                  "Total simulation time.................................",
332                  simulation_time.duration());
333         XBT_INFO("| %.*s: %g", DATA_DESCR_WIDTH,
334                  "Elapsed (wall clock) time.............................",
335                  elapsed_time.duration());
336         XBT_INFO("`----");
337     }
338     if (exit_status)
339         XBT_ERROR("Simulation failed (%#x).", exit_status);
340     else
341         XBT_INFO("Simulation succeeded.");
342
343     return exit_status;
344 }
345
346 // Local variables:
347 // mode: c++
348 // End: