Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix the inclusion paths
[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 "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 GRAS_LOG_NEW_DEFAULT_SUBCATEGORY(msg,GRAS);
17
18 gras_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  * gras_msg_init:
24  *
25  * Initialize this submodule.
26  */
27 void gras_msg_init(void) {
28   gras_error_t errcode;
29   
30   /* only initialize once */
31   if (_gras_msgtype_set != NULL)
32     return;
33
34   VERB0("Initializing Msg");
35   
36   TRYFAIL(gras_set_new(&_gras_msgtype_set));
37
38   memcpy(GRAS_header,"GRAS", 4);
39   GRAS_header[4]=GRAS_PROTOCOL_VERSION;
40   GRAS_header[5]=(char)GRAS_THISARCH;
41 }
42
43 /**
44  * gras_msg_exit:
45  *
46  * Finalize the msg module
47  **/
48 void
49 gras_msg_exit(void) {
50   VERB0("Exiting Msg");
51   gras_set_free(&_gras_msgtype_set);
52   _gras_msgtype_set = NULL;
53 }
54
55 /**
56  * gras_msgtype_free:
57  *
58  * Reclamed memory
59  */
60 void gras_msgtype_free(void *t) {
61   gras_msgtype_t *msgtype=(gras_msgtype_t *)t;
62   if (msgtype) {
63     free(msgtype->name);
64     free(msgtype);
65   }
66 }
67
68 /**
69  * make_namev:
70  *
71  * Returns the versionned name of the message. If the version is 0, that's 
72  * the name unchanged. Pay attention to this before free'ing the result.
73  */
74 static char *make_namev(const char *name, short int ver) {
75   char *namev;
76
77   if (!ver)
78     return (char *)name;
79
80   namev = malloc(strlen(name)+2+3+1);
81
82   if (namev) {
83       sprintf(namev,"%s_v%d",name,ver);
84   }
85   return namev;
86 }
87
88 /**
89  * gras_msgtype_declare:
90  * @name: name as it should be used for logging messages (must be uniq)
91  * @payload: datadescription of the payload
92  *
93  * Registers a message to the GRAS mecanism.
94  */
95 gras_error_t
96 gras_msgtype_declare(const char            *name,
97                      gras_datadesc_type_t  *payload) {
98   return gras_msgtype_declare_v(name, 0, payload);
99 }
100
101 /**
102  * gras_msgtype_declare_v:
103  * @name: name as it should be used for logging messages (must be uniq)
104  * @version: something like versionning symbol
105  * @payload: datadescription of the payload
106  *
107  * Registers a message to the GRAS mecanism. Use this version instead of 
108  * gras_msgtype_declare when you change the semantic or syntax of a message and
109  * want your programs to be able to deal with both versions. Internally, each
110  * will be handled as an independent message type, so you can register 
111  * differents for each of them.
112  */
113 gras_error_t
114 gras_msgtype_declare_v(const char            *name,
115                        short int              version,
116                        gras_datadesc_type_t  *payload) {
117  
118   gras_error_t    errcode;
119   gras_msgtype_t *msgtype;
120   char *namev=make_namev(name,version);
121   
122   if (!namev)
123     RAISE_MALLOC;
124
125   errcode = gras_set_get_by_name(_gras_msgtype_set,
126                                  namev,(gras_set_elm_t**)&msgtype);
127
128   if (errcode == no_error) {
129     VERB2("Re-register version %d of message '%s' (same payload, ignored).",
130           version, name);
131     gras_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload),
132                  "Message %s re-registred with another payload (%s was %s)",
133                  namev,gras_datadesc_get_name(payload),
134                  gras_datadesc_get_name(msgtype->ctn_type));
135
136     return no_error; /* do really ignore it */
137
138   } else if (errcode == mismatch_error) {
139     INFO3("Register version %d of message '%s' (payload: %s).", 
140            version, name, gras_datadesc_get_name(payload));    
141   } else {
142     return errcode; /* Was expecting for mismatch_error */
143   }
144
145   if (! (msgtype = malloc(sizeof(gras_msgtype_t))) ) 
146     RAISE_MALLOC;
147
148   msgtype->name = (namev == name ? strdup(name) : namev);
149   msgtype->name_len = strlen(namev);
150   msgtype->version = version;
151   msgtype->ctn_type = payload;
152
153   TRY(gras_set_add(_gras_msgtype_set, (gras_set_elm_t*)msgtype,
154                    &gras_msgtype_free));
155    
156   return no_error;
157 }
158
159 /**
160  * gras_msgtype_by_name:
161  *
162  * Retrieve a datatype description from its name
163  */
164 gras_msgtype_t * gras_msgtype_by_name (const char *name) {
165   return gras_msgtype_by_namev(name,0);
166 }
167 /**
168  * gras_msgtype_by_namev:
169  *
170  * Retrieve a datatype description from its name and version
171  */
172 gras_msgtype_t * gras_msgtype_by_namev(const char      *name,
173                                        short int        version) {
174   gras_msgtype_t *res;
175
176   gras_error_t errcode;
177   char *namev = make_namev(name,version); 
178
179   errcode = gras_set_get_by_name(_gras_msgtype_set, namev,
180                                  (gras_set_elm_t**)&res);
181   if (errcode != no_error)
182     res = NULL;
183   if (name != namev) 
184     free(namev);
185   
186   return res;
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
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     gras_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  * gras_msg_recv:
223  *
224  * receive the next message on the given socket.  
225  */
226 gras_error_t
227 gras_msg_recv(gras_socket_t   *sock,
228               gras_msgtype_t **msgtype,
229               void           **payload,
230               int             *payload_size) {
231
232   gras_error_t errcode;
233   static gras_datadesc_type_t *string_type=NULL;
234   char header[6];
235   int cpt;
236   int r_arch;
237   char *msg_name=NULL;
238
239   if (!string_type) {
240     string_type=gras_datadesc_by_name("string");
241     gras_assert(string_type);
242   }
243   
244   TRY(gras_trp_chunk_recv(sock, header, 6));
245   for (cpt=0; cpt<4; cpt++)
246     if (header[cpt] != GRAS_header[cpt])
247       RAISE0(mismatch_error,"Incoming bytes do not look like a GRAS message");
248   if (header[4] != GRAS_header[4]) 
249     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
250            (int)header[4], (int)GRAS_header[4]);
251   r_arch = (int)header[5];
252   DEBUG2("Handle an incoming message using protocol %d (remote is %s)",
253          (int)header[4],gras_datadesc_arch_name(r_arch));
254
255   TRY(gras_datadesc_recv(sock, string_type, r_arch, &msg_name));
256   errcode = gras_set_get_by_name(_gras_msgtype_set,
257                                  msg_name,(gras_set_elm_t**)msgtype);
258   if (errcode != no_error)
259     RAISE2(errcode,
260            "Got error %s while retrieving the type associated to messages '%s'",
261            gras_error_name(errcode),msg_name);
262   /* FIXME: Survive unknown messages */
263   free(msg_name);
264
265   *payload_size=gras_datadesc_size((*msgtype)->ctn_type);
266   gras_assert2(*payload_size > 0,
267                "%s %s",
268                "Dynamic array as payload is forbided for now (FIXME?).",
269                "Reference to dynamic array is allowed.");
270   *payload = malloc(*payload_size);
271   TRY(gras_datadesc_recv(sock, (*msgtype)->ctn_type, r_arch, *payload));
272
273   return no_error;
274 }
275
276 /**
277  * gras_msg_wait:
278  * @timeout: How long should we wait for this message.
279  * @id: id of awaited msg
280  * @Returns: the error code (or no_error).
281  *
282  * Waits for a message to come in over a given socket.
283  *
284  * Every message of another type received before the one waited will be queued
285  * and used by subsequent call to this function or MsgHandle().
286  */
287 gras_error_t
288 gras_msg_wait(double                 timeout,    
289               gras_msgtype_t        *msgt_want,
290               gras_socket_t        **expeditor,
291               void                  *payload) {
292
293   gras_msgtype_t *msgt_got;
294   void *payload_got;
295   int payload_size_got;
296   gras_error_t errcode;
297   double start, now;
298   gras_procdata_t *pd=gras_procdata_get();
299   int cpt;
300   gras_msg_t msg;
301   
302   *expeditor = NULL;
303   payload_got = NULL;
304
305   if (!msgt_want)
306     RAISE0(mismatch_error,
307            "Cannot wait for the NULL message (did msgtype_by_name fail?)");
308
309   VERB1("Waiting for message %s",msgt_want->name);
310
311   start = now = gras_os_time();
312
313   gras_dynar_foreach(pd->msg_queue,cpt,msg){
314     if (msg.type->code == msgt_want->code) {
315       *expeditor = msg.expeditor;
316       memcpy(payload, msg.payload, msg.payload_size);
317       free(msg.payload);
318       gras_dynar_cursor_rm(pd->msg_queue, &cpt);
319       VERB0("The waited message was queued");
320       return no_error;
321     }
322   }
323
324   while (1) {
325     TRY(gras_trp_select(timeout - now + start, expeditor));
326     TRY(gras_msg_recv(*expeditor, &msgt_got, &payload_got, &payload_size_got));
327     if (msgt_got->code == msgt_want->code) {
328       memcpy(payload, payload_got, payload_size_got);
329       free(payload_got);
330       VERB0("Got waited message");
331       return no_error;
332     }
333
334     /* not expected msg type. Queue it for later */
335     msg.expeditor = *expeditor;
336     msg.type      =  msgt_got;
337     msg.payload   =  payload;
338     msg.payload_size = payload_size_got;
339     TRY(gras_dynar_push(pd->msg_queue,&msg));
340     
341     now=gras_os_time();
342     if (now - start + 0.001 < timeout) {
343       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
344     }
345   }
346
347   RAISE_IMPOSSIBLE;
348 }
349
350 /**
351  * gras_msg_handle:
352  * @timeOut: How long to wait for incoming messages
353  * @Returns: the error code (or no_error).
354  *
355  * Waits up to #timeOut# seconds to see if a message comes in; if so, calls the
356  * registered listener for that message (see RegisterCallback()).
357  */
358 gras_error_t 
359 gras_msg_handle(double timeOut) {
360   
361   gras_error_t    errcode;
362   int             cpt;
363
364   gras_msg_t      msg;
365   gras_socket_t  *expeditor;
366   void           *payload=NULL;
367   int             payload_size;
368   gras_msgtype_t *msgtype;
369
370   gras_procdata_t*pd=gras_procdata_get();
371   gras_cblist_t  *list;
372   gras_cb_t       cb;
373
374
375
376   VERB1("Handling message within the next %.2fs",timeOut);
377   
378   /* get a message (from the queue or from the net) */
379   if (gras_dynar_length(pd->msg_queue)) {
380     gras_dynar_shift(pd->msg_queue,&msg);
381     expeditor = msg.expeditor;
382     msgtype   = msg.type;
383     payload   = msg.payload;
384     
385   } else {
386     TRY(gras_trp_select(timeOut, &expeditor));
387     TRY(gras_msg_recv(expeditor, &msgtype, &payload, &payload_size));
388   }
389       
390   /* handle it */
391   gras_dynar_foreach(pd->cbl_list,cpt,list) {
392     if (list->id == msgtype->code) {
393       break;
394     } else {
395       list=NULL;
396     }
397   }
398   if (!list) {
399     INFO1("No callback for the incomming '%s' message. Discarded.", 
400           msgtype->name);
401     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
402     return no_error;
403   }
404   
405   gras_dynar_foreach(list->cbs,cpt,cb) { 
406     INFO3("Invoque the callback #%d (@%p) for incomming msg %s",
407           cpt+1,cb,msgtype->name);
408     if ((*cb)(expeditor,payload)) {
409       /* cb handled the message */
410       free(payload);
411       return no_error;
412     }
413   }
414
415   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
416   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
417   return mismatch_error;
418 }
419
420 void
421 gras_cbl_free(void *data){
422   gras_cblist_t *list=*(void**)data;
423   if (list) {
424     gras_dynar_free(list->cbs);
425     free(list);
426   }
427 }
428
429 gras_error_t
430 gras_cb_register(gras_msgtype_t *msgtype,
431                  gras_cb_t cb) {
432   gras_error_t errcode;
433   gras_procdata_t *pd=gras_procdata_get();
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   gras_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 = malloc(sizeof(gras_cblist_t));
450     if (!list)
451       RAISE_MALLOC;
452
453     list->id = msgtype->code;
454     TRY(gras_dynar_new(&(list->cbs), sizeof(gras_cb_t), NULL));
455     TRY(gras_dynar_push(pd->cbl_list,&list));
456   }
457
458   /* Insert the new one into the set */
459   TRY(gras_dynar_insert_at(list->cbs,0,&cb));
460
461   return no_error;
462 }
463
464 void
465 gras_cb_unregister(gras_msgtype_t *msgtype,
466                    gras_cb_t cb) {
467
468   gras_procdata_t *pd=gras_procdata_get();
469   gras_cblist_t *list;
470   gras_cb_t cb_cpt;
471   int cpt;
472   int found = 0;
473
474   /* search the list of cb for this message on this host */
475   gras_dynar_foreach(pd->cbl_list,cpt,list) {
476     if (list->id == msgtype->code) {
477       break;
478     } else {
479       list=NULL;
480     }
481   }
482
483   /* Remove it from the set */
484   if (list) {
485     gras_dynar_foreach(list->cbs,cpt,cb_cpt) {
486       if (cb == cb_cpt) {
487         gras_dynar_cursor_rm(list->cbs, &cpt);
488         found = 1;
489       }
490     }
491   }
492   if (!found)
493     VERB1("Ignoring removal of unexisting callback to msg id %d",
494           msgtype->code);
495 }