Logo AND Algorithmique Numérique Distribuée

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