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>
37 #include <lttng/lttng.h>
38 #include <common/common.h>
39 #include <common/compat/poll.h>
40 #include <common/compat/socket.h>
41 #include <common/compat/endian.h>
42 #include <common/compat/getenv.h>
43 #include <common/defaults.h>
44 #include <common/daemonize.h>
45 #include <common/futex.h>
46 #include <common/sessiond-comm/sessiond-comm.h>
47 #include <common/sessiond-comm/inet.h>
48 #include <common/sessiond-comm/relayd.h>
49 #include <common/uri.h>
50 #include <common/utils.h>
51 #include <common/align.h>
52 #include <common/config/session-config.h>
53 #include <common/dynamic-buffer.h>
54 #include <common/buffer-view.h>
55 #include <common/string-utils/format.h>
56 #include <common/fd-tracker/fd-tracker.h>
57 #include <common/fd-tracker/utils.h>
59 #include "backward-compatibility-group-by.h"
61 #include "connection.h"
62 #include "ctf-trace.h"
63 #include "health-relayd.h"
66 #include "lttng-relayd.h"
68 #include "sessiond-trace-chunks.h"
70 #include "tcp_keep_alive.h"
71 #include "testpoint.h"
72 #include "tracefile-array.h"
75 #include "viewer-stream.h"
77 static const char *help_msg
=
78 #ifdef LTTNG_EMBED_HELP
79 #include <lttng-relayd.8.h>
85 enum relay_connection_status
{
86 RELAY_CONNECTION_STATUS_OK
,
87 /* An error occurred while processing an event on the connection. */
88 RELAY_CONNECTION_STATUS_ERROR
,
89 /* Connection closed/shutdown cleanly. */
90 RELAY_CONNECTION_STATUS_CLOSED
,
93 /* command line options */
94 char *opt_output_path
, *opt_working_directory
;
95 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
96 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
99 * We need to wait for listener and live listener threads, as well as
100 * health check thread, before being ready to signal readiness.
102 #define NR_LTTNG_RELAY_READY 3
103 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
105 /* Size of receive buffer. */
106 #define RECV_DATA_BUFFER_SIZE 65536
108 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
109 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
111 static struct lttng_uri
*control_uri
;
112 static struct lttng_uri
*data_uri
;
113 static struct lttng_uri
*live_uri
;
115 const char *progname
;
117 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
118 static int tracing_group_name_override
;
120 const char * const config_section_name
= "relayd";
123 * Quit pipe for all threads. This permits a single cancellation point
124 * for all threads when receiving an event on the pipe.
126 int thread_quit_pipe
[2] = { -1, -1 };
129 * This pipe is used to inform the worker thread that a command is queued and
130 * ready to be processed.
132 static int relay_conn_pipe
[2] = { -1, -1 };
134 /* Shared between threads */
135 static int dispatch_thread_exit
;
137 static pthread_t listener_thread
;
138 static pthread_t dispatcher_thread
;
139 static pthread_t worker_thread
;
140 static pthread_t health_thread
;
143 * last_relay_stream_id_lock protects last_relay_stream_id increment
144 * atomicity on 32-bit architectures.
146 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
147 static uint64_t last_relay_stream_id
;
150 * Relay command queue.
152 * The relay_thread_listener and relay_thread_dispatcher communicate with this
155 static struct relay_conn_queue relay_conn_queue
;
157 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
158 static unsigned int lttng_opt_fd_pool_size
= -1;
160 /* Global relay stream hash table. */
161 struct lttng_ht
*relay_streams_ht
;
163 /* Global relay viewer stream hash table. */
164 struct lttng_ht
*viewer_streams_ht
;
166 /* Global relay sessions hash table. */
167 struct lttng_ht
*sessions_ht
;
169 /* Relayd health monitoring */
170 struct health_app
*health_relayd
;
172 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
174 /* Global fd tracker. */
175 struct fd_tracker
*the_fd_tracker
;
177 static struct option long_options
[] = {
178 { "control-port", 1, 0, 'C', },
179 { "data-port", 1, 0, 'D', },
180 { "live-port", 1, 0, 'L', },
181 { "daemonize", 0, 0, 'd', },
182 { "background", 0, 0, 'b', },
183 { "group", 1, 0, 'g', },
184 { "fd-pool-size", 1, 0, '\0', },
185 { "help", 0, 0, 'h', },
186 { "output", 1, 0, 'o', },
187 { "verbose", 0, 0, 'v', },
188 { "config", 1, 0, 'f' },
189 { "version", 0, 0, 'V' },
190 { "working-directory", 1, 0, 'w', },
191 { "group-output-by-session", 0, 0, 's', },
192 { "group-output-by-host", 0, 0, 'p', },
193 { "disallow-clear", 0, 0, 'x' },
197 static const char *config_ignore_options
[] = { "help", "config", "version" };
199 static void print_version(void) {
200 fprintf(stdout
, "%s\n", VERSION
);
203 static void relayd_config_log(void)
205 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
206 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
207 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
208 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
209 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
211 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
212 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
217 * Take an option from the getopt output and set it in the right variable to be
220 * Return 0 on success else a negative value.
222 static int set_option(int opt
, const char *arg
, const char *optname
)
228 if (!strcmp(optname
, "fd-pool-size")) {
232 v
= strtoul(arg
, NULL
, 0);
233 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
234 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
239 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
243 lttng_opt_fd_pool_size
= (unsigned int) v
;
245 fprintf(stderr
, "unknown option %s", optname
);
247 fprintf(stderr
, " with arg %s\n", arg
);
252 if (lttng_is_setuid_setgid()) {
253 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
254 "-C, --control-port");
256 ret
= uri_parse(arg
, &control_uri
);
258 ERR("Invalid control URI specified");
261 if (control_uri
->port
== 0) {
262 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
267 if (lttng_is_setuid_setgid()) {
268 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
271 ret
= uri_parse(arg
, &data_uri
);
273 ERR("Invalid data URI specified");
276 if (data_uri
->port
== 0) {
277 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 ret
= uri_parse(arg
, &live_uri
);
288 ERR("Invalid live URI specified");
291 if (live_uri
->port
== 0) {
292 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
307 tracing_group_name
= strdup(arg
);
308 if (tracing_group_name
== NULL
) {
313 tracing_group_name_override
= 1;
317 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
319 ERR("Cannot show --help for `lttng-relayd`");
324 opt_print_version
= 1;
327 if (lttng_is_setuid_setgid()) {
328 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
331 ret
= asprintf(&opt_output_path
, "%s", arg
);
334 PERROR("asprintf opt_output_path");
340 if (lttng_is_setuid_setgid()) {
341 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
342 "-w, --working-directory");
344 ret
= asprintf(&opt_working_directory
, "%s", arg
);
347 PERROR("asprintf opt_working_directory");
354 /* Verbose level can increase using multiple -v */
356 lttng_opt_verbose
= config_parse_value(arg
);
358 /* Only 3 level of verbosity (-vvv). */
359 if (lttng_opt_verbose
< 3) {
360 lttng_opt_verbose
+= 1;
365 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
366 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
369 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
372 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
373 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
376 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
383 /* Unknown option or other error.
384 * Error is printed by getopt, just return */
397 * config_entry_handler_cb used to handle options read from a config file.
398 * See config_entry_handler_cb comment in common/config/session-config.h for the
399 * return value conventions.
401 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
405 if (!entry
|| !entry
->name
|| !entry
->value
) {
410 /* Check if the option is to be ignored */
411 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
412 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
417 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
418 /* Ignore if entry name is not fully matched. */
419 if (strcmp(entry
->name
, long_options
[i
].name
)) {
424 * If the option takes no argument on the command line,
425 * we have to check if the value is "true". We support
426 * non-zero numeric values, true, on and yes.
428 if (!long_options
[i
].has_arg
) {
429 ret
= config_parse_value(entry
->value
);
432 WARN("Invalid configuration value \"%s\" for option %s",
433 entry
->value
, entry
->name
);
435 /* False, skip boolean config option. */
440 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
444 WARN("Unrecognized option \"%s\" in daemon configuration file.",
451 static int parse_env_options(void)
456 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
458 opt_working_directory
= strdup(value
);
459 if (!opt_working_directory
) {
460 ERR("Failed to allocate working directory string (\"%s\")",
468 static int set_fd_pool_size(void)
471 struct rlimit rlimit
;
473 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
475 PERROR("Failed to get file descriptor limit");
480 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
481 (uint64_t) rlimit
.rlim_cur
,
482 (uint64_t) rlimit
.rlim_max
);
483 if (lttng_opt_fd_pool_size
== -1) {
484 /* Use default value (soft limit - reserve). */
485 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
486 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
487 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
491 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
492 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
496 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
497 ERR("File descriptor pool size must be set to at least %d",
498 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
503 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
504 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
505 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
510 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
511 lttng_opt_fd_pool_size
,
512 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
513 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
518 static int set_options(int argc
, char **argv
)
520 int c
, ret
= 0, option_index
= 0, retval
= 0;
521 int orig_optopt
= optopt
, orig_optind
= optind
;
522 char *default_address
, *optstring
;
523 const char *config_path
= NULL
;
525 optstring
= utils_generate_optstring(long_options
,
526 sizeof(long_options
) / sizeof(struct option
));
532 /* Check for the --config option */
534 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
535 &option_index
)) != -1) {
539 } else if (c
!= 'f') {
543 if (lttng_is_setuid_setgid()) {
544 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
547 config_path
= utils_expand_path(optarg
);
549 ERR("Failed to resolve path: %s", optarg
);
554 ret
= config_get_section_entries(config_path
, config_section_name
,
555 config_entry_handler
, NULL
);
558 ERR("Invalid configuration option at line %i", ret
);
564 /* Reset getopt's global state */
565 optopt
= orig_optopt
;
566 optind
= orig_optind
;
568 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
573 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
580 /* assign default values */
581 if (control_uri
== NULL
) {
582 ret
= asprintf(&default_address
,
583 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
584 DEFAULT_NETWORK_CONTROL_PORT
);
586 PERROR("asprintf default data address");
591 ret
= uri_parse(default_address
, &control_uri
);
592 free(default_address
);
594 ERR("Invalid control URI specified");
599 if (data_uri
== NULL
) {
600 ret
= asprintf(&default_address
,
601 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
602 DEFAULT_NETWORK_DATA_PORT
);
604 PERROR("asprintf default data address");
609 ret
= uri_parse(default_address
, &data_uri
);
610 free(default_address
);
612 ERR("Invalid data URI specified");
617 if (live_uri
== NULL
) {
618 ret
= asprintf(&default_address
,
619 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
620 DEFAULT_NETWORK_VIEWER_PORT
);
622 PERROR("asprintf default viewer control address");
627 ret
= uri_parse(default_address
, &live_uri
);
628 free(default_address
);
630 ERR("Invalid viewer control URI specified");
635 ret
= set_fd_pool_size();
641 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
642 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
644 if (opt_allow_clear
) {
645 /* Check if env variable exists. */
646 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
648 ret
= config_parse_value(value
);
650 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
654 opt_allow_clear
= !ret
;
663 static void print_global_objects(void)
665 print_viewer_streams();
666 print_relay_streams();
670 static int noop_close(void *data
, int *fds
)
675 static void untrack_stdio(void)
677 int fds
[] = { fileno(stdout
), fileno(stderr
) };
680 * noop_close is used since we don't really want to close
681 * the stdio output fds; we merely want to stop tracking them.
683 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
684 fds
, 2, noop_close
, NULL
);
690 static void relayd_cleanup(void)
692 print_global_objects();
696 if (viewer_streams_ht
)
697 lttng_ht_destroy(viewer_streams_ht
);
698 if (relay_streams_ht
)
699 lttng_ht_destroy(relay_streams_ht
);
701 lttng_ht_destroy(sessions_ht
);
703 free(opt_output_path
);
704 free(opt_working_directory
);
707 health_app_destroy(health_relayd
);
709 /* Close thread quit pipes */
710 if (health_quit_pipe
[0] != -1) {
711 (void) fd_tracker_util_pipe_close(
712 the_fd_tracker
, health_quit_pipe
);
714 if (thread_quit_pipe
[0] != -1) {
715 (void) fd_tracker_util_pipe_close(
716 the_fd_tracker
, thread_quit_pipe
);
718 if (sessiond_trace_chunk_registry
) {
719 sessiond_trace_chunk_registry_destroy(
720 sessiond_trace_chunk_registry
);
722 if (the_fd_tracker
) {
725 * fd_tracker_destroy() will log the contents of the fd-tracker
726 * if a leak is detected.
728 fd_tracker_destroy(the_fd_tracker
);
731 uri_free(control_uri
);
733 /* Live URI is freed in the live thread. */
735 if (tracing_group_name_override
) {
736 free((void *) tracing_group_name
);
741 * Write to writable pipe used to notify a thread.
743 static int notify_thread_pipe(int wpipe
)
747 ret
= lttng_write(wpipe
, "!", 1);
749 PERROR("write poll pipe");
757 static int notify_health_quit_pipe(int *pipe
)
761 ret
= lttng_write(pipe
[1], "4", 1);
763 PERROR("write relay health quit");
772 * Stop all relayd and relayd-live threads.
774 int lttng_relay_stop_threads(void)
778 /* Stopping all threads */
779 DBG("Terminating all threads");
780 if (notify_thread_pipe(thread_quit_pipe
[1])) {
781 ERR("write error on thread quit pipe");
785 if (notify_health_quit_pipe(health_quit_pipe
)) {
786 ERR("write error on health quit pipe");
789 /* Dispatch thread */
790 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
791 futex_nto1_wake(&relay_conn_queue
.futex
);
793 if (relayd_live_stop()) {
794 ERR("Error stopping live threads");
801 * Signal handler for the daemon
803 * Simply stop all worker threads, leaving main() return gracefully after
804 * joining all threads and calling cleanup().
806 static void sighandler(int sig
)
810 DBG("SIGINT caught");
811 if (lttng_relay_stop_threads()) {
812 ERR("Error stopping threads");
816 DBG("SIGTERM caught");
817 if (lttng_relay_stop_threads()) {
818 ERR("Error stopping threads");
822 CMM_STORE_SHARED(recv_child_signal
, 1);
830 * Setup signal handler for :
831 * SIGINT, SIGTERM, SIGPIPE
833 static int set_signal_handler(void)
839 if ((ret
= sigemptyset(&sigset
)) < 0) {
840 PERROR("sigemptyset");
847 sa
.sa_handler
= sighandler
;
848 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
853 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
858 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
863 sa
.sa_handler
= SIG_IGN
;
864 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
869 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
874 void lttng_relay_notify_ready(void)
876 /* Notify the parent of the fork() process that we are ready. */
877 if (opt_daemon
|| opt_background
) {
878 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
879 kill(child_ppid
, SIGUSR1
);
885 * Init thread quit pipe.
887 * Return -1 on error or 0 if all pipes are created.
889 static int init_thread_quit_pipe(void)
891 return fd_tracker_util_pipe_open_cloexec(
892 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
896 * Init health quit pipe.
898 * Return -1 on error or 0 if all pipes are created.
900 static int init_health_quit_pipe(void)
902 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
903 "Health quit pipe", health_quit_pipe
);
907 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
909 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
910 int size
, const char *name
)
914 if (events
== NULL
|| size
== 0) {
919 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
920 name
, events
, 1, LTTNG_CLOEXEC
);
922 PERROR("Failed to create \"%s\" poll file descriptor", name
);
927 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
939 * Check if the thread quit pipe was triggered.
941 * Return 1 if it was triggered else 0;
943 static int check_thread_quit_pipe(int fd
, uint32_t events
)
945 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
952 static int create_sock(void *data
, int *out_fd
)
955 struct lttcomm_sock
*sock
= data
;
957 ret
= lttcomm_create_sock(sock
);
967 static int close_sock(void *data
, int *in_fd
)
969 struct lttcomm_sock
*sock
= data
;
971 return sock
->ops
->close(sock
);
974 static int accept_sock(void *data
, int *out_fd
)
977 /* Socks is an array of in_sock, out_sock. */
978 struct lttcomm_sock
**socks
= data
;
979 struct lttcomm_sock
*in_sock
= socks
[0];
981 socks
[1] = in_sock
->ops
->accept(in_sock
);
986 *out_fd
= socks
[1]->fd
;
992 * Create and init socket from uri.
994 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
998 struct lttcomm_sock
*sock
= NULL
;
999 char uri_str
[PATH_MAX
];
1000 char *formated_name
= NULL
;
1002 sock
= lttcomm_alloc_sock_from_uri(uri
);
1004 ERR("Allocating socket");
1009 * Don't fail to create the socket if the name can't be built as it is
1010 * only used for debugging purposes.
1012 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1013 uri_str
[sizeof(uri_str
) - 1] = '\0';
1015 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1018 formated_name
= NULL
;
1022 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1023 (const char **) (formated_name
? &formated_name
: NULL
),
1024 1, create_sock
, sock
);
1026 PERROR("Failed to open \"%s\" relay socket",
1027 formated_name
?: "Unknown");
1030 DBG("Listening on %s socket %d", name
, sock
->fd
);
1032 ret
= sock
->ops
->bind(sock
);
1034 PERROR("Failed to bind socket");
1038 ret
= sock
->ops
->listen(sock
, -1);
1044 free(formated_name
);
1049 lttcomm_destroy_sock(sock
);
1051 free(formated_name
);
1056 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1060 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1061 struct lttcomm_sock
*new_sock
= NULL
;
1063 ret
= fd_tracker_open_unsuspendable_fd(
1064 the_fd_tracker
, &out_fd
,
1065 (const char **) &name
,
1066 1, accept_sock
, &socks
);
1070 new_sock
= socks
[1];
1071 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1077 * This thread manages the listening for new connections on the network
1079 static void *relay_thread_listener(void *data
)
1081 int i
, ret
, pollfd
, err
= -1;
1082 uint32_t revents
, nb_fd
;
1083 struct lttng_poll_event events
;
1084 struct lttcomm_sock
*control_sock
, *data_sock
;
1086 DBG("[thread] Relay listener started");
1088 rcu_register_thread();
1089 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1091 health_code_update();
1093 control_sock
= relay_socket_create(control_uri
, "Control listener");
1094 if (!control_sock
) {
1095 goto error_sock_control
;
1098 data_sock
= relay_socket_create(data_uri
, "Data listener");
1100 goto error_sock_relay
;
1104 * Pass 3 as size here for the thread quit pipe, control and
1107 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1109 goto error_create_poll
;
1112 /* Add the control socket */
1113 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1115 goto error_poll_add
;
1118 /* Add the data socket */
1119 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1121 goto error_poll_add
;
1124 lttng_relay_notify_ready();
1126 if (testpoint(relayd_thread_listener
)) {
1127 goto error_testpoint
;
1131 health_code_update();
1133 DBG("Listener accepting connections");
1136 health_poll_entry();
1137 ret
= lttng_poll_wait(&events
, -1);
1141 * Restart interrupted system call.
1143 if (errno
== EINTR
) {
1151 DBG("Relay new connection received");
1152 for (i
= 0; i
< nb_fd
; i
++) {
1153 health_code_update();
1155 /* Fetch once the poll data */
1156 revents
= LTTNG_POLL_GETEV(&events
, i
);
1157 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1159 /* Thread quit pipe has been closed. Killing thread. */
1160 ret
= check_thread_quit_pipe(pollfd
, revents
);
1166 if (revents
& LPOLLIN
) {
1168 * A new connection is requested, therefore a
1169 * sessiond/consumerd connection is allocated in
1170 * this thread, enqueued to a global queue and
1171 * dequeued (and freed) in the worker thread.
1174 struct relay_connection
*new_conn
;
1175 struct lttcomm_sock
*newsock
= NULL
;
1176 enum connection_type type
;
1178 if (pollfd
== data_sock
->fd
) {
1180 newsock
= accept_relayd_sock(data_sock
,
1181 "Data socket to relayd");
1183 assert(pollfd
== control_sock
->fd
);
1184 type
= RELAY_CONTROL
;
1185 newsock
= accept_relayd_sock(control_sock
,
1186 "Control socket to relayd");
1189 PERROR("accepting sock");
1193 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1196 PERROR("setsockopt inet");
1197 lttcomm_destroy_sock(newsock
);
1201 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1203 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1205 lttcomm_destroy_sock(newsock
);
1209 new_conn
= connection_create(newsock
, type
);
1211 lttcomm_destroy_sock(newsock
);
1215 /* Enqueue request for the dispatcher thread. */
1216 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1220 * Wake the dispatch queue futex.
1221 * Implicit memory barrier with the
1222 * exchange in cds_wfcq_enqueue.
1224 futex_nto1_wake(&relay_conn_queue
.futex
);
1225 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1226 ERR("socket poll error");
1229 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1239 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1241 if (data_sock
->fd
>= 0) {
1242 int data_sock_fd
= data_sock
->fd
;
1244 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1245 &data_sock_fd
, 1, close_sock
,
1248 PERROR("Failed to close the data listener socket file descriptor");
1252 lttcomm_destroy_sock(data_sock
);
1254 if (control_sock
->fd
>= 0) {
1255 int control_sock_fd
= control_sock
->fd
;
1257 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1258 &control_sock_fd
, 1, close_sock
,
1261 PERROR("Failed to close the control listener socket file descriptor");
1263 control_sock
->fd
= -1;
1265 lttcomm_destroy_sock(control_sock
);
1269 ERR("Health error occurred in %s", __func__
);
1271 health_unregister(health_relayd
);
1272 rcu_unregister_thread();
1273 DBG("Relay listener thread cleanup complete");
1274 lttng_relay_stop_threads();
1279 * This thread manages the dispatching of the requests to worker threads
1281 static void *relay_thread_dispatcher(void *data
)
1285 struct cds_wfcq_node
*node
;
1286 struct relay_connection
*new_conn
= NULL
;
1288 DBG("[thread] Relay dispatcher started");
1290 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1292 if (testpoint(relayd_thread_dispatcher
)) {
1293 goto error_testpoint
;
1296 health_code_update();
1299 health_code_update();
1301 /* Atomically prepare the queue futex */
1302 futex_nto1_prepare(&relay_conn_queue
.futex
);
1304 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1309 health_code_update();
1311 /* Dequeue commands */
1312 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1313 &relay_conn_queue
.tail
);
1315 DBG("Woken up but nothing in the relay command queue");
1316 /* Continue thread execution */
1319 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1321 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1324 * Inform worker thread of the new request. This
1325 * call is blocking so we can be assured that
1326 * the data will be read at some point in time
1327 * or wait to the end of the world :)
1329 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1331 PERROR("write connection pipe");
1332 connection_put(new_conn
);
1335 } while (node
!= NULL
);
1337 /* Futex wait on queue. Blocking call on futex() */
1338 health_poll_entry();
1339 futex_nto1_wait(&relay_conn_queue
.futex
);
1343 /* Normal exit, no error */
1350 ERR("Health error occurred in %s", __func__
);
1352 health_unregister(health_relayd
);
1353 DBG("Dispatch thread dying");
1354 lttng_relay_stop_threads();
1358 static bool session_streams_have_index(const struct relay_session
*session
)
1360 return session
->minor
>= 4 && !session
->snapshot
;
1364 * Handle the RELAYD_CREATE_SESSION command.
1366 * On success, send back the session id or else return a negative value.
1368 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1369 struct relay_connection
*conn
,
1370 const struct lttng_buffer_view
*payload
)
1374 struct relay_session
*session
= NULL
;
1375 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1376 char session_name
[LTTNG_NAME_MAX
] = {};
1377 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1378 uint32_t live_timer
= 0;
1379 bool snapshot
= false;
1380 bool session_name_contains_creation_timestamp
= false;
1381 /* Left nil for peers < 2.11. */
1382 char base_path
[LTTNG_PATH_MAX
] = {};
1383 lttng_uuid sessiond_uuid
= {};
1384 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1385 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1386 LTTNG_OPTIONAL(time_t) creation_time
= {};
1387 struct lttng_dynamic_buffer reply_payload
;
1389 lttng_dynamic_buffer_init(&reply_payload
);
1391 if (conn
->minor
< 4) {
1392 /* From 2.1 to 2.3 */
1394 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1395 /* From 2.4 to 2.10 */
1396 ret
= cmd_create_session_2_4(payload
, session_name
,
1397 hostname
, &live_timer
, &snapshot
);
1399 bool has_current_chunk
;
1400 uint64_t current_chunk_id_value
;
1401 time_t creation_time_value
;
1402 uint64_t id_sessiond_value
;
1404 /* From 2.11 to ... */
1405 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1406 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1407 sessiond_uuid
, &has_current_chunk
,
1408 ¤t_chunk_id_value
, &creation_time_value
,
1409 &session_name_contains_creation_timestamp
);
1410 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1411 /* The nil UUID is reserved for pre-2.11 clients. */
1412 ERR("Illegal nil UUID announced by peer in create session command");
1416 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1417 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1418 if (has_current_chunk
) {
1419 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1420 current_chunk_id_value
);
1428 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1429 snapshot
, sessiond_uuid
,
1430 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1431 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1432 creation_time
.is_set
? &creation_time
.value
: NULL
,
1433 conn
->major
, conn
->minor
,
1434 session_name_contains_creation_timestamp
);
1439 assert(!conn
->session
);
1440 conn
->session
= session
;
1441 DBG("Created session %" PRIu64
, session
->id
);
1443 reply
.generic
.session_id
= htobe64(session
->id
);
1447 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1449 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1452 if (conn
->minor
< 11) {
1453 /* From 2.1 to 2.10 */
1454 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1455 &reply
.generic
, sizeof(reply
.generic
));
1457 ERR("Failed to append \"create session\" command reply header to payload buffer");
1462 const uint32_t output_path_length
=
1463 session
? strlen(session
->output_path
) + 1 : 0;
1465 reply
.output_path_length
= htobe32(output_path_length
);
1466 ret
= lttng_dynamic_buffer_append(
1467 &reply_payload
, &reply
, sizeof(reply
));
1469 ERR("Failed to append \"create session\" command reply header to payload buffer");
1473 if (output_path_length
) {
1474 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1475 session
->output_path
,
1476 output_path_length
);
1478 ERR("Failed to append \"create session\" command reply path to payload buffer");
1484 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1485 reply_payload
.size
, 0);
1486 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1487 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1488 reply_payload
.size
, send_ret
);
1492 if (ret
< 0 && session
) {
1493 session_put(session
);
1495 lttng_dynamic_buffer_reset(&reply_payload
);
1500 * When we have received all the streams and the metadata for a channel,
1501 * we make them visible to the viewer threads.
1503 static void publish_connection_local_streams(struct relay_connection
*conn
)
1505 struct relay_stream
*stream
;
1506 struct relay_session
*session
= conn
->session
;
1509 * We publish all streams belonging to a session atomically wrt
1512 pthread_mutex_lock(&session
->lock
);
1514 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1516 stream_publish(stream
);
1521 * Inform the viewer that there are new streams in the session.
1523 if (session
->viewer_attached
) {
1524 uatomic_set(&session
->new_streams
, 1);
1526 pthread_mutex_unlock(&session
->lock
);
1529 static int conform_channel_path(char *channel_path
)
1533 if (strstr("../", channel_path
)) {
1534 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1540 if (*channel_path
== '/') {
1541 const size_t len
= strlen(channel_path
);
1544 * Channel paths from peers prior to 2.11 are expressed as an
1545 * absolute path that is, in reality, relative to the relay
1546 * daemon's output directory. Remove the leading slash so it
1547 * is correctly interpreted as a relative path later on.
1549 * len (and not len - 1) is used to copy the trailing NULL.
1551 bcopy(channel_path
+ 1, channel_path
, len
);
1558 * relay_add_stream: allocate a new stream for a session
1560 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1561 struct relay_connection
*conn
,
1562 const struct lttng_buffer_view
*payload
)
1566 struct relay_session
*session
= conn
->session
;
1567 struct relay_stream
*stream
= NULL
;
1568 struct lttcomm_relayd_status_stream reply
;
1569 struct ctf_trace
*trace
= NULL
;
1570 uint64_t stream_handle
= -1ULL;
1571 char *path_name
= NULL
, *channel_name
= NULL
;
1572 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1573 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1575 if (!session
|| !conn
->version_check_done
) {
1576 ERR("Trying to add a stream before version check");
1578 goto end_no_session
;
1581 if (session
->minor
== 1) {
1583 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1585 } else if (session
->minor
> 1 && session
->minor
< 11) {
1586 /* From 2.2 to 2.10 */
1587 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1588 &channel_name
, &tracefile_size
, &tracefile_count
);
1590 /* From 2.11 to ... */
1591 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1592 &channel_name
, &tracefile_size
, &tracefile_count
,
1593 &stream_chunk_id
.value
);
1594 stream_chunk_id
.is_set
= true;
1601 if (conform_channel_path(path_name
)) {
1606 * Backward compatibility for --group-output-by-session.
1607 * Prior to lttng 2.11, the complete path is passed by the stream.
1608 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1609 * >=2.11 the chunk is responsible for the output path. When dealing
1610 * with producer < 2.11 the chunk output_path is the root output path
1611 * and the stream carries the complete path (path_name).
1612 * To support --group-output-by-session with older producer (<2.11), we
1613 * need to craft the path based on the stream path.
1615 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1616 if (conn
->minor
< 4) {
1618 * From 2.1 to 2.3, the session_name is not passed on
1619 * the RELAYD_CREATE_SESSION command. The session name
1620 * is necessary to detect the presence of a base_path
1621 * inside the stream path. Without it we cannot perform
1622 * a valid group-output-by-session transformation.
1624 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1625 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1626 session
->id
, path_name
);
1627 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1628 char *group_by_session_path_name
;
1630 assert(session
->session_name
[0] != '\0');
1632 group_by_session_path_name
=
1633 backward_compat_group_by_session(
1635 session
->session_name
,
1636 session
->creation_time
.value
);
1637 if (!group_by_session_path_name
) {
1638 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1643 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1644 path_name
, group_by_session_path_name
);
1647 path_name
= group_by_session_path_name
;
1651 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1656 /* This stream here has one reference on the trace. */
1657 pthread_mutex_lock(&last_relay_stream_id_lock
);
1658 stream_handle
= ++last_relay_stream_id
;
1659 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1661 /* We pass ownership of path_name and channel_name. */
1662 stream
= stream_create(trace
, stream_handle
, path_name
,
1663 channel_name
, tracefile_size
, tracefile_count
);
1665 channel_name
= NULL
;
1668 * Streams are the owners of their trace. Reference to trace is
1669 * kept within stream_create().
1671 ctf_trace_put(trace
);
1674 memset(&reply
, 0, sizeof(reply
));
1675 reply
.handle
= htobe64(stream_handle
);
1677 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1679 reply
.ret_code
= htobe32(LTTNG_OK
);
1682 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1683 sizeof(struct lttcomm_relayd_status_stream
), 0);
1684 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1685 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1697 * relay_close_stream: close a specific stream
1699 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1700 struct relay_connection
*conn
,
1701 const struct lttng_buffer_view
*payload
)
1705 struct relay_session
*session
= conn
->session
;
1706 struct lttcomm_relayd_close_stream stream_info
;
1707 struct lttcomm_relayd_generic_reply reply
;
1708 struct relay_stream
*stream
;
1710 DBG("Close stream received");
1712 if (!session
|| !conn
->version_check_done
) {
1713 ERR("Trying to close a stream before version check");
1715 goto end_no_session
;
1718 if (payload
->size
< sizeof(stream_info
)) {
1719 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1720 sizeof(stream_info
), payload
->size
);
1722 goto end_no_session
;
1724 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1725 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1726 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1728 stream
= stream_get_by_id(stream_info
.stream_id
);
1735 * Set last_net_seq_num before the close flag. Required by data
1738 pthread_mutex_lock(&stream
->lock
);
1739 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1740 pthread_mutex_unlock(&stream
->lock
);
1743 * This is one of the conditions which may trigger a stream close
1744 * with the others being:
1745 * 1) A close command is received for a stream
1746 * 2) The control connection owning the stream is closed
1747 * 3) We have received all of the stream's data _after_ a close
1750 try_stream_close(stream
);
1755 memset(&reply
, 0, sizeof(reply
));
1757 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1759 reply
.ret_code
= htobe32(LTTNG_OK
);
1761 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1762 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1763 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1764 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1774 * relay_reset_metadata: reset a metadata stream
1777 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1778 struct relay_connection
*conn
,
1779 const struct lttng_buffer_view
*payload
)
1783 struct relay_session
*session
= conn
->session
;
1784 struct lttcomm_relayd_reset_metadata stream_info
;
1785 struct lttcomm_relayd_generic_reply reply
;
1786 struct relay_stream
*stream
;
1788 DBG("Reset metadata received");
1790 if (!session
|| !conn
->version_check_done
) {
1791 ERR("Trying to reset a metadata stream before version check");
1793 goto end_no_session
;
1796 if (payload
->size
< sizeof(stream_info
)) {
1797 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1798 sizeof(stream_info
), payload
->size
);
1800 goto end_no_session
;
1802 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1803 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1804 stream_info
.version
= be64toh(stream_info
.version
);
1806 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1808 /* Unsupported for live sessions for now. */
1809 if (session
->live_timer
!= 0) {
1814 stream
= stream_get_by_id(stream_info
.stream_id
);
1819 pthread_mutex_lock(&stream
->lock
);
1820 if (!stream
->is_metadata
) {
1825 ret
= stream_reset_file(stream
);
1827 ERR("Failed to reset metadata stream %" PRIu64
1828 ": stream_path = %s, channel = %s",
1829 stream
->stream_handle
, stream
->path_name
,
1830 stream
->channel_name
);
1834 pthread_mutex_unlock(&stream
->lock
);
1838 memset(&reply
, 0, sizeof(reply
));
1840 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1842 reply
.ret_code
= htobe32(LTTNG_OK
);
1844 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1845 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1846 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1847 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1857 * relay_unknown_command: send -1 if received unknown command
1859 static void relay_unknown_command(struct relay_connection
*conn
)
1861 struct lttcomm_relayd_generic_reply reply
;
1864 memset(&reply
, 0, sizeof(reply
));
1865 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1866 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1867 if (send_ret
< sizeof(reply
)) {
1868 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1873 * relay_start: send an acknowledgment to the client to tell if we are
1874 * ready to receive data. We are ready if a session is established.
1876 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1877 struct relay_connection
*conn
,
1878 const struct lttng_buffer_view
*payload
)
1882 struct lttcomm_relayd_generic_reply reply
;
1883 struct relay_session
*session
= conn
->session
;
1886 DBG("Trying to start the streaming without a session established");
1887 ret
= htobe32(LTTNG_ERR_UNK
);
1890 memset(&reply
, 0, sizeof(reply
));
1891 reply
.ret_code
= htobe32(LTTNG_OK
);
1892 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1894 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1895 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1904 * relay_recv_metadata: receive the metadata for the session.
1906 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1907 struct relay_connection
*conn
,
1908 const struct lttng_buffer_view
*payload
)
1911 struct relay_session
*session
= conn
->session
;
1912 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1913 struct relay_stream
*metadata_stream
;
1914 uint64_t metadata_payload_size
;
1915 struct lttng_buffer_view packet_view
;
1918 ERR("Metadata sent before version check");
1923 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1924 ERR("Incorrect data size");
1928 metadata_payload_size
= recv_hdr
->data_size
-
1929 sizeof(struct lttcomm_relayd_metadata_payload
);
1931 memcpy(&metadata_payload_header
, payload
->data
,
1932 sizeof(metadata_payload_header
));
1933 metadata_payload_header
.stream_id
= be64toh(
1934 metadata_payload_header
.stream_id
);
1935 metadata_payload_header
.padding_size
= be32toh(
1936 metadata_payload_header
.padding_size
);
1938 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1939 if (!metadata_stream
) {
1944 packet_view
= lttng_buffer_view_from_view(payload
,
1945 sizeof(metadata_payload_header
), metadata_payload_size
);
1946 if (!packet_view
.data
) {
1947 ERR("Invalid metadata packet length announced by header");
1952 pthread_mutex_lock(&metadata_stream
->lock
);
1953 ret
= stream_write(metadata_stream
, &packet_view
,
1954 metadata_payload_header
.padding_size
);
1955 pthread_mutex_unlock(&metadata_stream
->lock
);
1961 stream_put(metadata_stream
);
1967 * relay_send_version: send relayd version number
1969 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1970 struct relay_connection
*conn
,
1971 const struct lttng_buffer_view
*payload
)
1975 struct lttcomm_relayd_version reply
, msg
;
1976 bool compatible
= true;
1978 conn
->version_check_done
= true;
1980 /* Get version from the other side. */
1981 if (payload
->size
< sizeof(msg
)) {
1982 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1983 sizeof(msg
), payload
->size
);
1988 memcpy(&msg
, payload
->data
, sizeof(msg
));
1989 msg
.major
= be32toh(msg
.major
);
1990 msg
.minor
= be32toh(msg
.minor
);
1992 memset(&reply
, 0, sizeof(reply
));
1993 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1994 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1996 /* Major versions must be the same */
1997 if (reply
.major
!= msg
.major
) {
1998 DBG("Incompatible major versions (%u vs %u), deleting session",
1999 reply
.major
, msg
.major
);
2003 conn
->major
= reply
.major
;
2004 /* We adapt to the lowest compatible version */
2005 if (reply
.minor
<= msg
.minor
) {
2006 conn
->minor
= reply
.minor
;
2008 conn
->minor
= msg
.minor
;
2011 reply
.major
= htobe32(reply
.major
);
2012 reply
.minor
= htobe32(reply
.minor
);
2013 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2015 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2016 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2029 DBG("Version check done using protocol %u.%u", conn
->major
,
2037 * Check for data pending for a given stream id from the session daemon.
2039 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2040 struct relay_connection
*conn
,
2041 const struct lttng_buffer_view
*payload
)
2043 struct relay_session
*session
= conn
->session
;
2044 struct lttcomm_relayd_data_pending msg
;
2045 struct lttcomm_relayd_generic_reply reply
;
2046 struct relay_stream
*stream
;
2049 uint64_t stream_seq
;
2051 DBG("Data pending command received");
2053 if (!session
|| !conn
->version_check_done
) {
2054 ERR("Trying to check for data before version check");
2056 goto end_no_session
;
2059 if (payload
->size
< sizeof(msg
)) {
2060 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2061 sizeof(msg
), payload
->size
);
2063 goto end_no_session
;
2065 memcpy(&msg
, payload
->data
, sizeof(msg
));
2066 msg
.stream_id
= be64toh(msg
.stream_id
);
2067 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2069 stream
= stream_get_by_id(msg
.stream_id
);
2070 if (stream
== NULL
) {
2075 pthread_mutex_lock(&stream
->lock
);
2077 if (session_streams_have_index(session
)) {
2079 * Ensure that both the index and stream data have been
2080 * flushed up to the requested point.
2082 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2084 stream_seq
= stream
->prev_data_seq
;
2086 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2087 ", prev_index_seq %" PRIu64
2088 ", and last_seq %" PRIu64
, msg
.stream_id
,
2089 stream
->prev_data_seq
, stream
->prev_index_seq
,
2090 msg
.last_net_seq_num
);
2092 /* Avoid wrapping issue */
2093 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2094 /* Data has in fact been written and is NOT pending */
2097 /* Data still being streamed thus pending */
2101 stream
->data_pending_check_done
= true;
2102 pthread_mutex_unlock(&stream
->lock
);
2107 memset(&reply
, 0, sizeof(reply
));
2108 reply
.ret_code
= htobe32(ret
);
2109 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2110 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2111 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2121 * Wait for the control socket to reach a quiescent state.
2123 * Note that for now, when receiving this command from the session
2124 * daemon, this means that every subsequent commands or data received on
2125 * the control socket has been handled. So, this is why we simply return
2128 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2129 struct relay_connection
*conn
,
2130 const struct lttng_buffer_view
*payload
)
2134 struct relay_stream
*stream
;
2135 struct lttcomm_relayd_quiescent_control msg
;
2136 struct lttcomm_relayd_generic_reply reply
;
2138 DBG("Checking quiescent state on control socket");
2140 if (!conn
->session
|| !conn
->version_check_done
) {
2141 ERR("Trying to check for data before version check");
2143 goto end_no_session
;
2146 if (payload
->size
< sizeof(msg
)) {
2147 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2148 sizeof(msg
), payload
->size
);
2150 goto end_no_session
;
2152 memcpy(&msg
, payload
->data
, sizeof(msg
));
2153 msg
.stream_id
= be64toh(msg
.stream_id
);
2155 stream
= stream_get_by_id(msg
.stream_id
);
2159 pthread_mutex_lock(&stream
->lock
);
2160 stream
->data_pending_check_done
= true;
2161 pthread_mutex_unlock(&stream
->lock
);
2163 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2166 memset(&reply
, 0, sizeof(reply
));
2167 reply
.ret_code
= htobe32(LTTNG_OK
);
2168 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2169 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2170 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2182 * Initialize a data pending command. This means that a consumer is about
2183 * to ask for data pending for each stream it holds. Simply iterate over
2184 * all streams of a session and set the data_pending_check_done flag.
2186 * This command returns to the client a LTTNG_OK code.
2188 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2189 struct relay_connection
*conn
,
2190 const struct lttng_buffer_view
*payload
)
2194 struct lttng_ht_iter iter
;
2195 struct lttcomm_relayd_begin_data_pending msg
;
2196 struct lttcomm_relayd_generic_reply reply
;
2197 struct relay_stream
*stream
;
2202 DBG("Init streams for data pending");
2204 if (!conn
->session
|| !conn
->version_check_done
) {
2205 ERR("Trying to check for data before version check");
2207 goto end_no_session
;
2210 if (payload
->size
< sizeof(msg
)) {
2211 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2212 sizeof(msg
), payload
->size
);
2214 goto end_no_session
;
2216 memcpy(&msg
, payload
->data
, sizeof(msg
));
2217 msg
.session_id
= be64toh(msg
.session_id
);
2220 * Iterate over all streams to set the begin data pending flag.
2221 * For now, the streams are indexed by stream handle so we have
2222 * to iterate over all streams to find the one associated with
2223 * the right session_id.
2226 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2228 if (!stream_get(stream
)) {
2231 if (stream
->trace
->session
->id
== msg
.session_id
) {
2232 pthread_mutex_lock(&stream
->lock
);
2233 stream
->data_pending_check_done
= false;
2234 pthread_mutex_unlock(&stream
->lock
);
2235 DBG("Set begin data pending flag to stream %" PRIu64
,
2236 stream
->stream_handle
);
2242 memset(&reply
, 0, sizeof(reply
));
2243 /* All good, send back reply. */
2244 reply
.ret_code
= htobe32(LTTNG_OK
);
2246 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2247 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2248 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2260 * End data pending command. This will check, for a given session id, if
2261 * each stream associated with it has its data_pending_check_done flag
2262 * set. If not, this means that the client lost track of the stream but
2263 * the data is still being streamed on our side. In this case, we inform
2264 * the client that data is in flight.
2266 * Return to the client if there is data in flight or not with a ret_code.
2268 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2269 struct relay_connection
*conn
,
2270 const struct lttng_buffer_view
*payload
)
2274 struct lttng_ht_iter iter
;
2275 struct lttcomm_relayd_end_data_pending msg
;
2276 struct lttcomm_relayd_generic_reply reply
;
2277 struct relay_stream
*stream
;
2278 uint32_t is_data_inflight
= 0;
2280 DBG("End data pending command");
2282 if (!conn
->session
|| !conn
->version_check_done
) {
2283 ERR("Trying to check for data before version check");
2285 goto end_no_session
;
2288 if (payload
->size
< sizeof(msg
)) {
2289 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2290 sizeof(msg
), payload
->size
);
2292 goto end_no_session
;
2294 memcpy(&msg
, payload
->data
, sizeof(msg
));
2295 msg
.session_id
= be64toh(msg
.session_id
);
2298 * Iterate over all streams to see if the begin data pending
2302 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2304 if (!stream_get(stream
)) {
2307 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2311 pthread_mutex_lock(&stream
->lock
);
2312 if (!stream
->data_pending_check_done
) {
2313 uint64_t stream_seq
;
2315 if (session_streams_have_index(conn
->session
)) {
2317 * Ensure that both the index and stream data have been
2318 * flushed up to the requested point.
2320 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2322 stream_seq
= stream
->prev_data_seq
;
2324 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2325 is_data_inflight
= 1;
2326 DBG("Data is still in flight for stream %" PRIu64
,
2327 stream
->stream_handle
);
2328 pthread_mutex_unlock(&stream
->lock
);
2333 pthread_mutex_unlock(&stream
->lock
);
2338 memset(&reply
, 0, sizeof(reply
));
2339 /* All good, send back reply. */
2340 reply
.ret_code
= htobe32(is_data_inflight
);
2342 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2343 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2344 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2356 * Receive an index for a specific stream.
2358 * Return 0 on success else a negative value.
2360 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2361 struct relay_connection
*conn
,
2362 const struct lttng_buffer_view
*payload
)
2366 struct relay_session
*session
= conn
->session
;
2367 struct lttcomm_relayd_index index_info
;
2368 struct lttcomm_relayd_generic_reply reply
;
2369 struct relay_stream
*stream
;
2374 DBG("Relay receiving index");
2376 if (!session
|| !conn
->version_check_done
) {
2377 ERR("Trying to close a stream before version check");
2379 goto end_no_session
;
2382 msg_len
= lttcomm_relayd_index_len(
2383 lttng_to_index_major(conn
->major
, conn
->minor
),
2384 lttng_to_index_minor(conn
->major
, conn
->minor
));
2385 if (payload
->size
< msg_len
) {
2386 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2387 msg_len
, payload
->size
);
2389 goto end_no_session
;
2391 memcpy(&index_info
, payload
->data
, msg_len
);
2392 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2393 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2394 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2395 index_info
.content_size
= be64toh(index_info
.content_size
);
2396 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2397 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2398 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2399 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2401 if (conn
->minor
>= 8) {
2402 index_info
.stream_instance_id
=
2403 be64toh(index_info
.stream_instance_id
);
2404 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2406 index_info
.stream_instance_id
= -1ULL;
2407 index_info
.packet_seq_num
= -1ULL;
2410 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2412 ERR("stream_get_by_id not found");
2417 pthread_mutex_lock(&stream
->lock
);
2418 ret
= stream_add_index(stream
, &index_info
);
2419 pthread_mutex_unlock(&stream
->lock
);
2421 goto end_stream_put
;
2427 memset(&reply
, 0, sizeof(reply
));
2429 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2431 reply
.ret_code
= htobe32(LTTNG_OK
);
2433 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2434 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2435 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2444 * Receive the streams_sent message.
2446 * Return 0 on success else a negative value.
2448 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2449 struct relay_connection
*conn
,
2450 const struct lttng_buffer_view
*payload
)
2454 struct lttcomm_relayd_generic_reply reply
;
2458 DBG("Relay receiving streams_sent");
2460 if (!conn
->session
|| !conn
->version_check_done
) {
2461 ERR("Trying to close a stream before version check");
2463 goto end_no_session
;
2467 * Publish every pending stream in the connection recv list which are
2468 * now ready to be used by the viewer.
2470 publish_connection_local_streams(conn
);
2472 memset(&reply
, 0, sizeof(reply
));
2473 reply
.ret_code
= htobe32(LTTNG_OK
);
2474 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2475 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2476 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2488 static ssize_t
relay_unpack_rotate_streams_header(
2489 const struct lttng_buffer_view
*payload
,
2490 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2492 struct lttcomm_relayd_rotate_streams rotate_streams
;
2494 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2495 * This is the smallest version of this structure, but it can be larger;
2496 * this variable is updated once the proper size of the structure is known.
2498 * See comment at the declaration of this structure for more information.
2500 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2501 size_t expected_payload_size_no_padding
,
2502 expected_payload_size_3_bytes_padding
,
2503 expected_payload_size_7_bytes_padding
;
2505 if (payload
->size
< header_len
) {
2506 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2507 header_len
, payload
->size
);
2512 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2513 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2515 * We start by "unpacking" `stream_count` to figure out the padding length
2516 * emited by our peer.
2518 memcpy(&rotate_streams
.stream_count
, payload
->data
,
2519 sizeof(rotate_streams
.stream_count
));
2520 rotate_streams
= (typeof(rotate_streams
)) {
2521 .stream_count
= be32toh(rotate_streams
.stream_count
),
2525 * Payload size expected given the possible padding lengths in
2526 * `struct lttcomm_relayd_rotate_streams`.
2528 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2529 sizeof(*rotate_streams
.rotation_positions
)) +
2530 sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2531 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2532 sizeof(*rotate_streams
.rotation_positions
)) +
2533 sizeof(struct lttcomm_relayd_rotate_streams_3_bytes_padding
);
2534 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2535 sizeof(*rotate_streams
.rotation_positions
)) +
2536 sizeof(struct lttcomm_relayd_rotate_streams_7_bytes_padding
);
2538 if (payload
->size
== expected_payload_size_no_padding
) {
2539 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2542 * This handles cases where someone might build with
2543 * -fpack-struct or any other toolchain that wouldn't produce
2544 * padding to align `value`.
2546 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2548 header_len
= sizeof(packed_rotate_streams
);
2549 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2551 /* Unpack the packed structure to the natively-packed version. */
2552 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2553 .stream_count
= be32toh(packed_rotate_streams
.stream_count
),
2554 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2555 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2556 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2559 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2560 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2562 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2564 header_len
= sizeof(padded_rotate_streams
);
2565 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2567 /* Unpack the 3-byte padded structure to the natively-packed version. */
2568 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2569 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2570 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2571 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2572 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2575 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2576 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2578 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2580 header_len
= sizeof(padded_rotate_streams
);
2581 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2583 /* Unpack the 7-byte padded structure to the natively-packed version. */
2584 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2585 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2586 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2587 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2588 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2592 header_len
= sizeof(padded_rotate_streams
);
2594 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2595 expected_payload_size_no_padding
,
2596 expected_payload_size_3_bytes_padding
,
2597 expected_payload_size_7_bytes_padding
,
2608 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2609 * session rotation feature (not the tracefile rotation feature).
2611 static int relay_rotate_session_streams(
2612 const struct lttcomm_relayd_hdr
*recv_hdr
,
2613 struct relay_connection
*conn
,
2614 const struct lttng_buffer_view
*payload
)
2619 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2620 struct relay_session
*session
= conn
->session
;
2621 struct lttcomm_relayd_rotate_streams rotate_streams
;
2622 struct lttcomm_relayd_generic_reply reply
= {};
2623 struct relay_stream
*stream
= NULL
;
2624 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2625 struct lttng_buffer_view stream_positions
;
2626 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2627 const char *chunk_id_str
= "none";
2630 if (!session
|| !conn
->version_check_done
) {
2631 ERR("Trying to rotate a stream before version check");
2636 if (session
->major
== 2 && session
->minor
< 11) {
2637 ERR("Unsupported feature before 2.11");
2642 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2643 if (header_len
< 0) {
2648 if (rotate_streams
.new_chunk_id
.is_set
) {
2650 * Retrieve the trace chunk the stream must transition to. As
2651 * per the protocol, this chunk should have been created
2652 * before this command is received.
2654 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2655 sessiond_trace_chunk_registry
,
2656 session
->sessiond_uuid
,
2657 conn
->session
->id_sessiond
.is_set
?
2658 conn
->session
->id_sessiond
.value
:
2660 rotate_streams
.new_chunk_id
.value
);
2661 if (!next_trace_chunk
) {
2662 char uuid_str
[LTTNG_UUID_STR_LEN
];
2664 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2665 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2666 ", trace_chunk_id = %" PRIu64
,
2667 uuid_str
, session
->id
,
2668 rotate_streams
.new_chunk_id
.value
);
2669 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2674 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2675 rotate_streams
.new_chunk_id
.value
);
2676 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2677 chunk_id_str
= "formatting error";
2679 chunk_id_str
= chunk_id_buf
;
2683 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2684 rotate_streams
.stream_count
, session
->session_name
,
2687 stream_positions
= lttng_buffer_view_from_view(payload
,
2689 if (!stream_positions
.data
||
2690 stream_positions
.size
<
2691 (rotate_streams
.stream_count
*
2692 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2693 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2698 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2699 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2700 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2701 const struct lttcomm_relayd_stream_rotation_position pos
= {
2702 .stream_id
= be64toh(position_comm
->stream_id
),
2703 .rotate_at_seq_num
= be64toh(
2704 position_comm
->rotate_at_seq_num
),
2707 stream
= stream_get_by_id(pos
.stream_id
);
2709 reply_code
= LTTNG_ERR_INVALID
;
2714 pthread_mutex_lock(&stream
->lock
);
2715 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2716 pos
.rotate_at_seq_num
);
2717 pthread_mutex_unlock(&stream
->lock
);
2719 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2727 reply_code
= LTTNG_OK
;
2734 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2735 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2736 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2737 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2738 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2743 lttng_trace_chunk_put(next_trace_chunk
);
2748 * relay_create_trace_chunk: create a new trace chunk
2750 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2751 struct relay_connection
*conn
,
2752 const struct lttng_buffer_view
*payload
)
2756 struct relay_session
*session
= conn
->session
;
2757 struct lttcomm_relayd_create_trace_chunk
*msg
;
2758 struct lttcomm_relayd_generic_reply reply
= {};
2759 struct lttng_buffer_view header_view
;
2760 struct lttng_buffer_view chunk_name_view
;
2761 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2762 enum lttng_error_code reply_code
= LTTNG_OK
;
2763 enum lttng_trace_chunk_status chunk_status
;
2764 const char *new_path
;
2766 if (!session
|| !conn
->version_check_done
) {
2767 ERR("Trying to create a trace chunk before version check");
2772 if (session
->major
== 2 && session
->minor
< 11) {
2773 ERR("Chunk creation command is unsupported before 2.11");
2778 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2779 if (!header_view
.data
) {
2780 ERR("Failed to receive payload of chunk creation command");
2785 /* Convert to host endianness. */
2786 msg
= (typeof(msg
)) header_view
.data
;
2787 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2788 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2789 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2791 pthread_mutex_lock(&conn
->session
->lock
);
2792 session
->ongoing_rotation
= true;
2793 if (session
->current_trace_chunk
&&
2794 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2795 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2796 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2797 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2798 ERR("Failed to rename old chunk");
2800 reply_code
= LTTNG_ERR_UNK
;
2804 if (!session
->current_trace_chunk
) {
2805 if (!session
->has_rotated
) {
2811 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2813 chunk
= lttng_trace_chunk_create(
2814 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2816 ERR("Failed to create trace chunk in trace chunk creation command");
2818 reply_code
= LTTNG_ERR_NOMEM
;
2821 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2823 if (msg
->override_name_length
) {
2826 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2828 msg
->override_name_length
);
2829 name
= chunk_name_view
.data
;
2830 if (!name
|| name
[msg
->override_name_length
- 1]) {
2831 ERR("Failed to receive payload of chunk creation command");
2833 reply_code
= LTTNG_ERR_INVALID
;
2837 chunk_status
= lttng_trace_chunk_override_name(
2838 chunk
, chunk_name_view
.data
);
2839 switch (chunk_status
) {
2840 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2842 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2843 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2844 reply_code
= LTTNG_ERR_INVALID
;
2848 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2849 reply_code
= LTTNG_ERR_UNK
;
2855 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2856 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2857 reply_code
= LTTNG_ERR_UNK
;
2862 assert(conn
->session
->output_directory
);
2863 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2864 conn
->session
->output_directory
);
2865 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2866 reply_code
= LTTNG_ERR_UNK
;
2871 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2872 sessiond_trace_chunk_registry
,
2873 conn
->session
->sessiond_uuid
,
2874 conn
->session
->id_sessiond
.is_set
?
2875 conn
->session
->id_sessiond
.value
:
2878 if (!published_chunk
) {
2879 char uuid_str
[LTTNG_UUID_STR_LEN
];
2881 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2882 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2887 reply_code
= LTTNG_ERR_NOMEM
;
2891 if (conn
->session
->pending_closure_trace_chunk
) {
2893 * Invalid; this means a second create_trace_chunk command was
2894 * received before a close_trace_chunk.
2896 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2897 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2901 conn
->session
->pending_closure_trace_chunk
=
2902 conn
->session
->current_trace_chunk
;
2903 conn
->session
->current_trace_chunk
= published_chunk
;
2904 published_chunk
= NULL
;
2905 if (!conn
->session
->pending_closure_trace_chunk
) {
2906 session
->ongoing_rotation
= false;
2909 pthread_mutex_unlock(&conn
->session
->lock
);
2910 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2911 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2913 sizeof(struct lttcomm_relayd_generic_reply
),
2915 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2916 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2921 lttng_trace_chunk_put(chunk
);
2922 lttng_trace_chunk_put(published_chunk
);
2927 * relay_close_trace_chunk: close a trace chunk
2929 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2930 struct relay_connection
*conn
,
2931 const struct lttng_buffer_view
*payload
)
2933 int ret
= 0, buf_ret
;
2935 struct relay_session
*session
= conn
->session
;
2936 struct lttcomm_relayd_close_trace_chunk
*msg
;
2937 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2938 struct lttng_buffer_view header_view
;
2939 struct lttng_trace_chunk
*chunk
= NULL
;
2940 enum lttng_error_code reply_code
= LTTNG_OK
;
2941 enum lttng_trace_chunk_status chunk_status
;
2943 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2944 time_t close_timestamp
;
2945 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2946 size_t path_length
= 0;
2947 const char *chunk_name
= NULL
;
2948 struct lttng_dynamic_buffer reply_payload
;
2949 const char *new_path
;
2951 lttng_dynamic_buffer_init(&reply_payload
);
2953 if (!session
|| !conn
->version_check_done
) {
2954 ERR("Trying to close a trace chunk before version check");
2959 if (session
->major
== 2 && session
->minor
< 11) {
2960 ERR("Chunk close command is unsupported before 2.11");
2965 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2966 if (!header_view
.data
) {
2967 ERR("Failed to receive payload of chunk close command");
2972 /* Convert to host endianness. */
2973 msg
= (typeof(msg
)) header_view
.data
;
2974 chunk_id
= be64toh(msg
->chunk_id
);
2975 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2976 close_command
= (typeof(close_command
)){
2977 .value
= be32toh(msg
->close_command
.value
),
2978 .is_set
= msg
->close_command
.is_set
,
2981 chunk
= sessiond_trace_chunk_registry_get_chunk(
2982 sessiond_trace_chunk_registry
,
2983 conn
->session
->sessiond_uuid
,
2984 conn
->session
->id_sessiond
.is_set
?
2985 conn
->session
->id_sessiond
.value
:
2989 char uuid_str
[LTTNG_UUID_STR_LEN
];
2991 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2992 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2997 reply_code
= LTTNG_ERR_NOMEM
;
3001 pthread_mutex_lock(&session
->lock
);
3002 if (close_command
.is_set
&&
3003 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3005 * Clear command. It is a protocol error to ask for a
3006 * clear on a relay which does not allow it. Querying
3007 * the configuration allows figuring out whether
3008 * clearing is allowed before doing the clear.
3010 if (!opt_allow_clear
) {
3012 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3013 goto end_unlock_session
;
3016 if (session
->pending_closure_trace_chunk
&&
3017 session
->pending_closure_trace_chunk
!= chunk
) {
3018 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3019 session
->session_name
);
3020 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3022 goto end_unlock_session
;
3025 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3026 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3027 if (close_command
.is_set
&&
3028 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3029 !session
->has_rotated
) {
3030 /* New chunk stays in session output directory. */
3033 /* Use chunk name for new chunk. */
3036 /* Rename new chunk path. */
3037 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3039 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3041 goto end_unlock_session
;
3043 session
->ongoing_rotation
= false;
3045 if ((!close_command
.is_set
||
3046 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3047 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3048 const char *old_path
;
3050 if (!session
->has_rotated
) {
3055 /* We need to move back the .tmp_old_chunk to its rightful place. */
3056 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3057 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3059 goto end_unlock_session
;
3062 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3063 chunk
, close_timestamp
);
3064 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3065 ERR("Failed to set trace chunk close timestamp");
3067 reply_code
= LTTNG_ERR_UNK
;
3068 goto end_unlock_session
;
3071 if (close_command
.is_set
) {
3072 chunk_status
= lttng_trace_chunk_set_close_command(
3073 chunk
, close_command
.value
);
3074 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3076 reply_code
= LTTNG_ERR_INVALID
;
3077 goto end_unlock_session
;
3080 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3081 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3082 ERR("Failed to get chunk name");
3084 reply_code
= LTTNG_ERR_UNK
;
3085 goto end_unlock_session
;
3087 if (!session
->has_rotated
&& !session
->snapshot
) {
3088 ret
= lttng_strncpy(closed_trace_chunk_path
,
3089 session
->output_path
,
3090 sizeof(closed_trace_chunk_path
));
3092 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3093 strlen(session
->output_path
),
3094 sizeof(closed_trace_chunk_path
));
3095 reply_code
= LTTNG_ERR_NOMEM
;
3097 goto end_unlock_session
;
3100 if (session
->snapshot
) {
3101 ret
= snprintf(closed_trace_chunk_path
,
3102 sizeof(closed_trace_chunk_path
),
3103 "%s/%s", session
->output_path
,
3106 ret
= snprintf(closed_trace_chunk_path
,
3107 sizeof(closed_trace_chunk_path
),
3108 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3110 session
->output_path
, chunk_name
);
3112 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3113 ERR("Failed to format closed trace chunk resulting path");
3114 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3116 goto end_unlock_session
;
3119 if (close_command
.is_set
&&
3120 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3121 session
->has_rotated
= true;
3123 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3124 path_length
= strlen(closed_trace_chunk_path
) + 1;
3125 if (path_length
> UINT32_MAX
) {
3126 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3128 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3129 goto end_unlock_session
;
3132 if (session
->current_trace_chunk
== chunk
) {
3134 * After a trace chunk close command, no new streams
3135 * referencing the chunk may be created. Hence, on the
3136 * event that no new trace chunk have been created for
3137 * the session, the reference to the current trace chunk
3138 * is released in order to allow it to be reclaimed when
3139 * the last stream releases its reference to it.
3141 lttng_trace_chunk_put(session
->current_trace_chunk
);
3142 session
->current_trace_chunk
= NULL
;
3144 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3145 session
->pending_closure_trace_chunk
= NULL
;
3147 pthread_mutex_unlock(&session
->lock
);
3150 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3151 reply
.path_length
= htobe32((uint32_t) path_length
);
3152 buf_ret
= lttng_dynamic_buffer_append(
3153 &reply_payload
, &reply
, sizeof(reply
));
3155 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3159 if (reply_code
== LTTNG_OK
) {
3160 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3161 closed_trace_chunk_path
, path_length
);
3163 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3168 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3172 if (send_ret
< reply_payload
.size
) {
3173 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3174 reply_payload
.size
, send_ret
);
3179 lttng_trace_chunk_put(chunk
);
3180 lttng_dynamic_buffer_reset(&reply_payload
);
3185 * relay_trace_chunk_exists: check if a trace chunk exists
3187 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3188 struct relay_connection
*conn
,
3189 const struct lttng_buffer_view
*payload
)
3193 struct relay_session
*session
= conn
->session
;
3194 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3195 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3196 struct lttng_buffer_view header_view
;
3200 if (!session
|| !conn
->version_check_done
) {
3201 ERR("Trying to close a trace chunk before version check");
3206 if (session
->major
== 2 && session
->minor
< 11) {
3207 ERR("Chunk close command is unsupported before 2.11");
3212 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3213 if (!header_view
.data
) {
3214 ERR("Failed to receive payload of chunk close command");
3219 /* Convert to host endianness. */
3220 msg
= (typeof(msg
)) header_view
.data
;
3221 chunk_id
= be64toh(msg
->chunk_id
);
3223 ret
= sessiond_trace_chunk_registry_chunk_exists(
3224 sessiond_trace_chunk_registry
,
3225 conn
->session
->sessiond_uuid
,
3227 chunk_id
, &chunk_exists
);
3229 * If ret is not 0, send the reply and report the error to the caller.
3230 * It is a protocol (or internal) error and the session/connection
3231 * should be torn down.
3233 reply
= (typeof(reply
)){
3234 .generic
.ret_code
= htobe32((uint32_t)
3235 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3236 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
3238 send_ret
= conn
->sock
->ops
->sendmsg(
3239 conn
->sock
, &reply
, sizeof(reply
), 0);
3240 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3241 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3250 * relay_get_configuration: query whether feature is available
3252 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3253 struct relay_connection
*conn
,
3254 const struct lttng_buffer_view
*payload
)
3258 struct lttcomm_relayd_get_configuration
*msg
;
3259 struct lttcomm_relayd_get_configuration_reply reply
= {};
3260 struct lttng_buffer_view header_view
;
3261 uint64_t query_flags
= 0;
3262 uint64_t result_flags
= 0;
3264 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3265 if (!header_view
.data
) {
3266 ERR("Failed to receive payload of chunk close command");
3271 /* Convert to host endianness. */
3272 msg
= (typeof(msg
)) header_view
.data
;
3273 query_flags
= be64toh(msg
->query_flags
);
3276 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3279 if (opt_allow_clear
) {
3280 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3284 reply
= (typeof(reply
)){
3285 .generic
.ret_code
= htobe32((uint32_t)
3286 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3287 .relayd_configuration_flags
= htobe64(result_flags
),
3289 send_ret
= conn
->sock
->ops
->sendmsg(
3290 conn
->sock
, &reply
, sizeof(reply
), 0);
3291 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3292 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3300 #define DBG_CMD(cmd_name, conn) \
3301 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3303 static int relay_process_control_command(struct relay_connection
*conn
,
3304 const struct lttcomm_relayd_hdr
*header
,
3305 const struct lttng_buffer_view
*payload
)
3309 switch (header
->cmd
) {
3310 case RELAYD_CREATE_SESSION
:
3311 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3312 ret
= relay_create_session(header
, conn
, payload
);
3314 case RELAYD_ADD_STREAM
:
3315 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3316 ret
= relay_add_stream(header
, conn
, payload
);
3318 case RELAYD_START_DATA
:
3319 DBG_CMD("RELAYD_START_DATA", conn
);
3320 ret
= relay_start(header
, conn
, payload
);
3322 case RELAYD_SEND_METADATA
:
3323 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3324 ret
= relay_recv_metadata(header
, conn
, payload
);
3326 case RELAYD_VERSION
:
3327 DBG_CMD("RELAYD_VERSION", conn
);
3328 ret
= relay_send_version(header
, conn
, payload
);
3330 case RELAYD_CLOSE_STREAM
:
3331 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3332 ret
= relay_close_stream(header
, conn
, payload
);
3334 case RELAYD_DATA_PENDING
:
3335 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3336 ret
= relay_data_pending(header
, conn
, payload
);
3338 case RELAYD_QUIESCENT_CONTROL
:
3339 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3340 ret
= relay_quiescent_control(header
, conn
, payload
);
3342 case RELAYD_BEGIN_DATA_PENDING
:
3343 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3344 ret
= relay_begin_data_pending(header
, conn
, payload
);
3346 case RELAYD_END_DATA_PENDING
:
3347 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3348 ret
= relay_end_data_pending(header
, conn
, payload
);
3350 case RELAYD_SEND_INDEX
:
3351 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3352 ret
= relay_recv_index(header
, conn
, payload
);
3354 case RELAYD_STREAMS_SENT
:
3355 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3356 ret
= relay_streams_sent(header
, conn
, payload
);
3358 case RELAYD_RESET_METADATA
:
3359 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3360 ret
= relay_reset_metadata(header
, conn
, payload
);
3362 case RELAYD_ROTATE_STREAMS
:
3363 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3364 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3366 case RELAYD_CREATE_TRACE_CHUNK
:
3367 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3368 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3370 case RELAYD_CLOSE_TRACE_CHUNK
:
3371 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3372 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3374 case RELAYD_TRACE_CHUNK_EXISTS
:
3375 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3376 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3378 case RELAYD_GET_CONFIGURATION
:
3379 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3380 ret
= relay_get_configuration(header
, conn
, payload
);
3382 case RELAYD_UPDATE_SYNC_INFO
:
3384 ERR("Received unknown command (%u)", header
->cmd
);
3385 relay_unknown_command(conn
);
3394 static enum relay_connection_status
relay_process_control_receive_payload(
3395 struct relay_connection
*conn
)
3398 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3399 struct lttng_dynamic_buffer
*reception_buffer
=
3400 &conn
->protocol
.ctrl
.reception_buffer
;
3401 struct ctrl_connection_state_receive_payload
*state
=
3402 &conn
->protocol
.ctrl
.state
.receive_payload
;
3403 struct lttng_buffer_view payload_view
;
3405 if (state
->left_to_receive
== 0) {
3406 /* Short-circuit for payload-less commands. */
3407 goto reception_complete
;
3410 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3411 reception_buffer
->data
+ state
->received
,
3412 state
->left_to_receive
, MSG_DONTWAIT
);
3414 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3415 PERROR("Unable to receive command payload on sock %d",
3417 status
= RELAY_CONNECTION_STATUS_ERROR
;
3420 } else if (ret
== 0) {
3421 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3422 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3427 assert(ret
<= state
->left_to_receive
);
3429 state
->left_to_receive
-= ret
;
3430 state
->received
+= ret
;
3432 if (state
->left_to_receive
> 0) {
3434 * Can't transition to the protocol's next state, wait to
3435 * receive the rest of the header.
3437 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3438 state
->received
, state
->left_to_receive
,
3444 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3445 conn
->sock
->fd
, state
->received
);
3447 * The payload required to process the command has been received.
3448 * A view to the reception buffer is forwarded to the various
3449 * commands and the state of the control is reset on success.
3451 * Commands are responsible for sending their reply to the peer.
3453 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3455 ret
= relay_process_control_command(conn
,
3456 &state
->header
, &payload_view
);
3458 status
= RELAY_CONNECTION_STATUS_ERROR
;
3462 ret
= connection_reset_protocol_state(conn
);
3464 status
= RELAY_CONNECTION_STATUS_ERROR
;
3470 static enum relay_connection_status
relay_process_control_receive_header(
3471 struct relay_connection
*conn
)
3474 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3475 struct lttcomm_relayd_hdr header
;
3476 struct lttng_dynamic_buffer
*reception_buffer
=
3477 &conn
->protocol
.ctrl
.reception_buffer
;
3478 struct ctrl_connection_state_receive_header
*state
=
3479 &conn
->protocol
.ctrl
.state
.receive_header
;
3481 assert(state
->left_to_receive
!= 0);
3483 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3484 reception_buffer
->data
+ state
->received
,
3485 state
->left_to_receive
, MSG_DONTWAIT
);
3487 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3488 PERROR("Unable to receive control command header on sock %d",
3490 status
= RELAY_CONNECTION_STATUS_ERROR
;
3493 } else if (ret
== 0) {
3494 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3495 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3500 assert(ret
<= state
->left_to_receive
);
3502 state
->left_to_receive
-= ret
;
3503 state
->received
+= ret
;
3505 if (state
->left_to_receive
> 0) {
3507 * Can't transition to the protocol's next state, wait to
3508 * receive the rest of the header.
3510 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3511 state
->received
, state
->left_to_receive
,
3516 /* Transition to next state: receiving the command's payload. */
3517 conn
->protocol
.ctrl
.state_id
=
3518 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3519 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3520 header
.circuit_id
= be64toh(header
.circuit_id
);
3521 header
.data_size
= be64toh(header
.data_size
);
3522 header
.cmd
= be32toh(header
.cmd
);
3523 header
.cmd_version
= be32toh(header
.cmd_version
);
3524 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3525 &header
, sizeof(header
));
3527 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3528 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3531 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3532 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3534 status
= RELAY_CONNECTION_STATUS_ERROR
;
3538 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3540 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3541 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3544 status
= RELAY_CONNECTION_STATUS_ERROR
;
3548 if (header
.data_size
== 0) {
3550 * Manually invoke the next state as the poll loop
3551 * will not wake-up to allow us to proceed further.
3553 status
= relay_process_control_receive_payload(conn
);
3560 * Process the commands received on the control socket
3562 static enum relay_connection_status
relay_process_control(
3563 struct relay_connection
*conn
)
3565 enum relay_connection_status status
;
3567 switch (conn
->protocol
.ctrl
.state_id
) {
3568 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3569 status
= relay_process_control_receive_header(conn
);
3571 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3572 status
= relay_process_control_receive_payload(conn
);
3575 ERR("Unknown control connection protocol state encountered.");
3582 static enum relay_connection_status
relay_process_data_receive_header(
3583 struct relay_connection
*conn
)
3586 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3587 struct data_connection_state_receive_header
*state
=
3588 &conn
->protocol
.data
.state
.receive_header
;
3589 struct lttcomm_relayd_data_hdr header
;
3590 struct relay_stream
*stream
;
3592 assert(state
->left_to_receive
!= 0);
3594 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3595 state
->header_reception_buffer
+ state
->received
,
3596 state
->left_to_receive
, MSG_DONTWAIT
);
3598 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3599 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3600 status
= RELAY_CONNECTION_STATUS_ERROR
;
3603 } else if (ret
== 0) {
3604 /* Orderly shutdown. Not necessary to print an error. */
3605 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3606 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3611 assert(ret
<= state
->left_to_receive
);
3613 state
->left_to_receive
-= ret
;
3614 state
->received
+= ret
;
3616 if (state
->left_to_receive
> 0) {
3618 * Can't transition to the protocol's next state, wait to
3619 * receive the rest of the header.
3621 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3622 state
->received
, state
->left_to_receive
,
3627 /* Transition to next state: receiving the payload. */
3628 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3630 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3631 header
.circuit_id
= be64toh(header
.circuit_id
);
3632 header
.stream_id
= be64toh(header
.stream_id
);
3633 header
.data_size
= be32toh(header
.data_size
);
3634 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3635 header
.padding_size
= be32toh(header
.padding_size
);
3636 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3638 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3640 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3641 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3643 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3644 conn
->sock
->fd
, header
.circuit_id
,
3645 header
.stream_id
, header
.data_size
,
3646 header
.net_seq_num
, header
.padding_size
);
3648 stream
= stream_get_by_id(header
.stream_id
);
3650 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3652 /* Protocol error. */
3653 status
= RELAY_CONNECTION_STATUS_ERROR
;
3657 pthread_mutex_lock(&stream
->lock
);
3658 /* Prepare stream for the reception of a new packet. */
3659 ret
= stream_init_packet(stream
, header
.data_size
,
3660 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3661 pthread_mutex_unlock(&stream
->lock
);
3663 ERR("Failed to rotate stream output file");
3664 status
= RELAY_CONNECTION_STATUS_ERROR
;
3665 goto end_stream_unlock
;
3674 static enum relay_connection_status
relay_process_data_receive_payload(
3675 struct relay_connection
*conn
)
3678 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3679 struct relay_stream
*stream
;
3680 struct data_connection_state_receive_payload
*state
=
3681 &conn
->protocol
.data
.state
.receive_payload
;
3682 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3683 char data_buffer
[chunk_size
];
3684 bool partial_recv
= false;
3685 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3686 uint64_t left_to_receive
= state
->left_to_receive
;
3687 struct relay_session
*session
;
3689 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3690 state
->header
.stream_id
, state
->header
.net_seq_num
,
3691 state
->received
, left_to_receive
);
3693 stream
= stream_get_by_id(state
->header
.stream_id
);
3695 /* Protocol error. */
3696 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3697 state
->header
.stream_id
);
3698 status
= RELAY_CONNECTION_STATUS_ERROR
;
3702 pthread_mutex_lock(&stream
->lock
);
3703 session
= stream
->trace
->session
;
3704 if (!conn
->session
) {
3705 ret
= connection_set_session(conn
, session
);
3707 status
= RELAY_CONNECTION_STATUS_ERROR
;
3708 goto end_stream_unlock
;
3713 * The size of the "chunk" received on any iteration is bounded by:
3714 * - the data left to receive,
3715 * - the data immediately available on the socket,
3716 * - the on-stack data buffer
3718 while (left_to_receive
> 0 && !partial_recv
) {
3719 size_t recv_size
= min(left_to_receive
, chunk_size
);
3720 struct lttng_buffer_view packet_chunk
;
3722 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3723 recv_size
, MSG_DONTWAIT
);
3725 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3726 PERROR("Socket %d error", conn
->sock
->fd
);
3727 status
= RELAY_CONNECTION_STATUS_ERROR
;
3729 goto end_stream_unlock
;
3730 } else if (ret
== 0) {
3731 /* No more data ready to be consumed on socket. */
3732 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3733 state
->header
.stream_id
);
3734 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3736 } else if (ret
< (int) recv_size
) {
3738 * All the data available on the socket has been
3741 partial_recv
= true;
3745 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3747 assert(packet_chunk
.data
);
3749 ret
= stream_write(stream
, &packet_chunk
, 0);
3751 ERR("Relay error writing data to file");
3752 status
= RELAY_CONNECTION_STATUS_ERROR
;
3753 goto end_stream_unlock
;
3756 left_to_receive
-= recv_size
;
3757 state
->received
+= recv_size
;
3758 state
->left_to_receive
= left_to_receive
;
3761 if (state
->left_to_receive
> 0) {
3763 * Did not receive all the data expected, wait for more data to
3764 * become available on the socket.
3766 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3767 state
->header
.stream_id
, state
->received
,
3768 state
->left_to_receive
);
3769 goto end_stream_unlock
;
3772 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3774 status
= RELAY_CONNECTION_STATUS_ERROR
;
3775 goto end_stream_unlock
;
3778 if (session_streams_have_index(session
)) {
3779 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3780 state
->rotate_index
, &index_flushed
,
3781 state
->header
.data_size
+ state
->header
.padding_size
);
3783 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3784 stream
->stream_handle
,
3785 state
->header
.net_seq_num
, ret
);
3786 status
= RELAY_CONNECTION_STATUS_ERROR
;
3787 goto end_stream_unlock
;
3791 if (stream
->prev_data_seq
== -1ULL) {
3795 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3796 state
->header
.padding_size
, state
->header
.net_seq_num
,
3799 status
= RELAY_CONNECTION_STATUS_ERROR
;
3800 goto end_stream_unlock
;
3804 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3805 * contents of *state which are aliased (union) to the same location as
3806 * the new state. Don't use it beyond this point.
3808 connection_reset_protocol_state(conn
);
3812 close_requested
= stream
->close_requested
;
3813 pthread_mutex_unlock(&stream
->lock
);
3814 if (close_requested
&& left_to_receive
== 0) {
3815 try_stream_close(stream
);
3819 pthread_mutex_lock(&session
->lock
);
3820 uatomic_set(&session
->new_streams
, 1);
3821 pthread_mutex_unlock(&session
->lock
);
3830 * relay_process_data: Process the data received on the data socket
3832 static enum relay_connection_status
relay_process_data(
3833 struct relay_connection
*conn
)
3835 enum relay_connection_status status
;
3837 switch (conn
->protocol
.data
.state_id
) {
3838 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3839 status
= relay_process_data_receive_header(conn
);
3841 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3842 status
= relay_process_data_receive_payload(conn
);
3845 ERR("Unexpected data connection communication state.");
3852 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3856 (void) lttng_poll_del(events
, pollfd
);
3858 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3859 fd_tracker_util_close_fd
, NULL
);
3861 ERR("Closing pollfd %d", pollfd
);
3865 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3866 int pollfd
, struct relay_connection
*conn
)
3868 const char *type_str
;
3870 switch (conn
->type
) {
3875 type_str
= "Control";
3877 case RELAY_VIEWER_COMMAND
:
3878 type_str
= "Viewer Command";
3880 case RELAY_VIEWER_NOTIFICATION
:
3881 type_str
= "Viewer Notification";
3884 type_str
= "Unknown";
3886 cleanup_connection_pollfd(events
, pollfd
);
3887 connection_put(conn
);
3888 DBG("%s connection closed with %d", type_str
, pollfd
);
3892 * This thread does the actual work
3894 static void *relay_thread_worker(void *data
)
3896 int ret
, err
= -1, last_seen_data_fd
= -1;
3898 struct lttng_poll_event events
;
3899 struct lttng_ht
*relay_connections_ht
;
3900 struct lttng_ht_iter iter
;
3901 struct relay_connection
*destroy_conn
= NULL
;
3903 DBG("[thread] Relay worker started");
3905 rcu_register_thread();
3907 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3909 if (testpoint(relayd_thread_worker
)) {
3910 goto error_testpoint
;
3913 health_code_update();
3915 /* table of connections indexed on socket */
3916 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3917 if (!relay_connections_ht
) {
3918 goto relay_connections_ht_error
;
3921 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3923 goto error_poll_create
;
3926 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3933 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3935 health_code_update();
3937 /* Infinite blocking call, waiting for transmission */
3938 DBG3("Relayd worker thread polling...");
3939 health_poll_entry();
3940 ret
= lttng_poll_wait(&events
, -1);
3944 * Restart interrupted system call.
3946 if (errno
== EINTR
) {
3955 * Process control. The control connection is
3956 * prioritized so we don't starve it with high
3957 * throughput tracing data on the data connection.
3959 for (i
= 0; i
< nb_fd
; i
++) {
3960 /* Fetch once the poll data */
3961 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3962 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3964 health_code_update();
3966 /* Thread quit pipe has been closed. Killing thread. */
3967 ret
= check_thread_quit_pipe(pollfd
, revents
);
3973 /* Inspect the relay conn pipe for new connection */
3974 if (pollfd
== relay_conn_pipe
[0]) {
3975 if (revents
& LPOLLIN
) {
3976 struct relay_connection
*conn
;
3978 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3982 ret
= lttng_poll_add(&events
,
3984 LPOLLIN
| LPOLLRDHUP
);
3986 ERR("Failed to add new connection file descriptor to poll set");
3989 connection_ht_add(relay_connections_ht
, conn
);
3990 DBG("Connection socket %d added", conn
->sock
->fd
);
3991 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3992 ERR("Relay connection pipe error");
3995 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3999 struct relay_connection
*ctrl_conn
;
4001 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4002 /* If not found, there is a synchronization issue. */
4005 if (ctrl_conn
->type
== RELAY_DATA
) {
4006 if (revents
& LPOLLIN
) {
4008 * Flag the last seen data fd not deleted. It will be
4009 * used as the last seen fd if any fd gets deleted in
4012 last_notdel_data_fd
= pollfd
;
4014 goto put_ctrl_connection
;
4016 assert(ctrl_conn
->type
== RELAY_CONTROL
);
4018 if (revents
& LPOLLIN
) {
4019 enum relay_connection_status status
;
4021 status
= relay_process_control(ctrl_conn
);
4022 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4024 * On socket error flag the session as aborted to force
4025 * the cleanup of its stream otherwise it can leak
4026 * during the lifetime of the relayd.
4028 * This prevents situations in which streams can be
4029 * left opened because an index was received, the
4030 * control connection is closed, and the data
4031 * connection is closed (uncleanly) before the packet's
4034 * Since the control connection encountered an error,
4035 * it is okay to be conservative and close the
4036 * session right now as we can't rely on the protocol
4037 * being respected anymore.
4039 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4040 session_abort(ctrl_conn
->session
);
4043 /* Clear the connection on error or close. */
4044 relay_thread_close_connection(&events
,
4049 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4050 relay_thread_close_connection(&events
,
4052 if (last_seen_data_fd
== pollfd
) {
4053 last_seen_data_fd
= last_notdel_data_fd
;
4056 ERR("Unexpected poll events %u for control sock %d",
4058 connection_put(ctrl_conn
);
4061 put_ctrl_connection
:
4062 connection_put(ctrl_conn
);
4067 * The last loop handled a control request, go back to poll to make
4068 * sure we prioritise the control socket.
4074 if (last_seen_data_fd
>= 0) {
4075 for (i
= 0; i
< nb_fd
; i
++) {
4076 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4078 health_code_update();
4080 if (last_seen_data_fd
== pollfd
) {
4087 /* Process data connection. */
4088 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4089 /* Fetch the poll data. */
4090 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4091 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4092 struct relay_connection
*data_conn
;
4094 health_code_update();
4097 /* No activity for this FD (poll implementation). */
4101 /* Skip the command pipe. It's handled in the first loop. */
4102 if (pollfd
== relay_conn_pipe
[0]) {
4106 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4108 /* Skip it. Might be removed before. */
4111 if (data_conn
->type
== RELAY_CONTROL
) {
4112 goto put_data_connection
;
4114 assert(data_conn
->type
== RELAY_DATA
);
4116 if (revents
& LPOLLIN
) {
4117 enum relay_connection_status status
;
4119 status
= relay_process_data(data_conn
);
4120 /* Connection closed or error. */
4121 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4123 * On socket error flag the session as aborted to force
4124 * the cleanup of its stream otherwise it can leak
4125 * during the lifetime of the relayd.
4127 * This prevents situations in which streams can be
4128 * left opened because an index was received, the
4129 * control connection is closed, and the data
4130 * connection is closed (uncleanly) before the packet's
4133 * Since the data connection encountered an error,
4134 * it is okay to be conservative and close the
4135 * session right now as we can't rely on the protocol
4136 * being respected anymore.
4138 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4139 session_abort(data_conn
->session
);
4141 relay_thread_close_connection(&events
, pollfd
,
4144 * Every goto restart call sets the last seen fd where
4145 * here we don't really care since we gracefully
4146 * continue the loop after the connection is deleted.
4149 /* Keep last seen port. */
4150 last_seen_data_fd
= pollfd
;
4151 connection_put(data_conn
);
4154 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4155 relay_thread_close_connection(&events
, pollfd
,
4158 ERR("Unknown poll events %u for data sock %d",
4161 put_data_connection
:
4162 connection_put(data_conn
);
4164 last_seen_data_fd
= -1;
4167 /* Normal exit, no error */
4172 /* Cleanup remaining connection object. */
4174 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4177 health_code_update();
4179 session_abort(destroy_conn
->session
);
4182 * No need to grab another ref, because we own
4185 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4190 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4192 lttng_ht_destroy(relay_connections_ht
);
4193 relay_connections_ht_error
:
4194 /* Close relay conn pipes */
4195 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4198 DBG("Thread exited with error");
4200 DBG("Worker thread cleanup complete");
4204 ERR("Health error occurred in %s", __func__
);
4206 health_unregister(health_relayd
);
4207 rcu_unregister_thread();
4208 lttng_relay_stop_threads();
4213 * Create the relay command pipe to wake thread_manage_apps.
4214 * Closed in cleanup().
4216 static int create_relay_conn_pipe(void)
4218 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4219 "Relayd connection pipe", relay_conn_pipe
);
4222 static int stdio_open(void *data
, int *fds
)
4224 fds
[0] = fileno(stdout
);
4225 fds
[1] = fileno(stderr
);
4229 static int track_stdio(void)
4232 const char *names
[] = { "stdout", "stderr" };
4234 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4235 names
, 2, stdio_open
, NULL
);
4241 int main(int argc
, char **argv
)
4243 bool thread_is_rcu_registered
= false;
4244 int ret
= 0, retval
= 0;
4246 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4248 /* Parse environment variables */
4249 ret
= parse_env_options();
4257 * Command line arguments overwrite environment.
4260 if (set_options(argc
, argv
)) {
4265 if (set_signal_handler()) {
4270 relayd_config_log();
4272 if (opt_print_version
) {
4278 ret
= fclose(stdin
);
4280 PERROR("Failed to close stdin");
4284 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4286 /* Try to create directory if -o, --output is specified. */
4287 if (opt_output_path
) {
4288 if (*opt_output_path
!= '/') {
4289 ERR("Please specify an absolute path for -o, --output PATH");
4294 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4297 ERR("Unable to create %s", opt_output_path
);
4304 if (opt_daemon
|| opt_background
) {
4305 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4313 if (opt_working_directory
) {
4314 ret
= utils_change_working_directory(opt_working_directory
);
4316 /* All errors are already logged. */
4321 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4322 if (!sessiond_trace_chunk_registry
) {
4323 ERR("Failed to initialize session daemon trace chunk registry");
4329 * The RCU thread registration (and use, through the fd-tracker's
4330 * creation) is done after the daemonization to allow us to not
4331 * deal with liburcu's fork() management as the call RCU needs to
4334 rcu_register_thread();
4335 thread_is_rcu_registered
= true;
4337 output_path
= create_output_path("");
4339 ERR("Failed to get output path");
4343 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4344 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4347 ERR("Failed to format unlinked file directory path");
4351 the_fd_tracker
= fd_tracker_create(
4352 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4353 free(unlinked_file_directory_path
);
4354 if (!the_fd_tracker
) {
4359 ret
= track_stdio();
4365 /* Initialize thread health monitoring */
4366 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4367 if (!health_relayd
) {
4368 PERROR("health_app_create error");
4373 /* Create thread quit pipe */
4374 if (init_thread_quit_pipe()) {
4379 /* Setup the thread apps communication pipe. */
4380 if (create_relay_conn_pipe()) {
4385 /* Init relay command queue. */
4386 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4388 /* Initialize communication library */
4390 lttcomm_inet_init();
4392 /* tables of sessions indexed by session ID */
4393 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4399 /* tables of streams indexed by stream ID */
4400 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4401 if (!relay_streams_ht
) {
4406 /* tables of streams indexed by stream ID */
4407 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4408 if (!viewer_streams_ht
) {
4413 ret
= init_health_quit_pipe();
4419 /* Create thread to manage the client socket */
4420 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4421 thread_manage_health
, (void *) NULL
);
4424 PERROR("pthread_create health");
4429 /* Setup the dispatcher thread */
4430 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4431 relay_thread_dispatcher
, (void *) NULL
);
4434 PERROR("pthread_create dispatcher");
4436 goto exit_dispatcher_thread
;
4439 /* Setup the worker thread */
4440 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4441 relay_thread_worker
, NULL
);
4444 PERROR("pthread_create worker");
4446 goto exit_worker_thread
;
4449 /* Setup the listener thread */
4450 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4451 relay_thread_listener
, (void *) NULL
);
4454 PERROR("pthread_create listener");
4456 goto exit_listener_thread
;
4459 ret
= relayd_live_create(live_uri
);
4461 ERR("Starting live viewer threads");
4467 * This is where we start awaiting program completion (e.g. through
4468 * signal that asks threads to teardown).
4471 ret
= relayd_live_join();
4477 ret
= pthread_join(listener_thread
, &status
);
4480 PERROR("pthread_join listener_thread");
4484 exit_listener_thread
:
4485 ret
= pthread_join(worker_thread
, &status
);
4488 PERROR("pthread_join worker_thread");
4493 ret
= pthread_join(dispatcher_thread
, &status
);
4496 PERROR("pthread_join dispatcher_thread");
4499 exit_dispatcher_thread
:
4501 ret
= pthread_join(health_thread
, &status
);
4504 PERROR("pthread_join health_thread");
4509 * Wait for all pending call_rcu work to complete before tearing
4510 * down data structures. call_rcu worker may be trying to
4511 * perform lookups in those structures.
4516 /* Ensure all prior call_rcu are done. */
4519 if (thread_is_rcu_registered
) {
4520 rcu_unregister_thread();