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>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 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>
60 #include "ctf-trace.h"
63 #include "lttng-relayd.h"
65 #include "health-relayd.h"
66 #include "testpoint.h"
67 #include "viewer-stream.h"
70 #include "connection.h"
72 /* command line options */
73 char *opt_output_path
;
74 static int opt_daemon
, opt_background
;
77 * We need to wait for listener and live listener threads, as well as
78 * health check thread, before being ready to signal readiness.
80 #define NR_LTTNG_RELAY_READY 3
81 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
82 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
83 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
85 static struct lttng_uri
*control_uri
;
86 static struct lttng_uri
*data_uri
;
87 static struct lttng_uri
*live_uri
;
91 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
92 static int tracing_group_name_override
;
94 const char * const config_section_name
= "relayd";
97 * Quit pipe for all threads. This permits a single cancellation point
98 * for all threads when receiving an event on the pipe.
100 int thread_quit_pipe
[2] = { -1, -1 };
103 * This pipe is used to inform the worker thread that a command is queued and
104 * ready to be processed.
106 static int relay_conn_pipe
[2] = { -1, -1 };
108 /* Shared between threads */
109 static int dispatch_thread_exit
;
111 static pthread_t listener_thread
;
112 static pthread_t dispatcher_thread
;
113 static pthread_t worker_thread
;
114 static pthread_t health_thread
;
116 static uint64_t last_relay_stream_id
;
119 * Relay command queue.
121 * The relay_thread_listener and relay_thread_dispatcher communicate with this
124 static struct relay_conn_queue relay_conn_queue
;
126 /* buffer allocated at startup, used to store the trace data */
127 static char *data_buffer
;
128 static unsigned int data_buffer_size
;
130 /* We need those values for the file/dir creation. */
131 static uid_t relayd_uid
;
132 static gid_t relayd_gid
;
134 /* Global relay stream hash table. */
135 struct lttng_ht
*relay_streams_ht
;
137 /* Global relay viewer stream hash table. */
138 struct lttng_ht
*viewer_streams_ht
;
140 /* Global hash table that stores relay index object. */
141 struct lttng_ht
*indexes_ht
;
143 /* Relayd health monitoring */
144 struct health_app
*health_relayd
;
146 static struct option long_options
[] = {
147 { "control-port", 1, 0, 'C', },
148 { "data-port", 1, 0, 'D', },
149 { "live-port", 1, 0, 'L', },
150 { "daemonize", 0, 0, 'd', },
151 { "background", 0, 0, 'b', },
152 { "group", 1, 0, 'g', },
153 { "help", 0, 0, 'h', },
154 { "output", 1, 0, 'o', },
155 { "verbose", 0, 0, 'v', },
156 { "config", 1, 0, 'f' },
160 static const char *config_ignore_options
[] = { "help", "config" };
163 * usage function on stderr
168 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
169 fprintf(stderr
, " -h, --help Display this usage.\n");
170 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
171 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
172 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
173 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
174 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
175 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
176 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
177 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
178 fprintf(stderr
, " -f --config Load daemon configuration file\n");
182 * Take an option from the getopt output and set it in the right variable to be
185 * Return 0 on success else a negative value.
188 int set_option(int opt
, const char *arg
, const char *optname
)
194 fprintf(stderr
, "option %s", optname
);
196 fprintf(stderr
, " with arg %s\n", arg
);
200 ret
= uri_parse(arg
, &control_uri
);
202 ERR("Invalid control URI specified");
205 if (control_uri
->port
== 0) {
206 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
210 ret
= uri_parse(arg
, &data_uri
);
212 ERR("Invalid data URI specified");
215 if (data_uri
->port
== 0) {
216 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
220 ret
= uri_parse(arg
, &live_uri
);
222 ERR("Invalid live URI specified");
225 if (live_uri
->port
== 0) {
226 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
236 tracing_group_name
= strdup(arg
);
237 if (tracing_group_name
== NULL
) {
242 tracing_group_name_override
= 1;
248 ret
= asprintf(&opt_output_path
, "%s", arg
);
251 PERROR("asprintf opt_output_path");
256 /* Verbose level can increase using multiple -v */
258 lttng_opt_verbose
= config_parse_value(arg
);
260 /* Only 3 level of verbosity (-vvv). */
261 if (lttng_opt_verbose
< 3) {
262 lttng_opt_verbose
+= 1;
267 /* Unknown option or other error.
268 * Error is printed by getopt, just return */
281 * config_entry_handler_cb used to handle options read from a config file.
282 * See config_entry_handler_cb comment in common/config/config.h for the
283 * return value conventions.
286 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, we have to
310 * check if the value is "true". We support non-zero numeric values,
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.",
337 int set_options(int argc
, char **argv
)
339 int c
, ret
= 0, option_index
= 0;
340 int orig_optopt
= optopt
, orig_optind
= optind
;
341 char *default_address
, *optstring
;
342 const char *config_path
= NULL
;
344 optstring
= utils_generate_optstring(long_options
,
345 sizeof(long_options
) / sizeof(struct option
));
351 /* Check for the --config option */
353 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
354 &option_index
)) != -1) {
358 } else if (c
!= 'f') {
362 config_path
= utils_expand_path(optarg
);
364 ERR("Failed to resolve path: %s", optarg
);
368 ret
= config_get_section_entries(config_path
, config_section_name
,
369 config_entry_handler
, NULL
);
372 ERR("Invalid configuration option at line %i", ret
);
378 /* Reset getopt's global state */
379 optopt
= orig_optopt
;
380 optind
= orig_optind
;
382 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
387 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");
403 ret
= uri_parse(default_address
, &control_uri
);
404 free(default_address
);
406 ERR("Invalid control URI specified");
410 if (data_uri
== NULL
) {
411 ret
= asprintf(&default_address
,
412 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
413 DEFAULT_NETWORK_DATA_PORT
);
415 PERROR("asprintf default data address");
419 ret
= uri_parse(default_address
, &data_uri
);
420 free(default_address
);
422 ERR("Invalid data URI specified");
426 if (live_uri
== NULL
) {
427 ret
= asprintf(&default_address
,
428 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
429 DEFAULT_NETWORK_VIEWER_PORT
);
431 PERROR("asprintf default viewer control address");
435 ret
= uri_parse(default_address
, &live_uri
);
436 free(default_address
);
438 ERR("Invalid viewer control URI specified");
456 /* free the dynamically allocated opt_output_path */
457 free(opt_output_path
);
459 /* Close thread quit pipes */
460 utils_close_pipe(thread_quit_pipe
);
462 uri_free(control_uri
);
464 /* Live URI is freed in the live thread. */
466 if (tracing_group_name_override
) {
467 free((void *) tracing_group_name
);
472 * Write to writable pipe used to notify a thread.
475 int notify_thread_pipe(int wpipe
)
479 ret
= lttng_write(wpipe
, "!", 1);
481 PERROR("write poll pipe");
487 static void notify_health_quit_pipe(int *pipe
)
491 ret
= lttng_write(pipe
[1], "4", 1);
493 PERROR("write relay health quit");
498 * Stop all threads by closing the thread quit pipe.
501 void stop_threads(void)
505 /* Stopping all threads */
506 DBG("Terminating all threads");
507 ret
= notify_thread_pipe(thread_quit_pipe
[1]);
509 ERR("write error on thread quit pipe");
512 notify_health_quit_pipe(health_quit_pipe
);
514 /* Dispatch thread */
515 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
516 futex_nto1_wake(&relay_conn_queue
.futex
);
520 * Signal handler for the daemon
522 * Simply stop all worker threads, leaving main() return gracefully after
523 * joining all threads and calling cleanup().
526 void sighandler(int sig
)
530 DBG("SIGPIPE caught");
533 DBG("SIGINT caught");
537 DBG("SIGTERM caught");
541 CMM_STORE_SHARED(recv_child_signal
, 1);
549 * Setup signal handler for :
550 * SIGINT, SIGTERM, SIGPIPE
553 int set_signal_handler(void)
559 if ((ret
= sigemptyset(&sigset
)) < 0) {
560 PERROR("sigemptyset");
564 sa
.sa_handler
= sighandler
;
567 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
572 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
577 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
582 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
587 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
592 void lttng_relay_notify_ready(void)
594 /* Notify the parent of the fork() process that we are ready. */
595 if (opt_daemon
|| opt_background
) {
596 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
597 kill(child_ppid
, SIGUSR1
);
603 * Init thread quit pipe.
605 * Return -1 on error or 0 if all pipes are created.
608 int init_thread_quit_pipe(void)
612 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
618 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
621 int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
625 if (events
== NULL
|| size
== 0) {
630 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
636 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
648 * Check if the thread quit pipe was triggered.
650 * Return 1 if it was triggered else 0;
653 int check_thread_quit_pipe(int fd
, uint32_t events
)
655 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
663 * Create and init socket from uri.
666 struct lttcomm_sock
*relay_init_sock(struct lttng_uri
*uri
)
669 struct lttcomm_sock
*sock
= NULL
;
671 sock
= lttcomm_alloc_sock_from_uri(uri
);
673 ERR("Allocating socket");
677 ret
= lttcomm_create_sock(sock
);
681 DBG("Listening on sock %d", sock
->fd
);
683 ret
= sock
->ops
->bind(sock
);
688 ret
= sock
->ops
->listen(sock
, -1);
698 lttcomm_destroy_sock(sock
);
704 * Return nonzero if stream needs to be closed.
707 int close_stream_check(struct relay_stream
*stream
)
709 if (stream
->close_flag
&& stream
->prev_seq
== stream
->last_net_seq_num
) {
711 * We are about to close the stream so set the data pending flag to 1
712 * which will make the end data pending command skip the stream which
713 * is now closed and ready. Note that after proceeding to a file close,
714 * the written file is ready for reading.
716 stream
->data_pending_check_done
= 1;
722 static void try_close_stream(struct relay_session
*session
,
723 struct relay_stream
*stream
)
726 struct ctf_trace
*ctf_trace
;
731 if (!close_stream_check(stream
)) {
732 /* Can't close it, not ready for that. */
736 ctf_trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
,
740 pthread_mutex_lock(&session
->viewer_ready_lock
);
741 ctf_trace
->invalid_flag
= 1;
742 pthread_mutex_unlock(&session
->viewer_ready_lock
);
744 ret
= stream_close(session
, stream
);
745 if (ret
|| session
->snapshot
) {
746 /* Already close thus the ctf trace is being or has been destroyed. */
750 ctf_trace_try_destroy(session
, ctf_trace
);
757 * This thread manages the listening for new connections on the network
760 void *relay_thread_listener(void *data
)
762 int i
, ret
, pollfd
, err
= -1;
763 uint32_t revents
, nb_fd
;
764 struct lttng_poll_event events
;
765 struct lttcomm_sock
*control_sock
, *data_sock
;
767 DBG("[thread] Relay listener started");
769 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
771 health_code_update();
773 control_sock
= relay_init_sock(control_uri
);
775 goto error_sock_control
;
778 data_sock
= relay_init_sock(data_uri
);
780 goto error_sock_relay
;
784 * Pass 3 as size here for the thread quit pipe, control and data socket.
786 ret
= create_thread_poll_set(&events
, 3);
788 goto error_create_poll
;
791 /* Add the control socket */
792 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
797 /* Add the data socket */
798 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
803 lttng_relay_notify_ready();
805 if (testpoint(relayd_thread_listener
)) {
806 goto error_testpoint
;
810 health_code_update();
812 DBG("Listener accepting connections");
816 ret
= lttng_poll_wait(&events
, -1);
820 * Restart interrupted system call.
822 if (errno
== EINTR
) {
830 DBG("Relay new connection received");
831 for (i
= 0; i
< nb_fd
; i
++) {
832 health_code_update();
834 /* Fetch once the poll data */
835 revents
= LTTNG_POLL_GETEV(&events
, i
);
836 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
838 /* Thread quit pipe has been closed. Killing thread. */
839 ret
= check_thread_quit_pipe(pollfd
, revents
);
845 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
846 ERR("socket poll error");
848 } else if (revents
& LPOLLIN
) {
850 * Get allocated in this thread, enqueued to a global queue,
851 * dequeued and freed in the worker thread.
854 struct relay_connection
*new_conn
;
855 struct lttcomm_sock
*newsock
;
857 new_conn
= connection_create();
862 if (pollfd
== data_sock
->fd
) {
863 new_conn
->type
= RELAY_DATA
;
864 newsock
= data_sock
->ops
->accept(data_sock
);
865 DBG("Relay data connection accepted, socket %d",
868 assert(pollfd
== control_sock
->fd
);
869 new_conn
->type
= RELAY_CONTROL
;
870 newsock
= control_sock
->ops
->accept(control_sock
);
871 DBG("Relay control connection accepted, socket %d",
875 PERROR("accepting sock");
876 connection_free(new_conn
);
880 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
883 PERROR("setsockopt inet");
884 lttcomm_destroy_sock(newsock
);
885 connection_free(new_conn
);
888 new_conn
->sock
= newsock
;
890 /* Enqueue request for the dispatcher thread. */
891 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
895 * Wake the dispatch queue futex. Implicit memory barrier with
896 * the exchange in cds_wfcq_enqueue.
898 futex_nto1_wake(&relay_conn_queue
.futex
);
907 lttng_poll_clean(&events
);
909 if (data_sock
->fd
>= 0) {
910 ret
= data_sock
->ops
->close(data_sock
);
915 lttcomm_destroy_sock(data_sock
);
917 if (control_sock
->fd
>= 0) {
918 ret
= control_sock
->ops
->close(control_sock
);
923 lttcomm_destroy_sock(control_sock
);
927 ERR("Health error occurred in %s", __func__
);
929 health_unregister(health_relayd
);
930 DBG("Relay listener thread cleanup complete");
936 * This thread manages the dispatching of the requests to worker threads
939 void *relay_thread_dispatcher(void *data
)
943 struct cds_wfcq_node
*node
;
944 struct relay_connection
*new_conn
= NULL
;
946 DBG("[thread] Relay dispatcher started");
948 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
950 if (testpoint(relayd_thread_dispatcher
)) {
951 goto error_testpoint
;
954 health_code_update();
956 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
957 health_code_update();
959 /* Atomically prepare the queue futex */
960 futex_nto1_prepare(&relay_conn_queue
.futex
);
963 health_code_update();
965 /* Dequeue commands */
966 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
967 &relay_conn_queue
.tail
);
969 DBG("Woken up but nothing in the relay command queue");
970 /* Continue thread execution */
973 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
975 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
978 * Inform worker thread of the new request. This call is blocking
979 * so we can be assured that the data will be read at some point in
980 * time or wait to the end of the world :)
982 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
984 PERROR("write connection pipe");
985 connection_destroy(new_conn
);
988 } while (node
!= NULL
);
990 /* Futex wait on queue. Blocking call on futex() */
992 futex_nto1_wait(&relay_conn_queue
.futex
);
996 /* Normal exit, no error */
1003 ERR("Health error occurred in %s", __func__
);
1005 health_unregister(health_relayd
);
1006 DBG("Dispatch thread dying");
1011 static void try_close_streams(struct relay_session
*session
)
1013 struct ctf_trace
*ctf_trace
;
1014 struct lttng_ht_iter iter
;
1018 pthread_mutex_lock(&session
->viewer_ready_lock
);
1020 cds_lfht_for_each_entry(session
->ctf_traces_ht
->ht
, &iter
.iter
, ctf_trace
,
1022 struct relay_stream
*stream
;
1024 /* Close streams. */
1025 cds_list_for_each_entry(stream
, &ctf_trace
->stream_list
, trace_list
) {
1026 stream_close(session
, stream
);
1029 ctf_trace
->invalid_flag
= 1;
1030 ctf_trace_try_destroy(session
, ctf_trace
);
1033 pthread_mutex_unlock(&session
->viewer_ready_lock
);
1037 * Try to destroy a session within a connection.
1039 static void destroy_session(struct relay_session
*session
,
1040 struct lttng_ht
*sessions_ht
)
1043 assert(sessions_ht
);
1045 /* Indicate that this session can be destroyed from now on. */
1046 session
->close_flag
= 1;
1048 try_close_streams(session
);
1051 * This will try to delete and destroy the session if no viewer is attached
1052 * to it meaning the refcount is down to zero.
1054 session_try_destroy(sessions_ht
, session
);
1058 * Copy index data from the control port to a given index object.
1060 static void copy_index_control_data(struct relay_index
*index
,
1061 struct lttcomm_relayd_index
*data
)
1067 * The index on disk is encoded in big endian, so we don't need to convert
1068 * the data received on the network. The data_offset value is NEVER
1069 * modified here and is updated by the data thread.
1071 index
->index_data
.packet_size
= data
->packet_size
;
1072 index
->index_data
.content_size
= data
->content_size
;
1073 index
->index_data
.timestamp_begin
= data
->timestamp_begin
;
1074 index
->index_data
.timestamp_end
= data
->timestamp_end
;
1075 index
->index_data
.events_discarded
= data
->events_discarded
;
1076 index
->index_data
.stream_id
= data
->stream_id
;
1080 * Handle the RELAYD_CREATE_SESSION command.
1082 * On success, send back the session id or else return a negative value.
1085 int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1086 struct relay_connection
*conn
)
1088 int ret
= 0, send_ret
;
1089 struct relay_session
*session
;
1090 struct lttcomm_relayd_status_session reply
;
1095 memset(&reply
, 0, sizeof(reply
));
1097 session
= session_create();
1102 session
->minor
= conn
->minor
;
1103 session
->major
= conn
->major
;
1104 conn
->session_id
= session
->id
;
1105 conn
->session
= session
;
1107 reply
.session_id
= htobe64(session
->id
);
1109 switch (conn
->minor
) {
1114 case 4: /* LTTng sessiond 2.4 */
1116 ret
= cmd_create_session_2_4(conn
, session
);
1119 lttng_ht_add_unique_u64(conn
->sessions_ht
, &session
->session_n
);
1120 DBG("Created session %" PRIu64
, session
->id
);
1124 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1126 reply
.ret_code
= htobe32(LTTNG_OK
);
1129 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1131 ERR("Relayd sending session id");
1139 * When we have received all the streams and the metadata for a channel,
1140 * we make them visible to the viewer threads.
1143 void set_viewer_ready_flag(struct relay_connection
*conn
)
1145 struct relay_stream
*stream
, *tmp_stream
;
1147 pthread_mutex_lock(&conn
->session
->viewer_ready_lock
);
1148 cds_list_for_each_entry_safe(stream
, tmp_stream
, &conn
->recv_head
,
1150 stream
->viewer_ready
= 1;
1151 cds_list_del(&stream
->recv_list
);
1153 pthread_mutex_unlock(&conn
->session
->viewer_ready_lock
);
1158 * Add a recv handle node to the connection recv list with the given stream
1159 * handle. A new node is allocated thus must be freed when the node is deleted
1162 static void queue_stream(struct relay_stream
*stream
,
1163 struct relay_connection
*conn
)
1168 cds_list_add(&stream
->recv_list
, &conn
->recv_head
);
1172 * relay_add_stream: allocate a new stream for a session
1175 int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1176 struct relay_connection
*conn
)
1179 struct relay_session
*session
= conn
->session
;
1180 struct relay_stream
*stream
= NULL
;
1181 struct lttcomm_relayd_status_stream reply
;
1182 struct ctf_trace
*trace
;
1184 if (!session
|| conn
->version_check_done
== 0) {
1185 ERR("Trying to add a stream before version check");
1187 goto end_no_session
;
1190 stream
= zmalloc(sizeof(struct relay_stream
));
1191 if (stream
== NULL
) {
1192 PERROR("relay stream zmalloc");
1194 goto end_no_session
;
1197 switch (conn
->minor
) {
1198 case 1: /* LTTng sessiond 2.1 */
1199 ret
= cmd_recv_stream_2_1(conn
, stream
);
1201 case 2: /* LTTng sessiond 2.2 */
1203 ret
= cmd_recv_stream_2_2(conn
, stream
);
1207 goto err_free_stream
;
1211 stream
->stream_handle
= ++last_relay_stream_id
;
1212 stream
->prev_seq
= -1ULL;
1213 stream
->session_id
= session
->id
;
1214 stream
->index_fd
= -1;
1215 stream
->read_index_fd
= -1;
1216 stream
->ctf_stream_id
= -1ULL;
1217 lttng_ht_node_init_u64(&stream
->node
, stream
->stream_handle
);
1218 pthread_mutex_init(&stream
->lock
, NULL
);
1220 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
);
1222 ERR("relay creating output directory");
1227 * No need to use run_as API here because whatever we receives, the relayd
1228 * uses its own credentials for the stream files.
1230 ret
= utils_create_stream_file(stream
->path_name
, stream
->channel_name
,
1231 stream
->tracefile_size
, 0, relayd_uid
, relayd_gid
, NULL
);
1233 ERR("Create output file");
1237 if (stream
->tracefile_size
) {
1238 DBG("Tracefile %s/%s_0 created", stream
->path_name
, stream
->channel_name
);
1240 DBG("Tracefile %s/%s created", stream
->path_name
, stream
->channel_name
);
1243 trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
, stream
->path_name
);
1245 trace
= ctf_trace_create(stream
->path_name
);
1250 ctf_trace_add(session
->ctf_traces_ht
, trace
);
1252 ctf_trace_get_ref(trace
);
1254 if (!strncmp(stream
->channel_name
, DEFAULT_METADATA_NAME
, NAME_MAX
)) {
1255 stream
->metadata_flag
= 1;
1256 /* Assign quick reference to the metadata stream in the trace. */
1257 trace
->metadata_stream
= stream
;
1261 * Add the stream in the recv list of the connection. Once the end stream
1262 * message is received, this list is emptied and streams are set with the
1263 * viewer ready flag.
1265 queue_stream(stream
, conn
);
1268 * Both in the ctf_trace object and the global stream ht since the data
1269 * side of the relayd does not have the concept of session.
1271 lttng_ht_add_unique_u64(relay_streams_ht
, &stream
->node
);
1272 cds_list_add_tail(&stream
->trace_list
, &trace
->stream_list
);
1274 session
->stream_count
++;
1276 DBG("Relay new stream added %s with ID %" PRIu64
, stream
->channel_name
,
1277 stream
->stream_handle
);
1280 memset(&reply
, 0, sizeof(reply
));
1281 reply
.handle
= htobe64(stream
->stream_handle
);
1282 /* send the session id to the client or a negative return code on error */
1284 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1285 /* stream was not properly added to the ht, so free it */
1288 reply
.ret_code
= htobe32(LTTNG_OK
);
1291 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1292 sizeof(struct lttcomm_relayd_status_stream
), 0);
1294 ERR("Relay sending stream id");
1303 free(stream
->path_name
);
1304 free(stream
->channel_name
);
1310 * relay_close_stream: close a specific stream
1313 int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1314 struct relay_connection
*conn
)
1317 struct relay_session
*session
= conn
->session
;
1318 struct lttcomm_relayd_close_stream stream_info
;
1319 struct lttcomm_relayd_generic_reply reply
;
1320 struct relay_stream
*stream
;
1322 DBG("Close stream received");
1324 if (!session
|| conn
->version_check_done
== 0) {
1325 ERR("Trying to close a stream before version check");
1327 goto end_no_session
;
1330 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1331 sizeof(struct lttcomm_relayd_close_stream
), 0);
1332 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1334 /* Orderly shutdown. Not necessary to print an error. */
1335 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1337 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1340 goto end_no_session
;
1344 stream
= stream_find_by_id(relay_streams_ht
,
1345 be64toh(stream_info
.stream_id
));
1351 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1352 stream
->close_flag
= 1;
1353 session
->stream_count
--;
1355 /* Check if we can close it or else the data will do it. */
1356 try_close_stream(session
, stream
);
1361 memset(&reply
, 0, sizeof(reply
));
1363 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1365 reply
.ret_code
= htobe32(LTTNG_OK
);
1367 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1368 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1370 ERR("Relay sending stream id");
1379 * relay_unknown_command: send -1 if received unknown command
1382 void relay_unknown_command(struct relay_connection
*conn
)
1384 struct lttcomm_relayd_generic_reply reply
;
1387 memset(&reply
, 0, sizeof(reply
));
1388 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1389 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1390 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1392 ERR("Relay sending unknown command");
1397 * relay_start: send an acknowledgment to the client to tell if we are
1398 * ready to receive data. We are ready if a session is established.
1401 int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1402 struct relay_connection
*conn
)
1404 int ret
= htobe32(LTTNG_OK
);
1405 struct lttcomm_relayd_generic_reply reply
;
1406 struct relay_session
*session
= conn
->session
;
1409 DBG("Trying to start the streaming without a session established");
1410 ret
= htobe32(LTTNG_ERR_UNK
);
1413 memset(&reply
, 0, sizeof(reply
));
1414 reply
.ret_code
= ret
;
1415 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1416 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1418 ERR("Relay sending start ack");
1425 * Append padding to the file pointed by the file descriptor fd.
1427 static int write_padding_to_file(int fd
, uint32_t size
)
1436 zeros
= zmalloc(size
);
1437 if (zeros
== NULL
) {
1438 PERROR("zmalloc zeros for padding");
1443 ret
= lttng_write(fd
, zeros
, size
);
1445 PERROR("write padding to file");
1455 * relay_recv_metadata: receive the metada for the session.
1458 int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1459 struct relay_connection
*conn
)
1461 int ret
= htobe32(LTTNG_OK
);
1463 struct relay_session
*session
= conn
->session
;
1464 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1465 struct relay_stream
*metadata_stream
;
1466 uint64_t data_size
, payload_size
;
1467 struct ctf_trace
*ctf_trace
;
1470 ERR("Metadata sent before version check");
1475 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1476 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1477 ERR("Incorrect data size");
1481 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1483 if (data_buffer_size
< data_size
) {
1484 /* In case the realloc fails, we can free the memory */
1487 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1488 if (!tmp_data_ptr
) {
1489 ERR("Allocating data buffer");
1494 data_buffer
= tmp_data_ptr
;
1495 data_buffer_size
= data_size
;
1497 memset(data_buffer
, 0, data_size
);
1498 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1499 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1500 if (ret
< 0 || ret
!= data_size
) {
1502 /* Orderly shutdown. Not necessary to print an error. */
1503 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1505 ERR("Relay didn't receive the whole metadata");
1510 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1513 metadata_stream
= stream_find_by_id(relay_streams_ht
,
1514 be64toh(metadata_struct
->stream_id
));
1515 if (!metadata_stream
) {
1520 size_ret
= lttng_write(metadata_stream
->fd
, metadata_struct
->payload
,
1522 if (size_ret
< payload_size
) {
1523 ERR("Relay error writing metadata on file");
1528 ret
= write_padding_to_file(metadata_stream
->fd
,
1529 be32toh(metadata_struct
->padding_size
));
1534 ctf_trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
,
1535 metadata_stream
->path_name
);
1537 ctf_trace
->metadata_received
+=
1538 payload_size
+ be32toh(metadata_struct
->padding_size
);
1540 DBG2("Relay metadata written");
1549 * relay_send_version: send relayd version number
1552 int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1553 struct relay_connection
*conn
)
1556 struct lttcomm_relayd_version reply
, msg
;
1560 conn
->version_check_done
= 1;
1562 /* Get version from the other side. */
1563 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1564 if (ret
< 0 || ret
!= sizeof(msg
)) {
1566 /* Orderly shutdown. Not necessary to print an error. */
1567 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1569 ERR("Relay failed to receive the version values.");
1575 memset(&reply
, 0, sizeof(reply
));
1576 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1577 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1579 /* Major versions must be the same */
1580 if (reply
.major
!= be32toh(msg
.major
)) {
1581 DBG("Incompatible major versions (%u vs %u), deleting session",
1582 reply
.major
, be32toh(msg
.major
));
1583 destroy_session(conn
->session
, conn
->sessions_ht
);
1588 conn
->major
= reply
.major
;
1589 /* We adapt to the lowest compatible version */
1590 if (reply
.minor
<= be32toh(msg
.minor
)) {
1591 conn
->minor
= reply
.minor
;
1593 conn
->minor
= be32toh(msg
.minor
);
1596 reply
.major
= htobe32(reply
.major
);
1597 reply
.minor
= htobe32(reply
.minor
);
1598 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1599 sizeof(struct lttcomm_relayd_version
), 0);
1601 ERR("Relay sending version");
1604 DBG("Version check done using protocol %u.%u", conn
->major
,
1612 * Check for data pending for a given stream id from the session daemon.
1615 int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1616 struct relay_connection
*conn
)
1618 struct relay_session
*session
= conn
->session
;
1619 struct lttcomm_relayd_data_pending msg
;
1620 struct lttcomm_relayd_generic_reply reply
;
1621 struct relay_stream
*stream
;
1623 uint64_t last_net_seq_num
, stream_id
;
1625 DBG("Data pending command received");
1627 if (!session
|| conn
->version_check_done
== 0) {
1628 ERR("Trying to check for data before version check");
1630 goto end_no_session
;
1633 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1634 if (ret
< sizeof(msg
)) {
1636 /* Orderly shutdown. Not necessary to print an error. */
1637 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1639 ERR("Relay didn't receive valid data_pending struct size : %d",
1643 goto end_no_session
;
1646 stream_id
= be64toh(msg
.stream_id
);
1647 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1650 stream
= stream_find_by_id(relay_streams_ht
, stream_id
);
1651 if (stream
== NULL
) {
1656 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1657 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1660 /* Avoid wrapping issue */
1661 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1662 /* Data has in fact been written and is NOT pending */
1665 /* Data still being streamed thus pending */
1669 /* Pending check is now done. */
1670 stream
->data_pending_check_done
= 1;
1675 memset(&reply
, 0, sizeof(reply
));
1676 reply
.ret_code
= htobe32(ret
);
1677 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1679 ERR("Relay data pending ret code failed");
1687 * Wait for the control socket to reach a quiescent state.
1689 * Note that for now, when receiving this command from the session daemon, this
1690 * means that every subsequent commands or data received on the control socket
1691 * has been handled. So, this is why we simply return OK here.
1694 int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1695 struct relay_connection
*conn
)
1699 struct relay_stream
*stream
;
1700 struct lttng_ht_iter iter
;
1701 struct lttcomm_relayd_quiescent_control msg
;
1702 struct lttcomm_relayd_generic_reply reply
;
1704 DBG("Checking quiescent state on control socket");
1706 if (!conn
->session
|| conn
->version_check_done
== 0) {
1707 ERR("Trying to check for data before version check");
1709 goto end_no_session
;
1712 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1713 if (ret
< sizeof(msg
)) {
1715 /* Orderly shutdown. Not necessary to print an error. */
1716 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1718 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1722 goto end_no_session
;
1725 stream_id
= be64toh(msg
.stream_id
);
1728 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1730 if (stream
->stream_handle
== stream_id
) {
1731 stream
->data_pending_check_done
= 1;
1732 DBG("Relay quiescent control pending flag set to %" PRIu64
,
1739 memset(&reply
, 0, sizeof(reply
));
1740 reply
.ret_code
= htobe32(LTTNG_OK
);
1741 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1743 ERR("Relay data quiescent control ret code failed");
1751 * Initialize a data pending command. This means that a client is about to ask
1752 * for data pending for each stream he/she holds. Simply iterate over all
1753 * streams of a session and set the data_pending_check_done flag.
1755 * This command returns to the client a LTTNG_OK code.
1758 int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1759 struct relay_connection
*conn
)
1762 struct lttng_ht_iter iter
;
1763 struct lttcomm_relayd_begin_data_pending msg
;
1764 struct lttcomm_relayd_generic_reply reply
;
1765 struct relay_stream
*stream
;
1766 uint64_t session_id
;
1771 DBG("Init streams for data pending");
1773 if (!conn
->session
|| conn
->version_check_done
== 0) {
1774 ERR("Trying to check for data before version check");
1776 goto end_no_session
;
1779 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1780 if (ret
< sizeof(msg
)) {
1782 /* Orderly shutdown. Not necessary to print an error. */
1783 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1785 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1789 goto end_no_session
;
1792 session_id
= be64toh(msg
.session_id
);
1795 * Iterate over all streams to set the begin data pending flag. For now, the
1796 * streams are indexed by stream handle so we have to iterate over all
1797 * streams to find the one associated with the right session_id.
1800 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1802 if (stream
->session_id
== session_id
) {
1803 stream
->data_pending_check_done
= 0;
1804 DBG("Set begin data pending flag to stream %" PRIu64
,
1805 stream
->stream_handle
);
1810 memset(&reply
, 0, sizeof(reply
));
1811 /* All good, send back reply. */
1812 reply
.ret_code
= htobe32(LTTNG_OK
);
1814 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1816 ERR("Relay begin data pending send reply failed");
1824 * End data pending command. This will check, for a given session id, if each
1825 * stream associated with it has its data_pending_check_done flag set. If not,
1826 * this means that the client lost track of the stream but the data is still
1827 * being streamed on our side. In this case, we inform the client that data is
1830 * Return to the client if there is data in flight or not with a ret_code.
1833 int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1834 struct relay_connection
*conn
)
1837 struct lttng_ht_iter iter
;
1838 struct lttcomm_relayd_end_data_pending msg
;
1839 struct lttcomm_relayd_generic_reply reply
;
1840 struct relay_stream
*stream
;
1841 uint64_t session_id
;
1842 uint32_t is_data_inflight
= 0;
1847 DBG("End data pending command");
1849 if (!conn
->session
|| conn
->version_check_done
== 0) {
1850 ERR("Trying to check for data before version check");
1852 goto end_no_session
;
1855 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1856 if (ret
< sizeof(msg
)) {
1858 /* Orderly shutdown. Not necessary to print an error. */
1859 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1861 ERR("Relay didn't receive valid end data_pending struct size: %d",
1865 goto end_no_session
;
1868 session_id
= be64toh(msg
.session_id
);
1870 /* Iterate over all streams to see if the begin data pending flag is set. */
1872 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1874 if (stream
->session_id
== session_id
&&
1875 !stream
->data_pending_check_done
&& !stream
->terminated_flag
) {
1876 is_data_inflight
= 1;
1877 DBG("Data is still in flight for stream %" PRIu64
,
1878 stream
->stream_handle
);
1884 memset(&reply
, 0, sizeof(reply
));
1885 /* All good, send back reply. */
1886 reply
.ret_code
= htobe32(is_data_inflight
);
1888 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1890 ERR("Relay end data pending send reply failed");
1898 * Receive an index for a specific stream.
1900 * Return 0 on success else a negative value.
1903 int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1904 struct relay_connection
*conn
)
1906 int ret
, send_ret
, index_created
= 0;
1907 struct relay_session
*session
= conn
->session
;
1908 struct lttcomm_relayd_index index_info
;
1909 struct relay_index
*index
, *wr_index
= NULL
;
1910 struct lttcomm_relayd_generic_reply reply
;
1911 struct relay_stream
*stream
;
1912 uint64_t net_seq_num
;
1916 DBG("Relay receiving index");
1918 if (!session
|| conn
->version_check_done
== 0) {
1919 ERR("Trying to close a stream before version check");
1921 goto end_no_session
;
1924 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1925 sizeof(index_info
), 0);
1926 if (ret
< sizeof(index_info
)) {
1928 /* Orderly shutdown. Not necessary to print an error. */
1929 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1931 ERR("Relay didn't receive valid index struct size : %d", ret
);
1934 goto end_no_session
;
1937 net_seq_num
= be64toh(index_info
.net_seq_num
);
1940 stream
= stream_find_by_id(relay_streams_ht
,
1941 be64toh(index_info
.relay_stream_id
));
1944 goto end_rcu_unlock
;
1947 /* Live beacon handling */
1948 if (index_info
.packet_size
== 0) {
1949 DBG("Received live beacon for stream %" PRIu64
, stream
->stream_handle
);
1952 * Only flag a stream inactive when it has already received data
1953 * and no indexes are in flight.
1955 if (stream
->total_index_received
> 0 && stream
->indexes_in_flight
== 0) {
1956 stream
->beacon_ts_end
= be64toh(index_info
.timestamp_end
);
1959 goto end_rcu_unlock
;
1961 stream
->beacon_ts_end
= -1ULL;
1964 index
= relay_index_find(stream
->stream_handle
, net_seq_num
);
1966 /* A successful creation will add the object to the HT. */
1967 index
= relay_index_create(stream
->stream_handle
, net_seq_num
);
1969 goto end_rcu_unlock
;
1972 stream
->indexes_in_flight
++;
1975 copy_index_control_data(index
, &index_info
);
1976 if (stream
->ctf_stream_id
== -1ULL) {
1977 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1980 if (index_created
) {
1982 * Try to add the relay index object to the hash table. If an object
1983 * already exist, destroy back the index created, set the data in this
1984 * object and write it on disk.
1986 relay_index_add(index
, &wr_index
);
1988 copy_index_control_data(wr_index
, &index_info
);
1992 /* The index already exists so write it on disk. */
1996 /* Do we have a writable ready index to write on disk. */
1998 ret
= relay_index_write(wr_index
->fd
, wr_index
);
2000 goto end_rcu_unlock
;
2002 stream
->total_index_received
++;
2003 stream
->indexes_in_flight
--;
2004 assert(stream
->indexes_in_flight
>= 0);
2010 memset(&reply
, 0, sizeof(reply
));
2012 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2014 reply
.ret_code
= htobe32(LTTNG_OK
);
2016 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2018 ERR("Relay sending close index id reply");
2027 * Receive the streams_sent message.
2029 * Return 0 on success else a negative value.
2032 int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
2033 struct relay_connection
*conn
)
2036 struct lttcomm_relayd_generic_reply reply
;
2040 DBG("Relay receiving streams_sent");
2042 if (!conn
->session
|| conn
->version_check_done
== 0) {
2043 ERR("Trying to close a stream before version check");
2045 goto end_no_session
;
2049 * Flag every pending stream in the connection recv list that they are
2050 * ready to be used by the viewer.
2052 set_viewer_ready_flag(conn
);
2055 * Inform the viewer that there are new streams in the session.
2057 if (conn
->session
->viewer_refcount
) {
2058 uatomic_set(&conn
->session
->new_streams
, 1);
2061 memset(&reply
, 0, sizeof(reply
));
2062 reply
.ret_code
= htobe32(LTTNG_OK
);
2063 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2065 ERR("Relay sending sent_stream reply");
2077 * Process the commands received on the control socket
2080 int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2081 struct relay_connection
*conn
)
2085 switch (be32toh(recv_hdr
->cmd
)) {
2086 case RELAYD_CREATE_SESSION
:
2087 ret
= relay_create_session(recv_hdr
, conn
);
2089 case RELAYD_ADD_STREAM
:
2090 ret
= relay_add_stream(recv_hdr
, conn
);
2092 case RELAYD_START_DATA
:
2093 ret
= relay_start(recv_hdr
, conn
);
2095 case RELAYD_SEND_METADATA
:
2096 ret
= relay_recv_metadata(recv_hdr
, conn
);
2098 case RELAYD_VERSION
:
2099 ret
= relay_send_version(recv_hdr
, conn
);
2101 case RELAYD_CLOSE_STREAM
:
2102 ret
= relay_close_stream(recv_hdr
, conn
);
2104 case RELAYD_DATA_PENDING
:
2105 ret
= relay_data_pending(recv_hdr
, conn
);
2107 case RELAYD_QUIESCENT_CONTROL
:
2108 ret
= relay_quiescent_control(recv_hdr
, conn
);
2110 case RELAYD_BEGIN_DATA_PENDING
:
2111 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2113 case RELAYD_END_DATA_PENDING
:
2114 ret
= relay_end_data_pending(recv_hdr
, conn
);
2116 case RELAYD_SEND_INDEX
:
2117 ret
= relay_recv_index(recv_hdr
, conn
);
2119 case RELAYD_STREAMS_SENT
:
2120 ret
= relay_streams_sent(recv_hdr
, conn
);
2122 case RELAYD_UPDATE_SYNC_INFO
:
2124 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2125 relay_unknown_command(conn
);
2135 * Handle index for a data stream.
2137 * RCU read side lock MUST be acquired.
2139 * Return 0 on success else a negative value.
2141 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2144 int ret
= 0, index_created
= 0;
2145 uint64_t stream_id
, data_offset
;
2146 struct relay_index
*index
, *wr_index
= NULL
;
2150 stream_id
= stream
->stream_handle
;
2151 /* Get data offset because we are about to update the index. */
2152 data_offset
= htobe64(stream
->tracefile_size_current
);
2155 * Lookup for an existing index for that stream id/sequence number. If on
2156 * exists, the control thread already received the data for it thus we need
2157 * to write it on disk.
2159 index
= relay_index_find(stream_id
, net_seq_num
);
2161 /* A successful creation will add the object to the HT. */
2162 index
= relay_index_create(stream_id
, net_seq_num
);
2168 stream
->indexes_in_flight
++;
2171 if (rotate_index
|| stream
->index_fd
< 0) {
2172 index
->to_close_fd
= stream
->index_fd
;
2173 ret
= index_create_file(stream
->path_name
, stream
->channel_name
,
2174 relayd_uid
, relayd_gid
, stream
->tracefile_size
,
2175 stream
->tracefile_count_current
);
2177 /* This will close the stream's index fd if one. */
2178 relay_index_free_safe(index
);
2181 stream
->index_fd
= ret
;
2183 index
->fd
= stream
->index_fd
;
2184 index
->index_data
.offset
= data_offset
;
2186 if (index_created
) {
2188 * Try to add the relay index object to the hash table. If an object
2189 * already exist, destroy back the index created and set the data.
2191 relay_index_add(index
, &wr_index
);
2193 /* Copy back data from the created index. */
2194 wr_index
->fd
= index
->fd
;
2195 wr_index
->to_close_fd
= index
->to_close_fd
;
2196 wr_index
->index_data
.offset
= data_offset
;
2200 /* The index already exists so write it on disk. */
2204 /* Do we have a writable ready index to write on disk. */
2206 ret
= relay_index_write(wr_index
->fd
, wr_index
);
2210 stream
->total_index_received
++;
2211 stream
->indexes_in_flight
--;
2212 assert(stream
->indexes_in_flight
>= 0);
2220 * relay_process_data: Process the data received on the data socket
2223 int relay_process_data(struct relay_connection
*conn
)
2225 int ret
= 0, rotate_index
= 0;
2227 struct relay_stream
*stream
;
2228 struct lttcomm_relayd_data_hdr data_hdr
;
2230 uint64_t net_seq_num
;
2232 struct relay_session
*session
;
2236 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2237 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2240 /* Orderly shutdown. Not necessary to print an error. */
2241 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2243 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2249 stream_id
= be64toh(data_hdr
.stream_id
);
2252 stream
= stream_find_by_id(relay_streams_ht
, stream_id
);
2255 goto end_rcu_unlock
;
2258 session
= session_find_by_id(conn
->sessions_ht
, stream
->session_id
);
2261 data_size
= be32toh(data_hdr
.data_size
);
2262 if (data_buffer_size
< data_size
) {
2265 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2266 if (!tmp_data_ptr
) {
2267 ERR("Allocating data buffer");
2270 goto end_rcu_unlock
;
2272 data_buffer
= tmp_data_ptr
;
2273 data_buffer_size
= data_size
;
2275 memset(data_buffer
, 0, data_size
);
2277 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2279 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2280 data_size
, stream_id
, net_seq_num
);
2281 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2284 /* Orderly shutdown. Not necessary to print an error. */
2285 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2288 goto end_rcu_unlock
;
2291 /* Check if a rotation is needed. */
2292 if (stream
->tracefile_size
> 0 &&
2293 (stream
->tracefile_size_current
+ data_size
) >
2294 stream
->tracefile_size
) {
2295 struct relay_viewer_stream
*vstream
;
2298 new_id
= (stream
->tracefile_count_current
+ 1) %
2299 stream
->tracefile_count
;
2301 * When we wrap-around back to 0, we start overwriting old
2304 if (!stream
->tracefile_overwrite
&& new_id
== 0) {
2305 stream
->tracefile_overwrite
= 1;
2307 pthread_mutex_lock(&stream
->viewer_stream_rotation_lock
);
2308 if (stream
->tracefile_overwrite
) {
2309 stream
->oldest_tracefile_id
=
2310 (stream
->oldest_tracefile_id
+ 1) %
2311 stream
->tracefile_count
;
2313 vstream
= viewer_stream_find_by_id(stream
->stream_handle
);
2316 * The viewer is reading a file about to be
2317 * overwritten. Close the FDs it is
2318 * currently using and let it handle the fault.
2320 if (vstream
->tracefile_count_current
== new_id
) {
2321 pthread_mutex_lock(&vstream
->overwrite_lock
);
2322 vstream
->abort_flag
= 1;
2323 pthread_mutex_unlock(&vstream
->overwrite_lock
);
2324 DBG("Streaming side setting abort_flag on stream %s_%lu\n",
2325 stream
->channel_name
, new_id
);
2326 } else if (vstream
->tracefile_count_current
==
2327 stream
->tracefile_count_current
) {
2329 * The reader and writer were in the
2330 * same trace file, inform the viewer
2331 * that no new index will ever be added
2334 vstream
->close_write_flag
= 1;
2337 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
2338 stream
->tracefile_size
, stream
->tracefile_count
,
2339 relayd_uid
, relayd_gid
, stream
->fd
,
2340 &(stream
->tracefile_count_current
), &stream
->fd
);
2341 pthread_mutex_unlock(&stream
->viewer_stream_rotation_lock
);
2343 ERR("Rotating stream output file");
2344 goto end_rcu_unlock
;
2346 /* Reset current size because we just perform a stream rotation. */
2347 stream
->tracefile_size_current
= 0;
2352 * Index are handled in protocol version 2.4 and above. Also, snapshot and
2353 * index are NOT supported.
2355 if (session
->minor
>= 4 && !session
->snapshot
) {
2356 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2358 goto end_rcu_unlock
;
2362 /* Write data to stream output fd. */
2363 size_ret
= lttng_write(stream
->fd
, data_buffer
, data_size
);
2364 if (size_ret
< data_size
) {
2365 ERR("Relay error writing data to file");
2367 goto end_rcu_unlock
;
2370 DBG2("Relay wrote %d bytes to tracefile for stream id %" PRIu64
,
2371 ret
, stream
->stream_handle
);
2373 ret
= write_padding_to_file(stream
->fd
, be32toh(data_hdr
.padding_size
));
2375 goto end_rcu_unlock
;
2377 stream
->tracefile_size_current
+= data_size
+ be32toh(data_hdr
.padding_size
);
2379 stream
->prev_seq
= net_seq_num
;
2381 try_close_stream(session
, stream
);
2390 void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2396 (void) lttng_poll_del(events
, pollfd
);
2398 ret
= close(pollfd
);
2400 ERR("Closing pollfd %d", pollfd
);
2404 static void destroy_connection(struct lttng_ht
*relay_connections_ht
,
2405 struct relay_connection
*conn
)
2407 assert(relay_connections_ht
);
2410 connection_delete(relay_connections_ht
, conn
);
2412 /* For the control socket, we try to destroy the session. */
2413 if (conn
->type
== RELAY_CONTROL
&& conn
->session
) {
2414 destroy_session(conn
->session
, conn
->sessions_ht
);
2417 connection_destroy(conn
);
2421 * This thread does the actual work
2424 void *relay_thread_worker(void *data
)
2426 int ret
, err
= -1, last_seen_data_fd
= -1;
2428 struct relay_connection
*conn
;
2429 struct lttng_poll_event events
;
2430 struct lttng_ht
*relay_connections_ht
;
2431 struct lttng_ht_iter iter
;
2432 struct lttcomm_relayd_hdr recv_hdr
;
2433 struct relay_local_data
*relay_ctx
= (struct relay_local_data
*) data
;
2434 struct lttng_ht
*sessions_ht
= relay_ctx
->sessions_ht
;
2435 struct relay_index
*index
;
2437 DBG("[thread] Relay worker started");
2439 rcu_register_thread();
2441 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2443 if (testpoint(relayd_thread_worker
)) {
2444 goto error_testpoint
;
2447 health_code_update();
2449 /* table of connections indexed on socket */
2450 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2451 if (!relay_connections_ht
) {
2452 goto relay_connections_ht_error
;
2455 /* Tables of received indexes indexed by index handle and net_seq_num. */
2456 indexes_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_TWO_U64
);
2458 goto indexes_ht_error
;
2461 ret
= create_thread_poll_set(&events
, 2);
2463 goto error_poll_create
;
2466 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2473 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2475 health_code_update();
2477 /* Infinite blocking call, waiting for transmission */
2478 DBG3("Relayd worker thread polling...");
2479 health_poll_entry();
2480 ret
= lttng_poll_wait(&events
, -1);
2484 * Restart interrupted system call.
2486 if (errno
== EINTR
) {
2495 * Process control. The control connection is prioritised so we don't
2496 * starve it with high throughout put tracing data on the data
2499 for (i
= 0; i
< nb_fd
; i
++) {
2500 /* Fetch once the poll data */
2501 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2502 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2504 health_code_update();
2506 /* Thread quit pipe has been closed. Killing thread. */
2507 ret
= check_thread_quit_pipe(pollfd
, revents
);
2513 /* Inspect the relay conn pipe for new connection */
2514 if (pollfd
== relay_conn_pipe
[0]) {
2515 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2516 ERR("Relay connection pipe error");
2518 } else if (revents
& LPOLLIN
) {
2519 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2523 conn
->sessions_ht
= sessions_ht
;
2524 connection_init(conn
);
2525 lttng_poll_add(&events
, conn
->sock
->fd
,
2526 LPOLLIN
| LPOLLRDHUP
);
2528 lttng_ht_add_unique_ulong(relay_connections_ht
,
2531 DBG("Connection socket %d added", conn
->sock
->fd
);
2535 conn
= connection_find_by_sock(relay_connections_ht
, pollfd
);
2536 /* If not found, there is a synchronization issue. */
2539 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2540 cleanup_connection_pollfd(&events
, pollfd
);
2541 destroy_connection(relay_connections_ht
, conn
);
2542 if (last_seen_data_fd
== pollfd
) {
2543 last_seen_data_fd
= last_notdel_data_fd
;
2545 } else if (revents
& LPOLLIN
) {
2546 if (conn
->type
== RELAY_CONTROL
) {
2547 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &recv_hdr
,
2548 sizeof(recv_hdr
), 0);
2550 /* Connection closed */
2551 cleanup_connection_pollfd(&events
, pollfd
);
2552 destroy_connection(relay_connections_ht
, conn
);
2553 DBG("Control connection closed with %d", pollfd
);
2555 ret
= relay_process_control(&recv_hdr
, conn
);
2557 /* Clear the session on error. */
2558 cleanup_connection_pollfd(&events
, pollfd
);
2559 destroy_connection(relay_connections_ht
, conn
);
2560 DBG("Connection closed with %d", pollfd
);
2566 * Flag the last seen data fd not deleted. It will be
2567 * used as the last seen fd if any fd gets deleted in
2570 last_notdel_data_fd
= pollfd
;
2573 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
2580 * The last loop handled a control request, go back to poll to make
2581 * sure we prioritise the control socket.
2587 if (last_seen_data_fd
>= 0) {
2588 for (i
= 0; i
< nb_fd
; i
++) {
2589 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2591 health_code_update();
2593 if (last_seen_data_fd
== pollfd
) {
2600 /* Process data connection. */
2601 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2602 /* Fetch the poll data. */
2603 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2604 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2606 health_code_update();
2608 /* Skip the command pipe. It's handled in the first loop. */
2609 if (pollfd
== relay_conn_pipe
[0]) {
2615 conn
= connection_find_by_sock(relay_connections_ht
, pollfd
);
2617 /* Skip it. Might be removed before. */
2622 if (revents
& LPOLLIN
) {
2623 if (conn
->type
!= RELAY_DATA
) {
2628 ret
= relay_process_data(conn
);
2629 /* Connection closed */
2631 cleanup_connection_pollfd(&events
, pollfd
);
2632 destroy_connection(relay_connections_ht
, conn
);
2633 DBG("Data connection closed with %d", pollfd
);
2635 * Every goto restart call sets the last seen fd where
2636 * here we don't really care since we gracefully
2637 * continue the loop after the connection is deleted.
2640 /* Keep last seen port. */
2641 last_seen_data_fd
= pollfd
;
2649 last_seen_data_fd
= -1;
2652 /* Normal exit, no error */
2657 lttng_poll_clean(&events
);
2659 /* Cleanup reamaining connection object. */
2661 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
, conn
,
2663 health_code_update();
2664 destroy_connection(relay_connections_ht
, conn
);
2669 cds_lfht_for_each_entry(indexes_ht
->ht
, &iter
.iter
, index
,
2671 health_code_update();
2672 relay_index_delete(index
);
2673 relay_index_free_safe(index
);
2676 lttng_ht_destroy(indexes_ht
);
2678 lttng_ht_destroy(relay_connections_ht
);
2679 relay_connections_ht_error
:
2680 /* Close relay conn pipes */
2681 utils_close_pipe(relay_conn_pipe
);
2683 DBG("Thread exited with error");
2685 DBG("Worker thread cleanup complete");
2690 ERR("Health error occurred in %s", __func__
);
2692 health_unregister(health_relayd
);
2693 rcu_unregister_thread();
2699 * Create the relay command pipe to wake thread_manage_apps.
2700 * Closed in cleanup().
2702 static int create_relay_conn_pipe(void)
2706 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2714 int main(int argc
, char **argv
)
2718 struct relay_local_data
*relay_ctx
;
2720 /* Parse arguments */
2722 if ((ret
= set_options(argc
, argv
)) < 0) {
2726 if ((ret
= set_signal_handler()) < 0) {
2730 /* Try to create directory if -o, --output is specified. */
2731 if (opt_output_path
) {
2732 if (*opt_output_path
!= '/') {
2733 ERR("Please specify an absolute path for -o, --output PATH");
2737 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
);
2739 ERR("Unable to create %s", opt_output_path
);
2745 if (opt_daemon
|| opt_background
) {
2748 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2755 * We are in the child. Make sure all other file
2756 * descriptors are closed, in case we are called with
2757 * more opened file descriptors than the standard ones.
2759 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2764 /* Create thread quit pipe */
2765 if ((ret
= init_thread_quit_pipe()) < 0) {
2769 /* We need those values for the file/dir creation. */
2770 relayd_uid
= getuid();
2771 relayd_gid
= getgid();
2773 /* Check if daemon is UID = 0 */
2774 if (relayd_uid
== 0) {
2775 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2776 ERR("Need to be root to use ports < 1024");
2782 /* Setup the thread apps communication pipe. */
2783 if ((ret
= create_relay_conn_pipe()) < 0) {
2787 /* Init relay command queue. */
2788 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2790 /* Set up max poll set size */
2791 lttng_poll_set_max_size();
2793 /* Initialize communication library */
2795 lttcomm_inet_init();
2797 relay_ctx
= zmalloc(sizeof(struct relay_local_data
));
2799 PERROR("relay_ctx");
2803 /* tables of sessions indexed by session ID */
2804 relay_ctx
->sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2805 if (!relay_ctx
->sessions_ht
) {
2806 goto exit_relay_ctx_sessions
;
2809 /* tables of streams indexed by stream ID */
2810 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2811 if (!relay_streams_ht
) {
2812 goto exit_relay_ctx_streams
;
2815 /* tables of streams indexed by stream ID */
2816 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2817 if (!viewer_streams_ht
) {
2818 goto exit_relay_ctx_viewer_streams
;
2821 /* Initialize thread health monitoring */
2822 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2823 if (!health_relayd
) {
2824 PERROR("health_app_create error");
2825 goto exit_health_app_create
;
2828 ret
= utils_create_pipe(health_quit_pipe
);
2830 goto error_health_pipe
;
2833 /* Create thread to manage the client socket */
2834 ret
= pthread_create(&health_thread
, NULL
,
2835 thread_manage_health
, (void *) NULL
);
2837 PERROR("pthread_create health");
2841 /* Setup the dispatcher thread */
2842 ret
= pthread_create(&dispatcher_thread
, NULL
,
2843 relay_thread_dispatcher
, (void *) NULL
);
2845 PERROR("pthread_create dispatcher");
2846 goto exit_dispatcher
;
2849 /* Setup the worker thread */
2850 ret
= pthread_create(&worker_thread
, NULL
,
2851 relay_thread_worker
, (void *) relay_ctx
);
2853 PERROR("pthread_create worker");
2857 /* Setup the listener thread */
2858 ret
= pthread_create(&listener_thread
, NULL
,
2859 relay_thread_listener
, (void *) NULL
);
2861 PERROR("pthread_create listener");
2865 ret
= live_start_threads(live_uri
, relay_ctx
);
2867 ERR("Starting live viewer threads");
2872 ret
= pthread_join(listener_thread
, &status
);
2874 PERROR("pthread_join");
2875 goto error
; /* join error, exit without cleanup */
2879 ret
= pthread_join(worker_thread
, &status
);
2881 PERROR("pthread_join");
2882 goto error
; /* join error, exit without cleanup */
2886 ret
= pthread_join(dispatcher_thread
, &status
);
2888 PERROR("pthread_join");
2889 goto error
; /* join error, exit without cleanup */
2893 ret
= pthread_join(health_thread
, &status
);
2895 PERROR("pthread_join health thread");
2896 goto error
; /* join error, exit without cleanup */
2900 * Stop live threads only after joining other threads.
2902 live_stop_threads();
2905 utils_close_pipe(health_quit_pipe
);
2908 health_app_destroy(health_relayd
);
2910 exit_health_app_create
:
2911 lttng_ht_destroy(viewer_streams_ht
);
2913 exit_relay_ctx_viewer_streams
:
2914 lttng_ht_destroy(relay_streams_ht
);
2916 exit_relay_ctx_streams
:
2917 lttng_ht_destroy(relay_ctx
->sessions_ht
);
2919 exit_relay_ctx_sessions
: