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
, "Data listener");
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
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1098 &data_sock
->fd
, 1, close_sock
,
1104 lttcomm_destroy_sock(data_sock
);
1106 if (control_sock
->fd
>= 0) {
1107 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1108 &control_sock
->fd
, 1, close_sock
,
1114 lttcomm_destroy_sock(control_sock
);
1118 ERR("Health error occurred in %s", __func__
);
1120 health_unregister(health_relayd
);
1121 DBG("Relay listener thread cleanup complete");
1122 lttng_relay_stop_threads();
1127 * This thread manages the dispatching of the requests to worker threads
1129 static void *relay_thread_dispatcher(void *data
)
1133 struct cds_wfcq_node
*node
;
1134 struct relay_connection
*new_conn
= NULL
;
1136 DBG("[thread] Relay dispatcher started");
1138 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1140 if (testpoint(relayd_thread_dispatcher
)) {
1141 goto error_testpoint
;
1144 health_code_update();
1147 health_code_update();
1149 /* Atomically prepare the queue futex */
1150 futex_nto1_prepare(&relay_conn_queue
.futex
);
1152 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1157 health_code_update();
1159 /* Dequeue commands */
1160 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1161 &relay_conn_queue
.tail
);
1163 DBG("Woken up but nothing in the relay command queue");
1164 /* Continue thread execution */
1167 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1169 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1172 * Inform worker thread of the new request. This
1173 * call is blocking so we can be assured that
1174 * the data will be read at some point in time
1175 * or wait to the end of the world :)
1177 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1179 PERROR("write connection pipe");
1180 connection_put(new_conn
);
1183 } while (node
!= NULL
);
1185 /* Futex wait on queue. Blocking call on futex() */
1186 health_poll_entry();
1187 futex_nto1_wait(&relay_conn_queue
.futex
);
1191 /* Normal exit, no error */
1198 ERR("Health error occurred in %s", __func__
);
1200 health_unregister(health_relayd
);
1201 DBG("Dispatch thread dying");
1202 lttng_relay_stop_threads();
1207 * Set index data from the control port to a given index object.
1209 static int set_index_control_data(struct relay_index
*index
,
1210 struct lttcomm_relayd_index
*data
,
1211 struct relay_connection
*conn
)
1213 struct ctf_packet_index index_data
;
1216 * The index on disk is encoded in big endian.
1218 index_data
.packet_size
= htobe64(data
->packet_size
);
1219 index_data
.content_size
= htobe64(data
->content_size
);
1220 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1221 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1222 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1223 index_data
.stream_id
= htobe64(data
->stream_id
);
1225 if (conn
->minor
>= 8) {
1226 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1227 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1230 return relay_index_set_data(index
, &index_data
);
1234 * Handle the RELAYD_CREATE_SESSION command.
1236 * On success, send back the session id or else return a negative value.
1238 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1239 struct relay_connection
*conn
,
1240 const struct lttng_buffer_view
*payload
)
1244 struct relay_session
*session
;
1245 struct lttcomm_relayd_status_session reply
;
1246 char session_name
[LTTNG_NAME_MAX
];
1247 char hostname
[LTTNG_HOST_NAME_MAX
];
1248 uint32_t live_timer
= 0;
1249 bool snapshot
= false;
1251 memset(session_name
, 0, LTTNG_NAME_MAX
);
1252 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1254 memset(&reply
, 0, sizeof(reply
));
1256 switch (conn
->minor
) {
1261 case 4: /* LTTng sessiond 2.4 */
1263 ret
= cmd_create_session_2_4(payload
, session_name
,
1264 hostname
, &live_timer
, &snapshot
);
1270 session
= session_create(session_name
, hostname
, live_timer
,
1271 snapshot
, conn
->major
, conn
->minor
);
1276 assert(!conn
->session
);
1277 conn
->session
= session
;
1278 DBG("Created session %" PRIu64
, session
->id
);
1280 reply
.session_id
= htobe64(session
->id
);
1284 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1286 reply
.ret_code
= htobe32(LTTNG_OK
);
1289 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1290 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1291 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1300 * When we have received all the streams and the metadata for a channel,
1301 * we make them visible to the viewer threads.
1303 static void publish_connection_local_streams(struct relay_connection
*conn
)
1305 struct relay_stream
*stream
;
1306 struct relay_session
*session
= conn
->session
;
1309 * We publish all streams belonging to a session atomically wrt
1312 pthread_mutex_lock(&session
->lock
);
1314 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1316 stream_publish(stream
);
1321 * Inform the viewer that there are new streams in the session.
1323 if (session
->viewer_attached
) {
1324 uatomic_set(&session
->new_streams
, 1);
1326 pthread_mutex_unlock(&session
->lock
);
1330 * relay_add_stream: allocate a new stream for a session
1332 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1333 struct relay_connection
*conn
,
1334 const struct lttng_buffer_view
*payload
)
1338 struct relay_session
*session
= conn
->session
;
1339 struct relay_stream
*stream
= NULL
;
1340 struct lttcomm_relayd_status_stream reply
;
1341 struct ctf_trace
*trace
= NULL
;
1342 uint64_t stream_handle
= -1ULL;
1343 char *path_name
= NULL
, *channel_name
= NULL
;
1344 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1346 if (!session
|| !conn
->version_check_done
) {
1347 ERR("Trying to add a stream before version check");
1349 goto end_no_session
;
1352 switch (session
->minor
) {
1353 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1354 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1355 &channel_name
, session
);
1357 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1359 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1360 &channel_name
, &tracefile_size
, &tracefile_count
,
1368 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1372 /* This stream here has one reference on the trace. */
1374 pthread_mutex_lock(&last_relay_stream_id_lock
);
1375 stream_handle
= ++last_relay_stream_id
;
1376 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1378 /* We pass ownership of path_name and channel_name. */
1379 stream
= stream_create(trace
, stream_handle
, path_name
,
1380 channel_name
, tracefile_size
, tracefile_count
);
1382 channel_name
= NULL
;
1385 * Streams are the owners of their trace. Reference to trace is
1386 * kept within stream_create().
1388 ctf_trace_put(trace
);
1391 memset(&reply
, 0, sizeof(reply
));
1392 reply
.handle
= htobe64(stream_handle
);
1394 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1396 reply
.ret_code
= htobe32(LTTNG_OK
);
1399 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1400 sizeof(struct lttcomm_relayd_status_stream
), 0);
1401 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1402 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1414 * relay_close_stream: close a specific stream
1416 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1417 struct relay_connection
*conn
,
1418 const struct lttng_buffer_view
*payload
)
1422 struct relay_session
*session
= conn
->session
;
1423 struct lttcomm_relayd_close_stream stream_info
;
1424 struct lttcomm_relayd_generic_reply reply
;
1425 struct relay_stream
*stream
;
1427 DBG("Close stream received");
1429 if (!session
|| !conn
->version_check_done
) {
1430 ERR("Trying to close a stream before version check");
1432 goto end_no_session
;
1435 if (payload
->size
< sizeof(stream_info
)) {
1436 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1437 sizeof(stream_info
), payload
->size
);
1439 goto end_no_session
;
1441 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1442 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1443 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1445 stream
= stream_get_by_id(stream_info
.stream_id
);
1452 * Set last_net_seq_num before the close flag. Required by data
1455 pthread_mutex_lock(&stream
->lock
);
1456 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1457 pthread_mutex_unlock(&stream
->lock
);
1460 * This is one of the conditions which may trigger a stream close
1461 * with the others being:
1462 * 1) A close command is received for a stream
1463 * 2) The control connection owning the stream is closed
1464 * 3) We have received all of the stream's data _after_ a close
1467 try_stream_close(stream
);
1468 if (stream
->is_metadata
) {
1469 struct relay_viewer_stream
*vstream
;
1471 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1473 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1475 * Since all the metadata has been sent to the
1476 * viewer and that we have a request to close
1477 * its stream, we can safely teardown the
1478 * corresponding metadata viewer stream.
1480 viewer_stream_put(vstream
);
1482 /* Put local reference. */
1483 viewer_stream_put(vstream
);
1490 memset(&reply
, 0, sizeof(reply
));
1492 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1494 reply
.ret_code
= htobe32(LTTNG_OK
);
1496 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1497 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1498 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1499 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1509 * relay_reset_metadata: reset a metadata stream
1512 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1513 struct relay_connection
*conn
,
1514 const struct lttng_buffer_view
*payload
)
1518 struct relay_session
*session
= conn
->session
;
1519 struct lttcomm_relayd_reset_metadata stream_info
;
1520 struct lttcomm_relayd_generic_reply reply
;
1521 struct relay_stream
*stream
;
1523 DBG("Reset metadata received");
1525 if (!session
|| !conn
->version_check_done
) {
1526 ERR("Trying to reset a metadata stream before version check");
1528 goto end_no_session
;
1531 if (payload
->size
< sizeof(stream_info
)) {
1532 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1533 sizeof(stream_info
), payload
->size
);
1535 goto end_no_session
;
1537 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1538 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1539 stream_info
.version
= be64toh(stream_info
.version
);
1541 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1543 /* Unsupported for live sessions for now. */
1544 if (session
->live_timer
!= 0) {
1549 stream
= stream_get_by_id(stream_info
.stream_id
);
1554 pthread_mutex_lock(&stream
->lock
);
1555 if (!stream
->is_metadata
) {
1560 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1561 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1562 &stream
->stream_fd
->fd
);
1564 ERR("Failed to rotate metadata file %s of channel %s",
1565 stream
->path_name
, stream
->channel_name
);
1570 pthread_mutex_unlock(&stream
->lock
);
1574 memset(&reply
, 0, sizeof(reply
));
1576 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1578 reply
.ret_code
= htobe32(LTTNG_OK
);
1580 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1581 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1582 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1583 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1593 * relay_unknown_command: send -1 if received unknown command
1595 static void relay_unknown_command(struct relay_connection
*conn
)
1597 struct lttcomm_relayd_generic_reply reply
;
1600 memset(&reply
, 0, sizeof(reply
));
1601 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1602 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1603 if (send_ret
< sizeof(reply
)) {
1604 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1609 * relay_start: send an acknowledgment to the client to tell if we are
1610 * ready to receive data. We are ready if a session is established.
1612 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1613 struct relay_connection
*conn
,
1614 const struct lttng_buffer_view
*payload
)
1618 struct lttcomm_relayd_generic_reply reply
;
1619 struct relay_session
*session
= conn
->session
;
1622 DBG("Trying to start the streaming without a session established");
1623 ret
= htobe32(LTTNG_ERR_UNK
);
1626 memset(&reply
, 0, sizeof(reply
));
1627 reply
.ret_code
= htobe32(LTTNG_OK
);
1628 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1630 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1631 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1640 * Append padding to the file pointed by the file descriptor fd.
1642 static int write_padding_to_file(int fd
, uint32_t size
)
1651 zeros
= zmalloc(size
);
1652 if (zeros
== NULL
) {
1653 PERROR("zmalloc zeros for padding");
1658 ret
= lttng_write(fd
, zeros
, size
);
1660 PERROR("write padding to file");
1670 * relay_recv_metadata: receive the metadata for the session.
1672 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1673 struct relay_connection
*conn
,
1674 const struct lttng_buffer_view
*payload
)
1678 struct relay_session
*session
= conn
->session
;
1679 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1680 struct relay_stream
*metadata_stream
;
1681 uint64_t metadata_payload_size
;
1684 ERR("Metadata sent before version check");
1689 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1690 ERR("Incorrect data size");
1694 metadata_payload_size
= recv_hdr
->data_size
-
1695 sizeof(struct lttcomm_relayd_metadata_payload
);
1697 memcpy(&metadata_payload_header
, payload
->data
,
1698 sizeof(metadata_payload_header
));
1699 metadata_payload_header
.stream_id
= be64toh(
1700 metadata_payload_header
.stream_id
);
1701 metadata_payload_header
.padding_size
= be32toh(
1702 metadata_payload_header
.padding_size
);
1704 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1705 if (!metadata_stream
) {
1710 pthread_mutex_lock(&metadata_stream
->lock
);
1712 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1713 payload
->data
+ sizeof(metadata_payload_header
),
1714 metadata_payload_size
);
1715 if (size_ret
< metadata_payload_size
) {
1716 ERR("Relay error writing metadata on file");
1721 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1722 metadata_payload_header
.padding_size
);
1723 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1728 metadata_stream
->metadata_received
+=
1729 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1730 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1731 metadata_stream
->metadata_received
);
1734 pthread_mutex_unlock(&metadata_stream
->lock
);
1735 stream_put(metadata_stream
);
1741 * relay_send_version: send relayd version number
1743 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1744 struct relay_connection
*conn
,
1745 const struct lttng_buffer_view
*payload
)
1749 struct lttcomm_relayd_version reply
, msg
;
1750 bool compatible
= true;
1752 conn
->version_check_done
= true;
1754 /* Get version from the other side. */
1755 if (payload
->size
< sizeof(msg
)) {
1756 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1757 sizeof(msg
), payload
->size
);
1762 memcpy(&msg
, payload
->data
, sizeof(msg
));
1763 msg
.major
= be32toh(msg
.major
);
1764 msg
.minor
= be32toh(msg
.minor
);
1766 memset(&reply
, 0, sizeof(reply
));
1767 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1768 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1770 /* Major versions must be the same */
1771 if (reply
.major
!= msg
.major
) {
1772 DBG("Incompatible major versions (%u vs %u), deleting session",
1773 reply
.major
, msg
.major
);
1777 conn
->major
= reply
.major
;
1778 /* We adapt to the lowest compatible version */
1779 if (reply
.minor
<= msg
.minor
) {
1780 conn
->minor
= reply
.minor
;
1782 conn
->minor
= msg
.minor
;
1785 reply
.major
= htobe32(reply
.major
);
1786 reply
.minor
= htobe32(reply
.minor
);
1787 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1789 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1790 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1803 DBG("Version check done using protocol %u.%u", conn
->major
,
1811 * Check for data pending for a given stream id from the session daemon.
1813 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1814 struct relay_connection
*conn
,
1815 const struct lttng_buffer_view
*payload
)
1817 struct relay_session
*session
= conn
->session
;
1818 struct lttcomm_relayd_data_pending msg
;
1819 struct lttcomm_relayd_generic_reply reply
;
1820 struct relay_stream
*stream
;
1824 DBG("Data pending command received");
1826 if (!session
|| !conn
->version_check_done
) {
1827 ERR("Trying to check for data before version check");
1829 goto end_no_session
;
1832 if (payload
->size
< sizeof(msg
)) {
1833 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1834 sizeof(msg
), payload
->size
);
1836 goto end_no_session
;
1838 memcpy(&msg
, payload
->data
, sizeof(msg
));
1839 msg
.stream_id
= be64toh(msg
.stream_id
);
1840 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1842 stream
= stream_get_by_id(msg
.stream_id
);
1843 if (stream
== NULL
) {
1848 pthread_mutex_lock(&stream
->lock
);
1850 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1851 " and last_seq %" PRIu64
, msg
.stream_id
,
1852 stream
->prev_seq
, msg
.last_net_seq_num
);
1854 /* Avoid wrapping issue */
1855 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1856 /* Data has in fact been written and is NOT pending */
1859 /* Data still being streamed thus pending */
1863 stream
->data_pending_check_done
= true;
1864 pthread_mutex_unlock(&stream
->lock
);
1869 memset(&reply
, 0, sizeof(reply
));
1870 reply
.ret_code
= htobe32(ret
);
1871 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1872 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1873 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1883 * Wait for the control socket to reach a quiescent state.
1885 * Note that for now, when receiving this command from the session
1886 * daemon, this means that every subsequent commands or data received on
1887 * the control socket has been handled. So, this is why we simply return
1890 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1891 struct relay_connection
*conn
,
1892 const struct lttng_buffer_view
*payload
)
1896 struct relay_stream
*stream
;
1897 struct lttcomm_relayd_quiescent_control msg
;
1898 struct lttcomm_relayd_generic_reply reply
;
1900 DBG("Checking quiescent state on control socket");
1902 if (!conn
->session
|| !conn
->version_check_done
) {
1903 ERR("Trying to check for data before version check");
1905 goto end_no_session
;
1908 if (payload
->size
< sizeof(msg
)) {
1909 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1910 sizeof(msg
), payload
->size
);
1912 goto end_no_session
;
1914 memcpy(&msg
, payload
->data
, sizeof(msg
));
1915 msg
.stream_id
= be64toh(msg
.stream_id
);
1917 stream
= stream_get_by_id(msg
.stream_id
);
1921 pthread_mutex_lock(&stream
->lock
);
1922 stream
->data_pending_check_done
= true;
1923 pthread_mutex_unlock(&stream
->lock
);
1925 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1928 memset(&reply
, 0, sizeof(reply
));
1929 reply
.ret_code
= htobe32(LTTNG_OK
);
1930 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1931 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1932 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1944 * Initialize a data pending command. This means that a consumer is about
1945 * to ask for data pending for each stream it holds. Simply iterate over
1946 * all streams of a session and set the data_pending_check_done flag.
1948 * This command returns to the client a LTTNG_OK code.
1950 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1951 struct relay_connection
*conn
,
1952 const struct lttng_buffer_view
*payload
)
1956 struct lttng_ht_iter iter
;
1957 struct lttcomm_relayd_begin_data_pending msg
;
1958 struct lttcomm_relayd_generic_reply reply
;
1959 struct relay_stream
*stream
;
1964 DBG("Init streams for data pending");
1966 if (!conn
->session
|| !conn
->version_check_done
) {
1967 ERR("Trying to check for data before version check");
1969 goto end_no_session
;
1972 if (payload
->size
< sizeof(msg
)) {
1973 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1974 sizeof(msg
), payload
->size
);
1976 goto end_no_session
;
1978 memcpy(&msg
, payload
->data
, sizeof(msg
));
1979 msg
.session_id
= be64toh(msg
.session_id
);
1982 * Iterate over all streams to set the begin data pending flag.
1983 * For now, the streams are indexed by stream handle so we have
1984 * to iterate over all streams to find the one associated with
1985 * the right session_id.
1988 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1990 if (!stream_get(stream
)) {
1993 if (stream
->trace
->session
->id
== msg
.session_id
) {
1994 pthread_mutex_lock(&stream
->lock
);
1995 stream
->data_pending_check_done
= false;
1996 pthread_mutex_unlock(&stream
->lock
);
1997 DBG("Set begin data pending flag to stream %" PRIu64
,
1998 stream
->stream_handle
);
2004 memset(&reply
, 0, sizeof(reply
));
2005 /* All good, send back reply. */
2006 reply
.ret_code
= htobe32(LTTNG_OK
);
2008 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2009 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2010 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2022 * End data pending command. This will check, for a given session id, if
2023 * each stream associated with it has its data_pending_check_done flag
2024 * set. If not, this means that the client lost track of the stream but
2025 * the data is still being streamed on our side. In this case, we inform
2026 * the client that data is in flight.
2028 * Return to the client if there is data in flight or not with a ret_code.
2030 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2031 struct relay_connection
*conn
,
2032 const struct lttng_buffer_view
*payload
)
2036 struct lttng_ht_iter iter
;
2037 struct lttcomm_relayd_end_data_pending msg
;
2038 struct lttcomm_relayd_generic_reply reply
;
2039 struct relay_stream
*stream
;
2040 uint32_t is_data_inflight
= 0;
2042 DBG("End data pending command");
2044 if (!conn
->session
|| !conn
->version_check_done
) {
2045 ERR("Trying to check for data before version check");
2047 goto end_no_session
;
2050 if (payload
->size
< sizeof(msg
)) {
2051 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2052 sizeof(msg
), payload
->size
);
2054 goto end_no_session
;
2056 memcpy(&msg
, payload
->data
, sizeof(msg
));
2057 msg
.session_id
= be64toh(msg
.session_id
);
2060 * Iterate over all streams to see if the begin data pending
2064 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2066 if (!stream_get(stream
)) {
2069 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2073 pthread_mutex_lock(&stream
->lock
);
2074 if (!stream
->data_pending_check_done
) {
2075 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2076 is_data_inflight
= 1;
2077 DBG("Data is still in flight for stream %" PRIu64
,
2078 stream
->stream_handle
);
2079 pthread_mutex_unlock(&stream
->lock
);
2084 pthread_mutex_unlock(&stream
->lock
);
2089 memset(&reply
, 0, sizeof(reply
));
2090 /* All good, send back reply. */
2091 reply
.ret_code
= htobe32(is_data_inflight
);
2093 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2094 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2095 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2107 * Receive an index for a specific stream.
2109 * Return 0 on success else a negative value.
2111 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2112 struct relay_connection
*conn
,
2113 const struct lttng_buffer_view
*payload
)
2117 struct relay_session
*session
= conn
->session
;
2118 struct lttcomm_relayd_index index_info
;
2119 struct relay_index
*index
;
2120 struct lttcomm_relayd_generic_reply reply
;
2121 struct relay_stream
*stream
;
2126 DBG("Relay receiving index");
2128 if (!session
|| !conn
->version_check_done
) {
2129 ERR("Trying to close a stream before version check");
2131 goto end_no_session
;
2134 msg_len
= lttcomm_relayd_index_len(
2135 lttng_to_index_major(conn
->major
, conn
->minor
),
2136 lttng_to_index_minor(conn
->major
, conn
->minor
));
2137 if (payload
->size
< msg_len
) {
2138 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2139 msg_len
, payload
->size
);
2141 goto end_no_session
;
2143 memcpy(&index_info
, payload
->data
, msg_len
);
2144 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2145 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2146 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2147 index_info
.content_size
= be64toh(index_info
.content_size
);
2148 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2149 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2150 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2151 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2153 if (conn
->minor
>= 8) {
2154 index_info
.stream_instance_id
=
2155 be64toh(index_info
.stream_instance_id
);
2156 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2159 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2161 ERR("stream_get_by_id not found");
2165 pthread_mutex_lock(&stream
->lock
);
2167 /* Live beacon handling */
2168 if (index_info
.packet_size
== 0) {
2169 DBG("Received live beacon for stream %" PRIu64
,
2170 stream
->stream_handle
);
2173 * Only flag a stream inactive when it has already
2174 * received data and no indexes are in flight.
2176 if (stream
->index_received_seqcount
> 0
2177 && stream
->indexes_in_flight
== 0) {
2178 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2181 goto end_stream_put
;
2183 stream
->beacon_ts_end
= -1ULL;
2186 if (stream
->ctf_stream_id
== -1ULL) {
2187 stream
->ctf_stream_id
= index_info
.stream_id
;
2189 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2192 ERR("relay_index_get_by_id_or_create index NULL");
2193 goto end_stream_put
;
2195 if (set_index_control_data(index
, &index_info
, conn
)) {
2196 ERR("set_index_control_data error");
2197 relay_index_put(index
);
2199 goto end_stream_put
;
2201 ret
= relay_index_try_flush(index
);
2203 tracefile_array_commit_seq(stream
->tfa
);
2204 stream
->index_received_seqcount
++;
2205 } else if (ret
> 0) {
2209 ERR("relay_index_try_flush error %d", ret
);
2210 relay_index_put(index
);
2215 pthread_mutex_unlock(&stream
->lock
);
2220 memset(&reply
, 0, sizeof(reply
));
2222 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2224 reply
.ret_code
= htobe32(LTTNG_OK
);
2226 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2227 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2228 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2237 * Receive the streams_sent message.
2239 * Return 0 on success else a negative value.
2241 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2242 struct relay_connection
*conn
,
2243 const struct lttng_buffer_view
*payload
)
2247 struct lttcomm_relayd_generic_reply reply
;
2251 DBG("Relay receiving streams_sent");
2253 if (!conn
->session
|| !conn
->version_check_done
) {
2254 ERR("Trying to close a stream before version check");
2256 goto end_no_session
;
2260 * Publish every pending stream in the connection recv list which are
2261 * now ready to be used by the viewer.
2263 publish_connection_local_streams(conn
);
2265 memset(&reply
, 0, sizeof(reply
));
2266 reply
.ret_code
= htobe32(LTTNG_OK
);
2267 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2268 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2269 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2281 #define DBG_CMD(cmd_name, conn) \
2282 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2284 static int relay_process_control_command(struct relay_connection
*conn
,
2285 const struct lttcomm_relayd_hdr
*header
,
2286 const struct lttng_buffer_view
*payload
)
2290 switch (header
->cmd
) {
2291 case RELAYD_CREATE_SESSION
:
2292 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2293 ret
= relay_create_session(header
, conn
, payload
);
2295 case RELAYD_ADD_STREAM
:
2296 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2297 ret
= relay_add_stream(header
, conn
, payload
);
2299 case RELAYD_START_DATA
:
2300 DBG_CMD("RELAYD_START_DATA", conn
);
2301 ret
= relay_start(header
, conn
, payload
);
2303 case RELAYD_SEND_METADATA
:
2304 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2305 ret
= relay_recv_metadata(header
, conn
, payload
);
2307 case RELAYD_VERSION
:
2308 DBG_CMD("RELAYD_VERSION", conn
);
2309 ret
= relay_send_version(header
, conn
, payload
);
2311 case RELAYD_CLOSE_STREAM
:
2312 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2313 ret
= relay_close_stream(header
, conn
, payload
);
2315 case RELAYD_DATA_PENDING
:
2316 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2317 ret
= relay_data_pending(header
, conn
, payload
);
2319 case RELAYD_QUIESCENT_CONTROL
:
2320 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2321 ret
= relay_quiescent_control(header
, conn
, payload
);
2323 case RELAYD_BEGIN_DATA_PENDING
:
2324 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2325 ret
= relay_begin_data_pending(header
, conn
, payload
);
2327 case RELAYD_END_DATA_PENDING
:
2328 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2329 ret
= relay_end_data_pending(header
, conn
, payload
);
2331 case RELAYD_SEND_INDEX
:
2332 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2333 ret
= relay_recv_index(header
, conn
, payload
);
2335 case RELAYD_STREAMS_SENT
:
2336 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2337 ret
= relay_streams_sent(header
, conn
, payload
);
2339 case RELAYD_RESET_METADATA
:
2340 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2341 ret
= relay_reset_metadata(header
, conn
, payload
);
2343 case RELAYD_UPDATE_SYNC_INFO
:
2345 ERR("Received unknown command (%u)", header
->cmd
);
2346 relay_unknown_command(conn
);
2355 static enum relay_connection_status
relay_process_control_receive_payload(
2356 struct relay_connection
*conn
)
2359 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2360 struct lttng_dynamic_buffer
*reception_buffer
=
2361 &conn
->protocol
.ctrl
.reception_buffer
;
2362 struct ctrl_connection_state_receive_payload
*state
=
2363 &conn
->protocol
.ctrl
.state
.receive_payload
;
2364 struct lttng_buffer_view payload_view
;
2366 if (state
->left_to_receive
== 0) {
2367 /* Short-circuit for payload-less commands. */
2368 goto reception_complete
;
2370 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2371 reception_buffer
->data
+ state
->received
,
2372 state
->left_to_receive
, MSG_DONTWAIT
);
2374 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2375 PERROR("Unable to receive command payload on sock %d",
2377 status
= RELAY_CONNECTION_STATUS_ERROR
;
2380 } else if (ret
== 0) {
2381 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2382 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2387 assert(ret
<= state
->left_to_receive
);
2389 state
->left_to_receive
-= ret
;
2390 state
->received
+= ret
;
2392 if (state
->left_to_receive
> 0) {
2394 * Can't transition to the protocol's next state, wait to
2395 * receive the rest of the header.
2397 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2398 state
->received
, state
->left_to_receive
,
2404 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2405 conn
->sock
->fd
, state
->received
);
2407 * The payload required to process the command has been received.
2408 * A view to the reception buffer is forwarded to the various
2409 * commands and the state of the control is reset on success.
2411 * Commands are responsible for sending their reply to the peer.
2413 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2415 ret
= relay_process_control_command(conn
,
2416 &state
->header
, &payload_view
);
2418 status
= RELAY_CONNECTION_STATUS_ERROR
;
2422 ret
= connection_reset_protocol_state(conn
);
2424 status
= RELAY_CONNECTION_STATUS_ERROR
;
2430 static enum relay_connection_status
relay_process_control_receive_header(
2431 struct relay_connection
*conn
)
2434 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2435 struct lttcomm_relayd_hdr header
;
2436 struct lttng_dynamic_buffer
*reception_buffer
=
2437 &conn
->protocol
.ctrl
.reception_buffer
;
2438 struct ctrl_connection_state_receive_header
*state
=
2439 &conn
->protocol
.ctrl
.state
.receive_header
;
2441 assert(state
->left_to_receive
!= 0);
2443 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2444 reception_buffer
->data
+ state
->received
,
2445 state
->left_to_receive
, MSG_DONTWAIT
);
2447 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2448 PERROR("Unable to receive control command header on sock %d",
2450 status
= RELAY_CONNECTION_STATUS_ERROR
;
2453 } else if (ret
== 0) {
2454 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2455 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2460 assert(ret
<= state
->left_to_receive
);
2462 state
->left_to_receive
-= ret
;
2463 state
->received
+= ret
;
2465 if (state
->left_to_receive
> 0) {
2467 * Can't transition to the protocol's next state, wait to
2468 * receive the rest of the header.
2470 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2471 state
->received
, state
->left_to_receive
,
2476 /* Transition to next state: receiving the command's payload. */
2477 conn
->protocol
.ctrl
.state_id
=
2478 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2479 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2480 header
.circuit_id
= be64toh(header
.circuit_id
);
2481 header
.data_size
= be64toh(header
.data_size
);
2482 header
.cmd
= be32toh(header
.cmd
);
2483 header
.cmd_version
= be32toh(header
.cmd_version
);
2484 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2485 &header
, sizeof(header
));
2487 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2488 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2491 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2492 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2494 status
= RELAY_CONNECTION_STATUS_ERROR
;
2498 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2500 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2501 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2504 status
= RELAY_CONNECTION_STATUS_ERROR
;
2508 if (header
.data_size
== 0) {
2510 * Manually invoke the next state as the poll loop
2511 * will not wake-up to allow us to proceed further.
2513 status
= relay_process_control_receive_payload(conn
);
2520 * Process the commands received on the control socket
2522 static enum relay_connection_status
relay_process_control(
2523 struct relay_connection
*conn
)
2525 enum relay_connection_status status
;
2527 switch (conn
->protocol
.ctrl
.state_id
) {
2528 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2529 status
= relay_process_control_receive_header(conn
);
2531 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2532 status
= relay_process_control_receive_payload(conn
);
2535 ERR("Unknown control connection protocol state encountered.");
2543 * Handle index for a data stream.
2545 * Called with the stream lock held.
2547 * Return 0 on success else a negative value.
2549 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2553 uint64_t data_offset
;
2554 struct relay_index
*index
;
2556 /* Get data offset because we are about to update the index. */
2557 data_offset
= htobe64(stream
->tracefile_size_current
);
2559 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2560 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2563 * Lookup for an existing index for that stream id/sequence
2564 * number. If it exists, the control thread has already received the
2565 * data for it, thus we need to write it to disk.
2567 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2573 if (rotate_index
|| !stream
->index_file
) {
2574 uint32_t major
, minor
;
2576 /* Put ref on previous index_file. */
2577 if (stream
->index_file
) {
2578 lttng_index_file_put(stream
->index_file
);
2579 stream
->index_file
= NULL
;
2581 major
= stream
->trace
->session
->major
;
2582 minor
= stream
->trace
->session
->minor
;
2583 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2584 stream
->channel_name
,
2585 -1, -1, stream
->tracefile_size
,
2586 tracefile_array_get_file_index_head(stream
->tfa
),
2587 lttng_to_index_major(major
, minor
),
2588 lttng_to_index_minor(major
, minor
));
2589 if (!stream
->index_file
) {
2591 /* Put self-ref for this index due to error. */
2592 relay_index_put(index
);
2598 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2600 /* Put self-ref for this index due to error. */
2601 relay_index_put(index
);
2606 ret
= relay_index_try_flush(index
);
2608 tracefile_array_commit_seq(stream
->tfa
);
2609 stream
->index_received_seqcount
++;
2610 } else if (ret
> 0) {
2614 /* Put self-ref for this index due to error. */
2615 relay_index_put(index
);
2623 static enum relay_connection_status
relay_process_data_receive_header(
2624 struct relay_connection
*conn
)
2627 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2628 struct data_connection_state_receive_header
*state
=
2629 &conn
->protocol
.data
.state
.receive_header
;
2630 struct lttcomm_relayd_data_hdr header
;
2631 struct relay_stream
*stream
;
2633 assert(state
->left_to_receive
!= 0);
2635 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2636 state
->header_reception_buffer
+ state
->received
,
2637 state
->left_to_receive
, MSG_DONTWAIT
);
2639 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2640 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2641 status
= RELAY_CONNECTION_STATUS_ERROR
;
2644 } else if (ret
== 0) {
2645 /* Orderly shutdown. Not necessary to print an error. */
2646 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2647 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2652 assert(ret
<= state
->left_to_receive
);
2654 state
->left_to_receive
-= ret
;
2655 state
->received
+= ret
;
2657 if (state
->left_to_receive
> 0) {
2659 * Can't transition to the protocol's next state, wait to
2660 * receive the rest of the header.
2662 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2663 state
->received
, state
->left_to_receive
,
2669 /* Transition to next state: receiving the payload. */
2670 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2672 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2673 header
.circuit_id
= be64toh(header
.circuit_id
);
2674 header
.stream_id
= be64toh(header
.stream_id
);
2675 header
.data_size
= be32toh(header
.data_size
);
2676 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2677 header
.padding_size
= be32toh(header
.padding_size
);
2678 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2680 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2682 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2683 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2685 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2686 conn
->sock
->fd
, header
.circuit_id
,
2687 header
.stream_id
, header
.data_size
,
2688 header
.net_seq_num
, header
.padding_size
);
2690 stream
= stream_get_by_id(header
.stream_id
);
2692 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2694 /* Protocol error. */
2695 status
= RELAY_CONNECTION_STATUS_ERROR
;
2699 pthread_mutex_lock(&stream
->lock
);
2701 /* Check if a rotation is needed. */
2702 if (stream
->tracefile_size
> 0 &&
2703 (stream
->tracefile_size_current
+ header
.data_size
) >
2704 stream
->tracefile_size
) {
2705 uint64_t old_id
, new_id
;
2707 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2708 tracefile_array_file_rotate(stream
->tfa
);
2710 /* new_id is updated by utils_rotate_stream_file. */
2713 ret
= utils_rotate_stream_file(stream
->path_name
,
2714 stream
->channel_name
, stream
->tracefile_size
,
2715 stream
->tracefile_count
, -1,
2716 -1, stream
->stream_fd
->fd
,
2717 &new_id
, &stream
->stream_fd
->fd
);
2719 ERR("Failed to rotate stream output file");
2720 status
= RELAY_CONNECTION_STATUS_ERROR
;
2721 goto end_stream_unlock
;
2725 * Reset current size because we just performed a stream
2728 stream
->tracefile_size_current
= 0;
2729 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2734 pthread_mutex_unlock(&stream
->lock
);
2740 static enum relay_connection_status
relay_process_data_receive_payload(
2741 struct relay_connection
*conn
)
2744 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2745 struct relay_stream
*stream
;
2746 struct data_connection_state_receive_payload
*state
=
2747 &conn
->protocol
.data
.state
.receive_payload
;
2748 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2749 char data_buffer
[chunk_size
];
2750 bool partial_recv
= false;
2751 bool new_stream
= false, close_requested
= false;
2752 uint64_t left_to_receive
= state
->left_to_receive
;
2753 struct relay_session
*session
;
2755 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2756 state
->header
.stream_id
, state
->header
.net_seq_num
,
2757 state
->received
, left_to_receive
);
2759 stream
= stream_get_by_id(state
->header
.stream_id
);
2761 /* Protocol error. */
2762 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2763 state
->header
.stream_id
);
2764 status
= RELAY_CONNECTION_STATUS_ERROR
;
2768 pthread_mutex_lock(&stream
->lock
);
2769 session
= stream
->trace
->session
;
2770 if (!conn
->session
) {
2771 ret
= connection_set_session(conn
, session
);
2773 status
= RELAY_CONNECTION_STATUS_ERROR
;
2774 goto end_stream_unlock
;
2779 * The size of the "chunk" received on any iteration is bounded by:
2780 * - the data left to receive,
2781 * - the data immediately available on the socket,
2782 * - the on-stack data buffer
2784 while (left_to_receive
> 0 && !partial_recv
) {
2786 size_t recv_size
= min(left_to_receive
, chunk_size
);
2788 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2789 recv_size
, MSG_DONTWAIT
);
2791 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2792 PERROR("Socket %d error", conn
->sock
->fd
);
2793 status
= RELAY_CONNECTION_STATUS_ERROR
;
2795 goto end_stream_unlock
;
2796 } else if (ret
== 0) {
2797 /* No more data ready to be consumed on socket. */
2798 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2799 state
->header
.stream_id
);
2800 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2802 } else if (ret
< (int) recv_size
) {
2804 * All the data available on the socket has been
2807 partial_recv
= true;
2812 /* Write data to stream output fd. */
2813 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2815 if (write_ret
< (ssize_t
) recv_size
) {
2816 ERR("Relay error writing data to file");
2817 status
= RELAY_CONNECTION_STATUS_ERROR
;
2818 goto end_stream_unlock
;
2821 left_to_receive
-= recv_size
;
2822 state
->received
+= recv_size
;
2823 state
->left_to_receive
= left_to_receive
;
2825 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2826 write_ret
, stream
->stream_handle
);
2829 if (state
->left_to_receive
> 0) {
2831 * Did not receive all the data expected, wait for more data to
2832 * become available on the socket.
2834 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2835 state
->header
.stream_id
, state
->received
,
2836 state
->left_to_receive
);
2837 goto end_stream_unlock
;
2840 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2841 state
->header
.padding_size
);
2842 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2843 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2844 stream
->stream_handle
,
2845 state
->header
.net_seq_num
, ret
);
2846 status
= RELAY_CONNECTION_STATUS_ERROR
;
2847 goto end_stream_unlock
;
2851 if (session
->minor
>= 4 && !session
->snapshot
) {
2852 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2853 state
->rotate_index
);
2855 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2856 stream
->stream_handle
,
2857 state
->header
.net_seq_num
, ret
);
2858 status
= RELAY_CONNECTION_STATUS_ERROR
;
2859 goto end_stream_unlock
;
2863 stream
->tracefile_size_current
+= state
->header
.data_size
+
2864 state
->header
.padding_size
;
2866 if (stream
->prev_seq
== -1ULL) {
2870 stream
->prev_seq
= state
->header
.net_seq_num
;
2873 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2874 * contents of *state which are aliased (union) to the same location as
2875 * the new state. Don't use it beyond this point.
2877 connection_reset_protocol_state(conn
);
2881 close_requested
= stream
->close_requested
;
2882 pthread_mutex_unlock(&stream
->lock
);
2883 if (close_requested
&& left_to_receive
== 0) {
2884 try_stream_close(stream
);
2888 pthread_mutex_lock(&session
->lock
);
2889 uatomic_set(&session
->new_streams
, 1);
2890 pthread_mutex_unlock(&session
->lock
);
2899 * relay_process_data: Process the data received on the data socket
2901 static enum relay_connection_status
relay_process_data(
2902 struct relay_connection
*conn
)
2904 enum relay_connection_status status
;
2906 switch (conn
->protocol
.data
.state_id
) {
2907 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2908 status
= relay_process_data_receive_header(conn
);
2910 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2911 status
= relay_process_data_receive_payload(conn
);
2914 ERR("Unexpected data connection communication state.");
2921 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2925 (void) lttng_poll_del(events
, pollfd
);
2927 ret
= close(pollfd
);
2929 ERR("Closing pollfd %d", pollfd
);
2933 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2934 int pollfd
, struct relay_connection
*conn
)
2936 const char *type_str
;
2938 switch (conn
->type
) {
2943 type_str
= "Control";
2945 case RELAY_VIEWER_COMMAND
:
2946 type_str
= "Viewer Command";
2948 case RELAY_VIEWER_NOTIFICATION
:
2949 type_str
= "Viewer Notification";
2952 type_str
= "Unknown";
2954 cleanup_connection_pollfd(events
, pollfd
);
2955 connection_put(conn
);
2956 DBG("%s connection closed with %d", type_str
, pollfd
);
2960 * This thread does the actual work
2962 static void *relay_thread_worker(void *data
)
2964 int ret
, err
= -1, last_seen_data_fd
= -1;
2966 struct lttng_poll_event events
;
2967 struct lttng_ht
*relay_connections_ht
;
2968 struct lttng_ht_iter iter
;
2969 struct relay_connection
*destroy_conn
= NULL
;
2971 DBG("[thread] Relay worker started");
2973 rcu_register_thread();
2975 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2977 if (testpoint(relayd_thread_worker
)) {
2978 goto error_testpoint
;
2981 health_code_update();
2983 /* table of connections indexed on socket */
2984 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2985 if (!relay_connections_ht
) {
2986 goto relay_connections_ht_error
;
2989 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
2991 goto error_poll_create
;
2994 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3001 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3003 health_code_update();
3005 /* Infinite blocking call, waiting for transmission */
3006 DBG3("Relayd worker thread polling...");
3007 health_poll_entry();
3008 ret
= lttng_poll_wait(&events
, -1);
3012 * Restart interrupted system call.
3014 if (errno
== EINTR
) {
3023 * Process control. The control connection is
3024 * prioritized so we don't starve it with high
3025 * throughput tracing data on the data connection.
3027 for (i
= 0; i
< nb_fd
; i
++) {
3028 /* Fetch once the poll data */
3029 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3030 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3032 health_code_update();
3036 * No activity for this FD (poll
3042 /* Thread quit pipe has been closed. Killing thread. */
3043 ret
= check_thread_quit_pipe(pollfd
, revents
);
3049 /* Inspect the relay conn pipe for new connection */
3050 if (pollfd
== relay_conn_pipe
[0]) {
3051 if (revents
& LPOLLIN
) {
3052 struct relay_connection
*conn
;
3054 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3058 lttng_poll_add(&events
, conn
->sock
->fd
,
3059 LPOLLIN
| LPOLLRDHUP
);
3060 connection_ht_add(relay_connections_ht
, conn
);
3061 DBG("Connection socket %d added", conn
->sock
->fd
);
3062 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3063 ERR("Relay connection pipe error");
3066 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3070 struct relay_connection
*ctrl_conn
;
3072 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3073 /* If not found, there is a synchronization issue. */
3076 if (ctrl_conn
->type
== RELAY_DATA
) {
3077 if (revents
& LPOLLIN
) {
3079 * Flag the last seen data fd not deleted. It will be
3080 * used as the last seen fd if any fd gets deleted in
3083 last_notdel_data_fd
= pollfd
;
3085 goto put_ctrl_connection
;
3087 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3089 if (revents
& LPOLLIN
) {
3090 enum relay_connection_status status
;
3092 status
= relay_process_control(ctrl_conn
);
3093 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3095 * On socket error flag the session as aborted to force
3096 * the cleanup of its stream otherwise it can leak
3097 * during the lifetime of the relayd.
3099 * This prevents situations in which streams can be
3100 * left opened because an index was received, the
3101 * control connection is closed, and the data
3102 * connection is closed (uncleanly) before the packet's
3105 * Since the control connection encountered an error,
3106 * it is okay to be conservative and close the
3107 * session right now as we can't rely on the protocol
3108 * being respected anymore.
3110 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3111 session_abort(ctrl_conn
->session
);
3114 /* Clear the connection on error or close. */
3115 relay_thread_close_connection(&events
,
3120 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3121 relay_thread_close_connection(&events
,
3123 if (last_seen_data_fd
== pollfd
) {
3124 last_seen_data_fd
= last_notdel_data_fd
;
3127 ERR("Unexpected poll events %u for control sock %d",
3129 connection_put(ctrl_conn
);
3132 put_ctrl_connection
:
3133 connection_put(ctrl_conn
);
3138 * The last loop handled a control request, go back to poll to make
3139 * sure we prioritise the control socket.
3145 if (last_seen_data_fd
>= 0) {
3146 for (i
= 0; i
< nb_fd
; i
++) {
3147 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3149 health_code_update();
3151 if (last_seen_data_fd
== pollfd
) {
3158 /* Process data connection. */
3159 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3160 /* Fetch the poll data. */
3161 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3162 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3163 struct relay_connection
*data_conn
;
3165 health_code_update();
3168 /* No activity for this FD (poll implementation). */
3172 /* Skip the command pipe. It's handled in the first loop. */
3173 if (pollfd
== relay_conn_pipe
[0]) {
3177 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3179 /* Skip it. Might be removed before. */
3182 if (data_conn
->type
== RELAY_CONTROL
) {
3183 goto put_data_connection
;
3185 assert(data_conn
->type
== RELAY_DATA
);
3187 if (revents
& LPOLLIN
) {
3188 enum relay_connection_status status
;
3190 status
= relay_process_data(data_conn
);
3191 /* Connection closed or error. */
3192 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3194 * On socket error flag the session as aborted to force
3195 * the cleanup of its stream otherwise it can leak
3196 * during the lifetime of the relayd.
3198 * This prevents situations in which streams can be
3199 * left opened because an index was received, the
3200 * control connection is closed, and the data
3201 * connection is closed (uncleanly) before the packet's
3204 * Since the data connection encountered an error,
3205 * it is okay to be conservative and close the
3206 * session right now as we can't rely on the protocol
3207 * being respected anymore.
3209 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3210 session_abort(data_conn
->session
);
3212 relay_thread_close_connection(&events
, pollfd
,
3215 * Every goto restart call sets the last seen fd where
3216 * here we don't really care since we gracefully
3217 * continue the loop after the connection is deleted.
3220 /* Keep last seen port. */
3221 last_seen_data_fd
= pollfd
;
3222 connection_put(data_conn
);
3225 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3226 relay_thread_close_connection(&events
, pollfd
,
3229 ERR("Unknown poll events %u for data sock %d",
3232 put_data_connection
:
3233 connection_put(data_conn
);
3235 last_seen_data_fd
= -1;
3238 /* Normal exit, no error */
3243 /* Cleanup reamaining connection object. */
3245 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3248 health_code_update();
3250 session_abort(destroy_conn
->session
);
3253 * No need to grab another ref, because we own
3256 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3261 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3263 lttng_ht_destroy(relay_connections_ht
);
3264 relay_connections_ht_error
:
3265 /* Close relay conn pipes */
3266 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3269 DBG("Thread exited with error");
3271 DBG("Worker thread cleanup complete");
3275 ERR("Health error occurred in %s", __func__
);
3277 health_unregister(health_relayd
);
3278 rcu_unregister_thread();
3279 lttng_relay_stop_threads();
3284 * Create the relay command pipe to wake thread_manage_apps.
3285 * Closed in cleanup().
3287 static int create_relay_conn_pipe(void)
3289 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3290 "Relayd connection pipe", relay_conn_pipe
);
3294 int stdio_open(void *data
, int *fds
)
3296 fds
[0] = fileno(stdout
);
3297 fds
[1] = fileno(stderr
);
3302 int noop_close(void *data
, int *fds
)
3308 int track_stdio(void)
3311 const char *names
[] = { "stdout", "stderr" };
3313 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
3314 names
, 2, stdio_open
, NULL
);
3318 void untrack_stdio(void)
3320 int fds
[] = { fileno(stdout
), fileno(stderr
) };
3323 * noop_close is used since we don't really want to close
3324 * the stdio output fds; we merely want to stop tracking them.
3326 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
3327 fds
, 2, noop_close
, NULL
);
3333 int main(int argc
, char **argv
)
3335 int ret
= 0, retval
= 0;
3338 /* Parse environment variables */
3339 parse_env_options();
3343 * Command line arguments overwrite environment.
3346 if (set_options(argc
, argv
)) {
3351 if (set_signal_handler()) {
3356 relayd_config_log();
3358 if (opt_print_version
) {
3364 ret
= fclose(stdin
);
3366 PERROR("Failed to close stdin");
3369 /* Try to create directory if -o, --output is specified. */
3370 if (opt_output_path
) {
3371 if (*opt_output_path
!= '/') {
3372 ERR("Please specify an absolute path for -o, --output PATH");
3377 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3380 ERR("Unable to create %s", opt_output_path
);
3387 if (opt_daemon
|| opt_background
) {
3388 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3396 if (opt_working_directory
) {
3397 ret
= utils_change_working_dir(opt_working_directory
);
3399 ERR("Changing working directory");
3404 * The RCU thread registration (and use, through the fd-tracker's
3405 * creation) is done after the daemonization to allow us to not
3406 * deal with liburcu's fork() management as the call RCU needs to
3409 rcu_register_thread();
3411 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
3412 if (!the_fd_tracker
) {
3417 ret
= track_stdio();
3423 /* Initialize thread health monitoring */
3424 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3425 if (!health_relayd
) {
3426 PERROR("health_app_create error");
3428 goto exit_health_app_create
;
3431 /* Create thread quit pipe */
3432 if (init_thread_quit_pipe()) {
3434 goto exit_init_data
;
3437 /* Setup the thread apps communication pipe. */
3438 if (create_relay_conn_pipe()) {
3440 goto exit_init_data
;
3443 /* Init relay command queue. */
3444 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3446 /* Initialize communication library */
3448 lttcomm_inet_init();
3450 /* tables of sessions indexed by session ID */
3451 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3454 goto exit_init_data
;
3457 /* tables of streams indexed by stream ID */
3458 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3459 if (!relay_streams_ht
) {
3461 goto exit_init_data
;
3464 /* tables of streams indexed by stream ID */
3465 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3466 if (!viewer_streams_ht
) {
3468 goto exit_init_data
;
3471 ret
= init_health_quit_pipe();
3474 goto exit_health_quit_pipe
;
3477 /* Create thread to manage the client socket */
3478 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3479 thread_manage_health
, (void *) NULL
);
3482 PERROR("pthread_create health");
3484 goto exit_health_thread
;
3487 /* Setup the dispatcher thread */
3488 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3489 relay_thread_dispatcher
, (void *) NULL
);
3492 PERROR("pthread_create dispatcher");
3494 goto exit_dispatcher_thread
;
3497 /* Setup the worker thread */
3498 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3499 relay_thread_worker
, NULL
);
3502 PERROR("pthread_create worker");
3504 goto exit_worker_thread
;
3507 /* Setup the listener thread */
3508 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3509 relay_thread_listener
, (void *) NULL
);
3512 PERROR("pthread_create listener");
3514 goto exit_listener_thread
;
3517 ret
= relayd_live_create(live_uri
);
3519 ERR("Starting live viewer threads");
3525 * This is where we start awaiting program completion (e.g. through
3526 * signal that asks threads to teardown).
3529 ret
= relayd_live_join();
3535 ret
= pthread_join(listener_thread
, &status
);
3538 PERROR("pthread_join listener_thread");
3542 exit_listener_thread
:
3543 ret
= pthread_join(worker_thread
, &status
);
3546 PERROR("pthread_join worker_thread");
3551 ret
= pthread_join(dispatcher_thread
, &status
);
3554 PERROR("pthread_join dispatcher_thread");
3557 exit_dispatcher_thread
:
3559 ret
= pthread_join(health_thread
, &status
);
3562 PERROR("pthread_join health_thread");
3567 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
3568 exit_health_quit_pipe
:
3571 health_app_destroy(health_relayd
);
3572 exit_health_app_create
:
3575 * Wait for all pending call_rcu work to complete before tearing
3576 * down data structures. call_rcu worker may be trying to
3577 * perform lookups in those structures.
3582 /* Ensure all prior call_rcu are done. */
3587 * fd_tracker_destroy() will log the contents of the fd-tracker
3588 * if a leak is detected.
3590 fd_tracker_destroy(the_fd_tracker
);
3591 rcu_unregister_thread();