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_pool_size
= -1;
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-pool-size", 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-pool-size")) {
226 v
= strtoul(arg
, NULL
, 0);
227 if (errno
!= 0 || !isdigit(arg
[0])) {
228 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
233 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
237 lttng_opt_fd_pool_size
= (unsigned int) v
;
239 fprintf(stderr
, "unknown option %s", optname
);
241 fprintf(stderr
, " with arg %s\n", arg
);
246 if (lttng_is_setuid_setgid()) {
247 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
248 "-C, --control-port");
250 ret
= uri_parse(arg
, &control_uri
);
252 ERR("Invalid control URI specified");
255 if (control_uri
->port
== 0) {
256 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
261 if (lttng_is_setuid_setgid()) {
262 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
265 ret
= uri_parse(arg
, &data_uri
);
267 ERR("Invalid data URI specified");
270 if (data_uri
->port
== 0) {
271 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
276 if (lttng_is_setuid_setgid()) {
277 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
280 ret
= uri_parse(arg
, &live_uri
);
282 ERR("Invalid live URI specified");
285 if (live_uri
->port
== 0) {
286 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
297 if (lttng_is_setuid_setgid()) {
298 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
301 tracing_group_name
= strdup(arg
);
302 if (tracing_group_name
== NULL
) {
307 tracing_group_name_override
= 1;
311 ret
= utils_show_man_page(8, "lttng-relayd");
313 ERR("Cannot view man page lttng-relayd(8)");
318 opt_print_version
= 1;
321 if (lttng_is_setuid_setgid()) {
322 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
325 ret
= asprintf(&opt_output_path
, "%s", arg
);
328 PERROR("asprintf opt_output_path");
334 if (lttng_is_setuid_setgid()) {
335 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
336 "-w, --working-directory");
338 ret
= asprintf(&opt_working_directory
, "%s", arg
);
341 PERROR("asprintf working_directory");
348 /* Verbose level can increase using multiple -v */
350 lttng_opt_verbose
= config_parse_value(arg
);
352 /* Only 3 level of verbosity (-vvv). */
353 if (lttng_opt_verbose
< 3) {
354 lttng_opt_verbose
+= 1;
359 if (opt_group_output_by_host
) {
360 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
363 opt_group_output_by_session
= 1;
366 if (opt_group_output_by_session
) {
367 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
370 opt_group_output_by_host
= 1;
373 /* Unknown option or other error.
374 * Error is printed by getopt, just return */
387 * config_entry_handler_cb used to handle options read from a config file.
388 * See config_entry_handler_cb comment in common/config/session-config.h for the
389 * return value conventions.
391 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
395 if (!entry
|| !entry
->name
|| !entry
->value
) {
400 /* Check if the option is to be ignored */
401 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
402 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
407 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
408 /* Ignore if entry name is not fully matched. */
409 if (strcmp(entry
->name
, long_options
[i
].name
)) {
414 * If the option takes no argument on the command line,
415 * we have to check if the value is "true". We support
416 * non-zero numeric values, true, on and yes.
418 if (!long_options
[i
].has_arg
) {
419 ret
= config_parse_value(entry
->value
);
422 WARN("Invalid configuration value \"%s\" for option %s",
423 entry
->value
, entry
->name
);
425 /* False, skip boolean config option. */
430 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
434 WARN("Unrecognized option \"%s\" in daemon configuration file.",
441 static void parse_env_options(void)
445 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
447 opt_working_directory
= value
;
451 static int set_fd_pool_size(void)
454 struct rlimit rlimit
;
456 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
458 PERROR("Failed to get file descriptor limit");
463 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
464 (uint64_t) rlimit
.rlim_cur
, (uint64_t) rlimit
.rlim_max
);
465 if (lttng_opt_fd_pool_size
== -1) {
466 /* Use default value (soft limit - reserve). */
467 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
468 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
469 (uint64_t) rlimit
.rlim_cur
,
470 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
474 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
475 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
479 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
480 ERR("File descriptor pool size must be set to at least %d",
481 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
486 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
487 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%lu).",
488 lttng_opt_fd_pool_size
, rlimit
.rlim_cur
);
494 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
495 lttng_opt_fd_pool_size
,
496 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
497 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
502 static int set_options(int argc
, char **argv
)
504 int c
, ret
= 0, option_index
= 0, retval
= 0;
505 int orig_optopt
= optopt
, orig_optind
= optind
;
506 char *default_address
, *optstring
;
507 const char *config_path
= NULL
;
509 optstring
= utils_generate_optstring(long_options
,
510 sizeof(long_options
) / sizeof(struct option
));
516 /* Check for the --config option */
518 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
519 &option_index
)) != -1) {
523 } else if (c
!= 'f') {
527 if (lttng_is_setuid_setgid()) {
528 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
531 config_path
= utils_expand_path(optarg
);
533 ERR("Failed to resolve path: %s", optarg
);
538 ret
= config_get_section_entries(config_path
, config_section_name
,
539 config_entry_handler
, NULL
);
542 ERR("Invalid configuration option at line %i", ret
);
548 /* Reset getopt's global state */
549 optopt
= orig_optopt
;
550 optind
= orig_optind
;
552 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
557 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
564 /* assign default values */
565 if (control_uri
== NULL
) {
566 ret
= asprintf(&default_address
,
567 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
568 DEFAULT_NETWORK_CONTROL_PORT
);
570 PERROR("asprintf default data address");
575 ret
= uri_parse(default_address
, &control_uri
);
576 free(default_address
);
578 ERR("Invalid control URI specified");
583 if (data_uri
== NULL
) {
584 ret
= asprintf(&default_address
,
585 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
586 DEFAULT_NETWORK_DATA_PORT
);
588 PERROR("asprintf default data address");
593 ret
= uri_parse(default_address
, &data_uri
);
594 free(default_address
);
596 ERR("Invalid data URI specified");
601 if (live_uri
== NULL
) {
602 ret
= asprintf(&default_address
,
603 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
604 DEFAULT_NETWORK_VIEWER_PORT
);
606 PERROR("asprintf default viewer control address");
611 ret
= uri_parse(default_address
, &live_uri
);
612 free(default_address
);
614 ERR("Invalid viewer control URI specified");
619 ret
= set_fd_pool_size();
625 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
626 /* Group by host by default */
627 opt_group_output_by_host
= 1;
635 static void print_global_objects(void)
637 print_viewer_streams();
638 print_relay_streams();
645 static void relayd_cleanup(void)
647 print_global_objects();
651 if (viewer_streams_ht
)
652 lttng_ht_destroy(viewer_streams_ht
);
653 if (relay_streams_ht
)
654 lttng_ht_destroy(relay_streams_ht
);
656 lttng_ht_destroy(sessions_ht
);
658 /* free the dynamically allocated opt_output_path */
659 free(opt_output_path
);
661 /* Close thread quit pipes */
662 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
664 uri_free(control_uri
);
666 /* Live URI is freed in the live thread. */
668 if (tracing_group_name_override
) {
669 free((void *) tracing_group_name
);
674 * Write to writable pipe used to notify a thread.
676 static int notify_thread_pipe(int wpipe
)
680 ret
= lttng_write(wpipe
, "!", 1);
682 PERROR("write poll pipe");
690 static int notify_health_quit_pipe(int *pipe
)
694 ret
= lttng_write(pipe
[1], "4", 1);
696 PERROR("write relay health quit");
705 * Stop all relayd and relayd-live threads.
707 int lttng_relay_stop_threads(void)
711 /* Stopping all threads */
712 DBG("Terminating all threads");
713 if (notify_thread_pipe(thread_quit_pipe
[1])) {
714 ERR("write error on thread quit pipe");
718 if (notify_health_quit_pipe(health_quit_pipe
)) {
719 ERR("write error on health quit pipe");
722 /* Dispatch thread */
723 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
724 futex_nto1_wake(&relay_conn_queue
.futex
);
726 if (relayd_live_stop()) {
727 ERR("Error stopping live threads");
734 * Signal handler for the daemon
736 * Simply stop all worker threads, leaving main() return gracefully after
737 * joining all threads and calling cleanup().
739 static void sighandler(int sig
)
743 DBG("SIGINT caught");
744 if (lttng_relay_stop_threads()) {
745 ERR("Error stopping threads");
749 DBG("SIGTERM caught");
750 if (lttng_relay_stop_threads()) {
751 ERR("Error stopping threads");
755 CMM_STORE_SHARED(recv_child_signal
, 1);
763 * Setup signal handler for :
764 * SIGINT, SIGTERM, SIGPIPE
766 static int set_signal_handler(void)
772 if ((ret
= sigemptyset(&sigset
)) < 0) {
773 PERROR("sigemptyset");
780 sa
.sa_handler
= sighandler
;
781 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
786 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
791 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
796 sa
.sa_handler
= SIG_IGN
;
797 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
802 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
807 void lttng_relay_notify_ready(void)
809 /* Notify the parent of the fork() process that we are ready. */
810 if (opt_daemon
|| opt_background
) {
811 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
812 kill(child_ppid
, SIGUSR1
);
818 * Init thread quit pipe.
820 * Return -1 on error or 0 if all pipes are created.
822 static int init_thread_quit_pipe(void)
824 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
825 "Quit pipe", thread_quit_pipe
);
829 * Init health quit pipe.
831 * Return -1 on error or 0 if all pipes are created.
833 static int init_health_quit_pipe(void)
835 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
836 "Health quit pipe", health_quit_pipe
);
840 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
842 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
843 int size
, const char *name
)
847 if (events
== NULL
|| size
== 0) {
852 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
853 name
, events
, 1, LTTNG_CLOEXEC
);
856 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
868 * Check if the thread quit pipe was triggered.
870 * Return 1 if it was triggered else 0;
872 static int check_thread_quit_pipe(int fd
, uint32_t events
)
874 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
881 static int create_sock(void *data
, int *out_fd
)
884 struct lttcomm_sock
*sock
= data
;
886 ret
= lttcomm_create_sock(sock
);
896 static int close_sock(void *data
, int *in_fd
)
898 struct lttcomm_sock
*sock
= data
;
900 return sock
->ops
->close(sock
);
903 static int accept_sock(void *data
, int *out_fd
)
906 /* Socks is an array of in_sock, out_sock. */
907 struct lttcomm_sock
**socks
= data
;
908 struct lttcomm_sock
*in_sock
= socks
[0];
910 socks
[1] = in_sock
->ops
->accept(in_sock
);
915 *out_fd
= socks
[1]->fd
;
921 * Create and init socket from uri.
923 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
927 struct lttcomm_sock
*sock
= NULL
;
928 char uri_str
[PATH_MAX
];
929 char *formated_name
= NULL
;
931 sock
= lttcomm_alloc_sock_from_uri(uri
);
933 ERR("Allocating socket");
938 * Don't fail to create the socket if the name can't be built as it is
939 * only used for debugging purposes.
941 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
942 uri_str
[sizeof(uri_str
) - 1] = '\0';
944 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
947 formated_name
= NULL
;
951 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
952 (const char **) (formated_name
? &formated_name
: NULL
),
953 1, create_sock
, sock
);
955 DBG("Listening on %s socket %d", name
, sock
->fd
);
957 ret
= sock
->ops
->bind(sock
);
962 ret
= sock
->ops
->listen(sock
, -1);
972 lttcomm_destroy_sock(sock
);
978 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
982 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
983 struct lttcomm_sock
*new_sock
= NULL
;
985 ret
= fd_tracker_open_unsuspendable_fd(
986 the_fd_tracker
, &out_fd
,
987 (const char **) &name
,
988 1, accept_sock
, &socks
);
993 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
999 * This thread manages the listening for new connections on the network
1001 static void *relay_thread_listener(void *data
)
1003 int i
, ret
, pollfd
, err
= -1;
1004 uint32_t revents
, nb_fd
;
1005 struct lttng_poll_event events
;
1006 struct lttcomm_sock
*control_sock
, *data_sock
;
1008 DBG("[thread] Relay listener started");
1010 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1012 health_code_update();
1014 control_sock
= relay_socket_create(control_uri
, "Control listener");
1015 if (!control_sock
) {
1016 goto error_sock_control
;
1019 data_sock
= relay_socket_create(data_uri
, "Data listener");
1021 goto error_sock_relay
;
1025 * Pass 3 as size here for the thread quit pipe, control and
1028 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1030 goto error_create_poll
;
1033 /* Add the control socket */
1034 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1036 goto error_poll_add
;
1039 /* Add the data socket */
1040 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1042 goto error_poll_add
;
1045 lttng_relay_notify_ready();
1047 if (testpoint(relayd_thread_listener
)) {
1048 goto error_testpoint
;
1052 health_code_update();
1054 DBG("Listener accepting connections");
1057 health_poll_entry();
1058 ret
= lttng_poll_wait(&events
, -1);
1062 * Restart interrupted system call.
1064 if (errno
== EINTR
) {
1072 DBG("Relay new connection received");
1073 for (i
= 0; i
< nb_fd
; i
++) {
1074 health_code_update();
1076 /* Fetch once the poll data */
1077 revents
= LTTNG_POLL_GETEV(&events
, i
);
1078 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1082 * No activity for this FD (poll
1088 /* Thread quit pipe has been closed. Killing thread. */
1089 ret
= check_thread_quit_pipe(pollfd
, revents
);
1095 if (revents
& LPOLLIN
) {
1097 * A new connection is requested, therefore a
1098 * sessiond/consumerd connection is allocated in
1099 * this thread, enqueued to a global queue and
1100 * dequeued (and freed) in the worker thread.
1103 struct relay_connection
*new_conn
;
1104 struct lttcomm_sock
*newsock
= NULL
;
1105 enum connection_type type
;
1107 if (pollfd
== data_sock
->fd
) {
1109 newsock
= accept_relayd_sock(data_sock
,
1110 "Data socket to relayd");
1112 assert(pollfd
== control_sock
->fd
);
1113 type
= RELAY_CONTROL
;
1114 newsock
= accept_relayd_sock(control_sock
,
1115 "Control socket to relayd");
1118 PERROR("accepting sock");
1122 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1125 PERROR("setsockopt inet");
1126 lttcomm_destroy_sock(newsock
);
1130 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1132 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1134 lttcomm_destroy_sock(newsock
);
1138 new_conn
= connection_create(newsock
, type
);
1140 lttcomm_destroy_sock(newsock
);
1144 /* Enqueue request for the dispatcher thread. */
1145 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1149 * Wake the dispatch queue futex.
1150 * Implicit memory barrier with the
1151 * exchange in cds_wfcq_enqueue.
1153 futex_nto1_wake(&relay_conn_queue
.futex
);
1154 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1155 ERR("socket poll error");
1158 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1168 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1170 if (data_sock
->fd
>= 0) {
1171 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1172 &data_sock
->fd
, 1, close_sock
,
1178 lttcomm_destroy_sock(data_sock
);
1180 if (control_sock
->fd
>= 0) {
1181 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1182 &control_sock
->fd
, 1, close_sock
,
1188 lttcomm_destroy_sock(control_sock
);
1192 ERR("Health error occurred in %s", __func__
);
1194 health_unregister(health_relayd
);
1195 DBG("Relay listener thread cleanup complete");
1196 lttng_relay_stop_threads();
1201 * This thread manages the dispatching of the requests to worker threads
1203 static void *relay_thread_dispatcher(void *data
)
1207 struct cds_wfcq_node
*node
;
1208 struct relay_connection
*new_conn
= NULL
;
1210 DBG("[thread] Relay dispatcher started");
1212 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1214 if (testpoint(relayd_thread_dispatcher
)) {
1215 goto error_testpoint
;
1218 health_code_update();
1221 health_code_update();
1223 /* Atomically prepare the queue futex */
1224 futex_nto1_prepare(&relay_conn_queue
.futex
);
1226 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1231 health_code_update();
1233 /* Dequeue commands */
1234 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1235 &relay_conn_queue
.tail
);
1237 DBG("Woken up but nothing in the relay command queue");
1238 /* Continue thread execution */
1241 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1243 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1246 * Inform worker thread of the new request. This
1247 * call is blocking so we can be assured that
1248 * the data will be read at some point in time
1249 * or wait to the end of the world :)
1251 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1253 PERROR("write connection pipe");
1254 connection_put(new_conn
);
1257 } while (node
!= NULL
);
1259 /* Futex wait on queue. Blocking call on futex() */
1260 health_poll_entry();
1261 futex_nto1_wait(&relay_conn_queue
.futex
);
1265 /* Normal exit, no error */
1272 ERR("Health error occurred in %s", __func__
);
1274 health_unregister(health_relayd
);
1275 DBG("Dispatch thread dying");
1276 lttng_relay_stop_threads();
1281 * Set index data from the control port to a given index object.
1283 static int set_index_control_data(struct relay_index
*index
,
1284 struct lttcomm_relayd_index
*data
,
1285 struct relay_connection
*conn
)
1287 struct ctf_packet_index index_data
;
1290 * The index on disk is encoded in big endian.
1292 index_data
.packet_size
= htobe64(data
->packet_size
);
1293 index_data
.content_size
= htobe64(data
->content_size
);
1294 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1295 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1296 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1297 index_data
.stream_id
= htobe64(data
->stream_id
);
1299 if (conn
->minor
>= 8) {
1300 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1301 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1304 return relay_index_set_data(index
, &index_data
);
1308 * Handle the RELAYD_CREATE_SESSION command.
1310 * On success, send back the session id or else return a negative value.
1312 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1313 struct relay_connection
*conn
,
1314 const struct lttng_buffer_view
*payload
)
1318 struct relay_session
*session
;
1319 struct lttcomm_relayd_status_session reply
;
1320 char session_name
[LTTNG_NAME_MAX
];
1321 char hostname
[LTTNG_HOST_NAME_MAX
];
1322 uint32_t live_timer
= 0;
1323 bool snapshot
= false;
1325 memset(session_name
, 0, LTTNG_NAME_MAX
);
1326 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1328 memset(&reply
, 0, sizeof(reply
));
1330 switch (conn
->minor
) {
1335 case 4: /* LTTng sessiond 2.4 */
1337 ret
= cmd_create_session_2_4(payload
, session_name
,
1338 hostname
, &live_timer
, &snapshot
);
1344 session
= session_create(session_name
, hostname
, live_timer
,
1345 snapshot
, conn
->major
, conn
->minor
);
1350 assert(!conn
->session
);
1351 conn
->session
= session
;
1352 DBG("Created session %" PRIu64
, session
->id
);
1354 reply
.session_id
= htobe64(session
->id
);
1358 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1360 reply
.ret_code
= htobe32(LTTNG_OK
);
1363 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1364 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1365 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1374 * When we have received all the streams and the metadata for a channel,
1375 * we make them visible to the viewer threads.
1377 static void publish_connection_local_streams(struct relay_connection
*conn
)
1379 struct relay_stream
*stream
;
1380 struct relay_session
*session
= conn
->session
;
1383 * We publish all streams belonging to a session atomically wrt
1386 pthread_mutex_lock(&session
->lock
);
1388 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1390 stream_publish(stream
);
1395 * Inform the viewer that there are new streams in the session.
1397 if (session
->viewer_attached
) {
1398 uatomic_set(&session
->new_streams
, 1);
1400 pthread_mutex_unlock(&session
->lock
);
1404 * relay_add_stream: allocate a new stream for a session
1406 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1407 struct relay_connection
*conn
,
1408 const struct lttng_buffer_view
*payload
)
1412 struct relay_session
*session
= conn
->session
;
1413 struct relay_stream
*stream
= NULL
;
1414 struct lttcomm_relayd_status_stream reply
;
1415 struct ctf_trace
*trace
= NULL
;
1416 uint64_t stream_handle
= -1ULL;
1417 char *path_name
= NULL
, *channel_name
= NULL
;
1418 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1420 if (!session
|| !conn
->version_check_done
) {
1421 ERR("Trying to add a stream before version check");
1423 goto end_no_session
;
1426 switch (session
->minor
) {
1427 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1428 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1429 &channel_name
, session
);
1431 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1433 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1434 &channel_name
, &tracefile_size
, &tracefile_count
,
1442 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1446 /* This stream here has one reference on the trace. */
1448 pthread_mutex_lock(&last_relay_stream_id_lock
);
1449 stream_handle
= ++last_relay_stream_id
;
1450 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1452 /* We pass ownership of path_name and channel_name. */
1453 stream
= stream_create(trace
, stream_handle
, path_name
,
1454 channel_name
, tracefile_size
, tracefile_count
);
1456 channel_name
= NULL
;
1459 * Streams are the owners of their trace. Reference to trace is
1460 * kept within stream_create().
1462 ctf_trace_put(trace
);
1465 memset(&reply
, 0, sizeof(reply
));
1466 reply
.handle
= htobe64(stream_handle
);
1468 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1470 reply
.ret_code
= htobe32(LTTNG_OK
);
1473 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1474 sizeof(struct lttcomm_relayd_status_stream
), 0);
1475 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1476 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1488 * relay_close_stream: close a specific stream
1490 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1491 struct relay_connection
*conn
,
1492 const struct lttng_buffer_view
*payload
)
1496 struct relay_session
*session
= conn
->session
;
1497 struct lttcomm_relayd_close_stream stream_info
;
1498 struct lttcomm_relayd_generic_reply reply
;
1499 struct relay_stream
*stream
;
1501 DBG("Close stream received");
1503 if (!session
|| !conn
->version_check_done
) {
1504 ERR("Trying to close a stream before version check");
1506 goto end_no_session
;
1509 if (payload
->size
< sizeof(stream_info
)) {
1510 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1511 sizeof(stream_info
), payload
->size
);
1513 goto end_no_session
;
1515 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1516 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1517 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1519 stream
= stream_get_by_id(stream_info
.stream_id
);
1526 * Set last_net_seq_num before the close flag. Required by data
1529 pthread_mutex_lock(&stream
->lock
);
1530 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1531 pthread_mutex_unlock(&stream
->lock
);
1534 * This is one of the conditions which may trigger a stream close
1535 * with the others being:
1536 * 1) A close command is received for a stream
1537 * 2) The control connection owning the stream is closed
1538 * 3) We have received all of the stream's data _after_ a close
1541 try_stream_close(stream
);
1542 if (stream
->is_metadata
) {
1543 struct relay_viewer_stream
*vstream
;
1545 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1547 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1549 * Since all the metadata has been sent to the
1550 * viewer and that we have a request to close
1551 * its stream, we can safely teardown the
1552 * corresponding metadata viewer stream.
1554 viewer_stream_put(vstream
);
1556 /* Put local reference. */
1557 viewer_stream_put(vstream
);
1564 memset(&reply
, 0, sizeof(reply
));
1566 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1568 reply
.ret_code
= htobe32(LTTNG_OK
);
1570 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1571 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1572 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1573 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1583 * relay_reset_metadata: reset a metadata stream
1586 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1587 struct relay_connection
*conn
,
1588 const struct lttng_buffer_view
*payload
)
1592 struct relay_session
*session
= conn
->session
;
1593 struct lttcomm_relayd_reset_metadata stream_info
;
1594 struct lttcomm_relayd_generic_reply reply
;
1595 struct relay_stream
*stream
;
1597 DBG("Reset metadata received");
1599 if (!session
|| !conn
->version_check_done
) {
1600 ERR("Trying to reset a metadata stream before version check");
1602 goto end_no_session
;
1605 if (payload
->size
< sizeof(stream_info
)) {
1606 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1607 sizeof(stream_info
), payload
->size
);
1609 goto end_no_session
;
1611 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1612 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1613 stream_info
.version
= be64toh(stream_info
.version
);
1615 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1617 /* Unsupported for live sessions for now. */
1618 if (session
->live_timer
!= 0) {
1623 stream
= stream_get_by_id(stream_info
.stream_id
);
1628 pthread_mutex_lock(&stream
->lock
);
1629 if (!stream
->is_metadata
) {
1634 ret
= stream_fd_rotate(stream
->stream_fd
,
1635 stream
->path_name
, stream
->channel_name
, 0, 0, NULL
);
1637 ERR("Failed to rotate metadata file %s of channel %s",
1638 stream
->path_name
, stream
->channel_name
);
1643 pthread_mutex_unlock(&stream
->lock
);
1647 memset(&reply
, 0, sizeof(reply
));
1649 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1651 reply
.ret_code
= htobe32(LTTNG_OK
);
1653 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1654 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1655 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1656 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1666 * relay_unknown_command: send -1 if received unknown command
1668 static void relay_unknown_command(struct relay_connection
*conn
)
1670 struct lttcomm_relayd_generic_reply reply
;
1673 memset(&reply
, 0, sizeof(reply
));
1674 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1675 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1676 if (send_ret
< sizeof(reply
)) {
1677 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1682 * relay_start: send an acknowledgment to the client to tell if we are
1683 * ready to receive data. We are ready if a session is established.
1685 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1686 struct relay_connection
*conn
,
1687 const struct lttng_buffer_view
*payload
)
1691 struct lttcomm_relayd_generic_reply reply
;
1692 struct relay_session
*session
= conn
->session
;
1695 DBG("Trying to start the streaming without a session established");
1696 ret
= htobe32(LTTNG_ERR_UNK
);
1699 memset(&reply
, 0, sizeof(reply
));
1700 reply
.ret_code
= htobe32(LTTNG_OK
);
1701 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1703 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1704 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1713 * Append padding to the file pointed by the file descriptor fd.
1715 static int write_padding_to_file(int fd
, uint32_t size
)
1724 zeros
= zmalloc(size
);
1725 if (zeros
== NULL
) {
1726 PERROR("zmalloc zeros for padding");
1731 ret
= lttng_write(fd
, zeros
, size
);
1733 PERROR("write padding to file");
1743 * relay_recv_metadata: receive the metadata for the session.
1745 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1746 struct relay_connection
*conn
,
1747 const struct lttng_buffer_view
*payload
)
1751 struct relay_session
*session
= conn
->session
;
1752 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1753 struct relay_stream
*metadata_stream
;
1754 uint64_t metadata_payload_size
;
1755 int metadata_fd
= -1;
1758 ERR("Metadata sent before version check");
1763 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1764 ERR("Incorrect data size");
1768 metadata_payload_size
= recv_hdr
->data_size
-
1769 sizeof(struct lttcomm_relayd_metadata_payload
);
1771 memcpy(&metadata_payload_header
, payload
->data
,
1772 sizeof(metadata_payload_header
));
1773 metadata_payload_header
.stream_id
= be64toh(
1774 metadata_payload_header
.stream_id
);
1775 metadata_payload_header
.padding_size
= be32toh(
1776 metadata_payload_header
.padding_size
);
1778 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1779 if (!metadata_stream
) {
1784 pthread_mutex_lock(&metadata_stream
->lock
);
1786 metadata_fd
= stream_fd_get_fd(metadata_stream
->stream_fd
);
1787 if (metadata_fd
< 0) {
1790 size_ret
= lttng_write(metadata_fd
,
1791 payload
->data
+ sizeof(metadata_payload_header
),
1792 metadata_payload_size
);
1793 if (size_ret
< metadata_payload_size
) {
1794 ERR("Relay error writing metadata on file");
1799 size_ret
= write_padding_to_file(metadata_fd
,
1800 metadata_payload_header
.padding_size
);
1801 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1806 metadata_stream
->metadata_received
+=
1807 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1808 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1809 metadata_stream
->metadata_received
);
1812 stream_fd_put_fd(metadata_stream
->stream_fd
);
1814 pthread_mutex_unlock(&metadata_stream
->lock
);
1815 stream_put(metadata_stream
);
1821 * relay_send_version: send relayd version number
1823 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1824 struct relay_connection
*conn
,
1825 const struct lttng_buffer_view
*payload
)
1829 struct lttcomm_relayd_version reply
, msg
;
1830 bool compatible
= true;
1832 conn
->version_check_done
= true;
1834 /* Get version from the other side. */
1835 if (payload
->size
< sizeof(msg
)) {
1836 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1837 sizeof(msg
), payload
->size
);
1842 memcpy(&msg
, payload
->data
, sizeof(msg
));
1843 msg
.major
= be32toh(msg
.major
);
1844 msg
.minor
= be32toh(msg
.minor
);
1846 memset(&reply
, 0, sizeof(reply
));
1847 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1848 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1850 /* Major versions must be the same */
1851 if (reply
.major
!= msg
.major
) {
1852 DBG("Incompatible major versions (%u vs %u), deleting session",
1853 reply
.major
, msg
.major
);
1857 conn
->major
= reply
.major
;
1858 /* We adapt to the lowest compatible version */
1859 if (reply
.minor
<= msg
.minor
) {
1860 conn
->minor
= reply
.minor
;
1862 conn
->minor
= msg
.minor
;
1865 reply
.major
= htobe32(reply
.major
);
1866 reply
.minor
= htobe32(reply
.minor
);
1867 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1869 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1870 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1883 DBG("Version check done using protocol %u.%u", conn
->major
,
1891 * Check for data pending for a given stream id from the session daemon.
1893 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1894 struct relay_connection
*conn
,
1895 const struct lttng_buffer_view
*payload
)
1897 struct relay_session
*session
= conn
->session
;
1898 struct lttcomm_relayd_data_pending msg
;
1899 struct lttcomm_relayd_generic_reply reply
;
1900 struct relay_stream
*stream
;
1904 DBG("Data pending command received");
1906 if (!session
|| !conn
->version_check_done
) {
1907 ERR("Trying to check for data before version check");
1909 goto end_no_session
;
1912 if (payload
->size
< sizeof(msg
)) {
1913 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1914 sizeof(msg
), payload
->size
);
1916 goto end_no_session
;
1918 memcpy(&msg
, payload
->data
, sizeof(msg
));
1919 msg
.stream_id
= be64toh(msg
.stream_id
);
1920 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1922 stream
= stream_get_by_id(msg
.stream_id
);
1923 if (stream
== NULL
) {
1928 pthread_mutex_lock(&stream
->lock
);
1930 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1931 " and last_seq %" PRIu64
, msg
.stream_id
,
1932 stream
->prev_seq
, msg
.last_net_seq_num
);
1934 /* Avoid wrapping issue */
1935 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1936 /* Data has in fact been written and is NOT pending */
1939 /* Data still being streamed thus pending */
1943 stream
->data_pending_check_done
= true;
1944 pthread_mutex_unlock(&stream
->lock
);
1949 memset(&reply
, 0, sizeof(reply
));
1950 reply
.ret_code
= htobe32(ret
);
1951 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1952 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1953 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1963 * Wait for the control socket to reach a quiescent state.
1965 * Note that for now, when receiving this command from the session
1966 * daemon, this means that every subsequent commands or data received on
1967 * the control socket has been handled. So, this is why we simply return
1970 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1971 struct relay_connection
*conn
,
1972 const struct lttng_buffer_view
*payload
)
1976 struct relay_stream
*stream
;
1977 struct lttcomm_relayd_quiescent_control msg
;
1978 struct lttcomm_relayd_generic_reply reply
;
1980 DBG("Checking quiescent state on control socket");
1982 if (!conn
->session
|| !conn
->version_check_done
) {
1983 ERR("Trying to check for data before version check");
1985 goto end_no_session
;
1988 if (payload
->size
< sizeof(msg
)) {
1989 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1990 sizeof(msg
), payload
->size
);
1992 goto end_no_session
;
1994 memcpy(&msg
, payload
->data
, sizeof(msg
));
1995 msg
.stream_id
= be64toh(msg
.stream_id
);
1997 stream
= stream_get_by_id(msg
.stream_id
);
2001 pthread_mutex_lock(&stream
->lock
);
2002 stream
->data_pending_check_done
= true;
2003 pthread_mutex_unlock(&stream
->lock
);
2005 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2008 memset(&reply
, 0, sizeof(reply
));
2009 reply
.ret_code
= htobe32(LTTNG_OK
);
2010 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2011 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2012 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2024 * Initialize a data pending command. This means that a consumer is about
2025 * to ask for data pending for each stream it holds. Simply iterate over
2026 * all streams of a session and set the data_pending_check_done flag.
2028 * This command returns to the client a LTTNG_OK code.
2030 static int relay_begin_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_begin_data_pending msg
;
2038 struct lttcomm_relayd_generic_reply reply
;
2039 struct relay_stream
*stream
;
2044 DBG("Init streams for data pending");
2046 if (!conn
->session
|| !conn
->version_check_done
) {
2047 ERR("Trying to check for data before version check");
2049 goto end_no_session
;
2052 if (payload
->size
< sizeof(msg
)) {
2053 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2054 sizeof(msg
), payload
->size
);
2056 goto end_no_session
;
2058 memcpy(&msg
, payload
->data
, sizeof(msg
));
2059 msg
.session_id
= be64toh(msg
.session_id
);
2062 * Iterate over all streams to set the begin data pending flag.
2063 * For now, the streams are indexed by stream handle so we have
2064 * to iterate over all streams to find the one associated with
2065 * the right session_id.
2068 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2070 if (!stream_get(stream
)) {
2073 if (stream
->trace
->session
->id
== msg
.session_id
) {
2074 pthread_mutex_lock(&stream
->lock
);
2075 stream
->data_pending_check_done
= false;
2076 pthread_mutex_unlock(&stream
->lock
);
2077 DBG("Set begin data pending flag to stream %" PRIu64
,
2078 stream
->stream_handle
);
2084 memset(&reply
, 0, sizeof(reply
));
2085 /* All good, send back reply. */
2086 reply
.ret_code
= htobe32(LTTNG_OK
);
2088 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2089 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2090 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2102 * End data pending command. This will check, for a given session id, if
2103 * each stream associated with it has its data_pending_check_done flag
2104 * set. If not, this means that the client lost track of the stream but
2105 * the data is still being streamed on our side. In this case, we inform
2106 * the client that data is in flight.
2108 * Return to the client if there is data in flight or not with a ret_code.
2110 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2111 struct relay_connection
*conn
,
2112 const struct lttng_buffer_view
*payload
)
2116 struct lttng_ht_iter iter
;
2117 struct lttcomm_relayd_end_data_pending msg
;
2118 struct lttcomm_relayd_generic_reply reply
;
2119 struct relay_stream
*stream
;
2120 uint32_t is_data_inflight
= 0;
2122 DBG("End data pending command");
2124 if (!conn
->session
|| !conn
->version_check_done
) {
2125 ERR("Trying to check for data before version check");
2127 goto end_no_session
;
2130 if (payload
->size
< sizeof(msg
)) {
2131 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2132 sizeof(msg
), payload
->size
);
2134 goto end_no_session
;
2136 memcpy(&msg
, payload
->data
, sizeof(msg
));
2137 msg
.session_id
= be64toh(msg
.session_id
);
2140 * Iterate over all streams to see if the begin data pending
2144 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2146 if (!stream_get(stream
)) {
2149 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2153 pthread_mutex_lock(&stream
->lock
);
2154 if (!stream
->data_pending_check_done
) {
2155 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2156 is_data_inflight
= 1;
2157 DBG("Data is still in flight for stream %" PRIu64
,
2158 stream
->stream_handle
);
2159 pthread_mutex_unlock(&stream
->lock
);
2164 pthread_mutex_unlock(&stream
->lock
);
2169 memset(&reply
, 0, sizeof(reply
));
2170 /* All good, send back reply. */
2171 reply
.ret_code
= htobe32(is_data_inflight
);
2173 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2174 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2175 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2187 * Receive an index for a specific stream.
2189 * Return 0 on success else a negative value.
2191 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2192 struct relay_connection
*conn
,
2193 const struct lttng_buffer_view
*payload
)
2197 struct relay_session
*session
= conn
->session
;
2198 struct lttcomm_relayd_index index_info
;
2199 struct relay_index
*index
;
2200 struct lttcomm_relayd_generic_reply reply
;
2201 struct relay_stream
*stream
;
2206 DBG("Relay receiving index");
2208 if (!session
|| !conn
->version_check_done
) {
2209 ERR("Trying to close a stream before version check");
2211 goto end_no_session
;
2214 msg_len
= lttcomm_relayd_index_len(
2215 lttng_to_index_major(conn
->major
, conn
->minor
),
2216 lttng_to_index_minor(conn
->major
, conn
->minor
));
2217 if (payload
->size
< msg_len
) {
2218 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2219 msg_len
, payload
->size
);
2221 goto end_no_session
;
2223 memcpy(&index_info
, payload
->data
, msg_len
);
2224 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2225 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2226 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2227 index_info
.content_size
= be64toh(index_info
.content_size
);
2228 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2229 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2230 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2231 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2233 if (conn
->minor
>= 8) {
2234 index_info
.stream_instance_id
=
2235 be64toh(index_info
.stream_instance_id
);
2236 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2239 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2241 ERR("stream_get_by_id not found");
2245 pthread_mutex_lock(&stream
->lock
);
2247 /* Live beacon handling */
2248 if (index_info
.packet_size
== 0) {
2249 DBG("Received live beacon for stream %" PRIu64
,
2250 stream
->stream_handle
);
2253 * Only flag a stream inactive when it has already
2254 * received data and no indexes are in flight.
2256 if (stream
->index_received_seqcount
> 0
2257 && stream
->indexes_in_flight
== 0) {
2258 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2261 goto end_stream_put
;
2263 stream
->beacon_ts_end
= -1ULL;
2266 if (stream
->ctf_stream_id
== -1ULL) {
2267 stream
->ctf_stream_id
= index_info
.stream_id
;
2269 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2272 ERR("relay_index_get_by_id_or_create index NULL");
2273 goto end_stream_put
;
2275 if (set_index_control_data(index
, &index_info
, conn
)) {
2276 ERR("set_index_control_data error");
2277 relay_index_put(index
);
2279 goto end_stream_put
;
2281 ret
= relay_index_try_flush(index
);
2283 tracefile_array_commit_seq(stream
->tfa
);
2284 stream
->index_received_seqcount
++;
2285 } else if (ret
> 0) {
2292 * relay_index_try_flush is responsible for the self-reference
2293 * put of the index object on error.
2295 ERR("relay_index_try_flush error %d", ret
);
2300 pthread_mutex_unlock(&stream
->lock
);
2305 memset(&reply
, 0, sizeof(reply
));
2307 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2309 reply
.ret_code
= htobe32(LTTNG_OK
);
2311 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2312 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2313 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2322 * Receive the streams_sent message.
2324 * Return 0 on success else a negative value.
2326 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2327 struct relay_connection
*conn
,
2328 const struct lttng_buffer_view
*payload
)
2332 struct lttcomm_relayd_generic_reply reply
;
2336 DBG("Relay receiving streams_sent");
2338 if (!conn
->session
|| !conn
->version_check_done
) {
2339 ERR("Trying to close a stream before version check");
2341 goto end_no_session
;
2345 * Publish every pending stream in the connection recv list which are
2346 * now ready to be used by the viewer.
2348 publish_connection_local_streams(conn
);
2350 memset(&reply
, 0, sizeof(reply
));
2351 reply
.ret_code
= htobe32(LTTNG_OK
);
2352 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2353 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2354 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2366 #define DBG_CMD(cmd_name, conn) \
2367 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2369 static int relay_process_control_command(struct relay_connection
*conn
,
2370 const struct lttcomm_relayd_hdr
*header
,
2371 const struct lttng_buffer_view
*payload
)
2375 switch (header
->cmd
) {
2376 case RELAYD_CREATE_SESSION
:
2377 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2378 ret
= relay_create_session(header
, conn
, payload
);
2380 case RELAYD_ADD_STREAM
:
2381 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2382 ret
= relay_add_stream(header
, conn
, payload
);
2384 case RELAYD_START_DATA
:
2385 DBG_CMD("RELAYD_START_DATA", conn
);
2386 ret
= relay_start(header
, conn
, payload
);
2388 case RELAYD_SEND_METADATA
:
2389 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2390 ret
= relay_recv_metadata(header
, conn
, payload
);
2392 case RELAYD_VERSION
:
2393 DBG_CMD("RELAYD_VERSION", conn
);
2394 ret
= relay_send_version(header
, conn
, payload
);
2396 case RELAYD_CLOSE_STREAM
:
2397 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2398 ret
= relay_close_stream(header
, conn
, payload
);
2400 case RELAYD_DATA_PENDING
:
2401 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2402 ret
= relay_data_pending(header
, conn
, payload
);
2404 case RELAYD_QUIESCENT_CONTROL
:
2405 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2406 ret
= relay_quiescent_control(header
, conn
, payload
);
2408 case RELAYD_BEGIN_DATA_PENDING
:
2409 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2410 ret
= relay_begin_data_pending(header
, conn
, payload
);
2412 case RELAYD_END_DATA_PENDING
:
2413 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2414 ret
= relay_end_data_pending(header
, conn
, payload
);
2416 case RELAYD_SEND_INDEX
:
2417 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2418 ret
= relay_recv_index(header
, conn
, payload
);
2420 case RELAYD_STREAMS_SENT
:
2421 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2422 ret
= relay_streams_sent(header
, conn
, payload
);
2424 case RELAYD_RESET_METADATA
:
2425 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2426 ret
= relay_reset_metadata(header
, conn
, payload
);
2428 case RELAYD_UPDATE_SYNC_INFO
:
2430 ERR("Received unknown command (%u)", header
->cmd
);
2431 relay_unknown_command(conn
);
2440 static enum relay_connection_status
relay_process_control_receive_payload(
2441 struct relay_connection
*conn
)
2444 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2445 struct lttng_dynamic_buffer
*reception_buffer
=
2446 &conn
->protocol
.ctrl
.reception_buffer
;
2447 struct ctrl_connection_state_receive_payload
*state
=
2448 &conn
->protocol
.ctrl
.state
.receive_payload
;
2449 struct lttng_buffer_view payload_view
;
2451 if (state
->left_to_receive
== 0) {
2452 /* Short-circuit for payload-less commands. */
2453 goto reception_complete
;
2455 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2456 reception_buffer
->data
+ state
->received
,
2457 state
->left_to_receive
, MSG_DONTWAIT
);
2459 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2460 PERROR("Unable to receive command payload on sock %d",
2462 status
= RELAY_CONNECTION_STATUS_ERROR
;
2465 } else if (ret
== 0) {
2466 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2467 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2472 assert(ret
<= state
->left_to_receive
);
2474 state
->left_to_receive
-= ret
;
2475 state
->received
+= ret
;
2477 if (state
->left_to_receive
> 0) {
2479 * Can't transition to the protocol's next state, wait to
2480 * receive the rest of the header.
2482 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2483 state
->received
, state
->left_to_receive
,
2489 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2490 conn
->sock
->fd
, state
->received
);
2492 * The payload required to process the command has been received.
2493 * A view to the reception buffer is forwarded to the various
2494 * commands and the state of the control is reset on success.
2496 * Commands are responsible for sending their reply to the peer.
2498 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2500 ret
= relay_process_control_command(conn
,
2501 &state
->header
, &payload_view
);
2503 status
= RELAY_CONNECTION_STATUS_ERROR
;
2507 ret
= connection_reset_protocol_state(conn
);
2509 status
= RELAY_CONNECTION_STATUS_ERROR
;
2515 static enum relay_connection_status
relay_process_control_receive_header(
2516 struct relay_connection
*conn
)
2519 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2520 struct lttcomm_relayd_hdr header
;
2521 struct lttng_dynamic_buffer
*reception_buffer
=
2522 &conn
->protocol
.ctrl
.reception_buffer
;
2523 struct ctrl_connection_state_receive_header
*state
=
2524 &conn
->protocol
.ctrl
.state
.receive_header
;
2526 assert(state
->left_to_receive
!= 0);
2528 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2529 reception_buffer
->data
+ state
->received
,
2530 state
->left_to_receive
, MSG_DONTWAIT
);
2532 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2533 PERROR("Unable to receive control command header on sock %d",
2535 status
= RELAY_CONNECTION_STATUS_ERROR
;
2538 } else if (ret
== 0) {
2539 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2540 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2545 assert(ret
<= state
->left_to_receive
);
2547 state
->left_to_receive
-= ret
;
2548 state
->received
+= ret
;
2550 if (state
->left_to_receive
> 0) {
2552 * Can't transition to the protocol's next state, wait to
2553 * receive the rest of the header.
2555 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2556 state
->received
, state
->left_to_receive
,
2561 /* Transition to next state: receiving the command's payload. */
2562 conn
->protocol
.ctrl
.state_id
=
2563 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2564 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2565 header
.circuit_id
= be64toh(header
.circuit_id
);
2566 header
.data_size
= be64toh(header
.data_size
);
2567 header
.cmd
= be32toh(header
.cmd
);
2568 header
.cmd_version
= be32toh(header
.cmd_version
);
2569 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2570 &header
, sizeof(header
));
2572 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2573 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2576 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2577 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2579 status
= RELAY_CONNECTION_STATUS_ERROR
;
2583 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2585 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2586 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2589 status
= RELAY_CONNECTION_STATUS_ERROR
;
2593 if (header
.data_size
== 0) {
2595 * Manually invoke the next state as the poll loop
2596 * will not wake-up to allow us to proceed further.
2598 status
= relay_process_control_receive_payload(conn
);
2605 * Process the commands received on the control socket
2607 static enum relay_connection_status
relay_process_control(
2608 struct relay_connection
*conn
)
2610 enum relay_connection_status status
;
2612 switch (conn
->protocol
.ctrl
.state_id
) {
2613 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2614 status
= relay_process_control_receive_header(conn
);
2616 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2617 status
= relay_process_control_receive_payload(conn
);
2620 ERR("Unknown control connection protocol state encountered.");
2628 * Handle index for a data stream.
2630 * Called with the stream lock held.
2632 * Return 0 on success else a negative value.
2634 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2638 uint64_t data_offset
;
2639 struct relay_index
*index
;
2641 /* Get data offset because we are about to update the index. */
2642 data_offset
= htobe64(stream
->tracefile_size_current
);
2644 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2645 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2648 * Lookup for an existing index for that stream id/sequence
2649 * number. If it exists, the control thread has already received the
2650 * data for it, thus we need to write it to disk.
2652 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2658 if (rotate_index
|| !stream
->index_file
) {
2659 uint32_t major
, minor
;
2661 /* Put ref on previous index_file. */
2662 if (stream
->index_file
) {
2663 relay_index_file_put(stream
->index_file
);
2664 stream
->index_file
= NULL
;
2666 major
= stream
->trace
->session
->major
;
2667 minor
= stream
->trace
->session
->minor
;
2668 stream
->index_file
= relay_index_file_create(stream
->path_name
,
2669 stream
->channel_name
,
2670 stream
->tracefile_size
,
2671 tracefile_array_get_file_index_head(stream
->tfa
),
2672 lttng_to_index_major(major
, minor
),
2673 lttng_to_index_minor(major
, minor
));
2674 if (!stream
->index_file
) {
2676 /* Put self-ref for this index due to error. */
2677 relay_index_put(index
);
2683 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2685 /* Put self-ref for this index due to error. */
2686 relay_index_put(index
);
2691 ret
= relay_index_try_flush(index
);
2693 tracefile_array_commit_seq(stream
->tfa
);
2694 stream
->index_received_seqcount
++;
2695 } else if (ret
> 0) {
2702 * relay_index_try_flush is responsible for the self-reference
2703 * put of the index object on error.
2705 ERR("relay_index_try_flush error %d", ret
);
2712 static enum relay_connection_status
relay_process_data_receive_header(
2713 struct relay_connection
*conn
)
2716 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2717 struct data_connection_state_receive_header
*state
=
2718 &conn
->protocol
.data
.state
.receive_header
;
2719 struct lttcomm_relayd_data_hdr header
;
2720 struct relay_stream
*stream
;
2722 assert(state
->left_to_receive
!= 0);
2724 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2725 state
->header_reception_buffer
+ state
->received
,
2726 state
->left_to_receive
, MSG_DONTWAIT
);
2728 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2729 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2730 status
= RELAY_CONNECTION_STATUS_ERROR
;
2733 } else if (ret
== 0) {
2734 /* Orderly shutdown. Not necessary to print an error. */
2735 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2736 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2741 assert(ret
<= state
->left_to_receive
);
2743 state
->left_to_receive
-= ret
;
2744 state
->received
+= ret
;
2746 if (state
->left_to_receive
> 0) {
2748 * Can't transition to the protocol's next state, wait to
2749 * receive the rest of the header.
2751 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2752 state
->received
, state
->left_to_receive
,
2758 /* Transition to next state: receiving the payload. */
2759 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2761 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2762 header
.circuit_id
= be64toh(header
.circuit_id
);
2763 header
.stream_id
= be64toh(header
.stream_id
);
2764 header
.data_size
= be32toh(header
.data_size
);
2765 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2766 header
.padding_size
= be32toh(header
.padding_size
);
2767 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2769 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2771 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2772 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2774 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2775 conn
->sock
->fd
, header
.circuit_id
,
2776 header
.stream_id
, header
.data_size
,
2777 header
.net_seq_num
, header
.padding_size
);
2779 stream
= stream_get_by_id(header
.stream_id
);
2781 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2783 /* Protocol error. */
2784 status
= RELAY_CONNECTION_STATUS_ERROR
;
2788 pthread_mutex_lock(&stream
->lock
);
2790 /* Check if a rotation is needed. */
2791 if (stream
->tracefile_size
> 0 &&
2792 (stream
->tracefile_size_current
+ header
.data_size
) >
2793 stream
->tracefile_size
) {
2794 uint64_t old_id
, new_id
;
2796 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2797 tracefile_array_file_rotate(stream
->tfa
);
2799 /* new_id is updated by utils_rotate_stream_file. */
2802 ret
= stream_fd_rotate(stream
->stream_fd
, stream
->path_name
,
2803 stream
->channel_name
, stream
->tracefile_size
,
2804 stream
->tracefile_count
, &new_id
);
2806 ERR("Failed to rotate stream output file");
2807 status
= RELAY_CONNECTION_STATUS_ERROR
;
2808 goto end_stream_unlock
;
2812 * Reset current size because we just performed a stream
2815 stream
->tracefile_size_current
= 0;
2816 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2821 pthread_mutex_unlock(&stream
->lock
);
2827 static enum relay_connection_status
relay_process_data_receive_payload(
2828 struct relay_connection
*conn
)
2831 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2832 struct relay_stream
*stream
;
2833 struct data_connection_state_receive_payload
*state
=
2834 &conn
->protocol
.data
.state
.receive_payload
;
2835 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2836 char data_buffer
[chunk_size
];
2837 bool new_stream
= false, close_requested
= false;
2838 uint64_t left_to_receive
= state
->left_to_receive
;
2839 struct relay_session
*session
;
2842 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2843 state
->header
.stream_id
, state
->header
.net_seq_num
,
2844 state
->received
, left_to_receive
);
2846 stream
= stream_get_by_id(state
->header
.stream_id
);
2848 /* Protocol error. */
2849 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2850 state
->header
.stream_id
);
2851 status
= RELAY_CONNECTION_STATUS_ERROR
;
2855 pthread_mutex_lock(&stream
->lock
);
2856 session
= stream
->trace
->session
;
2857 if (!conn
->session
) {
2858 ret
= connection_set_session(conn
, session
);
2860 status
= RELAY_CONNECTION_STATUS_ERROR
;
2861 goto end_stream_unlock
;
2865 stream_fd
= stream_fd_get_fd(stream
->stream_fd
);
2866 if (stream_fd
< 0) {
2867 status
= RELAY_CONNECTION_STATUS_ERROR
;
2868 goto end_stream_unlock
;
2872 * The size of the "chunk" received on any iteration is bounded by:
2873 * - the data left to receive,
2874 * - the data immediately available on the socket,
2875 * - the on-stack data buffer
2877 if (left_to_receive
> 0) {
2879 size_t recv_size
= min(left_to_receive
, chunk_size
);
2881 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2882 recv_size
, MSG_DONTWAIT
);
2884 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2885 PERROR("Socket %d error", conn
->sock
->fd
);
2886 status
= RELAY_CONNECTION_STATUS_ERROR
;
2889 } else if (ret
== 0) {
2890 /* No more data ready to be consumed on socket. */
2891 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2892 state
->header
.stream_id
);
2893 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2894 goto data_left_to_process
;
2899 /* Write data to stream output fd. */
2900 write_ret
= lttng_write(stream_fd
, data_buffer
,
2902 if (write_ret
< (ssize_t
) recv_size
) {
2903 ERR("Relay error writing data to file");
2904 status
= RELAY_CONNECTION_STATUS_ERROR
;
2908 left_to_receive
-= recv_size
;
2909 state
->received
+= recv_size
;
2910 state
->left_to_receive
= left_to_receive
;
2912 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2913 write_ret
, stream
->stream_handle
);
2916 data_left_to_process
:
2918 if (state
->left_to_receive
> 0) {
2920 * Did not receive all the data expected, wait for more data to
2921 * become available on the socket.
2923 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2924 state
->header
.stream_id
, state
->received
,
2925 state
->left_to_receive
);
2929 ret
= write_padding_to_file(stream_fd
,
2930 state
->header
.padding_size
);
2931 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2932 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2933 stream
->stream_handle
,
2934 state
->header
.net_seq_num
, ret
);
2935 status
= RELAY_CONNECTION_STATUS_ERROR
;
2940 if (session
->minor
>= 4 && !session
->snapshot
) {
2941 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2942 state
->rotate_index
);
2944 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2945 stream
->stream_handle
,
2946 state
->header
.net_seq_num
, ret
);
2947 status
= RELAY_CONNECTION_STATUS_ERROR
;
2952 stream
->tracefile_size_current
+= state
->header
.data_size
+
2953 state
->header
.padding_size
;
2955 if (stream
->prev_seq
== -1ULL) {
2959 stream
->prev_seq
= state
->header
.net_seq_num
;
2962 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2963 * contents of *state which are aliased (union) to the same location as
2964 * the new state. Don't use it beyond this point.
2966 connection_reset_protocol_state(conn
);
2970 stream_fd_put_fd(stream
->stream_fd
);
2972 close_requested
= stream
->close_requested
;
2973 pthread_mutex_unlock(&stream
->lock
);
2974 if (close_requested
&& left_to_receive
== 0) {
2975 try_stream_close(stream
);
2979 pthread_mutex_lock(&session
->lock
);
2980 uatomic_set(&session
->new_streams
, 1);
2981 pthread_mutex_unlock(&session
->lock
);
2990 * relay_process_data: Process the data received on the data socket
2992 static enum relay_connection_status
relay_process_data(
2993 struct relay_connection
*conn
)
2995 enum relay_connection_status status
;
2997 switch (conn
->protocol
.data
.state_id
) {
2998 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2999 status
= relay_process_data_receive_header(conn
);
3001 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3002 status
= relay_process_data_receive_payload(conn
);
3005 ERR("Unexpected data connection communication state.");
3012 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3016 (void) lttng_poll_del(events
, pollfd
);
3018 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3019 fd_tracker_util_close_fd
, NULL
);
3021 ERR("Closing pollfd %d", pollfd
);
3025 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3026 int pollfd
, struct relay_connection
*conn
)
3028 const char *type_str
;
3030 switch (conn
->type
) {
3035 type_str
= "Control";
3037 case RELAY_VIEWER_COMMAND
:
3038 type_str
= "Viewer Command";
3040 case RELAY_VIEWER_NOTIFICATION
:
3041 type_str
= "Viewer Notification";
3044 type_str
= "Unknown";
3046 cleanup_connection_pollfd(events
, pollfd
);
3047 connection_put(conn
);
3048 DBG("%s connection closed with %d", type_str
, pollfd
);
3052 * This thread does the actual work
3054 static void *relay_thread_worker(void *data
)
3058 struct lttng_poll_event events
;
3059 struct lttng_ht
*relay_connections_ht
;
3060 struct lttng_ht_iter iter
;
3061 struct relay_connection
*tmp_conn
= NULL
;
3062 uint64_t relay_conn_pipe_activity_phase
= 0;
3063 uint64_t current_activity_phase
= 1;
3065 DBG("[thread] Relay worker started");
3067 rcu_register_thread();
3069 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3071 if (testpoint(relayd_thread_worker
)) {
3072 goto error_testpoint
;
3075 health_code_update();
3077 /* table of connections indexed on socket */
3078 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3079 if (!relay_connections_ht
) {
3080 goto relay_connections_ht_error
;
3083 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3085 goto error_poll_create
;
3088 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3096 bool at_least_one_event_processed
= false;
3098 health_code_update();
3100 /* Infinite blocking call, waiting for transmission */
3101 DBG3("Relayd worker thread polling...");
3102 health_poll_entry();
3103 ret
= lttng_poll_wait(&events
, -1);
3107 * Restart interrupted system call.
3109 if (errno
== EINTR
) {
3118 * Processes FDs that were not yet active during the
3119 * current activity phase. Increment the activity phase when all
3120 * events are already processed for the current activity
3121 * phase. This result in fairness across all connections and
3124 for (i
= 0; i
< nb_fd
; i
++) {
3125 /* Fetch once the poll data */
3126 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3127 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3129 health_code_update();
3133 * No activity for this FD (poll
3139 /* Thread quit pipe has been closed. Killing thread. */
3140 ret
= check_thread_quit_pipe(pollfd
, revents
);
3146 /* Inspect the relay conn pipe for new connection */
3147 if (pollfd
== relay_conn_pipe
[0]) {
3148 if (revents
& LPOLLIN
) {
3149 struct relay_connection
*conn
;
3151 if (relay_conn_pipe_activity_phase
== current_activity_phase
) {
3153 * Only consider once per
3154 * activity phase for fairness.
3156 DBG("Skipping adding reception, already happened in activity phase %" PRIu64
, current_activity_phase
);
3160 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3165 * For now we prefer fairness over
3166 * "immediate" action of new
3167 * connection. Set activity phase to the
3170 conn
->activity_phase
= current_activity_phase
;
3171 lttng_poll_add(&events
, conn
->sock
->fd
,
3172 LPOLLIN
| LPOLLRDHUP
);
3173 connection_ht_add(relay_connections_ht
, conn
);
3174 DBG("Connection socket %d added", conn
->sock
->fd
);
3175 relay_conn_pipe_activity_phase
= current_activity_phase
;
3176 at_least_one_event_processed
= true;
3177 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3178 ERR("Relay connection pipe error");
3181 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3185 struct relay_connection
*connection
;
3187 connection
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3188 /* If not found, there is a synchronization issue. */
3190 if (connection
->activity_phase
== current_activity_phase
) {
3191 DBG3("Skipping connection %d, already processed in activity phase %" PRIu64
, connection
->sock
->fd
, current_activity_phase
);
3192 goto connection_put
;
3195 if (revents
& LPOLLIN
) {
3196 enum relay_connection_status status
;
3198 at_least_one_event_processed
= true;
3199 connection
->activity_phase
= current_activity_phase
;
3201 if (connection
->type
== RELAY_DATA
) {
3202 status
= relay_process_data(connection
);
3204 status
= relay_process_control(connection
);
3206 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3208 * On socket error flag the session as aborted to force
3209 * the cleanup of its stream otherwise it can leak
3210 * during the lifetime of the relayd.
3212 * This prevents situations in which streams can be
3213 * left opened because an index was received, the
3214 * control connection is closed, and the data
3215 * connection is closed (uncleanly) before the packet's
3218 * Since the connection encountered an error,
3219 * it is okay to be conservative and close the
3220 * session right now as we can't rely on the protocol
3221 * being respected anymore.
3223 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3224 session_abort(connection
->session
);
3227 /* Clear the connection on error or close. */
3228 relay_thread_close_connection(&events
,
3232 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3233 relay_thread_close_connection(&events
,
3234 pollfd
, connection
);
3236 ERR("Unexpected poll events %u for sock %d",
3238 connection_put(connection
);
3242 connection_put(connection
);
3246 if (!at_least_one_event_processed
) {
3247 current_activity_phase
++;
3248 DBG3("Incrementing activity phase: %" PRIu64
, current_activity_phase
);
3252 /* Normal exit, no error */
3257 /* Cleanup reamaining connection object. */
3259 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3262 health_code_update();
3264 session_abort(tmp_conn
->session
);
3267 * No need to grab another ref, because we own
3270 relay_thread_close_connection(&events
, tmp_conn
->sock
->fd
,
3275 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3277 lttng_ht_destroy(relay_connections_ht
);
3278 relay_connections_ht_error
:
3279 /* Close relay conn pipes */
3280 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3283 DBG("Thread exited with error");
3285 DBG("Worker thread cleanup complete");
3289 ERR("Health error occurred in %s", __func__
);
3291 health_unregister(health_relayd
);
3292 rcu_unregister_thread();
3293 lttng_relay_stop_threads();
3298 * Create the relay command pipe to wake thread_manage_apps.
3299 * Closed in cleanup().
3301 static int create_relay_conn_pipe(void)
3303 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3304 "Relayd connection pipe", relay_conn_pipe
);
3308 int stdio_open(void *data
, int *fds
)
3310 fds
[0] = fileno(stdout
);
3311 fds
[1] = fileno(stderr
);
3316 int noop_close(void *data
, int *fds
)
3322 int track_stdio(void)
3325 const char *names
[] = { "stdout", "stderr" };
3327 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
3328 names
, 2, stdio_open
, NULL
);
3332 void untrack_stdio(void)
3334 int fds
[] = { fileno(stdout
), fileno(stderr
) };
3337 * noop_close is used since we don't really want to close
3338 * the stdio output fds; we merely want to stop tracking them.
3340 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
3341 fds
, 2, noop_close
, NULL
);
3347 int main(int argc
, char **argv
)
3349 int ret
= 0, retval
= 0;
3352 /* Parse environment variables */
3353 parse_env_options();
3357 * Command line arguments overwrite environment.
3360 if (set_options(argc
, argv
)) {
3365 if (set_signal_handler()) {
3370 relayd_config_log();
3372 if (opt_print_version
) {
3378 ret
= fclose(stdin
);
3380 PERROR("Failed to close stdin");
3383 /* Try to create directory if -o, --output is specified. */
3384 if (opt_output_path
) {
3385 if (*opt_output_path
!= '/') {
3386 ERR("Please specify an absolute path for -o, --output PATH");
3391 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3394 ERR("Unable to create %s", opt_output_path
);
3401 if (opt_daemon
|| opt_background
) {
3402 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3410 if (opt_working_directory
) {
3411 ret
= utils_change_working_dir(opt_working_directory
);
3413 ERR("Changing working directory");
3418 * The RCU thread registration (and use, through the fd-tracker's
3419 * creation) is done after the daemonization to allow us to not
3420 * deal with liburcu's fork() management as the call RCU needs to
3423 rcu_register_thread();
3425 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_pool_size
);
3426 if (!the_fd_tracker
) {
3431 ret
= track_stdio();
3437 /* Initialize thread health monitoring */
3438 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3439 if (!health_relayd
) {
3440 PERROR("health_app_create error");
3442 goto exit_health_app_create
;
3445 /* Create thread quit pipe */
3446 if (init_thread_quit_pipe()) {
3448 goto exit_init_data
;
3451 /* Setup the thread apps communication pipe. */
3452 if (create_relay_conn_pipe()) {
3454 goto exit_init_data
;
3457 /* Init relay command queue. */
3458 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3460 /* Initialize communication library */
3462 lttcomm_inet_init();
3464 /* tables of sessions indexed by session ID */
3465 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3468 goto exit_init_data
;
3471 /* tables of streams indexed by stream ID */
3472 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3473 if (!relay_streams_ht
) {
3475 goto exit_init_data
;
3478 /* tables of streams indexed by stream ID */
3479 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3480 if (!viewer_streams_ht
) {
3482 goto exit_init_data
;
3485 ret
= init_health_quit_pipe();
3488 goto exit_health_quit_pipe
;
3491 /* Create thread to manage the client socket */
3492 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3493 thread_manage_health
, (void *) NULL
);
3496 PERROR("pthread_create health");
3498 goto exit_health_thread
;
3501 /* Setup the dispatcher thread */
3502 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3503 relay_thread_dispatcher
, (void *) NULL
);
3506 PERROR("pthread_create dispatcher");
3508 goto exit_dispatcher_thread
;
3511 /* Setup the worker thread */
3512 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3513 relay_thread_worker
, NULL
);
3516 PERROR("pthread_create worker");
3518 goto exit_worker_thread
;
3521 /* Setup the listener thread */
3522 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3523 relay_thread_listener
, (void *) NULL
);
3526 PERROR("pthread_create listener");
3528 goto exit_listener_thread
;
3531 ret
= relayd_live_create(live_uri
);
3533 ERR("Starting live viewer threads");
3539 * This is where we start awaiting program completion (e.g. through
3540 * signal that asks threads to teardown).
3543 ret
= relayd_live_join();
3549 ret
= pthread_join(listener_thread
, &status
);
3552 PERROR("pthread_join listener_thread");
3556 exit_listener_thread
:
3557 ret
= pthread_join(worker_thread
, &status
);
3560 PERROR("pthread_join worker_thread");
3565 ret
= pthread_join(dispatcher_thread
, &status
);
3568 PERROR("pthread_join dispatcher_thread");
3571 exit_dispatcher_thread
:
3573 ret
= pthread_join(health_thread
, &status
);
3576 PERROR("pthread_join health_thread");
3581 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
3582 exit_health_quit_pipe
:
3585 health_app_destroy(health_relayd
);
3586 exit_health_app_create
:
3589 * Wait for all pending call_rcu work to complete before tearing
3590 * down data structures. call_rcu worker may be trying to
3591 * perform lookups in those structures.
3596 /* Ensure all prior call_rcu are done. */
3601 * fd_tracker_destroy() will log the contents of the fd-tracker
3602 * if a leak is detected.
3604 fd_tracker_destroy(the_fd_tracker
);
3605 rcu_unregister_thread();