Logo AND Algorithmique Numérique Distribuée

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