Logo AND Algorithmique Numérique Distribuée

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