Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Sanitize swag documentation: group definition in module-xbt; group structure in ...
[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
11 #include "gras/Msg/msg_private.h"
12 #include "gras/DataDesc/datadesc_interface.h"
13 #include "gras/Transport/transport_interface.h" /* gras_trp_chunk_send/recv */
14 #include "gras/Virtu/virtu_interface.h"
15
16 #define MIN(a,b) ((a) < (b) ? (a) : (b))
17
18 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_msg,gras,"High level messaging");
19
20 xbt_set_t _gras_msgtype_set = NULL;
21 static char GRAS_header[6];
22 static char *make_namev(const char *name, short int ver);
23
24 /*
25  * Creating procdata for this module
26  */
27 static void *gras_msg_procdata_new() {
28    gras_msg_procdata_t res = xbt_new(s_gras_msg_procdata_t,1);
29    
30    res->msg_queue = xbt_dynar_new(sizeof(s_gras_msg_t),   NULL);
31    res->cbl_list  = xbt_dynar_new(sizeof(gras_cblist_t *),gras_cbl_free);
32    res->timers    = xbt_dynar_new(sizeof(s_gras_timer_t), NULL);
33    
34    return (void*)res;
35 }
36
37 /*
38  * Freeing procdata for this module
39  */
40 static void gras_msg_procdata_free(void *data) {
41    gras_msg_procdata_t res = (gras_msg_procdata_t)data;
42    
43    xbt_dynar_free(&( res->msg_queue ));
44    xbt_dynar_free(&( res->cbl_list ));
45    xbt_dynar_free(&( res->timers ));
46 }
47
48 /*
49  * Module registration
50  */
51 void gras_msg_register() {
52    gras_procdata_add("gras_msg",gras_msg_procdata_new, gras_msg_procdata_free);
53 }
54
55 /*
56  * Initialize this submodule.
57  */
58 void gras_msg_init(void) {
59   /* only initialize once */
60   if (_gras_msgtype_set != NULL)
61     return;
62
63   VERB0("Initializing Msg");
64   
65   _gras_msgtype_set = xbt_set_new();
66
67   memcpy(GRAS_header,"GRAS", 4);
68   GRAS_header[4]=GRAS_PROTOCOL_VERSION;
69   GRAS_header[5]=(char)GRAS_THISARCH;
70 }
71
72 /*
73  * Finalize the msg module
74  */
75 void
76 gras_msg_exit(void) {
77   VERB0("Exiting Msg");
78   xbt_set_free(&_gras_msgtype_set);
79 }
80
81 /*
82  * Reclamed memory
83  */
84 void gras_msgtype_free(void *t) {
85   gras_msgtype_t msgtype=(gras_msgtype_t)t;
86   if (msgtype) {
87     free(msgtype->name);
88     free(msgtype);
89   }
90 }
91
92 /**
93  * make_namev:
94  *
95  * Returns the versionned name of the message. If the version is 0, that's 
96  * the name unchanged. Pay attention to this before free'ing the result.
97  */
98 static char *make_namev(const char *name, short int ver) {
99   char *namev;
100
101   if (!ver)
102     return (char *)name;
103
104   namev = (char*)xbt_malloc(strlen(name)+2+3+1);
105
106   if (namev)
107       sprintf(namev,"%s_v%d",name,ver);
108
109   return namev;
110 }
111
112 /** @brief declare a new message type of the given name. It only accepts the given datadesc as payload
113  *
114  * @param name: name as it should be used for logging messages (must be uniq)
115  * @param payload: datadescription of the payload
116  */
117 void gras_msgtype_declare(const char           *name,
118                           gras_datadesc_type_t  payload) {
119    gras_msgtype_declare_v(name, 0, payload);
120 }
121
122 /** @brief declare a new versionned message type of the given name and payload
123  *
124  * @param name: name as it should be used for logging messages (must be uniq)
125  * @param version: something like versionning symbol
126  * @param payload: datadescription of the payload
127  *
128  * Registers a message to the GRAS mechanism. Use this version instead of 
129  * gras_msgtype_declare when you change the semantic or syntax of a message and
130  * want your programs to be able to deal with both versions. Internally, each
131  * will be handled as an independent message type, so you can register 
132  * differents for each of them.
133  */
134 void
135 gras_msgtype_declare_v(const char           *name,
136                        short int             version,
137                        gras_datadesc_type_t  payload) {
138  
139   xbt_error_t   errcode;
140   gras_msgtype_t msgtype;
141   char *namev=make_namev(name,version);
142    
143   if (!payload) 
144      WARN1("Message %s has NULL payload",name);
145    
146   errcode = xbt_set_get_by_name(_gras_msgtype_set,
147                                  namev,(xbt_set_elm_t*)&msgtype);
148
149   if (errcode == no_error) {
150     VERB2("Re-register version %d of message '%s' (same payload, ignored).",
151           version, name);
152     xbt_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload),
153                  "Message %s re-registred with another payload (%s was %s)",
154                  namev,gras_datadesc_get_name(payload),
155                  gras_datadesc_get_name(msgtype->ctn_type));
156
157     return ; /* do really ignore it */
158
159   }
160   xbt_assert_error(mismatch_error); /* expect this error */
161   VERB3("Register version %d of message '%s' (payload: %s).", 
162         version, name, gras_datadesc_get_name(payload));    
163
164   msgtype = xbt_new(s_gras_msgtype_t,1);
165   msgtype->name = (namev == name ? strdup(name) : namev);
166   msgtype->name_len = strlen(namev);
167   msgtype->version = version;
168   msgtype->ctn_type = payload;
169
170   xbt_set_add(_gras_msgtype_set, (xbt_set_elm_t)msgtype,
171                &gras_msgtype_free);
172 }
173
174 /** @brief retrive an existing message type from its name. */
175 gras_msgtype_t gras_msgtype_by_name (const char *name) {
176   return gras_msgtype_by_namev(name,0);
177 }
178
179 /** @brief retrive an existing message type from its name and version. */
180 gras_msgtype_t gras_msgtype_by_namev(const char      *name,
181                                      short int        version) {
182   gras_msgtype_t res;
183
184   xbt_error_t errcode;
185   char *namev = make_namev(name,version); 
186
187   errcode = xbt_set_get_by_name(_gras_msgtype_set, namev,
188                                  (xbt_set_elm_t*)&res);
189   if (errcode != no_error)
190     res = NULL;
191   if (!res) 
192      WARN1("msgtype_by_name(%s) returns NULL",namev);
193   if (name != namev) 
194     free(namev);
195   
196   return res;
197 }
198
199 /** \brief Send the data pointed by \a payload as a message of type
200  * \a msgtype to the peer \a sock */
201 xbt_error_t
202 gras_msg_send(gras_socket_t   sock,
203               gras_msgtype_t  msgtype,
204               void           *payload) {
205
206   xbt_error_t errcode;
207   static gras_datadesc_type_t string_type=NULL;
208
209   if (!msgtype)
210     RAISE0(mismatch_error,
211            "Cannot send the NULL message (did msgtype_by_name fail?)");
212
213   if (!string_type) {
214     string_type = gras_datadesc_by_name("string");
215     xbt_assert(string_type);
216   }
217
218   DEBUG3("send '%s' to %s:%d", msgtype->name, 
219          gras_socket_peer_name(sock),gras_socket_peer_port(sock));
220   TRY(gras_trp_chunk_send(sock, GRAS_header, 6));
221
222   TRY(gras_datadesc_send(sock, string_type,   &msgtype->name));
223   TRY(gras_datadesc_send(sock, msgtype->ctn_type, payload));
224   TRY(gras_trp_flush(sock));
225
226   return no_error;
227 }
228 /*
229  * receive the next message on the given socket.  
230  */
231 xbt_error_t
232 gras_msg_recv(gras_socket_t    sock,
233               gras_msgtype_t  *msgtype,
234               void           **payload,
235               int             *payload_size) {
236
237   xbt_error_t errcode;
238   static gras_datadesc_type_t string_type=NULL;
239   char header[6];
240   int cpt;
241   int r_arch;
242   char *msg_name=NULL;
243
244   if (!string_type) {
245     string_type=gras_datadesc_by_name("string");
246     xbt_assert(string_type);
247   }
248   
249   TRY(gras_trp_chunk_recv(sock, header, 6));
250   for (cpt=0; cpt<4; cpt++)
251     if (header[cpt] != GRAS_header[cpt])
252       RAISE0(mismatch_error,"Incoming bytes do not look like a GRAS message");
253   if (header[4] != GRAS_header[4]) 
254     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
255            (int)header[4], (int)GRAS_header[4]);
256   r_arch = (int)header[5];
257   DEBUG2("Handle an incoming message using protocol %d (remote is %s)",
258          (int)header[4],gras_datadesc_arch_name(r_arch));
259
260   TRY(gras_datadesc_recv(sock, string_type, r_arch, &msg_name));
261   errcode = xbt_set_get_by_name(_gras_msgtype_set,
262                                  msg_name,(xbt_set_elm_t*)msgtype);
263   if (errcode != no_error)
264     RAISE2(errcode,
265            "Got error %s while retrieving the type associated to messages '%s'",
266            xbt_error_name(errcode),msg_name);
267   /* FIXME: Survive unknown messages */
268   free(msg_name);
269
270   *payload_size=gras_datadesc_size((*msgtype)->ctn_type);
271   xbt_assert2(*payload_size > 0,
272                "%s %s",
273                "Dynamic array as payload is forbided for now (FIXME?).",
274                "Reference to dynamic array is allowed.");
275   *payload = xbt_malloc(*payload_size);
276   TRY(gras_datadesc_recv(sock, (*msgtype)->ctn_type, r_arch, *payload));
277
278   return no_error;
279 }
280
281 /** \brief Waits for a message to come in over a given socket. 
282  *
283  * @param timeout: How long should we wait for this message.
284  * @param msgt_want: type of awaited msg
285  * @param[out] expeditor: where to create a socket to answer the incomming message
286  * @param[out] payload: where to write the payload of the incomming message
287  * @return the error code (or no_error).
288  *
289  * Every message of another type received before the one waited will be queued
290  * and used by subsequent call to this function or gras_msg_handle().
291  */
292 xbt_error_t
293 gras_msg_wait(double           timeout,    
294               gras_msgtype_t   msgt_want,
295               gras_socket_t   *expeditor,
296               void            *payload) {
297
298   gras_msgtype_t msgt_got;
299   void *payload_got;
300   int payload_size_got;
301   xbt_error_t errcode;
302   double start, now;
303   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
304   int cpt;
305   s_gras_msg_t msg;
306   
307   *expeditor = NULL;
308   payload_got = NULL;
309
310   if (!msgt_want)
311     RAISE0(mismatch_error,
312            "Cannot wait for the NULL message (did msgtype_by_name fail?)");
313
314   VERB1("Waiting for message %s",msgt_want->name);
315
316   start = now = gras_os_time();
317
318   xbt_dynar_foreach(pd->msg_queue,cpt,msg){
319     if (msg.type->code == msgt_want->code) {
320       *expeditor = msg.expeditor;
321       memcpy(payload, msg.payload, msg.payload_size);
322       free(msg.payload);
323       xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
324       VERB0("The waited message was queued");
325       return no_error;
326     }
327   }
328
329   while (1) {
330     TRY(gras_trp_select(timeout - now + start, expeditor));
331     TRY(gras_msg_recv(*expeditor, &msgt_got, &payload_got, &payload_size_got));
332     if (msgt_got->code == msgt_want->code) {
333       memcpy(payload, payload_got, payload_size_got);
334       free(payload_got);
335       VERB0("Got waited message");
336       return no_error;
337     }
338
339     /* not expected msg type. Queue it for later */
340     msg.expeditor = *expeditor;
341     msg.type      =  msgt_got;
342     msg.payload   =  payload;
343     msg.payload_size = payload_size_got;
344     xbt_dynar_push(pd->msg_queue,&msg);
345     
346     now=gras_os_time();
347     if (now - start + 0.001 < timeout) {
348       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
349     }
350   }
351
352   RAISE_IMPOSSIBLE;
353 }
354
355 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
356  *
357  * @param timeOut: How long to wait for incoming messages (in seconds)
358  * @return the error code (or no_error).
359  *
360  * Messages are passed to the callbacks.
361  */
362 xbt_error_t 
363 gras_msg_handle(double timeOut) {
364   
365   double          untiltimer;
366    
367   xbt_error_t    errcode;
368   int             cpt;
369
370   s_gras_msg_t    msg;
371   gras_socket_t   expeditor;
372   void           *payload=NULL;
373   int             payload_size;
374   gras_msgtype_t  msgtype;
375
376   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
377   gras_cblist_t  *list=NULL;
378   gras_msg_cb_t       cb;
379    
380   int timerexpected;
381
382   VERB1("Handling message within the next %.2fs",timeOut);
383   
384   untiltimer = gras_msg_timer_handle();
385   DEBUG2("[%.0f] Next timer in %f sec", gras_os_time(), untiltimer);
386   if (untiltimer == 0.0) {
387      /* A timer was already elapsed and handled */
388      return no_error;
389   }
390   if (untiltimer != -1.0) {
391      timerexpected = 1;
392      timeOut = MIN(timeOut, untiltimer);
393   } else {
394      timerexpected = 0;
395   }
396    
397   /* get a message (from the queue or from the net) */
398   if (xbt_dynar_length(pd->msg_queue)) {
399     DEBUG0("Get a message from the queue");
400     xbt_dynar_shift(pd->msg_queue,&msg);
401     expeditor = msg.expeditor;
402     msgtype   = msg.type;
403     payload   = msg.payload;
404     errcode   = no_error;
405   } else {
406     errcode = gras_trp_select(timeOut, &expeditor);
407     if (errcode != no_error && errcode != timeout_error)
408        return errcode;
409     if (errcode != timeout_error)
410        TRY(gras_msg_recv(expeditor, &msgtype, &payload, &payload_size));
411   }
412
413   if (errcode == timeout_error ) {
414      if (timerexpected) {
415           
416         /* A timer elapsed before the arrival of any message even if we select()ed a bit */
417         untiltimer = gras_msg_timer_handle();
418         if (untiltimer == 0.0) {
419            return no_error;
420         } else {
421            xbt_assert1(untiltimer>0, "Negative timer (%f). I'm puzzeled", untiltimer);
422            ERROR1("No timer elapsed, in contrary to expectations (next in %f sec)",
423                   untiltimer);
424            return timeout_error;
425         }
426         
427      } else {
428         /* select timeouted, and no timer elapsed. Nothing to do */
429         return timeout_error;
430      }
431      
432   }
433    
434   /* A message was already there or arrived in the meanwhile. handle it */
435   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
436     if (list->id == msgtype->code) {
437       break;
438     } else {
439       list=NULL;
440     }
441   }
442   if (!list) {
443     INFO1("No callback for the incomming '%s' message. Discarded.", 
444           msgtype->name);
445     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
446     return no_error;
447   }
448   
449   xbt_dynar_foreach(list->cbs,cpt,cb) { 
450     VERB3("Use the callback #%d (@%p) for incomming msg %s",
451           cpt+1,cb,msgtype->name);
452     if ((*cb)(expeditor,payload)) {
453       /* cb handled the message */
454       free(payload);
455       return no_error;
456     }
457   }
458
459   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
460   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
461   return mismatch_error;
462 }
463
464 void
465 gras_cbl_free(void *data){
466   gras_cblist_t *list=*(void**)data;
467   if (list) {
468     xbt_dynar_free(&( list->cbs ));
469     free(list);
470   }
471 }
472
473 /** \brief Bind the given callback to the given message type 
474  *
475  * Several callbacks can be attached to a given message type. The lastly added one will get the message first, and 
476  * if it returns false, the message will be passed to the second one. 
477  * And so on until one of the callbacks accepts the message.
478  */
479 void
480 gras_cb_register(gras_msgtype_t msgtype,
481                  gras_msg_cb_t cb) {
482   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
483   gras_cblist_t *list=NULL;
484   int cpt;
485
486   DEBUG2("Register %p as callback to %s",cb,msgtype->name);
487
488   /* search the list of cb for this message on this host (creating if NULL) */
489   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
490     if (list->id == msgtype->code) {
491       break;
492     } else {
493       list=NULL;
494     }
495   }
496   if (!list) {
497     /* First cb? Create room */
498     list = xbt_new(gras_cblist_t,1);
499     list->id = msgtype->code;
500     list->cbs = xbt_dynar_new(sizeof(gras_msg_cb_t), NULL);
501     xbt_dynar_push(pd->cbl_list,&list);
502   }
503
504   /* Insert the new one into the set */
505   xbt_dynar_insert_at(list->cbs,0,&cb);
506 }
507
508 /** \brief Unbind the given callback from the given message type */
509 void
510 gras_cb_unregister(gras_msgtype_t msgtype,
511                    gras_msg_cb_t cb) {
512
513   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
514   gras_cblist_t *list;
515   gras_msg_cb_t cb_cpt;
516   int cpt;
517   int found = 0;
518
519   /* search the list of cb for this message on this host */
520   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
521     if (list->id == msgtype->code) {
522       break;
523     } else {
524       list=NULL;
525     }
526   }
527
528   /* Remove it from the set */
529   if (list) {
530     xbt_dynar_foreach(list->cbs,cpt,cb_cpt) {
531       if (cb == cb_cpt) {
532         xbt_dynar_cursor_rm(list->cbs, &cpt);
533         found = 1;
534       }
535     }
536   }
537   if (!found)
538     VERB1("Ignoring removal of unexisting callback to msg id %d",
539           msgtype->code);
540 }