Logo AND Algorithmique Numérique Distribuée

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