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 <common/fd-tracker/utils.h>
63 #include <urcu/rculist.h>
67 #include "ctf-trace.h"
70 #include "lttng-relayd.h"
72 #include "health-relayd.h"
73 #include "testpoint.h"
74 #include "viewer-stream.h"
77 #include "connection.h"
78 #include "tracefile-array.h"
79 #include "tcp_keep_alive.h"
81 enum relay_connection_status
{
82 RELAY_CONNECTION_STATUS_OK
,
83 /* An error occured while processing an event on the connection. */
84 RELAY_CONNECTION_STATUS_ERROR
,
85 /* Connection closed/shutdown cleanly. */
86 RELAY_CONNECTION_STATUS_CLOSED
,
89 /* command line options */
90 char *opt_output_path
, *opt_working_directory
;
91 static int opt_daemon
, opt_background
, opt_print_version
;
92 int opt_group_output_by_session
;
93 int opt_group_output_by_host
;
96 * We need to wait for listener and live listener threads, as well as
97 * health check thread, before being ready to signal readiness.
99 #define NR_LTTNG_RELAY_READY 3
100 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
102 /* Size of receive buffer. */
103 #define RECV_DATA_BUFFER_SIZE 65536
105 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
106 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
108 static struct lttng_uri
*control_uri
;
109 static struct lttng_uri
*data_uri
;
110 static struct lttng_uri
*live_uri
;
112 const char *progname
;
114 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
115 static int tracing_group_name_override
;
117 const char * const config_section_name
= "relayd";
120 * Quit pipe for all threads. This permits a single cancellation point
121 * for all threads when receiving an event on the pipe.
123 int thread_quit_pipe
[2] = { -1, -1 };
126 * This pipe is used to inform the worker thread that a command is queued and
127 * ready to be processed.
129 static int relay_conn_pipe
[2] = { -1, -1 };
131 /* Shared between threads */
132 static int dispatch_thread_exit
;
134 static pthread_t listener_thread
;
135 static pthread_t dispatcher_thread
;
136 static pthread_t worker_thread
;
137 static pthread_t health_thread
;
140 * last_relay_stream_id_lock protects last_relay_stream_id increment
141 * atomicity on 32-bit architectures.
143 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
144 static uint64_t last_relay_stream_id
;
147 * Relay command queue.
149 * The relay_thread_listener and relay_thread_dispatcher communicate with this
152 static struct relay_conn_queue relay_conn_queue
;
154 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
155 static unsigned int lttng_opt_fd_cap
;
157 /* Global relay stream hash table. */
158 struct lttng_ht
*relay_streams_ht
;
160 /* Global relay viewer stream hash table. */
161 struct lttng_ht
*viewer_streams_ht
;
163 /* Global relay sessions hash table. */
164 struct lttng_ht
*sessions_ht
;
166 /* Relayd health monitoring */
167 struct health_app
*health_relayd
;
169 /* Global fd tracker. */
170 struct fd_tracker
*the_fd_tracker
;
172 static struct option long_options
[] = {
173 { "control-port", 1, 0, 'C', },
174 { "data-port", 1, 0, 'D', },
175 { "live-port", 1, 0, 'L', },
176 { "daemonize", 0, 0, 'd', },
177 { "background", 0, 0, 'b', },
178 { "group", 1, 0, 'g', },
179 { "fd-cap", 1, 0, '\0', },
180 { "help", 0, 0, 'h', },
181 { "output", 1, 0, 'o', },
182 { "verbose", 0, 0, 'v', },
183 { "config", 1, 0, 'f' },
184 { "version", 0, 0, 'V' },
185 { "working-directory", 1, 0, 'w', },
186 { "group-output-by-session", 0, 0, 's', },
187 { "group-output-by-host", 0, 0, 'p', },
191 static const char *config_ignore_options
[] = { "help", "config", "version" };
193 static void print_version(void) {
194 fprintf(stdout
, "%s\n", VERSION
);
197 static void relayd_config_log(void)
199 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
200 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
201 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
202 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
203 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
205 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
206 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
211 * Take an option from the getopt output and set it in the right variable to be
214 * Return 0 on success else a negative value.
216 static int set_option(int opt
, const char *arg
, const char *optname
)
222 if (!strcmp(optname
, "fd-cap")) {
226 v
= strtoul(arg
, NULL
, 0);
227 if (errno
!= 0 || !isdigit(arg
[0])) {
228 ERR("Wrong value in --fd-cap parameter: %s", arg
);
232 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
233 ERR("File descriptor cap must be set to at least %d",
234 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
237 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
241 lttng_opt_fd_cap
= (unsigned int) v
;
242 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
245 fprintf(stderr
, "unknown option %s", optname
);
247 fprintf(stderr
, " with arg %s\n", arg
);
252 if (lttng_is_setuid_setgid()) {
253 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
254 "-C, --control-port");
256 ret
= uri_parse(arg
, &control_uri
);
258 ERR("Invalid control URI specified");
261 if (control_uri
->port
== 0) {
262 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
267 if (lttng_is_setuid_setgid()) {
268 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
271 ret
= uri_parse(arg
, &data_uri
);
273 ERR("Invalid data URI specified");
276 if (data_uri
->port
== 0) {
277 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 ret
= uri_parse(arg
, &live_uri
);
288 ERR("Invalid live URI specified");
291 if (live_uri
->port
== 0) {
292 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
307 tracing_group_name
= strdup(arg
);
308 if (tracing_group_name
== NULL
) {
313 tracing_group_name_override
= 1;
317 ret
= utils_show_man_page(8, "lttng-relayd");
319 ERR("Cannot view man page lttng-relayd(8)");
324 opt_print_version
= 1;
327 if (lttng_is_setuid_setgid()) {
328 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
331 ret
= asprintf(&opt_output_path
, "%s", arg
);
334 PERROR("asprintf opt_output_path");
340 if (lttng_is_setuid_setgid()) {
341 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
342 "-w, --working-directory");
344 ret
= asprintf(&opt_working_directory
, "%s", arg
);
347 PERROR("asprintf working_directory");
354 /* Verbose level can increase using multiple -v */
356 lttng_opt_verbose
= config_parse_value(arg
);
358 /* Only 3 level of verbosity (-vvv). */
359 if (lttng_opt_verbose
< 3) {
360 lttng_opt_verbose
+= 1;
365 if (opt_group_output_by_host
) {
366 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
369 opt_group_output_by_session
= 1;
372 if (opt_group_output_by_session
) {
373 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
376 opt_group_output_by_host
= 1;
379 /* Unknown option or other error.
380 * Error is printed by getopt, just return */
393 * config_entry_handler_cb used to handle options read from a config file.
394 * See config_entry_handler_cb comment in common/config/session-config.h for the
395 * return value conventions.
397 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
401 if (!entry
|| !entry
->name
|| !entry
->value
) {
406 /* Check if the option is to be ignored */
407 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
408 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
413 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
414 /* Ignore if entry name is not fully matched. */
415 if (strcmp(entry
->name
, long_options
[i
].name
)) {
420 * If the option takes no argument on the command line,
421 * we have to check if the value is "true". We support
422 * non-zero numeric values, true, on and yes.
424 if (!long_options
[i
].has_arg
) {
425 ret
= config_parse_value(entry
->value
);
428 WARN("Invalid configuration value \"%s\" for option %s",
429 entry
->value
, entry
->name
);
431 /* False, skip boolean config option. */
436 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
440 WARN("Unrecognized option \"%s\" in daemon configuration file.",
447 static void parse_env_options(void)
451 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
453 opt_working_directory
= value
;
457 static int set_options(int argc
, char **argv
)
459 int c
, ret
= 0, option_index
= 0, retval
= 0;
460 int orig_optopt
= optopt
, orig_optind
= optind
;
461 char *default_address
, *optstring
;
462 const char *config_path
= NULL
;
464 optstring
= utils_generate_optstring(long_options
,
465 sizeof(long_options
) / sizeof(struct option
));
471 /* Check for the --config option */
473 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
474 &option_index
)) != -1) {
478 } else if (c
!= 'f') {
482 if (lttng_is_setuid_setgid()) {
483 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
486 config_path
= utils_expand_path(optarg
);
488 ERR("Failed to resolve path: %s", optarg
);
493 ret
= config_get_section_entries(config_path
, config_section_name
,
494 config_entry_handler
, NULL
);
497 ERR("Invalid configuration option at line %i", ret
);
503 /* Reset getopt's global state */
504 optopt
= orig_optopt
;
505 optind
= orig_optind
;
507 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
512 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
519 /* assign default values */
520 if (control_uri
== NULL
) {
521 ret
= asprintf(&default_address
,
522 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
523 DEFAULT_NETWORK_CONTROL_PORT
);
525 PERROR("asprintf default data address");
530 ret
= uri_parse(default_address
, &control_uri
);
531 free(default_address
);
533 ERR("Invalid control URI specified");
538 if (data_uri
== NULL
) {
539 ret
= asprintf(&default_address
,
540 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
541 DEFAULT_NETWORK_DATA_PORT
);
543 PERROR("asprintf default data address");
548 ret
= uri_parse(default_address
, &data_uri
);
549 free(default_address
);
551 ERR("Invalid data URI specified");
556 if (live_uri
== NULL
) {
557 ret
= asprintf(&default_address
,
558 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
559 DEFAULT_NETWORK_VIEWER_PORT
);
561 PERROR("asprintf default viewer control address");
566 ret
= uri_parse(default_address
, &live_uri
);
567 free(default_address
);
569 ERR("Invalid viewer control URI specified");
574 if (lttng_opt_fd_cap
== 0) {
576 struct rlimit rlimit
;
578 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
580 PERROR("Failed to get file descriptor limit");
584 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
587 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
588 /* Group by host by default */
589 opt_group_output_by_host
= 1;
597 static void print_global_objects(void)
599 print_viewer_streams();
600 print_relay_streams();
607 static void relayd_cleanup(void)
609 print_global_objects();
613 if (viewer_streams_ht
)
614 lttng_ht_destroy(viewer_streams_ht
);
615 if (relay_streams_ht
)
616 lttng_ht_destroy(relay_streams_ht
);
618 lttng_ht_destroy(sessions_ht
);
620 /* free the dynamically allocated opt_output_path */
621 free(opt_output_path
);
623 /* Close thread quit pipes */
624 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
626 uri_free(control_uri
);
628 /* Live URI is freed in the live thread. */
630 if (tracing_group_name_override
) {
631 free((void *) tracing_group_name
);
633 fd_tracker_log(the_fd_tracker
);
637 * Write to writable pipe used to notify a thread.
639 static int notify_thread_pipe(int wpipe
)
643 ret
= lttng_write(wpipe
, "!", 1);
645 PERROR("write poll pipe");
653 static int notify_health_quit_pipe(int *pipe
)
657 ret
= lttng_write(pipe
[1], "4", 1);
659 PERROR("write relay health quit");
668 * Stop all relayd and relayd-live threads.
670 int lttng_relay_stop_threads(void)
674 /* Stopping all threads */
675 DBG("Terminating all threads");
676 if (notify_thread_pipe(thread_quit_pipe
[1])) {
677 ERR("write error on thread quit pipe");
681 if (notify_health_quit_pipe(health_quit_pipe
)) {
682 ERR("write error on health quit pipe");
685 /* Dispatch thread */
686 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
687 futex_nto1_wake(&relay_conn_queue
.futex
);
689 if (relayd_live_stop()) {
690 ERR("Error stopping live threads");
697 * Signal handler for the daemon
699 * Simply stop all worker threads, leaving main() return gracefully after
700 * joining all threads and calling cleanup().
702 static void sighandler(int sig
)
706 DBG("SIGINT caught");
707 if (lttng_relay_stop_threads()) {
708 ERR("Error stopping threads");
712 DBG("SIGTERM caught");
713 if (lttng_relay_stop_threads()) {
714 ERR("Error stopping threads");
718 CMM_STORE_SHARED(recv_child_signal
, 1);
726 * Setup signal handler for :
727 * SIGINT, SIGTERM, SIGPIPE
729 static int set_signal_handler(void)
735 if ((ret
= sigemptyset(&sigset
)) < 0) {
736 PERROR("sigemptyset");
743 sa
.sa_handler
= sighandler
;
744 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
749 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
754 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
759 sa
.sa_handler
= SIG_IGN
;
760 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
765 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
770 void lttng_relay_notify_ready(void)
772 /* Notify the parent of the fork() process that we are ready. */
773 if (opt_daemon
|| opt_background
) {
774 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
775 kill(child_ppid
, SIGUSR1
);
781 * Init thread quit pipe.
783 * Return -1 on error or 0 if all pipes are created.
785 static int init_thread_quit_pipe(void)
787 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
788 "Quit pipe", thread_quit_pipe
);
792 * Init health quit pipe.
794 * Return -1 on error or 0 if all pipes are created.
796 static int init_health_quit_pipe(void)
798 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
799 "Health quit pipe", health_quit_pipe
);
803 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
805 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
806 int size
, const char *name
)
810 if (events
== NULL
|| size
== 0) {
815 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
816 name
, events
, 1, LTTNG_CLOEXEC
);
819 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
831 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
833 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
835 return create_named_thread_poll_set(events
, size
, "Unknown epoll");
839 * Check if the thread quit pipe was triggered.
841 * Return 1 if it was triggered else 0;
843 static int check_thread_quit_pipe(int fd
, uint32_t events
)
845 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
853 * Create and init socket from uri.
855 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
858 struct lttcomm_sock
*sock
= NULL
;
860 sock
= lttcomm_alloc_sock_from_uri(uri
);
862 ERR("Allocating socket");
866 ret
= lttcomm_create_sock(sock
);
870 DBG("Listening on sock %d", sock
->fd
);
872 ret
= sock
->ops
->bind(sock
);
877 ret
= sock
->ops
->listen(sock
, -1);
887 lttcomm_destroy_sock(sock
);
893 * This thread manages the listening for new connections on the network
895 static void *relay_thread_listener(void *data
)
897 int i
, ret
, pollfd
, err
= -1;
898 uint32_t revents
, nb_fd
;
899 struct lttng_poll_event events
;
900 struct lttcomm_sock
*control_sock
, *data_sock
;
902 DBG("[thread] Relay listener started");
904 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
906 health_code_update();
908 control_sock
= relay_socket_create(control_uri
);
910 goto error_sock_control
;
913 data_sock
= relay_socket_create(data_uri
);
915 goto error_sock_relay
;
919 * Pass 3 as size here for the thread quit pipe, control and
922 ret
= create_thread_poll_set(&events
, 3);
924 goto error_create_poll
;
927 /* Add the control socket */
928 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
933 /* Add the data socket */
934 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
939 lttng_relay_notify_ready();
941 if (testpoint(relayd_thread_listener
)) {
942 goto error_testpoint
;
946 health_code_update();
948 DBG("Listener accepting connections");
952 ret
= lttng_poll_wait(&events
, -1);
956 * Restart interrupted system call.
958 if (errno
== EINTR
) {
966 DBG("Relay new connection received");
967 for (i
= 0; i
< nb_fd
; i
++) {
968 health_code_update();
970 /* Fetch once the poll data */
971 revents
= LTTNG_POLL_GETEV(&events
, i
);
972 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
976 * No activity for this FD (poll
982 /* Thread quit pipe has been closed. Killing thread. */
983 ret
= check_thread_quit_pipe(pollfd
, revents
);
989 if (revents
& LPOLLIN
) {
991 * A new connection is requested, therefore a
992 * sessiond/consumerd connection is allocated in
993 * this thread, enqueued to a global queue and
994 * dequeued (and freed) in the worker thread.
997 struct relay_connection
*new_conn
;
998 struct lttcomm_sock
*newsock
;
999 enum connection_type type
;
1001 if (pollfd
== data_sock
->fd
) {
1003 newsock
= data_sock
->ops
->accept(data_sock
);
1004 DBG("Relay data connection accepted, socket %d",
1007 assert(pollfd
== control_sock
->fd
);
1008 type
= RELAY_CONTROL
;
1009 newsock
= control_sock
->ops
->accept(control_sock
);
1010 DBG("Relay control connection accepted, socket %d",
1014 PERROR("accepting sock");
1018 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1021 PERROR("setsockopt inet");
1022 lttcomm_destroy_sock(newsock
);
1026 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1028 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1030 lttcomm_destroy_sock(newsock
);
1034 new_conn
= connection_create(newsock
, type
);
1036 lttcomm_destroy_sock(newsock
);
1040 /* Enqueue request for the dispatcher thread. */
1041 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1045 * Wake the dispatch queue futex.
1046 * Implicit memory barrier with the
1047 * exchange in cds_wfcq_enqueue.
1049 futex_nto1_wake(&relay_conn_queue
.futex
);
1050 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1051 ERR("socket poll error");
1054 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1064 lttng_poll_clean(&events
);
1066 if (data_sock
->fd
>= 0) {
1067 ret
= data_sock
->ops
->close(data_sock
);
1072 lttcomm_destroy_sock(data_sock
);
1074 if (control_sock
->fd
>= 0) {
1075 ret
= control_sock
->ops
->close(control_sock
);
1080 lttcomm_destroy_sock(control_sock
);
1084 ERR("Health error occurred in %s", __func__
);
1086 health_unregister(health_relayd
);
1087 DBG("Relay listener thread cleanup complete");
1088 lttng_relay_stop_threads();
1093 * This thread manages the dispatching of the requests to worker threads
1095 static void *relay_thread_dispatcher(void *data
)
1099 struct cds_wfcq_node
*node
;
1100 struct relay_connection
*new_conn
= NULL
;
1102 DBG("[thread] Relay dispatcher started");
1104 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1106 if (testpoint(relayd_thread_dispatcher
)) {
1107 goto error_testpoint
;
1110 health_code_update();
1113 health_code_update();
1115 /* Atomically prepare the queue futex */
1116 futex_nto1_prepare(&relay_conn_queue
.futex
);
1118 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1123 health_code_update();
1125 /* Dequeue commands */
1126 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1127 &relay_conn_queue
.tail
);
1129 DBG("Woken up but nothing in the relay command queue");
1130 /* Continue thread execution */
1133 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1135 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1138 * Inform worker thread of the new request. This
1139 * call is blocking so we can be assured that
1140 * the data will be read at some point in time
1141 * or wait to the end of the world :)
1143 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1145 PERROR("write connection pipe");
1146 connection_put(new_conn
);
1149 } while (node
!= NULL
);
1151 /* Futex wait on queue. Blocking call on futex() */
1152 health_poll_entry();
1153 futex_nto1_wait(&relay_conn_queue
.futex
);
1157 /* Normal exit, no error */
1164 ERR("Health error occurred in %s", __func__
);
1166 health_unregister(health_relayd
);
1167 DBG("Dispatch thread dying");
1168 lttng_relay_stop_threads();
1173 * Set index data from the control port to a given index object.
1175 static int set_index_control_data(struct relay_index
*index
,
1176 struct lttcomm_relayd_index
*data
,
1177 struct relay_connection
*conn
)
1179 struct ctf_packet_index index_data
;
1182 * The index on disk is encoded in big endian.
1184 index_data
.packet_size
= htobe64(data
->packet_size
);
1185 index_data
.content_size
= htobe64(data
->content_size
);
1186 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1187 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1188 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1189 index_data
.stream_id
= htobe64(data
->stream_id
);
1191 if (conn
->minor
>= 8) {
1192 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1193 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1196 return relay_index_set_data(index
, &index_data
);
1200 * Handle the RELAYD_CREATE_SESSION command.
1202 * On success, send back the session id or else return a negative value.
1204 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1205 struct relay_connection
*conn
,
1206 const struct lttng_buffer_view
*payload
)
1210 struct relay_session
*session
;
1211 struct lttcomm_relayd_status_session reply
;
1212 char session_name
[LTTNG_NAME_MAX
];
1213 char hostname
[LTTNG_HOST_NAME_MAX
];
1214 uint32_t live_timer
= 0;
1215 bool snapshot
= false;
1217 memset(session_name
, 0, LTTNG_NAME_MAX
);
1218 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1220 memset(&reply
, 0, sizeof(reply
));
1222 switch (conn
->minor
) {
1227 case 4: /* LTTng sessiond 2.4 */
1229 ret
= cmd_create_session_2_4(payload
, session_name
,
1230 hostname
, &live_timer
, &snapshot
);
1236 session
= session_create(session_name
, hostname
, live_timer
,
1237 snapshot
, conn
->major
, conn
->minor
);
1242 assert(!conn
->session
);
1243 conn
->session
= session
;
1244 DBG("Created session %" PRIu64
, session
->id
);
1246 reply
.session_id
= htobe64(session
->id
);
1250 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1252 reply
.ret_code
= htobe32(LTTNG_OK
);
1255 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1256 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1257 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1266 * When we have received all the streams and the metadata for a channel,
1267 * we make them visible to the viewer threads.
1269 static void publish_connection_local_streams(struct relay_connection
*conn
)
1271 struct relay_stream
*stream
;
1272 struct relay_session
*session
= conn
->session
;
1275 * We publish all streams belonging to a session atomically wrt
1278 pthread_mutex_lock(&session
->lock
);
1280 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1282 stream_publish(stream
);
1287 * Inform the viewer that there are new streams in the session.
1289 if (session
->viewer_attached
) {
1290 uatomic_set(&session
->new_streams
, 1);
1292 pthread_mutex_unlock(&session
->lock
);
1296 * relay_add_stream: allocate a new stream for a session
1298 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1299 struct relay_connection
*conn
,
1300 const struct lttng_buffer_view
*payload
)
1304 struct relay_session
*session
= conn
->session
;
1305 struct relay_stream
*stream
= NULL
;
1306 struct lttcomm_relayd_status_stream reply
;
1307 struct ctf_trace
*trace
= NULL
;
1308 uint64_t stream_handle
= -1ULL;
1309 char *path_name
= NULL
, *channel_name
= NULL
;
1310 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1312 if (!session
|| !conn
->version_check_done
) {
1313 ERR("Trying to add a stream before version check");
1315 goto end_no_session
;
1318 switch (session
->minor
) {
1319 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1320 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1321 &channel_name
, session
);
1323 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1325 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1326 &channel_name
, &tracefile_size
, &tracefile_count
,
1334 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1338 /* This stream here has one reference on the trace. */
1340 pthread_mutex_lock(&last_relay_stream_id_lock
);
1341 stream_handle
= ++last_relay_stream_id
;
1342 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1344 /* We pass ownership of path_name and channel_name. */
1345 stream
= stream_create(trace
, stream_handle
, path_name
,
1346 channel_name
, tracefile_size
, tracefile_count
);
1348 channel_name
= NULL
;
1351 * Streams are the owners of their trace. Reference to trace is
1352 * kept within stream_create().
1354 ctf_trace_put(trace
);
1357 memset(&reply
, 0, sizeof(reply
));
1358 reply
.handle
= htobe64(stream_handle
);
1360 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1362 reply
.ret_code
= htobe32(LTTNG_OK
);
1365 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1366 sizeof(struct lttcomm_relayd_status_stream
), 0);
1367 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1368 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1380 * relay_close_stream: close a specific stream
1382 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1383 struct relay_connection
*conn
,
1384 const struct lttng_buffer_view
*payload
)
1388 struct relay_session
*session
= conn
->session
;
1389 struct lttcomm_relayd_close_stream stream_info
;
1390 struct lttcomm_relayd_generic_reply reply
;
1391 struct relay_stream
*stream
;
1393 DBG("Close stream received");
1395 if (!session
|| !conn
->version_check_done
) {
1396 ERR("Trying to close a stream before version check");
1398 goto end_no_session
;
1401 if (payload
->size
< sizeof(stream_info
)) {
1402 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1403 sizeof(stream_info
), payload
->size
);
1405 goto end_no_session
;
1407 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1408 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1409 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1411 stream
= stream_get_by_id(stream_info
.stream_id
);
1418 * Set last_net_seq_num before the close flag. Required by data
1421 pthread_mutex_lock(&stream
->lock
);
1422 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1423 pthread_mutex_unlock(&stream
->lock
);
1426 * This is one of the conditions which may trigger a stream close
1427 * with the others being:
1428 * 1) A close command is received for a stream
1429 * 2) The control connection owning the stream is closed
1430 * 3) We have received all of the stream's data _after_ a close
1433 try_stream_close(stream
);
1434 if (stream
->is_metadata
) {
1435 struct relay_viewer_stream
*vstream
;
1437 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1439 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1441 * Since all the metadata has been sent to the
1442 * viewer and that we have a request to close
1443 * its stream, we can safely teardown the
1444 * corresponding metadata viewer stream.
1446 viewer_stream_put(vstream
);
1448 /* Put local reference. */
1449 viewer_stream_put(vstream
);
1456 memset(&reply
, 0, sizeof(reply
));
1458 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1460 reply
.ret_code
= htobe32(LTTNG_OK
);
1462 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1463 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1464 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1465 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1475 * relay_reset_metadata: reset a metadata stream
1478 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1479 struct relay_connection
*conn
,
1480 const struct lttng_buffer_view
*payload
)
1484 struct relay_session
*session
= conn
->session
;
1485 struct lttcomm_relayd_reset_metadata stream_info
;
1486 struct lttcomm_relayd_generic_reply reply
;
1487 struct relay_stream
*stream
;
1489 DBG("Reset metadata received");
1491 if (!session
|| !conn
->version_check_done
) {
1492 ERR("Trying to reset a metadata stream before version check");
1494 goto end_no_session
;
1497 if (payload
->size
< sizeof(stream_info
)) {
1498 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1499 sizeof(stream_info
), payload
->size
);
1501 goto end_no_session
;
1503 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1504 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1505 stream_info
.version
= be64toh(stream_info
.version
);
1507 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1509 /* Unsupported for live sessions for now. */
1510 if (session
->live_timer
!= 0) {
1515 stream
= stream_get_by_id(stream_info
.stream_id
);
1520 pthread_mutex_lock(&stream
->lock
);
1521 if (!stream
->is_metadata
) {
1526 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1527 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1528 &stream
->stream_fd
->fd
);
1530 ERR("Failed to rotate metadata file %s of channel %s",
1531 stream
->path_name
, stream
->channel_name
);
1536 pthread_mutex_unlock(&stream
->lock
);
1540 memset(&reply
, 0, sizeof(reply
));
1542 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1544 reply
.ret_code
= htobe32(LTTNG_OK
);
1546 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1547 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1548 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1549 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1559 * relay_unknown_command: send -1 if received unknown command
1561 static void relay_unknown_command(struct relay_connection
*conn
)
1563 struct lttcomm_relayd_generic_reply reply
;
1566 memset(&reply
, 0, sizeof(reply
));
1567 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1568 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1569 if (send_ret
< sizeof(reply
)) {
1570 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1575 * relay_start: send an acknowledgment to the client to tell if we are
1576 * ready to receive data. We are ready if a session is established.
1578 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1579 struct relay_connection
*conn
,
1580 const struct lttng_buffer_view
*payload
)
1584 struct lttcomm_relayd_generic_reply reply
;
1585 struct relay_session
*session
= conn
->session
;
1588 DBG("Trying to start the streaming without a session established");
1589 ret
= htobe32(LTTNG_ERR_UNK
);
1592 memset(&reply
, 0, sizeof(reply
));
1593 reply
.ret_code
= htobe32(LTTNG_OK
);
1594 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1596 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1597 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1606 * Append padding to the file pointed by the file descriptor fd.
1608 static int write_padding_to_file(int fd
, uint32_t size
)
1617 zeros
= zmalloc(size
);
1618 if (zeros
== NULL
) {
1619 PERROR("zmalloc zeros for padding");
1624 ret
= lttng_write(fd
, zeros
, size
);
1626 PERROR("write padding to file");
1636 * relay_recv_metadata: receive the metadata for the session.
1638 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1639 struct relay_connection
*conn
,
1640 const struct lttng_buffer_view
*payload
)
1644 struct relay_session
*session
= conn
->session
;
1645 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1646 struct relay_stream
*metadata_stream
;
1647 uint64_t metadata_payload_size
;
1650 ERR("Metadata sent before version check");
1655 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1656 ERR("Incorrect data size");
1660 metadata_payload_size
= recv_hdr
->data_size
-
1661 sizeof(struct lttcomm_relayd_metadata_payload
);
1663 memcpy(&metadata_payload_header
, payload
->data
,
1664 sizeof(metadata_payload_header
));
1665 metadata_payload_header
.stream_id
= be64toh(
1666 metadata_payload_header
.stream_id
);
1667 metadata_payload_header
.padding_size
= be32toh(
1668 metadata_payload_header
.padding_size
);
1670 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1671 if (!metadata_stream
) {
1676 pthread_mutex_lock(&metadata_stream
->lock
);
1678 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1679 payload
->data
+ sizeof(metadata_payload_header
),
1680 metadata_payload_size
);
1681 if (size_ret
< metadata_payload_size
) {
1682 ERR("Relay error writing metadata on file");
1687 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1688 metadata_payload_header
.padding_size
);
1689 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1694 metadata_stream
->metadata_received
+=
1695 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1696 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1697 metadata_stream
->metadata_received
);
1700 pthread_mutex_unlock(&metadata_stream
->lock
);
1701 stream_put(metadata_stream
);
1707 * relay_send_version: send relayd version number
1709 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1710 struct relay_connection
*conn
,
1711 const struct lttng_buffer_view
*payload
)
1715 struct lttcomm_relayd_version reply
, msg
;
1716 bool compatible
= true;
1718 conn
->version_check_done
= true;
1720 /* Get version from the other side. */
1721 if (payload
->size
< sizeof(msg
)) {
1722 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1723 sizeof(msg
), payload
->size
);
1728 memcpy(&msg
, payload
->data
, sizeof(msg
));
1729 msg
.major
= be32toh(msg
.major
);
1730 msg
.minor
= be32toh(msg
.minor
);
1732 memset(&reply
, 0, sizeof(reply
));
1733 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1734 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1736 /* Major versions must be the same */
1737 if (reply
.major
!= msg
.major
) {
1738 DBG("Incompatible major versions (%u vs %u), deleting session",
1739 reply
.major
, msg
.major
);
1743 conn
->major
= reply
.major
;
1744 /* We adapt to the lowest compatible version */
1745 if (reply
.minor
<= msg
.minor
) {
1746 conn
->minor
= reply
.minor
;
1748 conn
->minor
= msg
.minor
;
1751 reply
.major
= htobe32(reply
.major
);
1752 reply
.minor
= htobe32(reply
.minor
);
1753 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1755 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1756 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1769 DBG("Version check done using protocol %u.%u", conn
->major
,
1777 * Check for data pending for a given stream id from the session daemon.
1779 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1780 struct relay_connection
*conn
,
1781 const struct lttng_buffer_view
*payload
)
1783 struct relay_session
*session
= conn
->session
;
1784 struct lttcomm_relayd_data_pending msg
;
1785 struct lttcomm_relayd_generic_reply reply
;
1786 struct relay_stream
*stream
;
1790 DBG("Data pending command received");
1792 if (!session
|| !conn
->version_check_done
) {
1793 ERR("Trying to check for data before version check");
1795 goto end_no_session
;
1798 if (payload
->size
< sizeof(msg
)) {
1799 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1800 sizeof(msg
), payload
->size
);
1802 goto end_no_session
;
1804 memcpy(&msg
, payload
->data
, sizeof(msg
));
1805 msg
.stream_id
= be64toh(msg
.stream_id
);
1806 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1808 stream
= stream_get_by_id(msg
.stream_id
);
1809 if (stream
== NULL
) {
1814 pthread_mutex_lock(&stream
->lock
);
1816 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1817 " and last_seq %" PRIu64
, msg
.stream_id
,
1818 stream
->prev_seq
, msg
.last_net_seq_num
);
1820 /* Avoid wrapping issue */
1821 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1822 /* Data has in fact been written and is NOT pending */
1825 /* Data still being streamed thus pending */
1829 stream
->data_pending_check_done
= true;
1830 pthread_mutex_unlock(&stream
->lock
);
1835 memset(&reply
, 0, sizeof(reply
));
1836 reply
.ret_code
= htobe32(ret
);
1837 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1838 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1839 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1849 * Wait for the control socket to reach a quiescent state.
1851 * Note that for now, when receiving this command from the session
1852 * daemon, this means that every subsequent commands or data received on
1853 * the control socket has been handled. So, this is why we simply return
1856 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1857 struct relay_connection
*conn
,
1858 const struct lttng_buffer_view
*payload
)
1862 struct relay_stream
*stream
;
1863 struct lttcomm_relayd_quiescent_control msg
;
1864 struct lttcomm_relayd_generic_reply reply
;
1866 DBG("Checking quiescent state on control socket");
1868 if (!conn
->session
|| !conn
->version_check_done
) {
1869 ERR("Trying to check for data before version check");
1871 goto end_no_session
;
1874 if (payload
->size
< sizeof(msg
)) {
1875 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1876 sizeof(msg
), payload
->size
);
1878 goto end_no_session
;
1880 memcpy(&msg
, payload
->data
, sizeof(msg
));
1881 msg
.stream_id
= be64toh(msg
.stream_id
);
1883 stream
= stream_get_by_id(msg
.stream_id
);
1887 pthread_mutex_lock(&stream
->lock
);
1888 stream
->data_pending_check_done
= true;
1889 pthread_mutex_unlock(&stream
->lock
);
1891 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1894 memset(&reply
, 0, sizeof(reply
));
1895 reply
.ret_code
= htobe32(LTTNG_OK
);
1896 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1897 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1898 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1910 * Initialize a data pending command. This means that a consumer is about
1911 * to ask for data pending for each stream it holds. Simply iterate over
1912 * all streams of a session and set the data_pending_check_done flag.
1914 * This command returns to the client a LTTNG_OK code.
1916 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1917 struct relay_connection
*conn
,
1918 const struct lttng_buffer_view
*payload
)
1922 struct lttng_ht_iter iter
;
1923 struct lttcomm_relayd_begin_data_pending msg
;
1924 struct lttcomm_relayd_generic_reply reply
;
1925 struct relay_stream
*stream
;
1930 DBG("Init streams for data pending");
1932 if (!conn
->session
|| !conn
->version_check_done
) {
1933 ERR("Trying to check for data before version check");
1935 goto end_no_session
;
1938 if (payload
->size
< sizeof(msg
)) {
1939 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1940 sizeof(msg
), payload
->size
);
1942 goto end_no_session
;
1944 memcpy(&msg
, payload
->data
, sizeof(msg
));
1945 msg
.session_id
= be64toh(msg
.session_id
);
1948 * Iterate over all streams to set the begin data pending flag.
1949 * For now, the streams are indexed by stream handle so we have
1950 * to iterate over all streams to find the one associated with
1951 * the right session_id.
1954 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1956 if (!stream_get(stream
)) {
1959 if (stream
->trace
->session
->id
== msg
.session_id
) {
1960 pthread_mutex_lock(&stream
->lock
);
1961 stream
->data_pending_check_done
= false;
1962 pthread_mutex_unlock(&stream
->lock
);
1963 DBG("Set begin data pending flag to stream %" PRIu64
,
1964 stream
->stream_handle
);
1970 memset(&reply
, 0, sizeof(reply
));
1971 /* All good, send back reply. */
1972 reply
.ret_code
= htobe32(LTTNG_OK
);
1974 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1975 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1976 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1988 * End data pending command. This will check, for a given session id, if
1989 * each stream associated with it has its data_pending_check_done flag
1990 * set. If not, this means that the client lost track of the stream but
1991 * the data is still being streamed on our side. In this case, we inform
1992 * the client that data is in flight.
1994 * Return to the client if there is data in flight or not with a ret_code.
1996 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1997 struct relay_connection
*conn
,
1998 const struct lttng_buffer_view
*payload
)
2002 struct lttng_ht_iter iter
;
2003 struct lttcomm_relayd_end_data_pending msg
;
2004 struct lttcomm_relayd_generic_reply reply
;
2005 struct relay_stream
*stream
;
2006 uint32_t is_data_inflight
= 0;
2008 DBG("End data pending command");
2010 if (!conn
->session
|| !conn
->version_check_done
) {
2011 ERR("Trying to check for data before version check");
2013 goto end_no_session
;
2016 if (payload
->size
< sizeof(msg
)) {
2017 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2018 sizeof(msg
), payload
->size
);
2020 goto end_no_session
;
2022 memcpy(&msg
, payload
->data
, sizeof(msg
));
2023 msg
.session_id
= be64toh(msg
.session_id
);
2026 * Iterate over all streams to see if the begin data pending
2030 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2032 if (!stream_get(stream
)) {
2035 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2039 pthread_mutex_lock(&stream
->lock
);
2040 if (!stream
->data_pending_check_done
) {
2041 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2042 is_data_inflight
= 1;
2043 DBG("Data is still in flight for stream %" PRIu64
,
2044 stream
->stream_handle
);
2045 pthread_mutex_unlock(&stream
->lock
);
2050 pthread_mutex_unlock(&stream
->lock
);
2055 memset(&reply
, 0, sizeof(reply
));
2056 /* All good, send back reply. */
2057 reply
.ret_code
= htobe32(is_data_inflight
);
2059 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2060 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2061 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2073 * Receive an index for a specific stream.
2075 * Return 0 on success else a negative value.
2077 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2078 struct relay_connection
*conn
,
2079 const struct lttng_buffer_view
*payload
)
2083 struct relay_session
*session
= conn
->session
;
2084 struct lttcomm_relayd_index index_info
;
2085 struct relay_index
*index
;
2086 struct lttcomm_relayd_generic_reply reply
;
2087 struct relay_stream
*stream
;
2092 DBG("Relay receiving index");
2094 if (!session
|| !conn
->version_check_done
) {
2095 ERR("Trying to close a stream before version check");
2097 goto end_no_session
;
2100 msg_len
= lttcomm_relayd_index_len(
2101 lttng_to_index_major(conn
->major
, conn
->minor
),
2102 lttng_to_index_minor(conn
->major
, conn
->minor
));
2103 if (payload
->size
< msg_len
) {
2104 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2105 msg_len
, payload
->size
);
2107 goto end_no_session
;
2109 memcpy(&index_info
, payload
->data
, msg_len
);
2110 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2111 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2112 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2113 index_info
.content_size
= be64toh(index_info
.content_size
);
2114 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2115 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2116 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2117 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2119 if (conn
->minor
>= 8) {
2120 index_info
.stream_instance_id
=
2121 be64toh(index_info
.stream_instance_id
);
2122 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2125 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2127 ERR("stream_get_by_id not found");
2131 pthread_mutex_lock(&stream
->lock
);
2133 /* Live beacon handling */
2134 if (index_info
.packet_size
== 0) {
2135 DBG("Received live beacon for stream %" PRIu64
,
2136 stream
->stream_handle
);
2139 * Only flag a stream inactive when it has already
2140 * received data and no indexes are in flight.
2142 if (stream
->index_received_seqcount
> 0
2143 && stream
->indexes_in_flight
== 0) {
2144 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2147 goto end_stream_put
;
2149 stream
->beacon_ts_end
= -1ULL;
2152 if (stream
->ctf_stream_id
== -1ULL) {
2153 stream
->ctf_stream_id
= index_info
.stream_id
;
2155 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2158 ERR("relay_index_get_by_id_or_create index NULL");
2159 goto end_stream_put
;
2161 if (set_index_control_data(index
, &index_info
, conn
)) {
2162 ERR("set_index_control_data error");
2163 relay_index_put(index
);
2165 goto end_stream_put
;
2167 ret
= relay_index_try_flush(index
);
2169 tracefile_array_commit_seq(stream
->tfa
);
2170 stream
->index_received_seqcount
++;
2171 } else if (ret
> 0) {
2175 ERR("relay_index_try_flush error %d", ret
);
2176 relay_index_put(index
);
2181 pthread_mutex_unlock(&stream
->lock
);
2186 memset(&reply
, 0, sizeof(reply
));
2188 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2190 reply
.ret_code
= htobe32(LTTNG_OK
);
2192 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2193 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2194 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2203 * Receive the streams_sent message.
2205 * Return 0 on success else a negative value.
2207 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2208 struct relay_connection
*conn
,
2209 const struct lttng_buffer_view
*payload
)
2213 struct lttcomm_relayd_generic_reply reply
;
2217 DBG("Relay receiving streams_sent");
2219 if (!conn
->session
|| !conn
->version_check_done
) {
2220 ERR("Trying to close a stream before version check");
2222 goto end_no_session
;
2226 * Publish every pending stream in the connection recv list which are
2227 * now ready to be used by the viewer.
2229 publish_connection_local_streams(conn
);
2231 memset(&reply
, 0, sizeof(reply
));
2232 reply
.ret_code
= htobe32(LTTNG_OK
);
2233 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2234 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2235 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2247 #define DBG_CMD(cmd_name, conn) \
2248 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2250 static int relay_process_control_command(struct relay_connection
*conn
,
2251 const struct lttcomm_relayd_hdr
*header
,
2252 const struct lttng_buffer_view
*payload
)
2256 switch (header
->cmd
) {
2257 case RELAYD_CREATE_SESSION
:
2258 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2259 ret
= relay_create_session(header
, conn
, payload
);
2261 case RELAYD_ADD_STREAM
:
2262 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2263 ret
= relay_add_stream(header
, conn
, payload
);
2265 case RELAYD_START_DATA
:
2266 DBG_CMD("RELAYD_START_DATA", conn
);
2267 ret
= relay_start(header
, conn
, payload
);
2269 case RELAYD_SEND_METADATA
:
2270 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2271 ret
= relay_recv_metadata(header
, conn
, payload
);
2273 case RELAYD_VERSION
:
2274 DBG_CMD("RELAYD_VERSION", conn
);
2275 ret
= relay_send_version(header
, conn
, payload
);
2277 case RELAYD_CLOSE_STREAM
:
2278 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2279 ret
= relay_close_stream(header
, conn
, payload
);
2281 case RELAYD_DATA_PENDING
:
2282 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2283 ret
= relay_data_pending(header
, conn
, payload
);
2285 case RELAYD_QUIESCENT_CONTROL
:
2286 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2287 ret
= relay_quiescent_control(header
, conn
, payload
);
2289 case RELAYD_BEGIN_DATA_PENDING
:
2290 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2291 ret
= relay_begin_data_pending(header
, conn
, payload
);
2293 case RELAYD_END_DATA_PENDING
:
2294 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2295 ret
= relay_end_data_pending(header
, conn
, payload
);
2297 case RELAYD_SEND_INDEX
:
2298 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2299 ret
= relay_recv_index(header
, conn
, payload
);
2301 case RELAYD_STREAMS_SENT
:
2302 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2303 ret
= relay_streams_sent(header
, conn
, payload
);
2305 case RELAYD_RESET_METADATA
:
2306 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2307 ret
= relay_reset_metadata(header
, conn
, payload
);
2309 case RELAYD_UPDATE_SYNC_INFO
:
2311 ERR("Received unknown command (%u)", header
->cmd
);
2312 relay_unknown_command(conn
);
2321 static enum relay_connection_status
relay_process_control_receive_payload(
2322 struct relay_connection
*conn
)
2325 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2326 struct lttng_dynamic_buffer
*reception_buffer
=
2327 &conn
->protocol
.ctrl
.reception_buffer
;
2328 struct ctrl_connection_state_receive_payload
*state
=
2329 &conn
->protocol
.ctrl
.state
.receive_payload
;
2330 struct lttng_buffer_view payload_view
;
2332 if (state
->left_to_receive
== 0) {
2333 /* Short-circuit for payload-less commands. */
2334 goto reception_complete
;
2336 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2337 reception_buffer
->data
+ state
->received
,
2338 state
->left_to_receive
, MSG_DONTWAIT
);
2340 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2341 PERROR("Unable to receive command payload on sock %d",
2343 status
= RELAY_CONNECTION_STATUS_ERROR
;
2346 } else if (ret
== 0) {
2347 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2348 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2353 assert(ret
<= state
->left_to_receive
);
2355 state
->left_to_receive
-= ret
;
2356 state
->received
+= ret
;
2358 if (state
->left_to_receive
> 0) {
2360 * Can't transition to the protocol's next state, wait to
2361 * receive the rest of the header.
2363 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2364 state
->received
, state
->left_to_receive
,
2370 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2371 conn
->sock
->fd
, state
->received
);
2373 * The payload required to process the command has been received.
2374 * A view to the reception buffer is forwarded to the various
2375 * commands and the state of the control is reset on success.
2377 * Commands are responsible for sending their reply to the peer.
2379 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2381 ret
= relay_process_control_command(conn
,
2382 &state
->header
, &payload_view
);
2384 status
= RELAY_CONNECTION_STATUS_ERROR
;
2388 ret
= connection_reset_protocol_state(conn
);
2390 status
= RELAY_CONNECTION_STATUS_ERROR
;
2396 static enum relay_connection_status
relay_process_control_receive_header(
2397 struct relay_connection
*conn
)
2400 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2401 struct lttcomm_relayd_hdr header
;
2402 struct lttng_dynamic_buffer
*reception_buffer
=
2403 &conn
->protocol
.ctrl
.reception_buffer
;
2404 struct ctrl_connection_state_receive_header
*state
=
2405 &conn
->protocol
.ctrl
.state
.receive_header
;
2407 assert(state
->left_to_receive
!= 0);
2409 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2410 reception_buffer
->data
+ state
->received
,
2411 state
->left_to_receive
, MSG_DONTWAIT
);
2413 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2414 PERROR("Unable to receive control command header on sock %d",
2416 status
= RELAY_CONNECTION_STATUS_ERROR
;
2419 } else if (ret
== 0) {
2420 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2421 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2426 assert(ret
<= state
->left_to_receive
);
2428 state
->left_to_receive
-= ret
;
2429 state
->received
+= ret
;
2431 if (state
->left_to_receive
> 0) {
2433 * Can't transition to the protocol's next state, wait to
2434 * receive the rest of the header.
2436 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2437 state
->received
, state
->left_to_receive
,
2442 /* Transition to next state: receiving the command's payload. */
2443 conn
->protocol
.ctrl
.state_id
=
2444 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2445 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2446 header
.circuit_id
= be64toh(header
.circuit_id
);
2447 header
.data_size
= be64toh(header
.data_size
);
2448 header
.cmd
= be32toh(header
.cmd
);
2449 header
.cmd_version
= be32toh(header
.cmd_version
);
2450 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2451 &header
, sizeof(header
));
2453 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2454 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2457 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2458 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2460 status
= RELAY_CONNECTION_STATUS_ERROR
;
2464 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2466 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2467 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2470 status
= RELAY_CONNECTION_STATUS_ERROR
;
2474 if (header
.data_size
== 0) {
2476 * Manually invoke the next state as the poll loop
2477 * will not wake-up to allow us to proceed further.
2479 status
= relay_process_control_receive_payload(conn
);
2486 * Process the commands received on the control socket
2488 static enum relay_connection_status
relay_process_control(
2489 struct relay_connection
*conn
)
2491 enum relay_connection_status status
;
2493 switch (conn
->protocol
.ctrl
.state_id
) {
2494 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2495 status
= relay_process_control_receive_header(conn
);
2497 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2498 status
= relay_process_control_receive_payload(conn
);
2501 ERR("Unknown control connection protocol state encountered.");
2509 * Handle index for a data stream.
2511 * Called with the stream lock held.
2513 * Return 0 on success else a negative value.
2515 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2519 uint64_t data_offset
;
2520 struct relay_index
*index
;
2522 /* Get data offset because we are about to update the index. */
2523 data_offset
= htobe64(stream
->tracefile_size_current
);
2525 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2526 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2529 * Lookup for an existing index for that stream id/sequence
2530 * number. If it exists, the control thread has already received the
2531 * data for it, thus we need to write it to disk.
2533 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2539 if (rotate_index
|| !stream
->index_file
) {
2540 uint32_t major
, minor
;
2542 /* Put ref on previous index_file. */
2543 if (stream
->index_file
) {
2544 lttng_index_file_put(stream
->index_file
);
2545 stream
->index_file
= NULL
;
2547 major
= stream
->trace
->session
->major
;
2548 minor
= stream
->trace
->session
->minor
;
2549 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2550 stream
->channel_name
,
2551 -1, -1, stream
->tracefile_size
,
2552 tracefile_array_get_file_index_head(stream
->tfa
),
2553 lttng_to_index_major(major
, minor
),
2554 lttng_to_index_minor(major
, minor
));
2555 if (!stream
->index_file
) {
2557 /* Put self-ref for this index due to error. */
2558 relay_index_put(index
);
2564 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2566 /* Put self-ref for this index due to error. */
2567 relay_index_put(index
);
2572 ret
= relay_index_try_flush(index
);
2574 tracefile_array_commit_seq(stream
->tfa
);
2575 stream
->index_received_seqcount
++;
2576 } else if (ret
> 0) {
2580 /* Put self-ref for this index due to error. */
2581 relay_index_put(index
);
2589 static enum relay_connection_status
relay_process_data_receive_header(
2590 struct relay_connection
*conn
)
2593 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2594 struct data_connection_state_receive_header
*state
=
2595 &conn
->protocol
.data
.state
.receive_header
;
2596 struct lttcomm_relayd_data_hdr header
;
2597 struct relay_stream
*stream
;
2599 assert(state
->left_to_receive
!= 0);
2601 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2602 state
->header_reception_buffer
+ state
->received
,
2603 state
->left_to_receive
, MSG_DONTWAIT
);
2605 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2606 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2607 status
= RELAY_CONNECTION_STATUS_ERROR
;
2610 } else if (ret
== 0) {
2611 /* Orderly shutdown. Not necessary to print an error. */
2612 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2613 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2618 assert(ret
<= state
->left_to_receive
);
2620 state
->left_to_receive
-= ret
;
2621 state
->received
+= ret
;
2623 if (state
->left_to_receive
> 0) {
2625 * Can't transition to the protocol's next state, wait to
2626 * receive the rest of the header.
2628 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2629 state
->received
, state
->left_to_receive
,
2635 /* Transition to next state: receiving the payload. */
2636 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2638 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2639 header
.circuit_id
= be64toh(header
.circuit_id
);
2640 header
.stream_id
= be64toh(header
.stream_id
);
2641 header
.data_size
= be32toh(header
.data_size
);
2642 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2643 header
.padding_size
= be32toh(header
.padding_size
);
2644 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2646 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2648 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2649 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2651 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2652 conn
->sock
->fd
, header
.circuit_id
,
2653 header
.stream_id
, header
.data_size
,
2654 header
.net_seq_num
, header
.padding_size
);
2656 stream
= stream_get_by_id(header
.stream_id
);
2658 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2660 /* Protocol error. */
2661 status
= RELAY_CONNECTION_STATUS_ERROR
;
2665 pthread_mutex_lock(&stream
->lock
);
2667 /* Check if a rotation is needed. */
2668 if (stream
->tracefile_size
> 0 &&
2669 (stream
->tracefile_size_current
+ header
.data_size
) >
2670 stream
->tracefile_size
) {
2671 uint64_t old_id
, new_id
;
2673 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2674 tracefile_array_file_rotate(stream
->tfa
);
2676 /* new_id is updated by utils_rotate_stream_file. */
2679 ret
= utils_rotate_stream_file(stream
->path_name
,
2680 stream
->channel_name
, stream
->tracefile_size
,
2681 stream
->tracefile_count
, -1,
2682 -1, stream
->stream_fd
->fd
,
2683 &new_id
, &stream
->stream_fd
->fd
);
2685 ERR("Failed to rotate stream output file");
2686 status
= RELAY_CONNECTION_STATUS_ERROR
;
2687 goto end_stream_unlock
;
2691 * Reset current size because we just performed a stream
2694 stream
->tracefile_size_current
= 0;
2695 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2700 pthread_mutex_unlock(&stream
->lock
);
2706 static enum relay_connection_status
relay_process_data_receive_payload(
2707 struct relay_connection
*conn
)
2710 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2711 struct relay_stream
*stream
;
2712 struct data_connection_state_receive_payload
*state
=
2713 &conn
->protocol
.data
.state
.receive_payload
;
2714 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2715 char data_buffer
[chunk_size
];
2716 bool partial_recv
= false;
2717 bool new_stream
= false, close_requested
= false;
2718 uint64_t left_to_receive
= state
->left_to_receive
;
2719 struct relay_session
*session
;
2721 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2722 state
->header
.stream_id
, state
->header
.net_seq_num
,
2723 state
->received
, left_to_receive
);
2725 stream
= stream_get_by_id(state
->header
.stream_id
);
2727 /* Protocol error. */
2728 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2729 state
->header
.stream_id
);
2730 status
= RELAY_CONNECTION_STATUS_ERROR
;
2734 pthread_mutex_lock(&stream
->lock
);
2735 session
= stream
->trace
->session
;
2736 if (!conn
->session
) {
2737 ret
= connection_set_session(conn
, session
);
2739 status
= RELAY_CONNECTION_STATUS_ERROR
;
2740 goto end_stream_unlock
;
2745 * The size of the "chunk" received on any iteration is bounded by:
2746 * - the data left to receive,
2747 * - the data immediately available on the socket,
2748 * - the on-stack data buffer
2750 while (left_to_receive
> 0 && !partial_recv
) {
2752 size_t recv_size
= min(left_to_receive
, chunk_size
);
2754 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2755 recv_size
, MSG_DONTWAIT
);
2757 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2758 PERROR("Socket %d error", conn
->sock
->fd
);
2759 status
= RELAY_CONNECTION_STATUS_ERROR
;
2761 goto end_stream_unlock
;
2762 } else if (ret
== 0) {
2763 /* No more data ready to be consumed on socket. */
2764 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2765 state
->header
.stream_id
);
2766 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2768 } else if (ret
< (int) recv_size
) {
2770 * All the data available on the socket has been
2773 partial_recv
= true;
2778 /* Write data to stream output fd. */
2779 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2781 if (write_ret
< (ssize_t
) recv_size
) {
2782 ERR("Relay error writing data to file");
2783 status
= RELAY_CONNECTION_STATUS_ERROR
;
2784 goto end_stream_unlock
;
2787 left_to_receive
-= recv_size
;
2788 state
->received
+= recv_size
;
2789 state
->left_to_receive
= left_to_receive
;
2791 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2792 write_ret
, stream
->stream_handle
);
2795 if (state
->left_to_receive
> 0) {
2797 * Did not receive all the data expected, wait for more data to
2798 * become available on the socket.
2800 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2801 state
->header
.stream_id
, state
->received
,
2802 state
->left_to_receive
);
2803 goto end_stream_unlock
;
2806 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2807 state
->header
.padding_size
);
2808 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2809 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2810 stream
->stream_handle
,
2811 state
->header
.net_seq_num
, ret
);
2812 status
= RELAY_CONNECTION_STATUS_ERROR
;
2813 goto end_stream_unlock
;
2817 if (session
->minor
>= 4 && !session
->snapshot
) {
2818 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2819 state
->rotate_index
);
2821 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2822 stream
->stream_handle
,
2823 state
->header
.net_seq_num
, ret
);
2824 status
= RELAY_CONNECTION_STATUS_ERROR
;
2825 goto end_stream_unlock
;
2829 stream
->tracefile_size_current
+= state
->header
.data_size
+
2830 state
->header
.padding_size
;
2832 if (stream
->prev_seq
== -1ULL) {
2836 stream
->prev_seq
= state
->header
.net_seq_num
;
2839 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2840 * contents of *state which are aliased (union) to the same location as
2841 * the new state. Don't use it beyond this point.
2843 connection_reset_protocol_state(conn
);
2847 close_requested
= stream
->close_requested
;
2848 pthread_mutex_unlock(&stream
->lock
);
2849 if (close_requested
&& left_to_receive
== 0) {
2850 try_stream_close(stream
);
2854 pthread_mutex_lock(&session
->lock
);
2855 uatomic_set(&session
->new_streams
, 1);
2856 pthread_mutex_unlock(&session
->lock
);
2865 * relay_process_data: Process the data received on the data socket
2867 static enum relay_connection_status
relay_process_data(
2868 struct relay_connection
*conn
)
2870 enum relay_connection_status status
;
2872 switch (conn
->protocol
.data
.state_id
) {
2873 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2874 status
= relay_process_data_receive_header(conn
);
2876 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2877 status
= relay_process_data_receive_payload(conn
);
2880 ERR("Unexpected data connection communication state.");
2887 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2891 (void) lttng_poll_del(events
, pollfd
);
2893 ret
= close(pollfd
);
2895 ERR("Closing pollfd %d", pollfd
);
2899 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2900 int pollfd
, struct relay_connection
*conn
)
2902 const char *type_str
;
2904 switch (conn
->type
) {
2909 type_str
= "Control";
2911 case RELAY_VIEWER_COMMAND
:
2912 type_str
= "Viewer Command";
2914 case RELAY_VIEWER_NOTIFICATION
:
2915 type_str
= "Viewer Notification";
2918 type_str
= "Unknown";
2920 cleanup_connection_pollfd(events
, pollfd
);
2921 connection_put(conn
);
2922 DBG("%s connection closed with %d", type_str
, pollfd
);
2926 * This thread does the actual work
2928 static void *relay_thread_worker(void *data
)
2930 int ret
, err
= -1, last_seen_data_fd
= -1;
2932 struct lttng_poll_event events
;
2933 struct lttng_ht
*relay_connections_ht
;
2934 struct lttng_ht_iter iter
;
2935 struct relay_connection
*destroy_conn
= NULL
;
2937 DBG("[thread] Relay worker started");
2939 rcu_register_thread();
2941 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2943 if (testpoint(relayd_thread_worker
)) {
2944 goto error_testpoint
;
2947 health_code_update();
2949 /* table of connections indexed on socket */
2950 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2951 if (!relay_connections_ht
) {
2952 goto relay_connections_ht_error
;
2955 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
2957 goto error_poll_create
;
2960 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2967 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2969 health_code_update();
2971 /* Infinite blocking call, waiting for transmission */
2972 DBG3("Relayd worker thread polling...");
2973 health_poll_entry();
2974 ret
= lttng_poll_wait(&events
, -1);
2978 * Restart interrupted system call.
2980 if (errno
== EINTR
) {
2989 * Process control. The control connection is
2990 * prioritized so we don't starve it with high
2991 * throughput tracing data on the data connection.
2993 for (i
= 0; i
< nb_fd
; i
++) {
2994 /* Fetch once the poll data */
2995 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2996 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2998 health_code_update();
3002 * No activity for this FD (poll
3008 /* Thread quit pipe has been closed. Killing thread. */
3009 ret
= check_thread_quit_pipe(pollfd
, revents
);
3015 /* Inspect the relay conn pipe for new connection */
3016 if (pollfd
== relay_conn_pipe
[0]) {
3017 if (revents
& LPOLLIN
) {
3018 struct relay_connection
*conn
;
3020 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3024 lttng_poll_add(&events
, conn
->sock
->fd
,
3025 LPOLLIN
| LPOLLRDHUP
);
3026 connection_ht_add(relay_connections_ht
, conn
);
3027 DBG("Connection socket %d added", conn
->sock
->fd
);
3028 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3029 ERR("Relay connection pipe error");
3032 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3036 struct relay_connection
*ctrl_conn
;
3038 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3039 /* If not found, there is a synchronization issue. */
3042 if (ctrl_conn
->type
== RELAY_DATA
) {
3043 if (revents
& LPOLLIN
) {
3045 * Flag the last seen data fd not deleted. It will be
3046 * used as the last seen fd if any fd gets deleted in
3049 last_notdel_data_fd
= pollfd
;
3051 goto put_ctrl_connection
;
3053 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3055 if (revents
& LPOLLIN
) {
3056 enum relay_connection_status status
;
3058 status
= relay_process_control(ctrl_conn
);
3059 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3061 * On socket error flag the session as aborted to force
3062 * the cleanup of its stream otherwise it can leak
3063 * during the lifetime of the relayd.
3065 * This prevents situations in which streams can be
3066 * left opened because an index was received, the
3067 * control connection is closed, and the data
3068 * connection is closed (uncleanly) before the packet's
3071 * Since the control connection encountered an error,
3072 * it is okay to be conservative and close the
3073 * session right now as we can't rely on the protocol
3074 * being respected anymore.
3076 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3077 session_abort(ctrl_conn
->session
);
3080 /* Clear the connection on error or close. */
3081 relay_thread_close_connection(&events
,
3086 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3087 relay_thread_close_connection(&events
,
3089 if (last_seen_data_fd
== pollfd
) {
3090 last_seen_data_fd
= last_notdel_data_fd
;
3093 ERR("Unexpected poll events %u for control sock %d",
3095 connection_put(ctrl_conn
);
3098 put_ctrl_connection
:
3099 connection_put(ctrl_conn
);
3104 * The last loop handled a control request, go back to poll to make
3105 * sure we prioritise the control socket.
3111 if (last_seen_data_fd
>= 0) {
3112 for (i
= 0; i
< nb_fd
; i
++) {
3113 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3115 health_code_update();
3117 if (last_seen_data_fd
== pollfd
) {
3124 /* Process data connection. */
3125 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3126 /* Fetch the poll data. */
3127 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3128 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3129 struct relay_connection
*data_conn
;
3131 health_code_update();
3134 /* No activity for this FD (poll implementation). */
3138 /* Skip the command pipe. It's handled in the first loop. */
3139 if (pollfd
== relay_conn_pipe
[0]) {
3143 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3145 /* Skip it. Might be removed before. */
3148 if (data_conn
->type
== RELAY_CONTROL
) {
3149 goto put_data_connection
;
3151 assert(data_conn
->type
== RELAY_DATA
);
3153 if (revents
& LPOLLIN
) {
3154 enum relay_connection_status status
;
3156 status
= relay_process_data(data_conn
);
3157 /* Connection closed or error. */
3158 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3160 * On socket error flag the session as aborted to force
3161 * the cleanup of its stream otherwise it can leak
3162 * during the lifetime of the relayd.
3164 * This prevents situations in which streams can be
3165 * left opened because an index was received, the
3166 * control connection is closed, and the data
3167 * connection is closed (uncleanly) before the packet's
3170 * Since the data connection encountered an error,
3171 * it is okay to be conservative and close the
3172 * session right now as we can't rely on the protocol
3173 * being respected anymore.
3175 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3176 session_abort(data_conn
->session
);
3178 relay_thread_close_connection(&events
, pollfd
,
3181 * Every goto restart call sets the last seen fd where
3182 * here we don't really care since we gracefully
3183 * continue the loop after the connection is deleted.
3186 /* Keep last seen port. */
3187 last_seen_data_fd
= pollfd
;
3188 connection_put(data_conn
);
3191 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3192 relay_thread_close_connection(&events
, pollfd
,
3195 ERR("Unknown poll events %u for data sock %d",
3198 put_data_connection
:
3199 connection_put(data_conn
);
3201 last_seen_data_fd
= -1;
3204 /* Normal exit, no error */
3209 /* Cleanup reamaining connection object. */
3211 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3214 health_code_update();
3216 session_abort(destroy_conn
->session
);
3219 * No need to grab another ref, because we own
3222 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3227 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3229 lttng_ht_destroy(relay_connections_ht
);
3230 relay_connections_ht_error
:
3231 /* Close relay conn pipes */
3232 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3235 DBG("Thread exited with error");
3237 DBG("Worker thread cleanup complete");
3241 ERR("Health error occurred in %s", __func__
);
3243 health_unregister(health_relayd
);
3244 rcu_unregister_thread();
3245 lttng_relay_stop_threads();
3250 * Create the relay command pipe to wake thread_manage_apps.
3251 * Closed in cleanup().
3253 static int create_relay_conn_pipe(void)
3255 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3256 "Relayd connection pipe", relay_conn_pipe
);
3262 int main(int argc
, char **argv
)
3264 int ret
= 0, retval
= 0;
3267 /* Parse environment variables */
3268 parse_env_options();
3272 * Command line arguments overwrite environment.
3275 if (set_options(argc
, argv
)) {
3280 if (set_signal_handler()) {
3285 relayd_config_log();
3287 if (opt_print_version
) {
3293 ret
= fclose(stdin
);
3295 PERROR("Failed to close stdin");
3298 /* Try to create directory if -o, --output is specified. */
3299 if (opt_output_path
) {
3300 if (*opt_output_path
!= '/') {
3301 ERR("Please specify an absolute path for -o, --output PATH");
3306 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3309 ERR("Unable to create %s", opt_output_path
);
3316 if (opt_daemon
|| opt_background
) {
3317 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3325 if (opt_working_directory
) {
3326 ret
= utils_change_working_dir(opt_working_directory
);
3328 ERR("Changing working directory");
3333 * The RCU thread registration (and use, through the fd-tracker's
3334 * creation) is done after the daemonization to allow us to not
3335 * deal with liburcu's fork() management as the call RCU needs to
3338 rcu_register_thread();
3340 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
3341 if (!the_fd_tracker
) {
3346 /* Initialize thread health monitoring */
3347 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3348 if (!health_relayd
) {
3349 PERROR("health_app_create error");
3351 goto exit_health_app_create
;
3354 /* Create thread quit pipe */
3355 if (init_thread_quit_pipe()) {
3357 goto exit_init_data
;
3360 /* Setup the thread apps communication pipe. */
3361 if (create_relay_conn_pipe()) {
3363 goto exit_init_data
;
3366 /* Init relay command queue. */
3367 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3369 /* Initialize communication library */
3371 lttcomm_inet_init();
3373 /* tables of sessions indexed by session ID */
3374 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3377 goto exit_init_data
;
3380 /* tables of streams indexed by stream ID */
3381 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3382 if (!relay_streams_ht
) {
3384 goto exit_init_data
;
3387 /* tables of streams indexed by stream ID */
3388 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3389 if (!viewer_streams_ht
) {
3391 goto exit_init_data
;
3394 ret
= init_health_quit_pipe();
3397 goto exit_health_quit_pipe
;
3400 /* Create thread to manage the client socket */
3401 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3402 thread_manage_health
, (void *) NULL
);
3405 PERROR("pthread_create health");
3407 goto exit_health_thread
;
3410 /* Setup the dispatcher thread */
3411 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3412 relay_thread_dispatcher
, (void *) NULL
);
3415 PERROR("pthread_create dispatcher");
3417 goto exit_dispatcher_thread
;
3420 /* Setup the worker thread */
3421 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3422 relay_thread_worker
, NULL
);
3425 PERROR("pthread_create worker");
3427 goto exit_worker_thread
;
3430 /* Setup the listener thread */
3431 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3432 relay_thread_listener
, (void *) NULL
);
3435 PERROR("pthread_create listener");
3437 goto exit_listener_thread
;
3440 ret
= relayd_live_create(live_uri
);
3442 ERR("Starting live viewer threads");
3448 * This is where we start awaiting program completion (e.g. through
3449 * signal that asks threads to teardown).
3452 ret
= relayd_live_join();
3458 ret
= pthread_join(listener_thread
, &status
);
3461 PERROR("pthread_join listener_thread");
3465 exit_listener_thread
:
3466 ret
= pthread_join(worker_thread
, &status
);
3469 PERROR("pthread_join worker_thread");
3474 ret
= pthread_join(dispatcher_thread
, &status
);
3477 PERROR("pthread_join dispatcher_thread");
3480 exit_dispatcher_thread
:
3482 ret
= pthread_join(health_thread
, &status
);
3485 PERROR("pthread_join health_thread");
3490 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
3491 exit_health_quit_pipe
:
3494 health_app_destroy(health_relayd
);
3495 exit_health_app_create
:
3498 * Wait for all pending call_rcu work to complete before tearing
3499 * down data structures. call_rcu worker may be trying to
3500 * perform lookups in those structures.
3505 /* Ensure all prior call_rcu are done. */
3508 fd_tracker_destroy(the_fd_tracker
);
3509 rcu_unregister_thread();