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
);
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)
786 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
787 "Quit pipe", thread_quit_pipe
);
791 * Init health quit pipe.
793 * Return -1 on error or 0 if all pipes are created.
795 static int init_health_quit_pipe(void)
797 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
798 "Health quit pipe", health_quit_pipe
);
802 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
804 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
805 int size
, const char *name
)
809 if (events
== NULL
|| size
== 0) {
814 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
815 name
, events
, 1, LTTNG_CLOEXEC
);
818 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
830 * Check if the thread quit pipe was triggered.
832 * Return 1 if it was triggered else 0;
834 static int check_thread_quit_pipe(int fd
, uint32_t events
)
836 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
843 static int create_sock(void *data
, int *out_fd
)
846 struct lttcomm_sock
*sock
= data
;
848 ret
= lttcomm_create_sock(sock
);
858 static int close_sock(void *data
, int *in_fd
)
860 struct lttcomm_sock
*sock
= data
;
862 return sock
->ops
->close(sock
);
866 * Create and init socket from uri.
868 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
872 struct lttcomm_sock
*sock
= NULL
;
873 char uri_str
[PATH_MAX
];
874 char *formated_name
= NULL
;
876 sock
= lttcomm_alloc_sock_from_uri(uri
);
878 ERR("Allocating socket");
883 * Don't fail to create the socket if the name can't be built as it is
884 * only used for debugging purposes.
886 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
887 uri_str
[sizeof(uri_str
) - 1] = '\0';
889 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
892 formated_name
= NULL
;
896 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
897 (const char **) (formated_name
? &formated_name
: NULL
),
898 1, create_sock
, sock
);
900 DBG("Listening on %s socket %d", name
, sock
->fd
);
902 ret
= sock
->ops
->bind(sock
);
907 ret
= sock
->ops
->listen(sock
, -1);
917 lttcomm_destroy_sock(sock
);
923 * This thread manages the listening for new connections on the network
925 static void *relay_thread_listener(void *data
)
927 int i
, ret
, pollfd
, err
= -1;
928 uint32_t revents
, nb_fd
;
929 struct lttng_poll_event events
;
930 struct lttcomm_sock
*control_sock
, *data_sock
;
932 DBG("[thread] Relay listener started");
934 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
936 health_code_update();
938 control_sock
= relay_socket_create(control_uri
, "Control listener");
940 goto error_sock_control
;
943 data_sock
= relay_socket_create(data_uri
, NULL
);
945 goto error_sock_relay
;
949 * Pass 3 as size here for the thread quit pipe, control and
952 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
954 goto error_create_poll
;
957 /* Add the control socket */
958 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
963 /* Add the data socket */
964 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
969 lttng_relay_notify_ready();
971 if (testpoint(relayd_thread_listener
)) {
972 goto error_testpoint
;
976 health_code_update();
978 DBG("Listener accepting connections");
982 ret
= lttng_poll_wait(&events
, -1);
986 * Restart interrupted system call.
988 if (errno
== EINTR
) {
996 DBG("Relay new connection received");
997 for (i
= 0; i
< nb_fd
; i
++) {
998 health_code_update();
1000 /* Fetch once the poll data */
1001 revents
= LTTNG_POLL_GETEV(&events
, i
);
1002 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1006 * No activity for this FD (poll
1012 /* Thread quit pipe has been closed. Killing thread. */
1013 ret
= check_thread_quit_pipe(pollfd
, revents
);
1019 if (revents
& LPOLLIN
) {
1021 * A new connection is requested, therefore a
1022 * sessiond/consumerd connection is allocated in
1023 * this thread, enqueued to a global queue and
1024 * dequeued (and freed) in the worker thread.
1027 struct relay_connection
*new_conn
;
1028 struct lttcomm_sock
*newsock
;
1029 enum connection_type type
;
1031 if (pollfd
== data_sock
->fd
) {
1033 newsock
= data_sock
->ops
->accept(data_sock
);
1034 DBG("Relay data connection accepted, socket %d",
1037 assert(pollfd
== control_sock
->fd
);
1038 type
= RELAY_CONTROL
;
1039 newsock
= control_sock
->ops
->accept(control_sock
);
1040 DBG("Relay control connection accepted, socket %d",
1044 PERROR("accepting sock");
1048 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1051 PERROR("setsockopt inet");
1052 lttcomm_destroy_sock(newsock
);
1056 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1058 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1060 lttcomm_destroy_sock(newsock
);
1064 new_conn
= connection_create(newsock
, type
);
1066 lttcomm_destroy_sock(newsock
);
1070 /* Enqueue request for the dispatcher thread. */
1071 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1075 * Wake the dispatch queue futex.
1076 * Implicit memory barrier with the
1077 * exchange in cds_wfcq_enqueue.
1079 futex_nto1_wake(&relay_conn_queue
.futex
);
1080 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1081 ERR("socket poll error");
1084 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1094 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1096 if (data_sock
->fd
>= 0) {
1097 ret
= data_sock
->ops
->close(data_sock
);
1102 lttcomm_destroy_sock(data_sock
);
1104 if (control_sock
->fd
>= 0) {
1105 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1106 &control_sock
->fd
, 1, close_sock
,
1112 lttcomm_destroy_sock(control_sock
);
1116 ERR("Health error occurred in %s", __func__
);
1118 health_unregister(health_relayd
);
1119 DBG("Relay listener thread cleanup complete");
1120 lttng_relay_stop_threads();
1125 * This thread manages the dispatching of the requests to worker threads
1127 static void *relay_thread_dispatcher(void *data
)
1131 struct cds_wfcq_node
*node
;
1132 struct relay_connection
*new_conn
= NULL
;
1134 DBG("[thread] Relay dispatcher started");
1136 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1138 if (testpoint(relayd_thread_dispatcher
)) {
1139 goto error_testpoint
;
1142 health_code_update();
1145 health_code_update();
1147 /* Atomically prepare the queue futex */
1148 futex_nto1_prepare(&relay_conn_queue
.futex
);
1150 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1155 health_code_update();
1157 /* Dequeue commands */
1158 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1159 &relay_conn_queue
.tail
);
1161 DBG("Woken up but nothing in the relay command queue");
1162 /* Continue thread execution */
1165 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1167 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1170 * Inform worker thread of the new request. This
1171 * call is blocking so we can be assured that
1172 * the data will be read at some point in time
1173 * or wait to the end of the world :)
1175 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1177 PERROR("write connection pipe");
1178 connection_put(new_conn
);
1181 } while (node
!= NULL
);
1183 /* Futex wait on queue. Blocking call on futex() */
1184 health_poll_entry();
1185 futex_nto1_wait(&relay_conn_queue
.futex
);
1189 /* Normal exit, no error */
1196 ERR("Health error occurred in %s", __func__
);
1198 health_unregister(health_relayd
);
1199 DBG("Dispatch thread dying");
1200 lttng_relay_stop_threads();
1205 * Set index data from the control port to a given index object.
1207 static int set_index_control_data(struct relay_index
*index
,
1208 struct lttcomm_relayd_index
*data
,
1209 struct relay_connection
*conn
)
1211 struct ctf_packet_index index_data
;
1214 * The index on disk is encoded in big endian.
1216 index_data
.packet_size
= htobe64(data
->packet_size
);
1217 index_data
.content_size
= htobe64(data
->content_size
);
1218 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1219 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1220 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1221 index_data
.stream_id
= htobe64(data
->stream_id
);
1223 if (conn
->minor
>= 8) {
1224 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1225 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1228 return relay_index_set_data(index
, &index_data
);
1232 * Handle the RELAYD_CREATE_SESSION command.
1234 * On success, send back the session id or else return a negative value.
1236 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1237 struct relay_connection
*conn
,
1238 const struct lttng_buffer_view
*payload
)
1242 struct relay_session
*session
;
1243 struct lttcomm_relayd_status_session reply
;
1244 char session_name
[LTTNG_NAME_MAX
];
1245 char hostname
[LTTNG_HOST_NAME_MAX
];
1246 uint32_t live_timer
= 0;
1247 bool snapshot
= false;
1249 memset(session_name
, 0, LTTNG_NAME_MAX
);
1250 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1252 memset(&reply
, 0, sizeof(reply
));
1254 switch (conn
->minor
) {
1259 case 4: /* LTTng sessiond 2.4 */
1261 ret
= cmd_create_session_2_4(payload
, session_name
,
1262 hostname
, &live_timer
, &snapshot
);
1268 session
= session_create(session_name
, hostname
, live_timer
,
1269 snapshot
, conn
->major
, conn
->minor
);
1274 assert(!conn
->session
);
1275 conn
->session
= session
;
1276 DBG("Created session %" PRIu64
, session
->id
);
1278 reply
.session_id
= htobe64(session
->id
);
1282 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1284 reply
.ret_code
= htobe32(LTTNG_OK
);
1287 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1288 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1289 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1298 * When we have received all the streams and the metadata for a channel,
1299 * we make them visible to the viewer threads.
1301 static void publish_connection_local_streams(struct relay_connection
*conn
)
1303 struct relay_stream
*stream
;
1304 struct relay_session
*session
= conn
->session
;
1307 * We publish all streams belonging to a session atomically wrt
1310 pthread_mutex_lock(&session
->lock
);
1312 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1314 stream_publish(stream
);
1319 * Inform the viewer that there are new streams in the session.
1321 if (session
->viewer_attached
) {
1322 uatomic_set(&session
->new_streams
, 1);
1324 pthread_mutex_unlock(&session
->lock
);
1328 * relay_add_stream: allocate a new stream for a session
1330 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1331 struct relay_connection
*conn
,
1332 const struct lttng_buffer_view
*payload
)
1336 struct relay_session
*session
= conn
->session
;
1337 struct relay_stream
*stream
= NULL
;
1338 struct lttcomm_relayd_status_stream reply
;
1339 struct ctf_trace
*trace
= NULL
;
1340 uint64_t stream_handle
= -1ULL;
1341 char *path_name
= NULL
, *channel_name
= NULL
;
1342 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1344 if (!session
|| !conn
->version_check_done
) {
1345 ERR("Trying to add a stream before version check");
1347 goto end_no_session
;
1350 switch (session
->minor
) {
1351 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1352 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1353 &channel_name
, session
);
1355 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1357 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1358 &channel_name
, &tracefile_size
, &tracefile_count
,
1366 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1370 /* This stream here has one reference on the trace. */
1372 pthread_mutex_lock(&last_relay_stream_id_lock
);
1373 stream_handle
= ++last_relay_stream_id
;
1374 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1376 /* We pass ownership of path_name and channel_name. */
1377 stream
= stream_create(trace
, stream_handle
, path_name
,
1378 channel_name
, tracefile_size
, tracefile_count
);
1380 channel_name
= NULL
;
1383 * Streams are the owners of their trace. Reference to trace is
1384 * kept within stream_create().
1386 ctf_trace_put(trace
);
1389 memset(&reply
, 0, sizeof(reply
));
1390 reply
.handle
= htobe64(stream_handle
);
1392 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1394 reply
.ret_code
= htobe32(LTTNG_OK
);
1397 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1398 sizeof(struct lttcomm_relayd_status_stream
), 0);
1399 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1400 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1412 * relay_close_stream: close a specific stream
1414 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1415 struct relay_connection
*conn
,
1416 const struct lttng_buffer_view
*payload
)
1420 struct relay_session
*session
= conn
->session
;
1421 struct lttcomm_relayd_close_stream stream_info
;
1422 struct lttcomm_relayd_generic_reply reply
;
1423 struct relay_stream
*stream
;
1425 DBG("Close stream received");
1427 if (!session
|| !conn
->version_check_done
) {
1428 ERR("Trying to close a stream before version check");
1430 goto end_no_session
;
1433 if (payload
->size
< sizeof(stream_info
)) {
1434 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1435 sizeof(stream_info
), payload
->size
);
1437 goto end_no_session
;
1439 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1440 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1441 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1443 stream
= stream_get_by_id(stream_info
.stream_id
);
1450 * Set last_net_seq_num before the close flag. Required by data
1453 pthread_mutex_lock(&stream
->lock
);
1454 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1455 pthread_mutex_unlock(&stream
->lock
);
1458 * This is one of the conditions which may trigger a stream close
1459 * with the others being:
1460 * 1) A close command is received for a stream
1461 * 2) The control connection owning the stream is closed
1462 * 3) We have received all of the stream's data _after_ a close
1465 try_stream_close(stream
);
1466 if (stream
->is_metadata
) {
1467 struct relay_viewer_stream
*vstream
;
1469 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1471 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1473 * Since all the metadata has been sent to the
1474 * viewer and that we have a request to close
1475 * its stream, we can safely teardown the
1476 * corresponding metadata viewer stream.
1478 viewer_stream_put(vstream
);
1480 /* Put local reference. */
1481 viewer_stream_put(vstream
);
1488 memset(&reply
, 0, sizeof(reply
));
1490 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1492 reply
.ret_code
= htobe32(LTTNG_OK
);
1494 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1495 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1496 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1497 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1507 * relay_reset_metadata: reset a metadata stream
1510 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1511 struct relay_connection
*conn
,
1512 const struct lttng_buffer_view
*payload
)
1516 struct relay_session
*session
= conn
->session
;
1517 struct lttcomm_relayd_reset_metadata stream_info
;
1518 struct lttcomm_relayd_generic_reply reply
;
1519 struct relay_stream
*stream
;
1521 DBG("Reset metadata received");
1523 if (!session
|| !conn
->version_check_done
) {
1524 ERR("Trying to reset a metadata stream before version check");
1526 goto end_no_session
;
1529 if (payload
->size
< sizeof(stream_info
)) {
1530 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1531 sizeof(stream_info
), payload
->size
);
1533 goto end_no_session
;
1535 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1536 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1537 stream_info
.version
= be64toh(stream_info
.version
);
1539 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1541 /* Unsupported for live sessions for now. */
1542 if (session
->live_timer
!= 0) {
1547 stream
= stream_get_by_id(stream_info
.stream_id
);
1552 pthread_mutex_lock(&stream
->lock
);
1553 if (!stream
->is_metadata
) {
1558 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1559 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1560 &stream
->stream_fd
->fd
);
1562 ERR("Failed to rotate metadata file %s of channel %s",
1563 stream
->path_name
, stream
->channel_name
);
1568 pthread_mutex_unlock(&stream
->lock
);
1572 memset(&reply
, 0, sizeof(reply
));
1574 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1576 reply
.ret_code
= htobe32(LTTNG_OK
);
1578 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1579 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1580 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1581 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1591 * relay_unknown_command: send -1 if received unknown command
1593 static void relay_unknown_command(struct relay_connection
*conn
)
1595 struct lttcomm_relayd_generic_reply reply
;
1598 memset(&reply
, 0, sizeof(reply
));
1599 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1600 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1601 if (send_ret
< sizeof(reply
)) {
1602 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1607 * relay_start: send an acknowledgment to the client to tell if we are
1608 * ready to receive data. We are ready if a session is established.
1610 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1611 struct relay_connection
*conn
,
1612 const struct lttng_buffer_view
*payload
)
1616 struct lttcomm_relayd_generic_reply reply
;
1617 struct relay_session
*session
= conn
->session
;
1620 DBG("Trying to start the streaming without a session established");
1621 ret
= htobe32(LTTNG_ERR_UNK
);
1624 memset(&reply
, 0, sizeof(reply
));
1625 reply
.ret_code
= htobe32(LTTNG_OK
);
1626 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1628 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1629 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1638 * Append padding to the file pointed by the file descriptor fd.
1640 static int write_padding_to_file(int fd
, uint32_t size
)
1649 zeros
= zmalloc(size
);
1650 if (zeros
== NULL
) {
1651 PERROR("zmalloc zeros for padding");
1656 ret
= lttng_write(fd
, zeros
, size
);
1658 PERROR("write padding to file");
1668 * relay_recv_metadata: receive the metadata for the session.
1670 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1671 struct relay_connection
*conn
,
1672 const struct lttng_buffer_view
*payload
)
1676 struct relay_session
*session
= conn
->session
;
1677 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1678 struct relay_stream
*metadata_stream
;
1679 uint64_t metadata_payload_size
;
1682 ERR("Metadata sent before version check");
1687 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1688 ERR("Incorrect data size");
1692 metadata_payload_size
= recv_hdr
->data_size
-
1693 sizeof(struct lttcomm_relayd_metadata_payload
);
1695 memcpy(&metadata_payload_header
, payload
->data
,
1696 sizeof(metadata_payload_header
));
1697 metadata_payload_header
.stream_id
= be64toh(
1698 metadata_payload_header
.stream_id
);
1699 metadata_payload_header
.padding_size
= be32toh(
1700 metadata_payload_header
.padding_size
);
1702 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1703 if (!metadata_stream
) {
1708 pthread_mutex_lock(&metadata_stream
->lock
);
1710 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1711 payload
->data
+ sizeof(metadata_payload_header
),
1712 metadata_payload_size
);
1713 if (size_ret
< metadata_payload_size
) {
1714 ERR("Relay error writing metadata on file");
1719 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1720 metadata_payload_header
.padding_size
);
1721 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1726 metadata_stream
->metadata_received
+=
1727 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1728 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1729 metadata_stream
->metadata_received
);
1732 pthread_mutex_unlock(&metadata_stream
->lock
);
1733 stream_put(metadata_stream
);
1739 * relay_send_version: send relayd version number
1741 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1742 struct relay_connection
*conn
,
1743 const struct lttng_buffer_view
*payload
)
1747 struct lttcomm_relayd_version reply
, msg
;
1748 bool compatible
= true;
1750 conn
->version_check_done
= true;
1752 /* Get version from the other side. */
1753 if (payload
->size
< sizeof(msg
)) {
1754 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1755 sizeof(msg
), payload
->size
);
1760 memcpy(&msg
, payload
->data
, sizeof(msg
));
1761 msg
.major
= be32toh(msg
.major
);
1762 msg
.minor
= be32toh(msg
.minor
);
1764 memset(&reply
, 0, sizeof(reply
));
1765 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1766 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1768 /* Major versions must be the same */
1769 if (reply
.major
!= msg
.major
) {
1770 DBG("Incompatible major versions (%u vs %u), deleting session",
1771 reply
.major
, msg
.major
);
1775 conn
->major
= reply
.major
;
1776 /* We adapt to the lowest compatible version */
1777 if (reply
.minor
<= msg
.minor
) {
1778 conn
->minor
= reply
.minor
;
1780 conn
->minor
= msg
.minor
;
1783 reply
.major
= htobe32(reply
.major
);
1784 reply
.minor
= htobe32(reply
.minor
);
1785 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1787 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1788 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1801 DBG("Version check done using protocol %u.%u", conn
->major
,
1809 * Check for data pending for a given stream id from the session daemon.
1811 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1812 struct relay_connection
*conn
,
1813 const struct lttng_buffer_view
*payload
)
1815 struct relay_session
*session
= conn
->session
;
1816 struct lttcomm_relayd_data_pending msg
;
1817 struct lttcomm_relayd_generic_reply reply
;
1818 struct relay_stream
*stream
;
1822 DBG("Data pending command received");
1824 if (!session
|| !conn
->version_check_done
) {
1825 ERR("Trying to check for data before version check");
1827 goto end_no_session
;
1830 if (payload
->size
< sizeof(msg
)) {
1831 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1832 sizeof(msg
), payload
->size
);
1834 goto end_no_session
;
1836 memcpy(&msg
, payload
->data
, sizeof(msg
));
1837 msg
.stream_id
= be64toh(msg
.stream_id
);
1838 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1840 stream
= stream_get_by_id(msg
.stream_id
);
1841 if (stream
== NULL
) {
1846 pthread_mutex_lock(&stream
->lock
);
1848 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1849 " and last_seq %" PRIu64
, msg
.stream_id
,
1850 stream
->prev_seq
, msg
.last_net_seq_num
);
1852 /* Avoid wrapping issue */
1853 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1854 /* Data has in fact been written and is NOT pending */
1857 /* Data still being streamed thus pending */
1861 stream
->data_pending_check_done
= true;
1862 pthread_mutex_unlock(&stream
->lock
);
1867 memset(&reply
, 0, sizeof(reply
));
1868 reply
.ret_code
= htobe32(ret
);
1869 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1870 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1871 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1881 * Wait for the control socket to reach a quiescent state.
1883 * Note that for now, when receiving this command from the session
1884 * daemon, this means that every subsequent commands or data received on
1885 * the control socket has been handled. So, this is why we simply return
1888 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1889 struct relay_connection
*conn
,
1890 const struct lttng_buffer_view
*payload
)
1894 struct relay_stream
*stream
;
1895 struct lttcomm_relayd_quiescent_control msg
;
1896 struct lttcomm_relayd_generic_reply reply
;
1898 DBG("Checking quiescent state on control socket");
1900 if (!conn
->session
|| !conn
->version_check_done
) {
1901 ERR("Trying to check for data before version check");
1903 goto end_no_session
;
1906 if (payload
->size
< sizeof(msg
)) {
1907 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1908 sizeof(msg
), payload
->size
);
1910 goto end_no_session
;
1912 memcpy(&msg
, payload
->data
, sizeof(msg
));
1913 msg
.stream_id
= be64toh(msg
.stream_id
);
1915 stream
= stream_get_by_id(msg
.stream_id
);
1919 pthread_mutex_lock(&stream
->lock
);
1920 stream
->data_pending_check_done
= true;
1921 pthread_mutex_unlock(&stream
->lock
);
1923 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1926 memset(&reply
, 0, sizeof(reply
));
1927 reply
.ret_code
= htobe32(LTTNG_OK
);
1928 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1929 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1930 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1942 * Initialize a data pending command. This means that a consumer is about
1943 * to ask for data pending for each stream it holds. Simply iterate over
1944 * all streams of a session and set the data_pending_check_done flag.
1946 * This command returns to the client a LTTNG_OK code.
1948 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1949 struct relay_connection
*conn
,
1950 const struct lttng_buffer_view
*payload
)
1954 struct lttng_ht_iter iter
;
1955 struct lttcomm_relayd_begin_data_pending msg
;
1956 struct lttcomm_relayd_generic_reply reply
;
1957 struct relay_stream
*stream
;
1962 DBG("Init streams for data pending");
1964 if (!conn
->session
|| !conn
->version_check_done
) {
1965 ERR("Trying to check for data before version check");
1967 goto end_no_session
;
1970 if (payload
->size
< sizeof(msg
)) {
1971 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1972 sizeof(msg
), payload
->size
);
1974 goto end_no_session
;
1976 memcpy(&msg
, payload
->data
, sizeof(msg
));
1977 msg
.session_id
= be64toh(msg
.session_id
);
1980 * Iterate over all streams to set the begin data pending flag.
1981 * For now, the streams are indexed by stream handle so we have
1982 * to iterate over all streams to find the one associated with
1983 * the right session_id.
1986 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1988 if (!stream_get(stream
)) {
1991 if (stream
->trace
->session
->id
== msg
.session_id
) {
1992 pthread_mutex_lock(&stream
->lock
);
1993 stream
->data_pending_check_done
= false;
1994 pthread_mutex_unlock(&stream
->lock
);
1995 DBG("Set begin data pending flag to stream %" PRIu64
,
1996 stream
->stream_handle
);
2002 memset(&reply
, 0, sizeof(reply
));
2003 /* All good, send back reply. */
2004 reply
.ret_code
= htobe32(LTTNG_OK
);
2006 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2007 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2008 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2020 * End data pending command. This will check, for a given session id, if
2021 * each stream associated with it has its data_pending_check_done flag
2022 * set. If not, this means that the client lost track of the stream but
2023 * the data is still being streamed on our side. In this case, we inform
2024 * the client that data is in flight.
2026 * Return to the client if there is data in flight or not with a ret_code.
2028 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2029 struct relay_connection
*conn
,
2030 const struct lttng_buffer_view
*payload
)
2034 struct lttng_ht_iter iter
;
2035 struct lttcomm_relayd_end_data_pending msg
;
2036 struct lttcomm_relayd_generic_reply reply
;
2037 struct relay_stream
*stream
;
2038 uint32_t is_data_inflight
= 0;
2040 DBG("End data pending command");
2042 if (!conn
->session
|| !conn
->version_check_done
) {
2043 ERR("Trying to check for data before version check");
2045 goto end_no_session
;
2048 if (payload
->size
< sizeof(msg
)) {
2049 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2050 sizeof(msg
), payload
->size
);
2052 goto end_no_session
;
2054 memcpy(&msg
, payload
->data
, sizeof(msg
));
2055 msg
.session_id
= be64toh(msg
.session_id
);
2058 * Iterate over all streams to see if the begin data pending
2062 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2064 if (!stream_get(stream
)) {
2067 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2071 pthread_mutex_lock(&stream
->lock
);
2072 if (!stream
->data_pending_check_done
) {
2073 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2074 is_data_inflight
= 1;
2075 DBG("Data is still in flight for stream %" PRIu64
,
2076 stream
->stream_handle
);
2077 pthread_mutex_unlock(&stream
->lock
);
2082 pthread_mutex_unlock(&stream
->lock
);
2087 memset(&reply
, 0, sizeof(reply
));
2088 /* All good, send back reply. */
2089 reply
.ret_code
= htobe32(is_data_inflight
);
2091 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2092 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2093 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2105 * Receive an index for a specific stream.
2107 * Return 0 on success else a negative value.
2109 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2110 struct relay_connection
*conn
,
2111 const struct lttng_buffer_view
*payload
)
2115 struct relay_session
*session
= conn
->session
;
2116 struct lttcomm_relayd_index index_info
;
2117 struct relay_index
*index
;
2118 struct lttcomm_relayd_generic_reply reply
;
2119 struct relay_stream
*stream
;
2124 DBG("Relay receiving index");
2126 if (!session
|| !conn
->version_check_done
) {
2127 ERR("Trying to close a stream before version check");
2129 goto end_no_session
;
2132 msg_len
= lttcomm_relayd_index_len(
2133 lttng_to_index_major(conn
->major
, conn
->minor
),
2134 lttng_to_index_minor(conn
->major
, conn
->minor
));
2135 if (payload
->size
< msg_len
) {
2136 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2137 msg_len
, payload
->size
);
2139 goto end_no_session
;
2141 memcpy(&index_info
, payload
->data
, msg_len
);
2142 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2143 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2144 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2145 index_info
.content_size
= be64toh(index_info
.content_size
);
2146 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2147 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2148 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2149 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2151 if (conn
->minor
>= 8) {
2152 index_info
.stream_instance_id
=
2153 be64toh(index_info
.stream_instance_id
);
2154 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2157 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2159 ERR("stream_get_by_id not found");
2163 pthread_mutex_lock(&stream
->lock
);
2165 /* Live beacon handling */
2166 if (index_info
.packet_size
== 0) {
2167 DBG("Received live beacon for stream %" PRIu64
,
2168 stream
->stream_handle
);
2171 * Only flag a stream inactive when it has already
2172 * received data and no indexes are in flight.
2174 if (stream
->index_received_seqcount
> 0
2175 && stream
->indexes_in_flight
== 0) {
2176 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2179 goto end_stream_put
;
2181 stream
->beacon_ts_end
= -1ULL;
2184 if (stream
->ctf_stream_id
== -1ULL) {
2185 stream
->ctf_stream_id
= index_info
.stream_id
;
2187 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2190 ERR("relay_index_get_by_id_or_create index NULL");
2191 goto end_stream_put
;
2193 if (set_index_control_data(index
, &index_info
, conn
)) {
2194 ERR("set_index_control_data error");
2195 relay_index_put(index
);
2197 goto end_stream_put
;
2199 ret
= relay_index_try_flush(index
);
2201 tracefile_array_commit_seq(stream
->tfa
);
2202 stream
->index_received_seqcount
++;
2203 } else if (ret
> 0) {
2207 ERR("relay_index_try_flush error %d", ret
);
2208 relay_index_put(index
);
2213 pthread_mutex_unlock(&stream
->lock
);
2218 memset(&reply
, 0, sizeof(reply
));
2220 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2222 reply
.ret_code
= htobe32(LTTNG_OK
);
2224 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2225 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2226 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2235 * Receive the streams_sent message.
2237 * Return 0 on success else a negative value.
2239 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2240 struct relay_connection
*conn
,
2241 const struct lttng_buffer_view
*payload
)
2245 struct lttcomm_relayd_generic_reply reply
;
2249 DBG("Relay receiving streams_sent");
2251 if (!conn
->session
|| !conn
->version_check_done
) {
2252 ERR("Trying to close a stream before version check");
2254 goto end_no_session
;
2258 * Publish every pending stream in the connection recv list which are
2259 * now ready to be used by the viewer.
2261 publish_connection_local_streams(conn
);
2263 memset(&reply
, 0, sizeof(reply
));
2264 reply
.ret_code
= htobe32(LTTNG_OK
);
2265 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2266 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2267 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2279 #define DBG_CMD(cmd_name, conn) \
2280 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2282 static int relay_process_control_command(struct relay_connection
*conn
,
2283 const struct lttcomm_relayd_hdr
*header
,
2284 const struct lttng_buffer_view
*payload
)
2288 switch (header
->cmd
) {
2289 case RELAYD_CREATE_SESSION
:
2290 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2291 ret
= relay_create_session(header
, conn
, payload
);
2293 case RELAYD_ADD_STREAM
:
2294 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2295 ret
= relay_add_stream(header
, conn
, payload
);
2297 case RELAYD_START_DATA
:
2298 DBG_CMD("RELAYD_START_DATA", conn
);
2299 ret
= relay_start(header
, conn
, payload
);
2301 case RELAYD_SEND_METADATA
:
2302 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2303 ret
= relay_recv_metadata(header
, conn
, payload
);
2305 case RELAYD_VERSION
:
2306 DBG_CMD("RELAYD_VERSION", conn
);
2307 ret
= relay_send_version(header
, conn
, payload
);
2309 case RELAYD_CLOSE_STREAM
:
2310 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2311 ret
= relay_close_stream(header
, conn
, payload
);
2313 case RELAYD_DATA_PENDING
:
2314 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2315 ret
= relay_data_pending(header
, conn
, payload
);
2317 case RELAYD_QUIESCENT_CONTROL
:
2318 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2319 ret
= relay_quiescent_control(header
, conn
, payload
);
2321 case RELAYD_BEGIN_DATA_PENDING
:
2322 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2323 ret
= relay_begin_data_pending(header
, conn
, payload
);
2325 case RELAYD_END_DATA_PENDING
:
2326 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2327 ret
= relay_end_data_pending(header
, conn
, payload
);
2329 case RELAYD_SEND_INDEX
:
2330 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2331 ret
= relay_recv_index(header
, conn
, payload
);
2333 case RELAYD_STREAMS_SENT
:
2334 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2335 ret
= relay_streams_sent(header
, conn
, payload
);
2337 case RELAYD_RESET_METADATA
:
2338 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2339 ret
= relay_reset_metadata(header
, conn
, payload
);
2341 case RELAYD_UPDATE_SYNC_INFO
:
2343 ERR("Received unknown command (%u)", header
->cmd
);
2344 relay_unknown_command(conn
);
2353 static enum relay_connection_status
relay_process_control_receive_payload(
2354 struct relay_connection
*conn
)
2357 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2358 struct lttng_dynamic_buffer
*reception_buffer
=
2359 &conn
->protocol
.ctrl
.reception_buffer
;
2360 struct ctrl_connection_state_receive_payload
*state
=
2361 &conn
->protocol
.ctrl
.state
.receive_payload
;
2362 struct lttng_buffer_view payload_view
;
2364 if (state
->left_to_receive
== 0) {
2365 /* Short-circuit for payload-less commands. */
2366 goto reception_complete
;
2368 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2369 reception_buffer
->data
+ state
->received
,
2370 state
->left_to_receive
, MSG_DONTWAIT
);
2372 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2373 PERROR("Unable to receive command payload on sock %d",
2375 status
= RELAY_CONNECTION_STATUS_ERROR
;
2378 } else if (ret
== 0) {
2379 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2380 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2385 assert(ret
<= state
->left_to_receive
);
2387 state
->left_to_receive
-= ret
;
2388 state
->received
+= ret
;
2390 if (state
->left_to_receive
> 0) {
2392 * Can't transition to the protocol's next state, wait to
2393 * receive the rest of the header.
2395 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2396 state
->received
, state
->left_to_receive
,
2402 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2403 conn
->sock
->fd
, state
->received
);
2405 * The payload required to process the command has been received.
2406 * A view to the reception buffer is forwarded to the various
2407 * commands and the state of the control is reset on success.
2409 * Commands are responsible for sending their reply to the peer.
2411 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2413 ret
= relay_process_control_command(conn
,
2414 &state
->header
, &payload_view
);
2416 status
= RELAY_CONNECTION_STATUS_ERROR
;
2420 ret
= connection_reset_protocol_state(conn
);
2422 status
= RELAY_CONNECTION_STATUS_ERROR
;
2428 static enum relay_connection_status
relay_process_control_receive_header(
2429 struct relay_connection
*conn
)
2432 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2433 struct lttcomm_relayd_hdr header
;
2434 struct lttng_dynamic_buffer
*reception_buffer
=
2435 &conn
->protocol
.ctrl
.reception_buffer
;
2436 struct ctrl_connection_state_receive_header
*state
=
2437 &conn
->protocol
.ctrl
.state
.receive_header
;
2439 assert(state
->left_to_receive
!= 0);
2441 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2442 reception_buffer
->data
+ state
->received
,
2443 state
->left_to_receive
, MSG_DONTWAIT
);
2445 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2446 PERROR("Unable to receive control command header on sock %d",
2448 status
= RELAY_CONNECTION_STATUS_ERROR
;
2451 } else if (ret
== 0) {
2452 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2453 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2458 assert(ret
<= state
->left_to_receive
);
2460 state
->left_to_receive
-= ret
;
2461 state
->received
+= ret
;
2463 if (state
->left_to_receive
> 0) {
2465 * Can't transition to the protocol's next state, wait to
2466 * receive the rest of the header.
2468 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2469 state
->received
, state
->left_to_receive
,
2474 /* Transition to next state: receiving the command's payload. */
2475 conn
->protocol
.ctrl
.state_id
=
2476 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2477 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2478 header
.circuit_id
= be64toh(header
.circuit_id
);
2479 header
.data_size
= be64toh(header
.data_size
);
2480 header
.cmd
= be32toh(header
.cmd
);
2481 header
.cmd_version
= be32toh(header
.cmd_version
);
2482 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2483 &header
, sizeof(header
));
2485 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2486 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2489 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2490 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2492 status
= RELAY_CONNECTION_STATUS_ERROR
;
2496 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2498 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2499 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2502 status
= RELAY_CONNECTION_STATUS_ERROR
;
2506 if (header
.data_size
== 0) {
2508 * Manually invoke the next state as the poll loop
2509 * will not wake-up to allow us to proceed further.
2511 status
= relay_process_control_receive_payload(conn
);
2518 * Process the commands received on the control socket
2520 static enum relay_connection_status
relay_process_control(
2521 struct relay_connection
*conn
)
2523 enum relay_connection_status status
;
2525 switch (conn
->protocol
.ctrl
.state_id
) {
2526 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2527 status
= relay_process_control_receive_header(conn
);
2529 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2530 status
= relay_process_control_receive_payload(conn
);
2533 ERR("Unknown control connection protocol state encountered.");
2541 * Handle index for a data stream.
2543 * Called with the stream lock held.
2545 * Return 0 on success else a negative value.
2547 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2551 uint64_t data_offset
;
2552 struct relay_index
*index
;
2554 /* Get data offset because we are about to update the index. */
2555 data_offset
= htobe64(stream
->tracefile_size_current
);
2557 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2558 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2561 * Lookup for an existing index for that stream id/sequence
2562 * number. If it exists, the control thread has already received the
2563 * data for it, thus we need to write it to disk.
2565 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2571 if (rotate_index
|| !stream
->index_file
) {
2572 uint32_t major
, minor
;
2574 /* Put ref on previous index_file. */
2575 if (stream
->index_file
) {
2576 lttng_index_file_put(stream
->index_file
);
2577 stream
->index_file
= NULL
;
2579 major
= stream
->trace
->session
->major
;
2580 minor
= stream
->trace
->session
->minor
;
2581 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2582 stream
->channel_name
,
2583 -1, -1, stream
->tracefile_size
,
2584 tracefile_array_get_file_index_head(stream
->tfa
),
2585 lttng_to_index_major(major
, minor
),
2586 lttng_to_index_minor(major
, minor
));
2587 if (!stream
->index_file
) {
2589 /* Put self-ref for this index due to error. */
2590 relay_index_put(index
);
2596 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2598 /* Put self-ref for this index due to error. */
2599 relay_index_put(index
);
2604 ret
= relay_index_try_flush(index
);
2606 tracefile_array_commit_seq(stream
->tfa
);
2607 stream
->index_received_seqcount
++;
2608 } else if (ret
> 0) {
2612 /* Put self-ref for this index due to error. */
2613 relay_index_put(index
);
2621 static enum relay_connection_status
relay_process_data_receive_header(
2622 struct relay_connection
*conn
)
2625 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2626 struct data_connection_state_receive_header
*state
=
2627 &conn
->protocol
.data
.state
.receive_header
;
2628 struct lttcomm_relayd_data_hdr header
;
2629 struct relay_stream
*stream
;
2631 assert(state
->left_to_receive
!= 0);
2633 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2634 state
->header_reception_buffer
+ state
->received
,
2635 state
->left_to_receive
, MSG_DONTWAIT
);
2637 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2638 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2639 status
= RELAY_CONNECTION_STATUS_ERROR
;
2642 } else if (ret
== 0) {
2643 /* Orderly shutdown. Not necessary to print an error. */
2644 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2645 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2650 assert(ret
<= state
->left_to_receive
);
2652 state
->left_to_receive
-= ret
;
2653 state
->received
+= ret
;
2655 if (state
->left_to_receive
> 0) {
2657 * Can't transition to the protocol's next state, wait to
2658 * receive the rest of the header.
2660 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2661 state
->received
, state
->left_to_receive
,
2667 /* Transition to next state: receiving the payload. */
2668 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2670 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2671 header
.circuit_id
= be64toh(header
.circuit_id
);
2672 header
.stream_id
= be64toh(header
.stream_id
);
2673 header
.data_size
= be32toh(header
.data_size
);
2674 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2675 header
.padding_size
= be32toh(header
.padding_size
);
2676 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2678 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2680 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2681 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2683 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2684 conn
->sock
->fd
, header
.circuit_id
,
2685 header
.stream_id
, header
.data_size
,
2686 header
.net_seq_num
, header
.padding_size
);
2688 stream
= stream_get_by_id(header
.stream_id
);
2690 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2692 /* Protocol error. */
2693 status
= RELAY_CONNECTION_STATUS_ERROR
;
2697 pthread_mutex_lock(&stream
->lock
);
2699 /* Check if a rotation is needed. */
2700 if (stream
->tracefile_size
> 0 &&
2701 (stream
->tracefile_size_current
+ header
.data_size
) >
2702 stream
->tracefile_size
) {
2703 uint64_t old_id
, new_id
;
2705 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2706 tracefile_array_file_rotate(stream
->tfa
);
2708 /* new_id is updated by utils_rotate_stream_file. */
2711 ret
= utils_rotate_stream_file(stream
->path_name
,
2712 stream
->channel_name
, stream
->tracefile_size
,
2713 stream
->tracefile_count
, -1,
2714 -1, stream
->stream_fd
->fd
,
2715 &new_id
, &stream
->stream_fd
->fd
);
2717 ERR("Failed to rotate stream output file");
2718 status
= RELAY_CONNECTION_STATUS_ERROR
;
2719 goto end_stream_unlock
;
2723 * Reset current size because we just performed a stream
2726 stream
->tracefile_size_current
= 0;
2727 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2732 pthread_mutex_unlock(&stream
->lock
);
2738 static enum relay_connection_status
relay_process_data_receive_payload(
2739 struct relay_connection
*conn
)
2742 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2743 struct relay_stream
*stream
;
2744 struct data_connection_state_receive_payload
*state
=
2745 &conn
->protocol
.data
.state
.receive_payload
;
2746 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2747 char data_buffer
[chunk_size
];
2748 bool partial_recv
= false;
2749 bool new_stream
= false, close_requested
= false;
2750 uint64_t left_to_receive
= state
->left_to_receive
;
2751 struct relay_session
*session
;
2753 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2754 state
->header
.stream_id
, state
->header
.net_seq_num
,
2755 state
->received
, left_to_receive
);
2757 stream
= stream_get_by_id(state
->header
.stream_id
);
2759 /* Protocol error. */
2760 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2761 state
->header
.stream_id
);
2762 status
= RELAY_CONNECTION_STATUS_ERROR
;
2766 pthread_mutex_lock(&stream
->lock
);
2767 session
= stream
->trace
->session
;
2768 if (!conn
->session
) {
2769 ret
= connection_set_session(conn
, session
);
2771 status
= RELAY_CONNECTION_STATUS_ERROR
;
2772 goto end_stream_unlock
;
2777 * The size of the "chunk" received on any iteration is bounded by:
2778 * - the data left to receive,
2779 * - the data immediately available on the socket,
2780 * - the on-stack data buffer
2782 while (left_to_receive
> 0 && !partial_recv
) {
2784 size_t recv_size
= min(left_to_receive
, chunk_size
);
2786 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2787 recv_size
, MSG_DONTWAIT
);
2789 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2790 PERROR("Socket %d error", conn
->sock
->fd
);
2791 status
= RELAY_CONNECTION_STATUS_ERROR
;
2793 goto end_stream_unlock
;
2794 } else if (ret
== 0) {
2795 /* No more data ready to be consumed on socket. */
2796 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2797 state
->header
.stream_id
);
2798 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2800 } else if (ret
< (int) recv_size
) {
2802 * All the data available on the socket has been
2805 partial_recv
= true;
2810 /* Write data to stream output fd. */
2811 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2813 if (write_ret
< (ssize_t
) recv_size
) {
2814 ERR("Relay error writing data to file");
2815 status
= RELAY_CONNECTION_STATUS_ERROR
;
2816 goto end_stream_unlock
;
2819 left_to_receive
-= recv_size
;
2820 state
->received
+= recv_size
;
2821 state
->left_to_receive
= left_to_receive
;
2823 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2824 write_ret
, stream
->stream_handle
);
2827 if (state
->left_to_receive
> 0) {
2829 * Did not receive all the data expected, wait for more data to
2830 * become available on the socket.
2832 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2833 state
->header
.stream_id
, state
->received
,
2834 state
->left_to_receive
);
2835 goto end_stream_unlock
;
2838 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2839 state
->header
.padding_size
);
2840 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2841 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2842 stream
->stream_handle
,
2843 state
->header
.net_seq_num
, ret
);
2844 status
= RELAY_CONNECTION_STATUS_ERROR
;
2845 goto end_stream_unlock
;
2849 if (session
->minor
>= 4 && !session
->snapshot
) {
2850 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2851 state
->rotate_index
);
2853 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2854 stream
->stream_handle
,
2855 state
->header
.net_seq_num
, ret
);
2856 status
= RELAY_CONNECTION_STATUS_ERROR
;
2857 goto end_stream_unlock
;
2861 stream
->tracefile_size_current
+= state
->header
.data_size
+
2862 state
->header
.padding_size
;
2864 if (stream
->prev_seq
== -1ULL) {
2868 stream
->prev_seq
= state
->header
.net_seq_num
;
2871 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2872 * contents of *state which are aliased (union) to the same location as
2873 * the new state. Don't use it beyond this point.
2875 connection_reset_protocol_state(conn
);
2879 close_requested
= stream
->close_requested
;
2880 pthread_mutex_unlock(&stream
->lock
);
2881 if (close_requested
&& left_to_receive
== 0) {
2882 try_stream_close(stream
);
2886 pthread_mutex_lock(&session
->lock
);
2887 uatomic_set(&session
->new_streams
, 1);
2888 pthread_mutex_unlock(&session
->lock
);
2897 * relay_process_data: Process the data received on the data socket
2899 static enum relay_connection_status
relay_process_data(
2900 struct relay_connection
*conn
)
2902 enum relay_connection_status status
;
2904 switch (conn
->protocol
.data
.state_id
) {
2905 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2906 status
= relay_process_data_receive_header(conn
);
2908 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2909 status
= relay_process_data_receive_payload(conn
);
2912 ERR("Unexpected data connection communication state.");
2919 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2923 (void) lttng_poll_del(events
, pollfd
);
2925 ret
= close(pollfd
);
2927 ERR("Closing pollfd %d", pollfd
);
2931 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2932 int pollfd
, struct relay_connection
*conn
)
2934 const char *type_str
;
2936 switch (conn
->type
) {
2941 type_str
= "Control";
2943 case RELAY_VIEWER_COMMAND
:
2944 type_str
= "Viewer Command";
2946 case RELAY_VIEWER_NOTIFICATION
:
2947 type_str
= "Viewer Notification";
2950 type_str
= "Unknown";
2952 cleanup_connection_pollfd(events
, pollfd
);
2953 connection_put(conn
);
2954 DBG("%s connection closed with %d", type_str
, pollfd
);
2958 * This thread does the actual work
2960 static void *relay_thread_worker(void *data
)
2962 int ret
, err
= -1, last_seen_data_fd
= -1;
2964 struct lttng_poll_event events
;
2965 struct lttng_ht
*relay_connections_ht
;
2966 struct lttng_ht_iter iter
;
2967 struct relay_connection
*destroy_conn
= NULL
;
2969 DBG("[thread] Relay worker started");
2971 rcu_register_thread();
2973 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2975 if (testpoint(relayd_thread_worker
)) {
2976 goto error_testpoint
;
2979 health_code_update();
2981 /* table of connections indexed on socket */
2982 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2983 if (!relay_connections_ht
) {
2984 goto relay_connections_ht_error
;
2987 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
2989 goto error_poll_create
;
2992 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2999 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3001 health_code_update();
3003 /* Infinite blocking call, waiting for transmission */
3004 DBG3("Relayd worker thread polling...");
3005 health_poll_entry();
3006 ret
= lttng_poll_wait(&events
, -1);
3010 * Restart interrupted system call.
3012 if (errno
== EINTR
) {
3021 * Process control. The control connection is
3022 * prioritized so we don't starve it with high
3023 * throughput tracing data on the data connection.
3025 for (i
= 0; i
< nb_fd
; i
++) {
3026 /* Fetch once the poll data */
3027 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3028 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3030 health_code_update();
3034 * No activity for this FD (poll
3040 /* Thread quit pipe has been closed. Killing thread. */
3041 ret
= check_thread_quit_pipe(pollfd
, revents
);
3047 /* Inspect the relay conn pipe for new connection */
3048 if (pollfd
== relay_conn_pipe
[0]) {
3049 if (revents
& LPOLLIN
) {
3050 struct relay_connection
*conn
;
3052 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3056 lttng_poll_add(&events
, conn
->sock
->fd
,
3057 LPOLLIN
| LPOLLRDHUP
);
3058 connection_ht_add(relay_connections_ht
, conn
);
3059 DBG("Connection socket %d added", conn
->sock
->fd
);
3060 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3061 ERR("Relay connection pipe error");
3064 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3068 struct relay_connection
*ctrl_conn
;
3070 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3071 /* If not found, there is a synchronization issue. */
3074 if (ctrl_conn
->type
== RELAY_DATA
) {
3075 if (revents
& LPOLLIN
) {
3077 * Flag the last seen data fd not deleted. It will be
3078 * used as the last seen fd if any fd gets deleted in
3081 last_notdel_data_fd
= pollfd
;
3083 goto put_ctrl_connection
;
3085 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3087 if (revents
& LPOLLIN
) {
3088 enum relay_connection_status status
;
3090 status
= relay_process_control(ctrl_conn
);
3091 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3093 * On socket error flag the session as aborted to force
3094 * the cleanup of its stream otherwise it can leak
3095 * during the lifetime of the relayd.
3097 * This prevents situations in which streams can be
3098 * left opened because an index was received, the
3099 * control connection is closed, and the data
3100 * connection is closed (uncleanly) before the packet's
3103 * Since the control connection encountered an error,
3104 * it is okay to be conservative and close the
3105 * session right now as we can't rely on the protocol
3106 * being respected anymore.
3108 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3109 session_abort(ctrl_conn
->session
);
3112 /* Clear the connection on error or close. */
3113 relay_thread_close_connection(&events
,
3118 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3119 relay_thread_close_connection(&events
,
3121 if (last_seen_data_fd
== pollfd
) {
3122 last_seen_data_fd
= last_notdel_data_fd
;
3125 ERR("Unexpected poll events %u for control sock %d",
3127 connection_put(ctrl_conn
);
3130 put_ctrl_connection
:
3131 connection_put(ctrl_conn
);
3136 * The last loop handled a control request, go back to poll to make
3137 * sure we prioritise the control socket.
3143 if (last_seen_data_fd
>= 0) {
3144 for (i
= 0; i
< nb_fd
; i
++) {
3145 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3147 health_code_update();
3149 if (last_seen_data_fd
== pollfd
) {
3156 /* Process data connection. */
3157 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3158 /* Fetch the poll data. */
3159 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3160 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3161 struct relay_connection
*data_conn
;
3163 health_code_update();
3166 /* No activity for this FD (poll implementation). */
3170 /* Skip the command pipe. It's handled in the first loop. */
3171 if (pollfd
== relay_conn_pipe
[0]) {
3175 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3177 /* Skip it. Might be removed before. */
3180 if (data_conn
->type
== RELAY_CONTROL
) {
3181 goto put_data_connection
;
3183 assert(data_conn
->type
== RELAY_DATA
);
3185 if (revents
& LPOLLIN
) {
3186 enum relay_connection_status status
;
3188 status
= relay_process_data(data_conn
);
3189 /* Connection closed or error. */
3190 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3192 * On socket error flag the session as aborted to force
3193 * the cleanup of its stream otherwise it can leak
3194 * during the lifetime of the relayd.
3196 * This prevents situations in which streams can be
3197 * left opened because an index was received, the
3198 * control connection is closed, and the data
3199 * connection is closed (uncleanly) before the packet's
3202 * Since the data connection encountered an error,
3203 * it is okay to be conservative and close the
3204 * session right now as we can't rely on the protocol
3205 * being respected anymore.
3207 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3208 session_abort(data_conn
->session
);
3210 relay_thread_close_connection(&events
, pollfd
,
3213 * Every goto restart call sets the last seen fd where
3214 * here we don't really care since we gracefully
3215 * continue the loop after the connection is deleted.
3218 /* Keep last seen port. */
3219 last_seen_data_fd
= pollfd
;
3220 connection_put(data_conn
);
3223 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3224 relay_thread_close_connection(&events
, pollfd
,
3227 ERR("Unknown poll events %u for data sock %d",
3230 put_data_connection
:
3231 connection_put(data_conn
);
3233 last_seen_data_fd
= -1;
3236 /* Normal exit, no error */
3241 /* Cleanup reamaining connection object. */
3243 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3246 health_code_update();
3248 session_abort(destroy_conn
->session
);
3251 * No need to grab another ref, because we own
3254 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3259 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3261 lttng_ht_destroy(relay_connections_ht
);
3262 relay_connections_ht_error
:
3263 /* Close relay conn pipes */
3264 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3267 DBG("Thread exited with error");
3269 DBG("Worker thread cleanup complete");
3273 ERR("Health error occurred in %s", __func__
);
3275 health_unregister(health_relayd
);
3276 rcu_unregister_thread();
3277 lttng_relay_stop_threads();
3282 * Create the relay command pipe to wake thread_manage_apps.
3283 * Closed in cleanup().
3285 static int create_relay_conn_pipe(void)
3287 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3288 "Relayd connection pipe", relay_conn_pipe
);
3292 int stdio_open(void *data
, int *fds
)
3294 fds
[0] = fileno(stdout
);
3295 fds
[1] = fileno(stderr
);
3300 int noop_close(void *data
, int *fds
)
3306 int track_stdio(void)
3309 const char *names
[] = { "stdout", "stderr" };
3311 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
3312 names
, 2, stdio_open
, NULL
);
3316 void untrack_stdio(void)
3318 int fds
[] = { fileno(stdout
), fileno(stderr
) };
3321 * noop_close is used since we don't really want to close
3322 * the stdio output fds; we merely want to stop tracking them.
3324 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
3325 fds
, 2, noop_close
, NULL
);
3331 int main(int argc
, char **argv
)
3333 int ret
= 0, retval
= 0;
3336 /* Parse environment variables */
3337 parse_env_options();
3341 * Command line arguments overwrite environment.
3344 if (set_options(argc
, argv
)) {
3349 if (set_signal_handler()) {
3354 relayd_config_log();
3356 if (opt_print_version
) {
3362 ret
= fclose(stdin
);
3364 PERROR("Failed to close stdin");
3367 /* Try to create directory if -o, --output is specified. */
3368 if (opt_output_path
) {
3369 if (*opt_output_path
!= '/') {
3370 ERR("Please specify an absolute path for -o, --output PATH");
3375 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3378 ERR("Unable to create %s", opt_output_path
);
3385 if (opt_daemon
|| opt_background
) {
3386 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3394 if (opt_working_directory
) {
3395 ret
= utils_change_working_dir(opt_working_directory
);
3397 ERR("Changing working directory");
3402 * The RCU thread registration (and use, through the fd-tracker's
3403 * creation) is done after the daemonization to allow us to not
3404 * deal with liburcu's fork() management as the call RCU needs to
3407 rcu_register_thread();
3409 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
3410 if (!the_fd_tracker
) {
3415 ret
= track_stdio();
3421 /* Initialize thread health monitoring */
3422 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3423 if (!health_relayd
) {
3424 PERROR("health_app_create error");
3426 goto exit_health_app_create
;
3429 /* Create thread quit pipe */
3430 if (init_thread_quit_pipe()) {
3432 goto exit_init_data
;
3435 /* Setup the thread apps communication pipe. */
3436 if (create_relay_conn_pipe()) {
3438 goto exit_init_data
;
3441 /* Init relay command queue. */
3442 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3444 /* Initialize communication library */
3446 lttcomm_inet_init();
3448 /* tables of sessions indexed by session ID */
3449 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3452 goto exit_init_data
;
3455 /* tables of streams indexed by stream ID */
3456 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3457 if (!relay_streams_ht
) {
3459 goto exit_init_data
;
3462 /* tables of streams indexed by stream ID */
3463 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3464 if (!viewer_streams_ht
) {
3466 goto exit_init_data
;
3469 ret
= init_health_quit_pipe();
3472 goto exit_health_quit_pipe
;
3475 /* Create thread to manage the client socket */
3476 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3477 thread_manage_health
, (void *) NULL
);
3480 PERROR("pthread_create health");
3482 goto exit_health_thread
;
3485 /* Setup the dispatcher thread */
3486 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3487 relay_thread_dispatcher
, (void *) NULL
);
3490 PERROR("pthread_create dispatcher");
3492 goto exit_dispatcher_thread
;
3495 /* Setup the worker thread */
3496 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3497 relay_thread_worker
, NULL
);
3500 PERROR("pthread_create worker");
3502 goto exit_worker_thread
;
3505 /* Setup the listener thread */
3506 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3507 relay_thread_listener
, (void *) NULL
);
3510 PERROR("pthread_create listener");
3512 goto exit_listener_thread
;
3515 ret
= relayd_live_create(live_uri
);
3517 ERR("Starting live viewer threads");
3523 * This is where we start awaiting program completion (e.g. through
3524 * signal that asks threads to teardown).
3527 ret
= relayd_live_join();
3533 ret
= pthread_join(listener_thread
, &status
);
3536 PERROR("pthread_join listener_thread");
3540 exit_listener_thread
:
3541 ret
= pthread_join(worker_thread
, &status
);
3544 PERROR("pthread_join worker_thread");
3549 ret
= pthread_join(dispatcher_thread
, &status
);
3552 PERROR("pthread_join dispatcher_thread");
3555 exit_dispatcher_thread
:
3557 ret
= pthread_join(health_thread
, &status
);
3560 PERROR("pthread_join health_thread");
3565 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
3566 exit_health_quit_pipe
:
3569 health_app_destroy(health_relayd
);
3570 exit_health_app_create
:
3573 * Wait for all pending call_rcu work to complete before tearing
3574 * down data structures. call_rcu worker may be trying to
3575 * perform lookups in those structures.
3580 /* Ensure all prior call_rcu are done. */
3585 * fd_tracker_destroy() will log the contents of the fd-tracker
3586 * if a leak is detected.
3588 fd_tracker_destroy(the_fd_tracker
);
3589 rcu_unregister_thread();