Logo AND Algorithmique Numérique Distribuée

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