Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Get v0.4 out of the door
[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 #include "DataDesc/datadesc_interface.h"
13 #include "Transport/transport_interface.h" /* gras_trp_chunk_send/recv */
14 #include "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   } else if (errcode == mismatch_error) {
136     INFO3("Register version %d of message '%s' (payload: %s).", 
137            version, name, gras_datadesc_get_name(payload));    
138   } else {
139     return errcode; /* Was expecting for mismatch_error */
140   }
141
142   /* create type anyway so that the old type gets removed from here, and
143      hopefully free'd when ref counter gets 0 */
144   if (! (msgtype = malloc(sizeof(gras_msgtype_t))) ) 
145     RAISE_MALLOC;
146
147   msgtype->name = (namev == name ? strdup(name) : namev);
148   msgtype->name_len = strlen(namev);
149   msgtype->version = version;
150   msgtype->ctn_type = payload;
151   gras_datadesc_addref(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_error_t 
165 gras_msgtype_by_name (const char     *name,
166                       gras_msgtype_t **dst) {
167   return gras_msgtype_by_namev(name,0,dst);
168 }
169 /**
170  * gras_msgtype_by_namev:
171  *
172  * Retrieve a datatype description from its name and version
173  */
174 gras_error_t
175 gras_msgtype_by_namev(const char      *name,
176                       short int        version,
177                       gras_msgtype_t **dst) {
178
179   gras_error_t errcode;
180   char *namev = make_namev(name,version); 
181
182   errcode = gras_set_get_by_name(_gras_msgtype_set, namev,
183                                  (gras_set_elm_t**)dst);
184   if (name != namev) 
185     free(namev);
186
187   return errcode;
188 }
189
190 /**
191  * gras_msg_send:
192  *
193  * Send the given message on the given socket 
194  */
195 gras_error_t
196 gras_msg_send(gras_socket_t  *sock,
197               gras_msgtype_t *msgtype,
198               void           *payload) {
199
200   gras_error_t errcode;
201   static gras_datadesc_type_t *string_type=NULL;
202   if (!string_type) {
203     string_type = gras_datadesc_by_name("string");
204     gras_assert(string_type);
205   }
206
207   DEBUG3("send '%s' to %s:%d", msgtype->name, 
208          gras_socket_peer_name(sock),gras_socket_peer_port(sock));
209   TRY(gras_trp_chunk_send(sock, GRAS_header, 6));
210
211   TRY(gras_datadesc_send(sock, string_type,   &msgtype->name));
212   TRY(gras_datadesc_send(sock, msgtype->ctn_type, payload));
213   TRY(gras_trp_flush(sock));
214
215   return no_error;
216 }
217 /**
218  * gras_msg_recv:
219  *
220  * receive the next message on the given socket.  
221  */
222 gras_error_t
223 gras_msg_recv(gras_socket_t   *sock,
224               gras_msgtype_t **msgtype,
225               void           **payload,
226               int             *payload_size) {
227
228   gras_error_t errcode;
229   static gras_datadesc_type_t *string_type=NULL;
230   char header[6];
231   int cpt;
232   int r_arch;
233   char *msg_name=NULL;
234
235   if (!string_type) {
236     string_type=gras_datadesc_by_name("string");
237     gras_assert(string_type);
238   }
239   
240   TRY(gras_trp_chunk_recv(sock, header, 6));
241   for (cpt=0; cpt<4; cpt++)
242     if (header[cpt] != GRAS_header[cpt])
243       RAISE0(mismatch_error,"Incoming bytes do not look like a GRAS message");
244   if (header[4] != GRAS_header[4]) 
245     RAISE2(mismatch_error,"GRAS protocol mismatch (got %d, use %d)",
246            (int)header[4], (int)GRAS_header[4]);
247   r_arch = (int)header[5];
248   DEBUG2("Handle an incoming message using protocol %d (remote is %s)",
249          (int)header[4],gras_datadesc_arch_name(r_arch));
250
251   TRY(gras_datadesc_recv(sock, string_type, r_arch, &msg_name));
252   errcode = gras_set_get_by_name(_gras_msgtype_set,
253                                  msg_name,(gras_set_elm_t**)msgtype);
254   if (errcode != no_error)
255     RAISE2(errcode,
256            "Got error %s while retrieving the type associated to messages '%s'",
257            gras_error_name(errcode),msg_name);
258   /* FIXME: Survive unknown messages */
259   free(msg_name);
260
261   *payload_size=gras_datadesc_size((*msgtype)->ctn_type);
262   gras_assert2(*payload_size > 0,
263                "%s %s",
264                "Dynamic array as payload is forbided for now (FIXME?).",
265                "Reference to dynamic array is allowed.");
266   *payload = malloc(*payload_size);
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   void *payload_got;
291   int payload_size_got;
292   gras_error_t errcode;
293   double start, now;
294   gras_procdata_t *pd=gras_procdata_get();
295   int cpt;
296   gras_msg_t msg;
297   
298   *expeditor = NULL;
299   payload_got = NULL;
300
301   VERB1("Waiting for message %s",msgt_want->name);
302
303   start = now = gras_os_time();
304
305   gras_dynar_foreach(pd->msg_queue,cpt,msg){
306     if (msg.type->code == msgt_want->code) {
307       *expeditor = msg.expeditor;
308       memcpy(payload, msg.payload, msg.payload_size);
309       free(msg.payload);
310       gras_dynar_cursor_rm(pd->msg_queue, &cpt);
311       VERB0("The waited message was queued");
312       return no_error;
313     }
314   }
315
316   while (1) {
317     TRY(gras_trp_select(timeout - now + start, expeditor));
318     TRY(gras_msg_recv(*expeditor, &msgt_got, &payload_got, &payload_size_got));
319     if (msgt_got->code == msgt_want->code) {
320       memcpy(payload, payload_got, payload_size_got);
321       free(payload_got);
322       VERB0("Got waited message");
323       return no_error;
324     }
325
326     /* not expected msg type. Queue it for later */
327     msg.expeditor = *expeditor;
328     msg.type      =  msgt_got;
329     msg.payload   =  payload;
330     msg.payload_size = payload_size_got;
331     TRY(gras_dynar_push(pd->msg_queue,&msg));
332     
333     now=gras_os_time();
334     if (now - start + 0.001 < timeout) {
335       RAISE1(timeout_error,"Timeout while waiting for msg %s",msgt_want->name);
336     }
337   }
338
339   RAISE_IMPOSSIBLE;
340 }
341
342 /**
343  * gras_msg_handle:
344  * @timeOut: How long to wait for incoming messages
345  * @Returns: the error code (or no_error).
346  *
347  * Waits up to #timeOut# seconds to see if a message comes in; if so, calls the
348  * registered listener for that message (see RegisterCallback()).
349  */
350 gras_error_t 
351 gras_msg_handle(double timeOut) {
352   
353   gras_error_t    errcode;
354   int             cpt;
355
356   gras_msg_t      msg;
357   gras_socket_t  *expeditor;
358   void           *payload=NULL;
359   int             payload_size;
360   gras_msgtype_t *msgtype;
361
362   gras_procdata_t*pd=gras_procdata_get();
363   gras_cblist_t  *list;
364   gras_cb_t       cb;
365
366
367
368   VERB1("Handling message within the next %.2fs",timeOut);
369   
370   /* get a message (from the queue or from the net) */
371   if (gras_dynar_length(pd->msg_queue)) {
372     gras_dynar_shift(pd->msg_queue,&msg);
373     expeditor = msg.expeditor;
374     msgtype   = msg.type;
375     payload   = msg.payload;
376     
377   } else {
378     TRY(gras_trp_select(timeOut, &expeditor));
379     TRY(gras_msg_recv(expeditor, &msgtype, &payload, &payload_size));
380   }
381       
382   /* handle it */
383   gras_dynar_foreach(pd->cbl_list,cpt,list) {
384     if (list->id == msgtype->code) {
385       break;
386     } else {
387       list=NULL;
388     }
389   }
390   if (!list) {
391     INFO1("No callback for the incomming '%s' message. Discarded.", 
392           msgtype->name);
393     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
394     return no_error;
395   }
396   
397   gras_dynar_foreach(list->cbs,cpt,cb) { 
398     INFO3("Invoque the callback #%d (@%p) for incomming msg %s",
399           cpt+1,cb,msgtype->name);
400     if ((*cb)(expeditor,payload)) {
401       /* cb handled the message */
402       free(payload);
403       return no_error;
404     }
405   }
406
407   INFO1("Message '%s' refused by all registered callbacks", msgtype->name);
408   WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
409   return mismatch_error;
410 }
411
412 void
413 gras_cbl_free(void *data){
414   gras_cblist_t *list=*(void**)data;
415   if (list) {
416     gras_dynar_free(list->cbs);
417     free(list);
418   }
419 }
420
421 gras_error_t
422 gras_cb_register(gras_msgtype_t *msgtype,
423                  gras_cb_t cb) {
424   gras_error_t errcode;
425   gras_procdata_t *pd=gras_procdata_get();
426   gras_cblist_t *list=NULL;
427   int cpt;
428
429   DEBUG2("Register %p as callback to %s",cb,msgtype->name);
430
431   /* search the list of cb for this message on this host (creating if NULL) */
432   gras_dynar_foreach(pd->cbl_list,cpt,list) {
433     if (list->id == msgtype->code) {
434       break;
435     } else {
436       list=NULL;
437     }
438   }
439   if (!list) {
440     /* First cb? Create room */
441     list = malloc(sizeof(gras_cblist_t));
442     if (!list)
443       RAISE_MALLOC;
444
445     list->id = msgtype->code;
446     TRY(gras_dynar_new(&(list->cbs), sizeof(gras_cb_t), NULL));
447     TRY(gras_dynar_push(pd->cbl_list,&list));
448   }
449
450   /* Insert the new one into the set */
451   TRY(gras_dynar_insert_at(list->cbs,0,&cb));
452
453   return no_error;
454 }
455
456 void
457 gras_cb_unregister(gras_msgtype_t *msgtype,
458                    gras_cb_t cb) {
459
460   gras_procdata_t *pd=gras_procdata_get();
461   gras_cblist_t *list;
462   gras_cb_t cb_cpt;
463   int cpt;
464   int found = 0;
465
466   /* search the list of cb for this message on this host */
467   gras_dynar_foreach(pd->cbl_list,cpt,list) {
468     if (list->id == msgtype->code) {
469       break;
470     } else {
471       list=NULL;
472     }
473   }
474
475   /* Remove it from the set */
476   if (list) {
477     gras_dynar_foreach(list->cbs,cpt,cb_cpt) {
478       if (cb == cb_cpt) {
479         gras_dynar_cursor_rm(list->cbs, &cpt);
480         found = 1;
481       }
482     }
483   }
484   if (!found)
485     VERB1("Ignoring removal of unexisting callback to msg id %d",
486           msgtype->code);
487 }