Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Be more verbose when propagating local exceptions
[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
39                 gras_msgtype_t   msgt_want,
40                 gras_socket_t    expe_want,
41                 gras_msg_filter_t filter,
42                 void             *filter_ctx,
43
44                 gras_msg_t       msg_got) {
45
46         s_gras_msg_t msg;
47         double start, now;
48         gras_msg_procdata_t pd=
49                 (gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
50         unsigned int cpt;
51
52         xbt_assert0(msg_got,"msg_got is an output parameter");
53
54         start = gras_os_time();
55         VERB2("Waiting for message '%s' for %fs",msgt_want?msgt_want->name:"(any)", timeout);
56
57         xbt_dynar_foreach(pd->msg_waitqueue,cpt,msg){
58                 if ( (   !msgt_want || (msg.type->code == msgt_want->code))
59                                 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
60                                                 gras_socket_peer_name(expe_want))))
61                                                 && (!filter || filter(&msg,filter_ctx))) {
62
63                         memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
64                         xbt_dynar_cursor_rm(pd->msg_waitqueue, &cpt);
65                         VERB0("The waited message was queued");
66                         return;
67                 }
68         }
69
70         xbt_dynar_foreach(pd->msg_queue,cpt,msg){
71                 if ( (   !msgt_want || (msg.type->code == msgt_want->code))
72                                 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
73                                                 gras_socket_peer_name(expe_want))))
74                                                 && (!filter || filter(&msg,filter_ctx))) {
75
76                         memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
77                         xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
78                         VERB0("The waited message was queued");
79                         return;
80                 }
81         }
82
83         while (1) {
84                 int need_restart;
85                 xbt_ex_t e;
86
87                 restart_receive: /* Goto here when the receive of a message failed */
88                 need_restart=0;
89                 now=gras_os_time();
90                 memset(&msg,sizeof(msg),0);
91
92                 TRY {
93                         xbt_queue_shift_timed(pd->msg_received,&msg,timeout ? timeout - now + start : 0);
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 /** \brief Waits for a message to come in over a given socket.
134  *
135  * @param timeout: How long should we wait for this message.
136  * @param msgt_want: type of awaited msg
137  * @param[out] expeditor: where to create a socket to answer the incomming message
138  * @param[out] payload: where to write the payload of the incomming message
139  * @return the error code (or no_error).
140  *
141  * Every message of another type received before the one waited will be queued
142  * and used by subsequent call to this function or gras_msg_handle().
143  */
144 void
145 gras_msg_wait_(double           timeout,
146                 gras_msgtype_t   msgt_want,
147                 gras_socket_t   *expeditor,
148                 void            *payload) {
149         s_gras_msg_t msg;
150
151         gras_msg_wait_ext_(timeout,
152                         msgt_want, NULL,      NULL, NULL,
153                         &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         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 /** \brief Waits for a message to come in over a given socket.
184  *
185  * @param timeout: How long should we wait for this message.
186  * @param msgt_want: a dynar containing all accepted message type
187  * @param[out] ctx: the context of received message (in case it's a RPC call we want to answer to)
188  * @param[out] msgt_got: indice in the dynar of the type of the received message
189  * @param[out] payload: where to write the payload of the incomming message
190  * @return the error code (or no_error).
191  *
192  * Every message of a type not in the accepted list received before the one
193  * waited will be queued and used by subsequent call to this function or
194  * gras_msg_handle().
195  *
196  * If you are interested in the context, pass the address of a s_gras_msg_cb_ctx_t variable.
197  */
198 void gras_msg_wait_or(double         timeout,
199                 xbt_dynar_t    msgt_want,
200                 gras_msg_cb_ctx_t *ctx,
201                 int           *msgt_got,
202                 void          *payload) {
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,
209                         &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         } /* don't check the other side since some of the types may have a payload */
216
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
234 gras_msg_send_(gras_socket_t   sock,
235                 gras_msgtype_t  msgtype,
236                 void           *payload) {
237
238         if (msgtype->ctn_type) {
239                 xbt_assert1(payload,
240                                 "Message type '%s' convey a payload you must provide",
241                                 msgtype->name);
242         } else {
243                 xbt_assert1(!payload,
244                                 "No payload was declared for message type '%s'",
245                                 msgtype->name);
246         }
247
248         DEBUG2("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         VERB2("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
265 gras_msg_handleall(double period) {
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                 } CATCH(e) {
276                         if (e.category != timeout_error)
277                                 RETHROW0("Error while waiting for messages: %s");
278                         xbt_ex_free(e);
279                 }
280                 /* Epsilon to avoid numerical stability issues were the waited interval is so small that the global clock cannot notice the increment */
281         } while (period - now + begin > 0);
282 }
283
284 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
285  *
286  * @param timeOut: How long to wait for incoming messages (in seconds)
287  * @return the error code (or no_error).
288  *
289  * Any message arriving in the given interval is passed to the callbacks.
290  *
291  * @sa gras_msg_handleall().
292  */
293 void
294 gras_msg_handle(double timeOut) {
295
296         double          untiltimer;
297
298         unsigned int cpt;
299         int volatile ran_ok;
300
301         s_gras_msg_t    msg;
302
303         gras_msg_procdata_t pd=(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                 } 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'", untiltimer);
354                                 WARN1("No timer elapsed, in contrary to expectations (next in %f sec)",
355                                                 untiltimer);
356                                 THROW1(timeout_error,0,
357                                                 "No timer elapsed, in contrary to expectations (next in %f sec)",
358                                                 untiltimer);
359                         }
360
361                 } else {
362                         /* select timeouted, and no timer elapsed. Nothing to do */
363                         THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
364                                         timeOut);
365                 }
366
367         }
368
369         /* A message was already there or arrived in the meanwhile. handle it */
370         xbt_dynar_foreach(pd->cbl_list,cpt,list) {
371                 if (list->id == msg.type->code) {
372                         break;
373                 } else {
374                         list=NULL;
375                 }
376         }
377         if (!list) {
378                 INFO3("No callback for message '%s' from %s:%d. Queue it for later gras_msg_wait() use.",
379                                 msg.type->name,
380                                 gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
381                 xbt_dynar_push(pd->msg_waitqueue,&msg);
382                 return; /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
383         }
384
385         ctx.expeditor = msg.expe;
386         ctx.ID = msg.ID;
387         ctx.msgtype = msg.type;
388         ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
389
390         switch (msg.kind) {
391         case e_gras_msg_kind_oneway:
392         case e_gras_msg_kind_rpccall:
393                 ran_ok=0;
394                 TRY {
395                         xbt_dynar_foreach(list->cbs,cpt,cb) {
396                                 if (!ran_ok) {
397                                         DEBUG4("Use the callback #%d (@%p) for incomming msg '%s' (payload_size=%d)",
398                                                         cpt+1,cb,msg.type->name,msg.payl_size);
399                                         if (!(*cb)(&ctx,msg.payl)) {
400                                                 /* cb handled the message */
401                                                 free(msg.payl);
402                                                 ran_ok = 1;
403                                         }
404                                 }
405                         }
406                 } CATCH(e) {
407                         free(msg.payl);
408                         if (msg.type->kind == e_gras_msg_kind_rpccall) {
409                                 char *old_file=e.file;
410                                 /* The callback raised an exception, propagate it on the network */
411                                 if (!e.remote) {
412                                         /* Make sure we reduce the file name to its basename to avoid issues in tests */
413                                         char *new_file=strrchr(e.file,'/');
414                                         if (new_file)
415                                                 e.file = new_file;
416                                         /* the exception is born on this machine */
417                                         e.host = (char*)gras_os_myname();
418                                         xbt_ex_setup_backtrace(&e);
419                                 }
420                                 INFO5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
421                                                 (e.remote ? "remote" : "local"),
422                                                 e.msg,
423                                                 msg.type->name,
424                                                 gras_socket_peer_name(msg.expe),
425                                                 gras_socket_peer_port(msg.expe));
426                                 if (XBT_LOG_ISENABLED(gras_msg,xbt_log_priority_verbose))
427                                         xbt_ex_display(&e);
428                                 gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
429                                                 msg.ID, msg.type, &e);
430                                 e.file=old_file;
431                                 xbt_ex_free(e);
432                                 ctx.answer_due = 0;
433                                 ran_ok=1;
434                         } else {
435                                 RETHROW4("Callback #%d (@%p) to message '%s' (payload size: %d) raised an exception: %s",
436                                                 cpt+1,cb,msg.type->name,msg.payl_size);
437                         }
438                 }
439
440                 xbt_assert1(! ctx.answer_due,
441                                 "Bug in user code: RPC callback to message '%s' didn't call gras_msg_rpcreturn",msg.type->name);
442                 if (ctx.answer_due)
443                         CRITICAL1("BUGS BOTH IN USER CODE (RPC callback to message '%s' didn't call gras_msg_rpcreturn) "
444                                         "AND IN SIMGRID (process wasn't killed by an assert)",msg.type->name);
445                 if (!ran_ok)
446                         THROW1(mismatch_error,0,
447                                         "Message '%s' refused by all registered callbacks (maybe your callback misses a 'return 0' at the end)", msg.type->name);
448                 /* FIXME: gras_datadesc_free not implemented => leaking the payload */
449                 break;
450
451
452         case e_gras_msg_kind_rpcanswer:
453                 INFO3("Unexpected RPC answer discarded (type: %s; from:%s:%d)", msg.type->name,
454                                 gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
455                 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
456                 return;
457
458         case e_gras_msg_kind_rpcerror:
459                 INFO3("Unexpected RPC error discarded (type: %s; from:%s:%d)", msg.type->name,
460                                 gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
461                 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
462                 return;
463
464         default:
465                 THROW1(unknown_error,0,
466                                 "Cannot handle messages of kind %d yet",msg.type->kind);
467         }
468
469 }
470