Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
If it is a win plateform we have to use wenvironment against environment.
[simgrid.git] / src / gras / Msg / gras_msg_exchange.c
1 /* gras message exchanges                                                   */
2
3 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "xbt/ex.h"
10 #include "xbt/ex_interface.h"
11 #include "gras/Msg/msg_private.h"
12 #include "gras/Virtu/virtu_interface.h"
13
14 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(gras_msg);
15
16
17 char _GRAS_header[6];
18 const char *e_gras_msg_kind_names[e_gras_msg_kind_count] =
19   { "UNKNOWN", "ONEWAY", "RPC call", "RPC answer", "RPC error" };
20
21
22 /** \brief Waits for a message to come in over a given socket.
23  *
24  * @param timeout: How long should we wait for this message.
25  * @param msgt_want: type of awaited msg (or NULL if I'm enclined to accept any message)
26  * @param expe_want: awaited expeditot (match on hostname, not port; NULL if not relevant)
27  * @param filter: function returning true or false when passed a payload. Messages for which it returns false are not selected. (NULL if not relevant)
28  * @param filter_ctx: context passed as second argument of the filter (a pattern to match?)
29  * @param[out] msg_got: where to write the message we got
30  *
31  * Every message of another type received before the one waited will be queued
32  * and used by subsequent call to this function or gras_msg_handle().
33  */
34
35 void
36 gras_msg_wait_ext_(double timeout,
37                    gras_msgtype_t msgt_want,
38                    gras_socket_t expe_want,
39                    gras_msg_filter_t filter,
40                    void *filter_ctx, gras_msg_t msg_got)
41 {
42
43   s_gras_msg_t msg;
44   double start, now;
45   gras_msg_procdata_t pd =
46     (gras_msg_procdata_t) gras_libdata_by_id(gras_msg_libdata_id);
47   unsigned int cpt;
48
49   xbt_assert0(msg_got, "msg_got is an output parameter");
50
51   start = gras_os_time();
52   VERB2("Waiting for message '%s' for %fs",
53         msgt_want ? msgt_want->name : "(any)", timeout);
54
55   xbt_dynar_foreach(pd->msg_waitqueue, cpt, msg) {
56     if ((!msgt_want || (msg.type->code == msgt_want->code))
57         && (!expe_want || (!strcmp(gras_socket_peer_name(msg.expe),
58                                    gras_socket_peer_name(expe_want))))
59         && (!filter || filter(&msg, filter_ctx))) {
60
61       memcpy(msg_got, &msg, sizeof(s_gras_msg_t));
62       xbt_dynar_cursor_rm(pd->msg_waitqueue, &cpt);
63       VERB0("The waited message was queued");
64       return;
65     }
66   }
67
68   xbt_dynar_foreach(pd->msg_queue, cpt, msg) {
69     if ((!msgt_want || (msg.type->code == msgt_want->code))
70         && (!expe_want || (!strcmp(gras_socket_peer_name(msg.expe),
71                                    gras_socket_peer_name(expe_want))))
72         && (!filter || filter(&msg, filter_ctx))) {
73
74       memcpy(msg_got, &msg, sizeof(s_gras_msg_t));
75       xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
76       VERB0("The waited message was queued");
77       return;
78     }
79   }
80
81   while (1) {
82     int need_restart;
83     xbt_ex_t e;
84
85   restart_receive:             /* Goto here when the receive of a message failed */
86     need_restart = 0;
87     now = gras_os_time();
88     memset(&msg, 0, sizeof(msg));
89
90     TRY {
91       xbt_queue_shift_timed(pd->msg_received, &msg,
92                             timeout ? timeout - now + start : 0);
93     }
94     CATCH(e) {
95       if (e.category == system_error &&
96           !strncmp("Socket closed by remote side", e.msg,
97                    strlen("Socket closed by remote side"))) {
98         xbt_ex_free(e);
99         need_restart = 1;
100       } else {
101         RETHROW;
102       }
103     }
104     if (need_restart)
105       goto restart_receive;
106
107     DEBUG0("Got a message from the socket");
108
109     if ((!msgt_want || (msg.type->code == msgt_want->code))
110         && (!expe_want || (!strcmp(gras_socket_peer_name(msg.expe),
111                                    gras_socket_peer_name(expe_want))))
112         && (!filter || filter(&msg, filter_ctx))) {
113
114       memcpy(msg_got, &msg, sizeof(s_gras_msg_t));
115       DEBUG0("Message matches expectations. Use it.");
116       return;
117     }
118     DEBUG0("Message does not match expectations. Queue it.");
119
120     /* not expected msg type. Queue it for later */
121     xbt_dynar_push(pd->msg_queue, &msg);
122
123     now = gras_os_time();
124     if (now - start + 0.001 > timeout) {
125       THROW1(timeout_error, now - start + 0.001 - timeout,
126              "Timeout while waiting for msg '%s'",
127              msgt_want ? msgt_want->name : "(any)");
128     }
129   }
130
131   THROW_IMPOSSIBLE;
132 }
133
134 /** \brief Waits for a message to come in over a given socket.
135  *
136  * @param timeout: How long should we wait for this message.
137  * @param msgt_want: type of awaited msg
138  * @param[out] expeditor: where to create a socket to answer the incomming message
139  * @param[out] payload: where to write the payload of the incomming message
140  * @return the error code (or no_error).
141  *
142  * Every message of another type received before the one waited will be queued
143  * and used by subsequent call to this function or gras_msg_handle().
144  */
145 void
146 gras_msg_wait_(double timeout,
147                gras_msgtype_t msgt_want,
148                gras_socket_t * expeditor, void *payload)
149 {
150   s_gras_msg_t msg;
151
152   gras_msg_wait_ext_(timeout, msgt_want, NULL, NULL, NULL, &msg);
153
154   if (msgt_want->ctn_type) {
155     xbt_assert1(payload,
156                 "Message type '%s' convey a payload you must accept",
157                 msgt_want->name);
158   } else {
159     xbt_assert1(!payload,
160                 "No payload was declared for message type '%s'",
161                 msgt_want->name);
162   }
163
164   if (payload) {
165     memcpy(payload, msg.payl, msg.payl_size);
166     free(msg.payl);
167   }
168
169   if (expeditor)
170     *expeditor = msg.expe;
171 }
172
173 static int gras_msg_wait_or_filter(gras_msg_t msg, void *ctx)
174 {
175   xbt_dynar_t dyn = (xbt_dynar_t) ctx;
176   int res = xbt_dynar_member(dyn, msg->type);
177   if (res)
178     VERB1("Got matching message (type=%s)", msg->type->name);
179   else
180     VERB0("Got message not matching our expectations");
181   return res;
182 }
183
184 /** \brief Waits for a message to come in over a given socket.
185  *
186  * @param timeout: How long should we wait for this message.
187  * @param msgt_want: a dynar containing all accepted message type
188  * @param[out] ctx: the context of received message (in case it's a RPC call we want to answer to)
189  * @param[out] msgt_got: indice in the dynar of the type of the received message
190  * @param[out] payload: where to write the payload of the incomming message
191  * @return the error code (or no_error).
192  *
193  * Every message of a type not in the accepted list received before the one
194  * waited will be queued and used by subsequent call to this function or
195  * gras_msg_handle().
196  *
197  * If you are interested in the context, pass the address of a s_gras_msg_cb_ctx_t variable.
198  */
199 void gras_msg_wait_or(double timeout,
200                       xbt_dynar_t msgt_want,
201                       gras_msg_cb_ctx_t * ctx, int *msgt_got, void *payload)
202 {
203   s_gras_msg_t msg;
204
205   VERB1("Wait %f seconds for several message types", timeout);
206   gras_msg_wait_ext_(timeout,
207                      NULL, NULL,
208                      &gras_msg_wait_or_filter, (void *) msgt_want, &msg);
209
210   if (msg.type->ctn_type) {
211     xbt_assert1(payload,
212                 "Message type '%s' convey a payload you must accept",
213                 msg.type->name);
214   }
215   /* don't check the other side since some of the types may have a payload */
216   if (payload && msg.type->ctn_type) {
217     memcpy(payload, msg.payl, msg.payl_size);
218     free(msg.payl);
219   }
220
221   if (ctx)
222     *ctx = gras_msg_cb_ctx_new(msg.expe, msg.type, msg.ID,
223                                (msg.kind == e_gras_msg_kind_rpccall), 60);
224
225   if (msgt_got)
226     *msgt_got = xbt_dynar_search(msgt_want, msg.type);
227 }
228
229
230 /** \brief Send the data pointed by \a payload as a message of type
231  * \a msgtype to the peer \a sock */
232 void gras_msg_send_(gras_socket_t sock, gras_msgtype_t msgtype, void *payload)
233 {
234
235   if (msgtype->ctn_type) {
236     xbt_assert1(payload,
237                 "Message type '%s' convey a payload you must provide",
238                 msgtype->name);
239   } else {
240     xbt_assert1(!payload,
241                 "No payload was declared for message type '%s'",
242                 msgtype->name);
243   }
244
245   DEBUG2("Send a oneway message of type '%s'. Payload=%p",
246          msgtype->name, payload);
247   gras_msg_send_ext(sock, e_gras_msg_kind_oneway, 0, msgtype, payload);
248   VERB2("Sent a oneway message of type '%s'. Payload=%p",
249         msgtype->name, payload);
250 }
251
252 /** @brief Handle all messages arriving within the given period
253  *
254  * @param period: How long to wait for incoming messages (in seconds)
255  *
256  * Messages are dealed with just like gras_msg_handle() would do. The
257  * difference is that gras_msg_handle() handles at most one message (or wait up
258  * to timeout second when no message arrives) while this function handles any
259  * amount of messages, and lasts the given period in any case.
260  */
261 void gras_msg_handleall(double period)
262 {
263   xbt_ex_t e;
264   double begin = gras_os_time();
265   double now;
266
267   do {
268     now = gras_os_time();
269     TRY {
270       if (period - now + begin > 0)
271         gras_msg_handle(period - now + begin);
272     }
273     CATCH(e) {
274       if (e.category != timeout_error)
275         RETHROW0("Error while waiting for messages: %s");
276       xbt_ex_free(e);
277     }
278     /* Epsilon to avoid numerical stability issues were the waited interval is so small that the global clock cannot notice the increment */
279   } while (period - now + begin > 0);
280 }
281
282 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
283  *
284  * @param timeOut: How long to wait for incoming messages (in seconds)
285  * @return the error code (or no_error).
286  *
287  * Any message arriving in the given interval is passed to the callbacks.
288  *
289  * @sa gras_msg_handleall().
290  */
291 void gras_msg_handle(double timeOut)
292 {
293
294   double untiltimer;
295
296   unsigned int cpt;
297   int volatile ran_ok;
298
299   s_gras_msg_t msg;
300
301   gras_msg_procdata_t pd =
302     (gras_msg_procdata_t) gras_libdata_by_id(gras_msg_libdata_id);
303   gras_cblist_t *list = NULL;
304   gras_msg_cb_t cb;
305   s_gras_msg_cb_ctx_t ctx;
306
307   int timerexpected, timeouted;
308   xbt_ex_t e;
309
310   VERB1("Handling message within the next %.2fs", timeOut);
311
312   untiltimer = gras_msg_timer_handle();
313   DEBUG1("Next timer in %f sec", untiltimer);
314   if (untiltimer == 0.0) {
315     /* A timer was already elapsed and handled */
316     return;
317   }
318   if (untiltimer != -1.0) {
319     timerexpected = 1;
320     timeOut = MIN(timeOut, untiltimer);
321   } else {
322     timerexpected = 0;
323   }
324
325   /* get a message (from the queue or from the net) */
326   timeouted = 0;
327   if (xbt_dynar_length(pd->msg_queue)) {
328     DEBUG0("Get a message from the queue");
329     xbt_dynar_shift(pd->msg_queue, &msg);
330   } else {
331     TRY {
332       xbt_queue_shift_timed(pd->msg_received, &msg, timeOut);
333       //      msg.expe = gras_trp_select(timeOut);
334     }
335     CATCH(e) {
336       if (e.category != timeout_error)
337         RETHROW;
338       DEBUG0("Damn. Timeout while getting a message from the queue");
339       xbt_ex_free(e);
340       timeouted = 1;
341     }
342   }
343
344   if (timeouted) {
345     if (timerexpected) {
346
347       /* A timer elapsed before the arrival of any message even if we select()ed a bit */
348       untiltimer = gras_msg_timer_handle();
349       if (untiltimer == 0.0) {
350         /* we served a timer, we're done */
351         return;
352       } else {
353         xbt_assert1(untiltimer > 0, "Negative timer (%f). I'm 'puzzeled'",
354                     untiltimer);
355         WARN1
356           ("No timer elapsed, in contrary to expectations (next in %f sec)",
357            untiltimer);
358         THROW1(timeout_error, 0,
359                "No timer elapsed, in contrary to expectations (next in %f sec)",
360                untiltimer);
361       }
362
363     } else {
364       /* select timeouted, and no timer elapsed. Nothing to do */
365       THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
366              timeOut);
367     }
368
369   }
370
371   /* A message was already there or arrived in the meanwhile. handle it */
372   xbt_dynar_foreach(pd->cbl_list, cpt, list) {
373     if (list->id == msg.type->code) {
374       break;
375     } else {
376       list = NULL;
377     }
378   }
379   if (!list) {
380     INFO4
381       ("No callback for message '%s' (type:%s) from %s:%d. Queue it for later gras_msg_wait() use.",
382        msg.type->name, e_gras_msg_kind_names[msg.kind],
383        gras_socket_peer_name(msg.expe), gras_socket_peer_port(msg.expe));
384     xbt_dynar_push(pd->msg_waitqueue, &msg);
385     return;                     /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
386   }
387
388   ctx.expeditor = msg.expe;
389   ctx.ID = msg.ID;
390   ctx.msgtype = msg.type;
391   ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
392
393   switch (msg.kind) {
394   case e_gras_msg_kind_oneway:
395   case e_gras_msg_kind_rpccall:
396     ran_ok = 0;
397     TRY {
398       xbt_dynar_foreach(list->cbs, cpt, cb) {
399         if (!ran_ok) {
400           DEBUG4
401             ("Use the callback #%d (@%p) for incomming msg '%s' (payload_size=%d)",
402              cpt + 1, cb, msg.type->name, msg.payl_size);
403           if (!(*cb) (&ctx, msg.payl)) {
404             /* cb handled the message */
405             free(msg.payl);
406             ran_ok = 1;
407           }
408         }
409       }
410     }
411     CATCH(e) {
412       free(msg.payl);
413       if (msg.type->kind == e_gras_msg_kind_rpccall) {
414         char *old_file = e.file;
415         /* The callback raised an exception, propagate it on the network */
416         if (!e.remote) {
417           /* Make sure we reduce the file name to its basename to avoid issues in tests */
418           char *new_file = strrchr(e.file, '/');
419           if (new_file)
420             e.file = new_file;
421           /* the exception is born on this machine */
422           e.host = (char *) gras_os_myname();
423           xbt_ex_setup_backtrace(&e);
424         }
425         INFO5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
426               (e.remote ? "remote" : "local"),
427               e.msg,
428               msg.type->name,
429               gras_socket_peer_name(msg.expe),
430               gras_socket_peer_port(msg.expe));
431         if (XBT_LOG_ISENABLED(gras_msg, xbt_log_priority_verbose))
432           xbt_ex_display(&e);
433         gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
434                           msg.ID, msg.type, &e);
435         e.file = old_file;
436         xbt_ex_free(e);
437         ctx.answer_due = 0;
438         ran_ok = 1;
439       } else {
440         RETHROW4
441           ("Callback #%d (@%p) to message '%s' (payload size: %d) raised an exception: %s",
442            cpt + 1, cb, msg.type->name, msg.payl_size);
443       }
444     }
445
446     xbt_assert1(!ctx.answer_due,
447                 "Bug in user code: RPC callback to message '%s' didn't call gras_msg_rpcreturn",
448                 msg.type->name);
449     if (ctx.answer_due)
450       CRITICAL1
451         ("BUGS BOTH IN USER CODE (RPC callback to message '%s' didn't call gras_msg_rpcreturn) "
452          "AND IN SIMGRID (process wasn't killed by an assert)",
453          msg.type->name);
454     if (!ran_ok)
455       THROW1(mismatch_error, 0,
456              "Message '%s' refused by all registered callbacks (maybe your callback misses a 'return 0' at the end)",
457              msg.type->name);
458     /* FIXME: gras_datadesc_free not implemented => leaking the payload */
459     break;
460
461
462   case e_gras_msg_kind_rpcanswer:
463     INFO3("Unexpected RPC answer discarded (type: %s; from:%s:%d)",
464           msg.type->name, gras_socket_peer_name(msg.expe),
465           gras_socket_peer_port(msg.expe));
466     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
467     return;
468
469   case e_gras_msg_kind_rpcerror:
470     INFO3("Unexpected RPC error discarded (type: %s; from:%s:%d)",
471           msg.type->name, gras_socket_peer_name(msg.expe),
472           gras_socket_peer_port(msg.expe));
473     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
474     return;
475
476   default:
477     THROW1(unknown_error, 0,
478            "Cannot handle messages of kind %d yet", msg.type->kind);
479   }
480
481 }