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.hpp>
40 #include <common/compat/poll.hpp>
41 #include <common/compat/socket.hpp>
42 #include <common/compat/endian.hpp>
43 #include <common/compat/getenv.hpp>
44 #include <common/defaults.hpp>
45 #include <common/daemonize.hpp>
46 #include <common/futex.hpp>
47 #include <common/sessiond-comm/sessiond-comm.hpp>
48 #include <common/sessiond-comm/inet.hpp>
49 #include <common/sessiond-comm/relayd.hpp>
50 #include <common/uri.hpp>
51 #include <common/utils.hpp>
52 #include <common/path.hpp>
53 #include <common/align.hpp>
54 #include <common/ini-config/ini-config.hpp>
55 #include <common/dynamic-buffer.hpp>
56 #include <common/buffer-view.hpp>
57 #include <common/string-utils/format.hpp>
58 #include <common/fd-tracker/fd-tracker.hpp>
59 #include <common/fd-tracker/utils.hpp>
61 #include "backward-compatibility-group-by.hpp"
63 #include "connection.hpp"
64 #include "ctf-trace.hpp"
65 #include "health-relayd.hpp"
68 #include "lttng-relayd.hpp"
69 #include "session.hpp"
70 #include "sessiond-trace-chunks.hpp"
72 #include "tcp_keep_alive.hpp"
73 #include "testpoint.hpp"
74 #include "tracefile-array.hpp"
76 #include "version.hpp"
77 #include "viewer-stream.hpp"
79 static const char *help_msg
=
80 #ifdef LTTNG_EMBED_HELP
81 #include <lttng-relayd.8.h>
87 enum relay_connection_status
{
88 RELAY_CONNECTION_STATUS_OK
,
89 /* An error occurred while processing an event on the connection. */
90 RELAY_CONNECTION_STATUS_ERROR
,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED
,
95 /* command line options */
96 char *opt_output_path
, *opt_working_directory
;
97 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
98 static int opt_allow_ctf2
= 1;
99 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
101 /* Argument variables */
102 int lttng_opt_quiet
; /* not static in error.h */
103 int lttng_opt_verbose
; /* not static in error.h */
104 int lttng_opt_mi
; /* not static in error.h */
107 * We need to wait for listener and live listener threads, as well as
108 * health check thread, before being ready to signal readiness.
110 #define NR_LTTNG_RELAY_READY 3
111 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
113 /* Size of receive buffer. */
114 #define RECV_DATA_BUFFER_SIZE 65536
116 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
117 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
119 static struct lttng_uri
*control_uri
;
120 static struct lttng_uri
*data_uri
;
121 static struct lttng_uri
*live_uri
;
123 const char *progname
;
125 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
126 static int tracing_group_name_override
;
128 const char * const config_section_name
= "relayd";
131 * Quit pipe for all threads. This permits a single cancellation point
132 * for all threads when receiving an event on the pipe.
134 int thread_quit_pipe
[2] = { -1, -1 };
137 * This pipe is used to inform the worker thread that a command is queued and
138 * ready to be processed.
140 static int relay_conn_pipe
[2] = { -1, -1 };
142 /* Shared between threads */
143 static int dispatch_thread_exit
;
145 static pthread_t listener_thread
;
146 static pthread_t dispatcher_thread
;
147 static pthread_t worker_thread
;
148 static pthread_t health_thread
;
151 * last_relay_stream_id_lock protects last_relay_stream_id increment
152 * atomicity on 32-bit architectures.
154 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
155 static uint64_t last_relay_stream_id
;
158 * Relay command queue.
160 * The relay_thread_listener and relay_thread_dispatcher communicate with this
163 static struct relay_conn_queue relay_conn_queue
;
165 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
166 static unsigned int lttng_opt_fd_pool_size
= -1;
168 /* Global relay stream hash table. */
169 struct lttng_ht
*relay_streams_ht
;
171 /* Global relay viewer stream hash table. */
172 struct lttng_ht
*viewer_streams_ht
;
174 /* Global relay sessions hash table. */
175 struct lttng_ht
*sessions_ht
;
177 /* Relayd health monitoring */
178 struct health_app
*health_relayd
;
180 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
182 /* Global fd tracker. */
183 struct fd_tracker
*the_fd_tracker
;
185 static struct option long_options
[] = {
186 { "control-port", 1, 0, 'C', },
187 { "data-port", 1, 0, 'D', },
188 { "live-port", 1, 0, 'L', },
189 { "daemonize", 0, 0, 'd', },
190 { "background", 0, 0, 'b', },
191 { "group", 1, 0, 'g', },
192 { "fd-pool-size", 1, 0, '\0', },
193 { "help", 0, 0, 'h', },
194 { "output", 1, 0, 'o', },
195 { "verbose", 0, 0, 'v', },
196 { "config", 1, 0, 'f' },
197 { "version", 0, 0, 'V' },
198 { "working-directory", 1, 0, 'w', },
199 { "group-output-by-session", 0, 0, 's', },
200 { "group-output-by-host", 0, 0, 'p', },
201 { "disallow-clear", 0, 0, 'x' },
202 { "disallow-ctf2", 0, 0, 'y' },
206 static const char *config_ignore_options
[] = { "help", "config", "version" };
208 static void print_version(void) {
209 fprintf(stdout
, "%s\n", VERSION
);
212 static void relayd_config_log(void)
214 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
215 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
216 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
217 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
218 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
220 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
221 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
224 DBG("Trace format supported: %s%s", "ctf1", opt_allow_ctf2
? ", ctf2" : "");
228 * Take an option from the getopt output and set it in the right variable to be
231 * Return 0 on success else a negative value.
233 static int set_option(int opt
, const char *arg
, const char *optname
)
239 if (!strcmp(optname
, "fd-pool-size")) {
243 v
= strtoul(arg
, NULL
, 0);
244 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
245 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
250 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
254 lttng_opt_fd_pool_size
= (unsigned int) v
;
256 fprintf(stderr
, "unknown option %s", optname
);
258 fprintf(stderr
, " with arg %s\n", arg
);
263 if (lttng_is_setuid_setgid()) {
264 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
265 "-C, --control-port");
267 ret
= uri_parse(arg
, &control_uri
);
269 ERR("Invalid control URI specified");
272 if (control_uri
->port
== 0) {
273 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
278 if (lttng_is_setuid_setgid()) {
279 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
282 ret
= uri_parse(arg
, &data_uri
);
284 ERR("Invalid data URI specified");
287 if (data_uri
->port
== 0) {
288 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
293 if (lttng_is_setuid_setgid()) {
294 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
297 ret
= uri_parse(arg
, &live_uri
);
299 ERR("Invalid live URI specified");
302 if (live_uri
->port
== 0) {
303 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
314 if (lttng_is_setuid_setgid()) {
315 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
318 tracing_group_name
= strdup(arg
);
319 if (tracing_group_name
== NULL
) {
324 tracing_group_name_override
= 1;
328 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
330 ERR("Cannot show --help for `lttng-relayd`");
335 opt_print_version
= 1;
338 if (lttng_is_setuid_setgid()) {
339 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
342 ret
= asprintf(&opt_output_path
, "%s", arg
);
345 PERROR("asprintf opt_output_path");
351 if (lttng_is_setuid_setgid()) {
352 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
353 "-w, --working-directory");
355 ret
= asprintf(&opt_working_directory
, "%s", arg
);
358 PERROR("asprintf opt_working_directory");
365 /* Verbose level can increase using multiple -v */
367 lttng_opt_verbose
= config_parse_value(arg
);
369 /* Only 3 level of verbosity (-vvv). */
370 if (lttng_opt_verbose
< 3) {
371 lttng_opt_verbose
+= 1;
376 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
377 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
380 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
383 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
384 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
387 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
398 /* Unknown option or other error.
399 * Error is printed by getopt, just return */
412 * config_entry_handler_cb used to handle options read from a config file.
413 * See config_entry_handler_cb comment in common/config/session-config.h for the
414 * return value conventions.
416 static int config_entry_handler(const struct config_entry
*entry
,
417 void *unused
__attribute__((unused
)))
421 if (!entry
|| !entry
->name
|| !entry
->value
) {
426 /* Check if the option is to be ignored */
427 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
428 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
433 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
434 /* Ignore if entry name is not fully matched. */
435 if (strcmp(entry
->name
, long_options
[i
].name
)) {
440 * If the option takes no argument on the command line,
441 * we have to check if the value is "true". We support
442 * non-zero numeric values, true, on and yes.
444 if (!long_options
[i
].has_arg
) {
445 ret
= config_parse_value(entry
->value
);
448 WARN("Invalid configuration value \"%s\" for option %s",
449 entry
->value
, entry
->name
);
451 /* False, skip boolean config option. */
456 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
460 WARN("Unrecognized option \"%s\" in daemon configuration file.",
467 static int parse_env_options(void)
472 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
474 opt_working_directory
= strdup(value
);
475 if (!opt_working_directory
) {
476 ERR("Failed to allocate working directory string (\"%s\")",
484 static int set_fd_pool_size(void)
487 struct rlimit rlimit
;
489 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
491 PERROR("Failed to get file descriptor limit");
496 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
497 (uint64_t) rlimit
.rlim_cur
,
498 (uint64_t) rlimit
.rlim_max
);
499 if (lttng_opt_fd_pool_size
== -1) {
500 /* Use default value (soft limit - reserve). */
501 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
502 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
503 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
507 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
508 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
512 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
513 ERR("File descriptor pool size must be set to at least %d",
514 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
519 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
520 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
521 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
526 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
527 lttng_opt_fd_pool_size
,
528 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
529 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
534 static int set_options(int argc
, char **argv
)
536 int c
, ret
= 0, option_index
= 0, retval
= 0;
537 int orig_optopt
= optopt
, orig_optind
= optind
;
538 char *default_address
, *optstring
;
539 char *config_path
= NULL
;
541 optstring
= utils_generate_optstring(long_options
,
542 sizeof(long_options
) / sizeof(struct option
));
548 /* Check for the --config option */
550 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
551 &option_index
)) != -1) {
555 } else if (c
!= 'f') {
559 if (lttng_is_setuid_setgid()) {
560 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
564 config_path
= utils_expand_path(optarg
);
566 ERR("Failed to resolve path: %s", optarg
);
571 ret
= config_get_section_entries(config_path
, config_section_name
,
572 config_entry_handler
, NULL
);
575 ERR("Invalid configuration option at line %i", ret
);
581 /* Reset getopt's global state */
582 optopt
= orig_optopt
;
583 optind
= orig_optind
;
585 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
590 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
597 /* assign default values */
598 if (control_uri
== NULL
) {
599 ret
= asprintf(&default_address
,
600 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
601 DEFAULT_NETWORK_CONTROL_PORT
);
603 PERROR("asprintf default data address");
608 ret
= uri_parse(default_address
, &control_uri
);
609 free(default_address
);
611 ERR("Invalid control URI specified");
616 if (data_uri
== NULL
) {
617 ret
= asprintf(&default_address
,
618 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
619 DEFAULT_NETWORK_DATA_PORT
);
621 PERROR("asprintf default data address");
626 ret
= uri_parse(default_address
, &data_uri
);
627 free(default_address
);
629 ERR("Invalid data URI specified");
634 if (live_uri
== NULL
) {
635 ret
= asprintf(&default_address
,
636 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
637 DEFAULT_NETWORK_VIEWER_PORT
);
639 PERROR("asprintf default viewer control address");
644 ret
= uri_parse(default_address
, &live_uri
);
645 free(default_address
);
647 ERR("Invalid viewer control URI specified");
652 ret
= set_fd_pool_size();
658 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
659 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
661 if (opt_allow_clear
) {
662 /* Check if env variable exists. */
663 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
665 ret
= config_parse_value(value
);
667 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
671 opt_allow_clear
= !ret
;
675 if (opt_allow_ctf2
) {
676 /* Check if env variable exists. */
677 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CTF2_ENV
);
679 ret
= config_parse_value(value
);
681 ERR("Invalid value for %s specified",
682 DEFAULT_LTTNG_RELAYD_DISALLOW_CTF2_ENV
);
686 opt_allow_ctf2
= !ret
;
696 static void print_global_objects(void)
698 print_viewer_streams();
699 print_relay_streams();
703 static int noop_close(void *data
__attribute__((unused
)),
704 int *fds
__attribute__((unused
)))
709 static void untrack_stdio(void)
711 int fds
[] = { fileno(stdout
), fileno(stderr
) };
714 * noop_close is used since we don't really want to close
715 * the stdio output fds; we merely want to stop tracking them.
717 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
718 fds
, 2, noop_close
, NULL
);
724 static void relayd_cleanup(void)
726 print_global_objects();
730 if (viewer_streams_ht
)
731 lttng_ht_destroy(viewer_streams_ht
);
732 if (relay_streams_ht
)
733 lttng_ht_destroy(relay_streams_ht
);
735 lttng_ht_destroy(sessions_ht
);
737 free(opt_output_path
);
738 free(opt_working_directory
);
741 health_app_destroy(health_relayd
);
743 /* Close thread quit pipes */
744 if (health_quit_pipe
[0] != -1) {
745 (void) fd_tracker_util_pipe_close(
746 the_fd_tracker
, health_quit_pipe
);
748 if (thread_quit_pipe
[0] != -1) {
749 (void) fd_tracker_util_pipe_close(
750 the_fd_tracker
, thread_quit_pipe
);
752 if (sessiond_trace_chunk_registry
) {
753 sessiond_trace_chunk_registry_destroy(
754 sessiond_trace_chunk_registry
);
756 if (the_fd_tracker
) {
759 * fd_tracker_destroy() will log the contents of the fd-tracker
760 * if a leak is detected.
762 fd_tracker_destroy(the_fd_tracker
);
765 uri_free(control_uri
);
767 /* Live URI is freed in the live thread. */
769 if (tracing_group_name_override
) {
770 free((void *) tracing_group_name
);
775 * Write to writable pipe used to notify a thread.
777 static int notify_thread_pipe(int wpipe
)
781 ret
= lttng_write(wpipe
, "!", 1);
783 PERROR("write poll pipe");
791 static int notify_health_quit_pipe(int *pipe
)
795 ret
= lttng_write(pipe
[1], "4", 1);
797 PERROR("write relay health quit");
806 * Stop all relayd and relayd-live threads.
808 int lttng_relay_stop_threads(void)
812 /* Stopping all threads */
813 DBG("Terminating all threads");
814 if (notify_thread_pipe(thread_quit_pipe
[1])) {
815 ERR("write error on thread quit pipe");
819 if (notify_health_quit_pipe(health_quit_pipe
)) {
820 ERR("write error on health quit pipe");
823 /* Dispatch thread */
824 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
825 futex_nto1_wake(&relay_conn_queue
.futex
);
827 if (relayd_live_stop()) {
828 ERR("Error stopping live threads");
835 * Signal handler for the daemon
837 * Simply stop all worker threads, leaving main() return gracefully after
838 * joining all threads and calling cleanup().
840 static void sighandler(int sig
)
844 DBG("SIGINT caught");
845 if (lttng_relay_stop_threads()) {
846 ERR("Error stopping threads");
850 DBG("SIGTERM caught");
851 if (lttng_relay_stop_threads()) {
852 ERR("Error stopping threads");
856 CMM_STORE_SHARED(recv_child_signal
, 1);
864 * Setup signal handler for :
865 * SIGINT, SIGTERM, SIGPIPE
867 static int set_signal_handler(void)
873 if ((ret
= sigemptyset(&sigset
)) < 0) {
874 PERROR("sigemptyset");
881 sa
.sa_handler
= sighandler
;
882 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
887 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
892 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
897 sa
.sa_handler
= SIG_IGN
;
898 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
903 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
908 void lttng_relay_notify_ready(void)
910 /* Notify the parent of the fork() process that we are ready. */
911 if (opt_daemon
|| opt_background
) {
912 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
913 kill(child_ppid
, SIGUSR1
);
919 * Init thread quit pipe.
921 * Return -1 on error or 0 if all pipes are created.
923 static int init_thread_quit_pipe(void)
925 return fd_tracker_util_pipe_open_cloexec(
926 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
930 * Init health quit pipe.
932 * Return -1 on error or 0 if all pipes are created.
934 static int init_health_quit_pipe(void)
936 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
937 "Health quit pipe", health_quit_pipe
);
941 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
943 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
944 int size
, const char *name
)
948 if (events
== NULL
|| size
== 0) {
953 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
954 name
, events
, 1, LTTNG_CLOEXEC
);
956 PERROR("Failed to create \"%s\" poll file descriptor", name
);
961 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
973 * Check if the thread quit pipe was triggered.
975 * Return 1 if it was triggered else 0;
977 static int check_thread_quit_pipe(int fd
, uint32_t events
)
979 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
986 static int create_sock(void *data
, int *out_fd
)
989 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
991 ret
= lttcomm_create_sock(sock
);
1001 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
1003 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
1005 return sock
->ops
->close(sock
);
1008 static int accept_sock(void *data
, int *out_fd
)
1011 /* Socks is an array of in_sock, out_sock. */
1012 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
1013 struct lttcomm_sock
*in_sock
= socks
[0];
1015 socks
[1] = in_sock
->ops
->accept(in_sock
);
1020 *out_fd
= socks
[1]->fd
;
1026 * Create and init socket from uri.
1028 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
1032 struct lttcomm_sock
*sock
= NULL
;
1033 char uri_str
[PATH_MAX
];
1034 char *formated_name
= NULL
;
1036 sock
= lttcomm_alloc_sock_from_uri(uri
);
1038 ERR("Allocating socket");
1043 * Don't fail to create the socket if the name can't be built as it is
1044 * only used for debugging purposes.
1046 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1047 uri_str
[sizeof(uri_str
) - 1] = '\0';
1049 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1052 formated_name
= NULL
;
1056 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1057 (const char **) (formated_name
? &formated_name
: NULL
),
1058 1, create_sock
, sock
);
1060 PERROR("Failed to open \"%s\" relay socket",
1061 formated_name
?: "Unknown");
1064 DBG("Listening on %s socket %d", name
, sock
->fd
);
1066 ret
= sock
->ops
->bind(sock
);
1068 PERROR("Failed to bind socket");
1072 ret
= sock
->ops
->listen(sock
, -1);
1078 free(formated_name
);
1083 lttcomm_destroy_sock(sock
);
1085 free(formated_name
);
1090 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1094 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1095 struct lttcomm_sock
*new_sock
= NULL
;
1097 ret
= fd_tracker_open_unsuspendable_fd(
1098 the_fd_tracker
, &out_fd
,
1099 (const char **) &name
,
1100 1, accept_sock
, &socks
);
1104 new_sock
= socks
[1];
1105 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1111 * This thread manages the listening for new connections on the network
1113 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1115 int i
, ret
, pollfd
, err
= -1;
1116 uint32_t revents
, nb_fd
;
1117 struct lttng_poll_event events
;
1118 struct lttcomm_sock
*control_sock
, *data_sock
;
1120 DBG("[thread] Relay listener started");
1122 rcu_register_thread();
1123 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1125 health_code_update();
1127 control_sock
= relay_socket_create(control_uri
, "Control listener");
1128 if (!control_sock
) {
1129 goto error_sock_control
;
1132 data_sock
= relay_socket_create(data_uri
, "Data listener");
1134 goto error_sock_relay
;
1138 * Pass 3 as size here for the thread quit pipe, control and
1141 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1143 goto error_create_poll
;
1146 /* Add the control socket */
1147 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1149 goto error_poll_add
;
1152 /* Add the data socket */
1153 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1155 goto error_poll_add
;
1158 lttng_relay_notify_ready();
1160 if (testpoint(relayd_thread_listener
)) {
1161 goto error_testpoint
;
1165 health_code_update();
1167 DBG("Listener accepting connections");
1170 health_poll_entry();
1171 ret
= lttng_poll_wait(&events
, -1);
1175 * Restart interrupted system call.
1177 if (errno
== EINTR
) {
1185 DBG("Relay new connection received");
1186 for (i
= 0; i
< nb_fd
; i
++) {
1187 health_code_update();
1189 /* Fetch once the poll data */
1190 revents
= LTTNG_POLL_GETEV(&events
, i
);
1191 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1193 /* Thread quit pipe has been closed. Killing thread. */
1194 ret
= check_thread_quit_pipe(pollfd
, revents
);
1200 if (revents
& LPOLLIN
) {
1202 * A new connection is requested, therefore a
1203 * sessiond/consumerd connection is allocated in
1204 * this thread, enqueued to a global queue and
1205 * dequeued (and freed) in the worker thread.
1208 struct relay_connection
*new_conn
;
1209 struct lttcomm_sock
*newsock
= NULL
;
1210 enum connection_type type
;
1212 if (pollfd
== data_sock
->fd
) {
1214 newsock
= accept_relayd_sock(data_sock
,
1215 "Data socket to relayd");
1217 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1218 type
= RELAY_CONTROL
;
1219 newsock
= accept_relayd_sock(control_sock
,
1220 "Control socket to relayd");
1223 PERROR("accepting sock");
1227 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1230 PERROR("setsockopt inet");
1231 lttcomm_destroy_sock(newsock
);
1235 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1237 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1239 lttcomm_destroy_sock(newsock
);
1243 new_conn
= connection_create(newsock
, type
);
1245 lttcomm_destroy_sock(newsock
);
1249 /* Enqueue request for the dispatcher thread. */
1250 cds_wfcq_head_ptr_t head
;
1251 head
.h
= &relay_conn_queue
.head
;
1252 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
,
1256 * Wake the dispatch queue futex.
1257 * Implicit memory barrier with the
1258 * exchange in cds_wfcq_enqueue.
1260 futex_nto1_wake(&relay_conn_queue
.futex
);
1261 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1262 ERR("socket poll error");
1265 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1275 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1277 if (data_sock
->fd
>= 0) {
1278 int data_sock_fd
= data_sock
->fd
;
1280 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1281 &data_sock_fd
, 1, close_sock
,
1284 PERROR("Failed to close the data listener socket file descriptor");
1288 lttcomm_destroy_sock(data_sock
);
1290 if (control_sock
->fd
>= 0) {
1291 int control_sock_fd
= control_sock
->fd
;
1293 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1294 &control_sock_fd
, 1, close_sock
,
1297 PERROR("Failed to close the control listener socket file descriptor");
1299 control_sock
->fd
= -1;
1301 lttcomm_destroy_sock(control_sock
);
1305 ERR("Health error occurred in %s", __func__
);
1307 health_unregister(health_relayd
);
1308 rcu_unregister_thread();
1309 DBG("Relay listener thread cleanup complete");
1310 lttng_relay_stop_threads();
1315 * This thread manages the dispatching of the requests to worker threads
1317 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1321 struct cds_wfcq_node
*node
;
1322 struct relay_connection
*new_conn
= NULL
;
1324 DBG("[thread] Relay dispatcher started");
1326 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1328 if (testpoint(relayd_thread_dispatcher
)) {
1329 goto error_testpoint
;
1332 health_code_update();
1335 health_code_update();
1337 /* Atomically prepare the queue futex */
1338 futex_nto1_prepare(&relay_conn_queue
.futex
);
1340 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1345 health_code_update();
1347 /* Dequeue commands */
1348 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1349 &relay_conn_queue
.tail
);
1351 DBG("Woken up but nothing in the relay command queue");
1352 /* Continue thread execution */
1355 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1357 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1360 * Inform worker thread of the new request. This
1361 * call is blocking so we can be assured that
1362 * the data will be read at some point in time
1363 * or wait to the end of the world :)
1365 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1367 PERROR("write connection pipe");
1368 connection_put(new_conn
);
1371 } while (node
!= NULL
);
1373 /* Futex wait on queue. Blocking call on futex() */
1374 health_poll_entry();
1375 futex_nto1_wait(&relay_conn_queue
.futex
);
1379 /* Normal exit, no error */
1386 ERR("Health error occurred in %s", __func__
);
1388 health_unregister(health_relayd
);
1389 DBG("Dispatch thread dying");
1390 lttng_relay_stop_threads();
1394 static bool session_streams_have_index(const struct relay_session
*session
)
1396 return session
->minor
>= 4 && !session
->snapshot
;
1400 * Handle the RELAYD_CREATE_SESSION command.
1402 * On success, send back the session id or else return a negative value.
1404 static int relay_create_session(
1405 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1406 struct relay_connection
*conn
,
1407 const struct lttng_buffer_view
*payload
)
1411 struct relay_session
*session
= NULL
;
1412 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1413 char session_name
[LTTNG_NAME_MAX
] = {};
1414 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1415 uint32_t live_timer
= 0;
1416 bool snapshot
= false;
1417 bool session_name_contains_creation_timestamp
= false;
1418 /* Left nil for peers < 2.11. */
1419 char base_path
[LTTNG_PATH_MAX
] = {};
1420 lttng_uuid sessiond_uuid
= {};
1421 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1422 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1423 LTTNG_OPTIONAL(time_t) creation_time
= {};
1424 struct lttng_dynamic_buffer reply_payload
;
1426 lttng_dynamic_buffer_init(&reply_payload
);
1428 if (conn
->minor
< 4) {
1429 /* From 2.1 to 2.3 */
1431 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1432 /* From 2.4 to 2.10 */
1433 ret
= cmd_create_session_2_4(payload
, session_name
,
1434 hostname
, &live_timer
, &snapshot
);
1436 bool has_current_chunk
;
1437 uint64_t current_chunk_id_value
;
1438 time_t creation_time_value
;
1439 uint64_t id_sessiond_value
;
1441 /* From 2.11 to ... */
1442 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1443 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1444 sessiond_uuid
, &has_current_chunk
,
1445 ¤t_chunk_id_value
, &creation_time_value
,
1446 &session_name_contains_creation_timestamp
);
1447 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1448 /* The nil UUID is reserved for pre-2.11 clients. */
1449 ERR("Illegal nil UUID announced by peer in create session command");
1453 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1454 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1455 if (has_current_chunk
) {
1456 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1457 current_chunk_id_value
);
1465 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1466 snapshot
, sessiond_uuid
,
1467 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1468 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1469 creation_time
.is_set
? &creation_time
.value
: NULL
,
1470 conn
->major
, conn
->minor
,
1471 session_name_contains_creation_timestamp
);
1476 LTTNG_ASSERT(!conn
->session
);
1477 conn
->session
= session
;
1478 DBG("Created session %" PRIu64
, session
->id
);
1480 reply
.generic
.session_id
= htobe64(session
->id
);
1484 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1486 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1489 if (conn
->minor
< 11) {
1490 /* From 2.1 to 2.10 */
1491 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1492 &reply
.generic
, sizeof(reply
.generic
));
1494 ERR("Failed to append \"create session\" command reply header to payload buffer");
1499 const uint32_t output_path_length
=
1500 session
? strlen(session
->output_path
) + 1 : 0;
1502 reply
.output_path_length
= htobe32(output_path_length
);
1503 ret
= lttng_dynamic_buffer_append(
1504 &reply_payload
, &reply
, sizeof(reply
));
1506 ERR("Failed to append \"create session\" command reply header to payload buffer");
1510 if (output_path_length
) {
1511 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1512 session
->output_path
,
1513 output_path_length
);
1515 ERR("Failed to append \"create session\" command reply path to payload buffer");
1521 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1522 reply_payload
.size
, 0);
1523 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1524 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1525 reply_payload
.size
, send_ret
);
1529 if (ret
< 0 && session
) {
1530 session_put(session
);
1532 lttng_dynamic_buffer_reset(&reply_payload
);
1537 * When we have received all the streams and the metadata for a channel,
1538 * we make them visible to the viewer threads.
1540 static void publish_connection_local_streams(struct relay_connection
*conn
)
1542 struct relay_stream
*stream
;
1543 struct relay_session
*session
= conn
->session
;
1546 * We publish all streams belonging to a session atomically wrt
1549 pthread_mutex_lock(&session
->lock
);
1551 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1553 stream_publish(stream
);
1558 * Inform the viewer that there are new streams in the session.
1560 if (session
->viewer_attached
) {
1561 uatomic_set(&session
->new_streams
, 1);
1563 pthread_mutex_unlock(&session
->lock
);
1566 static int conform_channel_path(char *channel_path
)
1570 if (strstr("../", channel_path
)) {
1571 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1577 if (*channel_path
== '/') {
1578 const size_t len
= strlen(channel_path
);
1581 * Channel paths from peers prior to 2.11 are expressed as an
1582 * absolute path that is, in reality, relative to the relay
1583 * daemon's output directory. Remove the leading slash so it
1584 * is correctly interpreted as a relative path later on.
1586 * len (and not len - 1) is used to copy the trailing NULL.
1588 bcopy(channel_path
+ 1, channel_path
, len
);
1595 * relay_add_stream: allocate a new stream for a session
1597 static int relay_add_stream(
1598 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1599 struct relay_connection
*conn
,
1600 const struct lttng_buffer_view
*payload
)
1604 struct relay_session
*session
= conn
->session
;
1605 struct relay_stream
*stream
= NULL
;
1606 struct lttcomm_relayd_status_stream reply
;
1607 struct ctf_trace
*trace
= NULL
;
1608 uint64_t stream_handle
= -1ULL;
1609 char *path_name
= NULL
, *channel_name
= NULL
;
1610 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1611 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1613 if (!session
|| !conn
->version_check_done
) {
1614 ERR("Trying to add a stream before version check");
1616 goto end_no_session
;
1619 if (session
->minor
== 1) {
1621 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1623 } else if (session
->minor
> 1 && session
->minor
< 11) {
1624 /* From 2.2 to 2.10 */
1625 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1626 &channel_name
, &tracefile_size
, &tracefile_count
);
1628 /* From 2.11 to ... */
1629 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1630 &channel_name
, &tracefile_size
, &tracefile_count
,
1631 &stream_chunk_id
.value
);
1632 stream_chunk_id
.is_set
= true;
1639 if (conform_channel_path(path_name
)) {
1644 * Backward compatibility for --group-output-by-session.
1645 * Prior to lttng 2.11, the complete path is passed by the stream.
1646 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1647 * >=2.11 the chunk is responsible for the output path. When dealing
1648 * with producer < 2.11 the chunk output_path is the root output path
1649 * and the stream carries the complete path (path_name).
1650 * To support --group-output-by-session with older producer (<2.11), we
1651 * need to craft the path based on the stream path.
1653 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1654 if (conn
->minor
< 4) {
1656 * From 2.1 to 2.3, the session_name is not passed on
1657 * the RELAYD_CREATE_SESSION command. The session name
1658 * is necessary to detect the presence of a base_path
1659 * inside the stream path. Without it we cannot perform
1660 * a valid group-output-by-session transformation.
1662 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1663 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1664 session
->id
, path_name
);
1665 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1666 char *group_by_session_path_name
;
1668 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1670 group_by_session_path_name
=
1671 backward_compat_group_by_session(
1673 session
->session_name
,
1674 session
->creation_time
.value
);
1675 if (!group_by_session_path_name
) {
1676 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1681 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1682 path_name
, group_by_session_path_name
);
1685 path_name
= group_by_session_path_name
;
1689 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1694 /* This stream here has one reference on the trace. */
1695 pthread_mutex_lock(&last_relay_stream_id_lock
);
1696 stream_handle
= ++last_relay_stream_id
;
1697 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1699 /* We pass ownership of path_name and channel_name. */
1700 stream
= stream_create(trace
, stream_handle
, path_name
,
1701 channel_name
, tracefile_size
, tracefile_count
);
1703 channel_name
= NULL
;
1706 * Streams are the owners of their trace. Reference to trace is
1707 * kept within stream_create().
1709 ctf_trace_put(trace
);
1712 memset(&reply
, 0, sizeof(reply
));
1713 reply
.handle
= htobe64(stream_handle
);
1715 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1717 reply
.ret_code
= htobe32(LTTNG_OK
);
1720 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1721 sizeof(struct lttcomm_relayd_status_stream
), 0);
1722 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1723 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1735 * relay_close_stream: close a specific stream
1737 static int relay_close_stream(
1738 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1739 struct relay_connection
*conn
,
1740 const struct lttng_buffer_view
*payload
)
1744 struct relay_session
*session
= conn
->session
;
1745 struct lttcomm_relayd_close_stream stream_info
;
1746 struct lttcomm_relayd_generic_reply reply
;
1747 struct relay_stream
*stream
;
1749 DBG("Close stream received");
1751 if (!session
|| !conn
->version_check_done
) {
1752 ERR("Trying to close a stream before version check");
1754 goto end_no_session
;
1757 if (payload
->size
< sizeof(stream_info
)) {
1758 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1759 sizeof(stream_info
), payload
->size
);
1761 goto end_no_session
;
1763 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1764 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1765 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1767 stream
= stream_get_by_id(stream_info
.stream_id
);
1774 * Set last_net_seq_num before the close flag. Required by data
1777 pthread_mutex_lock(&stream
->lock
);
1778 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1779 pthread_mutex_unlock(&stream
->lock
);
1782 * This is one of the conditions which may trigger a stream close
1783 * with the others being:
1784 * 1) A close command is received for a stream
1785 * 2) The control connection owning the stream is closed
1786 * 3) We have received all of the stream's data _after_ a close
1789 try_stream_close(stream
);
1794 memset(&reply
, 0, sizeof(reply
));
1796 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1798 reply
.ret_code
= htobe32(LTTNG_OK
);
1800 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1801 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1802 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1803 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1813 * relay_reset_metadata: reset a metadata stream
1816 int relay_reset_metadata(
1817 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1818 struct relay_connection
*conn
,
1819 const struct lttng_buffer_view
*payload
)
1823 struct relay_session
*session
= conn
->session
;
1824 struct lttcomm_relayd_reset_metadata stream_info
;
1825 struct lttcomm_relayd_generic_reply reply
;
1826 struct relay_stream
*stream
;
1828 DBG("Reset metadata received");
1830 if (!session
|| !conn
->version_check_done
) {
1831 ERR("Trying to reset a metadata stream before version check");
1833 goto end_no_session
;
1836 if (payload
->size
< sizeof(stream_info
)) {
1837 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1838 sizeof(stream_info
), payload
->size
);
1840 goto end_no_session
;
1842 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1843 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1844 stream_info
.version
= be64toh(stream_info
.version
);
1846 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1848 /* Unsupported for live sessions for now. */
1849 if (session
->live_timer
!= 0) {
1854 stream
= stream_get_by_id(stream_info
.stream_id
);
1859 pthread_mutex_lock(&stream
->lock
);
1860 if (!stream
->is_metadata
) {
1865 ret
= stream_reset_file(stream
);
1867 ERR("Failed to reset metadata stream %" PRIu64
1868 ": stream_path = %s, channel = %s",
1869 stream
->stream_handle
, stream
->path_name
,
1870 stream
->channel_name
);
1874 pthread_mutex_unlock(&stream
->lock
);
1878 memset(&reply
, 0, sizeof(reply
));
1880 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1882 reply
.ret_code
= htobe32(LTTNG_OK
);
1884 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1885 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1886 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1887 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1897 * relay_unknown_command: send -1 if received unknown command
1899 static void relay_unknown_command(struct relay_connection
*conn
)
1901 struct lttcomm_relayd_generic_reply reply
;
1904 memset(&reply
, 0, sizeof(reply
));
1905 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1906 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1907 if (send_ret
< sizeof(reply
)) {
1908 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1913 * relay_start: send an acknowledgment to the client to tell if we are
1914 * ready to receive data. We are ready if a session is established.
1916 static int relay_start(
1917 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1918 struct relay_connection
*conn
,
1919 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1923 struct lttcomm_relayd_generic_reply reply
;
1924 struct relay_session
*session
= conn
->session
;
1927 DBG("Trying to start the streaming without a session established");
1928 ret
= htobe32(LTTNG_ERR_UNK
);
1931 memset(&reply
, 0, sizeof(reply
));
1932 reply
.ret_code
= htobe32(LTTNG_OK
);
1933 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1935 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1936 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1945 * relay_recv_metadata: receive the metadata for the session.
1947 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1948 struct relay_connection
*conn
,
1949 const struct lttng_buffer_view
*payload
)
1952 struct relay_session
*session
= conn
->session
;
1953 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1954 struct relay_stream
*metadata_stream
;
1955 uint64_t metadata_payload_size
;
1956 struct lttng_buffer_view packet_view
;
1959 ERR("Metadata sent before version check");
1964 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1965 ERR("Incorrect data size");
1969 metadata_payload_size
= recv_hdr
->data_size
-
1970 sizeof(struct lttcomm_relayd_metadata_payload
);
1972 memcpy(&metadata_payload_header
, payload
->data
,
1973 sizeof(metadata_payload_header
));
1974 metadata_payload_header
.stream_id
= be64toh(
1975 metadata_payload_header
.stream_id
);
1976 metadata_payload_header
.padding_size
= be32toh(
1977 metadata_payload_header
.padding_size
);
1979 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1980 if (!metadata_stream
) {
1985 packet_view
= lttng_buffer_view_from_view(payload
,
1986 sizeof(metadata_payload_header
), metadata_payload_size
);
1987 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1988 ERR("Invalid metadata packet length announced by header");
1993 pthread_mutex_lock(&metadata_stream
->lock
);
1994 ret
= stream_write(metadata_stream
, &packet_view
,
1995 metadata_payload_header
.padding_size
);
1996 pthread_mutex_unlock(&metadata_stream
->lock
);
2002 stream_put(metadata_stream
);
2008 * relay_send_version: send relayd version number
2010 static int relay_send_version(
2011 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2012 struct relay_connection
*conn
,
2013 const struct lttng_buffer_view
*payload
)
2017 struct lttcomm_relayd_version reply
, msg
;
2018 bool compatible
= true;
2020 conn
->version_check_done
= true;
2022 /* Get version from the other side. */
2023 if (payload
->size
< sizeof(msg
)) {
2024 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2025 sizeof(msg
), payload
->size
);
2030 memcpy(&msg
, payload
->data
, sizeof(msg
));
2031 msg
.major
= be32toh(msg
.major
);
2032 msg
.minor
= be32toh(msg
.minor
);
2034 memset(&reply
, 0, sizeof(reply
));
2035 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2036 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2038 /* Major versions must be the same */
2039 if (reply
.major
!= msg
.major
) {
2040 DBG("Incompatible major versions (%u vs %u), deleting session",
2041 reply
.major
, msg
.major
);
2045 conn
->major
= reply
.major
;
2046 /* We adapt to the lowest compatible version */
2047 if (reply
.minor
<= msg
.minor
) {
2048 conn
->minor
= reply
.minor
;
2050 conn
->minor
= msg
.minor
;
2053 reply
.major
= htobe32(reply
.major
);
2054 reply
.minor
= htobe32(reply
.minor
);
2055 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2057 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2058 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2071 DBG("Version check done using protocol %u.%u", conn
->major
,
2079 * Check for data pending for a given stream id from the session daemon.
2081 static int relay_data_pending(
2082 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2083 struct relay_connection
*conn
,
2084 const struct lttng_buffer_view
*payload
)
2086 struct relay_session
*session
= conn
->session
;
2087 struct lttcomm_relayd_data_pending msg
;
2088 struct lttcomm_relayd_generic_reply reply
;
2089 struct relay_stream
*stream
;
2092 uint64_t stream_seq
;
2094 DBG("Data pending command received");
2096 if (!session
|| !conn
->version_check_done
) {
2097 ERR("Trying to check for data before version check");
2099 goto end_no_session
;
2102 if (payload
->size
< sizeof(msg
)) {
2103 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2104 sizeof(msg
), payload
->size
);
2106 goto end_no_session
;
2108 memcpy(&msg
, payload
->data
, sizeof(msg
));
2109 msg
.stream_id
= be64toh(msg
.stream_id
);
2110 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2112 stream
= stream_get_by_id(msg
.stream_id
);
2113 if (stream
== NULL
) {
2118 pthread_mutex_lock(&stream
->lock
);
2120 if (session_streams_have_index(session
)) {
2122 * Ensure that both the index and stream data have been
2123 * flushed up to the requested point.
2125 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2127 stream_seq
= stream
->prev_data_seq
;
2129 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2130 ", prev_index_seq %" PRIu64
2131 ", and last_seq %" PRIu64
, msg
.stream_id
,
2132 stream
->prev_data_seq
, stream
->prev_index_seq
,
2133 msg
.last_net_seq_num
);
2135 /* Avoid wrapping issue */
2136 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2137 /* Data has in fact been written and is NOT pending */
2140 /* Data still being streamed thus pending */
2144 stream
->data_pending_check_done
= true;
2145 pthread_mutex_unlock(&stream
->lock
);
2150 memset(&reply
, 0, sizeof(reply
));
2151 reply
.ret_code
= htobe32(ret
);
2152 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2153 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2154 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2164 * Wait for the control socket to reach a quiescent state.
2166 * Note that for now, when receiving this command from the session
2167 * daemon, this means that every subsequent commands or data received on
2168 * the control socket has been handled. So, this is why we simply return
2171 static int relay_quiescent_control(
2172 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2173 struct relay_connection
*conn
,
2174 const struct lttng_buffer_view
*payload
)
2178 struct relay_stream
*stream
;
2179 struct lttcomm_relayd_quiescent_control msg
;
2180 struct lttcomm_relayd_generic_reply reply
;
2182 DBG("Checking quiescent state on control socket");
2184 if (!conn
->session
|| !conn
->version_check_done
) {
2185 ERR("Trying to check for data before version check");
2187 goto end_no_session
;
2190 if (payload
->size
< sizeof(msg
)) {
2191 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2192 sizeof(msg
), payload
->size
);
2194 goto end_no_session
;
2196 memcpy(&msg
, payload
->data
, sizeof(msg
));
2197 msg
.stream_id
= be64toh(msg
.stream_id
);
2199 stream
= stream_get_by_id(msg
.stream_id
);
2203 pthread_mutex_lock(&stream
->lock
);
2204 stream
->data_pending_check_done
= true;
2205 pthread_mutex_unlock(&stream
->lock
);
2207 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2210 memset(&reply
, 0, sizeof(reply
));
2211 reply
.ret_code
= htobe32(LTTNG_OK
);
2212 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2213 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2214 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2226 * Initialize a data pending command. This means that a consumer is about
2227 * to ask for data pending for each stream it holds. Simply iterate over
2228 * all streams of a session and set the data_pending_check_done flag.
2230 * This command returns to the client a LTTNG_OK code.
2232 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2233 struct relay_connection
*conn
,
2234 const struct lttng_buffer_view
*payload
)
2238 struct lttng_ht_iter iter
;
2239 struct lttcomm_relayd_begin_data_pending msg
;
2240 struct lttcomm_relayd_generic_reply reply
;
2241 struct relay_stream
*stream
;
2243 LTTNG_ASSERT(recv_hdr
);
2246 DBG("Init streams for data pending");
2248 if (!conn
->session
|| !conn
->version_check_done
) {
2249 ERR("Trying to check for data before version check");
2251 goto end_no_session
;
2254 if (payload
->size
< sizeof(msg
)) {
2255 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2256 sizeof(msg
), payload
->size
);
2258 goto end_no_session
;
2260 memcpy(&msg
, payload
->data
, sizeof(msg
));
2261 msg
.session_id
= be64toh(msg
.session_id
);
2264 * Iterate over all streams to set the begin data pending flag.
2265 * For now, the streams are indexed by stream handle so we have
2266 * to iterate over all streams to find the one associated with
2267 * the right session_id.
2270 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2272 if (!stream_get(stream
)) {
2275 if (stream
->trace
->session
->id
== msg
.session_id
) {
2276 pthread_mutex_lock(&stream
->lock
);
2277 stream
->data_pending_check_done
= false;
2278 pthread_mutex_unlock(&stream
->lock
);
2279 DBG("Set begin data pending flag to stream %" PRIu64
,
2280 stream
->stream_handle
);
2286 memset(&reply
, 0, sizeof(reply
));
2287 /* All good, send back reply. */
2288 reply
.ret_code
= htobe32(LTTNG_OK
);
2290 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2291 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2292 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2304 * End data pending command. This will check, for a given session id, if
2305 * each stream associated with it has its data_pending_check_done flag
2306 * set. If not, this means that the client lost track of the stream but
2307 * the data is still being streamed on our side. In this case, we inform
2308 * the client that data is in flight.
2310 * Return to the client if there is data in flight or not with a ret_code.
2312 static int relay_end_data_pending(
2313 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2314 struct relay_connection
*conn
,
2315 const struct lttng_buffer_view
*payload
)
2319 struct lttng_ht_iter iter
;
2320 struct lttcomm_relayd_end_data_pending msg
;
2321 struct lttcomm_relayd_generic_reply reply
;
2322 struct relay_stream
*stream
;
2323 uint32_t is_data_inflight
= 0;
2325 DBG("End data pending command");
2327 if (!conn
->session
|| !conn
->version_check_done
) {
2328 ERR("Trying to check for data before version check");
2330 goto end_no_session
;
2333 if (payload
->size
< sizeof(msg
)) {
2334 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2335 sizeof(msg
), payload
->size
);
2337 goto end_no_session
;
2339 memcpy(&msg
, payload
->data
, sizeof(msg
));
2340 msg
.session_id
= be64toh(msg
.session_id
);
2343 * Iterate over all streams to see if the begin data pending
2347 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2349 if (!stream_get(stream
)) {
2352 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2356 pthread_mutex_lock(&stream
->lock
);
2357 if (!stream
->data_pending_check_done
) {
2358 uint64_t stream_seq
;
2360 if (session_streams_have_index(conn
->session
)) {
2362 * Ensure that both the index and stream data have been
2363 * flushed up to the requested point.
2365 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2367 stream_seq
= stream
->prev_data_seq
;
2369 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2370 is_data_inflight
= 1;
2371 DBG("Data is still in flight for stream %" PRIu64
,
2372 stream
->stream_handle
);
2373 pthread_mutex_unlock(&stream
->lock
);
2378 pthread_mutex_unlock(&stream
->lock
);
2383 memset(&reply
, 0, sizeof(reply
));
2384 /* All good, send back reply. */
2385 reply
.ret_code
= htobe32(is_data_inflight
);
2387 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2388 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2389 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2401 * Receive an index for a specific stream.
2403 * Return 0 on success else a negative value.
2405 static int relay_recv_index(
2406 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2407 struct relay_connection
*conn
,
2408 const struct lttng_buffer_view
*payload
)
2412 struct relay_session
*session
= conn
->session
;
2413 struct lttcomm_relayd_index index_info
;
2414 struct lttcomm_relayd_generic_reply reply
;
2415 struct relay_stream
*stream
;
2420 DBG("Relay receiving index");
2422 if (!session
|| !conn
->version_check_done
) {
2423 ERR("Trying to close a stream before version check");
2425 goto end_no_session
;
2428 msg_len
= lttcomm_relayd_index_len(
2429 lttng_to_index_major(conn
->major
, conn
->minor
),
2430 lttng_to_index_minor(conn
->major
, conn
->minor
));
2431 if (payload
->size
< msg_len
) {
2432 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2433 msg_len
, payload
->size
);
2435 goto end_no_session
;
2437 memcpy(&index_info
, payload
->data
, msg_len
);
2438 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2439 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2440 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2441 index_info
.content_size
= be64toh(index_info
.content_size
);
2442 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2443 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2444 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2445 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2447 if (conn
->minor
>= 8) {
2448 index_info
.stream_instance_id
=
2449 be64toh(index_info
.stream_instance_id
);
2450 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2452 index_info
.stream_instance_id
= -1ULL;
2453 index_info
.packet_seq_num
= -1ULL;
2456 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2458 ERR("stream_get_by_id not found");
2463 pthread_mutex_lock(&stream
->lock
);
2464 ret
= stream_add_index(stream
, &index_info
);
2465 pthread_mutex_unlock(&stream
->lock
);
2467 goto end_stream_put
;
2473 memset(&reply
, 0, sizeof(reply
));
2475 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2477 reply
.ret_code
= htobe32(LTTNG_OK
);
2479 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2480 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2481 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2490 * Receive the streams_sent message.
2492 * Return 0 on success else a negative value.
2494 static int relay_streams_sent(
2495 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2496 struct relay_connection
*conn
,
2497 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2501 struct lttcomm_relayd_generic_reply reply
;
2505 DBG("Relay receiving streams_sent");
2507 if (!conn
->session
|| !conn
->version_check_done
) {
2508 ERR("Trying to close a stream before version check");
2510 goto end_no_session
;
2514 * Publish every pending stream in the connection recv list which are
2515 * now ready to be used by the viewer.
2517 publish_connection_local_streams(conn
);
2519 memset(&reply
, 0, sizeof(reply
));
2520 reply
.ret_code
= htobe32(LTTNG_OK
);
2521 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2522 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2523 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2535 static ssize_t
relay_unpack_rotate_streams_header(
2536 const struct lttng_buffer_view
*payload
,
2537 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2539 struct lttcomm_relayd_rotate_streams rotate_streams
;
2541 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2542 * This is the smallest version of this structure, but it can be larger;
2543 * this variable is updated once the proper size of the structure is known.
2545 * See comment at the declaration of this structure for more information.
2547 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2548 size_t expected_payload_size_no_padding
,
2549 expected_payload_size_3_bytes_padding
,
2550 expected_payload_size_7_bytes_padding
;
2552 if (payload
->size
< header_len
) {
2553 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2554 header_len
, payload
->size
);
2559 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2560 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2562 * We start by "unpacking" `stream_count` to figure out the padding length
2563 * emited by our peer.
2566 decltype(rotate_streams
.stream_count
) stream_count
;
2568 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2569 rotate_streams
.stream_count
= be32toh(stream_count
);
2572 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2575 * Payload size expected given the possible padding lengths in
2576 * `struct lttcomm_relayd_rotate_streams`.
2578 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2579 sizeof(*rotate_streams
.rotation_positions
)) +
2580 sizeof(lttcomm_relayd_rotate_streams_packed
);
2581 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2582 sizeof(*rotate_streams
.rotation_positions
)) +
2583 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2584 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2585 sizeof(*rotate_streams
.rotation_positions
)) +
2586 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2588 if (payload
->size
== expected_payload_size_no_padding
) {
2589 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2592 * This handles cases where someone might build with
2593 * -fpack-struct or any other toolchain that wouldn't produce
2594 * padding to align `value`.
2596 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2598 header_len
= sizeof(packed_rotate_streams
);
2599 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2601 /* Unpack the packed structure to the natively-packed version. */
2602 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2603 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2604 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2606 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2607 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2608 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2610 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2612 header_len
= sizeof(padded_rotate_streams
);
2613 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2615 /* Unpack the 3-byte padded structure to the natively-packed version. */
2616 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2617 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2618 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2620 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2621 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2622 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2624 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2626 header_len
= sizeof(padded_rotate_streams
);
2627 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2629 /* Unpack the 7-byte padded structure to the natively-packed version. */
2630 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2631 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2632 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2634 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2636 header_len
= sizeof(padded_rotate_streams
);
2638 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2639 expected_payload_size_no_padding
,
2640 expected_payload_size_3_bytes_padding
,
2641 expected_payload_size_7_bytes_padding
,
2652 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2653 * session rotation feature (not the tracefile rotation feature).
2655 static int relay_rotate_session_streams(
2656 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2657 struct relay_connection
*conn
,
2658 const struct lttng_buffer_view
*payload
)
2663 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2664 struct relay_session
*session
= conn
->session
;
2665 struct lttcomm_relayd_rotate_streams rotate_streams
;
2666 struct lttcomm_relayd_generic_reply reply
= {};
2667 struct relay_stream
*stream
= NULL
;
2668 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2669 struct lttng_buffer_view stream_positions
;
2670 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2671 const char *chunk_id_str
= "none";
2674 if (!session
|| !conn
->version_check_done
) {
2675 ERR("Trying to rotate a stream before version check");
2680 if (session
->major
== 2 && session
->minor
< 11) {
2681 ERR("Unsupported feature before 2.11");
2686 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2687 if (header_len
< 0) {
2692 if (rotate_streams
.new_chunk_id
.is_set
) {
2694 * Retrieve the trace chunk the stream must transition to. As
2695 * per the protocol, this chunk should have been created
2696 * before this command is received.
2698 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2699 sessiond_trace_chunk_registry
,
2700 session
->sessiond_uuid
,
2701 conn
->session
->id_sessiond
.is_set
?
2702 conn
->session
->id_sessiond
.value
:
2704 rotate_streams
.new_chunk_id
.value
);
2705 if (!next_trace_chunk
) {
2706 char uuid_str
[LTTNG_UUID_STR_LEN
];
2708 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2709 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2710 ", trace_chunk_id = %" PRIu64
,
2711 uuid_str
, session
->id
,
2712 rotate_streams
.new_chunk_id
.value
);
2713 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2718 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2719 rotate_streams
.new_chunk_id
.value
);
2720 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2721 chunk_id_str
= "formatting error";
2723 chunk_id_str
= chunk_id_buf
;
2727 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2728 rotate_streams
.stream_count
, session
->session_name
,
2731 stream_positions
= lttng_buffer_view_from_view(payload
,
2733 if (!stream_positions
.data
||
2734 stream_positions
.size
<
2735 (rotate_streams
.stream_count
*
2736 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2737 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2742 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2743 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2744 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2745 const struct lttcomm_relayd_stream_rotation_position pos
= {
2746 .stream_id
= be64toh(position_comm
->stream_id
),
2747 .rotate_at_seq_num
= be64toh(
2748 position_comm
->rotate_at_seq_num
),
2751 stream
= stream_get_by_id(pos
.stream_id
);
2753 reply_code
= LTTNG_ERR_INVALID
;
2758 pthread_mutex_lock(&stream
->lock
);
2759 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2760 pos
.rotate_at_seq_num
);
2761 pthread_mutex_unlock(&stream
->lock
);
2763 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2771 reply_code
= LTTNG_OK
;
2778 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2779 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2780 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2781 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2782 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2787 lttng_trace_chunk_put(next_trace_chunk
);
2792 * relay_create_trace_chunk: create a new trace chunk
2794 static int relay_create_trace_chunk(
2795 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2796 struct relay_connection
*conn
,
2797 const struct lttng_buffer_view
*payload
)
2801 struct relay_session
*session
= conn
->session
;
2802 struct lttcomm_relayd_create_trace_chunk
*msg
;
2803 struct lttcomm_relayd_generic_reply reply
= {};
2804 struct lttng_buffer_view header_view
;
2805 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2806 enum lttng_error_code reply_code
= LTTNG_OK
;
2807 enum lttng_trace_chunk_status chunk_status
;
2808 const char *new_path
;
2810 if (!session
|| !conn
->version_check_done
) {
2811 ERR("Trying to create a trace chunk before version check");
2816 if (session
->major
== 2 && session
->minor
< 11) {
2817 ERR("Chunk creation command is unsupported before 2.11");
2822 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2823 if (!lttng_buffer_view_is_valid(&header_view
)) {
2824 ERR("Failed to receive payload of chunk creation command");
2829 /* Convert to host endianness. */
2830 msg
= (typeof(msg
)) header_view
.data
;
2831 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2832 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2833 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2835 pthread_mutex_lock(&conn
->session
->lock
);
2836 session
->ongoing_rotation
= true;
2837 if (session
->current_trace_chunk
&&
2838 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2839 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2840 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2841 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2842 ERR("Failed to rename old chunk");
2844 reply_code
= LTTNG_ERR_UNK
;
2848 if (!session
->current_trace_chunk
) {
2849 if (!session
->has_rotated
) {
2855 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2857 chunk
= lttng_trace_chunk_create(
2858 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2860 ERR("Failed to create trace chunk in trace chunk creation command");
2862 reply_code
= LTTNG_ERR_NOMEM
;
2865 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2867 if (msg
->override_name_length
) {
2869 const struct lttng_buffer_view chunk_name_view
=
2870 lttng_buffer_view_from_view(payload
,
2872 msg
->override_name_length
);
2874 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2875 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2877 reply_code
= LTTNG_ERR_INVALID
;
2881 name
= chunk_name_view
.data
;
2882 if (name
[msg
->override_name_length
- 1]) {
2883 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2885 reply_code
= LTTNG_ERR_INVALID
;
2889 chunk_status
= lttng_trace_chunk_override_name(
2890 chunk
, chunk_name_view
.data
);
2891 switch (chunk_status
) {
2892 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2894 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2895 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2896 reply_code
= LTTNG_ERR_INVALID
;
2900 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2901 reply_code
= LTTNG_ERR_UNK
;
2907 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2908 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2909 reply_code
= LTTNG_ERR_UNK
;
2914 LTTNG_ASSERT(conn
->session
->output_directory
);
2915 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2916 conn
->session
->output_directory
);
2917 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2918 reply_code
= LTTNG_ERR_UNK
;
2923 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2924 sessiond_trace_chunk_registry
,
2925 conn
->session
->sessiond_uuid
,
2926 conn
->session
->id_sessiond
.is_set
?
2927 conn
->session
->id_sessiond
.value
:
2930 if (!published_chunk
) {
2931 char uuid_str
[LTTNG_UUID_STR_LEN
];
2933 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2934 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2939 reply_code
= LTTNG_ERR_NOMEM
;
2943 if (conn
->session
->pending_closure_trace_chunk
) {
2945 * Invalid; this means a second create_trace_chunk command was
2946 * received before a close_trace_chunk.
2948 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2949 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2953 conn
->session
->pending_closure_trace_chunk
=
2954 conn
->session
->current_trace_chunk
;
2955 conn
->session
->current_trace_chunk
= published_chunk
;
2956 published_chunk
= NULL
;
2957 if (!conn
->session
->pending_closure_trace_chunk
) {
2958 session
->ongoing_rotation
= false;
2961 pthread_mutex_unlock(&conn
->session
->lock
);
2962 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2963 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2965 sizeof(struct lttcomm_relayd_generic_reply
),
2967 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2968 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2973 lttng_trace_chunk_put(chunk
);
2974 lttng_trace_chunk_put(published_chunk
);
2979 * relay_close_trace_chunk: close a trace chunk
2981 static int relay_close_trace_chunk(
2982 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2983 struct relay_connection
*conn
,
2984 const struct lttng_buffer_view
*payload
)
2986 int ret
= 0, buf_ret
;
2988 struct relay_session
*session
= conn
->session
;
2989 struct lttcomm_relayd_close_trace_chunk
*msg
;
2990 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2991 struct lttng_buffer_view header_view
;
2992 struct lttng_trace_chunk
*chunk
= NULL
;
2993 enum lttng_error_code reply_code
= LTTNG_OK
;
2994 enum lttng_trace_chunk_status chunk_status
;
2996 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2997 time_t close_timestamp
;
2998 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2999 size_t path_length
= 0;
3000 const char *chunk_name
= NULL
;
3001 struct lttng_dynamic_buffer reply_payload
;
3002 const char *new_path
;
3004 lttng_dynamic_buffer_init(&reply_payload
);
3006 if (!session
|| !conn
->version_check_done
) {
3007 ERR("Trying to close a trace chunk before version check");
3012 if (session
->major
== 2 && session
->minor
< 11) {
3013 ERR("Chunk close command is unsupported before 2.11");
3018 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3019 if (!lttng_buffer_view_is_valid(&header_view
)) {
3020 ERR("Failed to receive payload of chunk close command");
3025 /* Convert to host endianness. */
3026 msg
= (typeof(msg
)) header_view
.data
;
3027 chunk_id
= be64toh(msg
->chunk_id
);
3028 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
3029 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
3030 close_command
.is_set
= msg
->close_command
.is_set
;
3032 chunk
= sessiond_trace_chunk_registry_get_chunk(
3033 sessiond_trace_chunk_registry
,
3034 conn
->session
->sessiond_uuid
,
3035 conn
->session
->id_sessiond
.is_set
?
3036 conn
->session
->id_sessiond
.value
:
3040 char uuid_str
[LTTNG_UUID_STR_LEN
];
3042 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3043 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
3048 reply_code
= LTTNG_ERR_NOMEM
;
3052 pthread_mutex_lock(&session
->lock
);
3053 if (close_command
.is_set
&&
3054 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3056 * Clear command. It is a protocol error to ask for a
3057 * clear on a relay which does not allow it. Querying
3058 * the configuration allows figuring out whether
3059 * clearing is allowed before doing the clear.
3061 if (!opt_allow_clear
) {
3063 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3064 goto end_unlock_session
;
3067 if (session
->pending_closure_trace_chunk
&&
3068 session
->pending_closure_trace_chunk
!= chunk
) {
3069 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3070 session
->session_name
);
3071 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3073 goto end_unlock_session
;
3076 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3077 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3078 if (close_command
.is_set
&&
3079 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3080 !session
->has_rotated
) {
3081 /* New chunk stays in session output directory. */
3084 /* Use chunk name for new chunk. */
3087 /* Rename new chunk path. */
3088 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3090 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3092 goto end_unlock_session
;
3094 session
->ongoing_rotation
= false;
3096 if ((!close_command
.is_set
||
3097 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3098 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3099 const char *old_path
;
3101 if (!session
->has_rotated
) {
3106 /* We need to move back the .tmp_old_chunk to its rightful place. */
3107 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3108 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3110 goto end_unlock_session
;
3113 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3114 chunk
, close_timestamp
);
3115 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3116 ERR("Failed to set trace chunk close timestamp");
3118 reply_code
= LTTNG_ERR_UNK
;
3119 goto end_unlock_session
;
3122 if (close_command
.is_set
) {
3123 chunk_status
= lttng_trace_chunk_set_close_command(
3124 chunk
, close_command
.value
);
3125 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3127 reply_code
= LTTNG_ERR_INVALID
;
3128 goto end_unlock_session
;
3131 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3132 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3133 ERR("Failed to get chunk name");
3135 reply_code
= LTTNG_ERR_UNK
;
3136 goto end_unlock_session
;
3138 if (!session
->has_rotated
&& !session
->snapshot
) {
3139 ret
= lttng_strncpy(closed_trace_chunk_path
,
3140 session
->output_path
,
3141 sizeof(closed_trace_chunk_path
));
3143 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3144 strlen(session
->output_path
),
3145 sizeof(closed_trace_chunk_path
));
3146 reply_code
= LTTNG_ERR_NOMEM
;
3148 goto end_unlock_session
;
3151 if (session
->snapshot
) {
3152 ret
= snprintf(closed_trace_chunk_path
,
3153 sizeof(closed_trace_chunk_path
),
3154 "%s/%s", session
->output_path
,
3157 ret
= snprintf(closed_trace_chunk_path
,
3158 sizeof(closed_trace_chunk_path
),
3159 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3161 session
->output_path
, chunk_name
);
3163 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3164 ERR("Failed to format closed trace chunk resulting path");
3165 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3167 goto end_unlock_session
;
3170 if (close_command
.is_set
&&
3171 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3172 session
->has_rotated
= true;
3174 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3175 path_length
= strlen(closed_trace_chunk_path
) + 1;
3176 if (path_length
> UINT32_MAX
) {
3177 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3179 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3180 goto end_unlock_session
;
3183 if (session
->current_trace_chunk
== chunk
) {
3185 * After a trace chunk close command, no new streams
3186 * referencing the chunk may be created. Hence, on the
3187 * event that no new trace chunk have been created for
3188 * the session, the reference to the current trace chunk
3189 * is released in order to allow it to be reclaimed when
3190 * the last stream releases its reference to it.
3192 lttng_trace_chunk_put(session
->current_trace_chunk
);
3193 session
->current_trace_chunk
= NULL
;
3195 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3196 session
->pending_closure_trace_chunk
= NULL
;
3198 pthread_mutex_unlock(&session
->lock
);
3201 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3202 reply
.path_length
= htobe32((uint32_t) path_length
);
3203 buf_ret
= lttng_dynamic_buffer_append(
3204 &reply_payload
, &reply
, sizeof(reply
));
3206 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3210 if (reply_code
== LTTNG_OK
) {
3211 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3212 closed_trace_chunk_path
, path_length
);
3214 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3219 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3223 if (send_ret
< reply_payload
.size
) {
3224 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3225 reply_payload
.size
, send_ret
);
3230 lttng_trace_chunk_put(chunk
);
3231 lttng_dynamic_buffer_reset(&reply_payload
);
3236 * relay_trace_chunk_exists: check if a trace chunk exists
3238 static int relay_trace_chunk_exists(
3239 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
3240 struct relay_connection
*conn
,
3241 const struct lttng_buffer_view
*payload
)
3245 struct relay_session
*session
= conn
->session
;
3246 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3247 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3248 struct lttng_buffer_view header_view
;
3252 if (!session
|| !conn
->version_check_done
) {
3253 ERR("Trying to check for the presence of a trace chunk before version check");
3258 if (session
->major
== 2 && session
->minor
< 11) {
3259 ERR("Chunk exists command is unsupported before 2.11");
3264 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3265 if (!lttng_buffer_view_is_valid(&header_view
)) {
3266 ERR("Failed to receive payload of chunk exists command");
3271 /* Convert to host endianness. */
3272 msg
= (typeof(msg
)) header_view
.data
;
3273 chunk_id
= be64toh(msg
->chunk_id
);
3275 ret
= sessiond_trace_chunk_registry_chunk_exists(
3276 sessiond_trace_chunk_registry
,
3277 conn
->session
->sessiond_uuid
,
3279 chunk_id
, &chunk_exists
);
3281 * If ret is not 0, send the reply and report the error to the caller.
3282 * It is a protocol (or internal) error and the session/connection
3283 * should be torn down.
3285 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3286 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3288 send_ret
= conn
->sock
->ops
->sendmsg(
3289 conn
->sock
, &reply
, sizeof(reply
), 0);
3290 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3291 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3300 * relay_get_configuration: query whether feature is available
3302 static int relay_get_configuration(
3303 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
3304 struct relay_connection
*conn
,
3305 const struct lttng_buffer_view
*payload
)
3309 struct lttcomm_relayd_get_configuration
*msg
;
3310 struct lttcomm_relayd_get_configuration_reply reply
= {};
3311 struct lttng_buffer_view header_view
;
3312 struct lttng_dynamic_buffer buffer
;
3313 struct lttng_dynamic_buffer extra_payload
;
3314 uint64_t query_flags
= 0;
3315 uint64_t result_flags
= 0;
3317 lttng_dynamic_buffer_init(&buffer
);
3318 lttng_dynamic_buffer_init(&extra_payload
);
3320 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3321 if (!lttng_buffer_view_is_valid(&header_view
)) {
3322 ERR("Failed to receive payload of chunk close command");
3327 /* Convert to host endianness. */
3328 msg
= (typeof(msg
)) header_view
.data
;
3329 query_flags
= be64toh(msg
->query_flags
);
3331 /* FIXME: Do we want to return invalid protocol or do we want to return
3332 * an array of lttcomm_relayd_get_configuration_specialized_query_reply
3333 * for each unknown query bit ?
3335 if (query_flags
& ~LTTCOMM_RELAYD_CONFIGURATION_QUERY_FLAG_MASK
) {
3336 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3340 if (opt_allow_clear
) {
3341 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3344 if (query_flags
& LTTCOMM_RELAYD_CONFIGURATION_QUERY_FLAG_SUPPORTED_TRACE_FORMAT
) {
3345 uint64_t supported_trace_format
= 0;
3347 supported_trace_format
|= LTTCOMM_RELAYD_CONFIGURATION_TRACE_FORMAT_SUPPORTED_CTF1
;
3349 supported_trace_format
= htobe64(supported_trace_format
);
3351 lttcomm_relayd_get_configuration_specialized_query_reply s_reply
= {};
3352 s_reply
.query_flag
= htobe64(
3353 LTTCOMM_RELAYD_CONFIGURATION_QUERY_FLAG_SUPPORTED_TRACE_FORMAT
);
3354 s_reply
.payload_len
= htobe64((uint64_t) sizeof(supported_trace_format
));
3355 lttng_dynamic_buffer_append(&extra_payload
, &s_reply
, sizeof(s_reply
));
3356 lttng_dynamic_buffer_append(&extra_payload
, &supported_trace_format
,
3357 sizeof(supported_trace_format
));
3361 reply
.generic
.ret_code
=
3362 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3363 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3365 lttng_dynamic_buffer_append(&buffer
, &reply
, sizeof(reply
));
3366 lttng_dynamic_buffer_append_buffer(&buffer
, &extra_payload
);
3368 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, buffer
.data
, buffer
.size
, 0);
3369 if (send_ret
< (ssize_t
) buffer
.size
) {
3370 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3374 lttng_dynamic_buffer_reset(&extra_payload
);
3375 lttng_dynamic_buffer_reset(&buffer
);
3379 static int relay_process_control_command(struct relay_connection
*conn
,
3380 const struct lttcomm_relayd_hdr
*header
,
3381 const struct lttng_buffer_view
*payload
)
3385 DBG3("Processing \"%s\" command for socket %i",
3386 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3388 switch (header
->cmd
) {
3389 case RELAYD_CREATE_SESSION
:
3390 ret
= relay_create_session(header
, conn
, payload
);
3392 case RELAYD_ADD_STREAM
:
3393 ret
= relay_add_stream(header
, conn
, payload
);
3395 case RELAYD_START_DATA
:
3396 ret
= relay_start(header
, conn
, payload
);
3398 case RELAYD_SEND_METADATA
:
3399 ret
= relay_recv_metadata(header
, conn
, payload
);
3401 case RELAYD_VERSION
:
3402 ret
= relay_send_version(header
, conn
, payload
);
3404 case RELAYD_CLOSE_STREAM
:
3405 ret
= relay_close_stream(header
, conn
, payload
);
3407 case RELAYD_DATA_PENDING
:
3408 ret
= relay_data_pending(header
, conn
, payload
);
3410 case RELAYD_QUIESCENT_CONTROL
:
3411 ret
= relay_quiescent_control(header
, conn
, payload
);
3413 case RELAYD_BEGIN_DATA_PENDING
:
3414 ret
= relay_begin_data_pending(header
, conn
, payload
);
3416 case RELAYD_END_DATA_PENDING
:
3417 ret
= relay_end_data_pending(header
, conn
, payload
);
3419 case RELAYD_SEND_INDEX
:
3420 ret
= relay_recv_index(header
, conn
, payload
);
3422 case RELAYD_STREAMS_SENT
:
3423 ret
= relay_streams_sent(header
, conn
, payload
);
3425 case RELAYD_RESET_METADATA
:
3426 ret
= relay_reset_metadata(header
, conn
, payload
);
3428 case RELAYD_ROTATE_STREAMS
:
3429 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3431 case RELAYD_CREATE_TRACE_CHUNK
:
3432 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3434 case RELAYD_CLOSE_TRACE_CHUNK
:
3435 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3437 case RELAYD_TRACE_CHUNK_EXISTS
:
3438 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3440 case RELAYD_GET_CONFIGURATION
:
3441 ret
= relay_get_configuration(header
, conn
, payload
);
3443 case RELAYD_UPDATE_SYNC_INFO
:
3445 ERR("Received unknown command (%u)", header
->cmd
);
3446 relay_unknown_command(conn
);
3455 static enum relay_connection_status
relay_process_control_receive_payload(
3456 struct relay_connection
*conn
)
3459 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3460 struct lttng_dynamic_buffer
*reception_buffer
=
3461 &conn
->protocol
.ctrl
.reception_buffer
;
3462 struct ctrl_connection_state_receive_payload
*state
=
3463 &conn
->protocol
.ctrl
.state
.receive_payload
;
3464 struct lttng_buffer_view payload_view
;
3466 if (state
->left_to_receive
== 0) {
3467 /* Short-circuit for payload-less commands. */
3468 goto reception_complete
;
3471 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3472 reception_buffer
->data
+ state
->received
,
3473 state
->left_to_receive
, MSG_DONTWAIT
);
3476 DIAGNOSTIC_IGNORE_LOGICAL_OP
3477 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3479 PERROR("Unable to receive command payload on sock %d",
3481 status
= RELAY_CONNECTION_STATUS_ERROR
;
3484 } else if (ret
== 0) {
3485 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3486 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3490 LTTNG_ASSERT(ret
> 0);
3491 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3493 state
->left_to_receive
-= ret
;
3494 state
->received
+= ret
;
3496 if (state
->left_to_receive
> 0) {
3498 * Can't transition to the protocol's next state, wait to
3499 * receive the rest of the header.
3501 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3502 state
->received
, state
->left_to_receive
,
3508 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3509 conn
->sock
->fd
, state
->received
);
3511 * The payload required to process the command has been received.
3512 * A view to the reception buffer is forwarded to the various
3513 * commands and the state of the control is reset on success.
3515 * Commands are responsible for sending their reply to the peer.
3517 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3519 ret
= relay_process_control_command(conn
,
3520 &state
->header
, &payload_view
);
3522 status
= RELAY_CONNECTION_STATUS_ERROR
;
3526 ret
= connection_reset_protocol_state(conn
);
3528 status
= RELAY_CONNECTION_STATUS_ERROR
;
3534 static enum relay_connection_status
relay_process_control_receive_header(
3535 struct relay_connection
*conn
)
3538 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3539 struct lttcomm_relayd_hdr header
;
3540 struct lttng_dynamic_buffer
*reception_buffer
=
3541 &conn
->protocol
.ctrl
.reception_buffer
;
3542 struct ctrl_connection_state_receive_header
*state
=
3543 &conn
->protocol
.ctrl
.state
.receive_header
;
3545 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3547 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3548 reception_buffer
->data
+ state
->received
,
3549 state
->left_to_receive
, MSG_DONTWAIT
);
3552 DIAGNOSTIC_IGNORE_LOGICAL_OP
3553 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3555 PERROR("Unable to receive control command header on sock %d",
3557 status
= RELAY_CONNECTION_STATUS_ERROR
;
3560 } else if (ret
== 0) {
3561 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3562 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3566 LTTNG_ASSERT(ret
> 0);
3567 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3569 state
->left_to_receive
-= ret
;
3570 state
->received
+= ret
;
3572 if (state
->left_to_receive
> 0) {
3574 * Can't transition to the protocol's next state, wait to
3575 * receive the rest of the header.
3577 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3578 state
->received
, state
->left_to_receive
,
3583 /* Transition to next state: receiving the command's payload. */
3584 conn
->protocol
.ctrl
.state_id
=
3585 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3586 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3587 header
.circuit_id
= be64toh(header
.circuit_id
);
3588 header
.data_size
= be64toh(header
.data_size
);
3589 header
.cmd
= be32toh(header
.cmd
);
3590 header
.cmd_version
= be32toh(header
.cmd_version
);
3591 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3592 &header
, sizeof(header
));
3594 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3595 conn
->sock
->fd
, lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3596 header
.cmd_version
, header
.data_size
);
3598 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3599 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3601 status
= RELAY_CONNECTION_STATUS_ERROR
;
3605 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3607 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3608 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3611 status
= RELAY_CONNECTION_STATUS_ERROR
;
3615 if (header
.data_size
== 0) {
3617 * Manually invoke the next state as the poll loop
3618 * will not wake-up to allow us to proceed further.
3620 status
= relay_process_control_receive_payload(conn
);
3627 * Process the commands received on the control socket
3629 static enum relay_connection_status
relay_process_control(
3630 struct relay_connection
*conn
)
3632 enum relay_connection_status status
;
3634 switch (conn
->protocol
.ctrl
.state_id
) {
3635 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3636 status
= relay_process_control_receive_header(conn
);
3638 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3639 status
= relay_process_control_receive_payload(conn
);
3642 ERR("Unknown control connection protocol state encountered.");
3649 static enum relay_connection_status
relay_process_data_receive_header(
3650 struct relay_connection
*conn
)
3653 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3654 struct data_connection_state_receive_header
*state
=
3655 &conn
->protocol
.data
.state
.receive_header
;
3656 struct lttcomm_relayd_data_hdr header
;
3657 struct relay_stream
*stream
;
3659 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3661 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3662 state
->header_reception_buffer
+ state
->received
,
3663 state
->left_to_receive
, MSG_DONTWAIT
);
3666 DIAGNOSTIC_IGNORE_LOGICAL_OP
3667 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3669 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3670 status
= RELAY_CONNECTION_STATUS_ERROR
;
3673 } else if (ret
== 0) {
3674 /* Orderly shutdown. Not necessary to print an error. */
3675 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3676 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3680 LTTNG_ASSERT(ret
> 0);
3681 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3683 state
->left_to_receive
-= ret
;
3684 state
->received
+= ret
;
3686 if (state
->left_to_receive
> 0) {
3688 * Can't transition to the protocol's next state, wait to
3689 * receive the rest of the header.
3691 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3692 state
->received
, state
->left_to_receive
,
3697 /* Transition to next state: receiving the payload. */
3698 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3700 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3701 header
.circuit_id
= be64toh(header
.circuit_id
);
3702 header
.stream_id
= be64toh(header
.stream_id
);
3703 header
.data_size
= be32toh(header
.data_size
);
3704 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3705 header
.padding_size
= be32toh(header
.padding_size
);
3706 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3708 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3710 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3711 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3713 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3714 conn
->sock
->fd
, header
.circuit_id
,
3715 header
.stream_id
, header
.data_size
,
3716 header
.net_seq_num
, header
.padding_size
);
3718 stream
= stream_get_by_id(header
.stream_id
);
3720 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3722 /* Protocol error. */
3723 status
= RELAY_CONNECTION_STATUS_ERROR
;
3727 pthread_mutex_lock(&stream
->lock
);
3728 /* Prepare stream for the reception of a new packet. */
3729 ret
= stream_init_packet(stream
, header
.data_size
,
3730 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3731 pthread_mutex_unlock(&stream
->lock
);
3733 ERR("Failed to rotate stream output file");
3734 status
= RELAY_CONNECTION_STATUS_ERROR
;
3735 goto end_stream_unlock
;
3744 static enum relay_connection_status
relay_process_data_receive_payload(
3745 struct relay_connection
*conn
)
3748 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3749 struct relay_stream
*stream
;
3750 struct data_connection_state_receive_payload
*state
=
3751 &conn
->protocol
.data
.state
.receive_payload
;
3752 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3753 char data_buffer
[chunk_size
];
3754 bool partial_recv
= false;
3755 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3756 uint64_t left_to_receive
= state
->left_to_receive
;
3757 struct relay_session
*session
;
3759 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3760 state
->header
.stream_id
, state
->header
.net_seq_num
,
3761 state
->received
, left_to_receive
);
3763 stream
= stream_get_by_id(state
->header
.stream_id
);
3765 /* Protocol error. */
3766 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3767 state
->header
.stream_id
);
3768 status
= RELAY_CONNECTION_STATUS_ERROR
;
3772 pthread_mutex_lock(&stream
->lock
);
3773 session
= stream
->trace
->session
;
3774 if (!conn
->session
) {
3775 ret
= connection_set_session(conn
, session
);
3777 status
= RELAY_CONNECTION_STATUS_ERROR
;
3778 goto end_stream_unlock
;
3783 * The size of the "chunk" received on any iteration is bounded by:
3784 * - the data left to receive,
3785 * - the data immediately available on the socket,
3786 * - the on-stack data buffer
3788 while (left_to_receive
> 0 && !partial_recv
) {
3789 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3790 struct lttng_buffer_view packet_chunk
;
3792 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3793 recv_size
, MSG_DONTWAIT
);
3796 DIAGNOSTIC_IGNORE_LOGICAL_OP
3797 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3799 PERROR("Socket %d error", conn
->sock
->fd
);
3800 status
= RELAY_CONNECTION_STATUS_ERROR
;
3802 goto end_stream_unlock
;
3803 } else if (ret
== 0) {
3804 /* No more data ready to be consumed on socket. */
3805 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3806 state
->header
.stream_id
);
3807 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3809 } else if (ret
< (int) recv_size
) {
3811 * All the data available on the socket has been
3814 partial_recv
= true;
3818 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3820 LTTNG_ASSERT(packet_chunk
.data
);
3822 ret
= stream_write(stream
, &packet_chunk
, 0);
3824 ERR("Relay error writing data to file");
3825 status
= RELAY_CONNECTION_STATUS_ERROR
;
3826 goto end_stream_unlock
;
3829 left_to_receive
-= recv_size
;
3830 state
->received
+= recv_size
;
3831 state
->left_to_receive
= left_to_receive
;
3834 if (state
->left_to_receive
> 0) {
3836 * Did not receive all the data expected, wait for more data to
3837 * become available on the socket.
3839 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3840 state
->header
.stream_id
, state
->received
,
3841 state
->left_to_receive
);
3842 goto end_stream_unlock
;
3845 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3847 status
= RELAY_CONNECTION_STATUS_ERROR
;
3848 goto end_stream_unlock
;
3851 if (session_streams_have_index(session
)) {
3852 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3853 state
->rotate_index
, &index_flushed
,
3854 state
->header
.data_size
+ state
->header
.padding_size
);
3856 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3857 stream
->stream_handle
,
3858 state
->header
.net_seq_num
, ret
);
3859 status
= RELAY_CONNECTION_STATUS_ERROR
;
3860 goto end_stream_unlock
;
3864 if (stream
->prev_data_seq
== -1ULL) {
3868 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3869 state
->header
.padding_size
, state
->header
.net_seq_num
,
3872 status
= RELAY_CONNECTION_STATUS_ERROR
;
3873 goto end_stream_unlock
;
3877 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3878 * contents of *state which are aliased (union) to the same location as
3879 * the new state. Don't use it beyond this point.
3881 connection_reset_protocol_state(conn
);
3885 close_requested
= stream
->close_requested
;
3886 pthread_mutex_unlock(&stream
->lock
);
3887 if (close_requested
&& left_to_receive
== 0) {
3888 try_stream_close(stream
);
3892 pthread_mutex_lock(&session
->lock
);
3893 uatomic_set(&session
->new_streams
, 1);
3894 pthread_mutex_unlock(&session
->lock
);
3903 * relay_process_data: Process the data received on the data socket
3905 static enum relay_connection_status
relay_process_data(
3906 struct relay_connection
*conn
)
3908 enum relay_connection_status status
;
3910 switch (conn
->protocol
.data
.state_id
) {
3911 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3912 status
= relay_process_data_receive_header(conn
);
3914 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3915 status
= relay_process_data_receive_payload(conn
);
3918 ERR("Unexpected data connection communication state.");
3925 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3929 (void) lttng_poll_del(events
, pollfd
);
3931 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3932 fd_tracker_util_close_fd
, NULL
);
3934 ERR("Closing pollfd %d", pollfd
);
3938 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3939 int pollfd
, struct relay_connection
*conn
)
3941 const char *type_str
;
3943 switch (conn
->type
) {
3948 type_str
= "Control";
3950 case RELAY_VIEWER_COMMAND
:
3951 type_str
= "Viewer Command";
3953 case RELAY_VIEWER_NOTIFICATION
:
3954 type_str
= "Viewer Notification";
3957 type_str
= "Unknown";
3959 cleanup_connection_pollfd(events
, pollfd
);
3960 connection_put(conn
);
3961 DBG("%s connection closed with %d", type_str
, pollfd
);
3965 * This thread does the actual work
3967 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3969 int ret
, err
= -1, last_seen_data_fd
= -1;
3971 struct lttng_poll_event events
;
3972 struct lttng_ht
*relay_connections_ht
;
3973 struct lttng_ht_iter iter
;
3974 struct relay_connection
*destroy_conn
= NULL
;
3976 DBG("[thread] Relay worker started");
3978 rcu_register_thread();
3980 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3982 if (testpoint(relayd_thread_worker
)) {
3983 goto error_testpoint
;
3986 health_code_update();
3988 /* table of connections indexed on socket */
3989 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3990 if (!relay_connections_ht
) {
3991 goto relay_connections_ht_error
;
3994 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3996 goto error_poll_create
;
3999 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
4006 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
4008 health_code_update();
4010 /* Infinite blocking call, waiting for transmission */
4011 DBG3("Relayd worker thread polling...");
4012 health_poll_entry();
4013 ret
= lttng_poll_wait(&events
, -1);
4017 * Restart interrupted system call.
4019 if (errno
== EINTR
) {
4028 * Process control. The control connection is
4029 * prioritized so we don't starve it with high
4030 * throughput tracing data on the data connection.
4032 for (i
= 0; i
< nb_fd
; i
++) {
4033 /* Fetch once the poll data */
4034 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4035 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4037 health_code_update();
4039 /* Thread quit pipe has been closed. Killing thread. */
4040 ret
= check_thread_quit_pipe(pollfd
, revents
);
4046 /* Inspect the relay conn pipe for new connection */
4047 if (pollfd
== relay_conn_pipe
[0]) {
4048 if (revents
& LPOLLIN
) {
4049 struct relay_connection
*conn
;
4051 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
4055 ret
= lttng_poll_add(&events
,
4057 LPOLLIN
| LPOLLRDHUP
);
4059 ERR("Failed to add new connection file descriptor to poll set");
4062 connection_ht_add(relay_connections_ht
, conn
);
4063 DBG("Connection socket %d added", conn
->sock
->fd
);
4064 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4065 ERR("Relay connection pipe error");
4068 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4072 struct relay_connection
*ctrl_conn
;
4074 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4075 /* If not found, there is a synchronization issue. */
4076 LTTNG_ASSERT(ctrl_conn
);
4078 if (ctrl_conn
->type
== RELAY_DATA
) {
4079 if (revents
& LPOLLIN
) {
4081 * Flag the last seen data fd not deleted. It will be
4082 * used as the last seen fd if any fd gets deleted in
4085 last_notdel_data_fd
= pollfd
;
4087 goto put_ctrl_connection
;
4089 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4091 if (revents
& LPOLLIN
) {
4092 enum relay_connection_status status
;
4094 status
= relay_process_control(ctrl_conn
);
4095 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4097 * On socket error flag the session as aborted to force
4098 * the cleanup of its stream otherwise it can leak
4099 * during the lifetime of the relayd.
4101 * This prevents situations in which streams can be
4102 * left opened because an index was received, the
4103 * control connection is closed, and the data
4104 * connection is closed (uncleanly) before the packet's
4107 * Since the control connection encountered an error,
4108 * it is okay to be conservative and close the
4109 * session right now as we can't rely on the protocol
4110 * being respected anymore.
4112 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4113 session_abort(ctrl_conn
->session
);
4116 /* Clear the connection on error or close. */
4117 relay_thread_close_connection(&events
,
4122 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4123 relay_thread_close_connection(&events
,
4125 if (last_seen_data_fd
== pollfd
) {
4126 last_seen_data_fd
= last_notdel_data_fd
;
4129 ERR("Unexpected poll events %u for control sock %d",
4131 connection_put(ctrl_conn
);
4134 put_ctrl_connection
:
4135 connection_put(ctrl_conn
);
4140 * The last loop handled a control request, go back to poll to make
4141 * sure we prioritise the control socket.
4147 if (last_seen_data_fd
>= 0) {
4148 for (i
= 0; i
< nb_fd
; i
++) {
4149 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4151 health_code_update();
4153 if (last_seen_data_fd
== pollfd
) {
4160 /* Process data connection. */
4161 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4162 /* Fetch the poll data. */
4163 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4164 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4165 struct relay_connection
*data_conn
;
4167 health_code_update();
4170 /* No activity for this FD (poll implementation). */
4174 /* Skip the command pipe. It's handled in the first loop. */
4175 if (pollfd
== relay_conn_pipe
[0]) {
4179 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4181 /* Skip it. Might be removed before. */
4184 if (data_conn
->type
== RELAY_CONTROL
) {
4185 goto put_data_connection
;
4187 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4189 if (revents
& LPOLLIN
) {
4190 enum relay_connection_status status
;
4192 status
= relay_process_data(data_conn
);
4193 /* Connection closed or error. */
4194 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4196 * On socket error flag the session as aborted to force
4197 * the cleanup of its stream otherwise it can leak
4198 * during the lifetime of the relayd.
4200 * This prevents situations in which streams can be
4201 * left opened because an index was received, the
4202 * control connection is closed, and the data
4203 * connection is closed (uncleanly) before the packet's
4206 * Since the data connection encountered an error,
4207 * it is okay to be conservative and close the
4208 * session right now as we can't rely on the protocol
4209 * being respected anymore.
4211 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4212 session_abort(data_conn
->session
);
4214 relay_thread_close_connection(&events
, pollfd
,
4217 * Every goto restart call sets the last seen fd where
4218 * here we don't really care since we gracefully
4219 * continue the loop after the connection is deleted.
4222 /* Keep last seen port. */
4223 last_seen_data_fd
= pollfd
;
4224 connection_put(data_conn
);
4227 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4228 relay_thread_close_connection(&events
, pollfd
,
4231 ERR("Unknown poll events %u for data sock %d",
4234 put_data_connection
:
4235 connection_put(data_conn
);
4237 last_seen_data_fd
= -1;
4240 /* Normal exit, no error */
4245 /* Cleanup remaining connection object. */
4247 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4250 health_code_update();
4252 session_abort(destroy_conn
->session
);
4255 * No need to grab another ref, because we own
4258 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4263 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4265 lttng_ht_destroy(relay_connections_ht
);
4266 relay_connections_ht_error
:
4267 /* Close relay conn pipes */
4268 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4271 DBG("Thread exited with error");
4273 DBG("Worker thread cleanup complete");
4277 ERR("Health error occurred in %s", __func__
);
4279 health_unregister(health_relayd
);
4280 rcu_unregister_thread();
4281 lttng_relay_stop_threads();
4286 * Create the relay command pipe to wake thread_manage_apps.
4287 * Closed in cleanup().
4289 static int create_relay_conn_pipe(void)
4291 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4292 "Relayd connection pipe", relay_conn_pipe
);
4295 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4297 fds
[0] = fileno(stdout
);
4298 fds
[1] = fileno(stderr
);
4302 static int track_stdio(void)
4305 const char *names
[] = { "stdout", "stderr" };
4307 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4308 names
, 2, stdio_open
, NULL
);
4314 int main(int argc
, char **argv
)
4316 bool thread_is_rcu_registered
= false;
4317 int ret
= 0, retval
= 0;
4319 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4321 /* Parse environment variables */
4322 ret
= parse_env_options();
4330 * Command line arguments overwrite environment.
4333 if (set_options(argc
, argv
)) {
4338 if (set_signal_handler()) {
4343 relayd_config_log();
4345 if (opt_print_version
) {
4351 ret
= fclose(stdin
);
4353 PERROR("Failed to close stdin");
4357 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4359 /* Try to create directory if -o, --output is specified. */
4360 if (opt_output_path
) {
4361 if (*opt_output_path
!= '/') {
4362 ERR("Please specify an absolute path for -o, --output PATH");
4367 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4370 ERR("Unable to create %s", opt_output_path
);
4377 if (opt_daemon
|| opt_background
) {
4378 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4386 if (opt_working_directory
) {
4387 ret
= utils_change_working_directory(opt_working_directory
);
4389 /* All errors are already logged. */
4394 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4395 if (!sessiond_trace_chunk_registry
) {
4396 ERR("Failed to initialize session daemon trace chunk registry");
4402 * The RCU thread registration (and use, through the fd-tracker's
4403 * creation) is done after the daemonization to allow us to not
4404 * deal with liburcu's fork() management as the call RCU needs to
4407 rcu_register_thread();
4408 thread_is_rcu_registered
= true;
4410 output_path
= create_output_path("");
4412 ERR("Failed to get output path");
4416 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4417 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4420 ERR("Failed to format unlinked file directory path");
4424 the_fd_tracker
= fd_tracker_create(
4425 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4426 free(unlinked_file_directory_path
);
4427 if (!the_fd_tracker
) {
4432 ret
= track_stdio();
4438 /* Initialize thread health monitoring */
4439 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4440 if (!health_relayd
) {
4441 PERROR("health_app_create error");
4446 /* Create thread quit pipe */
4447 if (init_thread_quit_pipe()) {
4452 /* Setup the thread apps communication pipe. */
4453 if (create_relay_conn_pipe()) {
4458 /* Init relay command queue. */
4459 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4461 /* Initialize communication library */
4463 lttcomm_inet_init();
4465 /* tables of sessions indexed by session ID */
4466 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4472 /* tables of streams indexed by stream ID */
4473 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4474 if (!relay_streams_ht
) {
4479 /* tables of streams indexed by stream ID */
4480 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4481 if (!viewer_streams_ht
) {
4486 ret
= init_health_quit_pipe();
4492 /* Create thread to manage the client socket */
4493 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4494 thread_manage_health_relayd
, (void *) NULL
);
4497 PERROR("pthread_create health");
4502 /* Setup the dispatcher thread */
4503 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4504 relay_thread_dispatcher
, (void *) NULL
);
4507 PERROR("pthread_create dispatcher");
4509 goto exit_dispatcher_thread
;
4512 /* Setup the worker thread */
4513 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4514 relay_thread_worker
, NULL
);
4517 PERROR("pthread_create worker");
4519 goto exit_worker_thread
;
4522 /* Setup the listener thread */
4523 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4524 relay_thread_listener
, (void *) NULL
);
4527 PERROR("pthread_create listener");
4529 goto exit_listener_thread
;
4532 ret
= relayd_live_create(live_uri
);
4534 ERR("Starting live viewer threads");
4540 * This is where we start awaiting program completion (e.g. through
4541 * signal that asks threads to teardown).
4544 ret
= relayd_live_join();
4550 ret
= pthread_join(listener_thread
, &status
);
4553 PERROR("pthread_join listener_thread");
4557 exit_listener_thread
:
4558 ret
= pthread_join(worker_thread
, &status
);
4561 PERROR("pthread_join worker_thread");
4566 ret
= pthread_join(dispatcher_thread
, &status
);
4569 PERROR("pthread_join dispatcher_thread");
4572 exit_dispatcher_thread
:
4574 ret
= pthread_join(health_thread
, &status
);
4577 PERROR("pthread_join health_thread");
4582 * Wait for all pending call_rcu work to complete before tearing
4583 * down data structures. call_rcu worker may be trying to
4584 * perform lookups in those structures.
4589 /* Ensure all prior call_rcu are done. */
4592 if (thread_is_rcu_registered
) {
4593 rcu_unregister_thread();