Logo AND Algorithmique Numérique Distribuée

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