Logo AND Algorithmique Numérique Distribuée

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