2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
44 #include <lttng/lttng.h>
45 #include <common/common.h>
46 #include <common/compat/poll.h>
47 #include <common/compat/socket.h>
48 #include <common/compat/endian.h>
49 #include <common/defaults.h>
50 #include <common/daemonize.h>
51 #include <common/futex.h>
52 #include <common/sessiond-comm/sessiond-comm.h>
53 #include <common/sessiond-comm/inet.h>
54 #include <common/sessiond-comm/relayd.h>
55 #include <common/uri.h>
56 #include <common/utils.h>
57 #include <common/config/config.h>
58 #include <urcu/rculist.h>
61 #include "ctf-trace.h"
64 #include "lttng-relayd.h"
66 #include "health-relayd.h"
67 #include "testpoint.h"
68 #include "viewer-stream.h"
71 #include "connection.h"
72 #include "tracefile-array.h"
74 /* command line options */
75 char *opt_output_path
;
76 static int opt_daemon
, opt_background
;
79 * We need to wait for listener and live listener threads, as well as
80 * health check thread, before being ready to signal readiness.
82 #define NR_LTTNG_RELAY_READY 3
83 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
84 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
85 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
87 static struct lttng_uri
*control_uri
;
88 static struct lttng_uri
*data_uri
;
89 static struct lttng_uri
*live_uri
;
93 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
94 static int tracing_group_name_override
;
96 const char * const config_section_name
= "relayd";
99 * Quit pipe for all threads. This permits a single cancellation point
100 * for all threads when receiving an event on the pipe.
102 int thread_quit_pipe
[2] = { -1, -1 };
105 * This pipe is used to inform the worker thread that a command is queued and
106 * ready to be processed.
108 static int relay_conn_pipe
[2] = { -1, -1 };
110 /* Shared between threads */
111 static int dispatch_thread_exit
;
113 static pthread_t listener_thread
;
114 static pthread_t dispatcher_thread
;
115 static pthread_t worker_thread
;
116 static pthread_t health_thread
;
119 * last_relay_stream_id_lock protects last_relay_stream_id increment
120 * atomicity on 32-bit architectures.
122 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
123 static uint64_t last_relay_stream_id
;
126 * Relay command queue.
128 * The relay_thread_listener and relay_thread_dispatcher communicate with this
131 static struct relay_conn_queue relay_conn_queue
;
133 /* buffer allocated at startup, used to store the trace data */
134 static char *data_buffer
;
135 static unsigned int data_buffer_size
;
137 /* Global relay stream hash table. */
138 struct lttng_ht
*relay_streams_ht
;
140 /* Global relay viewer stream hash table. */
141 struct lttng_ht
*viewer_streams_ht
;
143 /* Global relay sessions hash table. */
144 struct lttng_ht
*sessions_ht
;
146 /* Relayd health monitoring */
147 struct health_app
*health_relayd
;
149 static struct option long_options
[] = {
150 { "control-port", 1, 0, 'C', },
151 { "data-port", 1, 0, 'D', },
152 { "live-port", 1, 0, 'L', },
153 { "daemonize", 0, 0, 'd', },
154 { "background", 0, 0, 'b', },
155 { "group", 1, 0, 'g', },
156 { "help", 0, 0, 'h', },
157 { "output", 1, 0, 'o', },
158 { "verbose", 0, 0, 'v', },
159 { "config", 1, 0, 'f' },
163 static const char *config_ignore_options
[] = { "help", "config" };
166 * usage function on stderr
168 static void usage(void)
170 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
171 fprintf(stderr
, " -h, --help Display this usage.\n");
172 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
173 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
174 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
175 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
176 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
177 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
178 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
179 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
180 fprintf(stderr
, " -f --config Load daemon configuration file\n");
184 * Take an option from the getopt output and set it in the right variable to be
187 * Return 0 on success else a negative value.
189 static int set_option(int opt
, const char *arg
, const char *optname
)
195 fprintf(stderr
, "option %s", optname
);
197 fprintf(stderr
, " with arg %s\n", arg
);
201 ret
= uri_parse(arg
, &control_uri
);
203 ERR("Invalid control URI specified");
206 if (control_uri
->port
== 0) {
207 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
211 ret
= uri_parse(arg
, &data_uri
);
213 ERR("Invalid data URI specified");
216 if (data_uri
->port
== 0) {
217 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
221 ret
= uri_parse(arg
, &live_uri
);
223 ERR("Invalid live URI specified");
226 if (live_uri
->port
== 0) {
227 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
237 tracing_group_name
= strdup(arg
);
238 if (tracing_group_name
== NULL
) {
243 tracing_group_name_override
= 1;
249 ret
= asprintf(&opt_output_path
, "%s", arg
);
252 PERROR("asprintf opt_output_path");
257 /* Verbose level can increase using multiple -v */
259 lttng_opt_verbose
= config_parse_value(arg
);
261 /* Only 3 level of verbosity (-vvv). */
262 if (lttng_opt_verbose
< 3) {
263 lttng_opt_verbose
+= 1;
268 /* Unknown option or other error.
269 * Error is printed by getopt, just return */
282 * config_entry_handler_cb used to handle options read from a config file.
283 * See config_entry_handler_cb comment in common/config/config.h for the
284 * return value conventions.
286 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
290 if (!entry
|| !entry
->name
|| !entry
->value
) {
295 /* Check if the option is to be ignored */
296 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
297 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
302 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
303 /* Ignore if entry name is not fully matched. */
304 if (strcmp(entry
->name
, long_options
[i
].name
)) {
309 * If the option takes no argument on the command line,
310 * we have to check if the value is "true". We support
311 * non-zero numeric values, true, on and yes.
313 if (!long_options
[i
].has_arg
) {
314 ret
= config_parse_value(entry
->value
);
317 WARN("Invalid configuration value \"%s\" for option %s",
318 entry
->value
, entry
->name
);
320 /* False, skip boolean config option. */
325 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
329 WARN("Unrecognized option \"%s\" in daemon configuration file.",
336 static int set_options(int argc
, char **argv
)
338 int c
, ret
= 0, option_index
= 0, retval
= 0;
339 int orig_optopt
= optopt
, orig_optind
= optind
;
340 char *default_address
, *optstring
;
341 const char *config_path
= NULL
;
343 optstring
= utils_generate_optstring(long_options
,
344 sizeof(long_options
) / sizeof(struct option
));
350 /* Check for the --config option */
352 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
353 &option_index
)) != -1) {
357 } else if (c
!= 'f') {
361 config_path
= utils_expand_path(optarg
);
363 ERR("Failed to resolve path: %s", optarg
);
367 ret
= config_get_section_entries(config_path
, config_section_name
,
368 config_entry_handler
, NULL
);
371 ERR("Invalid configuration option at line %i", ret
);
377 /* Reset getopt's global state */
378 optopt
= orig_optopt
;
379 optind
= orig_optind
;
381 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
386 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
393 /* assign default values */
394 if (control_uri
== NULL
) {
395 ret
= asprintf(&default_address
,
396 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
397 DEFAULT_NETWORK_CONTROL_PORT
);
399 PERROR("asprintf default data address");
404 ret
= uri_parse(default_address
, &control_uri
);
405 free(default_address
);
407 ERR("Invalid control URI specified");
412 if (data_uri
== NULL
) {
413 ret
= asprintf(&default_address
,
414 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
415 DEFAULT_NETWORK_DATA_PORT
);
417 PERROR("asprintf default data address");
422 ret
= uri_parse(default_address
, &data_uri
);
423 free(default_address
);
425 ERR("Invalid data URI specified");
430 if (live_uri
== NULL
) {
431 ret
= asprintf(&default_address
,
432 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
433 DEFAULT_NETWORK_VIEWER_PORT
);
435 PERROR("asprintf default viewer control address");
440 ret
= uri_parse(default_address
, &live_uri
);
441 free(default_address
);
443 ERR("Invalid viewer control URI specified");
454 static void print_global_objects(void)
456 rcu_register_thread();
458 print_viewer_streams();
459 print_relay_streams();
462 rcu_unregister_thread();
468 static void relayd_cleanup(void)
470 print_global_objects();
474 if (viewer_streams_ht
)
475 lttng_ht_destroy(viewer_streams_ht
);
476 if (relay_streams_ht
)
477 lttng_ht_destroy(relay_streams_ht
);
479 lttng_ht_destroy(sessions_ht
);
481 /* free the dynamically allocated opt_output_path */
482 free(opt_output_path
);
484 /* Close thread quit pipes */
485 utils_close_pipe(thread_quit_pipe
);
487 uri_free(control_uri
);
489 /* Live URI is freed in the live thread. */
491 if (tracing_group_name_override
) {
492 free((void *) tracing_group_name
);
497 * Write to writable pipe used to notify a thread.
499 static int notify_thread_pipe(int wpipe
)
503 ret
= lttng_write(wpipe
, "!", 1);
505 PERROR("write poll pipe");
513 static int notify_health_quit_pipe(int *pipe
)
517 ret
= lttng_write(pipe
[1], "4", 1);
519 PERROR("write relay health quit");
528 * Stop all relayd and relayd-live threads.
530 int lttng_relay_stop_threads(void)
534 /* Stopping all threads */
535 DBG("Terminating all threads");
536 if (notify_thread_pipe(thread_quit_pipe
[1])) {
537 ERR("write error on thread quit pipe");
541 if (notify_health_quit_pipe(health_quit_pipe
)) {
542 ERR("write error on health quit pipe");
545 /* Dispatch thread */
546 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
547 futex_nto1_wake(&relay_conn_queue
.futex
);
549 if (relayd_live_stop()) {
550 ERR("Error stopping live threads");
557 * Signal handler for the daemon
559 * Simply stop all worker threads, leaving main() return gracefully after
560 * joining all threads and calling cleanup().
562 static void sighandler(int sig
)
566 DBG("SIGPIPE caught");
569 DBG("SIGINT caught");
570 if (lttng_relay_stop_threads()) {
571 ERR("Error stopping threads");
575 DBG("SIGTERM caught");
576 if (lttng_relay_stop_threads()) {
577 ERR("Error stopping threads");
581 CMM_STORE_SHARED(recv_child_signal
, 1);
589 * Setup signal handler for :
590 * SIGINT, SIGTERM, SIGPIPE
592 static int set_signal_handler(void)
598 if ((ret
= sigemptyset(&sigset
)) < 0) {
599 PERROR("sigemptyset");
603 sa
.sa_handler
= sighandler
;
606 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
611 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
616 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
621 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
626 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
631 void lttng_relay_notify_ready(void)
633 /* Notify the parent of the fork() process that we are ready. */
634 if (opt_daemon
|| opt_background
) {
635 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
636 kill(child_ppid
, SIGUSR1
);
642 * Init thread quit pipe.
644 * Return -1 on error or 0 if all pipes are created.
646 static int init_thread_quit_pipe(void)
650 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
656 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
658 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
662 if (events
== NULL
|| size
== 0) {
667 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
673 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
685 * Check if the thread quit pipe was triggered.
687 * Return 1 if it was triggered else 0;
689 static int check_thread_quit_pipe(int fd
, uint32_t events
)
691 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
699 * Create and init socket from uri.
701 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
704 struct lttcomm_sock
*sock
= NULL
;
706 sock
= lttcomm_alloc_sock_from_uri(uri
);
708 ERR("Allocating socket");
712 ret
= lttcomm_create_sock(sock
);
716 DBG("Listening on sock %d", sock
->fd
);
718 ret
= sock
->ops
->bind(sock
);
723 ret
= sock
->ops
->listen(sock
, -1);
733 lttcomm_destroy_sock(sock
);
739 * This thread manages the listening for new connections on the network
741 static void *relay_thread_listener(void *data
)
743 int i
, ret
, pollfd
, err
= -1;
744 uint32_t revents
, nb_fd
;
745 struct lttng_poll_event events
;
746 struct lttcomm_sock
*control_sock
, *data_sock
;
748 DBG("[thread] Relay listener started");
750 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
752 health_code_update();
754 control_sock
= relay_socket_create(control_uri
);
756 goto error_sock_control
;
759 data_sock
= relay_socket_create(data_uri
);
761 goto error_sock_relay
;
765 * Pass 3 as size here for the thread quit pipe, control and
768 ret
= create_thread_poll_set(&events
, 3);
770 goto error_create_poll
;
773 /* Add the control socket */
774 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
779 /* Add the data socket */
780 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
785 lttng_relay_notify_ready();
787 if (testpoint(relayd_thread_listener
)) {
788 goto error_testpoint
;
792 health_code_update();
794 DBG("Listener accepting connections");
798 ret
= lttng_poll_wait(&events
, -1);
802 * Restart interrupted system call.
804 if (errno
== EINTR
) {
812 DBG("Relay new connection received");
813 for (i
= 0; i
< nb_fd
; i
++) {
814 health_code_update();
816 /* Fetch once the poll data */
817 revents
= LTTNG_POLL_GETEV(&events
, i
);
818 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
822 * No activity for this FD (poll
828 /* Thread quit pipe has been closed. Killing thread. */
829 ret
= check_thread_quit_pipe(pollfd
, revents
);
835 if (revents
& LPOLLIN
) {
837 * A new connection is requested, therefore a
838 * sessiond/consumerd connection is allocated in
839 * this thread, enqueued to a global queue and
840 * dequeued (and freed) in the worker thread.
843 struct relay_connection
*new_conn
;
844 struct lttcomm_sock
*newsock
;
845 enum connection_type type
;
847 if (pollfd
== data_sock
->fd
) {
849 newsock
= data_sock
->ops
->accept(data_sock
);
850 DBG("Relay data connection accepted, socket %d",
853 assert(pollfd
== control_sock
->fd
);
854 type
= RELAY_CONTROL
;
855 newsock
= control_sock
->ops
->accept(control_sock
);
856 DBG("Relay control connection accepted, socket %d",
860 PERROR("accepting sock");
864 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
867 PERROR("setsockopt inet");
868 lttcomm_destroy_sock(newsock
);
871 new_conn
= connection_create(newsock
, type
);
873 lttcomm_destroy_sock(newsock
);
877 /* Enqueue request for the dispatcher thread. */
878 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
882 * Wake the dispatch queue futex.
883 * Implicit memory barrier with the
884 * exchange in cds_wfcq_enqueue.
886 futex_nto1_wake(&relay_conn_queue
.futex
);
887 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
888 ERR("socket poll error");
891 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
901 lttng_poll_clean(&events
);
903 if (data_sock
->fd
>= 0) {
904 ret
= data_sock
->ops
->close(data_sock
);
909 lttcomm_destroy_sock(data_sock
);
911 if (control_sock
->fd
>= 0) {
912 ret
= control_sock
->ops
->close(control_sock
);
917 lttcomm_destroy_sock(control_sock
);
921 ERR("Health error occurred in %s", __func__
);
923 health_unregister(health_relayd
);
924 DBG("Relay listener thread cleanup complete");
925 lttng_relay_stop_threads();
930 * This thread manages the dispatching of the requests to worker threads
932 static void *relay_thread_dispatcher(void *data
)
936 struct cds_wfcq_node
*node
;
937 struct relay_connection
*new_conn
= NULL
;
939 DBG("[thread] Relay dispatcher started");
941 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
943 if (testpoint(relayd_thread_dispatcher
)) {
944 goto error_testpoint
;
947 health_code_update();
949 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
950 health_code_update();
952 /* Atomically prepare the queue futex */
953 futex_nto1_prepare(&relay_conn_queue
.futex
);
956 health_code_update();
958 /* Dequeue commands */
959 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
960 &relay_conn_queue
.tail
);
962 DBG("Woken up but nothing in the relay command queue");
963 /* Continue thread execution */
966 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
968 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
971 * Inform worker thread of the new request. This
972 * call is blocking so we can be assured that
973 * the data will be read at some point in time
974 * or wait to the end of the world :)
976 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
978 PERROR("write connection pipe");
979 connection_put(new_conn
);
982 } while (node
!= NULL
);
984 /* Futex wait on queue. Blocking call on futex() */
986 futex_nto1_wait(&relay_conn_queue
.futex
);
990 /* Normal exit, no error */
997 ERR("Health error occurred in %s", __func__
);
999 health_unregister(health_relayd
);
1000 DBG("Dispatch thread dying");
1001 lttng_relay_stop_threads();
1006 * Set index data from the control port to a given index object.
1008 static int set_index_control_data(struct relay_index
*index
,
1009 struct lttcomm_relayd_index
*data
)
1011 struct ctf_packet_index index_data
;
1014 * The index on disk is encoded in big endian, so we don't need
1015 * to convert the data received on the network. The data_offset
1016 * value is NEVER modified here and is updated by the data
1019 index_data
.packet_size
= data
->packet_size
;
1020 index_data
.content_size
= data
->content_size
;
1021 index_data
.timestamp_begin
= data
->timestamp_begin
;
1022 index_data
.timestamp_end
= data
->timestamp_end
;
1023 index_data
.events_discarded
= data
->events_discarded
;
1024 index_data
.stream_id
= data
->stream_id
;
1025 return relay_index_set_data(index
, &index_data
);
1029 * Handle the RELAYD_CREATE_SESSION command.
1031 * On success, send back the session id or else return a negative value.
1033 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1034 struct relay_connection
*conn
)
1036 int ret
= 0, send_ret
;
1037 struct relay_session
*session
;
1038 struct lttcomm_relayd_status_session reply
;
1039 char session_name
[NAME_MAX
];
1040 char hostname
[HOST_NAME_MAX
];
1041 uint32_t live_timer
= 0;
1042 bool snapshot
= false;
1044 memset(session_name
, 0, NAME_MAX
);
1045 memset(hostname
, 0, HOST_NAME_MAX
);
1047 memset(&reply
, 0, sizeof(reply
));
1049 switch (conn
->minor
) {
1054 case 4: /* LTTng sessiond 2.4 */
1056 ret
= cmd_create_session_2_4(conn
, session_name
,
1057 hostname
, &live_timer
, &snapshot
);
1063 session
= session_create(session_name
, hostname
, live_timer
,
1064 snapshot
, conn
->major
, conn
->minor
);
1069 assert(!conn
->session
);
1070 conn
->session
= session
;
1071 DBG("Created session %" PRIu64
, session
->id
);
1073 reply
.session_id
= htobe64(session
->id
);
1077 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1079 reply
.ret_code
= htobe32(LTTNG_OK
);
1082 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1084 ERR("Relayd sending session id");
1092 * When we have received all the streams and the metadata for a channel,
1093 * we make them visible to the viewer threads.
1095 static void publish_connection_local_streams(struct relay_connection
*conn
)
1097 struct relay_stream
*stream
;
1098 struct relay_session
*session
= conn
->session
;
1101 * We publish all streams belonging to a session atomically wrt
1104 pthread_mutex_lock(&session
->lock
);
1106 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1108 stream_publish(stream
);
1113 * Inform the viewer that there are new streams in the session.
1115 if (session
->viewer_attached
) {
1116 uatomic_set(&session
->new_streams
, 1);
1118 pthread_mutex_unlock(&session
->lock
);
1122 * relay_add_stream: allocate a new stream for a session
1124 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1125 struct relay_connection
*conn
)
1129 struct relay_session
*session
= conn
->session
;
1130 struct relay_stream
*stream
= NULL
;
1131 struct lttcomm_relayd_status_stream reply
;
1132 struct ctf_trace
*trace
= NULL
;
1133 uint64_t stream_handle
= -1ULL;
1134 char *path_name
= NULL
, *channel_name
= NULL
;
1135 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1137 if (!session
|| conn
->version_check_done
== 0) {
1138 ERR("Trying to add a stream before version check");
1140 goto end_no_session
;
1143 switch (session
->minor
) {
1144 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1145 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1148 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1150 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1151 &channel_name
, &tracefile_size
, &tracefile_count
);
1158 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1162 /* This stream here has one reference on the trace. */
1164 pthread_mutex_lock(&last_relay_stream_id_lock
);
1165 stream_handle
= ++last_relay_stream_id
;
1166 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1168 /* We pass ownership of path_name and channel_name. */
1169 stream
= stream_create(trace
, stream_handle
, path_name
,
1170 channel_name
, tracefile_size
, tracefile_count
);
1172 channel_name
= NULL
;
1175 * Streams are the owners of their trace. Reference to trace is
1176 * kept within stream_create().
1178 ctf_trace_put(trace
);
1181 memset(&reply
, 0, sizeof(reply
));
1182 reply
.handle
= htobe64(stream_handle
);
1184 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1186 reply
.ret_code
= htobe32(LTTNG_OK
);
1189 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1190 sizeof(struct lttcomm_relayd_status_stream
), 0);
1192 ERR("Relay sending stream id");
1193 ret
= (int) send_ret
;
1203 * relay_close_stream: close a specific stream
1205 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1206 struct relay_connection
*conn
)
1209 struct relay_session
*session
= conn
->session
;
1210 struct lttcomm_relayd_close_stream stream_info
;
1211 struct lttcomm_relayd_generic_reply reply
;
1212 struct relay_stream
*stream
;
1214 DBG("Close stream received");
1216 if (!session
|| conn
->version_check_done
== 0) {
1217 ERR("Trying to close a stream before version check");
1219 goto end_no_session
;
1222 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1223 sizeof(struct lttcomm_relayd_close_stream
), 0);
1224 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1226 /* Orderly shutdown. Not necessary to print an error. */
1227 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1229 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1232 goto end_no_session
;
1235 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1242 * Set last_net_seq_num before the close flag. Required by data
1245 pthread_mutex_lock(&stream
->lock
);
1246 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1247 pthread_mutex_unlock(&stream
->lock
);
1250 * This is one of the conditions which may trigger a stream close
1251 * with the others being:
1252 * 1) A close command is received for a stream
1253 * 2) The control connection owning the stream is closed
1254 * 3) We have received all of the stream's data _after_ a close
1257 try_stream_close(stream
);
1258 if (stream
->is_metadata
) {
1259 struct relay_viewer_stream
*vstream
;
1261 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1263 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1265 * Since all the metadata has been sent to the
1266 * viewer and that we have a request to close
1267 * its stream, we can safely teardown the
1268 * corresponding metadata viewer stream.
1270 viewer_stream_put(vstream
);
1272 /* Put local reference. */
1273 viewer_stream_put(vstream
);
1279 memset(&reply
, 0, sizeof(reply
));
1281 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1283 reply
.ret_code
= htobe32(LTTNG_OK
);
1285 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1286 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1288 ERR("Relay sending stream id");
1297 * relay_unknown_command: send -1 if received unknown command
1299 static void relay_unknown_command(struct relay_connection
*conn
)
1301 struct lttcomm_relayd_generic_reply reply
;
1304 memset(&reply
, 0, sizeof(reply
));
1305 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1306 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1307 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1309 ERR("Relay sending unknown command");
1314 * relay_start: send an acknowledgment to the client to tell if we are
1315 * ready to receive data. We are ready if a session is established.
1317 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1318 struct relay_connection
*conn
)
1320 int ret
= htobe32(LTTNG_OK
);
1321 struct lttcomm_relayd_generic_reply reply
;
1322 struct relay_session
*session
= conn
->session
;
1325 DBG("Trying to start the streaming without a session established");
1326 ret
= htobe32(LTTNG_ERR_UNK
);
1329 memset(&reply
, 0, sizeof(reply
));
1330 reply
.ret_code
= ret
;
1331 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1332 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1334 ERR("Relay sending start ack");
1341 * Append padding to the file pointed by the file descriptor fd.
1343 static int write_padding_to_file(int fd
, uint32_t size
)
1352 zeros
= zmalloc(size
);
1353 if (zeros
== NULL
) {
1354 PERROR("zmalloc zeros for padding");
1359 ret
= lttng_write(fd
, zeros
, size
);
1361 PERROR("write padding to file");
1371 * relay_recv_metadata: receive the metadata for the session.
1373 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1374 struct relay_connection
*conn
)
1378 struct relay_session
*session
= conn
->session
;
1379 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1380 struct relay_stream
*metadata_stream
;
1381 uint64_t data_size
, payload_size
;
1384 ERR("Metadata sent before version check");
1389 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1390 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1391 ERR("Incorrect data size");
1395 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1397 if (data_buffer_size
< data_size
) {
1398 /* In case the realloc fails, we can free the memory */
1401 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1402 if (!tmp_data_ptr
) {
1403 ERR("Allocating data buffer");
1408 data_buffer
= tmp_data_ptr
;
1409 data_buffer_size
= data_size
;
1411 memset(data_buffer
, 0, data_size
);
1412 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1413 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1414 if (size_ret
< 0 || size_ret
!= data_size
) {
1415 if (size_ret
== 0) {
1416 /* Orderly shutdown. Not necessary to print an error. */
1417 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1419 ERR("Relay didn't receive the whole metadata");
1424 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1426 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1427 if (!metadata_stream
) {
1432 pthread_mutex_lock(&metadata_stream
->lock
);
1434 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1436 if (size_ret
< payload_size
) {
1437 ERR("Relay error writing metadata on file");
1442 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1443 be32toh(metadata_struct
->padding_size
));
1448 metadata_stream
->metadata_received
+=
1449 payload_size
+ be32toh(metadata_struct
->padding_size
);
1450 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1451 metadata_stream
->metadata_received
);
1454 pthread_mutex_unlock(&metadata_stream
->lock
);
1455 stream_put(metadata_stream
);
1461 * relay_send_version: send relayd version number
1463 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1464 struct relay_connection
*conn
)
1467 struct lttcomm_relayd_version reply
, msg
;
1469 conn
->version_check_done
= 1;
1471 /* Get version from the other side. */
1472 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1473 if (ret
< 0 || ret
!= sizeof(msg
)) {
1475 /* Orderly shutdown. Not necessary to print an error. */
1476 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1478 ERR("Relay failed to receive the version values.");
1484 memset(&reply
, 0, sizeof(reply
));
1485 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1486 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1488 /* Major versions must be the same */
1489 if (reply
.major
!= be32toh(msg
.major
)) {
1490 DBG("Incompatible major versions (%u vs %u), deleting session",
1491 reply
.major
, be32toh(msg
.major
));
1492 connection_put(conn
);
1497 conn
->major
= reply
.major
;
1498 /* We adapt to the lowest compatible version */
1499 if (reply
.minor
<= be32toh(msg
.minor
)) {
1500 conn
->minor
= reply
.minor
;
1502 conn
->minor
= be32toh(msg
.minor
);
1505 reply
.major
= htobe32(reply
.major
);
1506 reply
.minor
= htobe32(reply
.minor
);
1507 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1508 sizeof(struct lttcomm_relayd_version
), 0);
1510 ERR("Relay sending version");
1513 DBG("Version check done using protocol %u.%u", conn
->major
,
1521 * Check for data pending for a given stream id from the session daemon.
1523 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1524 struct relay_connection
*conn
)
1526 struct relay_session
*session
= conn
->session
;
1527 struct lttcomm_relayd_data_pending msg
;
1528 struct lttcomm_relayd_generic_reply reply
;
1529 struct relay_stream
*stream
;
1531 uint64_t last_net_seq_num
, stream_id
;
1533 DBG("Data pending command received");
1535 if (!session
|| conn
->version_check_done
== 0) {
1536 ERR("Trying to check for data before version check");
1538 goto end_no_session
;
1541 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1542 if (ret
< sizeof(msg
)) {
1544 /* Orderly shutdown. Not necessary to print an error. */
1545 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1547 ERR("Relay didn't receive valid data_pending struct size : %d",
1551 goto end_no_session
;
1554 stream_id
= be64toh(msg
.stream_id
);
1555 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1557 stream
= stream_get_by_id(stream_id
);
1558 if (stream
== NULL
) {
1563 pthread_mutex_lock(&stream
->lock
);
1565 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1566 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1569 /* Avoid wrapping issue */
1570 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1571 /* Data has in fact been written and is NOT pending */
1574 /* Data still being streamed thus pending */
1578 stream
->data_pending_check_done
= true;
1579 pthread_mutex_unlock(&stream
->lock
);
1584 memset(&reply
, 0, sizeof(reply
));
1585 reply
.ret_code
= htobe32(ret
);
1586 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1588 ERR("Relay data pending ret code failed");
1596 * Wait for the control socket to reach a quiescent state.
1598 * Note that for now, when receiving this command from the session
1599 * daemon, this means that every subsequent commands or data received on
1600 * the control socket has been handled. So, this is why we simply return
1603 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1604 struct relay_connection
*conn
)
1608 struct relay_stream
*stream
;
1609 struct lttcomm_relayd_quiescent_control msg
;
1610 struct lttcomm_relayd_generic_reply reply
;
1612 DBG("Checking quiescent state on control socket");
1614 if (!conn
->session
|| conn
->version_check_done
== 0) {
1615 ERR("Trying to check for data before version check");
1617 goto end_no_session
;
1620 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1621 if (ret
< sizeof(msg
)) {
1623 /* Orderly shutdown. Not necessary to print an error. */
1624 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1626 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1630 goto end_no_session
;
1633 stream_id
= be64toh(msg
.stream_id
);
1634 stream
= stream_get_by_id(stream_id
);
1638 pthread_mutex_lock(&stream
->lock
);
1639 stream
->data_pending_check_done
= true;
1640 pthread_mutex_unlock(&stream
->lock
);
1641 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1644 memset(&reply
, 0, sizeof(reply
));
1645 reply
.ret_code
= htobe32(LTTNG_OK
);
1646 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1648 ERR("Relay data quiescent control ret code failed");
1656 * Initialize a data pending command. This means that a consumer is about
1657 * to ask for data pending for each stream it holds. Simply iterate over
1658 * all streams of a session and set the data_pending_check_done flag.
1660 * This command returns to the client a LTTNG_OK code.
1662 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1663 struct relay_connection
*conn
)
1666 struct lttng_ht_iter iter
;
1667 struct lttcomm_relayd_begin_data_pending msg
;
1668 struct lttcomm_relayd_generic_reply reply
;
1669 struct relay_stream
*stream
;
1670 uint64_t session_id
;
1675 DBG("Init streams for data pending");
1677 if (!conn
->session
|| conn
->version_check_done
== 0) {
1678 ERR("Trying to check for data before version check");
1680 goto end_no_session
;
1683 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1684 if (ret
< sizeof(msg
)) {
1686 /* Orderly shutdown. Not necessary to print an error. */
1687 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1689 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1693 goto end_no_session
;
1696 session_id
= be64toh(msg
.session_id
);
1699 * Iterate over all streams to set the begin data pending flag.
1700 * For now, the streams are indexed by stream handle so we have
1701 * to iterate over all streams to find the one associated with
1702 * the right session_id.
1705 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1707 if (!stream_get(stream
)) {
1710 if (stream
->trace
->session
->id
== session_id
) {
1711 pthread_mutex_lock(&stream
->lock
);
1712 stream
->data_pending_check_done
= false;
1713 pthread_mutex_unlock(&stream
->lock
);
1714 DBG("Set begin data pending flag to stream %" PRIu64
,
1715 stream
->stream_handle
);
1721 memset(&reply
, 0, sizeof(reply
));
1722 /* All good, send back reply. */
1723 reply
.ret_code
= htobe32(LTTNG_OK
);
1725 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1727 ERR("Relay begin data pending send reply failed");
1735 * End data pending command. This will check, for a given session id, if
1736 * each stream associated with it has its data_pending_check_done flag
1737 * set. If not, this means that the client lost track of the stream but
1738 * the data is still being streamed on our side. In this case, we inform
1739 * the client that data is in flight.
1741 * Return to the client if there is data in flight or not with a ret_code.
1743 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1744 struct relay_connection
*conn
)
1747 struct lttng_ht_iter iter
;
1748 struct lttcomm_relayd_end_data_pending msg
;
1749 struct lttcomm_relayd_generic_reply reply
;
1750 struct relay_stream
*stream
;
1751 uint64_t session_id
;
1752 uint32_t is_data_inflight
= 0;
1754 DBG("End data pending command");
1756 if (!conn
->session
|| conn
->version_check_done
== 0) {
1757 ERR("Trying to check for data before version check");
1759 goto end_no_session
;
1762 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1763 if (ret
< sizeof(msg
)) {
1765 /* Orderly shutdown. Not necessary to print an error. */
1766 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1768 ERR("Relay didn't receive valid end data_pending struct size: %d",
1772 goto end_no_session
;
1775 session_id
= be64toh(msg
.session_id
);
1778 * Iterate over all streams to see if the begin data pending
1782 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1784 if (!stream_get(stream
)) {
1787 if (stream
->trace
->session
->id
!= session_id
) {
1791 pthread_mutex_lock(&stream
->lock
);
1792 if (!stream
->data_pending_check_done
) {
1793 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1794 is_data_inflight
= 1;
1795 DBG("Data is still in flight for stream %" PRIu64
,
1796 stream
->stream_handle
);
1797 pthread_mutex_unlock(&stream
->lock
);
1802 pthread_mutex_unlock(&stream
->lock
);
1807 memset(&reply
, 0, sizeof(reply
));
1808 /* All good, send back reply. */
1809 reply
.ret_code
= htobe32(is_data_inflight
);
1811 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1813 ERR("Relay end data pending send reply failed");
1821 * Receive an index for a specific stream.
1823 * Return 0 on success else a negative value.
1825 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1826 struct relay_connection
*conn
)
1829 struct relay_session
*session
= conn
->session
;
1830 struct lttcomm_relayd_index index_info
;
1831 struct relay_index
*index
;
1832 struct lttcomm_relayd_generic_reply reply
;
1833 struct relay_stream
*stream
;
1834 uint64_t net_seq_num
;
1838 DBG("Relay receiving index");
1840 if (!session
|| conn
->version_check_done
== 0) {
1841 ERR("Trying to close a stream before version check");
1843 goto end_no_session
;
1846 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1847 sizeof(index_info
), 0);
1848 if (ret
< sizeof(index_info
)) {
1850 /* Orderly shutdown. Not necessary to print an error. */
1851 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1853 ERR("Relay didn't receive valid index struct size : %d", ret
);
1856 goto end_no_session
;
1859 net_seq_num
= be64toh(index_info
.net_seq_num
);
1861 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1863 ERR("stream_get_by_id not found");
1867 pthread_mutex_lock(&stream
->lock
);
1869 /* Live beacon handling */
1870 if (index_info
.packet_size
== 0) {
1871 DBG("Received live beacon for stream %" PRIu64
,
1872 stream
->stream_handle
);
1875 * Only flag a stream inactive when it has already
1876 * received data and no indexes are in flight.
1878 if (stream
->index_received_seqcount
> 0
1879 && stream
->indexes_in_flight
== 0) {
1880 stream
->beacon_ts_end
=
1881 be64toh(index_info
.timestamp_end
);
1884 goto end_stream_put
;
1886 stream
->beacon_ts_end
= -1ULL;
1889 if (stream
->ctf_stream_id
== -1ULL) {
1890 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1892 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1895 ERR("relay_index_get_by_id_or_create index NULL");
1896 goto end_stream_put
;
1898 if (set_index_control_data(index
, &index_info
)) {
1899 ERR("set_index_control_data error");
1900 relay_index_put(index
);
1902 goto end_stream_put
;
1904 ret
= relay_index_try_flush(index
);
1906 tracefile_array_commit_seq(stream
->tfa
);
1907 stream
->index_received_seqcount
++;
1908 } else if (ret
> 0) {
1912 ERR("relay_index_try_flush error %d", ret
);
1913 relay_index_put(index
);
1918 pthread_mutex_unlock(&stream
->lock
);
1923 memset(&reply
, 0, sizeof(reply
));
1925 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1927 reply
.ret_code
= htobe32(LTTNG_OK
);
1929 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1931 ERR("Relay sending close index id reply");
1940 * Receive the streams_sent message.
1942 * Return 0 on success else a negative value.
1944 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1945 struct relay_connection
*conn
)
1948 struct lttcomm_relayd_generic_reply reply
;
1952 DBG("Relay receiving streams_sent");
1954 if (!conn
->session
|| conn
->version_check_done
== 0) {
1955 ERR("Trying to close a stream before version check");
1957 goto end_no_session
;
1961 * Publish every pending stream in the connection recv list which are
1962 * now ready to be used by the viewer.
1964 publish_connection_local_streams(conn
);
1966 memset(&reply
, 0, sizeof(reply
));
1967 reply
.ret_code
= htobe32(LTTNG_OK
);
1968 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1970 ERR("Relay sending sent_stream reply");
1982 * Process the commands received on the control socket
1984 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1985 struct relay_connection
*conn
)
1989 switch (be32toh(recv_hdr
->cmd
)) {
1990 case RELAYD_CREATE_SESSION
:
1991 ret
= relay_create_session(recv_hdr
, conn
);
1993 case RELAYD_ADD_STREAM
:
1994 ret
= relay_add_stream(recv_hdr
, conn
);
1996 case RELAYD_START_DATA
:
1997 ret
= relay_start(recv_hdr
, conn
);
1999 case RELAYD_SEND_METADATA
:
2000 ret
= relay_recv_metadata(recv_hdr
, conn
);
2002 case RELAYD_VERSION
:
2003 ret
= relay_send_version(recv_hdr
, conn
);
2005 case RELAYD_CLOSE_STREAM
:
2006 ret
= relay_close_stream(recv_hdr
, conn
);
2008 case RELAYD_DATA_PENDING
:
2009 ret
= relay_data_pending(recv_hdr
, conn
);
2011 case RELAYD_QUIESCENT_CONTROL
:
2012 ret
= relay_quiescent_control(recv_hdr
, conn
);
2014 case RELAYD_BEGIN_DATA_PENDING
:
2015 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2017 case RELAYD_END_DATA_PENDING
:
2018 ret
= relay_end_data_pending(recv_hdr
, conn
);
2020 case RELAYD_SEND_INDEX
:
2021 ret
= relay_recv_index(recv_hdr
, conn
);
2023 case RELAYD_STREAMS_SENT
:
2024 ret
= relay_streams_sent(recv_hdr
, conn
);
2026 case RELAYD_UPDATE_SYNC_INFO
:
2028 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2029 relay_unknown_command(conn
);
2039 * Handle index for a data stream.
2041 * Called with the stream lock held.
2043 * Return 0 on success else a negative value.
2045 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2049 uint64_t data_offset
;
2050 struct relay_index
*index
;
2052 /* Get data offset because we are about to update the index. */
2053 data_offset
= htobe64(stream
->tracefile_size_current
);
2055 DBG("handle_index_data: stream %" PRIu64
" data offset %" PRIu64
,
2056 stream
->stream_handle
, stream
->tracefile_size_current
);
2059 * Lookup for an existing index for that stream id/sequence
2060 * number. If it exists, the control thread has already received the
2061 * data for it, thus we need to write it to disk.
2063 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2069 if (rotate_index
|| !stream
->index_fd
) {
2072 /* Put ref on previous index_fd. */
2073 if (stream
->index_fd
) {
2074 stream_fd_put(stream
->index_fd
);
2075 stream
->index_fd
= NULL
;
2078 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2079 -1, -1, stream
->tracefile_size
,
2080 tracefile_array_get_file_index_head(stream
->tfa
));
2083 /* Put self-ref for this index due to error. */
2084 relay_index_put(index
);
2087 stream
->index_fd
= stream_fd_create(fd
);
2088 if (!stream
->index_fd
) {
2091 PERROR("Error closing FD %d", fd
);
2093 /* Put self-ref for this index due to error. */
2094 relay_index_put(index
);
2095 /* Will put the local ref. */
2100 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2102 /* Put self-ref for this index due to error. */
2103 relay_index_put(index
);
2107 ret
= relay_index_try_flush(index
);
2109 tracefile_array_commit_seq(stream
->tfa
);
2110 stream
->index_received_seqcount
++;
2111 } else if (ret
> 0) {
2115 /* Put self-ref for this index due to error. */
2116 relay_index_put(index
);
2124 * relay_process_data: Process the data received on the data socket
2126 static int relay_process_data(struct relay_connection
*conn
)
2128 int ret
= 0, rotate_index
= 0;
2130 struct relay_stream
*stream
;
2131 struct lttcomm_relayd_data_hdr data_hdr
;
2133 uint64_t net_seq_num
;
2135 struct relay_session
*session
;
2136 bool new_stream
= false, close_requested
= false;
2138 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2139 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2142 /* Orderly shutdown. Not necessary to print an error. */
2143 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2145 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2151 stream_id
= be64toh(data_hdr
.stream_id
);
2152 stream
= stream_get_by_id(stream_id
);
2157 session
= stream
->trace
->session
;
2158 data_size
= be32toh(data_hdr
.data_size
);
2159 if (data_buffer_size
< data_size
) {
2162 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2163 if (!tmp_data_ptr
) {
2164 ERR("Allocating data buffer");
2167 goto end_stream_put
;
2169 data_buffer
= tmp_data_ptr
;
2170 data_buffer_size
= data_size
;
2172 memset(data_buffer
, 0, data_size
);
2174 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2176 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2177 data_size
, stream_id
, net_seq_num
);
2178 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2181 /* Orderly shutdown. Not necessary to print an error. */
2182 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2185 goto end_stream_put
;
2188 pthread_mutex_lock(&stream
->lock
);
2190 /* Check if a rotation is needed. */
2191 if (stream
->tracefile_size
> 0 &&
2192 (stream
->tracefile_size_current
+ data_size
) >
2193 stream
->tracefile_size
) {
2194 uint64_t old_id
, new_id
;
2196 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2197 tracefile_array_file_rotate(stream
->tfa
);
2199 /* new_id is updated by utils_rotate_stream_file. */
2202 ret
= utils_rotate_stream_file(stream
->path_name
,
2203 stream
->channel_name
, stream
->tracefile_size
,
2204 stream
->tracefile_count
, -1,
2205 -1, stream
->stream_fd
->fd
,
2206 &new_id
, &stream
->stream_fd
->fd
);
2208 ERR("Rotating stream output file");
2209 goto end_stream_unlock
;
2212 * Reset current size because we just performed a stream
2215 stream
->tracefile_size_current
= 0;
2220 * Index are handled in protocol version 2.4 and above. Also,
2221 * snapshot and index are NOT supported.
2223 if (session
->minor
>= 4 && !session
->snapshot
) {
2224 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2226 goto end_stream_unlock
;
2230 /* Write data to stream output fd. */
2231 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2232 if (size_ret
< data_size
) {
2233 ERR("Relay error writing data to file");
2235 goto end_stream_unlock
;
2238 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2239 size_ret
, stream
->stream_handle
);
2241 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2242 be32toh(data_hdr
.padding_size
));
2244 goto end_stream_unlock
;
2246 stream
->tracefile_size_current
+=
2247 data_size
+ be32toh(data_hdr
.padding_size
);
2248 if (stream
->prev_seq
== -1ULL) {
2252 stream
->prev_seq
= net_seq_num
;
2255 close_requested
= stream
->close_requested
;
2256 pthread_mutex_unlock(&stream
->lock
);
2257 if (close_requested
) {
2258 try_stream_close(stream
);
2262 pthread_mutex_lock(&session
->lock
);
2263 uatomic_set(&session
->new_streams
, 1);
2264 pthread_mutex_unlock(&session
->lock
);
2272 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2276 (void) lttng_poll_del(events
, pollfd
);
2278 ret
= close(pollfd
);
2280 ERR("Closing pollfd %d", pollfd
);
2284 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2285 int pollfd
, struct relay_connection
*conn
)
2287 const char *type_str
;
2289 switch (conn
->type
) {
2294 type_str
= "Control";
2296 case RELAY_VIEWER_COMMAND
:
2297 type_str
= "Viewer Command";
2299 case RELAY_VIEWER_NOTIFICATION
:
2300 type_str
= "Viewer Notification";
2303 type_str
= "Unknown";
2305 cleanup_connection_pollfd(events
, pollfd
);
2306 connection_put(conn
);
2307 DBG("%s connection closed with %d", type_str
, pollfd
);
2311 * This thread does the actual work
2313 static void *relay_thread_worker(void *data
)
2315 int ret
, err
= -1, last_seen_data_fd
= -1;
2317 struct lttng_poll_event events
;
2318 struct lttng_ht
*relay_connections_ht
;
2319 struct lttng_ht_iter iter
;
2320 struct lttcomm_relayd_hdr recv_hdr
;
2321 struct relay_connection
*destroy_conn
= NULL
;
2323 DBG("[thread] Relay worker started");
2325 rcu_register_thread();
2327 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2329 if (testpoint(relayd_thread_worker
)) {
2330 goto error_testpoint
;
2333 health_code_update();
2335 /* table of connections indexed on socket */
2336 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2337 if (!relay_connections_ht
) {
2338 goto relay_connections_ht_error
;
2341 ret
= create_thread_poll_set(&events
, 2);
2343 goto error_poll_create
;
2346 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2353 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2355 health_code_update();
2357 /* Infinite blocking call, waiting for transmission */
2358 DBG3("Relayd worker thread polling...");
2359 health_poll_entry();
2360 ret
= lttng_poll_wait(&events
, -1);
2364 * Restart interrupted system call.
2366 if (errno
== EINTR
) {
2375 * Process control. The control connection is
2376 * prioritized so we don't starve it with high
2377 * throughput tracing data on the data connection.
2379 for (i
= 0; i
< nb_fd
; i
++) {
2380 /* Fetch once the poll data */
2381 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2382 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2384 health_code_update();
2388 * No activity for this FD (poll
2394 /* Thread quit pipe has been closed. Killing thread. */
2395 ret
= check_thread_quit_pipe(pollfd
, revents
);
2401 /* Inspect the relay conn pipe for new connection */
2402 if (pollfd
== relay_conn_pipe
[0]) {
2403 if (revents
& LPOLLIN
) {
2404 struct relay_connection
*conn
;
2406 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2410 lttng_poll_add(&events
, conn
->sock
->fd
,
2411 LPOLLIN
| LPOLLRDHUP
);
2412 connection_ht_add(relay_connections_ht
, conn
);
2413 DBG("Connection socket %d added", conn
->sock
->fd
);
2414 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2415 ERR("Relay connection pipe error");
2418 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2422 struct relay_connection
*ctrl_conn
;
2424 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2425 /* If not found, there is a synchronization issue. */
2428 if (ctrl_conn
->type
== RELAY_DATA
) {
2429 if (revents
& LPOLLIN
) {
2431 * Flag the last seen data fd not deleted. It will be
2432 * used as the last seen fd if any fd gets deleted in
2435 last_notdel_data_fd
= pollfd
;
2437 goto put_ctrl_connection
;
2439 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2441 if (revents
& LPOLLIN
) {
2442 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2443 &recv_hdr
, sizeof(recv_hdr
), 0);
2445 /* Connection closed */
2446 relay_thread_close_connection(&events
, pollfd
,
2449 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2451 /* Clear the session on error. */
2452 relay_thread_close_connection(&events
,
2457 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2458 relay_thread_close_connection(&events
,
2460 if (last_seen_data_fd
== pollfd
) {
2461 last_seen_data_fd
= last_notdel_data_fd
;
2464 ERR("Unexpected poll events %u for control sock %d",
2466 connection_put(ctrl_conn
);
2469 put_ctrl_connection
:
2470 connection_put(ctrl_conn
);
2475 * The last loop handled a control request, go back to poll to make
2476 * sure we prioritise the control socket.
2482 if (last_seen_data_fd
>= 0) {
2483 for (i
= 0; i
< nb_fd
; i
++) {
2484 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2486 health_code_update();
2488 if (last_seen_data_fd
== pollfd
) {
2495 /* Process data connection. */
2496 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2497 /* Fetch the poll data. */
2498 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2499 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2500 struct relay_connection
*data_conn
;
2502 health_code_update();
2505 /* No activity for this FD (poll implementation). */
2509 /* Skip the command pipe. It's handled in the first loop. */
2510 if (pollfd
== relay_conn_pipe
[0]) {
2514 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2516 /* Skip it. Might be removed before. */
2519 if (data_conn
->type
== RELAY_CONTROL
) {
2520 goto put_data_connection
;
2522 assert(data_conn
->type
== RELAY_DATA
);
2524 if (revents
& LPOLLIN
) {
2525 ret
= relay_process_data(data_conn
);
2526 /* Connection closed */
2528 relay_thread_close_connection(&events
, pollfd
,
2531 * Every goto restart call sets the last seen fd where
2532 * here we don't really care since we gracefully
2533 * continue the loop after the connection is deleted.
2536 /* Keep last seen port. */
2537 last_seen_data_fd
= pollfd
;
2538 connection_put(data_conn
);
2541 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2542 relay_thread_close_connection(&events
, pollfd
,
2545 ERR("Unknown poll events %u for data sock %d",
2548 put_data_connection
:
2549 connection_put(data_conn
);
2551 last_seen_data_fd
= -1;
2554 /* Normal exit, no error */
2559 /* Cleanup reamaining connection object. */
2561 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2564 health_code_update();
2566 * No need to grab another ref, because we own
2569 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2574 lttng_poll_clean(&events
);
2576 lttng_ht_destroy(relay_connections_ht
);
2577 relay_connections_ht_error
:
2578 /* Close relay conn pipes */
2579 utils_close_pipe(relay_conn_pipe
);
2581 DBG("Thread exited with error");
2583 DBG("Worker thread cleanup complete");
2588 ERR("Health error occurred in %s", __func__
);
2590 health_unregister(health_relayd
);
2591 rcu_unregister_thread();
2592 lttng_relay_stop_threads();
2597 * Create the relay command pipe to wake thread_manage_apps.
2598 * Closed in cleanup().
2600 static int create_relay_conn_pipe(void)
2604 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2612 int main(int argc
, char **argv
)
2614 int ret
= 0, retval
= 0;
2617 /* Parse arguments */
2619 if (set_options(argc
, argv
)) {
2624 if (set_signal_handler()) {
2629 /* Try to create directory if -o, --output is specified. */
2630 if (opt_output_path
) {
2631 if (*opt_output_path
!= '/') {
2632 ERR("Please specify an absolute path for -o, --output PATH");
2637 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2640 ERR("Unable to create %s", opt_output_path
);
2647 if (opt_daemon
|| opt_background
) {
2650 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2658 * We are in the child. Make sure all other file
2659 * descriptors are closed, in case we are called with
2660 * more opened file descriptors than the standard ones.
2662 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2668 /* Initialize thread health monitoring */
2669 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2670 if (!health_relayd
) {
2671 PERROR("health_app_create error");
2673 goto exit_health_app_create
;
2676 /* Create thread quit pipe */
2677 if (init_thread_quit_pipe()) {
2679 goto exit_init_data
;
2682 /* Check if daemon is UID = 0 */
2684 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2685 ERR("Need to be root to use ports < 1024");
2687 goto exit_init_data
;
2691 /* Setup the thread apps communication pipe. */
2692 if (create_relay_conn_pipe()) {
2694 goto exit_init_data
;
2697 /* Init relay command queue. */
2698 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2700 /* Set up max poll set size */
2701 lttng_poll_set_max_size();
2703 /* Initialize communication library */
2705 lttcomm_inet_init();
2707 /* tables of sessions indexed by session ID */
2708 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2711 goto exit_init_data
;
2714 /* tables of streams indexed by stream ID */
2715 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2716 if (!relay_streams_ht
) {
2718 goto exit_init_data
;
2721 /* tables of streams indexed by stream ID */
2722 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2723 if (!viewer_streams_ht
) {
2725 goto exit_init_data
;
2728 ret
= utils_create_pipe(health_quit_pipe
);
2731 goto exit_health_quit_pipe
;
2734 /* Create thread to manage the client socket */
2735 ret
= pthread_create(&health_thread
, NULL
,
2736 thread_manage_health
, (void *) NULL
);
2739 PERROR("pthread_create health");
2741 goto exit_health_thread
;
2744 /* Setup the dispatcher thread */
2745 ret
= pthread_create(&dispatcher_thread
, NULL
,
2746 relay_thread_dispatcher
, (void *) NULL
);
2749 PERROR("pthread_create dispatcher");
2751 goto exit_dispatcher_thread
;
2754 /* Setup the worker thread */
2755 ret
= pthread_create(&worker_thread
, NULL
,
2756 relay_thread_worker
, NULL
);
2759 PERROR("pthread_create worker");
2761 goto exit_worker_thread
;
2764 /* Setup the listener thread */
2765 ret
= pthread_create(&listener_thread
, NULL
,
2766 relay_thread_listener
, (void *) NULL
);
2769 PERROR("pthread_create listener");
2771 goto exit_listener_thread
;
2774 ret
= relayd_live_create(live_uri
);
2776 ERR("Starting live viewer threads");
2782 * This is where we start awaiting program completion (e.g. through
2783 * signal that asks threads to teardown).
2786 ret
= relayd_live_join();
2792 ret
= pthread_join(listener_thread
, &status
);
2795 PERROR("pthread_join listener_thread");
2799 exit_listener_thread
:
2800 ret
= pthread_join(worker_thread
, &status
);
2803 PERROR("pthread_join worker_thread");
2808 ret
= pthread_join(dispatcher_thread
, &status
);
2811 PERROR("pthread_join dispatcher_thread");
2814 exit_dispatcher_thread
:
2816 ret
= pthread_join(health_thread
, &status
);
2819 PERROR("pthread_join health_thread");
2824 utils_close_pipe(health_quit_pipe
);
2825 exit_health_quit_pipe
:
2828 health_app_destroy(health_relayd
);
2829 exit_health_app_create
:
2833 /* Ensure all prior call_rcu are done. */