2 * Copyright (C) 2012 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * SPDX-License-Identifier: GPL-2.0-only
21 #include <sys/mount.h>
22 #include <sys/resource.h>
23 #include <sys/socket.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
29 #include <urcu/futex.h>
30 #include <urcu/uatomic.h>
31 #include <urcu/rculist.h>
38 #include <lttng/lttng.h>
39 #include <common/common.h>
40 #include <common/compat/poll.h>
41 #include <common/compat/socket.h>
42 #include <common/compat/endian.h>
43 #include <common/compat/getenv.h>
44 #include <common/defaults.h>
45 #include <common/daemonize.h>
46 #include <common/futex.h>
47 #include <common/sessiond-comm/sessiond-comm.h>
48 #include <common/sessiond-comm/inet.h>
49 #include <common/sessiond-comm/relayd.h>
50 #include <common/uri.h>
51 #include <common/utils.h>
52 #include <common/align.h>
53 #include <common/ini-config/ini-config.h>
54 #include <common/dynamic-buffer.h>
55 #include <common/buffer-view.h>
56 #include <common/string-utils/format.h>
57 #include <common/fd-tracker/fd-tracker.h>
58 #include <common/fd-tracker/utils.h>
60 #include "backward-compatibility-group-by.h"
62 #include "connection.h"
63 #include "ctf-trace.h"
64 #include "health-relayd.h"
67 #include "lttng-relayd.h"
69 #include "sessiond-trace-chunks.h"
71 #include "tcp_keep_alive.h"
72 #include "testpoint.h"
73 #include "tracefile-array.h"
76 #include "viewer-stream.h"
78 static const char *help_msg
=
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
86 enum relay_connection_status
{
87 RELAY_CONNECTION_STATUS_OK
,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR
,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED
,
94 /* command line options */
95 char *opt_output_path
, *opt_working_directory
;
96 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
97 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
99 /* Argument variables */
100 int lttng_opt_quiet
; /* not static in error.h */
101 int lttng_opt_verbose
; /* not static in error.h */
102 int lttng_opt_mi
; /* not static in error.h */
105 * We need to wait for listener and live listener threads, as well as
106 * health check thread, before being ready to signal readiness.
108 #define NR_LTTNG_RELAY_READY 3
109 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
111 /* Size of receive buffer. */
112 #define RECV_DATA_BUFFER_SIZE 65536
114 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
115 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
117 static struct lttng_uri
*control_uri
;
118 static struct lttng_uri
*data_uri
;
119 static struct lttng_uri
*live_uri
;
121 const char *progname
;
123 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
124 static int tracing_group_name_override
;
126 const char * const config_section_name
= "relayd";
129 * Quit pipe for all threads. This permits a single cancellation point
130 * for all threads when receiving an event on the pipe.
132 int thread_quit_pipe
[2] = { -1, -1 };
135 * This pipe is used to inform the worker thread that a command is queued and
136 * ready to be processed.
138 static int relay_conn_pipe
[2] = { -1, -1 };
140 /* Shared between threads */
141 static int dispatch_thread_exit
;
143 static pthread_t listener_thread
;
144 static pthread_t dispatcher_thread
;
145 static pthread_t worker_thread
;
146 static pthread_t health_thread
;
149 * last_relay_stream_id_lock protects last_relay_stream_id increment
150 * atomicity on 32-bit architectures.
152 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
153 static uint64_t last_relay_stream_id
;
156 * Relay command queue.
158 * The relay_thread_listener and relay_thread_dispatcher communicate with this
161 static struct relay_conn_queue relay_conn_queue
;
163 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
164 static unsigned int lttng_opt_fd_pool_size
= -1;
166 /* Global relay stream hash table. */
167 struct lttng_ht
*relay_streams_ht
;
169 /* Global relay viewer stream hash table. */
170 struct lttng_ht
*viewer_streams_ht
;
172 /* Global relay sessions hash table. */
173 struct lttng_ht
*sessions_ht
;
175 /* Relayd health monitoring */
176 struct health_app
*health_relayd
;
178 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
180 /* Global fd tracker. */
181 struct fd_tracker
*the_fd_tracker
;
183 static struct option long_options
[] = {
184 { "control-port", 1, 0, 'C', },
185 { "data-port", 1, 0, 'D', },
186 { "live-port", 1, 0, 'L', },
187 { "daemonize", 0, 0, 'd', },
188 { "background", 0, 0, 'b', },
189 { "group", 1, 0, 'g', },
190 { "fd-pool-size", 1, 0, '\0', },
191 { "help", 0, 0, 'h', },
192 { "output", 1, 0, 'o', },
193 { "verbose", 0, 0, 'v', },
194 { "config", 1, 0, 'f' },
195 { "version", 0, 0, 'V' },
196 { "working-directory", 1, 0, 'w', },
197 { "group-output-by-session", 0, 0, 's', },
198 { "group-output-by-host", 0, 0, 'p', },
199 { "disallow-clear", 0, 0, 'x' },
203 static const char *config_ignore_options
[] = { "help", "config", "version" };
205 static void print_version(void) {
206 fprintf(stdout
, "%s\n", VERSION
);
209 static void relayd_config_log(void)
211 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
212 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
213 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
214 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
215 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
217 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
218 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
223 * Take an option from the getopt output and set it in the right variable to be
226 * Return 0 on success else a negative value.
228 static int set_option(int opt
, const char *arg
, const char *optname
)
234 if (!strcmp(optname
, "fd-pool-size")) {
238 v
= strtoul(arg
, NULL
, 0);
239 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
240 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
245 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
249 lttng_opt_fd_pool_size
= (unsigned int) v
;
251 fprintf(stderr
, "unknown option %s", optname
);
253 fprintf(stderr
, " with arg %s\n", arg
);
258 if (lttng_is_setuid_setgid()) {
259 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
260 "-C, --control-port");
262 ret
= uri_parse(arg
, &control_uri
);
264 ERR("Invalid control URI specified");
267 if (control_uri
->port
== 0) {
268 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
273 if (lttng_is_setuid_setgid()) {
274 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
277 ret
= uri_parse(arg
, &data_uri
);
279 ERR("Invalid data URI specified");
282 if (data_uri
->port
== 0) {
283 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
288 if (lttng_is_setuid_setgid()) {
289 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
292 ret
= uri_parse(arg
, &live_uri
);
294 ERR("Invalid live URI specified");
297 if (live_uri
->port
== 0) {
298 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
309 if (lttng_is_setuid_setgid()) {
310 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
313 tracing_group_name
= strdup(arg
);
314 if (tracing_group_name
== NULL
) {
319 tracing_group_name_override
= 1;
323 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
325 ERR("Cannot show --help for `lttng-relayd`");
330 opt_print_version
= 1;
333 if (lttng_is_setuid_setgid()) {
334 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
337 ret
= asprintf(&opt_output_path
, "%s", arg
);
340 PERROR("asprintf opt_output_path");
346 if (lttng_is_setuid_setgid()) {
347 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
348 "-w, --working-directory");
350 ret
= asprintf(&opt_working_directory
, "%s", arg
);
353 PERROR("asprintf opt_working_directory");
360 /* Verbose level can increase using multiple -v */
362 lttng_opt_verbose
= config_parse_value(arg
);
364 /* Only 3 level of verbosity (-vvv). */
365 if (lttng_opt_verbose
< 3) {
366 lttng_opt_verbose
+= 1;
371 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
372 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
375 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
378 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
379 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
382 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
389 /* Unknown option or other error.
390 * Error is printed by getopt, just return */
403 * config_entry_handler_cb used to handle options read from a config file.
404 * See config_entry_handler_cb comment in common/config/session-config.h for the
405 * return value conventions.
407 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
411 if (!entry
|| !entry
->name
|| !entry
->value
) {
416 /* Check if the option is to be ignored */
417 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
418 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
423 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
424 /* Ignore if entry name is not fully matched. */
425 if (strcmp(entry
->name
, long_options
[i
].name
)) {
430 * If the option takes no argument on the command line,
431 * we have to check if the value is "true". We support
432 * non-zero numeric values, true, on and yes.
434 if (!long_options
[i
].has_arg
) {
435 ret
= config_parse_value(entry
->value
);
438 WARN("Invalid configuration value \"%s\" for option %s",
439 entry
->value
, entry
->name
);
441 /* False, skip boolean config option. */
446 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
450 WARN("Unrecognized option \"%s\" in daemon configuration file.",
457 static int parse_env_options(void)
462 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
464 opt_working_directory
= strdup(value
);
465 if (!opt_working_directory
) {
466 ERR("Failed to allocate working directory string (\"%s\")",
474 static int set_fd_pool_size(void)
477 struct rlimit rlimit
;
479 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
481 PERROR("Failed to get file descriptor limit");
486 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
487 (uint64_t) rlimit
.rlim_cur
,
488 (uint64_t) rlimit
.rlim_max
);
489 if (lttng_opt_fd_pool_size
== -1) {
490 /* Use default value (soft limit - reserve). */
491 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
492 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
493 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
497 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
498 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
502 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
503 ERR("File descriptor pool size must be set to at least %d",
504 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
509 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
510 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
511 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
516 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
517 lttng_opt_fd_pool_size
,
518 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
519 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
524 static int set_options(int argc
, char **argv
)
526 int c
, ret
= 0, option_index
= 0, retval
= 0;
527 int orig_optopt
= optopt
, orig_optind
= optind
;
528 char *default_address
, *optstring
;
529 char *config_path
= NULL
;
531 optstring
= utils_generate_optstring(long_options
,
532 sizeof(long_options
) / sizeof(struct option
));
538 /* Check for the --config option */
540 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
541 &option_index
)) != -1) {
545 } else if (c
!= 'f') {
549 if (lttng_is_setuid_setgid()) {
550 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
554 config_path
= utils_expand_path(optarg
);
556 ERR("Failed to resolve path: %s", optarg
);
561 ret
= config_get_section_entries(config_path
, config_section_name
,
562 config_entry_handler
, NULL
);
565 ERR("Invalid configuration option at line %i", ret
);
571 /* Reset getopt's global state */
572 optopt
= orig_optopt
;
573 optind
= orig_optind
;
575 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
580 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
587 /* assign default values */
588 if (control_uri
== NULL
) {
589 ret
= asprintf(&default_address
,
590 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
591 DEFAULT_NETWORK_CONTROL_PORT
);
593 PERROR("asprintf default data address");
598 ret
= uri_parse(default_address
, &control_uri
);
599 free(default_address
);
601 ERR("Invalid control URI specified");
606 if (data_uri
== NULL
) {
607 ret
= asprintf(&default_address
,
608 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
609 DEFAULT_NETWORK_DATA_PORT
);
611 PERROR("asprintf default data address");
616 ret
= uri_parse(default_address
, &data_uri
);
617 free(default_address
);
619 ERR("Invalid data URI specified");
624 if (live_uri
== NULL
) {
625 ret
= asprintf(&default_address
,
626 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
627 DEFAULT_NETWORK_VIEWER_PORT
);
629 PERROR("asprintf default viewer control address");
634 ret
= uri_parse(default_address
, &live_uri
);
635 free(default_address
);
637 ERR("Invalid viewer control URI specified");
642 ret
= set_fd_pool_size();
648 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
649 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
651 if (opt_allow_clear
) {
652 /* Check if env variable exists. */
653 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
655 ret
= config_parse_value(value
);
657 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
661 opt_allow_clear
= !ret
;
671 static void print_global_objects(void)
673 print_viewer_streams();
674 print_relay_streams();
678 static int noop_close(void *data
, int *fds
)
683 static void untrack_stdio(void)
685 int fds
[] = { fileno(stdout
), fileno(stderr
) };
688 * noop_close is used since we don't really want to close
689 * the stdio output fds; we merely want to stop tracking them.
691 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
692 fds
, 2, noop_close
, NULL
);
698 static void relayd_cleanup(void)
700 print_global_objects();
704 if (viewer_streams_ht
)
705 lttng_ht_destroy(viewer_streams_ht
);
706 if (relay_streams_ht
)
707 lttng_ht_destroy(relay_streams_ht
);
709 lttng_ht_destroy(sessions_ht
);
711 free(opt_output_path
);
712 free(opt_working_directory
);
715 health_app_destroy(health_relayd
);
717 /* Close thread quit pipes */
718 if (health_quit_pipe
[0] != -1) {
719 (void) fd_tracker_util_pipe_close(
720 the_fd_tracker
, health_quit_pipe
);
722 if (thread_quit_pipe
[0] != -1) {
723 (void) fd_tracker_util_pipe_close(
724 the_fd_tracker
, thread_quit_pipe
);
726 if (sessiond_trace_chunk_registry
) {
727 sessiond_trace_chunk_registry_destroy(
728 sessiond_trace_chunk_registry
);
730 if (the_fd_tracker
) {
733 * fd_tracker_destroy() will log the contents of the fd-tracker
734 * if a leak is detected.
736 fd_tracker_destroy(the_fd_tracker
);
739 uri_free(control_uri
);
741 /* Live URI is freed in the live thread. */
743 if (tracing_group_name_override
) {
744 free((void *) tracing_group_name
);
749 * Write to writable pipe used to notify a thread.
751 static int notify_thread_pipe(int wpipe
)
755 ret
= lttng_write(wpipe
, "!", 1);
757 PERROR("write poll pipe");
765 static int notify_health_quit_pipe(int *pipe
)
769 ret
= lttng_write(pipe
[1], "4", 1);
771 PERROR("write relay health quit");
780 * Stop all relayd and relayd-live threads.
782 int lttng_relay_stop_threads(void)
786 /* Stopping all threads */
787 DBG("Terminating all threads");
788 if (notify_thread_pipe(thread_quit_pipe
[1])) {
789 ERR("write error on thread quit pipe");
793 if (notify_health_quit_pipe(health_quit_pipe
)) {
794 ERR("write error on health quit pipe");
797 /* Dispatch thread */
798 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
799 futex_nto1_wake(&relay_conn_queue
.futex
);
801 if (relayd_live_stop()) {
802 ERR("Error stopping live threads");
809 * Signal handler for the daemon
811 * Simply stop all worker threads, leaving main() return gracefully after
812 * joining all threads and calling cleanup().
814 static void sighandler(int sig
)
818 DBG("SIGINT caught");
819 if (lttng_relay_stop_threads()) {
820 ERR("Error stopping threads");
824 DBG("SIGTERM caught");
825 if (lttng_relay_stop_threads()) {
826 ERR("Error stopping threads");
830 CMM_STORE_SHARED(recv_child_signal
, 1);
838 * Setup signal handler for :
839 * SIGINT, SIGTERM, SIGPIPE
841 static int set_signal_handler(void)
847 if ((ret
= sigemptyset(&sigset
)) < 0) {
848 PERROR("sigemptyset");
855 sa
.sa_handler
= sighandler
;
856 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
861 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
866 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
871 sa
.sa_handler
= SIG_IGN
;
872 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
877 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
882 void lttng_relay_notify_ready(void)
884 /* Notify the parent of the fork() process that we are ready. */
885 if (opt_daemon
|| opt_background
) {
886 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
887 kill(child_ppid
, SIGUSR1
);
893 * Init thread quit pipe.
895 * Return -1 on error or 0 if all pipes are created.
897 static int init_thread_quit_pipe(void)
899 return fd_tracker_util_pipe_open_cloexec(
900 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
904 * Init health quit pipe.
906 * Return -1 on error or 0 if all pipes are created.
908 static int init_health_quit_pipe(void)
910 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
911 "Health quit pipe", health_quit_pipe
);
915 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
917 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
918 int size
, const char *name
)
922 if (events
== NULL
|| size
== 0) {
927 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
928 name
, events
, 1, LTTNG_CLOEXEC
);
930 PERROR("Failed to create \"%s\" poll file descriptor", name
);
935 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
947 * Check if the thread quit pipe was triggered.
949 * Return 1 if it was triggered else 0;
951 static int check_thread_quit_pipe(int fd
, uint32_t events
)
953 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
960 static int create_sock(void *data
, int *out_fd
)
963 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
965 ret
= lttcomm_create_sock(sock
);
975 static int close_sock(void *data
, int *in_fd
)
977 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
979 return sock
->ops
->close(sock
);
982 static int accept_sock(void *data
, int *out_fd
)
985 /* Socks is an array of in_sock, out_sock. */
986 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
987 struct lttcomm_sock
*in_sock
= socks
[0];
989 socks
[1] = in_sock
->ops
->accept(in_sock
);
994 *out_fd
= socks
[1]->fd
;
1000 * Create and init socket from uri.
1002 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
1006 struct lttcomm_sock
*sock
= NULL
;
1007 char uri_str
[PATH_MAX
];
1008 char *formated_name
= NULL
;
1010 sock
= lttcomm_alloc_sock_from_uri(uri
);
1012 ERR("Allocating socket");
1017 * Don't fail to create the socket if the name can't be built as it is
1018 * only used for debugging purposes.
1020 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1021 uri_str
[sizeof(uri_str
) - 1] = '\0';
1023 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1026 formated_name
= NULL
;
1030 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1031 (const char **) (formated_name
? &formated_name
: NULL
),
1032 1, create_sock
, sock
);
1034 PERROR("Failed to open \"%s\" relay socket",
1035 formated_name
?: "Unknown");
1038 DBG("Listening on %s socket %d", name
, sock
->fd
);
1040 ret
= sock
->ops
->bind(sock
);
1042 PERROR("Failed to bind socket");
1046 ret
= sock
->ops
->listen(sock
, -1);
1052 free(formated_name
);
1057 lttcomm_destroy_sock(sock
);
1059 free(formated_name
);
1064 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1068 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1069 struct lttcomm_sock
*new_sock
= NULL
;
1071 ret
= fd_tracker_open_unsuspendable_fd(
1072 the_fd_tracker
, &out_fd
,
1073 (const char **) &name
,
1074 1, accept_sock
, &socks
);
1078 new_sock
= socks
[1];
1079 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1085 * This thread manages the listening for new connections on the network
1087 static void *relay_thread_listener(void *data
)
1089 int i
, ret
, pollfd
, err
= -1;
1090 uint32_t revents
, nb_fd
;
1091 struct lttng_poll_event events
;
1092 struct lttcomm_sock
*control_sock
, *data_sock
;
1094 DBG("[thread] Relay listener started");
1096 rcu_register_thread();
1097 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1099 health_code_update();
1101 control_sock
= relay_socket_create(control_uri
, "Control listener");
1102 if (!control_sock
) {
1103 goto error_sock_control
;
1106 data_sock
= relay_socket_create(data_uri
, "Data listener");
1108 goto error_sock_relay
;
1112 * Pass 3 as size here for the thread quit pipe, control and
1115 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1117 goto error_create_poll
;
1120 /* Add the control socket */
1121 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1123 goto error_poll_add
;
1126 /* Add the data socket */
1127 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1129 goto error_poll_add
;
1132 lttng_relay_notify_ready();
1134 if (testpoint(relayd_thread_listener
)) {
1135 goto error_testpoint
;
1139 health_code_update();
1141 DBG("Listener accepting connections");
1144 health_poll_entry();
1145 ret
= lttng_poll_wait(&events
, -1);
1149 * Restart interrupted system call.
1151 if (errno
== EINTR
) {
1159 DBG("Relay new connection received");
1160 for (i
= 0; i
< nb_fd
; i
++) {
1161 health_code_update();
1163 /* Fetch once the poll data */
1164 revents
= LTTNG_POLL_GETEV(&events
, i
);
1165 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1167 /* Thread quit pipe has been closed. Killing thread. */
1168 ret
= check_thread_quit_pipe(pollfd
, revents
);
1174 if (revents
& LPOLLIN
) {
1176 * A new connection is requested, therefore a
1177 * sessiond/consumerd connection is allocated in
1178 * this thread, enqueued to a global queue and
1179 * dequeued (and freed) in the worker thread.
1182 struct relay_connection
*new_conn
;
1183 struct lttcomm_sock
*newsock
= NULL
;
1184 enum connection_type type
;
1186 if (pollfd
== data_sock
->fd
) {
1188 newsock
= accept_relayd_sock(data_sock
,
1189 "Data socket to relayd");
1191 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1192 type
= RELAY_CONTROL
;
1193 newsock
= accept_relayd_sock(control_sock
,
1194 "Control socket to relayd");
1197 PERROR("accepting sock");
1201 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1204 PERROR("setsockopt inet");
1205 lttcomm_destroy_sock(newsock
);
1209 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1211 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1213 lttcomm_destroy_sock(newsock
);
1217 new_conn
= connection_create(newsock
, type
);
1219 lttcomm_destroy_sock(newsock
);
1223 /* Enqueue request for the dispatcher thread. */
1224 cds_wfcq_head_ptr_t head
;
1225 head
.h
= &relay_conn_queue
.head
;
1226 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
,
1230 * Wake the dispatch queue futex.
1231 * Implicit memory barrier with the
1232 * exchange in cds_wfcq_enqueue.
1234 futex_nto1_wake(&relay_conn_queue
.futex
);
1235 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1236 ERR("socket poll error");
1239 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1249 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1251 if (data_sock
->fd
>= 0) {
1252 int data_sock_fd
= data_sock
->fd
;
1254 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1255 &data_sock_fd
, 1, close_sock
,
1258 PERROR("Failed to close the data listener socket file descriptor");
1262 lttcomm_destroy_sock(data_sock
);
1264 if (control_sock
->fd
>= 0) {
1265 int control_sock_fd
= control_sock
->fd
;
1267 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1268 &control_sock_fd
, 1, close_sock
,
1271 PERROR("Failed to close the control listener socket file descriptor");
1273 control_sock
->fd
= -1;
1275 lttcomm_destroy_sock(control_sock
);
1279 ERR("Health error occurred in %s", __func__
);
1281 health_unregister(health_relayd
);
1282 rcu_unregister_thread();
1283 DBG("Relay listener thread cleanup complete");
1284 lttng_relay_stop_threads();
1289 * This thread manages the dispatching of the requests to worker threads
1291 static void *relay_thread_dispatcher(void *data
)
1295 struct cds_wfcq_node
*node
;
1296 struct relay_connection
*new_conn
= NULL
;
1298 DBG("[thread] Relay dispatcher started");
1300 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1302 if (testpoint(relayd_thread_dispatcher
)) {
1303 goto error_testpoint
;
1306 health_code_update();
1309 health_code_update();
1311 /* Atomically prepare the queue futex */
1312 futex_nto1_prepare(&relay_conn_queue
.futex
);
1314 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1319 health_code_update();
1321 /* Dequeue commands */
1322 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1323 &relay_conn_queue
.tail
);
1325 DBG("Woken up but nothing in the relay command queue");
1326 /* Continue thread execution */
1329 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1331 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1334 * Inform worker thread of the new request. This
1335 * call is blocking so we can be assured that
1336 * the data will be read at some point in time
1337 * or wait to the end of the world :)
1339 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1341 PERROR("write connection pipe");
1342 connection_put(new_conn
);
1345 } while (node
!= NULL
);
1347 /* Futex wait on queue. Blocking call on futex() */
1348 health_poll_entry();
1349 futex_nto1_wait(&relay_conn_queue
.futex
);
1353 /* Normal exit, no error */
1360 ERR("Health error occurred in %s", __func__
);
1362 health_unregister(health_relayd
);
1363 DBG("Dispatch thread dying");
1364 lttng_relay_stop_threads();
1368 static bool session_streams_have_index(const struct relay_session
*session
)
1370 return session
->minor
>= 4 && !session
->snapshot
;
1374 * Handle the RELAYD_CREATE_SESSION command.
1376 * On success, send back the session id or else return a negative value.
1378 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1379 struct relay_connection
*conn
,
1380 const struct lttng_buffer_view
*payload
)
1384 struct relay_session
*session
= NULL
;
1385 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1386 char session_name
[LTTNG_NAME_MAX
] = {};
1387 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1388 uint32_t live_timer
= 0;
1389 bool snapshot
= false;
1390 bool session_name_contains_creation_timestamp
= false;
1391 /* Left nil for peers < 2.11. */
1392 char base_path
[LTTNG_PATH_MAX
] = {};
1393 lttng_uuid sessiond_uuid
= {};
1394 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1395 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1396 LTTNG_OPTIONAL(time_t) creation_time
= {};
1397 struct lttng_dynamic_buffer reply_payload
;
1399 lttng_dynamic_buffer_init(&reply_payload
);
1401 if (conn
->minor
< 4) {
1402 /* From 2.1 to 2.3 */
1404 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1405 /* From 2.4 to 2.10 */
1406 ret
= cmd_create_session_2_4(payload
, session_name
,
1407 hostname
, &live_timer
, &snapshot
);
1409 bool has_current_chunk
;
1410 uint64_t current_chunk_id_value
;
1411 time_t creation_time_value
;
1412 uint64_t id_sessiond_value
;
1414 /* From 2.11 to ... */
1415 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1416 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1417 sessiond_uuid
, &has_current_chunk
,
1418 ¤t_chunk_id_value
, &creation_time_value
,
1419 &session_name_contains_creation_timestamp
);
1420 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1421 /* The nil UUID is reserved for pre-2.11 clients. */
1422 ERR("Illegal nil UUID announced by peer in create session command");
1426 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1427 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1428 if (has_current_chunk
) {
1429 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1430 current_chunk_id_value
);
1438 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1439 snapshot
, sessiond_uuid
,
1440 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1441 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1442 creation_time
.is_set
? &creation_time
.value
: NULL
,
1443 conn
->major
, conn
->minor
,
1444 session_name_contains_creation_timestamp
);
1449 LTTNG_ASSERT(!conn
->session
);
1450 conn
->session
= session
;
1451 DBG("Created session %" PRIu64
, session
->id
);
1453 reply
.generic
.session_id
= htobe64(session
->id
);
1457 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1459 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1462 if (conn
->minor
< 11) {
1463 /* From 2.1 to 2.10 */
1464 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1465 &reply
.generic
, sizeof(reply
.generic
));
1467 ERR("Failed to append \"create session\" command reply header to payload buffer");
1472 const uint32_t output_path_length
=
1473 session
? strlen(session
->output_path
) + 1 : 0;
1475 reply
.output_path_length
= htobe32(output_path_length
);
1476 ret
= lttng_dynamic_buffer_append(
1477 &reply_payload
, &reply
, sizeof(reply
));
1479 ERR("Failed to append \"create session\" command reply header to payload buffer");
1483 if (output_path_length
) {
1484 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1485 session
->output_path
,
1486 output_path_length
);
1488 ERR("Failed to append \"create session\" command reply path to payload buffer");
1494 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1495 reply_payload
.size
, 0);
1496 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1497 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1498 reply_payload
.size
, send_ret
);
1502 if (ret
< 0 && session
) {
1503 session_put(session
);
1505 lttng_dynamic_buffer_reset(&reply_payload
);
1510 * When we have received all the streams and the metadata for a channel,
1511 * we make them visible to the viewer threads.
1513 static void publish_connection_local_streams(struct relay_connection
*conn
)
1515 struct relay_stream
*stream
;
1516 struct relay_session
*session
= conn
->session
;
1519 * We publish all streams belonging to a session atomically wrt
1522 pthread_mutex_lock(&session
->lock
);
1524 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1526 stream_publish(stream
);
1531 * Inform the viewer that there are new streams in the session.
1533 if (session
->viewer_attached
) {
1534 uatomic_set(&session
->new_streams
, 1);
1536 pthread_mutex_unlock(&session
->lock
);
1539 static int conform_channel_path(char *channel_path
)
1543 if (strstr("../", channel_path
)) {
1544 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1550 if (*channel_path
== '/') {
1551 const size_t len
= strlen(channel_path
);
1554 * Channel paths from peers prior to 2.11 are expressed as an
1555 * absolute path that is, in reality, relative to the relay
1556 * daemon's output directory. Remove the leading slash so it
1557 * is correctly interpreted as a relative path later on.
1559 * len (and not len - 1) is used to copy the trailing NULL.
1561 bcopy(channel_path
+ 1, channel_path
, len
);
1568 * relay_add_stream: allocate a new stream for a session
1570 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1571 struct relay_connection
*conn
,
1572 const struct lttng_buffer_view
*payload
)
1576 struct relay_session
*session
= conn
->session
;
1577 struct relay_stream
*stream
= NULL
;
1578 struct lttcomm_relayd_status_stream reply
;
1579 struct ctf_trace
*trace
= NULL
;
1580 uint64_t stream_handle
= -1ULL;
1581 char *path_name
= NULL
, *channel_name
= NULL
;
1582 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1583 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1585 if (!session
|| !conn
->version_check_done
) {
1586 ERR("Trying to add a stream before version check");
1588 goto end_no_session
;
1591 if (session
->minor
== 1) {
1593 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1595 } else if (session
->minor
> 1 && session
->minor
< 11) {
1596 /* From 2.2 to 2.10 */
1597 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1598 &channel_name
, &tracefile_size
, &tracefile_count
);
1600 /* From 2.11 to ... */
1601 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1602 &channel_name
, &tracefile_size
, &tracefile_count
,
1603 &stream_chunk_id
.value
);
1604 stream_chunk_id
.is_set
= true;
1611 if (conform_channel_path(path_name
)) {
1616 * Backward compatibility for --group-output-by-session.
1617 * Prior to lttng 2.11, the complete path is passed by the stream.
1618 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1619 * >=2.11 the chunk is responsible for the output path. When dealing
1620 * with producer < 2.11 the chunk output_path is the root output path
1621 * and the stream carries the complete path (path_name).
1622 * To support --group-output-by-session with older producer (<2.11), we
1623 * need to craft the path based on the stream path.
1625 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1626 if (conn
->minor
< 4) {
1628 * From 2.1 to 2.3, the session_name is not passed on
1629 * the RELAYD_CREATE_SESSION command. The session name
1630 * is necessary to detect the presence of a base_path
1631 * inside the stream path. Without it we cannot perform
1632 * a valid group-output-by-session transformation.
1634 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1635 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1636 session
->id
, path_name
);
1637 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1638 char *group_by_session_path_name
;
1640 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1642 group_by_session_path_name
=
1643 backward_compat_group_by_session(
1645 session
->session_name
,
1646 session
->creation_time
.value
);
1647 if (!group_by_session_path_name
) {
1648 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1653 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1654 path_name
, group_by_session_path_name
);
1657 path_name
= group_by_session_path_name
;
1661 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1666 /* This stream here has one reference on the trace. */
1667 pthread_mutex_lock(&last_relay_stream_id_lock
);
1668 stream_handle
= ++last_relay_stream_id
;
1669 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1671 /* We pass ownership of path_name and channel_name. */
1672 stream
= stream_create(trace
, stream_handle
, path_name
,
1673 channel_name
, tracefile_size
, tracefile_count
);
1675 channel_name
= NULL
;
1678 * Streams are the owners of their trace. Reference to trace is
1679 * kept within stream_create().
1681 ctf_trace_put(trace
);
1684 memset(&reply
, 0, sizeof(reply
));
1685 reply
.handle
= htobe64(stream_handle
);
1687 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1689 reply
.ret_code
= htobe32(LTTNG_OK
);
1692 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1693 sizeof(struct lttcomm_relayd_status_stream
), 0);
1694 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1695 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1707 * relay_close_stream: close a specific stream
1709 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1710 struct relay_connection
*conn
,
1711 const struct lttng_buffer_view
*payload
)
1715 struct relay_session
*session
= conn
->session
;
1716 struct lttcomm_relayd_close_stream stream_info
;
1717 struct lttcomm_relayd_generic_reply reply
;
1718 struct relay_stream
*stream
;
1720 DBG("Close stream received");
1722 if (!session
|| !conn
->version_check_done
) {
1723 ERR("Trying to close a stream before version check");
1725 goto end_no_session
;
1728 if (payload
->size
< sizeof(stream_info
)) {
1729 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1730 sizeof(stream_info
), payload
->size
);
1732 goto end_no_session
;
1734 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1735 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1736 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1738 stream
= stream_get_by_id(stream_info
.stream_id
);
1745 * Set last_net_seq_num before the close flag. Required by data
1748 pthread_mutex_lock(&stream
->lock
);
1749 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1750 pthread_mutex_unlock(&stream
->lock
);
1753 * This is one of the conditions which may trigger a stream close
1754 * with the others being:
1755 * 1) A close command is received for a stream
1756 * 2) The control connection owning the stream is closed
1757 * 3) We have received all of the stream's data _after_ a close
1760 try_stream_close(stream
);
1761 if (stream
->is_metadata
) {
1762 struct relay_viewer_stream
*vstream
;
1764 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1766 if (stream
->no_new_metadata_notified
) {
1768 * Since all the metadata has been sent to the
1769 * viewer and that we have a request to close
1770 * its stream, we can safely teardown the
1771 * corresponding metadata viewer stream.
1773 viewer_stream_put(vstream
);
1775 /* Put local reference. */
1776 viewer_stream_put(vstream
);
1783 memset(&reply
, 0, sizeof(reply
));
1785 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1787 reply
.ret_code
= htobe32(LTTNG_OK
);
1789 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1790 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1791 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1792 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1802 * relay_reset_metadata: reset a metadata stream
1805 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1806 struct relay_connection
*conn
,
1807 const struct lttng_buffer_view
*payload
)
1811 struct relay_session
*session
= conn
->session
;
1812 struct lttcomm_relayd_reset_metadata stream_info
;
1813 struct lttcomm_relayd_generic_reply reply
;
1814 struct relay_stream
*stream
;
1816 DBG("Reset metadata received");
1818 if (!session
|| !conn
->version_check_done
) {
1819 ERR("Trying to reset a metadata stream before version check");
1821 goto end_no_session
;
1824 if (payload
->size
< sizeof(stream_info
)) {
1825 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1826 sizeof(stream_info
), payload
->size
);
1828 goto end_no_session
;
1830 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1831 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1832 stream_info
.version
= be64toh(stream_info
.version
);
1834 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1836 /* Unsupported for live sessions for now. */
1837 if (session
->live_timer
!= 0) {
1842 stream
= stream_get_by_id(stream_info
.stream_id
);
1847 pthread_mutex_lock(&stream
->lock
);
1848 if (!stream
->is_metadata
) {
1853 ret
= stream_reset_file(stream
);
1855 ERR("Failed to reset metadata stream %" PRIu64
1856 ": stream_path = %s, channel = %s",
1857 stream
->stream_handle
, stream
->path_name
,
1858 stream
->channel_name
);
1862 pthread_mutex_unlock(&stream
->lock
);
1866 memset(&reply
, 0, sizeof(reply
));
1868 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1870 reply
.ret_code
= htobe32(LTTNG_OK
);
1872 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1873 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1874 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1875 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1885 * relay_unknown_command: send -1 if received unknown command
1887 static void relay_unknown_command(struct relay_connection
*conn
)
1889 struct lttcomm_relayd_generic_reply reply
;
1892 memset(&reply
, 0, sizeof(reply
));
1893 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1894 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1895 if (send_ret
< sizeof(reply
)) {
1896 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1901 * relay_start: send an acknowledgment to the client to tell if we are
1902 * ready to receive data. We are ready if a session is established.
1904 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1905 struct relay_connection
*conn
,
1906 const struct lttng_buffer_view
*payload
)
1910 struct lttcomm_relayd_generic_reply reply
;
1911 struct relay_session
*session
= conn
->session
;
1914 DBG("Trying to start the streaming without a session established");
1915 ret
= htobe32(LTTNG_ERR_UNK
);
1918 memset(&reply
, 0, sizeof(reply
));
1919 reply
.ret_code
= htobe32(LTTNG_OK
);
1920 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1922 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1923 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1932 * relay_recv_metadata: receive the metadata for the session.
1934 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1935 struct relay_connection
*conn
,
1936 const struct lttng_buffer_view
*payload
)
1939 struct relay_session
*session
= conn
->session
;
1940 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1941 struct relay_stream
*metadata_stream
;
1942 uint64_t metadata_payload_size
;
1943 struct lttng_buffer_view packet_view
;
1946 ERR("Metadata sent before version check");
1951 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1952 ERR("Incorrect data size");
1956 metadata_payload_size
= recv_hdr
->data_size
-
1957 sizeof(struct lttcomm_relayd_metadata_payload
);
1959 memcpy(&metadata_payload_header
, payload
->data
,
1960 sizeof(metadata_payload_header
));
1961 metadata_payload_header
.stream_id
= be64toh(
1962 metadata_payload_header
.stream_id
);
1963 metadata_payload_header
.padding_size
= be32toh(
1964 metadata_payload_header
.padding_size
);
1966 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1967 if (!metadata_stream
) {
1972 packet_view
= lttng_buffer_view_from_view(payload
,
1973 sizeof(metadata_payload_header
), metadata_payload_size
);
1974 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1975 ERR("Invalid metadata packet length announced by header");
1980 pthread_mutex_lock(&metadata_stream
->lock
);
1981 ret
= stream_write(metadata_stream
, &packet_view
,
1982 metadata_payload_header
.padding_size
);
1983 pthread_mutex_unlock(&metadata_stream
->lock
);
1989 stream_put(metadata_stream
);
1995 * relay_send_version: send relayd version number
1997 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1998 struct relay_connection
*conn
,
1999 const struct lttng_buffer_view
*payload
)
2003 struct lttcomm_relayd_version reply
, msg
;
2004 bool compatible
= true;
2006 conn
->version_check_done
= true;
2008 /* Get version from the other side. */
2009 if (payload
->size
< sizeof(msg
)) {
2010 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2011 sizeof(msg
), payload
->size
);
2016 memcpy(&msg
, payload
->data
, sizeof(msg
));
2017 msg
.major
= be32toh(msg
.major
);
2018 msg
.minor
= be32toh(msg
.minor
);
2020 memset(&reply
, 0, sizeof(reply
));
2021 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2022 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2024 /* Major versions must be the same */
2025 if (reply
.major
!= msg
.major
) {
2026 DBG("Incompatible major versions (%u vs %u), deleting session",
2027 reply
.major
, msg
.major
);
2031 conn
->major
= reply
.major
;
2032 /* We adapt to the lowest compatible version */
2033 if (reply
.minor
<= msg
.minor
) {
2034 conn
->minor
= reply
.minor
;
2036 conn
->minor
= msg
.minor
;
2039 reply
.major
= htobe32(reply
.major
);
2040 reply
.minor
= htobe32(reply
.minor
);
2041 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2043 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2044 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2057 DBG("Version check done using protocol %u.%u", conn
->major
,
2065 * Check for data pending for a given stream id from the session daemon.
2067 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2068 struct relay_connection
*conn
,
2069 const struct lttng_buffer_view
*payload
)
2071 struct relay_session
*session
= conn
->session
;
2072 struct lttcomm_relayd_data_pending msg
;
2073 struct lttcomm_relayd_generic_reply reply
;
2074 struct relay_stream
*stream
;
2077 uint64_t stream_seq
;
2079 DBG("Data pending command received");
2081 if (!session
|| !conn
->version_check_done
) {
2082 ERR("Trying to check for data before version check");
2084 goto end_no_session
;
2087 if (payload
->size
< sizeof(msg
)) {
2088 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2089 sizeof(msg
), payload
->size
);
2091 goto end_no_session
;
2093 memcpy(&msg
, payload
->data
, sizeof(msg
));
2094 msg
.stream_id
= be64toh(msg
.stream_id
);
2095 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2097 stream
= stream_get_by_id(msg
.stream_id
);
2098 if (stream
== NULL
) {
2103 pthread_mutex_lock(&stream
->lock
);
2105 if (session_streams_have_index(session
)) {
2107 * Ensure that both the index and stream data have been
2108 * flushed up to the requested point.
2110 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2112 stream_seq
= stream
->prev_data_seq
;
2114 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2115 ", prev_index_seq %" PRIu64
2116 ", and last_seq %" PRIu64
, msg
.stream_id
,
2117 stream
->prev_data_seq
, stream
->prev_index_seq
,
2118 msg
.last_net_seq_num
);
2120 /* Avoid wrapping issue */
2121 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2122 /* Data has in fact been written and is NOT pending */
2125 /* Data still being streamed thus pending */
2129 stream
->data_pending_check_done
= true;
2130 pthread_mutex_unlock(&stream
->lock
);
2135 memset(&reply
, 0, sizeof(reply
));
2136 reply
.ret_code
= htobe32(ret
);
2137 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2138 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2139 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2149 * Wait for the control socket to reach a quiescent state.
2151 * Note that for now, when receiving this command from the session
2152 * daemon, this means that every subsequent commands or data received on
2153 * the control socket has been handled. So, this is why we simply return
2156 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2157 struct relay_connection
*conn
,
2158 const struct lttng_buffer_view
*payload
)
2162 struct relay_stream
*stream
;
2163 struct lttcomm_relayd_quiescent_control msg
;
2164 struct lttcomm_relayd_generic_reply reply
;
2166 DBG("Checking quiescent state on control socket");
2168 if (!conn
->session
|| !conn
->version_check_done
) {
2169 ERR("Trying to check for data before version check");
2171 goto end_no_session
;
2174 if (payload
->size
< sizeof(msg
)) {
2175 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2176 sizeof(msg
), payload
->size
);
2178 goto end_no_session
;
2180 memcpy(&msg
, payload
->data
, sizeof(msg
));
2181 msg
.stream_id
= be64toh(msg
.stream_id
);
2183 stream
= stream_get_by_id(msg
.stream_id
);
2187 pthread_mutex_lock(&stream
->lock
);
2188 stream
->data_pending_check_done
= true;
2189 pthread_mutex_unlock(&stream
->lock
);
2191 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2194 memset(&reply
, 0, sizeof(reply
));
2195 reply
.ret_code
= htobe32(LTTNG_OK
);
2196 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2197 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2198 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2210 * Initialize a data pending command. This means that a consumer is about
2211 * to ask for data pending for each stream it holds. Simply iterate over
2212 * all streams of a session and set the data_pending_check_done flag.
2214 * This command returns to the client a LTTNG_OK code.
2216 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2217 struct relay_connection
*conn
,
2218 const struct lttng_buffer_view
*payload
)
2222 struct lttng_ht_iter iter
;
2223 struct lttcomm_relayd_begin_data_pending msg
;
2224 struct lttcomm_relayd_generic_reply reply
;
2225 struct relay_stream
*stream
;
2227 LTTNG_ASSERT(recv_hdr
);
2230 DBG("Init streams for data pending");
2232 if (!conn
->session
|| !conn
->version_check_done
) {
2233 ERR("Trying to check for data before version check");
2235 goto end_no_session
;
2238 if (payload
->size
< sizeof(msg
)) {
2239 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2240 sizeof(msg
), payload
->size
);
2242 goto end_no_session
;
2244 memcpy(&msg
, payload
->data
, sizeof(msg
));
2245 msg
.session_id
= be64toh(msg
.session_id
);
2248 * Iterate over all streams to set the begin data pending flag.
2249 * For now, the streams are indexed by stream handle so we have
2250 * to iterate over all streams to find the one associated with
2251 * the right session_id.
2254 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2256 if (!stream_get(stream
)) {
2259 if (stream
->trace
->session
->id
== msg
.session_id
) {
2260 pthread_mutex_lock(&stream
->lock
);
2261 stream
->data_pending_check_done
= false;
2262 pthread_mutex_unlock(&stream
->lock
);
2263 DBG("Set begin data pending flag to stream %" PRIu64
,
2264 stream
->stream_handle
);
2270 memset(&reply
, 0, sizeof(reply
));
2271 /* All good, send back reply. */
2272 reply
.ret_code
= htobe32(LTTNG_OK
);
2274 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2275 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2276 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2288 * End data pending command. This will check, for a given session id, if
2289 * each stream associated with it has its data_pending_check_done flag
2290 * set. If not, this means that the client lost track of the stream but
2291 * the data is still being streamed on our side. In this case, we inform
2292 * the client that data is in flight.
2294 * Return to the client if there is data in flight or not with a ret_code.
2296 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2297 struct relay_connection
*conn
,
2298 const struct lttng_buffer_view
*payload
)
2302 struct lttng_ht_iter iter
;
2303 struct lttcomm_relayd_end_data_pending msg
;
2304 struct lttcomm_relayd_generic_reply reply
;
2305 struct relay_stream
*stream
;
2306 uint32_t is_data_inflight
= 0;
2308 DBG("End data pending command");
2310 if (!conn
->session
|| !conn
->version_check_done
) {
2311 ERR("Trying to check for data before version check");
2313 goto end_no_session
;
2316 if (payload
->size
< sizeof(msg
)) {
2317 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2318 sizeof(msg
), payload
->size
);
2320 goto end_no_session
;
2322 memcpy(&msg
, payload
->data
, sizeof(msg
));
2323 msg
.session_id
= be64toh(msg
.session_id
);
2326 * Iterate over all streams to see if the begin data pending
2330 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2332 if (!stream_get(stream
)) {
2335 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2339 pthread_mutex_lock(&stream
->lock
);
2340 if (!stream
->data_pending_check_done
) {
2341 uint64_t stream_seq
;
2343 if (session_streams_have_index(conn
->session
)) {
2345 * Ensure that both the index and stream data have been
2346 * flushed up to the requested point.
2348 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2350 stream_seq
= stream
->prev_data_seq
;
2352 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2353 is_data_inflight
= 1;
2354 DBG("Data is still in flight for stream %" PRIu64
,
2355 stream
->stream_handle
);
2356 pthread_mutex_unlock(&stream
->lock
);
2361 pthread_mutex_unlock(&stream
->lock
);
2366 memset(&reply
, 0, sizeof(reply
));
2367 /* All good, send back reply. */
2368 reply
.ret_code
= htobe32(is_data_inflight
);
2370 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2371 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2372 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2384 * Receive an index for a specific stream.
2386 * Return 0 on success else a negative value.
2388 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2389 struct relay_connection
*conn
,
2390 const struct lttng_buffer_view
*payload
)
2394 struct relay_session
*session
= conn
->session
;
2395 struct lttcomm_relayd_index index_info
;
2396 struct lttcomm_relayd_generic_reply reply
;
2397 struct relay_stream
*stream
;
2402 DBG("Relay receiving index");
2404 if (!session
|| !conn
->version_check_done
) {
2405 ERR("Trying to close a stream before version check");
2407 goto end_no_session
;
2410 msg_len
= lttcomm_relayd_index_len(
2411 lttng_to_index_major(conn
->major
, conn
->minor
),
2412 lttng_to_index_minor(conn
->major
, conn
->minor
));
2413 if (payload
->size
< msg_len
) {
2414 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2415 msg_len
, payload
->size
);
2417 goto end_no_session
;
2419 memcpy(&index_info
, payload
->data
, msg_len
);
2420 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2421 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2422 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2423 index_info
.content_size
= be64toh(index_info
.content_size
);
2424 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2425 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2426 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2427 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2429 if (conn
->minor
>= 8) {
2430 index_info
.stream_instance_id
=
2431 be64toh(index_info
.stream_instance_id
);
2432 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2434 index_info
.stream_instance_id
= -1ULL;
2435 index_info
.packet_seq_num
= -1ULL;
2438 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2440 ERR("stream_get_by_id not found");
2445 pthread_mutex_lock(&stream
->lock
);
2446 ret
= stream_add_index(stream
, &index_info
);
2447 pthread_mutex_unlock(&stream
->lock
);
2449 goto end_stream_put
;
2455 memset(&reply
, 0, sizeof(reply
));
2457 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2459 reply
.ret_code
= htobe32(LTTNG_OK
);
2461 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2462 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2463 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2472 * Receive the streams_sent message.
2474 * Return 0 on success else a negative value.
2476 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2477 struct relay_connection
*conn
,
2478 const struct lttng_buffer_view
*payload
)
2482 struct lttcomm_relayd_generic_reply reply
;
2486 DBG("Relay receiving streams_sent");
2488 if (!conn
->session
|| !conn
->version_check_done
) {
2489 ERR("Trying to close a stream before version check");
2491 goto end_no_session
;
2495 * Publish every pending stream in the connection recv list which are
2496 * now ready to be used by the viewer.
2498 publish_connection_local_streams(conn
);
2500 memset(&reply
, 0, sizeof(reply
));
2501 reply
.ret_code
= htobe32(LTTNG_OK
);
2502 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2503 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2504 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2516 static ssize_t
relay_unpack_rotate_streams_header(
2517 const struct lttng_buffer_view
*payload
,
2518 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2520 struct lttcomm_relayd_rotate_streams rotate_streams
;
2522 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2523 * This is the smallest version of this structure, but it can be larger;
2524 * this variable is updated once the proper size of the structure is known.
2526 * See comment at the declaration of this structure for more information.
2528 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2529 size_t expected_payload_size_no_padding
,
2530 expected_payload_size_3_bytes_padding
,
2531 expected_payload_size_7_bytes_padding
;
2533 if (payload
->size
< header_len
) {
2534 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2535 header_len
, payload
->size
);
2540 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2541 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2543 * We start by "unpacking" `stream_count` to figure out the padding length
2544 * emited by our peer.
2546 memcpy(&rotate_streams
.stream_count
, payload
->data
,
2547 sizeof(rotate_streams
.stream_count
));
2548 rotate_streams
= (typeof(rotate_streams
)) {
2549 .stream_count
= be32toh(rotate_streams
.stream_count
),
2553 * Payload size expected given the possible padding lengths in
2554 * `struct lttcomm_relayd_rotate_streams`.
2556 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2557 sizeof(*rotate_streams
.rotation_positions
)) +
2558 sizeof(lttcomm_relayd_rotate_streams_packed
);
2559 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2560 sizeof(*rotate_streams
.rotation_positions
)) +
2561 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2562 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2563 sizeof(*rotate_streams
.rotation_positions
)) +
2564 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2566 if (payload
->size
== expected_payload_size_no_padding
) {
2567 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2570 * This handles cases where someone might build with
2571 * -fpack-struct or any other toolchain that wouldn't produce
2572 * padding to align `value`.
2574 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2576 header_len
= sizeof(packed_rotate_streams
);
2577 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2579 /* Unpack the packed structure to the natively-packed version. */
2580 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2581 .stream_count
= be32toh(packed_rotate_streams
.stream_count
),
2582 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2583 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2584 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2587 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2588 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2590 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2592 header_len
= sizeof(padded_rotate_streams
);
2593 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2595 /* Unpack the 3-byte padded structure to the natively-packed version. */
2596 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2597 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2598 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2599 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2600 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2603 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2604 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2606 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2608 header_len
= sizeof(padded_rotate_streams
);
2609 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2611 /* Unpack the 7-byte padded structure to the natively-packed version. */
2612 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2613 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2614 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2615 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2616 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2620 header_len
= sizeof(padded_rotate_streams
);
2622 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2623 expected_payload_size_no_padding
,
2624 expected_payload_size_3_bytes_padding
,
2625 expected_payload_size_7_bytes_padding
,
2636 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2637 * session rotation feature (not the tracefile rotation feature).
2639 static int relay_rotate_session_streams(
2640 const struct lttcomm_relayd_hdr
*recv_hdr
,
2641 struct relay_connection
*conn
,
2642 const struct lttng_buffer_view
*payload
)
2647 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2648 struct relay_session
*session
= conn
->session
;
2649 struct lttcomm_relayd_rotate_streams rotate_streams
;
2650 struct lttcomm_relayd_generic_reply reply
= {};
2651 struct relay_stream
*stream
= NULL
;
2652 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2653 struct lttng_buffer_view stream_positions
;
2654 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2655 const char *chunk_id_str
= "none";
2658 if (!session
|| !conn
->version_check_done
) {
2659 ERR("Trying to rotate a stream before version check");
2664 if (session
->major
== 2 && session
->minor
< 11) {
2665 ERR("Unsupported feature before 2.11");
2670 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2671 if (header_len
< 0) {
2676 if (rotate_streams
.new_chunk_id
.is_set
) {
2678 * Retrieve the trace chunk the stream must transition to. As
2679 * per the protocol, this chunk should have been created
2680 * before this command is received.
2682 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2683 sessiond_trace_chunk_registry
,
2684 session
->sessiond_uuid
, session
->id
,
2685 rotate_streams
.new_chunk_id
.value
);
2686 if (!next_trace_chunk
) {
2687 char uuid_str
[LTTNG_UUID_STR_LEN
];
2689 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2690 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2691 ", trace_chunk_id = %" PRIu64
,
2692 uuid_str
, session
->id
,
2693 rotate_streams
.new_chunk_id
.value
);
2694 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2699 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2700 rotate_streams
.new_chunk_id
.value
);
2701 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2702 chunk_id_str
= "formatting error";
2704 chunk_id_str
= chunk_id_buf
;
2708 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2709 rotate_streams
.stream_count
, session
->session_name
,
2712 stream_positions
= lttng_buffer_view_from_view(payload
,
2714 if (!stream_positions
.data
||
2715 stream_positions
.size
<
2716 (rotate_streams
.stream_count
*
2717 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2718 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2723 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2724 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2725 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2726 const struct lttcomm_relayd_stream_rotation_position pos
= {
2727 .stream_id
= be64toh(position_comm
->stream_id
),
2728 .rotate_at_seq_num
= be64toh(
2729 position_comm
->rotate_at_seq_num
),
2732 stream
= stream_get_by_id(pos
.stream_id
);
2734 reply_code
= LTTNG_ERR_INVALID
;
2739 pthread_mutex_lock(&stream
->lock
);
2740 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2741 pos
.rotate_at_seq_num
);
2742 pthread_mutex_unlock(&stream
->lock
);
2744 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2752 reply_code
= LTTNG_OK
;
2759 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2760 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2761 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2762 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2763 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2768 lttng_trace_chunk_put(next_trace_chunk
);
2773 * relay_create_trace_chunk: create a new trace chunk
2775 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2776 struct relay_connection
*conn
,
2777 const struct lttng_buffer_view
*payload
)
2781 struct relay_session
*session
= conn
->session
;
2782 struct lttcomm_relayd_create_trace_chunk
*msg
;
2783 struct lttcomm_relayd_generic_reply reply
= {};
2784 struct lttng_buffer_view header_view
;
2785 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2786 enum lttng_error_code reply_code
= LTTNG_OK
;
2787 enum lttng_trace_chunk_status chunk_status
;
2788 const char *new_path
;
2790 if (!session
|| !conn
->version_check_done
) {
2791 ERR("Trying to create a trace chunk before version check");
2796 if (session
->major
== 2 && session
->minor
< 11) {
2797 ERR("Chunk creation command is unsupported before 2.11");
2802 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2803 if (!lttng_buffer_view_is_valid(&header_view
)) {
2804 ERR("Failed to receive payload of chunk creation command");
2809 /* Convert to host endianness. */
2810 msg
= (typeof(msg
)) header_view
.data
;
2811 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2812 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2813 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2815 if (session
->current_trace_chunk
&&
2816 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2817 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2818 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2819 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2820 ERR("Failed to rename old chunk");
2822 reply_code
= LTTNG_ERR_UNK
;
2826 session
->ongoing_rotation
= true;
2827 if (!session
->current_trace_chunk
) {
2828 if (!session
->has_rotated
) {
2834 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2836 chunk
= lttng_trace_chunk_create(
2837 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2839 ERR("Failed to create trace chunk in trace chunk creation command");
2841 reply_code
= LTTNG_ERR_NOMEM
;
2844 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2846 if (msg
->override_name_length
) {
2848 const struct lttng_buffer_view chunk_name_view
=
2849 lttng_buffer_view_from_view(payload
,
2851 msg
->override_name_length
);
2853 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2854 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2856 reply_code
= LTTNG_ERR_INVALID
;
2860 name
= chunk_name_view
.data
;
2861 if (name
[msg
->override_name_length
- 1]) {
2862 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2864 reply_code
= LTTNG_ERR_INVALID
;
2868 chunk_status
= lttng_trace_chunk_override_name(
2869 chunk
, chunk_name_view
.data
);
2870 switch (chunk_status
) {
2871 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2873 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2874 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2875 reply_code
= LTTNG_ERR_INVALID
;
2879 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2880 reply_code
= LTTNG_ERR_UNK
;
2886 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2887 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2888 reply_code
= LTTNG_ERR_UNK
;
2893 LTTNG_ASSERT(conn
->session
->output_directory
);
2894 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2895 conn
->session
->output_directory
);
2896 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2897 reply_code
= LTTNG_ERR_UNK
;
2902 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2903 sessiond_trace_chunk_registry
,
2904 conn
->session
->sessiond_uuid
,
2907 if (!published_chunk
) {
2908 char uuid_str
[LTTNG_UUID_STR_LEN
];
2910 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2911 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2916 reply_code
= LTTNG_ERR_NOMEM
;
2920 pthread_mutex_lock(&conn
->session
->lock
);
2921 if (conn
->session
->pending_closure_trace_chunk
) {
2923 * Invalid; this means a second create_trace_chunk command was
2924 * received before a close_trace_chunk.
2926 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2927 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2929 goto end_unlock_session
;
2931 conn
->session
->pending_closure_trace_chunk
=
2932 conn
->session
->current_trace_chunk
;
2933 conn
->session
->current_trace_chunk
= published_chunk
;
2934 published_chunk
= NULL
;
2935 if (!conn
->session
->pending_closure_trace_chunk
) {
2936 session
->ongoing_rotation
= false;
2939 pthread_mutex_unlock(&conn
->session
->lock
);
2941 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2942 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2944 sizeof(struct lttcomm_relayd_generic_reply
),
2946 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2947 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2952 lttng_trace_chunk_put(chunk
);
2953 lttng_trace_chunk_put(published_chunk
);
2958 * relay_close_trace_chunk: close a trace chunk
2960 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2961 struct relay_connection
*conn
,
2962 const struct lttng_buffer_view
*payload
)
2964 int ret
= 0, buf_ret
;
2966 struct relay_session
*session
= conn
->session
;
2967 struct lttcomm_relayd_close_trace_chunk
*msg
;
2968 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2969 struct lttng_buffer_view header_view
;
2970 struct lttng_trace_chunk
*chunk
= NULL
;
2971 enum lttng_error_code reply_code
= LTTNG_OK
;
2972 enum lttng_trace_chunk_status chunk_status
;
2974 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2975 time_t close_timestamp
;
2976 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2977 size_t path_length
= 0;
2978 const char *chunk_name
= NULL
;
2979 struct lttng_dynamic_buffer reply_payload
;
2980 const char *new_path
;
2982 lttng_dynamic_buffer_init(&reply_payload
);
2984 if (!session
|| !conn
->version_check_done
) {
2985 ERR("Trying to close a trace chunk before version check");
2990 if (session
->major
== 2 && session
->minor
< 11) {
2991 ERR("Chunk close command is unsupported before 2.11");
2996 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2997 if (!lttng_buffer_view_is_valid(&header_view
)) {
2998 ERR("Failed to receive payload of chunk close command");
3003 /* Convert to host endianness. */
3004 msg
= (typeof(msg
)) header_view
.data
;
3005 chunk_id
= be64toh(msg
->chunk_id
);
3006 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
3007 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
3008 close_command
.is_set
= msg
->close_command
.is_set
;
3010 chunk
= sessiond_trace_chunk_registry_get_chunk(
3011 sessiond_trace_chunk_registry
,
3012 conn
->session
->sessiond_uuid
,
3016 char uuid_str
[LTTNG_UUID_STR_LEN
];
3018 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3019 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
3024 reply_code
= LTTNG_ERR_NOMEM
;
3028 pthread_mutex_lock(&session
->lock
);
3029 if (close_command
.is_set
&&
3030 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3032 * Clear command. It is a protocol error to ask for a
3033 * clear on a relay which does not allow it. Querying
3034 * the configuration allows figuring out whether
3035 * clearing is allowed before doing the clear.
3037 if (!opt_allow_clear
) {
3039 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3040 goto end_unlock_session
;
3043 if (session
->pending_closure_trace_chunk
&&
3044 session
->pending_closure_trace_chunk
!= chunk
) {
3045 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3046 session
->session_name
);
3047 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3049 goto end_unlock_session
;
3052 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3053 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3054 if (close_command
.is_set
&&
3055 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3056 !session
->has_rotated
) {
3057 /* New chunk stays in session output directory. */
3060 /* Use chunk name for new chunk. */
3063 /* Rename new chunk path. */
3064 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3066 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3068 goto end_unlock_session
;
3070 session
->ongoing_rotation
= false;
3072 if ((!close_command
.is_set
||
3073 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3074 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3075 const char *old_path
;
3077 if (!session
->has_rotated
) {
3082 /* We need to move back the .tmp_old_chunk to its rightful place. */
3083 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3084 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3086 goto end_unlock_session
;
3089 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3090 chunk
, close_timestamp
);
3091 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3092 ERR("Failed to set trace chunk close timestamp");
3094 reply_code
= LTTNG_ERR_UNK
;
3095 goto end_unlock_session
;
3098 if (close_command
.is_set
) {
3099 chunk_status
= lttng_trace_chunk_set_close_command(
3100 chunk
, close_command
.value
);
3101 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3103 reply_code
= LTTNG_ERR_INVALID
;
3104 goto end_unlock_session
;
3107 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3108 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3109 ERR("Failed to get chunk name");
3111 reply_code
= LTTNG_ERR_UNK
;
3112 goto end_unlock_session
;
3114 if (!session
->has_rotated
&& !session
->snapshot
) {
3115 ret
= lttng_strncpy(closed_trace_chunk_path
,
3116 session
->output_path
,
3117 sizeof(closed_trace_chunk_path
));
3119 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3120 strlen(session
->output_path
),
3121 sizeof(closed_trace_chunk_path
));
3122 reply_code
= LTTNG_ERR_NOMEM
;
3124 goto end_unlock_session
;
3127 if (session
->snapshot
) {
3128 ret
= snprintf(closed_trace_chunk_path
,
3129 sizeof(closed_trace_chunk_path
),
3130 "%s/%s", session
->output_path
,
3133 ret
= snprintf(closed_trace_chunk_path
,
3134 sizeof(closed_trace_chunk_path
),
3135 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3137 session
->output_path
, chunk_name
);
3139 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3140 ERR("Failed to format closed trace chunk resulting path");
3141 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3143 goto end_unlock_session
;
3146 if (close_command
.is_set
&&
3147 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3148 session
->has_rotated
= true;
3150 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3151 path_length
= strlen(closed_trace_chunk_path
) + 1;
3152 if (path_length
> UINT32_MAX
) {
3153 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3155 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3156 goto end_unlock_session
;
3159 if (session
->current_trace_chunk
== chunk
) {
3161 * After a trace chunk close command, no new streams
3162 * referencing the chunk may be created. Hence, on the
3163 * event that no new trace chunk have been created for
3164 * the session, the reference to the current trace chunk
3165 * is released in order to allow it to be reclaimed when
3166 * the last stream releases its reference to it.
3168 lttng_trace_chunk_put(session
->current_trace_chunk
);
3169 session
->current_trace_chunk
= NULL
;
3171 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3172 session
->pending_closure_trace_chunk
= NULL
;
3174 pthread_mutex_unlock(&session
->lock
);
3177 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3178 reply
.path_length
= htobe32((uint32_t) path_length
);
3179 buf_ret
= lttng_dynamic_buffer_append(
3180 &reply_payload
, &reply
, sizeof(reply
));
3182 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3186 if (reply_code
== LTTNG_OK
) {
3187 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3188 closed_trace_chunk_path
, path_length
);
3190 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3195 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3199 if (send_ret
< reply_payload
.size
) {
3200 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3201 reply_payload
.size
, send_ret
);
3206 lttng_trace_chunk_put(chunk
);
3207 lttng_dynamic_buffer_reset(&reply_payload
);
3212 * relay_trace_chunk_exists: check if a trace chunk exists
3214 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3215 struct relay_connection
*conn
,
3216 const struct lttng_buffer_view
*payload
)
3220 struct relay_session
*session
= conn
->session
;
3221 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3222 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3223 struct lttng_buffer_view header_view
;
3227 if (!session
|| !conn
->version_check_done
) {
3228 ERR("Trying to check for the presence of a trace chunk before version check");
3233 if (session
->major
== 2 && session
->minor
< 11) {
3234 ERR("Chunk exists command is unsupported before 2.11");
3239 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3240 if (!lttng_buffer_view_is_valid(&header_view
)) {
3241 ERR("Failed to receive payload of chunk exists command");
3246 /* Convert to host endianness. */
3247 msg
= (typeof(msg
)) header_view
.data
;
3248 chunk_id
= be64toh(msg
->chunk_id
);
3250 ret
= sessiond_trace_chunk_registry_chunk_exists(
3251 sessiond_trace_chunk_registry
,
3252 conn
->session
->sessiond_uuid
,
3254 chunk_id
, &chunk_exists
);
3256 * If ret is not 0, send the reply and report the error to the caller.
3257 * It is a protocol (or internal) error and the session/connection
3258 * should be torn down.
3260 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3261 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3263 send_ret
= conn
->sock
->ops
->sendmsg(
3264 conn
->sock
, &reply
, sizeof(reply
), 0);
3265 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3266 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3275 * relay_get_configuration: query whether feature is available
3277 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3278 struct relay_connection
*conn
,
3279 const struct lttng_buffer_view
*payload
)
3283 struct lttcomm_relayd_get_configuration
*msg
;
3284 struct lttcomm_relayd_get_configuration_reply reply
= {};
3285 struct lttng_buffer_view header_view
;
3286 uint64_t query_flags
= 0;
3287 uint64_t result_flags
= 0;
3289 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3290 if (!lttng_buffer_view_is_valid(&header_view
)) {
3291 ERR("Failed to receive payload of chunk close command");
3296 /* Convert to host endianness. */
3297 msg
= (typeof(msg
)) header_view
.data
;
3298 query_flags
= be64toh(msg
->query_flags
);
3301 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3304 if (opt_allow_clear
) {
3305 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3309 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3310 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3312 send_ret
= conn
->sock
->ops
->sendmsg(
3313 conn
->sock
, &reply
, sizeof(reply
), 0);
3314 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3315 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3323 #define DBG_CMD(cmd_name, conn) \
3324 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3326 static int relay_process_control_command(struct relay_connection
*conn
,
3327 const struct lttcomm_relayd_hdr
*header
,
3328 const struct lttng_buffer_view
*payload
)
3332 switch (header
->cmd
) {
3333 case RELAYD_CREATE_SESSION
:
3334 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3335 ret
= relay_create_session(header
, conn
, payload
);
3337 case RELAYD_ADD_STREAM
:
3338 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3339 ret
= relay_add_stream(header
, conn
, payload
);
3341 case RELAYD_START_DATA
:
3342 DBG_CMD("RELAYD_START_DATA", conn
);
3343 ret
= relay_start(header
, conn
, payload
);
3345 case RELAYD_SEND_METADATA
:
3346 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3347 ret
= relay_recv_metadata(header
, conn
, payload
);
3349 case RELAYD_VERSION
:
3350 DBG_CMD("RELAYD_VERSION", conn
);
3351 ret
= relay_send_version(header
, conn
, payload
);
3353 case RELAYD_CLOSE_STREAM
:
3354 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3355 ret
= relay_close_stream(header
, conn
, payload
);
3357 case RELAYD_DATA_PENDING
:
3358 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3359 ret
= relay_data_pending(header
, conn
, payload
);
3361 case RELAYD_QUIESCENT_CONTROL
:
3362 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3363 ret
= relay_quiescent_control(header
, conn
, payload
);
3365 case RELAYD_BEGIN_DATA_PENDING
:
3366 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3367 ret
= relay_begin_data_pending(header
, conn
, payload
);
3369 case RELAYD_END_DATA_PENDING
:
3370 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3371 ret
= relay_end_data_pending(header
, conn
, payload
);
3373 case RELAYD_SEND_INDEX
:
3374 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3375 ret
= relay_recv_index(header
, conn
, payload
);
3377 case RELAYD_STREAMS_SENT
:
3378 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3379 ret
= relay_streams_sent(header
, conn
, payload
);
3381 case RELAYD_RESET_METADATA
:
3382 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3383 ret
= relay_reset_metadata(header
, conn
, payload
);
3385 case RELAYD_ROTATE_STREAMS
:
3386 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3387 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3389 case RELAYD_CREATE_TRACE_CHUNK
:
3390 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3391 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3393 case RELAYD_CLOSE_TRACE_CHUNK
:
3394 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3395 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3397 case RELAYD_TRACE_CHUNK_EXISTS
:
3398 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3399 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3401 case RELAYD_GET_CONFIGURATION
:
3402 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3403 ret
= relay_get_configuration(header
, conn
, payload
);
3405 case RELAYD_UPDATE_SYNC_INFO
:
3407 ERR("Received unknown command (%u)", header
->cmd
);
3408 relay_unknown_command(conn
);
3417 static enum relay_connection_status
relay_process_control_receive_payload(
3418 struct relay_connection
*conn
)
3421 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3422 struct lttng_dynamic_buffer
*reception_buffer
=
3423 &conn
->protocol
.ctrl
.reception_buffer
;
3424 struct ctrl_connection_state_receive_payload
*state
=
3425 &conn
->protocol
.ctrl
.state
.receive_payload
;
3426 struct lttng_buffer_view payload_view
;
3428 if (state
->left_to_receive
== 0) {
3429 /* Short-circuit for payload-less commands. */
3430 goto reception_complete
;
3433 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3434 reception_buffer
->data
+ state
->received
,
3435 state
->left_to_receive
, MSG_DONTWAIT
);
3437 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3438 PERROR("Unable to receive command payload on sock %d",
3440 status
= RELAY_CONNECTION_STATUS_ERROR
;
3443 } else if (ret
== 0) {
3444 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3445 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3449 LTTNG_ASSERT(ret
> 0);
3450 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3452 state
->left_to_receive
-= ret
;
3453 state
->received
+= ret
;
3455 if (state
->left_to_receive
> 0) {
3457 * Can't transition to the protocol's next state, wait to
3458 * receive the rest of the header.
3460 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3461 state
->received
, state
->left_to_receive
,
3467 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3468 conn
->sock
->fd
, state
->received
);
3470 * The payload required to process the command has been received.
3471 * A view to the reception buffer is forwarded to the various
3472 * commands and the state of the control is reset on success.
3474 * Commands are responsible for sending their reply to the peer.
3476 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3478 ret
= relay_process_control_command(conn
,
3479 &state
->header
, &payload_view
);
3481 status
= RELAY_CONNECTION_STATUS_ERROR
;
3485 ret
= connection_reset_protocol_state(conn
);
3487 status
= RELAY_CONNECTION_STATUS_ERROR
;
3493 static enum relay_connection_status
relay_process_control_receive_header(
3494 struct relay_connection
*conn
)
3497 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3498 struct lttcomm_relayd_hdr header
;
3499 struct lttng_dynamic_buffer
*reception_buffer
=
3500 &conn
->protocol
.ctrl
.reception_buffer
;
3501 struct ctrl_connection_state_receive_header
*state
=
3502 &conn
->protocol
.ctrl
.state
.receive_header
;
3504 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3506 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3507 reception_buffer
->data
+ state
->received
,
3508 state
->left_to_receive
, MSG_DONTWAIT
);
3510 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3511 PERROR("Unable to receive control command header on sock %d",
3513 status
= RELAY_CONNECTION_STATUS_ERROR
;
3516 } else if (ret
== 0) {
3517 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3518 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3522 LTTNG_ASSERT(ret
> 0);
3523 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3525 state
->left_to_receive
-= ret
;
3526 state
->received
+= ret
;
3528 if (state
->left_to_receive
> 0) {
3530 * Can't transition to the protocol's next state, wait to
3531 * receive the rest of the header.
3533 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3534 state
->received
, state
->left_to_receive
,
3539 /* Transition to next state: receiving the command's payload. */
3540 conn
->protocol
.ctrl
.state_id
=
3541 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3542 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3543 header
.circuit_id
= be64toh(header
.circuit_id
);
3544 header
.data_size
= be64toh(header
.data_size
);
3545 header
.cmd
= be32toh(header
.cmd
);
3546 header
.cmd_version
= be32toh(header
.cmd_version
);
3547 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3548 &header
, sizeof(header
));
3550 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3551 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3554 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3555 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3557 status
= RELAY_CONNECTION_STATUS_ERROR
;
3561 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3563 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3564 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3567 status
= RELAY_CONNECTION_STATUS_ERROR
;
3571 if (header
.data_size
== 0) {
3573 * Manually invoke the next state as the poll loop
3574 * will not wake-up to allow us to proceed further.
3576 status
= relay_process_control_receive_payload(conn
);
3583 * Process the commands received on the control socket
3585 static enum relay_connection_status
relay_process_control(
3586 struct relay_connection
*conn
)
3588 enum relay_connection_status status
;
3590 switch (conn
->protocol
.ctrl
.state_id
) {
3591 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3592 status
= relay_process_control_receive_header(conn
);
3594 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3595 status
= relay_process_control_receive_payload(conn
);
3598 ERR("Unknown control connection protocol state encountered.");
3605 static enum relay_connection_status
relay_process_data_receive_header(
3606 struct relay_connection
*conn
)
3609 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3610 struct data_connection_state_receive_header
*state
=
3611 &conn
->protocol
.data
.state
.receive_header
;
3612 struct lttcomm_relayd_data_hdr header
;
3613 struct relay_stream
*stream
;
3615 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3617 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3618 state
->header_reception_buffer
+ state
->received
,
3619 state
->left_to_receive
, MSG_DONTWAIT
);
3621 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3622 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3623 status
= RELAY_CONNECTION_STATUS_ERROR
;
3626 } else if (ret
== 0) {
3627 /* Orderly shutdown. Not necessary to print an error. */
3628 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3629 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3633 LTTNG_ASSERT(ret
> 0);
3634 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3636 state
->left_to_receive
-= ret
;
3637 state
->received
+= ret
;
3639 if (state
->left_to_receive
> 0) {
3641 * Can't transition to the protocol's next state, wait to
3642 * receive the rest of the header.
3644 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3645 state
->received
, state
->left_to_receive
,
3650 /* Transition to next state: receiving the payload. */
3651 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3653 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3654 header
.circuit_id
= be64toh(header
.circuit_id
);
3655 header
.stream_id
= be64toh(header
.stream_id
);
3656 header
.data_size
= be32toh(header
.data_size
);
3657 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3658 header
.padding_size
= be32toh(header
.padding_size
);
3659 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3661 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3663 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3664 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3666 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3667 conn
->sock
->fd
, header
.circuit_id
,
3668 header
.stream_id
, header
.data_size
,
3669 header
.net_seq_num
, header
.padding_size
);
3671 stream
= stream_get_by_id(header
.stream_id
);
3673 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3675 /* Protocol error. */
3676 status
= RELAY_CONNECTION_STATUS_ERROR
;
3680 pthread_mutex_lock(&stream
->lock
);
3681 /* Prepare stream for the reception of a new packet. */
3682 ret
= stream_init_packet(stream
, header
.data_size
,
3683 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3684 pthread_mutex_unlock(&stream
->lock
);
3686 ERR("Failed to rotate stream output file");
3687 status
= RELAY_CONNECTION_STATUS_ERROR
;
3688 goto end_stream_unlock
;
3697 static enum relay_connection_status
relay_process_data_receive_payload(
3698 struct relay_connection
*conn
)
3701 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3702 struct relay_stream
*stream
;
3703 struct data_connection_state_receive_payload
*state
=
3704 &conn
->protocol
.data
.state
.receive_payload
;
3705 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3706 char data_buffer
[chunk_size
];
3707 bool partial_recv
= false;
3708 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3709 uint64_t left_to_receive
= state
->left_to_receive
;
3710 struct relay_session
*session
;
3712 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3713 state
->header
.stream_id
, state
->header
.net_seq_num
,
3714 state
->received
, left_to_receive
);
3716 stream
= stream_get_by_id(state
->header
.stream_id
);
3718 /* Protocol error. */
3719 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3720 state
->header
.stream_id
);
3721 status
= RELAY_CONNECTION_STATUS_ERROR
;
3725 pthread_mutex_lock(&stream
->lock
);
3726 session
= stream
->trace
->session
;
3727 if (!conn
->session
) {
3728 ret
= connection_set_session(conn
, session
);
3730 status
= RELAY_CONNECTION_STATUS_ERROR
;
3731 goto end_stream_unlock
;
3736 * The size of the "chunk" received on any iteration is bounded by:
3737 * - the data left to receive,
3738 * - the data immediately available on the socket,
3739 * - the on-stack data buffer
3741 while (left_to_receive
> 0 && !partial_recv
) {
3742 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3743 struct lttng_buffer_view packet_chunk
;
3745 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3746 recv_size
, MSG_DONTWAIT
);
3748 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3749 PERROR("Socket %d error", conn
->sock
->fd
);
3750 status
= RELAY_CONNECTION_STATUS_ERROR
;
3752 goto end_stream_unlock
;
3753 } else if (ret
== 0) {
3754 /* No more data ready to be consumed on socket. */
3755 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3756 state
->header
.stream_id
);
3757 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3759 } else if (ret
< (int) recv_size
) {
3761 * All the data available on the socket has been
3764 partial_recv
= true;
3768 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3770 LTTNG_ASSERT(packet_chunk
.data
);
3772 ret
= stream_write(stream
, &packet_chunk
, 0);
3774 ERR("Relay error writing data to file");
3775 status
= RELAY_CONNECTION_STATUS_ERROR
;
3776 goto end_stream_unlock
;
3779 left_to_receive
-= recv_size
;
3780 state
->received
+= recv_size
;
3781 state
->left_to_receive
= left_to_receive
;
3784 if (state
->left_to_receive
> 0) {
3786 * Did not receive all the data expected, wait for more data to
3787 * become available on the socket.
3789 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3790 state
->header
.stream_id
, state
->received
,
3791 state
->left_to_receive
);
3792 goto end_stream_unlock
;
3795 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3797 status
= RELAY_CONNECTION_STATUS_ERROR
;
3798 goto end_stream_unlock
;
3801 if (session_streams_have_index(session
)) {
3802 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3803 state
->rotate_index
, &index_flushed
,
3804 state
->header
.data_size
+ state
->header
.padding_size
);
3806 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3807 stream
->stream_handle
,
3808 state
->header
.net_seq_num
, ret
);
3809 status
= RELAY_CONNECTION_STATUS_ERROR
;
3810 goto end_stream_unlock
;
3814 if (stream
->prev_data_seq
== -1ULL) {
3818 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3819 state
->header
.padding_size
, state
->header
.net_seq_num
,
3822 status
= RELAY_CONNECTION_STATUS_ERROR
;
3823 goto end_stream_unlock
;
3827 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3828 * contents of *state which are aliased (union) to the same location as
3829 * the new state. Don't use it beyond this point.
3831 connection_reset_protocol_state(conn
);
3835 close_requested
= stream
->close_requested
;
3836 pthread_mutex_unlock(&stream
->lock
);
3837 if (close_requested
&& left_to_receive
== 0) {
3838 try_stream_close(stream
);
3842 pthread_mutex_lock(&session
->lock
);
3843 uatomic_set(&session
->new_streams
, 1);
3844 pthread_mutex_unlock(&session
->lock
);
3853 * relay_process_data: Process the data received on the data socket
3855 static enum relay_connection_status
relay_process_data(
3856 struct relay_connection
*conn
)
3858 enum relay_connection_status status
;
3860 switch (conn
->protocol
.data
.state_id
) {
3861 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3862 status
= relay_process_data_receive_header(conn
);
3864 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3865 status
= relay_process_data_receive_payload(conn
);
3868 ERR("Unexpected data connection communication state.");
3875 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3879 (void) lttng_poll_del(events
, pollfd
);
3881 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3882 fd_tracker_util_close_fd
, NULL
);
3884 ERR("Closing pollfd %d", pollfd
);
3888 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3889 int pollfd
, struct relay_connection
*conn
)
3891 const char *type_str
;
3893 switch (conn
->type
) {
3898 type_str
= "Control";
3900 case RELAY_VIEWER_COMMAND
:
3901 type_str
= "Viewer Command";
3903 case RELAY_VIEWER_NOTIFICATION
:
3904 type_str
= "Viewer Notification";
3907 type_str
= "Unknown";
3909 cleanup_connection_pollfd(events
, pollfd
);
3910 connection_put(conn
);
3911 DBG("%s connection closed with %d", type_str
, pollfd
);
3915 * This thread does the actual work
3917 static void *relay_thread_worker(void *data
)
3919 int ret
, err
= -1, last_seen_data_fd
= -1;
3921 struct lttng_poll_event events
;
3922 struct lttng_ht
*relay_connections_ht
;
3923 struct lttng_ht_iter iter
;
3924 struct relay_connection
*destroy_conn
= NULL
;
3926 DBG("[thread] Relay worker started");
3928 rcu_register_thread();
3930 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3932 if (testpoint(relayd_thread_worker
)) {
3933 goto error_testpoint
;
3936 health_code_update();
3938 /* table of connections indexed on socket */
3939 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3940 if (!relay_connections_ht
) {
3941 goto relay_connections_ht_error
;
3944 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3946 goto error_poll_create
;
3949 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3956 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3958 health_code_update();
3960 /* Infinite blocking call, waiting for transmission */
3961 DBG3("Relayd worker thread polling...");
3962 health_poll_entry();
3963 ret
= lttng_poll_wait(&events
, -1);
3967 * Restart interrupted system call.
3969 if (errno
== EINTR
) {
3978 * Process control. The control connection is
3979 * prioritized so we don't starve it with high
3980 * throughput tracing data on the data connection.
3982 for (i
= 0; i
< nb_fd
; i
++) {
3983 /* Fetch once the poll data */
3984 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3985 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3987 health_code_update();
3989 /* Thread quit pipe has been closed. Killing thread. */
3990 ret
= check_thread_quit_pipe(pollfd
, revents
);
3996 /* Inspect the relay conn pipe for new connection */
3997 if (pollfd
== relay_conn_pipe
[0]) {
3998 if (revents
& LPOLLIN
) {
3999 struct relay_connection
*conn
;
4001 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
4005 ret
= lttng_poll_add(&events
,
4007 LPOLLIN
| LPOLLRDHUP
);
4009 ERR("Failed to add new connection file descriptor to poll set");
4012 connection_ht_add(relay_connections_ht
, conn
);
4013 DBG("Connection socket %d added", conn
->sock
->fd
);
4014 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4015 ERR("Relay connection pipe error");
4018 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4022 struct relay_connection
*ctrl_conn
;
4024 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4025 /* If not found, there is a synchronization issue. */
4026 LTTNG_ASSERT(ctrl_conn
);
4028 if (ctrl_conn
->type
== RELAY_DATA
) {
4029 if (revents
& LPOLLIN
) {
4031 * Flag the last seen data fd not deleted. It will be
4032 * used as the last seen fd if any fd gets deleted in
4035 last_notdel_data_fd
= pollfd
;
4037 goto put_ctrl_connection
;
4039 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4041 if (revents
& LPOLLIN
) {
4042 enum relay_connection_status status
;
4044 status
= relay_process_control(ctrl_conn
);
4045 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4047 * On socket error flag the session as aborted to force
4048 * the cleanup of its stream otherwise it can leak
4049 * during the lifetime of the relayd.
4051 * This prevents situations in which streams can be
4052 * left opened because an index was received, the
4053 * control connection is closed, and the data
4054 * connection is closed (uncleanly) before the packet's
4057 * Since the control connection encountered an error,
4058 * it is okay to be conservative and close the
4059 * session right now as we can't rely on the protocol
4060 * being respected anymore.
4062 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4063 session_abort(ctrl_conn
->session
);
4066 /* Clear the connection on error or close. */
4067 relay_thread_close_connection(&events
,
4072 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4073 relay_thread_close_connection(&events
,
4075 if (last_seen_data_fd
== pollfd
) {
4076 last_seen_data_fd
= last_notdel_data_fd
;
4079 ERR("Unexpected poll events %u for control sock %d",
4081 connection_put(ctrl_conn
);
4084 put_ctrl_connection
:
4085 connection_put(ctrl_conn
);
4090 * The last loop handled a control request, go back to poll to make
4091 * sure we prioritise the control socket.
4097 if (last_seen_data_fd
>= 0) {
4098 for (i
= 0; i
< nb_fd
; i
++) {
4099 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4101 health_code_update();
4103 if (last_seen_data_fd
== pollfd
) {
4110 /* Process data connection. */
4111 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4112 /* Fetch the poll data. */
4113 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4114 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4115 struct relay_connection
*data_conn
;
4117 health_code_update();
4120 /* No activity for this FD (poll implementation). */
4124 /* Skip the command pipe. It's handled in the first loop. */
4125 if (pollfd
== relay_conn_pipe
[0]) {
4129 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4131 /* Skip it. Might be removed before. */
4134 if (data_conn
->type
== RELAY_CONTROL
) {
4135 goto put_data_connection
;
4137 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4139 if (revents
& LPOLLIN
) {
4140 enum relay_connection_status status
;
4142 status
= relay_process_data(data_conn
);
4143 /* Connection closed or error. */
4144 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4146 * On socket error flag the session as aborted to force
4147 * the cleanup of its stream otherwise it can leak
4148 * during the lifetime of the relayd.
4150 * This prevents situations in which streams can be
4151 * left opened because an index was received, the
4152 * control connection is closed, and the data
4153 * connection is closed (uncleanly) before the packet's
4156 * Since the data connection encountered an error,
4157 * it is okay to be conservative and close the
4158 * session right now as we can't rely on the protocol
4159 * being respected anymore.
4161 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4162 session_abort(data_conn
->session
);
4164 relay_thread_close_connection(&events
, pollfd
,
4167 * Every goto restart call sets the last seen fd where
4168 * here we don't really care since we gracefully
4169 * continue the loop after the connection is deleted.
4172 /* Keep last seen port. */
4173 last_seen_data_fd
= pollfd
;
4174 connection_put(data_conn
);
4177 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4178 relay_thread_close_connection(&events
, pollfd
,
4181 ERR("Unknown poll events %u for data sock %d",
4184 put_data_connection
:
4185 connection_put(data_conn
);
4187 last_seen_data_fd
= -1;
4190 /* Normal exit, no error */
4195 /* Cleanup remaining connection object. */
4197 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4200 health_code_update();
4202 session_abort(destroy_conn
->session
);
4205 * No need to grab another ref, because we own
4208 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4213 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4215 lttng_ht_destroy(relay_connections_ht
);
4216 relay_connections_ht_error
:
4217 /* Close relay conn pipes */
4218 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4221 DBG("Thread exited with error");
4223 DBG("Worker thread cleanup complete");
4227 ERR("Health error occurred in %s", __func__
);
4229 health_unregister(health_relayd
);
4230 rcu_unregister_thread();
4231 lttng_relay_stop_threads();
4236 * Create the relay command pipe to wake thread_manage_apps.
4237 * Closed in cleanup().
4239 static int create_relay_conn_pipe(void)
4241 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4242 "Relayd connection pipe", relay_conn_pipe
);
4245 static int stdio_open(void *data
, int *fds
)
4247 fds
[0] = fileno(stdout
);
4248 fds
[1] = fileno(stderr
);
4252 static int track_stdio(void)
4255 const char *names
[] = { "stdout", "stderr" };
4257 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4258 names
, 2, stdio_open
, NULL
);
4264 int main(int argc
, char **argv
)
4266 bool thread_is_rcu_registered
= false;
4267 int ret
= 0, retval
= 0;
4269 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4271 /* Parse environment variables */
4272 ret
= parse_env_options();
4280 * Command line arguments overwrite environment.
4283 if (set_options(argc
, argv
)) {
4288 if (set_signal_handler()) {
4293 relayd_config_log();
4295 if (opt_print_version
) {
4301 ret
= fclose(stdin
);
4303 PERROR("Failed to close stdin");
4307 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4309 /* Try to create directory if -o, --output is specified. */
4310 if (opt_output_path
) {
4311 if (*opt_output_path
!= '/') {
4312 ERR("Please specify an absolute path for -o, --output PATH");
4317 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4320 ERR("Unable to create %s", opt_output_path
);
4327 if (opt_daemon
|| opt_background
) {
4328 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4336 if (opt_working_directory
) {
4337 ret
= utils_change_working_directory(opt_working_directory
);
4339 /* All errors are already logged. */
4344 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4345 if (!sessiond_trace_chunk_registry
) {
4346 ERR("Failed to initialize session daemon trace chunk registry");
4352 * The RCU thread registration (and use, through the fd-tracker's
4353 * creation) is done after the daemonization to allow us to not
4354 * deal with liburcu's fork() management as the call RCU needs to
4357 rcu_register_thread();
4358 thread_is_rcu_registered
= true;
4360 output_path
= create_output_path("");
4362 ERR("Failed to get output path");
4366 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4367 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4370 ERR("Failed to format unlinked file directory path");
4374 the_fd_tracker
= fd_tracker_create(
4375 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4376 free(unlinked_file_directory_path
);
4377 if (!the_fd_tracker
) {
4382 ret
= track_stdio();
4388 /* Initialize thread health monitoring */
4389 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4390 if (!health_relayd
) {
4391 PERROR("health_app_create error");
4396 /* Create thread quit pipe */
4397 if (init_thread_quit_pipe()) {
4402 /* Setup the thread apps communication pipe. */
4403 if (create_relay_conn_pipe()) {
4408 /* Init relay command queue. */
4409 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4411 /* Initialize communication library */
4413 lttcomm_inet_init();
4415 /* tables of sessions indexed by session ID */
4416 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4422 /* tables of streams indexed by stream ID */
4423 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4424 if (!relay_streams_ht
) {
4429 /* tables of streams indexed by stream ID */
4430 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4431 if (!viewer_streams_ht
) {
4436 ret
= init_health_quit_pipe();
4442 /* Create thread to manage the client socket */
4443 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4444 thread_manage_health
, (void *) NULL
);
4447 PERROR("pthread_create health");
4452 /* Setup the dispatcher thread */
4453 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4454 relay_thread_dispatcher
, (void *) NULL
);
4457 PERROR("pthread_create dispatcher");
4459 goto exit_dispatcher_thread
;
4462 /* Setup the worker thread */
4463 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4464 relay_thread_worker
, NULL
);
4467 PERROR("pthread_create worker");
4469 goto exit_worker_thread
;
4472 /* Setup the listener thread */
4473 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4474 relay_thread_listener
, (void *) NULL
);
4477 PERROR("pthread_create listener");
4479 goto exit_listener_thread
;
4482 ret
= relayd_live_create(live_uri
);
4484 ERR("Starting live viewer threads");
4490 * This is where we start awaiting program completion (e.g. through
4491 * signal that asks threads to teardown).
4494 ret
= relayd_live_join();
4500 ret
= pthread_join(listener_thread
, &status
);
4503 PERROR("pthread_join listener_thread");
4507 exit_listener_thread
:
4508 ret
= pthread_join(worker_thread
, &status
);
4511 PERROR("pthread_join worker_thread");
4516 ret
= pthread_join(dispatcher_thread
, &status
);
4519 PERROR("pthread_join dispatcher_thread");
4522 exit_dispatcher_thread
:
4524 ret
= pthread_join(health_thread
, &status
);
4527 PERROR("pthread_join health_thread");
4532 * Wait for all pending call_rcu work to complete before tearing
4533 * down data structures. call_rcu worker may be trying to
4534 * perform lookups in those structures.
4539 /* Ensure all prior call_rcu are done. */
4542 if (thread_is_rcu_registered
) {
4543 rcu_unregister_thread();