Logo AND Algorithmique Numérique Distribuée

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