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>
37 #include <sys/resource.h>
39 #include <urcu/futex.h>
40 #include <urcu/uatomic.h>
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/config/session-config.h>
60 #include <common/dynamic-buffer.h>
61 #include <common/buffer-view.h>
62 #include <urcu/rculist.h>
66 #include "ctf-trace.h"
69 #include "lttng-relayd.h"
71 #include "health-relayd.h"
72 #include "testpoint.h"
73 #include "viewer-stream.h"
76 #include "connection.h"
77 #include "tracefile-array.h"
78 #include "tcp_keep_alive.h"
80 enum relay_connection_status
{
81 RELAY_CONNECTION_STATUS_OK
,
82 /* An error occured while processing an event on the connection. */
83 RELAY_CONNECTION_STATUS_ERROR
,
84 /* Connection closed/shutdown cleanly. */
85 RELAY_CONNECTION_STATUS_CLOSED
,
88 /* command line options */
89 char *opt_output_path
, *opt_working_directory
;
90 static int opt_daemon
, opt_background
, opt_print_version
;
91 int opt_group_output_by_session
;
92 int opt_group_output_by_host
;
95 * We need to wait for listener and live listener threads, as well as
96 * health check thread, before being ready to signal readiness.
98 #define NR_LTTNG_RELAY_READY 3
99 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
101 /* Size of receive buffer. */
102 #define RECV_DATA_BUFFER_SIZE 65536
104 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
105 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
107 static struct lttng_uri
*control_uri
;
108 static struct lttng_uri
*data_uri
;
109 static struct lttng_uri
*live_uri
;
111 const char *progname
;
113 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
114 static int tracing_group_name_override
;
116 const char * const config_section_name
= "relayd";
119 * Quit pipe for all threads. This permits a single cancellation point
120 * for all threads when receiving an event on the pipe.
122 int thread_quit_pipe
[2] = { -1, -1 };
125 * This pipe is used to inform the worker thread that a command is queued and
126 * ready to be processed.
128 static int relay_conn_pipe
[2] = { -1, -1 };
130 /* Shared between threads */
131 static int dispatch_thread_exit
;
133 static pthread_t listener_thread
;
134 static pthread_t dispatcher_thread
;
135 static pthread_t worker_thread
;
136 static pthread_t health_thread
;
139 * last_relay_stream_id_lock protects last_relay_stream_id increment
140 * atomicity on 32-bit architectures.
142 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
143 static uint64_t last_relay_stream_id
;
146 * Relay command queue.
148 * The relay_thread_listener and relay_thread_dispatcher communicate with this
151 static struct relay_conn_queue relay_conn_queue
;
153 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
154 static unsigned int lttng_opt_fd_cap
;
156 /* Global relay stream hash table. */
157 struct lttng_ht
*relay_streams_ht
;
159 /* Global relay viewer stream hash table. */
160 struct lttng_ht
*viewer_streams_ht
;
162 /* Global relay sessions hash table. */
163 struct lttng_ht
*sessions_ht
;
165 /* Relayd health monitoring */
166 struct health_app
*health_relayd
;
168 /* Global fd tracker. */
169 struct fd_tracker
*the_fd_tracker
;
171 static struct option long_options
[] = {
172 { "control-port", 1, 0, 'C', },
173 { "data-port", 1, 0, 'D', },
174 { "live-port", 1, 0, 'L', },
175 { "daemonize", 0, 0, 'd', },
176 { "background", 0, 0, 'b', },
177 { "group", 1, 0, 'g', },
178 { "fd-cap", 1, 0, '\0', },
179 { "help", 0, 0, 'h', },
180 { "output", 1, 0, 'o', },
181 { "verbose", 0, 0, 'v', },
182 { "config", 1, 0, 'f' },
183 { "version", 0, 0, 'V' },
184 { "working-directory", 1, 0, 'w', },
185 { "group-output-by-session", 0, 0, 's', },
186 { "group-output-by-host", 0, 0, 'p', },
190 static const char *config_ignore_options
[] = { "help", "config", "version" };
192 static void print_version(void) {
193 fprintf(stdout
, "%s\n", VERSION
);
196 static void relayd_config_log(void)
198 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
199 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
200 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
201 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
202 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
204 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
205 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
210 * Take an option from the getopt output and set it in the right variable to be
213 * Return 0 on success else a negative value.
215 static int set_option(int opt
, const char *arg
, const char *optname
)
221 if (!strcmp(optname
, "fd-cap")) {
225 v
= strtoul(arg
, NULL
, 0);
226 if (errno
!= 0 || !isdigit(arg
[0])) {
227 ERR("Wrong value in --fd-cap parameter: %s", arg
);
231 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
232 ERR("File descriptor cap must be set to at least %d",
233 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
236 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
240 lttng_opt_fd_cap
= (unsigned int) v
;
241 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
244 fprintf(stderr
, "unknown option %s", optname
);
246 fprintf(stderr
, " with arg %s\n", arg
);
251 if (lttng_is_setuid_setgid()) {
252 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
253 "-C, --control-port");
255 ret
= uri_parse(arg
, &control_uri
);
257 ERR("Invalid control URI specified");
260 if (control_uri
->port
== 0) {
261 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
266 if (lttng_is_setuid_setgid()) {
267 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
270 ret
= uri_parse(arg
, &data_uri
);
272 ERR("Invalid data URI specified");
275 if (data_uri
->port
== 0) {
276 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
281 if (lttng_is_setuid_setgid()) {
282 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
285 ret
= uri_parse(arg
, &live_uri
);
287 ERR("Invalid live URI specified");
290 if (live_uri
->port
== 0) {
291 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
302 if (lttng_is_setuid_setgid()) {
303 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
306 tracing_group_name
= strdup(arg
);
307 if (tracing_group_name
== NULL
) {
312 tracing_group_name_override
= 1;
316 ret
= utils_show_man_page(8, "lttng-relayd");
318 ERR("Cannot view man page lttng-relayd(8)");
323 opt_print_version
= 1;
326 if (lttng_is_setuid_setgid()) {
327 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
330 ret
= asprintf(&opt_output_path
, "%s", arg
);
333 PERROR("asprintf opt_output_path");
339 if (lttng_is_setuid_setgid()) {
340 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
341 "-w, --working-directory");
343 ret
= asprintf(&opt_working_directory
, "%s", arg
);
346 PERROR("asprintf working_directory");
353 /* Verbose level can increase using multiple -v */
355 lttng_opt_verbose
= config_parse_value(arg
);
357 /* Only 3 level of verbosity (-vvv). */
358 if (lttng_opt_verbose
< 3) {
359 lttng_opt_verbose
+= 1;
364 if (opt_group_output_by_host
) {
365 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
368 opt_group_output_by_session
= 1;
371 if (opt_group_output_by_session
) {
372 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
375 opt_group_output_by_host
= 1;
378 /* Unknown option or other error.
379 * Error is printed by getopt, just return */
392 * config_entry_handler_cb used to handle options read from a config file.
393 * See config_entry_handler_cb comment in common/config/session-config.h for the
394 * return value conventions.
396 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
400 if (!entry
|| !entry
->name
|| !entry
->value
) {
405 /* Check if the option is to be ignored */
406 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
407 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
412 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
413 /* Ignore if entry name is not fully matched. */
414 if (strcmp(entry
->name
, long_options
[i
].name
)) {
419 * If the option takes no argument on the command line,
420 * we have to check if the value is "true". We support
421 * non-zero numeric values, true, on and yes.
423 if (!long_options
[i
].has_arg
) {
424 ret
= config_parse_value(entry
->value
);
427 WARN("Invalid configuration value \"%s\" for option %s",
428 entry
->value
, entry
->name
);
430 /* False, skip boolean config option. */
435 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
439 WARN("Unrecognized option \"%s\" in daemon configuration file.",
446 static void parse_env_options(void)
450 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
452 opt_working_directory
= value
;
456 static int set_options(int argc
, char **argv
)
458 int c
, ret
= 0, option_index
= 0, retval
= 0;
459 int orig_optopt
= optopt
, orig_optind
= optind
;
460 char *default_address
, *optstring
;
461 const char *config_path
= NULL
;
463 optstring
= utils_generate_optstring(long_options
,
464 sizeof(long_options
) / sizeof(struct option
));
470 /* Check for the --config option */
472 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
473 &option_index
)) != -1) {
477 } else if (c
!= 'f') {
481 if (lttng_is_setuid_setgid()) {
482 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
485 config_path
= utils_expand_path(optarg
);
487 ERR("Failed to resolve path: %s", optarg
);
492 ret
= config_get_section_entries(config_path
, config_section_name
,
493 config_entry_handler
, NULL
);
496 ERR("Invalid configuration option at line %i", ret
);
502 /* Reset getopt's global state */
503 optopt
= orig_optopt
;
504 optind
= orig_optind
;
506 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
511 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
518 /* assign default values */
519 if (control_uri
== NULL
) {
520 ret
= asprintf(&default_address
,
521 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
522 DEFAULT_NETWORK_CONTROL_PORT
);
524 PERROR("asprintf default data address");
529 ret
= uri_parse(default_address
, &control_uri
);
530 free(default_address
);
532 ERR("Invalid control URI specified");
537 if (data_uri
== NULL
) {
538 ret
= asprintf(&default_address
,
539 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
540 DEFAULT_NETWORK_DATA_PORT
);
542 PERROR("asprintf default data address");
547 ret
= uri_parse(default_address
, &data_uri
);
548 free(default_address
);
550 ERR("Invalid data URI specified");
555 if (live_uri
== NULL
) {
556 ret
= asprintf(&default_address
,
557 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
558 DEFAULT_NETWORK_VIEWER_PORT
);
560 PERROR("asprintf default viewer control address");
565 ret
= uri_parse(default_address
, &live_uri
);
566 free(default_address
);
568 ERR("Invalid viewer control URI specified");
573 if (lttng_opt_fd_cap
== 0) {
575 struct rlimit rlimit
;
577 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
579 PERROR("Failed to get file descriptor limit");
583 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
586 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
587 /* Group by host by default */
588 opt_group_output_by_host
= 1;
596 static void print_global_objects(void)
598 print_viewer_streams();
599 print_relay_streams();
606 static void relayd_cleanup(void)
608 print_global_objects();
612 if (viewer_streams_ht
)
613 lttng_ht_destroy(viewer_streams_ht
);
614 if (relay_streams_ht
)
615 lttng_ht_destroy(relay_streams_ht
);
617 lttng_ht_destroy(sessions_ht
);
619 /* free the dynamically allocated opt_output_path */
620 free(opt_output_path
);
622 /* Close thread quit pipes */
623 utils_close_pipe(thread_quit_pipe
);
625 uri_free(control_uri
);
627 /* Live URI is freed in the live thread. */
629 if (tracing_group_name_override
) {
630 free((void *) tracing_group_name
);
632 fd_tracker_log(the_fd_tracker
);
636 * Write to writable pipe used to notify a thread.
638 static int notify_thread_pipe(int wpipe
)
642 ret
= lttng_write(wpipe
, "!", 1);
644 PERROR("write poll pipe");
652 static int notify_health_quit_pipe(int *pipe
)
656 ret
= lttng_write(pipe
[1], "4", 1);
658 PERROR("write relay health quit");
667 * Stop all relayd and relayd-live threads.
669 int lttng_relay_stop_threads(void)
673 /* Stopping all threads */
674 DBG("Terminating all threads");
675 if (notify_thread_pipe(thread_quit_pipe
[1])) {
676 ERR("write error on thread quit pipe");
680 if (notify_health_quit_pipe(health_quit_pipe
)) {
681 ERR("write error on health quit pipe");
684 /* Dispatch thread */
685 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
686 futex_nto1_wake(&relay_conn_queue
.futex
);
688 if (relayd_live_stop()) {
689 ERR("Error stopping live threads");
696 * Signal handler for the daemon
698 * Simply stop all worker threads, leaving main() return gracefully after
699 * joining all threads and calling cleanup().
701 static void sighandler(int sig
)
705 DBG("SIGINT caught");
706 if (lttng_relay_stop_threads()) {
707 ERR("Error stopping threads");
711 DBG("SIGTERM caught");
712 if (lttng_relay_stop_threads()) {
713 ERR("Error stopping threads");
717 CMM_STORE_SHARED(recv_child_signal
, 1);
725 * Setup signal handler for :
726 * SIGINT, SIGTERM, SIGPIPE
728 static int set_signal_handler(void)
734 if ((ret
= sigemptyset(&sigset
)) < 0) {
735 PERROR("sigemptyset");
742 sa
.sa_handler
= sighandler
;
743 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
748 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
753 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
758 sa
.sa_handler
= SIG_IGN
;
759 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
764 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
769 void lttng_relay_notify_ready(void)
771 /* Notify the parent of the fork() process that we are ready. */
772 if (opt_daemon
|| opt_background
) {
773 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
774 kill(child_ppid
, SIGUSR1
);
780 * Init thread quit pipe.
782 * Return -1 on error or 0 if all pipes are created.
784 static int init_thread_quit_pipe(void)
788 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
794 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
796 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
800 if (events
== NULL
|| size
== 0) {
805 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
811 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
823 * Check if the thread quit pipe was triggered.
825 * Return 1 if it was triggered else 0;
827 static int check_thread_quit_pipe(int fd
, uint32_t events
)
829 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
837 * Create and init socket from uri.
839 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
842 struct lttcomm_sock
*sock
= NULL
;
844 sock
= lttcomm_alloc_sock_from_uri(uri
);
846 ERR("Allocating socket");
850 ret
= lttcomm_create_sock(sock
);
854 DBG("Listening on sock %d", sock
->fd
);
856 ret
= sock
->ops
->bind(sock
);
861 ret
= sock
->ops
->listen(sock
, -1);
871 lttcomm_destroy_sock(sock
);
877 * This thread manages the listening for new connections on the network
879 static void *relay_thread_listener(void *data
)
881 int i
, ret
, pollfd
, err
= -1;
882 uint32_t revents
, nb_fd
;
883 struct lttng_poll_event events
;
884 struct lttcomm_sock
*control_sock
, *data_sock
;
886 DBG("[thread] Relay listener started");
888 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
890 health_code_update();
892 control_sock
= relay_socket_create(control_uri
);
894 goto error_sock_control
;
897 data_sock
= relay_socket_create(data_uri
);
899 goto error_sock_relay
;
903 * Pass 3 as size here for the thread quit pipe, control and
906 ret
= create_thread_poll_set(&events
, 3);
908 goto error_create_poll
;
911 /* Add the control socket */
912 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
917 /* Add the data socket */
918 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
923 lttng_relay_notify_ready();
925 if (testpoint(relayd_thread_listener
)) {
926 goto error_testpoint
;
930 health_code_update();
932 DBG("Listener accepting connections");
936 ret
= lttng_poll_wait(&events
, -1);
940 * Restart interrupted system call.
942 if (errno
== EINTR
) {
950 DBG("Relay new connection received");
951 for (i
= 0; i
< nb_fd
; i
++) {
952 health_code_update();
954 /* Fetch once the poll data */
955 revents
= LTTNG_POLL_GETEV(&events
, i
);
956 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
960 * No activity for this FD (poll
966 /* Thread quit pipe has been closed. Killing thread. */
967 ret
= check_thread_quit_pipe(pollfd
, revents
);
973 if (revents
& LPOLLIN
) {
975 * A new connection is requested, therefore a
976 * sessiond/consumerd connection is allocated in
977 * this thread, enqueued to a global queue and
978 * dequeued (and freed) in the worker thread.
981 struct relay_connection
*new_conn
;
982 struct lttcomm_sock
*newsock
;
983 enum connection_type type
;
985 if (pollfd
== data_sock
->fd
) {
987 newsock
= data_sock
->ops
->accept(data_sock
);
988 DBG("Relay data connection accepted, socket %d",
991 assert(pollfd
== control_sock
->fd
);
992 type
= RELAY_CONTROL
;
993 newsock
= control_sock
->ops
->accept(control_sock
);
994 DBG("Relay control connection accepted, socket %d",
998 PERROR("accepting sock");
1002 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1005 PERROR("setsockopt inet");
1006 lttcomm_destroy_sock(newsock
);
1010 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1012 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1014 lttcomm_destroy_sock(newsock
);
1018 new_conn
= connection_create(newsock
, type
);
1020 lttcomm_destroy_sock(newsock
);
1024 /* Enqueue request for the dispatcher thread. */
1025 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1029 * Wake the dispatch queue futex.
1030 * Implicit memory barrier with the
1031 * exchange in cds_wfcq_enqueue.
1033 futex_nto1_wake(&relay_conn_queue
.futex
);
1034 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1035 ERR("socket poll error");
1038 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1048 lttng_poll_clean(&events
);
1050 if (data_sock
->fd
>= 0) {
1051 ret
= data_sock
->ops
->close(data_sock
);
1056 lttcomm_destroy_sock(data_sock
);
1058 if (control_sock
->fd
>= 0) {
1059 ret
= control_sock
->ops
->close(control_sock
);
1064 lttcomm_destroy_sock(control_sock
);
1068 ERR("Health error occurred in %s", __func__
);
1070 health_unregister(health_relayd
);
1071 DBG("Relay listener thread cleanup complete");
1072 lttng_relay_stop_threads();
1077 * This thread manages the dispatching of the requests to worker threads
1079 static void *relay_thread_dispatcher(void *data
)
1083 struct cds_wfcq_node
*node
;
1084 struct relay_connection
*new_conn
= NULL
;
1086 DBG("[thread] Relay dispatcher started");
1088 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1090 if (testpoint(relayd_thread_dispatcher
)) {
1091 goto error_testpoint
;
1094 health_code_update();
1097 health_code_update();
1099 /* Atomically prepare the queue futex */
1100 futex_nto1_prepare(&relay_conn_queue
.futex
);
1102 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1107 health_code_update();
1109 /* Dequeue commands */
1110 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1111 &relay_conn_queue
.tail
);
1113 DBG("Woken up but nothing in the relay command queue");
1114 /* Continue thread execution */
1117 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1119 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1122 * Inform worker thread of the new request. This
1123 * call is blocking so we can be assured that
1124 * the data will be read at some point in time
1125 * or wait to the end of the world :)
1127 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1129 PERROR("write connection pipe");
1130 connection_put(new_conn
);
1133 } while (node
!= NULL
);
1135 /* Futex wait on queue. Blocking call on futex() */
1136 health_poll_entry();
1137 futex_nto1_wait(&relay_conn_queue
.futex
);
1141 /* Normal exit, no error */
1148 ERR("Health error occurred in %s", __func__
);
1150 health_unregister(health_relayd
);
1151 DBG("Dispatch thread dying");
1152 lttng_relay_stop_threads();
1157 * Set index data from the control port to a given index object.
1159 static int set_index_control_data(struct relay_index
*index
,
1160 struct lttcomm_relayd_index
*data
,
1161 struct relay_connection
*conn
)
1163 struct ctf_packet_index index_data
;
1166 * The index on disk is encoded in big endian.
1168 index_data
.packet_size
= htobe64(data
->packet_size
);
1169 index_data
.content_size
= htobe64(data
->content_size
);
1170 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1171 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1172 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1173 index_data
.stream_id
= htobe64(data
->stream_id
);
1175 if (conn
->minor
>= 8) {
1176 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1177 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1180 return relay_index_set_data(index
, &index_data
);
1184 * Handle the RELAYD_CREATE_SESSION command.
1186 * On success, send back the session id or else return a negative value.
1188 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1189 struct relay_connection
*conn
,
1190 const struct lttng_buffer_view
*payload
)
1194 struct relay_session
*session
;
1195 struct lttcomm_relayd_status_session reply
;
1196 char session_name
[LTTNG_NAME_MAX
];
1197 char hostname
[LTTNG_HOST_NAME_MAX
];
1198 uint32_t live_timer
= 0;
1199 bool snapshot
= false;
1201 memset(session_name
, 0, LTTNG_NAME_MAX
);
1202 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1204 memset(&reply
, 0, sizeof(reply
));
1206 switch (conn
->minor
) {
1211 case 4: /* LTTng sessiond 2.4 */
1213 ret
= cmd_create_session_2_4(payload
, session_name
,
1214 hostname
, &live_timer
, &snapshot
);
1220 session
= session_create(session_name
, hostname
, live_timer
,
1221 snapshot
, conn
->major
, conn
->minor
);
1226 assert(!conn
->session
);
1227 conn
->session
= session
;
1228 DBG("Created session %" PRIu64
, session
->id
);
1230 reply
.session_id
= htobe64(session
->id
);
1234 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1236 reply
.ret_code
= htobe32(LTTNG_OK
);
1239 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1240 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1241 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1250 * When we have received all the streams and the metadata for a channel,
1251 * we make them visible to the viewer threads.
1253 static void publish_connection_local_streams(struct relay_connection
*conn
)
1255 struct relay_stream
*stream
;
1256 struct relay_session
*session
= conn
->session
;
1259 * We publish all streams belonging to a session atomically wrt
1262 pthread_mutex_lock(&session
->lock
);
1264 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1266 stream_publish(stream
);
1271 * Inform the viewer that there are new streams in the session.
1273 if (session
->viewer_attached
) {
1274 uatomic_set(&session
->new_streams
, 1);
1276 pthread_mutex_unlock(&session
->lock
);
1280 * relay_add_stream: allocate a new stream for a session
1282 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1283 struct relay_connection
*conn
,
1284 const struct lttng_buffer_view
*payload
)
1288 struct relay_session
*session
= conn
->session
;
1289 struct relay_stream
*stream
= NULL
;
1290 struct lttcomm_relayd_status_stream reply
;
1291 struct ctf_trace
*trace
= NULL
;
1292 uint64_t stream_handle
= -1ULL;
1293 char *path_name
= NULL
, *channel_name
= NULL
;
1294 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1296 if (!session
|| !conn
->version_check_done
) {
1297 ERR("Trying to add a stream before version check");
1299 goto end_no_session
;
1302 switch (session
->minor
) {
1303 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1304 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1305 &channel_name
, session
);
1307 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1309 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1310 &channel_name
, &tracefile_size
, &tracefile_count
,
1318 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1322 /* This stream here has one reference on the trace. */
1324 pthread_mutex_lock(&last_relay_stream_id_lock
);
1325 stream_handle
= ++last_relay_stream_id
;
1326 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1328 /* We pass ownership of path_name and channel_name. */
1329 stream
= stream_create(trace
, stream_handle
, path_name
,
1330 channel_name
, tracefile_size
, tracefile_count
);
1332 channel_name
= NULL
;
1335 * Streams are the owners of their trace. Reference to trace is
1336 * kept within stream_create().
1338 ctf_trace_put(trace
);
1341 memset(&reply
, 0, sizeof(reply
));
1342 reply
.handle
= htobe64(stream_handle
);
1344 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1346 reply
.ret_code
= htobe32(LTTNG_OK
);
1349 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1350 sizeof(struct lttcomm_relayd_status_stream
), 0);
1351 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1352 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1364 * relay_close_stream: close a specific stream
1366 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1367 struct relay_connection
*conn
,
1368 const struct lttng_buffer_view
*payload
)
1372 struct relay_session
*session
= conn
->session
;
1373 struct lttcomm_relayd_close_stream stream_info
;
1374 struct lttcomm_relayd_generic_reply reply
;
1375 struct relay_stream
*stream
;
1377 DBG("Close stream received");
1379 if (!session
|| !conn
->version_check_done
) {
1380 ERR("Trying to close a stream before version check");
1382 goto end_no_session
;
1385 if (payload
->size
< sizeof(stream_info
)) {
1386 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1387 sizeof(stream_info
), payload
->size
);
1389 goto end_no_session
;
1391 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1392 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1393 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1395 stream
= stream_get_by_id(stream_info
.stream_id
);
1402 * Set last_net_seq_num before the close flag. Required by data
1405 pthread_mutex_lock(&stream
->lock
);
1406 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1407 pthread_mutex_unlock(&stream
->lock
);
1410 * This is one of the conditions which may trigger a stream close
1411 * with the others being:
1412 * 1) A close command is received for a stream
1413 * 2) The control connection owning the stream is closed
1414 * 3) We have received all of the stream's data _after_ a close
1417 try_stream_close(stream
);
1418 if (stream
->is_metadata
) {
1419 struct relay_viewer_stream
*vstream
;
1421 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1423 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1425 * Since all the metadata has been sent to the
1426 * viewer and that we have a request to close
1427 * its stream, we can safely teardown the
1428 * corresponding metadata viewer stream.
1430 viewer_stream_put(vstream
);
1432 /* Put local reference. */
1433 viewer_stream_put(vstream
);
1440 memset(&reply
, 0, sizeof(reply
));
1442 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1444 reply
.ret_code
= htobe32(LTTNG_OK
);
1446 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1447 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1448 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1449 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1459 * relay_reset_metadata: reset a metadata stream
1462 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1463 struct relay_connection
*conn
,
1464 const struct lttng_buffer_view
*payload
)
1468 struct relay_session
*session
= conn
->session
;
1469 struct lttcomm_relayd_reset_metadata stream_info
;
1470 struct lttcomm_relayd_generic_reply reply
;
1471 struct relay_stream
*stream
;
1473 DBG("Reset metadata received");
1475 if (!session
|| !conn
->version_check_done
) {
1476 ERR("Trying to reset a metadata stream before version check");
1478 goto end_no_session
;
1481 if (payload
->size
< sizeof(stream_info
)) {
1482 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1483 sizeof(stream_info
), payload
->size
);
1485 goto end_no_session
;
1487 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1488 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1489 stream_info
.version
= be64toh(stream_info
.version
);
1491 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1493 /* Unsupported for live sessions for now. */
1494 if (session
->live_timer
!= 0) {
1499 stream
= stream_get_by_id(stream_info
.stream_id
);
1504 pthread_mutex_lock(&stream
->lock
);
1505 if (!stream
->is_metadata
) {
1510 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1511 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1512 &stream
->stream_fd
->fd
);
1514 ERR("Failed to rotate metadata file %s of channel %s",
1515 stream
->path_name
, stream
->channel_name
);
1520 pthread_mutex_unlock(&stream
->lock
);
1524 memset(&reply
, 0, sizeof(reply
));
1526 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1528 reply
.ret_code
= htobe32(LTTNG_OK
);
1530 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1531 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1532 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1533 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1543 * relay_unknown_command: send -1 if received unknown command
1545 static void relay_unknown_command(struct relay_connection
*conn
)
1547 struct lttcomm_relayd_generic_reply reply
;
1550 memset(&reply
, 0, sizeof(reply
));
1551 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1552 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1553 if (send_ret
< sizeof(reply
)) {
1554 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1559 * relay_start: send an acknowledgment to the client to tell if we are
1560 * ready to receive data. We are ready if a session is established.
1562 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1563 struct relay_connection
*conn
,
1564 const struct lttng_buffer_view
*payload
)
1568 struct lttcomm_relayd_generic_reply reply
;
1569 struct relay_session
*session
= conn
->session
;
1572 DBG("Trying to start the streaming without a session established");
1573 ret
= htobe32(LTTNG_ERR_UNK
);
1576 memset(&reply
, 0, sizeof(reply
));
1577 reply
.ret_code
= htobe32(LTTNG_OK
);
1578 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1580 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1581 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1590 * Append padding to the file pointed by the file descriptor fd.
1592 static int write_padding_to_file(int fd
, uint32_t size
)
1601 zeros
= zmalloc(size
);
1602 if (zeros
== NULL
) {
1603 PERROR("zmalloc zeros for padding");
1608 ret
= lttng_write(fd
, zeros
, size
);
1610 PERROR("write padding to file");
1620 * relay_recv_metadata: receive the metadata for the session.
1622 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1623 struct relay_connection
*conn
,
1624 const struct lttng_buffer_view
*payload
)
1628 struct relay_session
*session
= conn
->session
;
1629 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1630 struct relay_stream
*metadata_stream
;
1631 uint64_t metadata_payload_size
;
1634 ERR("Metadata sent before version check");
1639 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1640 ERR("Incorrect data size");
1644 metadata_payload_size
= recv_hdr
->data_size
-
1645 sizeof(struct lttcomm_relayd_metadata_payload
);
1647 memcpy(&metadata_payload_header
, payload
->data
,
1648 sizeof(metadata_payload_header
));
1649 metadata_payload_header
.stream_id
= be64toh(
1650 metadata_payload_header
.stream_id
);
1651 metadata_payload_header
.padding_size
= be32toh(
1652 metadata_payload_header
.padding_size
);
1654 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1655 if (!metadata_stream
) {
1660 pthread_mutex_lock(&metadata_stream
->lock
);
1662 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1663 payload
->data
+ sizeof(metadata_payload_header
),
1664 metadata_payload_size
);
1665 if (size_ret
< metadata_payload_size
) {
1666 ERR("Relay error writing metadata on file");
1671 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1672 metadata_payload_header
.padding_size
);
1673 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1678 metadata_stream
->metadata_received
+=
1679 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1680 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1681 metadata_stream
->metadata_received
);
1684 pthread_mutex_unlock(&metadata_stream
->lock
);
1685 stream_put(metadata_stream
);
1691 * relay_send_version: send relayd version number
1693 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1694 struct relay_connection
*conn
,
1695 const struct lttng_buffer_view
*payload
)
1699 struct lttcomm_relayd_version reply
, msg
;
1700 bool compatible
= true;
1702 conn
->version_check_done
= true;
1704 /* Get version from the other side. */
1705 if (payload
->size
< sizeof(msg
)) {
1706 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1707 sizeof(msg
), payload
->size
);
1712 memcpy(&msg
, payload
->data
, sizeof(msg
));
1713 msg
.major
= be32toh(msg
.major
);
1714 msg
.minor
= be32toh(msg
.minor
);
1716 memset(&reply
, 0, sizeof(reply
));
1717 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1718 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1720 /* Major versions must be the same */
1721 if (reply
.major
!= msg
.major
) {
1722 DBG("Incompatible major versions (%u vs %u), deleting session",
1723 reply
.major
, msg
.major
);
1727 conn
->major
= reply
.major
;
1728 /* We adapt to the lowest compatible version */
1729 if (reply
.minor
<= msg
.minor
) {
1730 conn
->minor
= reply
.minor
;
1732 conn
->minor
= msg
.minor
;
1735 reply
.major
= htobe32(reply
.major
);
1736 reply
.minor
= htobe32(reply
.minor
);
1737 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1739 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1740 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1753 DBG("Version check done using protocol %u.%u", conn
->major
,
1761 * Check for data pending for a given stream id from the session daemon.
1763 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1764 struct relay_connection
*conn
,
1765 const struct lttng_buffer_view
*payload
)
1767 struct relay_session
*session
= conn
->session
;
1768 struct lttcomm_relayd_data_pending msg
;
1769 struct lttcomm_relayd_generic_reply reply
;
1770 struct relay_stream
*stream
;
1774 DBG("Data pending command received");
1776 if (!session
|| !conn
->version_check_done
) {
1777 ERR("Trying to check for data before version check");
1779 goto end_no_session
;
1782 if (payload
->size
< sizeof(msg
)) {
1783 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1784 sizeof(msg
), payload
->size
);
1786 goto end_no_session
;
1788 memcpy(&msg
, payload
->data
, sizeof(msg
));
1789 msg
.stream_id
= be64toh(msg
.stream_id
);
1790 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1792 stream
= stream_get_by_id(msg
.stream_id
);
1793 if (stream
== NULL
) {
1798 pthread_mutex_lock(&stream
->lock
);
1800 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1801 " and last_seq %" PRIu64
, msg
.stream_id
,
1802 stream
->prev_seq
, msg
.last_net_seq_num
);
1804 /* Avoid wrapping issue */
1805 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1806 /* Data has in fact been written and is NOT pending */
1809 /* Data still being streamed thus pending */
1813 stream
->data_pending_check_done
= true;
1814 pthread_mutex_unlock(&stream
->lock
);
1819 memset(&reply
, 0, sizeof(reply
));
1820 reply
.ret_code
= htobe32(ret
);
1821 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1822 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1823 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1833 * Wait for the control socket to reach a quiescent state.
1835 * Note that for now, when receiving this command from the session
1836 * daemon, this means that every subsequent commands or data received on
1837 * the control socket has been handled. So, this is why we simply return
1840 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1841 struct relay_connection
*conn
,
1842 const struct lttng_buffer_view
*payload
)
1846 struct relay_stream
*stream
;
1847 struct lttcomm_relayd_quiescent_control msg
;
1848 struct lttcomm_relayd_generic_reply reply
;
1850 DBG("Checking quiescent state on control socket");
1852 if (!conn
->session
|| !conn
->version_check_done
) {
1853 ERR("Trying to check for data before version check");
1855 goto end_no_session
;
1858 if (payload
->size
< sizeof(msg
)) {
1859 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1860 sizeof(msg
), payload
->size
);
1862 goto end_no_session
;
1864 memcpy(&msg
, payload
->data
, sizeof(msg
));
1865 msg
.stream_id
= be64toh(msg
.stream_id
);
1867 stream
= stream_get_by_id(msg
.stream_id
);
1871 pthread_mutex_lock(&stream
->lock
);
1872 stream
->data_pending_check_done
= true;
1873 pthread_mutex_unlock(&stream
->lock
);
1875 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1878 memset(&reply
, 0, sizeof(reply
));
1879 reply
.ret_code
= htobe32(LTTNG_OK
);
1880 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1881 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1882 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1894 * Initialize a data pending command. This means that a consumer is about
1895 * to ask for data pending for each stream it holds. Simply iterate over
1896 * all streams of a session and set the data_pending_check_done flag.
1898 * This command returns to the client a LTTNG_OK code.
1900 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1901 struct relay_connection
*conn
,
1902 const struct lttng_buffer_view
*payload
)
1906 struct lttng_ht_iter iter
;
1907 struct lttcomm_relayd_begin_data_pending msg
;
1908 struct lttcomm_relayd_generic_reply reply
;
1909 struct relay_stream
*stream
;
1914 DBG("Init streams for data pending");
1916 if (!conn
->session
|| !conn
->version_check_done
) {
1917 ERR("Trying to check for data before version check");
1919 goto end_no_session
;
1922 if (payload
->size
< sizeof(msg
)) {
1923 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1924 sizeof(msg
), payload
->size
);
1926 goto end_no_session
;
1928 memcpy(&msg
, payload
->data
, sizeof(msg
));
1929 msg
.session_id
= be64toh(msg
.session_id
);
1932 * Iterate over all streams to set the begin data pending flag.
1933 * For now, the streams are indexed by stream handle so we have
1934 * to iterate over all streams to find the one associated with
1935 * the right session_id.
1938 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1940 if (!stream_get(stream
)) {
1943 if (stream
->trace
->session
->id
== msg
.session_id
) {
1944 pthread_mutex_lock(&stream
->lock
);
1945 stream
->data_pending_check_done
= false;
1946 pthread_mutex_unlock(&stream
->lock
);
1947 DBG("Set begin data pending flag to stream %" PRIu64
,
1948 stream
->stream_handle
);
1954 memset(&reply
, 0, sizeof(reply
));
1955 /* All good, send back reply. */
1956 reply
.ret_code
= htobe32(LTTNG_OK
);
1958 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1959 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1960 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1972 * End data pending command. This will check, for a given session id, if
1973 * each stream associated with it has its data_pending_check_done flag
1974 * set. If not, this means that the client lost track of the stream but
1975 * the data is still being streamed on our side. In this case, we inform
1976 * the client that data is in flight.
1978 * Return to the client if there is data in flight or not with a ret_code.
1980 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1981 struct relay_connection
*conn
,
1982 const struct lttng_buffer_view
*payload
)
1986 struct lttng_ht_iter iter
;
1987 struct lttcomm_relayd_end_data_pending msg
;
1988 struct lttcomm_relayd_generic_reply reply
;
1989 struct relay_stream
*stream
;
1990 uint32_t is_data_inflight
= 0;
1992 DBG("End data pending command");
1994 if (!conn
->session
|| !conn
->version_check_done
) {
1995 ERR("Trying to check for data before version check");
1997 goto end_no_session
;
2000 if (payload
->size
< sizeof(msg
)) {
2001 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2002 sizeof(msg
), payload
->size
);
2004 goto end_no_session
;
2006 memcpy(&msg
, payload
->data
, sizeof(msg
));
2007 msg
.session_id
= be64toh(msg
.session_id
);
2010 * Iterate over all streams to see if the begin data pending
2014 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2016 if (!stream_get(stream
)) {
2019 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2023 pthread_mutex_lock(&stream
->lock
);
2024 if (!stream
->data_pending_check_done
) {
2025 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2026 is_data_inflight
= 1;
2027 DBG("Data is still in flight for stream %" PRIu64
,
2028 stream
->stream_handle
);
2029 pthread_mutex_unlock(&stream
->lock
);
2034 pthread_mutex_unlock(&stream
->lock
);
2039 memset(&reply
, 0, sizeof(reply
));
2040 /* All good, send back reply. */
2041 reply
.ret_code
= htobe32(is_data_inflight
);
2043 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2044 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2045 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2057 * Receive an index for a specific stream.
2059 * Return 0 on success else a negative value.
2061 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2062 struct relay_connection
*conn
,
2063 const struct lttng_buffer_view
*payload
)
2067 struct relay_session
*session
= conn
->session
;
2068 struct lttcomm_relayd_index index_info
;
2069 struct relay_index
*index
;
2070 struct lttcomm_relayd_generic_reply reply
;
2071 struct relay_stream
*stream
;
2076 DBG("Relay receiving index");
2078 if (!session
|| !conn
->version_check_done
) {
2079 ERR("Trying to close a stream before version check");
2081 goto end_no_session
;
2084 msg_len
= lttcomm_relayd_index_len(
2085 lttng_to_index_major(conn
->major
, conn
->minor
),
2086 lttng_to_index_minor(conn
->major
, conn
->minor
));
2087 if (payload
->size
< msg_len
) {
2088 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2089 msg_len
, payload
->size
);
2091 goto end_no_session
;
2093 memcpy(&index_info
, payload
->data
, msg_len
);
2094 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2095 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2096 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2097 index_info
.content_size
= be64toh(index_info
.content_size
);
2098 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2099 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2100 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2101 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2103 if (conn
->minor
>= 8) {
2104 index_info
.stream_instance_id
=
2105 be64toh(index_info
.stream_instance_id
);
2106 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2109 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2111 ERR("stream_get_by_id not found");
2115 pthread_mutex_lock(&stream
->lock
);
2117 /* Live beacon handling */
2118 if (index_info
.packet_size
== 0) {
2119 DBG("Received live beacon for stream %" PRIu64
,
2120 stream
->stream_handle
);
2123 * Only flag a stream inactive when it has already
2124 * received data and no indexes are in flight.
2126 if (stream
->index_received_seqcount
> 0
2127 && stream
->indexes_in_flight
== 0) {
2128 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2131 goto end_stream_put
;
2133 stream
->beacon_ts_end
= -1ULL;
2136 if (stream
->ctf_stream_id
== -1ULL) {
2137 stream
->ctf_stream_id
= index_info
.stream_id
;
2139 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2142 ERR("relay_index_get_by_id_or_create index NULL");
2143 goto end_stream_put
;
2145 if (set_index_control_data(index
, &index_info
, conn
)) {
2146 ERR("set_index_control_data error");
2147 relay_index_put(index
);
2149 goto end_stream_put
;
2151 ret
= relay_index_try_flush(index
);
2153 tracefile_array_commit_seq(stream
->tfa
);
2154 stream
->index_received_seqcount
++;
2155 } else if (ret
> 0) {
2159 ERR("relay_index_try_flush error %d", ret
);
2160 relay_index_put(index
);
2165 pthread_mutex_unlock(&stream
->lock
);
2170 memset(&reply
, 0, sizeof(reply
));
2172 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2174 reply
.ret_code
= htobe32(LTTNG_OK
);
2176 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2177 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2178 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2187 * Receive the streams_sent message.
2189 * Return 0 on success else a negative value.
2191 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2192 struct relay_connection
*conn
,
2193 const struct lttng_buffer_view
*payload
)
2197 struct lttcomm_relayd_generic_reply reply
;
2201 DBG("Relay receiving streams_sent");
2203 if (!conn
->session
|| !conn
->version_check_done
) {
2204 ERR("Trying to close a stream before version check");
2206 goto end_no_session
;
2210 * Publish every pending stream in the connection recv list which are
2211 * now ready to be used by the viewer.
2213 publish_connection_local_streams(conn
);
2215 memset(&reply
, 0, sizeof(reply
));
2216 reply
.ret_code
= htobe32(LTTNG_OK
);
2217 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2218 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2219 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2231 #define DBG_CMD(cmd_name, conn) \
2232 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2234 static int relay_process_control_command(struct relay_connection
*conn
,
2235 const struct lttcomm_relayd_hdr
*header
,
2236 const struct lttng_buffer_view
*payload
)
2240 switch (header
->cmd
) {
2241 case RELAYD_CREATE_SESSION
:
2242 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2243 ret
= relay_create_session(header
, conn
, payload
);
2245 case RELAYD_ADD_STREAM
:
2246 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2247 ret
= relay_add_stream(header
, conn
, payload
);
2249 case RELAYD_START_DATA
:
2250 DBG_CMD("RELAYD_START_DATA", conn
);
2251 ret
= relay_start(header
, conn
, payload
);
2253 case RELAYD_SEND_METADATA
:
2254 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2255 ret
= relay_recv_metadata(header
, conn
, payload
);
2257 case RELAYD_VERSION
:
2258 DBG_CMD("RELAYD_VERSION", conn
);
2259 ret
= relay_send_version(header
, conn
, payload
);
2261 case RELAYD_CLOSE_STREAM
:
2262 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2263 ret
= relay_close_stream(header
, conn
, payload
);
2265 case RELAYD_DATA_PENDING
:
2266 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2267 ret
= relay_data_pending(header
, conn
, payload
);
2269 case RELAYD_QUIESCENT_CONTROL
:
2270 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2271 ret
= relay_quiescent_control(header
, conn
, payload
);
2273 case RELAYD_BEGIN_DATA_PENDING
:
2274 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2275 ret
= relay_begin_data_pending(header
, conn
, payload
);
2277 case RELAYD_END_DATA_PENDING
:
2278 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2279 ret
= relay_end_data_pending(header
, conn
, payload
);
2281 case RELAYD_SEND_INDEX
:
2282 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2283 ret
= relay_recv_index(header
, conn
, payload
);
2285 case RELAYD_STREAMS_SENT
:
2286 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2287 ret
= relay_streams_sent(header
, conn
, payload
);
2289 case RELAYD_RESET_METADATA
:
2290 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2291 ret
= relay_reset_metadata(header
, conn
, payload
);
2293 case RELAYD_UPDATE_SYNC_INFO
:
2295 ERR("Received unknown command (%u)", header
->cmd
);
2296 relay_unknown_command(conn
);
2305 static enum relay_connection_status
relay_process_control_receive_payload(
2306 struct relay_connection
*conn
)
2309 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2310 struct lttng_dynamic_buffer
*reception_buffer
=
2311 &conn
->protocol
.ctrl
.reception_buffer
;
2312 struct ctrl_connection_state_receive_payload
*state
=
2313 &conn
->protocol
.ctrl
.state
.receive_payload
;
2314 struct lttng_buffer_view payload_view
;
2316 if (state
->left_to_receive
== 0) {
2317 /* Short-circuit for payload-less commands. */
2318 goto reception_complete
;
2320 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2321 reception_buffer
->data
+ state
->received
,
2322 state
->left_to_receive
, MSG_DONTWAIT
);
2324 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2325 PERROR("Unable to receive command payload on sock %d",
2327 status
= RELAY_CONNECTION_STATUS_ERROR
;
2330 } else if (ret
== 0) {
2331 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2332 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2337 assert(ret
<= state
->left_to_receive
);
2339 state
->left_to_receive
-= ret
;
2340 state
->received
+= ret
;
2342 if (state
->left_to_receive
> 0) {
2344 * Can't transition to the protocol's next state, wait to
2345 * receive the rest of the header.
2347 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2348 state
->received
, state
->left_to_receive
,
2354 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2355 conn
->sock
->fd
, state
->received
);
2357 * The payload required to process the command has been received.
2358 * A view to the reception buffer is forwarded to the various
2359 * commands and the state of the control is reset on success.
2361 * Commands are responsible for sending their reply to the peer.
2363 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2365 ret
= relay_process_control_command(conn
,
2366 &state
->header
, &payload_view
);
2368 status
= RELAY_CONNECTION_STATUS_ERROR
;
2372 ret
= connection_reset_protocol_state(conn
);
2374 status
= RELAY_CONNECTION_STATUS_ERROR
;
2380 static enum relay_connection_status
relay_process_control_receive_header(
2381 struct relay_connection
*conn
)
2384 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2385 struct lttcomm_relayd_hdr header
;
2386 struct lttng_dynamic_buffer
*reception_buffer
=
2387 &conn
->protocol
.ctrl
.reception_buffer
;
2388 struct ctrl_connection_state_receive_header
*state
=
2389 &conn
->protocol
.ctrl
.state
.receive_header
;
2391 assert(state
->left_to_receive
!= 0);
2393 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2394 reception_buffer
->data
+ state
->received
,
2395 state
->left_to_receive
, MSG_DONTWAIT
);
2397 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2398 PERROR("Unable to receive control command header on sock %d",
2400 status
= RELAY_CONNECTION_STATUS_ERROR
;
2403 } else if (ret
== 0) {
2404 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2405 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2410 assert(ret
<= state
->left_to_receive
);
2412 state
->left_to_receive
-= ret
;
2413 state
->received
+= ret
;
2415 if (state
->left_to_receive
> 0) {
2417 * Can't transition to the protocol's next state, wait to
2418 * receive the rest of the header.
2420 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2421 state
->received
, state
->left_to_receive
,
2426 /* Transition to next state: receiving the command's payload. */
2427 conn
->protocol
.ctrl
.state_id
=
2428 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2429 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2430 header
.circuit_id
= be64toh(header
.circuit_id
);
2431 header
.data_size
= be64toh(header
.data_size
);
2432 header
.cmd
= be32toh(header
.cmd
);
2433 header
.cmd_version
= be32toh(header
.cmd_version
);
2434 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2435 &header
, sizeof(header
));
2437 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2438 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2441 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2442 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2444 status
= RELAY_CONNECTION_STATUS_ERROR
;
2448 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2450 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2451 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2454 status
= RELAY_CONNECTION_STATUS_ERROR
;
2458 if (header
.data_size
== 0) {
2460 * Manually invoke the next state as the poll loop
2461 * will not wake-up to allow us to proceed further.
2463 status
= relay_process_control_receive_payload(conn
);
2470 * Process the commands received on the control socket
2472 static enum relay_connection_status
relay_process_control(
2473 struct relay_connection
*conn
)
2475 enum relay_connection_status status
;
2477 switch (conn
->protocol
.ctrl
.state_id
) {
2478 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2479 status
= relay_process_control_receive_header(conn
);
2481 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2482 status
= relay_process_control_receive_payload(conn
);
2485 ERR("Unknown control connection protocol state encountered.");
2493 * Handle index for a data stream.
2495 * Called with the stream lock held.
2497 * Return 0 on success else a negative value.
2499 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2503 uint64_t data_offset
;
2504 struct relay_index
*index
;
2506 /* Get data offset because we are about to update the index. */
2507 data_offset
= htobe64(stream
->tracefile_size_current
);
2509 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2510 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2513 * Lookup for an existing index for that stream id/sequence
2514 * number. If it exists, the control thread has already received the
2515 * data for it, thus we need to write it to disk.
2517 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2523 if (rotate_index
|| !stream
->index_file
) {
2524 uint32_t major
, minor
;
2526 /* Put ref on previous index_file. */
2527 if (stream
->index_file
) {
2528 lttng_index_file_put(stream
->index_file
);
2529 stream
->index_file
= NULL
;
2531 major
= stream
->trace
->session
->major
;
2532 minor
= stream
->trace
->session
->minor
;
2533 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2534 stream
->channel_name
,
2535 -1, -1, stream
->tracefile_size
,
2536 tracefile_array_get_file_index_head(stream
->tfa
),
2537 lttng_to_index_major(major
, minor
),
2538 lttng_to_index_minor(major
, minor
));
2539 if (!stream
->index_file
) {
2541 /* Put self-ref for this index due to error. */
2542 relay_index_put(index
);
2548 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2550 /* Put self-ref for this index due to error. */
2551 relay_index_put(index
);
2556 ret
= relay_index_try_flush(index
);
2558 tracefile_array_commit_seq(stream
->tfa
);
2559 stream
->index_received_seqcount
++;
2560 } else if (ret
> 0) {
2564 /* Put self-ref for this index due to error. */
2565 relay_index_put(index
);
2573 static enum relay_connection_status
relay_process_data_receive_header(
2574 struct relay_connection
*conn
)
2577 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2578 struct data_connection_state_receive_header
*state
=
2579 &conn
->protocol
.data
.state
.receive_header
;
2580 struct lttcomm_relayd_data_hdr header
;
2581 struct relay_stream
*stream
;
2583 assert(state
->left_to_receive
!= 0);
2585 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2586 state
->header_reception_buffer
+ state
->received
,
2587 state
->left_to_receive
, MSG_DONTWAIT
);
2589 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2590 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2591 status
= RELAY_CONNECTION_STATUS_ERROR
;
2594 } else if (ret
== 0) {
2595 /* Orderly shutdown. Not necessary to print an error. */
2596 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2597 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2602 assert(ret
<= state
->left_to_receive
);
2604 state
->left_to_receive
-= ret
;
2605 state
->received
+= ret
;
2607 if (state
->left_to_receive
> 0) {
2609 * Can't transition to the protocol's next state, wait to
2610 * receive the rest of the header.
2612 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2613 state
->received
, state
->left_to_receive
,
2619 /* Transition to next state: receiving the payload. */
2620 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2622 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2623 header
.circuit_id
= be64toh(header
.circuit_id
);
2624 header
.stream_id
= be64toh(header
.stream_id
);
2625 header
.data_size
= be32toh(header
.data_size
);
2626 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2627 header
.padding_size
= be32toh(header
.padding_size
);
2628 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2630 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2632 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2633 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2635 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2636 conn
->sock
->fd
, header
.circuit_id
,
2637 header
.stream_id
, header
.data_size
,
2638 header
.net_seq_num
, header
.padding_size
);
2640 stream
= stream_get_by_id(header
.stream_id
);
2642 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2644 /* Protocol error. */
2645 status
= RELAY_CONNECTION_STATUS_ERROR
;
2649 pthread_mutex_lock(&stream
->lock
);
2651 /* Check if a rotation is needed. */
2652 if (stream
->tracefile_size
> 0 &&
2653 (stream
->tracefile_size_current
+ header
.data_size
) >
2654 stream
->tracefile_size
) {
2655 uint64_t old_id
, new_id
;
2657 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2658 tracefile_array_file_rotate(stream
->tfa
);
2660 /* new_id is updated by utils_rotate_stream_file. */
2663 ret
= utils_rotate_stream_file(stream
->path_name
,
2664 stream
->channel_name
, stream
->tracefile_size
,
2665 stream
->tracefile_count
, -1,
2666 -1, stream
->stream_fd
->fd
,
2667 &new_id
, &stream
->stream_fd
->fd
);
2669 ERR("Failed to rotate stream output file");
2670 status
= RELAY_CONNECTION_STATUS_ERROR
;
2671 goto end_stream_unlock
;
2675 * Reset current size because we just performed a stream
2678 stream
->tracefile_size_current
= 0;
2679 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2684 pthread_mutex_unlock(&stream
->lock
);
2690 static enum relay_connection_status
relay_process_data_receive_payload(
2691 struct relay_connection
*conn
)
2694 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2695 struct relay_stream
*stream
;
2696 struct data_connection_state_receive_payload
*state
=
2697 &conn
->protocol
.data
.state
.receive_payload
;
2698 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2699 char data_buffer
[chunk_size
];
2700 bool partial_recv
= false;
2701 bool new_stream
= false, close_requested
= false;
2702 uint64_t left_to_receive
= state
->left_to_receive
;
2703 struct relay_session
*session
;
2705 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2706 state
->header
.stream_id
, state
->header
.net_seq_num
,
2707 state
->received
, left_to_receive
);
2709 stream
= stream_get_by_id(state
->header
.stream_id
);
2711 /* Protocol error. */
2712 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2713 state
->header
.stream_id
);
2714 status
= RELAY_CONNECTION_STATUS_ERROR
;
2718 pthread_mutex_lock(&stream
->lock
);
2719 session
= stream
->trace
->session
;
2720 if (!conn
->session
) {
2721 ret
= connection_set_session(conn
, session
);
2723 status
= RELAY_CONNECTION_STATUS_ERROR
;
2724 goto end_stream_unlock
;
2729 * The size of the "chunk" received on any iteration is bounded by:
2730 * - the data left to receive,
2731 * - the data immediately available on the socket,
2732 * - the on-stack data buffer
2734 while (left_to_receive
> 0 && !partial_recv
) {
2736 size_t recv_size
= min(left_to_receive
, chunk_size
);
2738 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2739 recv_size
, MSG_DONTWAIT
);
2741 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2742 PERROR("Socket %d error", conn
->sock
->fd
);
2743 status
= RELAY_CONNECTION_STATUS_ERROR
;
2745 goto end_stream_unlock
;
2746 } else if (ret
== 0) {
2747 /* No more data ready to be consumed on socket. */
2748 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2749 state
->header
.stream_id
);
2750 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2752 } else if (ret
< (int) recv_size
) {
2754 * All the data available on the socket has been
2757 partial_recv
= true;
2762 /* Write data to stream output fd. */
2763 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2765 if (write_ret
< (ssize_t
) recv_size
) {
2766 ERR("Relay error writing data to file");
2767 status
= RELAY_CONNECTION_STATUS_ERROR
;
2768 goto end_stream_unlock
;
2771 left_to_receive
-= recv_size
;
2772 state
->received
+= recv_size
;
2773 state
->left_to_receive
= left_to_receive
;
2775 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2776 write_ret
, stream
->stream_handle
);
2779 if (state
->left_to_receive
> 0) {
2781 * Did not receive all the data expected, wait for more data to
2782 * become available on the socket.
2784 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2785 state
->header
.stream_id
, state
->received
,
2786 state
->left_to_receive
);
2787 goto end_stream_unlock
;
2790 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2791 state
->header
.padding_size
);
2792 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2793 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2794 stream
->stream_handle
,
2795 state
->header
.net_seq_num
, ret
);
2796 status
= RELAY_CONNECTION_STATUS_ERROR
;
2797 goto end_stream_unlock
;
2801 if (session
->minor
>= 4 && !session
->snapshot
) {
2802 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2803 state
->rotate_index
);
2805 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2806 stream
->stream_handle
,
2807 state
->header
.net_seq_num
, ret
);
2808 status
= RELAY_CONNECTION_STATUS_ERROR
;
2809 goto end_stream_unlock
;
2813 stream
->tracefile_size_current
+= state
->header
.data_size
+
2814 state
->header
.padding_size
;
2816 if (stream
->prev_seq
== -1ULL) {
2820 stream
->prev_seq
= state
->header
.net_seq_num
;
2823 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2824 * contents of *state which are aliased (union) to the same location as
2825 * the new state. Don't use it beyond this point.
2827 connection_reset_protocol_state(conn
);
2831 close_requested
= stream
->close_requested
;
2832 pthread_mutex_unlock(&stream
->lock
);
2833 if (close_requested
&& left_to_receive
== 0) {
2834 try_stream_close(stream
);
2838 pthread_mutex_lock(&session
->lock
);
2839 uatomic_set(&session
->new_streams
, 1);
2840 pthread_mutex_unlock(&session
->lock
);
2849 * relay_process_data: Process the data received on the data socket
2851 static enum relay_connection_status
relay_process_data(
2852 struct relay_connection
*conn
)
2854 enum relay_connection_status status
;
2856 switch (conn
->protocol
.data
.state_id
) {
2857 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2858 status
= relay_process_data_receive_header(conn
);
2860 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2861 status
= relay_process_data_receive_payload(conn
);
2864 ERR("Unexpected data connection communication state.");
2871 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2875 (void) lttng_poll_del(events
, pollfd
);
2877 ret
= close(pollfd
);
2879 ERR("Closing pollfd %d", pollfd
);
2883 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2884 int pollfd
, struct relay_connection
*conn
)
2886 const char *type_str
;
2888 switch (conn
->type
) {
2893 type_str
= "Control";
2895 case RELAY_VIEWER_COMMAND
:
2896 type_str
= "Viewer Command";
2898 case RELAY_VIEWER_NOTIFICATION
:
2899 type_str
= "Viewer Notification";
2902 type_str
= "Unknown";
2904 cleanup_connection_pollfd(events
, pollfd
);
2905 connection_put(conn
);
2906 DBG("%s connection closed with %d", type_str
, pollfd
);
2910 * This thread does the actual work
2912 static void *relay_thread_worker(void *data
)
2914 int ret
, err
= -1, last_seen_data_fd
= -1;
2916 struct lttng_poll_event events
;
2917 struct lttng_ht
*relay_connections_ht
;
2918 struct lttng_ht_iter iter
;
2919 struct relay_connection
*destroy_conn
= NULL
;
2921 DBG("[thread] Relay worker started");
2923 rcu_register_thread();
2925 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2927 if (testpoint(relayd_thread_worker
)) {
2928 goto error_testpoint
;
2931 health_code_update();
2933 /* table of connections indexed on socket */
2934 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2935 if (!relay_connections_ht
) {
2936 goto relay_connections_ht_error
;
2939 ret
= create_thread_poll_set(&events
, 2);
2941 goto error_poll_create
;
2944 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2951 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2953 health_code_update();
2955 /* Infinite blocking call, waiting for transmission */
2956 DBG3("Relayd worker thread polling...");
2957 health_poll_entry();
2958 ret
= lttng_poll_wait(&events
, -1);
2962 * Restart interrupted system call.
2964 if (errno
== EINTR
) {
2973 * Process control. The control connection is
2974 * prioritized so we don't starve it with high
2975 * throughput tracing data on the data connection.
2977 for (i
= 0; i
< nb_fd
; i
++) {
2978 /* Fetch once the poll data */
2979 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2980 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2982 health_code_update();
2986 * No activity for this FD (poll
2992 /* Thread quit pipe has been closed. Killing thread. */
2993 ret
= check_thread_quit_pipe(pollfd
, revents
);
2999 /* Inspect the relay conn pipe for new connection */
3000 if (pollfd
== relay_conn_pipe
[0]) {
3001 if (revents
& LPOLLIN
) {
3002 struct relay_connection
*conn
;
3004 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3008 lttng_poll_add(&events
, conn
->sock
->fd
,
3009 LPOLLIN
| LPOLLRDHUP
);
3010 connection_ht_add(relay_connections_ht
, conn
);
3011 DBG("Connection socket %d added", conn
->sock
->fd
);
3012 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3013 ERR("Relay connection pipe error");
3016 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3020 struct relay_connection
*ctrl_conn
;
3022 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3023 /* If not found, there is a synchronization issue. */
3026 if (ctrl_conn
->type
== RELAY_DATA
) {
3027 if (revents
& LPOLLIN
) {
3029 * Flag the last seen data fd not deleted. It will be
3030 * used as the last seen fd if any fd gets deleted in
3033 last_notdel_data_fd
= pollfd
;
3035 goto put_ctrl_connection
;
3037 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3039 if (revents
& LPOLLIN
) {
3040 enum relay_connection_status status
;
3042 status
= relay_process_control(ctrl_conn
);
3043 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3045 * On socket error flag the session as aborted to force
3046 * the cleanup of its stream otherwise it can leak
3047 * during the lifetime of the relayd.
3049 * This prevents situations in which streams can be
3050 * left opened because an index was received, the
3051 * control connection is closed, and the data
3052 * connection is closed (uncleanly) before the packet's
3055 * Since the control connection encountered an error,
3056 * it is okay to be conservative and close the
3057 * session right now as we can't rely on the protocol
3058 * being respected anymore.
3060 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3061 session_abort(ctrl_conn
->session
);
3064 /* Clear the connection on error or close. */
3065 relay_thread_close_connection(&events
,
3070 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3071 relay_thread_close_connection(&events
,
3073 if (last_seen_data_fd
== pollfd
) {
3074 last_seen_data_fd
= last_notdel_data_fd
;
3077 ERR("Unexpected poll events %u for control sock %d",
3079 connection_put(ctrl_conn
);
3082 put_ctrl_connection
:
3083 connection_put(ctrl_conn
);
3088 * The last loop handled a control request, go back to poll to make
3089 * sure we prioritise the control socket.
3095 if (last_seen_data_fd
>= 0) {
3096 for (i
= 0; i
< nb_fd
; i
++) {
3097 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3099 health_code_update();
3101 if (last_seen_data_fd
== pollfd
) {
3108 /* Process data connection. */
3109 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3110 /* Fetch the poll data. */
3111 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3112 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3113 struct relay_connection
*data_conn
;
3115 health_code_update();
3118 /* No activity for this FD (poll implementation). */
3122 /* Skip the command pipe. It's handled in the first loop. */
3123 if (pollfd
== relay_conn_pipe
[0]) {
3127 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3129 /* Skip it. Might be removed before. */
3132 if (data_conn
->type
== RELAY_CONTROL
) {
3133 goto put_data_connection
;
3135 assert(data_conn
->type
== RELAY_DATA
);
3137 if (revents
& LPOLLIN
) {
3138 enum relay_connection_status status
;
3140 status
= relay_process_data(data_conn
);
3141 /* Connection closed or error. */
3142 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3144 * On socket error flag the session as aborted to force
3145 * the cleanup of its stream otherwise it can leak
3146 * during the lifetime of the relayd.
3148 * This prevents situations in which streams can be
3149 * left opened because an index was received, the
3150 * control connection is closed, and the data
3151 * connection is closed (uncleanly) before the packet's
3154 * Since the data connection encountered an error,
3155 * it is okay to be conservative and close the
3156 * session right now as we can't rely on the protocol
3157 * being respected anymore.
3159 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3160 session_abort(data_conn
->session
);
3162 relay_thread_close_connection(&events
, pollfd
,
3165 * Every goto restart call sets the last seen fd where
3166 * here we don't really care since we gracefully
3167 * continue the loop after the connection is deleted.
3170 /* Keep last seen port. */
3171 last_seen_data_fd
= pollfd
;
3172 connection_put(data_conn
);
3175 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3176 relay_thread_close_connection(&events
, pollfd
,
3179 ERR("Unknown poll events %u for data sock %d",
3182 put_data_connection
:
3183 connection_put(data_conn
);
3185 last_seen_data_fd
= -1;
3188 /* Normal exit, no error */
3193 /* Cleanup reamaining connection object. */
3195 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3198 health_code_update();
3200 session_abort(destroy_conn
->session
);
3203 * No need to grab another ref, because we own
3206 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3211 lttng_poll_clean(&events
);
3213 lttng_ht_destroy(relay_connections_ht
);
3214 relay_connections_ht_error
:
3215 /* Close relay conn pipes */
3216 utils_close_pipe(relay_conn_pipe
);
3218 DBG("Thread exited with error");
3220 DBG("Worker thread cleanup complete");
3224 ERR("Health error occurred in %s", __func__
);
3226 health_unregister(health_relayd
);
3227 rcu_unregister_thread();
3228 lttng_relay_stop_threads();
3233 * Create the relay command pipe to wake thread_manage_apps.
3234 * Closed in cleanup().
3236 static int create_relay_conn_pipe(void)
3240 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3248 int main(int argc
, char **argv
)
3250 int ret
= 0, retval
= 0;
3253 /* Parse environment variables */
3254 parse_env_options();
3258 * Command line arguments overwrite environment.
3261 if (set_options(argc
, argv
)) {
3266 if (set_signal_handler()) {
3271 relayd_config_log();
3273 if (opt_print_version
) {
3279 /* Try to create directory if -o, --output is specified. */
3280 if (opt_output_path
) {
3281 if (*opt_output_path
!= '/') {
3282 ERR("Please specify an absolute path for -o, --output PATH");
3287 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3290 ERR("Unable to create %s", opt_output_path
);
3297 if (opt_daemon
|| opt_background
) {
3300 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3308 * We are in the child. Make sure all other file
3309 * descriptors are closed, in case we are called with
3310 * more opened file descriptors than the standard ones.
3312 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3317 if (opt_working_directory
) {
3318 ret
= utils_change_working_dir(opt_working_directory
);
3320 ERR("Changing working directory");
3325 * The RCU thread registration (and use, through the fd-tracker's
3326 * creation) is done after the daemonization to allow us to not
3327 * deal with liburcu's fork() management as the call RCU needs to
3330 rcu_register_thread();
3332 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
3333 if (!the_fd_tracker
) {
3338 /* Initialize thread health monitoring */
3339 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3340 if (!health_relayd
) {
3341 PERROR("health_app_create error");
3343 goto exit_health_app_create
;
3346 /* Create thread quit pipe */
3347 if (init_thread_quit_pipe()) {
3349 goto exit_init_data
;
3352 /* Setup the thread apps communication pipe. */
3353 if (create_relay_conn_pipe()) {
3355 goto exit_init_data
;
3358 /* Init relay command queue. */
3359 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3361 /* Initialize communication library */
3363 lttcomm_inet_init();
3365 /* tables of sessions indexed by session ID */
3366 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3369 goto exit_init_data
;
3372 /* tables of streams indexed by stream ID */
3373 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3374 if (!relay_streams_ht
) {
3376 goto exit_init_data
;
3379 /* tables of streams indexed by stream ID */
3380 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3381 if (!viewer_streams_ht
) {
3383 goto exit_init_data
;
3386 ret
= utils_create_pipe(health_quit_pipe
);
3389 goto exit_health_quit_pipe
;
3392 /* Create thread to manage the client socket */
3393 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3394 thread_manage_health
, (void *) NULL
);
3397 PERROR("pthread_create health");
3399 goto exit_health_thread
;
3402 /* Setup the dispatcher thread */
3403 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3404 relay_thread_dispatcher
, (void *) NULL
);
3407 PERROR("pthread_create dispatcher");
3409 goto exit_dispatcher_thread
;
3412 /* Setup the worker thread */
3413 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3414 relay_thread_worker
, NULL
);
3417 PERROR("pthread_create worker");
3419 goto exit_worker_thread
;
3422 /* Setup the listener thread */
3423 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3424 relay_thread_listener
, (void *) NULL
);
3427 PERROR("pthread_create listener");
3429 goto exit_listener_thread
;
3432 ret
= relayd_live_create(live_uri
);
3434 ERR("Starting live viewer threads");
3440 * This is where we start awaiting program completion (e.g. through
3441 * signal that asks threads to teardown).
3444 ret
= relayd_live_join();
3450 ret
= pthread_join(listener_thread
, &status
);
3453 PERROR("pthread_join listener_thread");
3457 exit_listener_thread
:
3458 ret
= pthread_join(worker_thread
, &status
);
3461 PERROR("pthread_join worker_thread");
3466 ret
= pthread_join(dispatcher_thread
, &status
);
3469 PERROR("pthread_join dispatcher_thread");
3472 exit_dispatcher_thread
:
3474 ret
= pthread_join(health_thread
, &status
);
3477 PERROR("pthread_join health_thread");
3482 utils_close_pipe(health_quit_pipe
);
3483 exit_health_quit_pipe
:
3486 health_app_destroy(health_relayd
);
3487 exit_health_app_create
:
3490 * Wait for all pending call_rcu work to complete before tearing
3491 * down data structures. call_rcu worker may be trying to
3492 * perform lookups in those structures.
3497 /* Ensure all prior call_rcu are done. */
3500 fd_tracker_destroy(the_fd_tracker
);
3501 rcu_unregister_thread();