Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
dc579391ca4f004d0234f8f7758146b69768a097
[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   errcode = xbt_set_get_by_name(_gras_msgtype_set,
144                                  namev,(xbt_set_elm_t*)&msgtype);
145
146   if (errcode == no_error) {
147     VERB2("Re-register version %d of message '%s' (same payload, ignored).",
148           version, name);
149     xbt_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload),
150                  "Message %s re-registred with another payload (%s was %s)",
151                  namev,gras_datadesc_get_name(payload),
152                  gras_datadesc_get_name(msgtype->ctn_type));
153
154     return ; /* do really ignore it */
155
156   }
157   xbt_assert_error(mismatch_error); /* expect this error */
158   VERB3("Register version %d of message '%s' (payload: %s).", 
159         version, name, gras_datadesc_get_name(payload));    
160
161   msgtype = xbt_new(s_gras_msgtype_t,1);
162   msgtype->name = (namev == name ? strdup(name) : namev);
163   msgtype->name_len = strlen(namev);
164   msgtype->version = version;
165   msgtype->ctn_type = payload;
166
167   xbt_set_add(_gras_msgtype_set, (xbt_set_elm_t)msgtype,
168                &gras_msgtype_free);
169 }
170
171 /** @brief retrive an existing message type from its name. */
172 gras_msgtype_t gras_msgtype_by_name (const char *name) {
173   return gras_msgtype_by_namev(name,0);
174 }
175
176 /** @brief retrive an existing message type from its name and version. */
177 gras_msgtype_t gras_msgtype_by_namev(const char      *name,
178                                      short int        version) {
179   gras_msgtype_t res;
180
181   xbt_error_t errcode;
182   char *namev = make_namev(name,version); 
183
184   errcode = xbt_set_get_by_name(_gras_msgtype_set, namev,
185                                  (xbt_set_elm_t*)&res);
186   if (errcode != no_error)
187     res = NULL;
188   if (!res) 
189      WARN1("msgtype_by_name(%s) returns NULL",namev);
190   if (name != namev) 
191     free(namev);
192   
193   return res;
194 }
195
196 /** \brief Send the data pointed by \a payload as a message of type
197  * \a msgtype to the peer \a sock */
198 xbt_error_t
199 gras_msg_send(gras_socket_t   sock,
200               gras_msgtype_t  msgtype,
201               void           *payload) {
202
203   xbt_error_t errcode;
204   static gras_datadesc_type_t string_type=NULL;
205
206   if (!msgtype)
207     RAISE0(mismatch_error,
208            "Cannot send the NULL message (did msgtype_by_name fail?)");
209
210   if (!string_type) {
211     string_type = gras_datadesc_by_name("string");
212     xbt_assert(string_type);
213   }
214
215   DEBUG3("send '%s' to %s:%d", msgtype->name, 
216          gras_socket_peer_name(sock),gras_socket_peer_port(sock));
217   TRY(gras_trp_chunk_send(sock, GRAS_header, 6));
218
219   TRY(gras_datadesc_send(sock, string_type,   &msgtype->name));
220   TRY(gras_datadesc_send(sock, msgtype->ctn_type, payload));
221   TRY(gras_trp_flush(sock));
222
223   return no_error;
224 }
225 /*
226  * receive the next message on the given socket.  
227  */
228 xbt_error_t
229 gras_msg_recv(gras_socket_t    sock,
230               gras_msgtype_t  *msgtype,
231               void           **payload,
232               int             *payload_size) {
233
234   xbt_error_t errcode;
235   static gras_datadesc_type_t string_type=NULL;
236   char header[6];
237   int cpt;
238   int r_arch;
239   char *msg_name=NULL;
240
241   if (!string_type) {
242     string_type=gras_datadesc_by_name("string");
243     xbt_assert(string_type);
244   }
245   
246   TRY(gras_trp_chunk_recv(sock, header, 6));
247   for (cpt=0; cpt<4; cpt++)
248     if (header[cpt] != GRAS_header[cpt])
249       RAISE2(mismatch_error,"Incoming bytes do not look like a GRAS message (header='%.4s' not '%.4s')",header,GRAS_header);
250   if (header[4] != GRAS_header[4]) 
251     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
252            (int)header[4], (int)GRAS_header[4]);
253   r_arch = (int)header[5];
254   DEBUG2("Handle an incoming message using protocol %d (remote is %s)",
255          (int)header[4],gras_datadesc_arch_name(r_arch));
256
257   TRY(gras_datadesc_recv(sock, string_type, r_arch, &msg_name));
258   errcode = xbt_set_get_by_name(_gras_msgtype_set,
259                                  msg_name,(xbt_set_elm_t*)msgtype);
260   if (errcode != no_error)
261     RAISE2(errcode,
262            "Got error %s while retrieving the type associated to messages '%s'",
263            xbt_error_name(errcode),msg_name);
264   /* FIXME: Survive unknown messages */
265   free(msg_name);
266
267   *payload_size=gras_datadesc_size((*msgtype)->ctn_type);
268   xbt_assert2(*payload_size > 0,
269                "%s %s",
270                "Dynamic array as payload is forbided for now (FIXME?).",
271                "Reference to dynamic array is allowed.");
272   *payload = xbt_malloc(*payload_size);
273   TRY(gras_datadesc_recv(sock, (*msgtype)->ctn_type, r_arch, *payload));
274
275   return no_error;
276 }
277
278 /** \brief Waits for a message to come in over a given socket. 
279  *
280  * @param timeout: How long should we wait for this message.
281  * @param msgt_want: type of awaited msg
282  * @param[out] expeditor: where to create a socket to answer the incomming message
283  * @param[out] payload: where to write the payload of the incomming message
284  * @return the error code (or no_error).
285  *
286  * Every message of another type received before the one waited will be queued
287  * and used by subsequent call to this function or gras_msg_handle().
288  */
289 xbt_error_t
290 gras_msg_wait(double           timeout,    
291               gras_msgtype_t   msgt_want,
292               gras_socket_t   *expeditor,
293               void            *payload) {
294
295   gras_msgtype_t msgt_got;
296   void *payload_got;
297   int payload_size_got;
298   xbt_error_t errcode;
299   double start, now;
300   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
301   int cpt;
302   s_gras_msg_t msg;
303   
304   *expeditor = NULL;
305   payload_got = NULL;
306
307   if (!msgt_want)
308     RAISE0(mismatch_error,
309            "Cannot wait for the NULL message (did msgtype_by_name fail?)");
310
311   VERB1("Waiting for message %s",msgt_want->name);
312
313   start = now = gras_os_time();
314
315   xbt_dynar_foreach(pd->msg_queue,cpt,msg){
316     if (msg.type->code == msgt_want->code) {
317       *expeditor = msg.expeditor;
318       memcpy(payload, msg.payload, msg.payload_size);
319       free(msg.payload);
320       xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
321       VERB0("The waited message was queued");
322       return no_error;
323     }
324   }
325
326   while (1) {
327     TRY(gras_trp_select(timeout - now + start, expeditor));
328     TRY(gras_msg_recv(*expeditor, &msgt_got, &payload_got, &payload_size_got));
329     if (msgt_got->code == msgt_want->code) {
330       memcpy(payload, payload_got, payload_size_got);
331       free(payload_got);
332       VERB0("Got waited message");
333       return no_error;
334     }
335
336     /* not expected msg type. Queue it for later */
337     msg.expeditor = *expeditor;
338     msg.type      =  msgt_got;
339     msg.payload   =  payload;
340     msg.payload_size = payload_size_got;
341     xbt_dynar_push(pd->msg_queue,&msg);
342     
343     now=gras_os_time();
344     if (now - start + 0.001 < timeout) {
345       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
346     }
347   }
348
349   RAISE_IMPOSSIBLE;
350 }
351
352 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
353  *
354  * @param timeOut: How long to wait for incoming messages (in seconds)
355  * @return the error code (or no_error).
356  *
357  * Messages are passed to the callbacks.
358  */
359 xbt_error_t 
360 gras_msg_handle(double timeOut) {
361   
362   double          untiltimer;
363    
364   xbt_error_t    errcode;
365   int             cpt;
366
367   s_gras_msg_t    msg;
368   gras_socket_t   expeditor;
369   void           *payload=NULL;
370   int             payload_size;
371   gras_msgtype_t  msgtype;
372
373   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
374   gras_cblist_t  *list=NULL;
375   gras_msg_cb_t       cb;
376    
377   int timerexpected;
378
379   VERB1("Handling message within the next %.2fs",timeOut);
380   
381   untiltimer = gras_msg_timer_handle();
382   DEBUG2("[%.0f] Next timer in %f sec", gras_os_time(), untiltimer);
383   if (untiltimer == 0.0) {
384      /* A timer was already elapsed and handled */
385      return no_error;
386   }
387   if (untiltimer != -1.0) {
388      timerexpected = 1;
389      timeOut = MIN(timeOut, untiltimer);
390   } else {
391      timerexpected = 0;
392   }
393    
394   /* get a message (from the queue or from the net) */
395   if (xbt_dynar_length(pd->msg_queue)) {
396     DEBUG0("Get a message from the queue");
397     xbt_dynar_shift(pd->msg_queue,&msg);
398     expeditor = msg.expeditor;
399     msgtype   = msg.type;
400     payload   = msg.payload;
401     errcode   = no_error;
402   } else {
403     errcode = gras_trp_select(timeOut, &expeditor);
404     if (errcode != no_error && errcode != timeout_error)
405        return errcode;
406     if (errcode != timeout_error)
407        TRY(gras_msg_recv(expeditor, &msgtype, &payload, &payload_size));
408   }
409
410   if (errcode == timeout_error ) {
411      if (timerexpected) {
412           
413         /* A timer elapsed before the arrival of any message even if we select()ed a bit */
414         untiltimer = gras_msg_timer_handle();
415         if (untiltimer == 0.0) {
416            return no_error;
417         } else {
418            xbt_assert1(untiltimer>0, "Negative timer (%f). I'm puzzeled", untiltimer);
419            ERROR1("No timer elapsed, in contrary to expectations (next in %f sec)",
420                   untiltimer);
421            return timeout_error;
422         }
423         
424      } else {
425         /* select timeouted, and no timer elapsed. Nothing to do */
426         return timeout_error;
427      }
428      
429   }
430    
431   /* A message was already there or arrived in the meanwhile. handle it */
432   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
433     if (list->id == msgtype->code) {
434       break;
435     } else {
436       list=NULL;
437     }
438   }
439   if (!list) {
440     INFO1("No callback for the incomming '%s' message. Discarded.", 
441           msgtype->name);
442     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
443     return no_error;
444   }
445   
446   xbt_dynar_foreach(list->cbs,cpt,cb) { 
447     VERB3("Use the callback #%d (@%p) for incomming msg %s",
448           cpt+1,cb,msgtype->name);
449     if ((*cb)(expeditor,payload)) {
450       /* cb handled the message */
451       free(payload);
452       return no_error;
453     }
454   }
455
456   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
457   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
458   return mismatch_error;
459 }
460
461 void
462 gras_cbl_free(void *data){
463   gras_cblist_t *list=*(void**)data;
464   if (list) {
465     xbt_dynar_free(&( list->cbs ));
466     free(list);
467   }
468 }
469
470 /** \brief Bind the given callback to the given message type 
471  *
472  * Several callbacks can be attached to a given message type. The lastly added one will get the message first, and 
473  * if it returns false, the message will be passed to the second one. 
474  * And so on until one of the callbacks accepts the message.
475  */
476 void
477 gras_cb_register(gras_msgtype_t msgtype,
478                  gras_msg_cb_t cb) {
479   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
480   gras_cblist_t *list=NULL;
481   int cpt;
482
483   DEBUG2("Register %p as callback to %s",cb,msgtype->name);
484
485   /* search the list of cb for this message on this host (creating if NULL) */
486   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
487     if (list->id == msgtype->code) {
488       break;
489     } else {
490       list=NULL;
491     }
492   }
493   if (!list) {
494     /* First cb? Create room */
495     list = xbt_new(gras_cblist_t,1);
496     list->id = msgtype->code;
497     list->cbs = xbt_dynar_new(sizeof(gras_msg_cb_t), NULL);
498     xbt_dynar_push(pd->cbl_list,&list);
499   }
500
501   /* Insert the new one into the set */
502   xbt_dynar_insert_at(list->cbs,0,&cb);
503 }
504
505 /** \brief Unbind the given callback from the given message type */
506 void
507 gras_cb_unregister(gras_msgtype_t msgtype,
508                    gras_msg_cb_t cb) {
509
510   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_get("gras_msg");
511   gras_cblist_t *list;
512   gras_msg_cb_t cb_cpt;
513   int cpt;
514   int found = 0;
515
516   /* search the list of cb for this message on this host */
517   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
518     if (list->id == msgtype->code) {
519       break;
520     } else {
521       list=NULL;
522     }
523   }
524
525   /* Remove it from the set */
526   if (list) {
527     xbt_dynar_foreach(list->cbs,cpt,cb_cpt) {
528       if (cb == cb_cpt) {
529         xbt_dynar_cursor_rm(list->cbs, &cpt);
530         found = 1;
531       }
532     }
533   }
534   if (!found)
535     VERB1("Ignoring removal of unexisting callback to msg id %d",
536           msgtype->code);
537 }