Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a directory for all builds
[simgrid.git] / src / gras / Msg / msg.c
1 /* $Id$ */
2
3 /* messaging - Function related to messaging (code shared between RL and SG)*/
4
5 /* Copyright (c) 2003, 2004 Martin Quinson. 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 #include "gras/DataDesc/datadesc_interface.h"
15 #include "gras/Transport/transport_interface.h" /* gras_select */
16 #include "portable.h" /* execinfo when available to propagate exceptions */
17
18 #ifndef MIN
19 #define MIN(a,b) ((a) < (b) ? (a) : (b))
20 #endif
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_msg,gras,"High level messaging");
23
24 xbt_set_t _gras_msgtype_set = NULL;
25 static char *make_namev(const char *name, short int ver);
26 char _GRAS_header[6];
27 const char *e_gras_msg_kind_names[e_gras_msg_kind_count]=
28   {"UNKNOWN","ONEWAY","RPC call","RPC answer","RPC error"};
29
30 /*
31  * Creating procdata for this module
32  */
33 static void *gras_msg_procdata_new() {
34    gras_msg_procdata_t res = xbt_new(s_gras_msg_procdata_t,1);
35    
36    res->name = xbt_strdup("gras_msg");
37    res->name_len = 0;
38    res->msg_queue     = xbt_dynar_new(sizeof(s_gras_msg_t),   NULL);
39    res->msg_waitqueue = xbt_dynar_new(sizeof(s_gras_msg_t),   NULL);
40    res->cbl_list      = xbt_dynar_new(sizeof(gras_cblist_t *),gras_cbl_free);
41    res->timers        = xbt_dynar_new(sizeof(s_gras_timer_t), NULL);
42    
43    return (void*)res;
44 }
45
46 /*
47  * Freeing procdata for this module
48  */
49 static void gras_msg_procdata_free(void *data) {
50    gras_msg_procdata_t res = (gras_msg_procdata_t)data;
51    
52    xbt_dynar_free(&( res->msg_queue ));
53    xbt_dynar_free(&( res->msg_waitqueue ));
54    xbt_dynar_free(&( res->cbl_list ));
55    xbt_dynar_free(&( res->timers ));
56
57    free(res->name);
58    free(res);
59 }
60
61 /*
62  * Module registration
63  */
64 int gras_msg_libdata_id;
65 void gras_msg_register() {
66    gras_msg_libdata_id = gras_procdata_add("gras_msg",gras_msg_procdata_new, gras_msg_procdata_free);
67 }
68
69 /*
70  * Initialize this submodule.
71  */
72 void gras_msg_init(void) {
73   /* only initialize once */
74   if (_gras_msgtype_set != NULL)
75     return;
76
77   VERB0("Initializing Msg");
78   
79   _gras_msgtype_set = xbt_set_new();
80
81   memcpy(_GRAS_header,"GRAS", 4);
82   _GRAS_header[4]=GRAS_PROTOCOL_VERSION;
83   _GRAS_header[5]=(char)GRAS_THISARCH;
84    
85   gras_msg_ctx_mallocator = 
86      xbt_mallocator_new(1000,
87                         gras_msg_ctx_mallocator_new_f,
88                         gras_msg_ctx_mallocator_free_f,
89                         gras_msg_ctx_mallocator_reset_f);
90 }
91
92 /*
93  * Finalize the msg module
94  */
95 void
96 gras_msg_exit(void) {
97   VERB0("Exiting Msg");
98   xbt_set_free(&_gras_msgtype_set);
99
100   xbt_mallocator_free(gras_msg_ctx_mallocator);
101 }
102
103 /*
104  * Reclamed memory
105  */
106 void gras_msgtype_free(void *t) {
107   gras_msgtype_t msgtype=(gras_msgtype_t)t;
108   if (msgtype) {
109     free(msgtype->name);
110     free(msgtype);
111   }
112 }
113 /**
114  * Dump all declared message types (debugging purpose)
115  */
116 void gras_msgtype_dumpall(void) {   
117   xbt_set_cursor_t cursor;
118   gras_msgtype_t msgtype=NULL;
119    
120   INFO0("Dump of all registered messages:");
121   xbt_set_foreach(_gras_msgtype_set, cursor, msgtype) {
122     INFO6("  Message name: %s (v%d) %s; %s%s%s", 
123           msgtype->name, msgtype->version, e_gras_msg_kind_names[msgtype->kind],
124           gras_datadesc_get_name(msgtype->ctn_type),
125           (msgtype->kind==e_gras_msg_kind_rpccall ? " -> ":""),
126           (msgtype->kind==e_gras_msg_kind_rpccall ? gras_datadesc_get_name(msgtype->answer_type) : ""));
127   }   
128 }
129
130
131 /**
132  * make_namev:
133  *
134  * Returns the versionned name of the message. If the version is 0, that's 
135  * the name unchanged. Pay attention to this before free'ing the result.
136  */
137 static char *make_namev(const char *name, short int ver) {
138   char *namev;
139
140   if (!ver)
141     return (char *)name;
142
143   namev = (char*)xbt_malloc(strlen(name)+2+3+1);
144
145   if (namev)
146       sprintf(namev,"%s_v%d",name,ver);
147
148   return namev;
149 }
150
151 /* Internal function doing the crude work of registering messages */
152 void 
153 gras_msgtype_declare_ext(const char           *name,
154                          short int             version,
155                          e_gras_msg_kind_t     kind, 
156                          gras_datadesc_type_t  payload_request,
157                          gras_datadesc_type_t  payload_answer) {
158
159   gras_msgtype_t msgtype=NULL;
160   char *namev=make_namev(name,version);
161   volatile int found = 0;
162   xbt_ex_t e;    
163   
164   TRY {
165     msgtype = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set,namev);
166     found = 1;
167   } CATCH(e) {
168     if (e.category != not_found_error)
169       RETHROW;
170     xbt_ex_free(e);
171   }
172
173   if (found) {
174     VERB2("Re-register version %d of message '%s' (same kind & payload, ignored).",
175           version, name);
176     xbt_assert3(msgtype->kind == kind,
177                 "Message %s re-registered as a %s (it was known as a %s)",
178                 namev,e_gras_msg_kind_names[kind],e_gras_msg_kind_names[msgtype->kind]);
179     xbt_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload_request),
180                  "Message %s re-registred with another payload (%s was %s)",
181                  namev,gras_datadesc_get_name(payload_request),
182                  gras_datadesc_get_name(msgtype->ctn_type));
183
184     xbt_assert3(!gras_datadesc_type_cmp(msgtype->answer_type, payload_answer),
185              "Message %s re-registred with another answer payload (%s was %s)",
186                  namev,gras_datadesc_get_name(payload_answer),
187                  gras_datadesc_get_name(msgtype->answer_type));
188
189     return ; /* do really ignore it */
190
191   }
192
193   VERB4("Register version %d of message '%s' "
194         "(payload: %s; answer payload: %s).", 
195         version, name, gras_datadesc_get_name(payload_request),
196         gras_datadesc_get_name(payload_answer));    
197
198   msgtype = xbt_new(s_gras_msgtype_t,1);
199   msgtype->name = (namev == name ? strdup(name) : namev);
200   msgtype->name_len = strlen(namev);
201   msgtype->version = version;
202   msgtype->kind = kind;
203   msgtype->ctn_type = payload_request;
204   msgtype->answer_type = payload_answer;
205
206   xbt_set_add(_gras_msgtype_set, (xbt_set_elm_t)msgtype,
207                &gras_msgtype_free);
208 }
209
210
211 /** @brief declare a new message type of the given name. It only accepts the given datadesc as payload
212  *
213  * @param name: name as it should be used for logging messages (must be uniq)
214  * @param payload: datadescription of the payload
215  */
216 void gras_msgtype_declare(const char           *name,
217                           gras_datadesc_type_t  payload) {
218    gras_msgtype_declare_ext(name, 0, e_gras_msg_kind_oneway, payload, NULL);
219 }
220
221
222
223 /** @brief declare a new versionned message type of the given name and payload
224  *
225  * @param name: name as it should be used for logging messages (must be uniq)
226  * @param version: something like versionning symbol
227  * @param payload: datadescription of the payload
228  *
229  * Registers a message to the GRAS mechanism. Use this version instead of 
230  * gras_msgtype_declare when you change the semantic or syntax of a message and
231  * want your programs to be able to deal with both versions. Internally, each
232  * will be handled as an independent message type, so you can register 
233  * differents for each of them.
234  */
235 void
236 gras_msgtype_declare_v(const char           *name,
237                        short int             version,
238                        gras_datadesc_type_t  payload) {
239  
240    gras_msgtype_declare_ext(name, version, 
241                             e_gras_msg_kind_oneway, payload, NULL);
242 }
243
244 /** @brief retrieve an existing message type from its name (raises an exception if it does not exist). */
245 gras_msgtype_t gras_msgtype_by_name (const char *name) {
246   return gras_msgtype_by_namev(name,0);
247 }
248 /** @brief retrieve an existing message type from its name (or NULL if it does not exist). */
249 gras_msgtype_t gras_msgtype_by_name_or_null (const char *name) {
250   xbt_ex_t e;
251   gras_msgtype_t res = NULL;
252    
253   TRY {
254      res = gras_msgtype_by_namev(name,0);
255   } CATCH(e) {
256      res = NULL;
257      xbt_ex_free(e);
258   }
259   return res;
260 }
261
262 /** @brief retrieve an existing message type from its name and version. */
263 gras_msgtype_t gras_msgtype_by_namev(const char      *name,
264                                      short int        version) {
265   gras_msgtype_t res = NULL;
266   char *namev = make_namev(name,version);
267   volatile int found=0;
268   xbt_ex_t e;
269
270   TRY {
271     res = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set, namev);
272     found=1;
273   } CATCH(e) {
274     xbt_ex_free(e);
275   }
276   if (!found)
277     THROW1(not_found_error,0,"No registred message of that name: %s",name);
278
279   if (name != namev) 
280     free(namev);
281   
282   return res;
283 }
284 /** @brief retrieve an existing message type from its name and version. */
285 gras_msgtype_t gras_msgtype_by_id(int id) {
286   return (gras_msgtype_t)xbt_set_get_by_id(_gras_msgtype_set, id);
287 }
288
289 /** \brief Waits for a message to come in over a given socket. 
290  *
291  * @param timeout: How long should we wait for this message.
292  * @param msgt_want: type of awaited msg (or NULL if I'm enclined to accept any message)
293  * @param expe_want: awaited expeditot (match on hostname, not port; NULL if not relevant)
294  * @param filter: function returning true or false when passed a payload. Messages for which it returns false are not selected. (NULL if not relevant)
295  * @param filter_ctx: context passed as second argument of the filter (a pattern to match?)
296  * @param[out] msg_got: where to write the message we got
297  *
298  * Every message of another type received before the one waited will be queued
299  * and used by subsequent call to this function or gras_msg_handle().
300  */
301
302 void
303 gras_msg_wait_ext(double           timeout,    
304
305                   gras_msgtype_t   msgt_want,
306                   gras_socket_t    expe_want,
307                   gras_msg_filter_t filter,
308                   void             *filter_ctx, 
309
310                   gras_msg_t       msg_got) {
311
312   s_gras_msg_t msg;
313   double start, now;
314   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
315   int cpt;
316
317   xbt_assert0(msg_got,"msg_got is an output parameter");
318
319   start = gras_os_time();
320   VERB1("Waiting for message '%s'",msgt_want?msgt_want->name:"(any)");
321
322   xbt_dynar_foreach(pd->msg_waitqueue,cpt,msg){
323     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
324          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
325                                      gras_socket_peer_name(expe_want))))
326          && (!filter || filter(&msg,filter_ctx))) {
327
328       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
329       xbt_dynar_cursor_rm(pd->msg_waitqueue, &cpt);
330       VERB0("The waited message was queued");
331       return;
332     }
333   }
334
335   xbt_dynar_foreach(pd->msg_queue,cpt,msg){
336     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
337          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
338                                      gras_socket_peer_name(expe_want))))
339          && (!filter || filter(&msg,filter_ctx))) {
340
341       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
342       xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
343       VERB0("The waited message was queued");
344       return;
345     }
346   }
347
348   while (1) {
349     int need_restart;
350     xbt_ex_t e;
351
352   restart_receive: /* Goto here when the receive of a message failed */
353     need_restart=0;
354     now=gras_os_time();
355     memset(&msg,sizeof(msg),0);
356
357     TRY {
358       msg.expe = gras_trp_select(timeout ? timeout - now + start : 0);
359       gras_msg_recv(msg.expe, &msg);
360     } CATCH(e) {
361       if (e.category == system_error &&
362           !strncmp("Socket closed by remote side",e.msg,
363                   strlen("Socket closed by remote side"))) {
364         xbt_ex_free(e);
365         need_restart=1;
366       } else {
367         RETHROW;
368       }
369     }
370     if (need_restart)
371       goto restart_receive;
372
373     DEBUG0("Got a message from the socket");
374
375     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
376          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
377                                      gras_socket_peer_name(expe_want))))
378          && (!filter || filter(&msg,filter_ctx))) {
379
380       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
381       DEBUG0("Message matches expectations. Use it.");
382       return;
383     }
384     DEBUG0("Message does not match expectations. Queue it.");
385
386     /* not expected msg type. Queue it for later */
387     xbt_dynar_push(pd->msg_queue,&msg);
388     
389     now=gras_os_time();
390     if (now - start + 0.001 > timeout) {
391       THROW1(timeout_error,  now-start+0.001-timeout,
392              "Timeout while waiting for msg '%s'",
393              msgt_want?msgt_want->name:"(any)");
394     }
395   }
396
397   THROW_IMPOSSIBLE;
398 }
399 /** \brief Waits for a message to come in over a given socket. 
400  *
401  * @param timeout: How long should we wait for this message.
402  * @param msgt_want: type of awaited msg
403  * @param[out] expeditor: where to create a socket to answer the incomming message
404  * @param[out] payload: where to write the payload of the incomming message
405  * @return the error code (or no_error).
406  *
407  * Every message of another type received before the one waited will be queued
408  * and used by subsequent call to this function or gras_msg_handle().
409  */
410 void
411 gras_msg_wait(double           timeout,    
412               gras_msgtype_t   msgt_want,
413               gras_socket_t   *expeditor,
414               void            *payload) {
415   s_gras_msg_t msg;
416
417   gras_msg_wait_ext(timeout,
418                     msgt_want, NULL,      NULL, NULL,
419                     &msg);
420
421   if (msgt_want->ctn_type) {
422     xbt_assert1(payload,
423                 "Message type '%s' convey a payload you must accept",
424                 msgt_want->name);
425   } else {
426     xbt_assert1(!payload,
427                 "No payload was declared for message type '%s'",
428                 msgt_want->name);
429   }
430
431   if (payload) {
432     memcpy(payload,msg.payl,msg.payl_size);
433     free(msg.payl);
434   }
435
436   if (expeditor)
437     *expeditor = msg.expe;
438 }
439
440 static int gras_msg_wait_or_filter(gras_msg_t msg, void *ctx) {
441   xbt_dynar_t dyn=(xbt_dynar_t)ctx;
442   int res =  xbt_dynar_member(dyn,msg->type);
443   if (res)
444     VERB1("Got matching message (type=%s)",msg->type->name);
445   else
446     VERB0("Got message not matching our expectations");
447   return res;
448 }
449 /** \brief Waits for a message to come in over a given socket. 
450  *
451  * @param timeout: How long should we wait for this message.
452  * @param msgt_want: a dynar containing all accepted message type
453  * @param[out] ctx: the context of received message (in case it's a RPC call we want to answer to)
454  * @param[out] msgt_got: indice in the dynar of the type of the received message 
455  * @param[out] payload: where to write the payload of the incomming message
456  * @return the error code (or no_error).
457  *
458  * Every message of a type not in the accepted list received before the one
459  * waited will be queued and used by subsequent call to this function or
460  * gras_msg_handle().
461  *
462  * If you are interested in the context, pass the address of a s_gras_msg_cb_ctx_t variable.
463  */
464 void gras_msg_wait_or(double         timeout,
465                       xbt_dynar_t    msgt_want,
466                       gras_msg_cb_ctx_t *ctx,
467                       int           *msgt_got,
468                       void          *payload) {
469   s_gras_msg_t msg;
470
471   VERB1("Wait %f seconds for several message types",timeout);
472   gras_msg_wait_ext(timeout,
473                     NULL, NULL,      
474                     &gras_msg_wait_or_filter, (void*)msgt_want,
475                     &msg);
476
477   if (msg.type->ctn_type) {
478     xbt_assert1(payload,
479                 "Message type '%s' convey a payload you must accept",
480                 msg.type->name);
481   } /* don't check the other side since some of the types may have a payload */
482
483   if (payload && msg.type->ctn_type) {
484     memcpy(payload,msg.payl,msg.payl_size);
485     free(msg.payl);
486   }
487
488   if (ctx) 
489     *ctx=gras_msg_cb_ctx_new(msg.expe, msg.type, msg.ID,
490                              (msg.kind == e_gras_msg_kind_rpccall), 60);
491
492   if (msgt_got)
493     *msgt_got = xbt_dynar_search(msgt_want,msg.type);
494 }
495
496
497 /** \brief Send the data pointed by \a payload as a message of type
498  * \a msgtype to the peer \a sock */
499 void
500 gras_msg_send(gras_socket_t   sock,
501               gras_msgtype_t  msgtype,
502               void           *payload) {
503
504   if (msgtype->ctn_type) {
505     xbt_assert1(payload,
506                 "Message type '%s' convey a payload you must provide",
507                 msgtype->name);
508   } else {
509     xbt_assert1(!payload,
510                 "No payload was declared for message type '%s'",
511                 msgtype->name);
512   }
513
514   DEBUG2("Send a oneway message of type '%s'. Payload=%p",
515          msgtype->name,payload);
516   gras_msg_send_ext(sock, e_gras_msg_kind_oneway,0, msgtype, payload);
517   VERB2("Sent a oneway message of type '%s'. Payload=%p",
518         msgtype->name,payload);
519 }
520
521 /** @brief Handle all messages arriving within the given period
522  *
523  * @param period: How long to wait for incoming messages (in seconds)
524  *
525  * Messages are dealed with just like gras_msg_handle() would do. The
526  * difference is that gras_msg_handle() handles at most one message (or wait up
527  * to timeout second when no message arrives) while this function handles any
528  * amount of messages, and lasts the given period in any case.
529  */
530 void 
531 gras_msg_handleall(double period) {
532   xbt_ex_t e;
533   double begin=gras_os_time();
534   double now;
535
536   do {
537     now=gras_os_time();
538     TRY{
539       if (period - now + begin > 0)
540         gras_msg_handle(period - now + begin);
541     } CATCH(e) {
542       if (e.category != timeout_error) 
543         RETHROW0("Error while waiting for messages: %s");
544       xbt_ex_free(e);
545     }
546   } while (now - begin < period);
547 }
548
549 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
550  *
551  * @param timeOut: How long to wait for incoming messages (in seconds)
552  * @return the error code (or no_error).
553  *
554  * Messages are passed to the callbacks. See also gras_msg_handleall().
555  */
556 void
557 gras_msg_handle(double timeOut) {
558   
559   double          untiltimer;
560    
561   int             cpt;
562   int volatile ran_ok;
563
564   s_gras_msg_t    msg;
565
566   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
567   gras_cblist_t  *list=NULL;
568   gras_msg_cb_t       cb;
569   s_gras_msg_cb_ctx_t ctx;
570    
571   int timerexpected, timeouted;
572   xbt_ex_t e;
573
574   VERB1("Handling message within the next %.2fs",timeOut);
575   
576   untiltimer = gras_msg_timer_handle();
577   DEBUG1("Next timer in %f sec", untiltimer);
578   if (untiltimer == 0.0) {
579      /* A timer was already elapsed and handled */
580      return;
581   }
582   if (untiltimer != -1.0) {
583      timerexpected = 1;
584      timeOut = MIN(timeOut, untiltimer);
585   } else {
586      timerexpected = 0;
587   }
588    
589   /* get a message (from the queue or from the net) */
590   timeouted = 0;
591   if (xbt_dynar_length(pd->msg_queue)) {
592     DEBUG0("Get a message from the queue");
593     xbt_dynar_shift(pd->msg_queue,&msg);
594   } else {
595     TRY {
596       msg.expe = gras_trp_select(timeOut);
597     } CATCH(e) {
598       if (e.category != timeout_error)
599         RETHROW;
600       xbt_ex_free(e);
601       timeouted = 1;
602     }
603
604     if (!timeouted) {
605       TRY {
606         /* FIXME: if not the right kind, queue it and recall ourself or goto >:-) */
607         gras_msg_recv(msg.expe, &msg);
608         DEBUG1("Received a msg from the socket kind:%s",
609                e_gras_msg_kind_names[msg.kind]);
610     
611       } CATCH(e) {
612         RETHROW4("Error while receiving a message on select()ed socket %p to [%s]%s:%d: %s",
613                  msg.expe,
614                  gras_socket_peer_proc(msg.expe),gras_socket_peer_name(msg.expe),
615                  gras_socket_peer_port(msg.expe));
616       }
617     }
618   }
619
620   if (timeouted) {
621      if (timerexpected) {
622           
623         /* A timer elapsed before the arrival of any message even if we select()ed a bit */
624         untiltimer = gras_msg_timer_handle();
625         if (untiltimer == 0.0) {
626           /* we served a timer, we're done */
627           return;
628         } else {
629            xbt_assert1(untiltimer>0, "Negative timer (%f). I'm 'puzzeled'", untiltimer);
630            WARN1("No timer elapsed, in contrary to expectations (next in %f sec)",
631                   untiltimer);
632            THROW1(timeout_error,0,
633                   "No timer elapsed, in contrary to expectations (next in %f sec)",
634                   untiltimer);
635         }
636         
637      } else {
638         /* select timeouted, and no timer elapsed. Nothing to do */
639        THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
640               timeOut);
641      }
642      
643   }
644    
645   /* A message was already there or arrived in the meanwhile. handle it */
646   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
647     if (list->id == msg.type->code) {
648       break;
649     } else {
650       list=NULL;
651     }
652   }
653   if (!list) {
654     INFO3("No callback for message '%s' from %s:%d. Queue it for later gras_msg_wait() use.",
655           msg.type->name,
656           gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
657     xbt_dynar_push(pd->msg_waitqueue,&msg);
658     return; /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
659   }
660   
661   ctx.expeditor = msg.expe;
662   ctx.ID = msg.ID;
663   ctx.msgtype = msg.type;
664   ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
665
666   switch (msg.kind) {
667   case e_gras_msg_kind_oneway:
668   case e_gras_msg_kind_rpccall:
669     ran_ok=0;
670     TRY {
671       xbt_dynar_foreach(list->cbs,cpt,cb) { 
672         if (!ran_ok) {
673           DEBUG4("Use the callback #%d (@%p) for incomming msg %s (payload_size=%d)",
674                 cpt+1,cb,msg.type->name,msg.payl_size);
675           if ((*cb)(&ctx,msg.payl)) {
676             /* cb handled the message */
677             free(msg.payl);
678             ran_ok = 1;
679           }
680         }
681       }
682     } CATCH(e) {
683       free(msg.payl);
684       if (msg.type->kind == e_gras_msg_kind_rpccall) {
685         /* The callback raised an exception, propagate it on the network */
686         if (!e.remote) { /* the exception is born on this machine */
687           e.host = (char*)gras_os_myname();
688           xbt_ex_setup_backtrace(&e);
689         } 
690         VERB5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
691               (e.remote ? "remote" : "local"),
692               e.msg,
693               msg.type->name,
694               gras_socket_peer_name(msg.expe),
695               gras_socket_peer_port(msg.expe));
696         gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
697                           msg.ID, msg.type, &e);
698         xbt_ex_free(e);
699         ctx.answer_due = 0;
700         ran_ok=1;
701       } else {
702         RETHROW0("Callback raised an exception: %s");
703       }
704     }
705     xbt_assert0(!(ctx.answer_due),
706                 "RPC callback didn't call gras_msg_rpcreturn");
707
708     if (!ran_ok)
709       THROW1(mismatch_error,0,
710              "Message '%s' refused by all registered callbacks", msg.type->name);
711     /* FIXME: gras_datadesc_free not implemented => leaking the payload */
712     break;
713
714
715   case e_gras_msg_kind_rpcanswer:
716     INFO1("Unexpected RPC answer discarded (type: %s)", msg.type->name);
717     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
718     return;
719
720   case e_gras_msg_kind_rpcerror:
721     INFO1("Unexpected RPC error discarded (type: %s)", msg.type->name);
722     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
723     return;
724
725   default:
726     THROW1(unknown_error,0,
727            "Cannot handle messages of kind %d yet",msg.type->kind);
728   }
729
730 }
731
732 void
733 gras_cbl_free(void *data){
734   gras_cblist_t *list=*(void**)data;
735   if (list) {
736     xbt_dynar_free(&( list->cbs ));
737     free(list);
738   }
739 }
740
741 /** \brief Bind the given callback to the given message type 
742  *
743  * Several callbacks can be attached to a given message type. The lastly added one will get the message first, and 
744  * if it returns false, the message will be passed to the second one. 
745  * And so on until one of the callbacks accepts the message.
746  */
747 void
748 gras_cb_register(gras_msgtype_t msgtype,
749                  gras_msg_cb_t cb) {
750   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
751   gras_cblist_t *list=NULL;
752   int cpt;
753
754   DEBUG2("Register %p as callback to '%s'",cb,msgtype->name);
755
756   /* search the list of cb for this message on this host (creating if NULL) */
757   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
758     if (list->id == msgtype->code) {
759       break;
760     } else {
761       list=NULL;
762     }
763   }
764   if (!list) {
765     /* First cb? Create room */
766     list = xbt_new(gras_cblist_t,1);
767     list->id = msgtype->code;
768     list->cbs = xbt_dynar_new(sizeof(gras_msg_cb_t), NULL);
769     xbt_dynar_push(pd->cbl_list,&list);
770   }
771
772   /* Insert the new one into the set */
773   xbt_dynar_insert_at(list->cbs,0,&cb);
774 }
775
776 /** \brief Unbind the given callback from the given message type */
777 void
778 gras_cb_unregister(gras_msgtype_t msgtype,
779                    gras_msg_cb_t cb) {
780
781   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
782   gras_cblist_t *list;
783   gras_msg_cb_t cb_cpt;
784   int cpt;
785   int found = 0;
786
787   /* search the list of cb for this message on this host */
788   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
789     if (list->id == msgtype->code) {
790       break;
791     } else {
792       list=NULL;
793     }
794   }
795
796   /* Remove it from the set */
797   if (list) {
798     xbt_dynar_foreach(list->cbs,cpt,cb_cpt) {
799       if (cb == cb_cpt) {
800         xbt_dynar_cursor_rm(list->cbs, &cpt);
801         found = 1;
802       }
803     }
804   }
805   if (!found)
806     VERB1("Ignoring removal of unexisting callback to msg id %d",
807           msgtype->code);
808 }
809
810 /** \brief Retrieve the expeditor of the message */
811 gras_socket_t gras_msg_cb_ctx_from(gras_msg_cb_ctx_t ctx) {
812   return ctx->expeditor;
813 }
814 /* \brief Creates a new message exchange context (user should never have to) */
815 gras_msg_cb_ctx_t gras_msg_cb_ctx_new(gras_socket_t expe, 
816                                       gras_msgtype_t msgtype,
817                                       unsigned long int ID,
818                                       int answer_due,
819                                       double timeout) {
820   gras_msg_cb_ctx_t res=xbt_new(s_gras_msg_cb_ctx_t,1);
821   res->expeditor = expe;
822   res->msgtype = msgtype;
823   res->ID = ID;
824   res->timeout = timeout;
825   res->answer_due = answer_due;
826
827   return res;
828 }
829 /* \brief Frees a message exchange context 
830  *
831  * This function is mainly useful with \ref gras_msg_wait_or, ie seldom.
832  */
833 void gras_msg_cb_ctx_free(gras_msg_cb_ctx_t ctx) {
834   free(ctx);
835 }