Logo AND Algorithmique Numérique Distribuée

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