3 /* messaging - Function related to messaging (code shared between RL and SG)*/
5 /* Copyright (c) 2003, 2004 Martin Quinson. All rights reserved. */
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. */
11 #include "xbt/ex_interface.h"
12 #include "gras/Msg/msg_private.h"
13 #include "gras/Virtu/virtu_interface.h"
14 #include "gras/DataDesc/datadesc_interface.h"
15 #include "gras/Transport/transport_interface.h" /* gras_select */
16 #include "portable.h" /* execinfo when available to propagate exceptions */
19 #define MIN(a,b) ((a) < (b) ? (a) : (b))
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_msg,gras,"High level messaging");
24 xbt_set_t _gras_msgtype_set = NULL;
25 static char *make_namev(const char *name, short int ver);
27 const char *e_gras_msg_kind_names[e_gras_msg_kind_count]=
28 {"UNKNOWN","ONEWAY","RPC call","RPC answer","RPC error"};
31 * Creating procdata for this module
33 static void *gras_msg_procdata_new() {
34 gras_msg_procdata_t res = xbt_new(s_gras_msg_procdata_t,1);
36 res->name = xbt_strdup("gras_msg");
38 res->msg_queue = xbt_dynar_new(sizeof(s_gras_msg_t), NULL);
39 res->cbl_list = xbt_dynar_new(sizeof(gras_cblist_t *),gras_cbl_free);
40 res->timers = xbt_dynar_new(sizeof(s_gras_timer_t), NULL);
46 * Freeing procdata for this module
48 static void gras_msg_procdata_free(void *data) {
49 gras_msg_procdata_t res = (gras_msg_procdata_t)data;
51 xbt_dynar_free(&( res->msg_queue ));
52 xbt_dynar_free(&( res->cbl_list ));
53 xbt_dynar_free(&( res->timers ));
62 int gras_msg_libdata_id;
63 void gras_msg_register() {
64 gras_msg_libdata_id = gras_procdata_add("gras_msg",gras_msg_procdata_new, gras_msg_procdata_free);
68 * Initialize this submodule.
70 void gras_msg_init(void) {
71 /* only initialize once */
72 if (_gras_msgtype_set != NULL)
75 VERB0("Initializing Msg");
77 _gras_msgtype_set = xbt_set_new();
79 memcpy(_GRAS_header,"GRAS", 4);
80 _GRAS_header[4]=GRAS_PROTOCOL_VERSION;
81 _GRAS_header[5]=(char)GRAS_THISARCH;
85 * Finalize the msg module
90 xbt_set_free(&_gras_msgtype_set);
96 void gras_msgtype_free(void *t) {
97 gras_msgtype_t msgtype=(gras_msgtype_t)t;
107 * Returns the versionned name of the message. If the version is 0, that's
108 * the name unchanged. Pay attention to this before free'ing the result.
110 static char *make_namev(const char *name, short int ver) {
116 namev = (char*)xbt_malloc(strlen(name)+2+3+1);
119 sprintf(namev,"%s_v%d",name,ver);
124 /* Internal function doing the crude work of registering messages */
126 gras_msgtype_declare_ext(const char *name,
128 e_gras_msg_kind_t kind,
129 gras_datadesc_type_t payload_request,
130 gras_datadesc_type_t payload_answer) {
132 gras_msgtype_t msgtype=NULL;
133 char *namev=make_namev(name,version);
134 volatile int found = 0;
138 msgtype = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set,namev);
141 if (e.category != not_found_error)
147 VERB2("Re-register version %d of message '%s' (same kind & payload, ignored).",
149 xbt_assert3(msgtype->kind == kind,
150 "Message %s re-registered as a %s (it was known as a %s)",
151 namev,e_gras_msg_kind_names[kind],e_gras_msg_kind_names[msgtype->kind]);
152 xbt_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload_request),
153 "Message %s re-registred with another payload (%s was %s)",
154 namev,gras_datadesc_get_name(payload_request),
155 gras_datadesc_get_name(msgtype->ctn_type));
157 xbt_assert3(!gras_datadesc_type_cmp(msgtype->answer_type, payload_answer),
158 "Message %s re-registred with another answer payload (%s was %s)",
159 namev,gras_datadesc_get_name(payload_answer),
160 gras_datadesc_get_name(msgtype->answer_type));
162 return ; /* do really ignore it */
166 VERB4("Register version %d of message '%s' "
167 "(payload: %s; answer payload: %s).",
168 version, name, gras_datadesc_get_name(payload_request),
169 gras_datadesc_get_name(payload_answer));
171 msgtype = xbt_new(s_gras_msgtype_t,1);
172 msgtype->name = (namev == name ? strdup(name) : namev);
173 msgtype->name_len = strlen(namev);
174 msgtype->version = version;
175 msgtype->kind = kind;
176 msgtype->ctn_type = payload_request;
177 msgtype->answer_type = payload_answer;
179 xbt_set_add(_gras_msgtype_set, (xbt_set_elm_t)msgtype,
184 /** @brief declare a new message type of the given name. It only accepts the given datadesc as payload
186 * @param name: name as it should be used for logging messages (must be uniq)
187 * @param payload: datadescription of the payload
189 void gras_msgtype_declare(const char *name,
190 gras_datadesc_type_t payload) {
191 gras_msgtype_declare_ext(name, 0, e_gras_msg_kind_oneway, payload, NULL);
196 /** @brief declare a new versionned message type of the given name and payload
198 * @param name: name as it should be used for logging messages (must be uniq)
199 * @param version: something like versionning symbol
200 * @param payload: datadescription of the payload
202 * Registers a message to the GRAS mechanism. Use this version instead of
203 * gras_msgtype_declare when you change the semantic or syntax of a message and
204 * want your programs to be able to deal with both versions. Internally, each
205 * will be handled as an independent message type, so you can register
206 * differents for each of them.
209 gras_msgtype_declare_v(const char *name,
211 gras_datadesc_type_t payload) {
213 gras_msgtype_declare_ext(name, version,
214 e_gras_msg_kind_oneway, payload, NULL);
217 /** @brief retrive an existing message type from its name. */
218 gras_msgtype_t gras_msgtype_by_name (const char *name) {
219 return gras_msgtype_by_namev(name,0);
222 /** @brief retrive an existing message type from its name and version. */
223 gras_msgtype_t gras_msgtype_by_namev(const char *name,
225 gras_msgtype_t res = NULL;
226 char *namev = make_namev(name,version);
230 res = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set, namev);
233 THROW1(not_found_error,0,"No registred message of that name: %s",name);
240 /** @brief retrive an existing message type from its name and version. */
241 gras_msgtype_t gras_msgtype_by_id(int id) {
242 return (gras_msgtype_t)xbt_set_get_by_id(_gras_msgtype_set, id);
245 /** \brief Waits for a message to come in over a given socket.
247 * @param timeout: How long should we wait for this message.
248 * @param msgt_want: type of awaited msg (or NULL if I'm enclined to accept any message)
249 * @param expe_want: awaited expeditot (match on hostname, not port; NULL if not relevant)
250 * @param filter: function returning true or false when passed a payload. Messages for which it returns false are not selected. (NULL if not relevant)
251 * @param filter_ctx: context passed as second argument of the filter (a pattern to match?)
252 * @param[out] msg_got: where to write the message we got
254 * Every message of another type received before the one waited will be queued
255 * and used by subsequent call to this function or gras_msg_handle().
259 gras_msg_wait_ext(double timeout,
261 gras_msgtype_t msgt_want,
262 gras_socket_t expe_want,
263 gras_msg_filter_t filter,
266 gras_msg_t msg_got) {
270 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
273 xbt_assert0(msgt_want,"Cannot wait for the NULL message");
274 xbt_assert0(msg_got,"msg_got is an output parameter");
276 VERB1("Waiting for message '%s'",msgt_want->name);
278 start = now = gras_os_time();
280 xbt_dynar_foreach(pd->msg_queue,cpt,msg){
281 if ( ( !msgt_want || (msg.type->code == msgt_want->code))
282 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
283 gras_socket_peer_name(expe_want))))
284 && (!filter || filter(&msg,filter_ctx))) {
286 memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
287 xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
288 VERB0("The waited message was queued");
294 memset(&msg,sizeof(msg),0);
296 msg.expe = gras_trp_select(timeout ? timeout - now + start : 0);
297 gras_msg_recv(msg.expe, &msg);
298 DEBUG0("Got a message from the socket");
300 if ( ( !msgt_want || (msg.type->code == msgt_want->code))
301 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
302 gras_socket_peer_name(expe_want))))
303 && (!filter || filter(&msg,filter_ctx))) {
305 memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
306 DEBUG0("Message matches expectations. Use it.");
309 DEBUG0("Message does not match expectations. Queue it.");
311 /* not expected msg type. Queue it for later */
312 xbt_dynar_push(pd->msg_queue,&msg);
315 if (now - start + 0.001 > timeout) {
316 THROW1(timeout_error, now-start+0.001-timeout,
317 "Timeout while waiting for msg %s",msgt_want->name);
323 /** \brief Waits for a message to come in over a given socket.
325 * @param timeout: How long should we wait for this message.
326 * @param msgt_want: type of awaited msg
327 * @param[out] expeditor: where to create a socket to answer the incomming message
328 * @param[out] payload: where to write the payload of the incomming message
329 * @return the error code (or no_error).
331 * Every message of another type received before the one waited will be queued
332 * and used by subsequent call to this function or gras_msg_handle().
335 gras_msg_wait(double timeout,
336 gras_msgtype_t msgt_want,
337 gras_socket_t *expeditor,
341 gras_msg_wait_ext(timeout,
342 msgt_want, NULL, NULL, NULL,
346 memcpy(payload,msg.payl,msg.payl_size);
351 *expeditor = msg.expe;
355 /** \brief Send the data pointed by \a payload as a message of type
356 * \a msgtype to the peer \a sock */
358 gras_msg_send(gras_socket_t sock,
359 gras_msgtype_t msgtype,
362 gras_msg_send_ext(sock, e_gras_msg_kind_oneway,0, msgtype, payload);
365 /** @brief Handle all messages arriving within the given period
367 * @param timeOut: How long to wait for incoming messages (in seconds)
368 * @return the error code (or no_error).
370 * Messages are dealed with just like gras_msg_handle() would do. The
371 * difference is that gras_msg_handle() handles at most one message (or wait up
372 * to timeout second when no message arrives) while this function handles any
373 * amount of messages, and lasts the given period in any case.
376 gras_msg_handleall(double period) {
378 double begin=gras_os_time();
384 gras_msg_handle(period - now + begin);
386 if (e.category != timeout_error)
387 RETHROW0("Error while waiting for messages: %s");
390 } while (now - begin < period);
392 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
394 * @param timeOut: How long to wait for incoming messages (in seconds)
395 * @return the error code (or no_error).
397 * Messages are passed to the callbacks. See also gras_msg_handleall().
400 gras_msg_handle(double timeOut) {
408 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
409 gras_cblist_t *list=NULL;
411 s_gras_msg_cb_ctx_t ctx;
413 int timerexpected, timeouted;
416 VERB1("Handling message within the next %.2fs",timeOut);
418 untiltimer = gras_msg_timer_handle();
419 DEBUG1("Next timer in %f sec", untiltimer);
420 if (untiltimer == 0.0) {
421 /* A timer was already elapsed and handled */
424 if (untiltimer != -1.0) {
426 timeOut = MIN(timeOut, untiltimer);
431 /* get a message (from the queue or from the net) */
433 if (xbt_dynar_length(pd->msg_queue)) {
434 DEBUG0("Get a message from the queue");
435 xbt_dynar_shift(pd->msg_queue,&msg);
438 msg.expe = gras_trp_select(timeOut);
440 if (e.category != timeout_error)
448 /* FIXME: if not the right kind, queue it and recall ourself or goto >:-) */
449 gras_msg_recv(msg.expe, &msg);
450 DEBUG1("Received a msg from the socket kind:%s",
451 e_gras_msg_kind_names[msg.kind]);
454 RETHROW4("Error while receiving a message on select()ed socket %p to [%s]%s:%d: %s",
456 gras_socket_peer_proc(msg.expe),gras_socket_peer_name(msg.expe),
457 gras_socket_peer_port(msg.expe));
465 /* A timer elapsed before the arrival of any message even if we select()ed a bit */
466 untiltimer = gras_msg_timer_handle();
467 if (untiltimer == 0.0) {
468 /* we served a timer, we're done */
471 xbt_assert1(untiltimer>0, "Negative timer (%f). I'm 'puzzeled'", untiltimer);
472 WARN1("No timer elapsed, in contrary to expectations (next in %f sec)",
474 THROW1(timeout_error,0,
475 "No timer elapsed, in contrary to expectations (next in %f sec)",
480 /* select timeouted, and no timer elapsed. Nothing to do */
481 THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
487 /* A message was already there or arrived in the meanwhile. handle it */
488 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
489 if (list->id == msg.type->code) {
496 INFO1("No callback for the incomming '%s' message. Discarded.",
498 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
502 ctx.expeditor = msg.expe;
504 ctx.msgtype = msg.type;
507 case e_gras_msg_kind_oneway:
508 case e_gras_msg_kind_rpccall:
511 xbt_dynar_foreach(list->cbs,cpt,cb) {
513 VERB3("Use the callback #%d (@%p) for incomming msg %s",
514 cpt+1,cb,msg.type->name);
515 if ((*cb)(&ctx,msg.payl)) {
516 /* cb handled the message */
524 if (msg.type->kind == e_gras_msg_kind_rpccall) {
525 /* The callback raised an exception, propagate it on the network */
526 if (!e.remote) { /* the exception is born on this machine */
527 e.host = (char*)gras_os_myname();
528 xbt_ex_setup_backtrace(&e);
530 VERB4("Propagate %s exception from '%s' RPC cb back to %s:%d",
531 (e.remote ? "remote" : "local"),
533 gras_socket_peer_name(msg.expe),
534 gras_socket_peer_port(msg.expe));
535 gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
536 msg.ID, msg.type, &e);
540 RETHROW0("Callback raised an exception: %s");
544 THROW1(mismatch_error,0,
545 "Message '%s' refused by all registered callbacks", msg.type->name);
546 /* FIXME: gras_datadesc_free not implemented => leaking the payload */
550 case e_gras_msg_kind_rpcanswer:
551 INFO1("Unexpected RPC answer discarded (type: %s)", msg.type->name);
552 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
555 case e_gras_msg_kind_rpcerror:
556 INFO1("Unexpected RPC error discarded (type: %s)", msg.type->name);
557 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
561 THROW1(unknown_error,0,
562 "Cannot handle messages of kind %d yet",msg.type->kind);
568 gras_cbl_free(void *data){
569 gras_cblist_t *list=*(void**)data;
571 xbt_dynar_free(&( list->cbs ));
576 /** \brief Bind the given callback to the given message type
578 * Several callbacks can be attached to a given message type. The lastly added one will get the message first, and
579 * if it returns false, the message will be passed to the second one.
580 * And so on until one of the callbacks accepts the message.
583 gras_cb_register(gras_msgtype_t msgtype,
585 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
586 gras_cblist_t *list=NULL;
589 DEBUG2("Register %p as callback to '%s'",cb,msgtype->name);
591 /* search the list of cb for this message on this host (creating if NULL) */
592 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
593 if (list->id == msgtype->code) {
600 /* First cb? Create room */
601 list = xbt_new(gras_cblist_t,1);
602 list->id = msgtype->code;
603 list->cbs = xbt_dynar_new(sizeof(gras_msg_cb_t), NULL);
604 xbt_dynar_push(pd->cbl_list,&list);
607 /* Insert the new one into the set */
608 xbt_dynar_insert_at(list->cbs,0,&cb);
611 /** \brief Unbind the given callback from the given message type */
613 gras_cb_unregister(gras_msgtype_t msgtype,
616 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
618 gras_msg_cb_t cb_cpt;
622 /* search the list of cb for this message on this host */
623 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
624 if (list->id == msgtype->code) {
631 /* Remove it from the set */
633 xbt_dynar_foreach(list->cbs,cpt,cb_cpt) {
635 xbt_dynar_cursor_rm(list->cbs, &cpt);
641 VERB1("Ignoring removal of unexisting callback to msg id %d",
645 /** \brief Retrieve the expeditor of the message */
646 gras_socket_t gras_msg_cb_ctx_from(gras_msg_cb_ctx_t ctx) {
647 return ctx->expeditor;