Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a bit more debugs
[simgrid.git] / src / gras / Msg / gras_msg_exchange.c
1 /* $Id$ */
2
3 /* gras message exchanges                                                   */
4
5 /* Copyright (c) 2003, 2004, 2005, 2006, 2007 Martin Quinson.               */
6 /* All rights reserved.                                                     */
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 "xbt/ex.h"
12 #include "xbt/ex_interface.h"
13 #include "gras/Msg/msg_private.h"
14 #include "gras/Virtu/virtu_interface.h"
15
16 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(gras_msg);
17
18
19 char _GRAS_header[6];
20 const char *e_gras_msg_kind_names[e_gras_msg_kind_count]=
21   {"UNKNOWN","ONEWAY","RPC call","RPC answer","RPC error"};
22
23
24 /** \brief Waits for a message to come in over a given socket. 
25  *
26  * @param timeout: How long should we wait for this message.
27  * @param msgt_want: type of awaited msg (or NULL if I'm enclined to accept any message)
28  * @param expe_want: awaited expeditot (match on hostname, not port; NULL if not relevant)
29  * @param filter: function returning true or false when passed a payload. Messages for which it returns false are not selected. (NULL if not relevant)
30  * @param filter_ctx: context passed as second argument of the filter (a pattern to match?)
31  * @param[out] msg_got: where to write the message we got
32  *
33  * Every message of another type received before the one waited will be queued
34  * and used by subsequent call to this function or gras_msg_handle().
35  */
36
37 void
38 gras_msg_wait_ext_(double           timeout,    
39
40                   gras_msgtype_t   msgt_want,
41                   gras_socket_t    expe_want,
42                   gras_msg_filter_t filter,
43                   void             *filter_ctx, 
44
45                   gras_msg_t       msg_got) {
46
47   s_gras_msg_t msg;
48   double start, now;
49   gras_msg_procdata_t pd=
50     (gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
51   int cpt;
52
53   xbt_assert0(msg_got,"msg_got is an output parameter");
54
55   start = gras_os_time();
56   VERB1("Waiting for message '%s'",msgt_want?msgt_want->name:"(any)");
57
58   xbt_dynar_foreach(pd->msg_waitqueue,cpt,msg){
59     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
60          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
61                                      gras_socket_peer_name(expe_want))))
62          && (!filter || filter(&msg,filter_ctx))) {
63
64       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
65       xbt_dynar_cursor_rm(pd->msg_waitqueue, &cpt);
66       VERB0("The waited message was queued");
67       return;
68     }
69   }
70
71   xbt_dynar_foreach(pd->msg_queue,cpt,msg){
72     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
73          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
74                                      gras_socket_peer_name(expe_want))))
75          && (!filter || filter(&msg,filter_ctx))) {
76
77       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
78       xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
79       VERB0("The waited message was queued");
80       return;
81     }
82   }
83
84   while (1) {
85     int need_restart;
86     xbt_ex_t e;
87
88   restart_receive: /* Goto here when the receive of a message failed */
89     need_restart=0;
90     now=gras_os_time();
91     memset(&msg,sizeof(msg),0);
92
93     TRY {
94                         xbt_queue_shift_timed(pd->msg_received,&msg,timeout ? timeout - now + start : 0);
95                         /*
96       msg.expe = gras_trp_select(timeout ? timeout - now + start : 0);
97       gras_msg_recv(msg.expe, &msg);
98                         */
99     } CATCH(e) {
100       if (e.category == system_error &&
101           !strncmp("Socket closed by remote side",e.msg,
102                   strlen("Socket closed by remote side"))) {
103         xbt_ex_free(e);
104         need_restart=1;
105       } else {
106         RETHROW;
107       }
108     }
109     if (need_restart)
110       goto restart_receive;
111
112     DEBUG0("Got a message from the socket");
113
114     if ( (   !msgt_want || (msg.type->code == msgt_want->code)) 
115          && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
116                                      gras_socket_peer_name(expe_want))))
117          && (!filter || filter(&msg,filter_ctx))) {
118
119       memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
120       DEBUG0("Message matches expectations. Use it.");
121       return;
122     }
123     DEBUG0("Message does not match expectations. Queue it.");
124
125     /* not expected msg type. Queue it for later */
126     xbt_dynar_push(pd->msg_queue,&msg);
127     
128     now=gras_os_time();
129     if (now - start + 0.001 > timeout) {
130       THROW1(timeout_error,  now-start+0.001-timeout,
131              "Timeout while waiting for msg '%s'",
132              msgt_want?msgt_want->name:"(any)");
133     }
134   }
135
136   THROW_IMPOSSIBLE;
137 }
138 /** \brief Waits for a message to come in over a given socket. 
139  *
140  * @param timeout: How long should we wait for this message.
141  * @param msgt_want: type of awaited msg
142  * @param[out] expeditor: where to create a socket to answer the incomming message
143  * @param[out] payload: where to write the payload of the incomming message
144  * @return the error code (or no_error).
145  *
146  * Every message of another type received before the one waited will be queued
147  * and used by subsequent call to this function or gras_msg_handle().
148  */
149 void
150 gras_msg_wait_(double           timeout,    
151                gras_msgtype_t   msgt_want,
152                gras_socket_t   *expeditor,
153                void            *payload) {
154   s_gras_msg_t msg;
155
156   gras_msg_wait_ext_(timeout,
157                      msgt_want, NULL,      NULL, NULL,
158                      &msg);
159
160   if (msgt_want->ctn_type) {
161     xbt_assert1(payload,
162                 "Message type '%s' convey a payload you must accept",
163                 msgt_want->name);
164   } else {
165     xbt_assert1(!payload,
166                 "No payload was declared for message type '%s'",
167                 msgt_want->name);
168   }
169
170   if (payload) {
171     memcpy(payload,msg.payl,msg.payl_size);
172     free(msg.payl);
173   }
174
175   if (expeditor)
176     *expeditor = msg.expe;
177 }
178
179 static int gras_msg_wait_or_filter(gras_msg_t msg, void *ctx) {
180   xbt_dynar_t dyn=(xbt_dynar_t)ctx;
181   int res =  xbt_dynar_member(dyn,msg->type);
182   if (res)
183     VERB1("Got matching message (type=%s)",msg->type->name);
184   else
185     VERB0("Got message not matching our expectations");
186   return res;
187 }
188 /** \brief Waits for a message to come in over a given socket. 
189  *
190  * @param timeout: How long should we wait for this message.
191  * @param msgt_want: a dynar containing all accepted message type
192  * @param[out] ctx: the context of received message (in case it's a RPC call we want to answer to)
193  * @param[out] msgt_got: indice in the dynar of the type of the received message 
194  * @param[out] payload: where to write the payload of the incomming message
195  * @return the error code (or no_error).
196  *
197  * Every message of a type not in the accepted list received before the one
198  * waited will be queued and used by subsequent call to this function or
199  * gras_msg_handle().
200  *
201  * If you are interested in the context, pass the address of a s_gras_msg_cb_ctx_t variable.
202  */
203 void gras_msg_wait_or(double         timeout,
204                       xbt_dynar_t    msgt_want,
205                       gras_msg_cb_ctx_t *ctx,
206                       int           *msgt_got,
207                       void          *payload) {
208   s_gras_msg_t msg;
209
210   VERB1("Wait %f seconds for several message types",timeout);
211   gras_msg_wait_ext_(timeout,
212                      NULL, NULL,      
213                      &gras_msg_wait_or_filter, (void*)msgt_want,
214                      &msg);
215
216   if (msg.type->ctn_type) {
217     xbt_assert1(payload,
218                 "Message type '%s' convey a payload you must accept",
219                 msg.type->name);
220   } /* don't check the other side since some of the types may have a payload */
221
222   if (payload && msg.type->ctn_type) {
223     memcpy(payload,msg.payl,msg.payl_size);
224     free(msg.payl);
225   }
226
227   if (ctx) 
228     *ctx=gras_msg_cb_ctx_new(msg.expe, msg.type, msg.ID,
229                              (msg.kind == e_gras_msg_kind_rpccall), 60);
230
231   if (msgt_got)
232     *msgt_got = xbt_dynar_search(msgt_want,msg.type);
233 }
234
235
236 /** \brief Send the data pointed by \a payload as a message of type
237  * \a msgtype to the peer \a sock */
238 void
239 gras_msg_send_(gras_socket_t   sock,
240               gras_msgtype_t  msgtype,
241               void           *payload) {
242
243   if (msgtype->ctn_type) {
244     xbt_assert1(payload,
245                 "Message type '%s' convey a payload you must provide",
246                 msgtype->name);
247   } else {
248     xbt_assert1(!payload,
249                 "No payload was declared for message type '%s'",
250                 msgtype->name);
251   }
252
253   DEBUG2("Send a oneway message of type '%s'. Payload=%p",
254          msgtype->name,payload);
255   gras_msg_send_ext(sock, e_gras_msg_kind_oneway,0, msgtype, payload);
256   VERB2("Sent a oneway message of type '%s'. Payload=%p",
257         msgtype->name,payload);
258 }
259
260 /** @brief Handle all messages arriving within the given period
261  *
262  * @param period: How long to wait for incoming messages (in seconds)
263  *
264  * Messages are dealed with just like gras_msg_handle() would do. The
265  * difference is that gras_msg_handle() handles at most one message (or wait up
266  * to timeout second when no message arrives) while this function handles any
267  * amount of messages, and lasts the given period in any case.
268  */
269 void 
270 gras_msg_handleall(double period) {
271   xbt_ex_t e;
272   double begin=gras_os_time();
273   double now;
274
275   do {
276     now=gras_os_time();
277     TRY{
278       if (period - now + begin > 0)
279         gras_msg_handle(period - now + begin);
280     } CATCH(e) {
281       if (e.category != timeout_error) 
282         RETHROW0("Error while waiting for messages: %s");
283       xbt_ex_free(e);
284     }
285   } while (now - begin < period);
286 }
287
288 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
289  *
290  * @param timeOut: How long to wait for incoming messages (in seconds)
291  * @return the error code (or no_error).
292  *
293  * Any message arriving in the given interval is passed to the callbacks.
294  * 
295  * @sa gras_msg_handleall().
296  */
297 void
298 gras_msg_handle(double timeOut) {
299   
300   double          untiltimer;
301    
302   int             cpt;
303   int volatile ran_ok;
304
305   s_gras_msg_t    msg;
306
307   gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
308   gras_cblist_t  *list=NULL;
309   gras_msg_cb_t       cb;
310   s_gras_msg_cb_ctx_t ctx;
311    
312   int timerexpected, timeouted;
313   xbt_ex_t e;
314
315   VERB1("Handling message within the next %.2fs",timeOut);
316   
317   untiltimer = gras_msg_timer_handle();
318   DEBUG1("Next timer in %f sec", untiltimer);
319   if (untiltimer == 0.0) {
320      /* A timer was already elapsed and handled */
321      return;
322   }
323   if (untiltimer != -1.0) {
324      timerexpected = 1;
325      timeOut = MIN(timeOut, untiltimer);
326   } else {
327      timerexpected = 0;
328   }
329    
330   /* get a message (from the queue or from the net) */
331   timeouted = 0;
332   if (xbt_dynar_length(pd->msg_queue)) {
333     DEBUG0("Get a message from the queue");
334     xbt_dynar_shift(pd->msg_queue,&msg);
335   } else {
336     TRY {
337        xbt_queue_shift_timed(pd->msg_received,&msg,timeOut);
338 //      msg.expe = gras_trp_select(timeOut);
339     } CATCH(e) {
340       if (e.category != timeout_error)
341         RETHROW;
342       DEBUG0("Damn. Timeout while getting a message from the queue");
343       xbt_ex_free(e);
344       timeouted = 1;
345     }
346   }
347
348   if (timeouted) {
349      if (timerexpected) {
350           
351         /* A timer elapsed before the arrival of any message even if we select()ed a bit */
352         untiltimer = gras_msg_timer_handle();
353         if (untiltimer == 0.0) {
354           /* we served a timer, we're done */
355           return;
356         } else {
357            xbt_assert1(untiltimer>0, "Negative timer (%f). I'm 'puzzeled'", untiltimer);
358            WARN1("No timer elapsed, in contrary to expectations (next in %f sec)",
359                   untiltimer);
360            THROW1(timeout_error,0,
361                   "No timer elapsed, in contrary to expectations (next in %f sec)",
362                   untiltimer);
363         }
364         
365      } else {
366         /* select timeouted, and no timer elapsed. Nothing to do */
367        THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
368               timeOut);
369      }
370      
371   }
372    
373   /* A message was already there or arrived in the meanwhile. handle it */
374   xbt_dynar_foreach(pd->cbl_list,cpt,list) {
375     if (list->id == msg.type->code) {
376       break;
377     } else {
378       list=NULL;
379     }
380   }
381   if (!list) {
382     INFO3("No callback for message '%s' from %s:%d. Queue it for later gras_msg_wait() use.",
383           msg.type->name,
384           gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
385     xbt_dynar_push(pd->msg_waitqueue,&msg);
386     return; /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
387   }
388   
389   ctx.expeditor = msg.expe;
390   ctx.ID = msg.ID;
391   ctx.msgtype = msg.type;
392   ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
393
394   switch (msg.kind) {
395   case e_gras_msg_kind_oneway:
396   case e_gras_msg_kind_rpccall:
397     ran_ok=0;
398     TRY {
399       xbt_dynar_foreach(list->cbs,cpt,cb) { 
400         if (!ran_ok) {
401           DEBUG4("Use the callback #%d (@%p) for incomming msg %s (payload_size=%d)",
402                 cpt+1,cb,msg.type->name,msg.payl_size);
403           if (!(*cb)(&ctx,msg.payl)) {
404             /* cb handled the message */
405             free(msg.payl);
406             ran_ok = 1;
407           }
408         }
409       }
410     } CATCH(e) {
411       free(msg.payl);
412       if (msg.type->kind == e_gras_msg_kind_rpccall) {
413         char *old_file=e.file;
414         /* The callback raised an exception, propagate it on the network */
415         if (!e.remote) { 
416           /* Make sure we reduce the file name to its basename to avoid issues in tests */
417           char *new_file=strrchr(e.file,'/');
418           if (new_file)
419              e.file = new_file;
420           /* the exception is born on this machine */
421           e.host = (char*)gras_os_myname();
422           xbt_ex_setup_backtrace(&e);
423         } 
424         VERB5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
425               (e.remote ? "remote" : "local"),
426               e.msg,
427               msg.type->name,
428               gras_socket_peer_name(msg.expe),
429               gras_socket_peer_port(msg.expe));
430         gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
431                           msg.ID, msg.type, &e);
432         e.file=old_file;
433         xbt_ex_free(e);
434         ctx.answer_due = 0;
435         ran_ok=1;
436       } else {
437         RETHROW0("Callback raised an exception: %s");
438       }
439     }
440
441     xbt_assert1(! ctx.answer_due,
442                 "Bug in user code: RPC callback to message '%s' didn't call gras_msg_rpcreturn",msg.type->name);
443     if (ctx.answer_due)
444        CRITICAL1("BUGS BOTH IN USER CODE (RPC callback to message '%s' didn't call gras_msg_rpcreturn) "
445                  "AND IN SIMGRID (process wasn't killed by an assert)",msg.type->name);
446     if (!ran_ok)
447       THROW1(mismatch_error,0,
448              "Message '%s' refused by all registered callbacks", msg.type->name);
449     /* FIXME: gras_datadesc_free not implemented => leaking the payload */
450     break;
451
452
453   case e_gras_msg_kind_rpcanswer:
454     INFO1("Unexpected RPC answer discarded (type: %s)", msg.type->name);
455     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
456     return;
457
458   case e_gras_msg_kind_rpcerror:
459     INFO1("Unexpected RPC error discarded (type: %s)", msg.type->name);
460     WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
461     return;
462
463   default:
464     THROW1(unknown_error,0,
465            "Cannot handle messages of kind %d yet",msg.type->kind);
466   }
467
468 }
469