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->msg_waitqueue = xbt_dynar_new(sizeof(s_gras_msg_t), NULL);
40 res->cbl_list = xbt_dynar_new(sizeof(gras_cblist_t *),gras_cbl_free);
41 res->timers = xbt_dynar_new(sizeof(s_gras_timer_t), NULL);
42 res->msg_to_receive_queue = xbt_fifo_new();
43 res->msg_to_receive_queue_meas = xbt_fifo_new();
49 * Freeing procdata for this module
51 static void gras_msg_procdata_free(void *data) {
52 gras_msg_procdata_t res = (gras_msg_procdata_t)data;
54 xbt_dynar_free(&( res->msg_queue ));
55 xbt_dynar_free(&( res->msg_waitqueue ));
56 xbt_dynar_free(&( res->cbl_list ));
57 xbt_dynar_free(&( res->timers ));
58 xbt_fifo_free( res->msg_to_receive_queue );
59 xbt_fifo_free( res->msg_to_receive_queue_meas );
68 int gras_msg_libdata_id;
69 void gras_msg_register() {
70 gras_msg_libdata_id = gras_procdata_add("gras_msg",gras_msg_procdata_new, gras_msg_procdata_free);
74 * Initialize this submodule.
76 void gras_msg_init(void) {
77 /* only initialize once */
78 if (_gras_msgtype_set != NULL)
81 VERB0("Initializing Msg");
83 _gras_msgtype_set = xbt_set_new();
85 memcpy(_GRAS_header,"GRAS", 4);
86 _GRAS_header[4]=GRAS_PROTOCOL_VERSION;
87 _GRAS_header[5]=(char)GRAS_THISARCH;
89 gras_msg_ctx_mallocator =
90 xbt_mallocator_new(1000,
91 gras_msg_ctx_mallocator_new_f,
92 gras_msg_ctx_mallocator_free_f,
93 gras_msg_ctx_mallocator_reset_f);
97 * Finalize the msg module
100 gras_msg_exit(void) {
101 VERB0("Exiting Msg");
102 xbt_set_free(&_gras_msgtype_set);
104 xbt_mallocator_free(gras_msg_ctx_mallocator);
110 void gras_msgtype_free(void *t) {
111 gras_msgtype_t msgtype=(gras_msgtype_t)t;
118 * Dump all declared message types (debugging purpose)
120 void gras_msgtype_dumpall(void) {
121 xbt_set_cursor_t cursor;
122 gras_msgtype_t msgtype=NULL;
124 INFO0("Dump of all registered messages:");
125 xbt_set_foreach(_gras_msgtype_set, cursor, msgtype) {
126 INFO6(" Message name: %s (v%d) %s; %s%s%s",
127 msgtype->name, msgtype->version, e_gras_msg_kind_names[msgtype->kind],
128 gras_datadesc_get_name(msgtype->ctn_type),
129 (msgtype->kind==e_gras_msg_kind_rpccall ? " -> ":""),
130 (msgtype->kind==e_gras_msg_kind_rpccall ? gras_datadesc_get_name(msgtype->answer_type) : ""));
138 * Returns the versionned name of the message. If the version is 0, that's
139 * the name unchanged. Pay attention to this before free'ing the result.
141 static char *make_namev(const char *name, short int ver) {
147 namev = (char*)xbt_malloc(strlen(name)+2+3+1);
150 sprintf(namev,"%s_v%d",name,ver);
155 /* Internal function doing the crude work of registering messages */
157 gras_msgtype_declare_ext(const char *name,
159 e_gras_msg_kind_t kind,
160 gras_datadesc_type_t payload_request,
161 gras_datadesc_type_t payload_answer) {
163 gras_msgtype_t msgtype=NULL;
164 char *namev=make_namev(name,version);
165 volatile int found = 0;
169 msgtype = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set,namev);
172 if (e.category != not_found_error)
178 VERB2("Re-register version %d of message '%s' (same kind & payload, ignored).",
180 xbt_assert3(msgtype->kind == kind,
181 "Message %s re-registered as a %s (it was known as a %s)",
182 namev,e_gras_msg_kind_names[kind],e_gras_msg_kind_names[msgtype->kind]);
183 xbt_assert3(!gras_datadesc_type_cmp(msgtype->ctn_type, payload_request),
184 "Message %s re-registred with another payload (%s was %s)",
185 namev,gras_datadesc_get_name(payload_request),
186 gras_datadesc_get_name(msgtype->ctn_type));
188 xbt_assert3(!gras_datadesc_type_cmp(msgtype->answer_type, payload_answer),
189 "Message %s re-registred with another answer payload (%s was %s)",
190 namev,gras_datadesc_get_name(payload_answer),
191 gras_datadesc_get_name(msgtype->answer_type));
193 return ; /* do really ignore it */
197 VERB4("Register version %d of message '%s' "
198 "(payload: %s; answer payload: %s).",
199 version, name, gras_datadesc_get_name(payload_request),
200 gras_datadesc_get_name(payload_answer));
202 msgtype = xbt_new(s_gras_msgtype_t,1);
203 msgtype->name = (namev == name ? strdup(name) : namev);
204 msgtype->name_len = strlen(namev);
205 msgtype->version = version;
206 msgtype->kind = kind;
207 msgtype->ctn_type = payload_request;
208 msgtype->answer_type = payload_answer;
210 xbt_set_add(_gras_msgtype_set, (xbt_set_elm_t)msgtype,
215 /** @brief declare a new message type of the given name. It only accepts the given datadesc as payload
217 * @param name: name as it should be used for logging messages (must be uniq)
218 * @param payload: datadescription of the payload
220 void gras_msgtype_declare(const char *name,
221 gras_datadesc_type_t payload) {
222 gras_msgtype_declare_ext(name, 0, e_gras_msg_kind_oneway, payload, NULL);
227 /** @brief declare a new versionned message type of the given name and payload
229 * @param name: name as it should be used for logging messages (must be uniq)
230 * @param version: something like versionning symbol
231 * @param payload: datadescription of the payload
233 * Registers a message to the GRAS mechanism. Use this version instead of
234 * gras_msgtype_declare when you change the semantic or syntax of a message and
235 * want your programs to be able to deal with both versions. Internally, each
236 * will be handled as an independent message type, so you can register
237 * differents for each of them.
240 gras_msgtype_declare_v(const char *name,
242 gras_datadesc_type_t payload) {
244 gras_msgtype_declare_ext(name, version,
245 e_gras_msg_kind_oneway, payload, NULL);
248 /** @brief retrieve an existing message type from its name (raises an exception if it does not exist). */
249 gras_msgtype_t gras_msgtype_by_name (const char *name) {
250 return gras_msgtype_by_namev(name,0);
252 /** @brief retrieve an existing message type from its name (or NULL if it does not exist). */
253 gras_msgtype_t gras_msgtype_by_name_or_null (const char *name) {
255 gras_msgtype_t res = NULL;
258 res = gras_msgtype_by_namev(name,0);
266 /** @brief retrieve an existing message type from its name and version. */
267 gras_msgtype_t gras_msgtype_by_namev(const char *name,
269 gras_msgtype_t res = NULL;
270 char *namev = make_namev(name,version);
271 volatile int found=0;
275 res = (gras_msgtype_t)xbt_set_get_by_name(_gras_msgtype_set, namev);
281 THROW1(not_found_error,0,"No registred message of that name: %s",name);
288 /** @brief retrieve an existing message type from its name and version. */
289 gras_msgtype_t gras_msgtype_by_id(int id) {
290 return (gras_msgtype_t)xbt_set_get_by_id(_gras_msgtype_set, id);
293 /** \brief Waits for a message to come in over a given socket.
295 * @param timeout: How long should we wait for this message.
296 * @param msgt_want: type of awaited msg (or NULL if I'm enclined to accept any message)
297 * @param expe_want: awaited expeditot (match on hostname, not port; NULL if not relevant)
298 * @param filter: function returning true or false when passed a payload. Messages for which it returns false are not selected. (NULL if not relevant)
299 * @param filter_ctx: context passed as second argument of the filter (a pattern to match?)
300 * @param[out] msg_got: where to write the message we got
302 * Every message of another type received before the one waited will be queued
303 * and used by subsequent call to this function or gras_msg_handle().
307 gras_msg_wait_ext_(double timeout,
309 gras_msgtype_t msgt_want,
310 gras_socket_t expe_want,
311 gras_msg_filter_t filter,
314 gras_msg_t msg_got) {
318 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
321 xbt_assert0(msg_got,"msg_got is an output parameter");
323 start = gras_os_time();
324 VERB1("Waiting for message '%s'",msgt_want?msgt_want->name:"(any)");
326 xbt_dynar_foreach(pd->msg_waitqueue,cpt,msg){
327 if ( ( !msgt_want || (msg.type->code == msgt_want->code))
328 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
329 gras_socket_peer_name(expe_want))))
330 && (!filter || filter(&msg,filter_ctx))) {
332 memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
333 xbt_dynar_cursor_rm(pd->msg_waitqueue, &cpt);
334 VERB0("The waited message was queued");
339 xbt_dynar_foreach(pd->msg_queue,cpt,msg){
340 if ( ( !msgt_want || (msg.type->code == msgt_want->code))
341 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
342 gras_socket_peer_name(expe_want))))
343 && (!filter || filter(&msg,filter_ctx))) {
345 memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
346 xbt_dynar_cursor_rm(pd->msg_queue, &cpt);
347 VERB0("The waited message was queued");
356 restart_receive: /* Goto here when the receive of a message failed */
359 memset(&msg,sizeof(msg),0);
362 msg.expe = gras_trp_select(timeout ? timeout - now + start : 0);
363 gras_msg_recv(msg.expe, &msg);
365 if (e.category == system_error &&
366 !strncmp("Socket closed by remote side",e.msg,
367 strlen("Socket closed by remote side"))) {
375 goto restart_receive;
377 DEBUG0("Got a message from the socket");
379 if ( ( !msgt_want || (msg.type->code == msgt_want->code))
380 && (!expe_want || (!strcmp( gras_socket_peer_name(msg.expe),
381 gras_socket_peer_name(expe_want))))
382 && (!filter || filter(&msg,filter_ctx))) {
384 memcpy(msg_got,&msg,sizeof(s_gras_msg_t));
385 DEBUG0("Message matches expectations. Use it.");
388 DEBUG0("Message does not match expectations. Queue it.");
390 /* not expected msg type. Queue it for later */
391 xbt_dynar_push(pd->msg_queue,&msg);
394 if (now - start + 0.001 > timeout) {
395 THROW1(timeout_error, now-start+0.001-timeout,
396 "Timeout while waiting for msg '%s'",
397 msgt_want?msgt_want->name:"(any)");
403 /** \brief Waits for a message to come in over a given socket.
405 * @param timeout: How long should we wait for this message.
406 * @param msgt_want: type of awaited msg
407 * @param[out] expeditor: where to create a socket to answer the incomming message
408 * @param[out] payload: where to write the payload of the incomming message
409 * @return the error code (or no_error).
411 * Every message of another type received before the one waited will be queued
412 * and used by subsequent call to this function or gras_msg_handle().
415 gras_msg_wait_(double timeout,
416 gras_msgtype_t msgt_want,
417 gras_socket_t *expeditor,
421 gras_msg_wait_ext_(timeout,
422 msgt_want, NULL, NULL, NULL,
425 if (msgt_want->ctn_type) {
427 "Message type '%s' convey a payload you must accept",
430 xbt_assert1(!payload,
431 "No payload was declared for message type '%s'",
436 memcpy(payload,msg.payl,msg.payl_size);
441 *expeditor = msg.expe;
444 static int gras_msg_wait_or_filter(gras_msg_t msg, void *ctx) {
445 xbt_dynar_t dyn=(xbt_dynar_t)ctx;
446 int res = xbt_dynar_member(dyn,msg->type);
448 VERB1("Got matching message (type=%s)",msg->type->name);
450 VERB0("Got message not matching our expectations");
453 /** \brief Waits for a message to come in over a given socket.
455 * @param timeout: How long should we wait for this message.
456 * @param msgt_want: a dynar containing all accepted message type
457 * @param[out] ctx: the context of received message (in case it's a RPC call we want to answer to)
458 * @param[out] msgt_got: indice in the dynar of the type of the received message
459 * @param[out] payload: where to write the payload of the incomming message
460 * @return the error code (or no_error).
462 * Every message of a type not in the accepted list received before the one
463 * waited will be queued and used by subsequent call to this function or
466 * If you are interested in the context, pass the address of a s_gras_msg_cb_ctx_t variable.
468 void gras_msg_wait_or(double timeout,
469 xbt_dynar_t msgt_want,
470 gras_msg_cb_ctx_t *ctx,
475 VERB1("Wait %f seconds for several message types",timeout);
476 gras_msg_wait_ext_(timeout,
478 &gras_msg_wait_or_filter, (void*)msgt_want,
481 if (msg.type->ctn_type) {
483 "Message type '%s' convey a payload you must accept",
485 } /* don't check the other side since some of the types may have a payload */
487 if (payload && msg.type->ctn_type) {
488 memcpy(payload,msg.payl,msg.payl_size);
493 *ctx=gras_msg_cb_ctx_new(msg.expe, msg.type, msg.ID,
494 (msg.kind == e_gras_msg_kind_rpccall), 60);
497 *msgt_got = xbt_dynar_search(msgt_want,msg.type);
501 /** \brief Send the data pointed by \a payload as a message of type
502 * \a msgtype to the peer \a sock */
504 gras_msg_send_(gras_socket_t sock,
505 gras_msgtype_t msgtype,
508 if (msgtype->ctn_type) {
510 "Message type '%s' convey a payload you must provide",
513 xbt_assert1(!payload,
514 "No payload was declared for message type '%s'",
518 DEBUG2("Send a oneway message of type '%s'. Payload=%p",
519 msgtype->name,payload);
520 gras_msg_send_ext(sock, e_gras_msg_kind_oneway,0, msgtype, payload);
521 VERB2("Sent a oneway message of type '%s'. Payload=%p",
522 msgtype->name,payload);
525 /** @brief Handle all messages arriving within the given period
527 * @param period: How long to wait for incoming messages (in seconds)
529 * Messages are dealed with just like gras_msg_handle() would do. The
530 * difference is that gras_msg_handle() handles at most one message (or wait up
531 * to timeout second when no message arrives) while this function handles any
532 * amount of messages, and lasts the given period in any case.
535 gras_msg_handleall(double period) {
537 double begin=gras_os_time();
543 if (period - now + begin > 0)
544 gras_msg_handle(period - now + begin);
546 if (e.category != timeout_error)
547 RETHROW0("Error while waiting for messages: %s");
550 } while (now - begin < period);
553 /** @brief Handle an incomming message or timer (or wait up to \a timeOut seconds)
555 * @param timeOut: How long to wait for incoming messages (in seconds)
556 * @return the error code (or no_error).
558 * Messages are passed to the callbacks. See also gras_msg_handleall().
561 gras_msg_handle(double timeOut) {
570 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
571 gras_cblist_t *list=NULL;
573 s_gras_msg_cb_ctx_t ctx;
575 int timerexpected, timeouted;
578 VERB1("Handling message within the next %.2fs",timeOut);
580 untiltimer = gras_msg_timer_handle();
581 DEBUG1("Next timer in %f sec", untiltimer);
582 if (untiltimer == 0.0) {
583 /* A timer was already elapsed and handled */
586 if (untiltimer != -1.0) {
588 timeOut = MIN(timeOut, untiltimer);
593 /* get a message (from the queue or from the net) */
595 if (xbt_dynar_length(pd->msg_queue)) {
596 DEBUG0("Get a message from the queue");
597 xbt_dynar_shift(pd->msg_queue,&msg);
600 msg.expe = gras_trp_select(timeOut);
602 if (e.category != timeout_error)
610 /* FIXME: if not the right kind, queue it and recall ourself or goto >:-) */
611 gras_msg_recv(msg.expe, &msg);
612 DEBUG1("Received a msg from the socket kind:%s",
613 e_gras_msg_kind_names[msg.kind]);
616 RETHROW4("Error while receiving a message on select()ed socket %p to [%s]%s:%d: %s",
618 gras_socket_peer_proc(msg.expe),gras_socket_peer_name(msg.expe),
619 gras_socket_peer_port(msg.expe));
627 /* A timer elapsed before the arrival of any message even if we select()ed a bit */
628 untiltimer = gras_msg_timer_handle();
629 if (untiltimer == 0.0) {
630 /* we served a timer, we're done */
633 xbt_assert1(untiltimer>0, "Negative timer (%f). I'm 'puzzeled'", untiltimer);
634 WARN1("No timer elapsed, in contrary to expectations (next in %f sec)",
636 THROW1(timeout_error,0,
637 "No timer elapsed, in contrary to expectations (next in %f sec)",
642 /* select timeouted, and no timer elapsed. Nothing to do */
643 THROW1(timeout_error, 0, "No new message or timer (delay was %f)",
649 /* A message was already there or arrived in the meanwhile. handle it */
650 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
651 if (list->id == msg.type->code) {
658 INFO3("No callback for message '%s' from %s:%d. Queue it for later gras_msg_wait() use.",
660 gras_socket_peer_name(msg.expe),gras_socket_peer_port(msg.expe));
661 xbt_dynar_push(pd->msg_waitqueue,&msg);
662 return; /* FIXME: maybe we should call ourselves again until the end of the timer or a proper msg is got */
665 ctx.expeditor = msg.expe;
667 ctx.msgtype = msg.type;
668 ctx.answer_due = (msg.kind == e_gras_msg_kind_rpccall);
671 case e_gras_msg_kind_oneway:
672 case e_gras_msg_kind_rpccall:
675 xbt_dynar_foreach(list->cbs,cpt,cb) {
677 DEBUG4("Use the callback #%d (@%p) for incomming msg %s (payload_size=%d)",
678 cpt+1,cb,msg.type->name,msg.payl_size);
679 if (!(*cb)(&ctx,msg.payl)) {
680 /* cb handled the message */
688 if (msg.type->kind == e_gras_msg_kind_rpccall) {
689 char *old_file=e.file;
690 /* The callback raised an exception, propagate it on the network */
692 /* Make sure we reduce the file name to its basename to avoid issues in tests */
693 char *new_file=strrchr(e.file,'/');
696 /* the exception is born on this machine */
697 e.host = (char*)gras_os_myname();
698 xbt_ex_setup_backtrace(&e);
700 VERB5("Propagate %s exception ('%s') from '%s' RPC cb back to %s:%d",
701 (e.remote ? "remote" : "local"),
704 gras_socket_peer_name(msg.expe),
705 gras_socket_peer_port(msg.expe));
706 gras_msg_send_ext(msg.expe, e_gras_msg_kind_rpcerror,
707 msg.ID, msg.type, &e);
713 RETHROW0("Callback raised an exception: %s");
716 xbt_assert0(!(ctx.answer_due),
717 "RPC callback didn't call gras_msg_rpcreturn");
720 THROW1(mismatch_error,0,
721 "Message '%s' refused by all registered callbacks", msg.type->name);
722 /* FIXME: gras_datadesc_free not implemented => leaking the payload */
726 case e_gras_msg_kind_rpcanswer:
727 INFO1("Unexpected RPC answer discarded (type: %s)", msg.type->name);
728 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
731 case e_gras_msg_kind_rpcerror:
732 INFO1("Unexpected RPC error discarded (type: %s)", msg.type->name);
733 WARN0("FIXME: gras_datadesc_free not implemented => leaking the payload");
737 THROW1(unknown_error,0,
738 "Cannot handle messages of kind %d yet",msg.type->kind);
744 gras_cbl_free(void *data){
745 gras_cblist_t *list=*(void**)data;
747 xbt_dynar_free(&( list->cbs ));
752 /** \brief Bind the given callback to the given message type
754 * Several callbacks can be attached to a given message type. The lastly added one will get the message first, and
755 * if it returns a non-null value, the message will be passed to the second one.
756 * And so on until one of the callbacks accepts the message.
759 gras_cb_register_(gras_msgtype_t msgtype,
761 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
762 gras_cblist_t *list=NULL;
765 DEBUG2("Register %p as callback to '%s'",cb,msgtype->name);
767 /* search the list of cb for this message on this host (creating if NULL) */
768 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
769 if (list->id == msgtype->code) {
776 /* First cb? Create room */
777 list = xbt_new(gras_cblist_t,1);
778 list->id = msgtype->code;
779 list->cbs = xbt_dynar_new(sizeof(gras_msg_cb_t), NULL);
780 xbt_dynar_push(pd->cbl_list,&list);
783 /* Insert the new one into the set */
784 xbt_dynar_insert_at(list->cbs,0,&cb);
787 /** \brief Unbind the given callback from the given message type */
789 gras_cb_unregister_(gras_msgtype_t msgtype,
792 gras_msg_procdata_t pd=(gras_msg_procdata_t)gras_libdata_by_id(gras_msg_libdata_id);
794 gras_msg_cb_t cb_cpt;
798 /* search the list of cb for this message on this host */
799 xbt_dynar_foreach(pd->cbl_list,cpt,list) {
800 if (list->id == msgtype->code) {
807 /* Remove it from the set */
809 xbt_dynar_foreach(list->cbs,cpt,cb_cpt) {
811 xbt_dynar_cursor_rm(list->cbs, &cpt);
817 VERB1("Ignoring removal of unexisting callback to msg id %d",
821 /** \brief Retrieve the expeditor of the message */
822 gras_socket_t gras_msg_cb_ctx_from(gras_msg_cb_ctx_t ctx) {
823 return ctx->expeditor;
825 /* \brief Creates a new message exchange context (user should never have to) */
826 gras_msg_cb_ctx_t gras_msg_cb_ctx_new(gras_socket_t expe,
827 gras_msgtype_t msgtype,
828 unsigned long int ID,
831 gras_msg_cb_ctx_t res=xbt_new(s_gras_msg_cb_ctx_t,1);
832 res->expeditor = expe;
833 res->msgtype = msgtype;
835 res->timeout = timeout;
836 res->answer_due = answer_due;
840 /* \brief Frees a message exchange context
842 * This function is mainly useful with \ref gras_msg_wait_or, ie seldom.
844 void gras_msg_cb_ctx_free(gras_msg_cb_ctx_t ctx) {