Logo AND Algorithmique Numérique Distribuée

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