Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
79bd73cdfa59ff690bf3143da0f394c41b021620
[simgrid.git] / src / gras / Msg / gras_msg_exchange.c
1 /* $Id$ */
2
3 /* gras message exchanges                                                   */
4
5 /* Copyright (c) 2003-2009. The SimGrid Team. All rights reserved.          */
6
7 /* This program is free software; you can redistribute it and/or modify it
8  * under the terms of the license (GNU LGPL) which comes with this package. */
9
10 #include "xbt/ex.h"
11 #include "xbt/ex_interface.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                    gras_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_assert0(msg_got, "msg_got is an output parameter");
51
52   start = gras_os_time();
53   VERB2("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(gras_socket_peer_name(msg.expe),
59                                    gras_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       VERB0("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(gras_socket_peer_name(msg.expe),
72                                    gras_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       VERB0("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, sizeof(msg), 0);
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     DEBUG0("Got a message from the socket");
109
110     if ((!msgt_want || (msg.type->code == msgt_want->code))
111         && (!expe_want || (!strcmp(gras_socket_peer_name(msg.expe),
112                                    gras_socket_peer_name(expe_want))))
113         && (!filter || filter(&msg, filter_ctx))) {
114
115       memcpy(msg_got, &msg, sizeof(s_gras_msg_t));
116       DEBUG0("Message matches expectations. Use it.");
117       return;
118     }
119     DEBUG0("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       THROW1(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                gras_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_assert1(payload,
157                 "Message type '%s' convey a payload you must accept",
158                 msgt_want->name);
159   } else {
160     xbt_assert1(!payload,
161                 "No payload was declared for message type '%s'",
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     VERB1("Got matching message (type=%s)", msg->type->name);
180   else
181     VERB0("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, void *payload)
203 {
204   s_gras_msg_t msg;
205
206   VERB1("Wait %f seconds for several message types", timeout);
207   gras_msg_wait_ext_(timeout,
208                      NULL, NULL,
209                      &gras_msg_wait_or_filter, (void *) msgt_want, &msg);
210
211   if (msg.type->ctn_type) {
212     xbt_assert1(payload,
213                 "Message type '%s' convey a payload you must accept",
214                 msg.type->name);
215   }
216   /* don't check the other side since some of the types may have a payload */
217   if (payload && msg.type->ctn_type) {
218     memcpy(payload, msg.payl, msg.payl_size);
219     free(msg.payl);
220   }
221
222   if (ctx)
223     *ctx = gras_msg_cb_ctx_new(msg.expe, msg.type, msg.ID,
224                                (msg.kind == e_gras_msg_kind_rpccall), 60);
225
226   if (msgt_got)
227     *msgt_got = xbt_dynar_search(msgt_want, msg.type);
228 }
229
230
231 /** \brief Send the data pointed by \a payload as a message of type
232  * \a msgtype to the peer \a sock */
233 void gras_msg_send_(gras_socket_t sock, gras_msgtype_t msgtype, void *payload)
234 {
235
236   if (msgtype->ctn_type) {
237     xbt_assert1(payload,
238                 "Message type '%s' convey a payload you must provide",
239                 msgtype->name);
240   } else {
241     xbt_assert1(!payload,
242                 "No payload was declared for message type '%s'",
243                 msgtype->name);
244   }
245
246   DEBUG2("Send a oneway message of type '%s'. Payload=%p",
247          msgtype->name, payload);
248   gras_msg_send_ext(sock, e_gras_msg_kind_oneway, 0, msgtype, payload);
249   VERB2("Sent a oneway message of type '%s'. Payload=%p",
250         msgtype->name, payload);
251 }
252
253 /** @brief Handle all messages arriving within the given period
254  *
255  * @param period: How long to wait for incoming messages (in seconds)
256  *
257  * Messages are dealed with just like gras_msg_handle() would do. The
258  * difference is that gras_msg_handle() handles at most one message (or wait up
259  * to timeout second when no message arrives) while this function handles any
260  * amount of messages, and lasts the given period in any case.
261  */
262 void gras_msg_handleall(double period)
263 {
264   xbt_ex_t e;
265   double begin = gras_os_time();
266   double now;
267
268   do {
269     now = gras_os_time();
270     TRY {
271       if (period - now + begin > 0)
272         gras_msg_handle(period - now + begin);
273     }
274     CATCH(e) {
275       if (e.category != timeout_error)
276         RETHROW0("Error while waiting for messages: %s");
277       xbt_ex_free(e);
278     }
279     /* Epsilon to avoid numerical stability issues were the waited interval is so small that the global clock cannot notice the increment */
280   } while (period - now + begin > 0);
281 }
282
283 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
284  *
285  * @param timeOut: How long to wait for incoming messages (in seconds)
286  * @return the error code (or no_error).
287  *
288  * Any message arriving in the given interval is passed to the callbacks.
289  *
290  * @sa gras_msg_handleall().
291  */
292 void gras_msg_handle(double timeOut)
293 {
294
295   double untiltimer;
296
297   unsigned int cpt;
298   int volatile ran_ok;
299
300   s_gras_msg_t msg;
301
302   gras_msg_procdata_t pd =
303     (gras_msg_procdata_t) gras_libdata_by_id(gras_msg_libdata_id);
304   gras_cblist_t *list = NULL;
305   gras_msg_cb_t cb;
306   s_gras_msg_cb_ctx_t ctx;
307
308   int timerexpected, timeouted;
309   xbt_ex_t e;
310
311   VERB1("Handling message within the next %.2fs", timeOut);
312
313   untiltimer = gras_msg_timer_handle();
314   DEBUG1("Next timer in %f sec", untiltimer);
315   if (untiltimer == 0.0) {
316     /* A timer was already elapsed and handled */
317     return;
318   }
319   if (untiltimer != -1.0) {
320     timerexpected = 1;
321     timeOut = MIN(timeOut, untiltimer);
322   } else {
323     timerexpected = 0;
324   }
325
326   /* get a message (from the queue or from the net) */
327   timeouted = 0;
328   if (xbt_dynar_length(pd->msg_queue)) {
329     DEBUG0("Get a message from the queue");
330     xbt_dynar_shift(pd->msg_queue, &msg);
331   } else {
332     TRY {
333       xbt_queue_shift_timed(pd->msg_received, &msg, timeOut);
334       //      msg.expe = gras_trp_select(timeOut);
335     }
336     CATCH(e) {
337       if (e.category != timeout_error)
338         RETHROW;
339       DEBUG0("Damn. Timeout while getting a message from the queue");
340       xbt_ex_free(e);
341       timeouted = 1;
342     }
343   }
344
345   if (timeouted) {
346     if (timerexpected) {
347
348       /* A timer elapsed before the arrival of any message even if we select()ed a bit */
349       untiltimer = gras_msg_timer_handle();
350       if (untiltimer == 0.0) {
351         /* we served a timer, we're done */
352         return;
353       } else {
354         xbt_assert1(untiltimer > 0, "Negative timer (%f). I'm 'puzzeled'",
355                     untiltimer);
356         WARN1
357           ("No timer elapsed, in contrary to expectations (next in %f sec)",
358            untiltimer);
359         THROW1(timeout_error, 0,
360                "No timer elapsed, in contrary to expectations (next in %f sec)",
361                untiltimer);
362       }
363
364     } else {
365       /* select timeouted, and no timer elapsed. Nothing to do */
366       THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
367              timeOut);
368     }
369
370   }
371
372   /* A message was already there or arrived in the meanwhile. handle it */
373   xbt_dynar_foreach(pd->cbl_list, cpt, list) {
374     if (list->id == msg.type->code) {
375       break;
376     } else {
377       list = NULL;
378     }
379   }
380   if (!list) {
381     INFO4
382       ("No callback for message '%s' (type:%s) from %s:%d. Queue it for later gras_msg_wait() use.",
383        msg.type->name, e_gras_msg_kind_names[msg.kind],
384        gras_socket_peer_name(msg.expe), gras_socket_peer_port(msg.expe));
385     xbt_dynar_push(pd->msg_waitqueue, &msg);
386     return;                     /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
387   }
388
389   ctx.expeditor = msg.expe;
390   ctx.ID = msg.ID;
391   ctx.msgtype = msg.type;
392   ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
393
394   switch (msg.kind) {
395   case e_gras_msg_kind_oneway:
396   case e_gras_msg_kind_rpccall:
397     ran_ok = 0;
398     TRY {
399       xbt_dynar_foreach(list->cbs, cpt, cb) {
400         if (!ran_ok) {
401           DEBUG4
402             ("Use the callback #%d (@%p) for incomming msg '%s' (payload_size=%d)",
403              cpt + 1, cb, msg.type->name, msg.payl_size);
404           if (!(*cb) (&ctx, msg.payl)) {
405             /* cb handled the message */
406             free(msg.payl);
407             ran_ok = 1;
408           }
409         }
410       }
411     }
412     CATCH(e) {
413       free(msg.payl);
414       if (msg.type->kind == e_gras_msg_kind_rpccall) {
415         char *old_file = e.file;
416         /* The callback raised an exception, propagate it on the network */
417         if (!e.remote) {
418           /* Make sure we reduce the file name to its basename to avoid issues in tests */
419           char *new_file = strrchr(e.file, '/');
420           if (new_file)
421             e.file = new_file;
422           /* the exception is born on this machine */
423           e.host = (char *) gras_os_myname();
424           xbt_ex_setup_backtrace(&e);
425         }
426         INFO5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
427               (e.remote ? "remote" : "local"),
428               e.msg,
429               msg.type->name,
430               gras_socket_peer_name(msg.expe),
431               gras_socket_peer_port(msg.expe));
432         if (XBT_LOG_ISENABLED(gras_msg, xbt_log_priority_verbose))
433           xbt_ex_display(&e);
434         gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
435                           msg.ID, msg.type, &e);
436         e.file = old_file;
437         xbt_ex_free(e);
438         ctx.answer_due = 0;
439         ran_ok = 1;
440       } else {
441         RETHROW4
442           ("Callback #%d (@%p) to message '%s' (payload size: %d) raised an exception: %s",
443            cpt + 1, cb, msg.type->name, msg.payl_size);
444       }
445     }
446
447     xbt_assert1(!ctx.answer_due,
448                 "Bug in user code: RPC callback to message '%s' didn't call gras_msg_rpcreturn",
449                 msg.type->name);
450     if (ctx.answer_due)
451       CRITICAL1
452         ("BUGS BOTH IN USER CODE (RPC callback to message '%s' didn't call gras_msg_rpcreturn) "
453          "AND IN SIMGRID (process wasn't killed by an assert)",
454          msg.type->name);
455     if (!ran_ok)
456       THROW1(mismatch_error, 0,
457              "Message '%s' refused by all registered callbacks (maybe your callback misses a 'return 0' at the end)",
458              msg.type->name);
459     /* FIXME: gras_datadesc_free not implemented => leaking the payload */
460     break;
461
462
463   case e_gras_msg_kind_rpcanswer:
464     INFO3("Unexpected RPC answer discarded (type: %s; from:%s:%d)",
465           msg.type->name, gras_socket_peer_name(msg.expe),
466           gras_socket_peer_port(msg.expe));
467     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
468     return;
469
470   case e_gras_msg_kind_rpcerror:
471     INFO3("Unexpected RPC error discarded (type: %s; from:%s:%d)",
472           msg.type->name, gras_socket_peer_name(msg.expe),
473           gras_socket_peer_port(msg.expe));
474     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
475     return;
476
477   default:
478     THROW1(unknown_error, 0,
479            "Cannot handle messages of kind %d yet", msg.type->kind);
480   }
481
482 }