Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Current state. See changelog, sorry, I'm out of time
[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,"High level messaging");
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   _gras_msgtype_set = gras_set_new();
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     gras_free(msgtype->name);
64     gras_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 = (char*)gras_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 void gras_msgtype_declare(const char            *name,
96                           gras_datadesc_type_t  *payload) {
97    gras_msgtype_declare_v(name, 0, payload);
98 }
99
100 /**
101  * gras_msgtype_declare_v:
102  * @name: name as it should be used for logging messages (must be uniq)
103  * @version: something like versionning symbol
104  * @payload: datadescription of the payload
105  *
106  * Registers a message to the GRAS mecanism. Use this version instead of 
107  * gras_msgtype_declare when you change the semantic or syntax of a message and
108  * want your programs to be able to deal with both versions. Internally, each
109  * will be handled as an independent message type, so you can register 
110  * differents for each of them.
111  */
112 void
113 gras_msgtype_declare_v(const char            *name,
114                        short int              version,
115                        gras_datadesc_type_t  *payload) {
116  
117   gras_error_t    errcode;
118   gras_msgtype_t *msgtype;
119   char *namev=make_namev(name,version);
120   
121   errcode = gras_set_get_by_name(_gras_msgtype_set,
122                                  namev,(gras_set_elm_t**)&msgtype);
123
124   if (errcode == no_error) {
125     VERB2("Re-register version %d of message '%s' (same payload, ignored).",
126           version, name);
127     gras_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload),
128                  "Message %s re-registred with another payload (%s was %s)",
129                  namev,gras_datadesc_get_name(payload),
130                  gras_datadesc_get_name(msgtype->ctn_type));
131
132     return ; /* do really ignore it */
133
134   }
135   gras_assert_error(mismatch_error); /* expect this error */
136   INFO3("Register version %d of message '%s' (payload: %s).", 
137         version, name, gras_datadesc_get_name(payload));    
138
139   msgtype = gras_new(gras_msgtype_t,1);
140   msgtype->name = (namev == name ? strdup(name) : namev);
141   msgtype->name_len = strlen(namev);
142   msgtype->version = version;
143   msgtype->ctn_type = payload;
144
145   gras_set_add(_gras_msgtype_set, (gras_set_elm_t*)msgtype,
146                &gras_msgtype_free);
147 }
148
149 /**
150  * gras_msgtype_by_name:
151  *
152  * Retrieve a datatype description from its name
153  */
154 gras_msgtype_t * gras_msgtype_by_name (const char *name) {
155   return gras_msgtype_by_namev(name,0);
156 }
157 /**
158  * gras_msgtype_by_namev:
159  *
160  * Retrieve a datatype description from its name and version
161  */
162 gras_msgtype_t * gras_msgtype_by_namev(const char      *name,
163                                        short int        version) {
164   gras_msgtype_t *res;
165
166   gras_error_t errcode;
167   char *namev = make_namev(name,version); 
168
169   errcode = gras_set_get_by_name(_gras_msgtype_set, namev,
170                                  (gras_set_elm_t**)&res);
171   if (errcode != no_error)
172     res = NULL;
173   if (name != namev) 
174     gras_free(namev);
175   
176   return res;
177 }
178
179 /**
180  * gras_msg_send:
181  *
182  * Send the given message on the given socket 
183  */
184 gras_error_t
185 gras_msg_send(gras_socket_t  *sock,
186               gras_msgtype_t *msgtype,
187               void           *payload) {
188
189   gras_error_t errcode;
190   static gras_datadesc_type_t *string_type=NULL;
191
192   if (!msgtype)
193     RAISE0(mismatch_error,
194            "Cannot send the NULL message (did msgtype_by_name fail?)");
195
196   if (!string_type) {
197     string_type = gras_datadesc_by_name("string");
198     gras_assert(string_type);
199   }
200
201   DEBUG3("send '%s' to %s:%d", msgtype->name, 
202          gras_socket_peer_name(sock),gras_socket_peer_port(sock));
203   TRY(gras_trp_chunk_send(sock, GRAS_header, 6));
204
205   TRY(gras_datadesc_send(sock, string_type,   &msgtype->name));
206   TRY(gras_datadesc_send(sock, msgtype->ctn_type, payload));
207   TRY(gras_trp_flush(sock));
208
209   return no_error;
210 }
211 /**
212  * gras_msg_recv:
213  *
214  * receive the next message on the given socket.  
215  */
216 gras_error_t
217 gras_msg_recv(gras_socket_t   *sock,
218               gras_msgtype_t **msgtype,
219               void           **payload,
220               int             *payload_size) {
221
222   gras_error_t errcode;
223   static gras_datadesc_type_t *string_type=NULL;
224   char header[6];
225   int cpt;
226   int r_arch;
227   char *msg_name=NULL;
228
229   if (!string_type) {
230     string_type=gras_datadesc_by_name("string");
231     gras_assert(string_type);
232   }
233   
234   TRY(gras_trp_chunk_recv(sock, header, 6));
235   for (cpt=0; cpt<4; cpt++)
236     if (header[cpt] != GRAS_header[cpt])
237       RAISE0(mismatch_error,"Incoming bytes do not look like a GRAS message");
238   if (header[4] != GRAS_header[4]) 
239     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
240            (int)header[4], (int)GRAS_header[4]);
241   r_arch = (int)header[5];
242   DEBUG2("Handle an incoming message using protocol %d (remote is %s)",
243          (int)header[4],gras_datadesc_arch_name(r_arch));
244
245   TRY(gras_datadesc_recv(sock, string_type, r_arch, &msg_name));
246   errcode = gras_set_get_by_name(_gras_msgtype_set,
247                                  msg_name,(gras_set_elm_t**)msgtype);
248   if (errcode != no_error)
249     RAISE2(errcode,
250            "Got error %s while retrieving the type associated to messages '%s'",
251            gras_error_name(errcode),msg_name);
252   /* FIXME: Survive unknown messages */
253   gras_free(msg_name);
254
255   *payload_size=gras_datadesc_size((*msgtype)->ctn_type);
256   gras_assert2(*payload_size > 0,
257                "%s %s",
258                "Dynamic array as payload is forbided for now (FIXME?).",
259                "Reference to dynamic array is allowed.");
260   *payload = gras_malloc(*payload_size);
261   TRY(gras_datadesc_recv(sock, (*msgtype)->ctn_type, r_arch, *payload));
262
263   return no_error;
264 }
265
266 /**
267  * gras_msg_wait:
268  * @timeout: How long should we wait for this message.
269  * @id: id of awaited msg
270  * @Returns: the error code (or no_error).
271  *
272  * Waits for a message to come in over a given socket.
273  *
274  * Every message of another type received before the one waited will be queued
275  * and used by subsequent call to this function or MsgHandle().
276  */
277 gras_error_t
278 gras_msg_wait(double                 timeout,    
279               gras_msgtype_t        *msgt_want,
280               gras_socket_t        **expeditor,
281               void                  *payload) {
282
283   gras_msgtype_t *msgt_got;
284   void *payload_got;
285   int payload_size_got;
286   gras_error_t errcode;
287   double start, now;
288   gras_procdata_t *pd=gras_procdata_get();
289   int cpt;
290   gras_msg_t msg;
291   
292   *expeditor = NULL;
293   payload_got = NULL;
294
295   if (!msgt_want)
296     RAISE0(mismatch_error,
297            "Cannot wait for the NULL message (did msgtype_by_name fail?)");
298
299   VERB1("Waiting for message %s",msgt_want->name);
300
301   start = now = gras_os_time();
302
303   gras_dynar_foreach(pd->msg_queue,cpt,msg){
304     if (msg.type->code == msgt_want->code) {
305       *expeditor = msg.expeditor;
306       memcpy(payload, msg.payload, msg.payload_size);
307       gras_free(msg.payload);
308       gras_dynar_cursor_rm(pd->msg_queue, &cpt);
309       VERB0("The waited message was queued");
310       return no_error;
311     }
312   }
313
314   while (1) {
315     TRY(gras_trp_select(timeout - now + start, expeditor));
316     TRY(gras_msg_recv(*expeditor, &msgt_got, &payload_got, &payload_size_got));
317     if (msgt_got->code == msgt_want->code) {
318       memcpy(payload, payload_got, payload_size_got);
319       gras_free(payload_got);
320       VERB0("Got waited message");
321       return no_error;
322     }
323
324     /* not expected msg type. Queue it for later */
325     msg.expeditor = *expeditor;
326     msg.type      =  msgt_got;
327     msg.payload   =  payload;
328     msg.payload_size = payload_size_got;
329     gras_dynar_push(pd->msg_queue,&msg);
330     
331     now=gras_os_time();
332     if (now - start + 0.001 < timeout) {
333       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
334     }
335   }
336
337   RAISE_IMPOSSIBLE;
338 }
339
340 /**
341  * gras_msg_handle:
342  * @timeOut: How long to wait for incoming messages
343  * @Returns: the error code (or no_error).
344  *
345  * Waits up to #timeOut# seconds to see if a message comes in; if so, calls the
346  * registered listener for that message (see RegisterCallback()).
347  */
348 gras_error_t 
349 gras_msg_handle(double timeOut) {
350   
351   gras_error_t    errcode;
352   int             cpt;
353
354   gras_msg_t      msg;
355   gras_socket_t  *expeditor;
356   void           *payload=NULL;
357   int             payload_size;
358   gras_msgtype_t *msgtype;
359
360   gras_procdata_t*pd=gras_procdata_get();
361   gras_cblist_t  *list;
362   gras_cb_t       cb;
363
364
365
366   VERB1("Handling message within the next %.2fs",timeOut);
367   
368   /* get a message (from the queue or from the net) */
369   if (gras_dynar_length(pd->msg_queue)) {
370     gras_dynar_shift(pd->msg_queue,&msg);
371     expeditor = msg.expeditor;
372     msgtype   = msg.type;
373     payload   = msg.payload;
374     
375   } else {
376     TRY(gras_trp_select(timeOut, &expeditor));
377     TRY(gras_msg_recv(expeditor, &msgtype, &payload, &payload_size));
378   }
379       
380   /* handle it */
381   gras_dynar_foreach(pd->cbl_list,cpt,list) {
382     if (list->id == msgtype->code) {
383       break;
384     } else {
385       list=NULL;
386     }
387   }
388   if (!list) {
389     INFO1("No callback for the incomming '%s' message. Discarded.", 
390           msgtype->name);
391     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
392     return no_error;
393   }
394   
395   gras_dynar_foreach(list->cbs,cpt,cb) { 
396     INFO3("Invoque the callback #%d (@%p) for incomming msg %s",
397           cpt+1,cb,msgtype->name);
398     if ((*cb)(expeditor,payload)) {
399       /* cb handled the message */
400       gras_free(payload);
401       return no_error;
402     }
403   }
404
405   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
406   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
407   return mismatch_error;
408 }
409
410 void
411 gras_cbl_free(void *data){
412   gras_cblist_t *list=*(void**)data;
413   if (list) {
414     gras_dynar_free(list->cbs);
415     gras_free(list);
416   }
417 }
418
419 void
420 gras_cb_register(gras_msgtype_t *msgtype,
421                  gras_cb_t cb) {
422   gras_procdata_t *pd=gras_procdata_get();
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   gras_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 = gras_new(gras_cblist_t,1);
439     list->id = msgtype->code;
440     list->cbs = gras_dynar_new(sizeof(gras_cb_t), NULL);
441     gras_dynar_push(pd->cbl_list,&list);
442   }
443
444   /* Insert the new one into the set */
445   gras_dynar_insert_at(list->cbs,0,&cb);
446 }
447
448 void
449 gras_cb_unregister(gras_msgtype_t *msgtype,
450                    gras_cb_t cb) {
451
452   gras_procdata_t *pd=gras_procdata_get();
453   gras_cblist_t *list;
454   gras_cb_t cb_cpt;
455   int cpt;
456   int found = 0;
457
458   /* search the list of cb for this message on this host */
459   gras_dynar_foreach(pd->cbl_list,cpt,list) {
460     if (list->id == msgtype->code) {
461       break;
462     } else {
463       list=NULL;
464     }
465   }
466
467   /* Remove it from the set */
468   if (list) {
469     gras_dynar_foreach(list->cbs,cpt,cb_cpt) {
470       if (cb == cb_cpt) {
471         gras_dynar_cursor_rm(list->cbs, &cpt);
472         found = 1;
473       }
474     }
475   }
476   if (!found)
477     VERB1("Ignoring removal of unexisting callback to msg id %d",
478           msgtype->code);
479 }