Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
register the message even if it's already there with the same payload so that the...
[simgrid.git] / src / gras / Msg / msg.c
1 /* $Id$ */
2
3 /* messaging - Function related to messaging (code shared between RL and SG)*/
4
5 /* Authors: Martin Quinson                                                  */
6 /* Copyright (C) 2003 the OURAGAN project.                                  */
7
8 /* This program is free software; you can redistribute it and/or modify it
9    under the terms of the license (GNU LGPL) which comes with this package. */
10
11 #include "Msg/msg_private.h"
12
13 GRAS_LOG_NEW_DEFAULT_SUBCATEGORY(msg,GRAS);
14
15 gras_set_t *_gras_msgtype_set = NULL;
16 static char GRAS_header[6];
17 static char *make_namev(const char *name, short int ver);
18
19 /**
20  * gras_msg_init:
21  *
22  * Initialize this submodule.
23  */
24 void gras_msg_init(void) {
25   gras_error_t errcode;
26   
27   /* only initialize once */
28   if (_gras_msgtype_set != NULL)
29     return;
30
31   VERB0("Initializing Msg");
32   
33   TRYFAIL(gras_set_new(&_gras_msgtype_set));
34
35   memcpy(GRAS_header,"GRAS", 4);
36   GRAS_header[4]=GRAS_PROTOCOL_VERSION;
37   GRAS_header[5]=(char)GRAS_THISARCH;
38 }
39
40 /**
41  * gras_msg_exit:
42  *
43  * Finalize the msg module
44  **/
45 void
46 gras_msg_exit(void) {
47   VERB0("Exiting Msg");
48   gras_set_free(&_gras_msgtype_set);
49   _gras_msgtype_set = NULL;
50 }
51
52 /**
53  * gras_msgtype_free:
54  *
55  * Reclamed memory
56  */
57 void gras_msgtype_free(void *t) {
58   gras_msgtype_t *msgtype=(gras_msgtype_t *)t;
59   if (msgtype) {
60     free(msgtype->name);
61     free(msgtype);
62   }
63 }
64
65 /**
66  * make_namev:
67  *
68  * Returns the versionned name of the message. If the version is 0, that's 
69  * the name unchanged. Pay attention to this before free'ing the result.
70  */
71 static char *make_namev(const char *name, short int ver) {
72   char *namev;
73
74   if (!ver)
75     return (char *)name;
76
77   namev = malloc(strlen(name)+2+3+1);
78
79   if (namev) {
80       sprintf(namev,"%s_v%d",name,ver);
81   }
82   return namev;
83 }
84
85 /**
86  * gras_msgtype_declare:
87  * @name: name as it should be used for logging messages (must be uniq)
88  * @payload: datadescription of the payload
89  *
90  * Registers a message to the GRAS mecanism.
91  */
92 gras_error_t
93 gras_msgtype_declare(const char            *name,
94                      gras_datadesc_type_t  *payload,
95                      gras_msgtype_t       **dst) {
96   return gras_msgtype_declare_v(name, 0, payload, dst);
97 }
98
99 /**
100  * gras_msgtype_declare_v:
101  * @name: name as it should be used for logging messages (must be uniq)
102  * @version: something like versionning symbol
103  * @payload: datadescription of the payload
104  *
105  * Registers a message to the GRAS mecanism. Use this version instead of 
106  * gras_msgtype_declare when you change the semantic or syntax of a message and
107  * want your programs to be able to deal with both versions. Internally, each
108  * will be handled as an independent message type, so you can register 
109  * differents for each of them.
110  */
111 gras_error_t
112 gras_msgtype_declare_v(const char            *name,
113                        short int              version,
114                        gras_datadesc_type_t  *payload,
115                        gras_msgtype_t       **dst) {
116  
117   gras_error_t    errcode;
118   gras_msgtype_t *msgtype;
119   char *namev=make_namev(name,version);
120   
121   if (!namev)
122     RAISE_MALLOC;
123
124   errcode = gras_set_get_by_name(_gras_msgtype_set,
125                                  namev,(gras_set_elm_t**)&msgtype);
126
127   if (errcode == no_error) {
128     VERB2("Re-register version %d of message '%s' (same payload, ignored).",
129           version, name);
130     gras_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload),
131                  "Message %s re-registred with another payload (%s was %s)",
132                  namev,gras_datadesc_get_name(payload),
133                  gras_datadesc_get_name(msgtype->ctn_type));
134   } else if (errcode == mismatch_error) {
135     INFO3("Register version %d of message '%s' (payload: %s).", 
136            version, name, gras_datadesc_get_name(payload));    
137   } else {
138     return errcode; /* Was expecting for mismatch_error */
139   }
140
141   /* create type anyway so that the old type gets removed from here, and
142      hopefully free'd when ref counter gets 0 */
143   if (! (msgtype = malloc(sizeof(gras_msgtype_t))) ) 
144     RAISE_MALLOC;
145
146   msgtype->name = (namev == name ? strdup(name) : namev);
147   msgtype->name_len = strlen(namev);
148   msgtype->version = version;
149   msgtype->ctn_type = payload;
150   gras_datadesc_ref(payload);
151
152   TRY(gras_set_add(_gras_msgtype_set, (gras_set_elm_t*)msgtype,
153                    &gras_msgtype_free));
154
155   return no_error;
156 }
157
158 /**
159  * gras_msgtype_by_name:
160  *
161  * Retrieve a datatype description from its name
162  */
163 gras_error_t 
164 gras_msgtype_by_name (const char     *name,
165                       gras_msgtype_t **dst) {
166   return gras_msgtype_by_namev(name,0,dst);
167 }
168 /**
169  * gras_msgtype_by_namev:
170  *
171  * Retrieve a datatype description from its name and version
172  */
173 gras_error_t
174 gras_msgtype_by_namev(const char      *name,
175                       short int        version,
176                       gras_msgtype_t **dst) {
177
178   gras_error_t errcode;
179   char *namev = make_namev(name,version); 
180
181   errcode = gras_set_get_by_name(_gras_msgtype_set, namev,
182                                  (gras_set_elm_t**)dst);
183   if (name != namev) 
184     free(namev);
185
186   return errcode;
187 }
188
189 /**
190  * gras_msg_send:
191  *
192  * Send the given message on the given socket 
193  */
194 gras_error_t
195 gras_msg_send(gras_socket_t  *sock,
196               gras_msgtype_t *msgtype,
197               void           *payload) {
198
199   gras_error_t errcode;
200   static gras_datadesc_type_t *string_type=NULL;
201   if (!string_type) {
202     string_type = gras_datadesc_by_name("string");
203     gras_assert(string_type);
204   }
205   
206   TRY(gras_trp_chunk_send(sock, GRAS_header, 6));
207
208   TRY(gras_datadesc_send(sock, string_type,       msgtype->name));
209   TRY(gras_datadesc_send(sock, msgtype->ctn_type, payload));
210
211   return no_error;
212 }
213 /**
214  * gras_msg_recv:
215  *
216  * receive the next message on the given socket.  
217  * The room for the payload will be malloc'ed by the function.
218  */
219 gras_error_t
220 gras_msg_recv(gras_socket_t   *sock,
221               gras_msgtype_t **msgtype,
222               void           **payload) {
223
224   *payload = NULL;
225   return gras_msg_recv_no_malloc(sock,msgtype,payload);
226 }
227 /**
228  * gras_msg_recv_no_malloc:
229  *
230  * receive the next message on the given socket. 
231  *
232  * No room will be allocated by the function, which is good to get
233  * the payload onto the stack (passing the address of a static variable), 
234  * but will happily segfault if passed an arbitrary pointer... 
235  */
236 gras_error_t
237 gras_msg_recv_no_malloc(gras_socket_t   *sock,
238                         gras_msgtype_t **msgtype,
239                         void           **payload) {
240   
241   gras_error_t errcode;
242   static gras_datadesc_type_t *string_type=NULL;
243   char header[6];
244   int cpt;
245   int r_arch;
246   char *msg_name=NULL;
247
248   if (!string_type) {
249     string_type=gras_datadesc_by_name("string");
250     gras_assert(string_type);
251   }
252   
253   TRY(gras_trp_chunk_recv(sock, header, 6));
254   for (cpt=0; cpt<4; cpt++)
255     if (header[cpt] != GRAS_header[cpt])
256       RAISE0(mismatch_error,"Incoming bytes do not look like a GRAS message");
257   if (header[4] != GRAS_header[4]) 
258     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
259            (int)header[4], (int)GRAS_header[4]);
260   r_arch = (int)header[5];
261   DEBUG2("Handle an incoming message using protocol %d from arch %s",
262          (int)header[4],gras_datadesc_arch_name(r_arch));
263
264   TRY(gras_datadesc_recv(sock, string_type, r_arch,(void**) &msg_name));
265   TRY(gras_set_get_by_name(_gras_msgtype_set,
266                            msg_name,(gras_set_elm_t**)msgtype));
267   TRY(gras_datadesc_recv(sock, (*msgtype)->ctn_type, r_arch, payload));
268
269   return no_error;
270 }
271
272 /**
273  * gras_msg_wait:
274  * @timeout: How long should we wait for this message.
275  * @id: id of awaited msg
276  * @Returns: the error code (or no_error).
277  *
278  * Waits for a message to come in over a given socket.
279  *
280  * Every message of another type received before the one waited will be queued
281  * and used by subsequent call to this function or MsgHandle().
282  */
283 gras_error_t
284 gras_msg_wait(double                 timeout,    
285               gras_msgtype_t        *msgt_want,
286               gras_socket_t        **expeditor,
287               void                 **payload) {
288
289   gras_msgtype_t *msgt_got;
290   gras_error_t errcode;
291   double start, now;
292   gras_procdata_t *pd=gras_procdata_get();
293   int cpt;
294   gras_msg_t msg;
295   
296   *expeditor = NULL;
297   *payload   = NULL;
298
299   VERB1("Waiting for message %s",msgt_want->name);
300
301   start = now = gras_time();
302
303   gras_dynar_foreach(pd->msg_queue,cpt,msg){
304     if (msg.type->code == msgt_want->code) {
305       *expeditor = msg.expeditor;
306       *payload   = msg.payload;
307       gras_dynar_cursor_rm(pd->msg_queue, &cpt);
308       VERB0("Waited message was queued");
309       return no_error;
310     }
311   }
312
313   while (1) {
314     TRY(gras_trp_select(timeout - now + start, expeditor));
315     TRY(gras_msg_recv(*expeditor, &msgt_got, payload));
316     if (msgt_got->code == msgt_want->code) {
317       VERB0("Got waited message");
318       return no_error;
319     }
320
321     /* not expected msg type. Queue it for later */
322     msg.expeditor = *expeditor;
323     msg.type      =  msgt_got;
324     msg.payload   = *payload;
325     TRY(gras_dynar_push(pd->msg_queue,&msg));
326     
327     now=gras_time();
328     if (now - start + 0.001 < timeout) {
329       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
330     }
331   }
332
333   RAISE_IMPOSSIBLE;
334 }
335
336 /**
337  * gras_msg_handle:
338  * @timeOut: How long to wait for incoming messages
339  * @Returns: the error code (or no_error).
340  *
341  * Waits up to #timeOut# seconds to see if a message comes in; if so, calls the
342  * registered listener for that message (see RegisterCallback()).
343  */
344 gras_error_t 
345 gras_msg_handle(double timeOut) {
346   
347   gras_error_t    errcode;
348   int             cpt;
349
350   gras_msg_t      msg;
351   gras_socket_t  *expeditor;
352   void           *payload=NULL;
353   gras_msgtype_t *msgtype;
354
355   gras_procdata_t*pd=gras_procdata_get();
356   gras_cblist_t  *list;
357   gras_cb_t       cb;
358
359
360
361   VERB1("Handling message within the next %.2fs",timeOut);
362   
363   /* get a message (from the queue or from the net) */
364   if (gras_dynar_length(pd->msg_queue)) {
365     gras_dynar_shift(pd->msg_queue,&msg);
366     expeditor = msg.expeditor;
367     msgtype   = msg.type;
368     payload   = msg.payload;
369     
370   } else {
371     TRY(gras_trp_select(timeOut, &expeditor));
372     TRY(gras_msg_recv(expeditor, &msgtype, &payload));
373   }
374       
375   /* handle it */
376   gras_dynar_foreach(pd->cbl_list,cpt,list) {
377     if (list->id == msgtype->code) {
378       break;
379     } else {
380       list=NULL;
381     }
382   }
383   if (!list) {
384     INFO1("No callback for the incomming '%s' message. Discarded.", 
385           msgtype->name);
386     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
387     return no_error;
388   }
389   
390   gras_dynar_foreach(list->cbs,cpt,cb) { 
391     INFO3("Invoque the callback #%d (@%p) for incomming msg %s",
392           cpt+1,cb,msgtype->name);
393     if ((*cb)(expeditor,msgtype->ctn_type,payload)) {
394       /* cb handled the message */
395       return no_error;
396     }
397   }
398
399   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
400   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
401   return mismatch_error;
402 }
403
404 gras_error_t
405 gras_cb_register(gras_msgtype_t *msgtype,
406                  gras_cb_t cb) {
407   gras_error_t errcode;
408   gras_procdata_t *pd=gras_procdata_get();
409   gras_cblist_t *list=NULL;
410   int cpt;
411
412   DEBUG2("Register %p as callback to %s",cb,msgtype->name);
413
414   /* search the list of cb for this message on this host (creating if NULL) */
415   gras_dynar_foreach(pd->cbl_list,cpt,list) {
416     if (list->id == msgtype->code) {
417       break;
418     } else {
419       list=NULL;
420     }
421   }
422   if (!list) {
423     /* First cb? Create room */
424     list = malloc(sizeof(gras_cblist_t));
425     if (!list)
426       RAISE_MALLOC;
427
428     list->id = msgtype->code;
429     TRY(gras_dynar_new(&(list->cbs), sizeof(gras_cb_t), NULL));
430     TRY(gras_dynar_push(pd->cbl_list,&list));
431   }
432
433   /* Insert the new one into the set */
434   TRY(gras_dynar_insert_at(list->cbs,0,&cb));
435
436   return no_error;
437 }
438
439 void
440 gras_cb_unregister(gras_msgtype_t *msgtype,
441                    gras_cb_t cb) {
442
443   gras_procdata_t *pd=gras_procdata_get();
444   gras_cblist_t *list;
445   gras_cb_t cb_cpt;
446   int cpt;
447   int found = 0;
448
449   /* search the list of cb for this message on this host */
450   gras_dynar_foreach(pd->cbl_list,cpt,list) {
451     if (list->id == msgtype->code) {
452       break;
453     } else {
454       list=NULL;
455     }
456   }
457
458   /* Remove it from the set */
459   if (list) {
460     gras_dynar_foreach(list->cbs,cpt,cb_cpt) {
461       if (cb == cb_cpt) {
462         gras_dynar_cursor_rm(list->cbs, &cpt);
463         found = 1;
464       }
465     }
466   }
467   if (!found)
468     VERB1("Ignoring removal of unexisting callback to msg id %d",
469           msgtype->code);
470 }