2 * Copyright (C) 2012 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * SPDX-License-Identifier: GPL-2.0-only
21 #include <sys/mount.h>
22 #include <sys/resource.h>
23 #include <sys/socket.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
29 #include <urcu/futex.h>
30 #include <urcu/uatomic.h>
31 #include <urcu/rculist.h>
38 #include <lttng/lttng.h>
39 #include <common/common.h>
40 #include <common/compat/poll.h>
41 #include <common/compat/socket.h>
42 #include <common/compat/endian.h>
43 #include <common/compat/getenv.h>
44 #include <common/defaults.h>
45 #include <common/daemonize.h>
46 #include <common/futex.h>
47 #include <common/sessiond-comm/sessiond-comm.h>
48 #include <common/sessiond-comm/inet.h>
49 #include <common/sessiond-comm/relayd.h>
50 #include <common/uri.h>
51 #include <common/utils.h>
52 #include <common/path.h>
53 #include <common/align.h>
54 #include <common/ini-config/ini-config.h>
55 #include <common/dynamic-buffer.h>
56 #include <common/buffer-view.h>
57 #include <common/string-utils/format.h>
58 #include <common/fd-tracker/fd-tracker.h>
59 #include <common/fd-tracker/utils.h>
61 #include "backward-compatibility-group-by.h"
63 #include "connection.h"
64 #include "ctf-trace.h"
65 #include "health-relayd.h"
68 #include "lttng-relayd.h"
70 #include "sessiond-trace-chunks.h"
72 #include "tcp_keep_alive.h"
73 #include "testpoint.h"
74 #include "tracefile-array.h"
77 #include "viewer-stream.h"
79 static const char *help_msg
=
80 #ifdef LTTNG_EMBED_HELP
81 #include <lttng-relayd.8.h>
87 enum relay_connection_status
{
88 RELAY_CONNECTION_STATUS_OK
,
89 /* An error occurred while processing an event on the connection. */
90 RELAY_CONNECTION_STATUS_ERROR
,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED
,
95 /* command line options */
96 char *opt_output_path
, *opt_working_directory
;
97 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
98 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
100 /* Argument variables */
101 int lttng_opt_quiet
; /* not static in error.h */
102 int lttng_opt_verbose
; /* not static in error.h */
103 int lttng_opt_mi
; /* not static in error.h */
106 * We need to wait for listener and live listener threads, as well as
107 * health check thread, before being ready to signal readiness.
109 #define NR_LTTNG_RELAY_READY 3
110 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
112 /* Size of receive buffer. */
113 #define RECV_DATA_BUFFER_SIZE 65536
115 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
116 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
118 static struct lttng_uri
*control_uri
;
119 static struct lttng_uri
*data_uri
;
120 static struct lttng_uri
*live_uri
;
122 const char *progname
;
124 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
125 static int tracing_group_name_override
;
127 const char * const config_section_name
= "relayd";
130 * Quit pipe for all threads. This permits a single cancellation point
131 * for all threads when receiving an event on the pipe.
133 int thread_quit_pipe
[2] = { -1, -1 };
136 * This pipe is used to inform the worker thread that a command is queued and
137 * ready to be processed.
139 static int relay_conn_pipe
[2] = { -1, -1 };
141 /* Shared between threads */
142 static int dispatch_thread_exit
;
144 static pthread_t listener_thread
;
145 static pthread_t dispatcher_thread
;
146 static pthread_t worker_thread
;
147 static pthread_t health_thread
;
150 * last_relay_stream_id_lock protects last_relay_stream_id increment
151 * atomicity on 32-bit architectures.
153 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
154 static uint64_t last_relay_stream_id
;
157 * Relay command queue.
159 * The relay_thread_listener and relay_thread_dispatcher communicate with this
162 static struct relay_conn_queue relay_conn_queue
;
164 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
165 static unsigned int lttng_opt_fd_pool_size
= -1;
167 /* Global relay stream hash table. */
168 struct lttng_ht
*relay_streams_ht
;
170 /* Global relay viewer stream hash table. */
171 struct lttng_ht
*viewer_streams_ht
;
173 /* Global relay sessions hash table. */
174 struct lttng_ht
*sessions_ht
;
176 /* Relayd health monitoring */
177 struct health_app
*health_relayd
;
179 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
181 /* Global fd tracker. */
182 struct fd_tracker
*the_fd_tracker
;
184 static struct option long_options
[] = {
185 { "control-port", 1, 0, 'C', },
186 { "data-port", 1, 0, 'D', },
187 { "live-port", 1, 0, 'L', },
188 { "daemonize", 0, 0, 'd', },
189 { "background", 0, 0, 'b', },
190 { "group", 1, 0, 'g', },
191 { "fd-pool-size", 1, 0, '\0', },
192 { "help", 0, 0, 'h', },
193 { "output", 1, 0, 'o', },
194 { "verbose", 0, 0, 'v', },
195 { "config", 1, 0, 'f' },
196 { "version", 0, 0, 'V' },
197 { "working-directory", 1, 0, 'w', },
198 { "group-output-by-session", 0, 0, 's', },
199 { "group-output-by-host", 0, 0, 'p', },
200 { "disallow-clear", 0, 0, 'x' },
204 static const char *config_ignore_options
[] = { "help", "config", "version" };
206 static void print_version(void) {
207 fprintf(stdout
, "%s\n", VERSION
);
210 static void relayd_config_log(void)
212 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
213 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
214 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
215 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
216 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
218 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
219 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
224 * Take an option from the getopt output and set it in the right variable to be
227 * Return 0 on success else a negative value.
229 static int set_option(int opt
, const char *arg
, const char *optname
)
235 if (!strcmp(optname
, "fd-pool-size")) {
239 v
= strtoul(arg
, NULL
, 0);
240 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
241 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
246 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
250 lttng_opt_fd_pool_size
= (unsigned int) v
;
252 fprintf(stderr
, "unknown option %s", optname
);
254 fprintf(stderr
, " with arg %s\n", arg
);
259 if (lttng_is_setuid_setgid()) {
260 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
261 "-C, --control-port");
263 ret
= uri_parse(arg
, &control_uri
);
265 ERR("Invalid control URI specified");
268 if (control_uri
->port
== 0) {
269 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
274 if (lttng_is_setuid_setgid()) {
275 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
278 ret
= uri_parse(arg
, &data_uri
);
280 ERR("Invalid data URI specified");
283 if (data_uri
->port
== 0) {
284 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
289 if (lttng_is_setuid_setgid()) {
290 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
293 ret
= uri_parse(arg
, &live_uri
);
295 ERR("Invalid live URI specified");
298 if (live_uri
->port
== 0) {
299 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
310 if (lttng_is_setuid_setgid()) {
311 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
314 tracing_group_name
= strdup(arg
);
315 if (tracing_group_name
== NULL
) {
320 tracing_group_name_override
= 1;
324 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
326 ERR("Cannot show --help for `lttng-relayd`");
331 opt_print_version
= 1;
334 if (lttng_is_setuid_setgid()) {
335 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
338 ret
= asprintf(&opt_output_path
, "%s", arg
);
341 PERROR("asprintf opt_output_path");
347 if (lttng_is_setuid_setgid()) {
348 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
349 "-w, --working-directory");
351 ret
= asprintf(&opt_working_directory
, "%s", arg
);
354 PERROR("asprintf opt_working_directory");
361 /* Verbose level can increase using multiple -v */
363 lttng_opt_verbose
= config_parse_value(arg
);
365 /* Only 3 level of verbosity (-vvv). */
366 if (lttng_opt_verbose
< 3) {
367 lttng_opt_verbose
+= 1;
372 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
373 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
376 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
379 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
380 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
383 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
390 /* Unknown option or other error.
391 * Error is printed by getopt, just return */
404 * config_entry_handler_cb used to handle options read from a config file.
405 * See config_entry_handler_cb comment in common/config/session-config.h for the
406 * return value conventions.
408 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
412 if (!entry
|| !entry
->name
|| !entry
->value
) {
417 /* Check if the option is to be ignored */
418 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
419 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
424 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
425 /* Ignore if entry name is not fully matched. */
426 if (strcmp(entry
->name
, long_options
[i
].name
)) {
431 * If the option takes no argument on the command line,
432 * we have to check if the value is "true". We support
433 * non-zero numeric values, true, on and yes.
435 if (!long_options
[i
].has_arg
) {
436 ret
= config_parse_value(entry
->value
);
439 WARN("Invalid configuration value \"%s\" for option %s",
440 entry
->value
, entry
->name
);
442 /* False, skip boolean config option. */
447 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
451 WARN("Unrecognized option \"%s\" in daemon configuration file.",
458 static int parse_env_options(void)
463 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
465 opt_working_directory
= strdup(value
);
466 if (!opt_working_directory
) {
467 ERR("Failed to allocate working directory string (\"%s\")",
475 static int set_fd_pool_size(void)
478 struct rlimit rlimit
;
480 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
482 PERROR("Failed to get file descriptor limit");
487 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
488 (uint64_t) rlimit
.rlim_cur
,
489 (uint64_t) rlimit
.rlim_max
);
490 if (lttng_opt_fd_pool_size
== -1) {
491 /* Use default value (soft limit - reserve). */
492 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
493 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
494 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
498 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
499 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
503 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
504 ERR("File descriptor pool size must be set to at least %d",
505 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
510 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
511 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
512 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
517 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
518 lttng_opt_fd_pool_size
,
519 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
520 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
525 static int set_options(int argc
, char **argv
)
527 int c
, ret
= 0, option_index
= 0, retval
= 0;
528 int orig_optopt
= optopt
, orig_optind
= optind
;
529 char *default_address
, *optstring
;
530 char *config_path
= NULL
;
532 optstring
= utils_generate_optstring(long_options
,
533 sizeof(long_options
) / sizeof(struct option
));
539 /* Check for the --config option */
541 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
542 &option_index
)) != -1) {
546 } else if (c
!= 'f') {
550 if (lttng_is_setuid_setgid()) {
551 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
555 config_path
= utils_expand_path(optarg
);
557 ERR("Failed to resolve path: %s", optarg
);
562 ret
= config_get_section_entries(config_path
, config_section_name
,
563 config_entry_handler
, NULL
);
566 ERR("Invalid configuration option at line %i", ret
);
572 /* Reset getopt's global state */
573 optopt
= orig_optopt
;
574 optind
= orig_optind
;
576 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
581 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
588 /* assign default values */
589 if (control_uri
== NULL
) {
590 ret
= asprintf(&default_address
,
591 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
592 DEFAULT_NETWORK_CONTROL_PORT
);
594 PERROR("asprintf default data address");
599 ret
= uri_parse(default_address
, &control_uri
);
600 free(default_address
);
602 ERR("Invalid control URI specified");
607 if (data_uri
== NULL
) {
608 ret
= asprintf(&default_address
,
609 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
610 DEFAULT_NETWORK_DATA_PORT
);
612 PERROR("asprintf default data address");
617 ret
= uri_parse(default_address
, &data_uri
);
618 free(default_address
);
620 ERR("Invalid data URI specified");
625 if (live_uri
== NULL
) {
626 ret
= asprintf(&default_address
,
627 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
628 DEFAULT_NETWORK_VIEWER_PORT
);
630 PERROR("asprintf default viewer control address");
635 ret
= uri_parse(default_address
, &live_uri
);
636 free(default_address
);
638 ERR("Invalid viewer control URI specified");
643 ret
= set_fd_pool_size();
649 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
650 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
652 if (opt_allow_clear
) {
653 /* Check if env variable exists. */
654 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
656 ret
= config_parse_value(value
);
658 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
662 opt_allow_clear
= !ret
;
672 static void print_global_objects(void)
674 print_viewer_streams();
675 print_relay_streams();
679 static int noop_close(void *data
, int *fds
)
684 static void untrack_stdio(void)
686 int fds
[] = { fileno(stdout
), fileno(stderr
) };
689 * noop_close is used since we don't really want to close
690 * the stdio output fds; we merely want to stop tracking them.
692 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
693 fds
, 2, noop_close
, NULL
);
699 static void relayd_cleanup(void)
701 print_global_objects();
705 if (viewer_streams_ht
)
706 lttng_ht_destroy(viewer_streams_ht
);
707 if (relay_streams_ht
)
708 lttng_ht_destroy(relay_streams_ht
);
710 lttng_ht_destroy(sessions_ht
);
712 free(opt_output_path
);
713 free(opt_working_directory
);
716 health_app_destroy(health_relayd
);
718 /* Close thread quit pipes */
719 if (health_quit_pipe
[0] != -1) {
720 (void) fd_tracker_util_pipe_close(
721 the_fd_tracker
, health_quit_pipe
);
723 if (thread_quit_pipe
[0] != -1) {
724 (void) fd_tracker_util_pipe_close(
725 the_fd_tracker
, thread_quit_pipe
);
727 if (sessiond_trace_chunk_registry
) {
728 sessiond_trace_chunk_registry_destroy(
729 sessiond_trace_chunk_registry
);
731 if (the_fd_tracker
) {
734 * fd_tracker_destroy() will log the contents of the fd-tracker
735 * if a leak is detected.
737 fd_tracker_destroy(the_fd_tracker
);
740 uri_free(control_uri
);
742 /* Live URI is freed in the live thread. */
744 if (tracing_group_name_override
) {
745 free((void *) tracing_group_name
);
750 * Write to writable pipe used to notify a thread.
752 static int notify_thread_pipe(int wpipe
)
756 ret
= lttng_write(wpipe
, "!", 1);
758 PERROR("write poll pipe");
766 static int notify_health_quit_pipe(int *pipe
)
770 ret
= lttng_write(pipe
[1], "4", 1);
772 PERROR("write relay health quit");
781 * Stop all relayd and relayd-live threads.
783 int lttng_relay_stop_threads(void)
787 /* Stopping all threads */
788 DBG("Terminating all threads");
789 if (notify_thread_pipe(thread_quit_pipe
[1])) {
790 ERR("write error on thread quit pipe");
794 if (notify_health_quit_pipe(health_quit_pipe
)) {
795 ERR("write error on health quit pipe");
798 /* Dispatch thread */
799 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
800 futex_nto1_wake(&relay_conn_queue
.futex
);
802 if (relayd_live_stop()) {
803 ERR("Error stopping live threads");
810 * Signal handler for the daemon
812 * Simply stop all worker threads, leaving main() return gracefully after
813 * joining all threads and calling cleanup().
815 static void sighandler(int sig
)
819 DBG("SIGINT caught");
820 if (lttng_relay_stop_threads()) {
821 ERR("Error stopping threads");
825 DBG("SIGTERM caught");
826 if (lttng_relay_stop_threads()) {
827 ERR("Error stopping threads");
831 CMM_STORE_SHARED(recv_child_signal
, 1);
839 * Setup signal handler for :
840 * SIGINT, SIGTERM, SIGPIPE
842 static int set_signal_handler(void)
848 if ((ret
= sigemptyset(&sigset
)) < 0) {
849 PERROR("sigemptyset");
856 sa
.sa_handler
= sighandler
;
857 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
862 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
867 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
872 sa
.sa_handler
= SIG_IGN
;
873 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
878 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
883 void lttng_relay_notify_ready(void)
885 /* Notify the parent of the fork() process that we are ready. */
886 if (opt_daemon
|| opt_background
) {
887 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
888 kill(child_ppid
, SIGUSR1
);
894 * Init thread quit pipe.
896 * Return -1 on error or 0 if all pipes are created.
898 static int init_thread_quit_pipe(void)
900 return fd_tracker_util_pipe_open_cloexec(
901 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
905 * Init health quit pipe.
907 * Return -1 on error or 0 if all pipes are created.
909 static int init_health_quit_pipe(void)
911 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
912 "Health quit pipe", health_quit_pipe
);
916 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
918 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
919 int size
, const char *name
)
923 if (events
== NULL
|| size
== 0) {
928 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
929 name
, events
, 1, LTTNG_CLOEXEC
);
931 PERROR("Failed to create \"%s\" poll file descriptor", name
);
936 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
948 * Check if the thread quit pipe was triggered.
950 * Return 1 if it was triggered else 0;
952 static int check_thread_quit_pipe(int fd
, uint32_t events
)
954 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
961 static int create_sock(void *data
, int *out_fd
)
964 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
966 ret
= lttcomm_create_sock(sock
);
976 static int close_sock(void *data
, int *in_fd
)
978 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
980 return sock
->ops
->close(sock
);
983 static int accept_sock(void *data
, int *out_fd
)
986 /* Socks is an array of in_sock, out_sock. */
987 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
988 struct lttcomm_sock
*in_sock
= socks
[0];
990 socks
[1] = in_sock
->ops
->accept(in_sock
);
995 *out_fd
= socks
[1]->fd
;
1001 * Create and init socket from uri.
1003 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
1007 struct lttcomm_sock
*sock
= NULL
;
1008 char uri_str
[PATH_MAX
];
1009 char *formated_name
= NULL
;
1011 sock
= lttcomm_alloc_sock_from_uri(uri
);
1013 ERR("Allocating socket");
1018 * Don't fail to create the socket if the name can't be built as it is
1019 * only used for debugging purposes.
1021 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1022 uri_str
[sizeof(uri_str
) - 1] = '\0';
1024 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1027 formated_name
= NULL
;
1031 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1032 (const char **) (formated_name
? &formated_name
: NULL
),
1033 1, create_sock
, sock
);
1035 PERROR("Failed to open \"%s\" relay socket",
1036 formated_name
?: "Unknown");
1039 DBG("Listening on %s socket %d", name
, sock
->fd
);
1041 ret
= sock
->ops
->bind(sock
);
1043 PERROR("Failed to bind socket");
1047 ret
= sock
->ops
->listen(sock
, -1);
1053 free(formated_name
);
1058 lttcomm_destroy_sock(sock
);
1060 free(formated_name
);
1065 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1069 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1070 struct lttcomm_sock
*new_sock
= NULL
;
1072 ret
= fd_tracker_open_unsuspendable_fd(
1073 the_fd_tracker
, &out_fd
,
1074 (const char **) &name
,
1075 1, accept_sock
, &socks
);
1079 new_sock
= socks
[1];
1080 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1086 * This thread manages the listening for new connections on the network
1088 static void *relay_thread_listener(void *data
)
1090 int i
, ret
, pollfd
, err
= -1;
1091 uint32_t revents
, nb_fd
;
1092 struct lttng_poll_event events
;
1093 struct lttcomm_sock
*control_sock
, *data_sock
;
1095 DBG("[thread] Relay listener started");
1097 rcu_register_thread();
1098 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1100 health_code_update();
1102 control_sock
= relay_socket_create(control_uri
, "Control listener");
1103 if (!control_sock
) {
1104 goto error_sock_control
;
1107 data_sock
= relay_socket_create(data_uri
, "Data listener");
1109 goto error_sock_relay
;
1113 * Pass 3 as size here for the thread quit pipe, control and
1116 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1118 goto error_create_poll
;
1121 /* Add the control socket */
1122 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1124 goto error_poll_add
;
1127 /* Add the data socket */
1128 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1130 goto error_poll_add
;
1133 lttng_relay_notify_ready();
1135 if (testpoint(relayd_thread_listener
)) {
1136 goto error_testpoint
;
1140 health_code_update();
1142 DBG("Listener accepting connections");
1145 health_poll_entry();
1146 ret
= lttng_poll_wait(&events
, -1);
1150 * Restart interrupted system call.
1152 if (errno
== EINTR
) {
1160 DBG("Relay new connection received");
1161 for (i
= 0; i
< nb_fd
; i
++) {
1162 health_code_update();
1164 /* Fetch once the poll data */
1165 revents
= LTTNG_POLL_GETEV(&events
, i
);
1166 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1168 /* Thread quit pipe has been closed. Killing thread. */
1169 ret
= check_thread_quit_pipe(pollfd
, revents
);
1175 if (revents
& LPOLLIN
) {
1177 * A new connection is requested, therefore a
1178 * sessiond/consumerd connection is allocated in
1179 * this thread, enqueued to a global queue and
1180 * dequeued (and freed) in the worker thread.
1183 struct relay_connection
*new_conn
;
1184 struct lttcomm_sock
*newsock
= NULL
;
1185 enum connection_type type
;
1187 if (pollfd
== data_sock
->fd
) {
1189 newsock
= accept_relayd_sock(data_sock
,
1190 "Data socket to relayd");
1192 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1193 type
= RELAY_CONTROL
;
1194 newsock
= accept_relayd_sock(control_sock
,
1195 "Control socket to relayd");
1198 PERROR("accepting sock");
1202 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1205 PERROR("setsockopt inet");
1206 lttcomm_destroy_sock(newsock
);
1210 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1212 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1214 lttcomm_destroy_sock(newsock
);
1218 new_conn
= connection_create(newsock
, type
);
1220 lttcomm_destroy_sock(newsock
);
1224 /* Enqueue request for the dispatcher thread. */
1225 cds_wfcq_head_ptr_t head
;
1226 head
.h
= &relay_conn_queue
.head
;
1227 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
,
1231 * Wake the dispatch queue futex.
1232 * Implicit memory barrier with the
1233 * exchange in cds_wfcq_enqueue.
1235 futex_nto1_wake(&relay_conn_queue
.futex
);
1236 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1237 ERR("socket poll error");
1240 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1250 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1252 if (data_sock
->fd
>= 0) {
1253 int data_sock_fd
= data_sock
->fd
;
1255 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1256 &data_sock_fd
, 1, close_sock
,
1259 PERROR("Failed to close the data listener socket file descriptor");
1263 lttcomm_destroy_sock(data_sock
);
1265 if (control_sock
->fd
>= 0) {
1266 int control_sock_fd
= control_sock
->fd
;
1268 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1269 &control_sock_fd
, 1, close_sock
,
1272 PERROR("Failed to close the control listener socket file descriptor");
1274 control_sock
->fd
= -1;
1276 lttcomm_destroy_sock(control_sock
);
1280 ERR("Health error occurred in %s", __func__
);
1282 health_unregister(health_relayd
);
1283 rcu_unregister_thread();
1284 DBG("Relay listener thread cleanup complete");
1285 lttng_relay_stop_threads();
1290 * This thread manages the dispatching of the requests to worker threads
1292 static void *relay_thread_dispatcher(void *data
)
1296 struct cds_wfcq_node
*node
;
1297 struct relay_connection
*new_conn
= NULL
;
1299 DBG("[thread] Relay dispatcher started");
1301 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1303 if (testpoint(relayd_thread_dispatcher
)) {
1304 goto error_testpoint
;
1307 health_code_update();
1310 health_code_update();
1312 /* Atomically prepare the queue futex */
1313 futex_nto1_prepare(&relay_conn_queue
.futex
);
1315 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1320 health_code_update();
1322 /* Dequeue commands */
1323 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1324 &relay_conn_queue
.tail
);
1326 DBG("Woken up but nothing in the relay command queue");
1327 /* Continue thread execution */
1330 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1332 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1335 * Inform worker thread of the new request. This
1336 * call is blocking so we can be assured that
1337 * the data will be read at some point in time
1338 * or wait to the end of the world :)
1340 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1342 PERROR("write connection pipe");
1343 connection_put(new_conn
);
1346 } while (node
!= NULL
);
1348 /* Futex wait on queue. Blocking call on futex() */
1349 health_poll_entry();
1350 futex_nto1_wait(&relay_conn_queue
.futex
);
1354 /* Normal exit, no error */
1361 ERR("Health error occurred in %s", __func__
);
1363 health_unregister(health_relayd
);
1364 DBG("Dispatch thread dying");
1365 lttng_relay_stop_threads();
1369 static bool session_streams_have_index(const struct relay_session
*session
)
1371 return session
->minor
>= 4 && !session
->snapshot
;
1375 * Handle the RELAYD_CREATE_SESSION command.
1377 * On success, send back the session id or else return a negative value.
1379 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1380 struct relay_connection
*conn
,
1381 const struct lttng_buffer_view
*payload
)
1385 struct relay_session
*session
= NULL
;
1386 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1387 char session_name
[LTTNG_NAME_MAX
] = {};
1388 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1389 uint32_t live_timer
= 0;
1390 bool snapshot
= false;
1391 bool session_name_contains_creation_timestamp
= false;
1392 /* Left nil for peers < 2.11. */
1393 char base_path
[LTTNG_PATH_MAX
] = {};
1394 lttng_uuid sessiond_uuid
= {};
1395 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1396 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1397 LTTNG_OPTIONAL(time_t) creation_time
= {};
1398 struct lttng_dynamic_buffer reply_payload
;
1400 lttng_dynamic_buffer_init(&reply_payload
);
1402 if (conn
->minor
< 4) {
1403 /* From 2.1 to 2.3 */
1405 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1406 /* From 2.4 to 2.10 */
1407 ret
= cmd_create_session_2_4(payload
, session_name
,
1408 hostname
, &live_timer
, &snapshot
);
1410 bool has_current_chunk
;
1411 uint64_t current_chunk_id_value
;
1412 time_t creation_time_value
;
1413 uint64_t id_sessiond_value
;
1415 /* From 2.11 to ... */
1416 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1417 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1418 sessiond_uuid
, &has_current_chunk
,
1419 ¤t_chunk_id_value
, &creation_time_value
,
1420 &session_name_contains_creation_timestamp
);
1421 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1422 /* The nil UUID is reserved for pre-2.11 clients. */
1423 ERR("Illegal nil UUID announced by peer in create session command");
1427 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1428 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1429 if (has_current_chunk
) {
1430 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1431 current_chunk_id_value
);
1439 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1440 snapshot
, sessiond_uuid
,
1441 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1442 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1443 creation_time
.is_set
? &creation_time
.value
: NULL
,
1444 conn
->major
, conn
->minor
,
1445 session_name_contains_creation_timestamp
);
1450 LTTNG_ASSERT(!conn
->session
);
1451 conn
->session
= session
;
1452 DBG("Created session %" PRIu64
, session
->id
);
1454 reply
.generic
.session_id
= htobe64(session
->id
);
1458 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1460 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1463 if (conn
->minor
< 11) {
1464 /* From 2.1 to 2.10 */
1465 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1466 &reply
.generic
, sizeof(reply
.generic
));
1468 ERR("Failed to append \"create session\" command reply header to payload buffer");
1473 const uint32_t output_path_length
=
1474 session
? strlen(session
->output_path
) + 1 : 0;
1476 reply
.output_path_length
= htobe32(output_path_length
);
1477 ret
= lttng_dynamic_buffer_append(
1478 &reply_payload
, &reply
, sizeof(reply
));
1480 ERR("Failed to append \"create session\" command reply header to payload buffer");
1484 if (output_path_length
) {
1485 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1486 session
->output_path
,
1487 output_path_length
);
1489 ERR("Failed to append \"create session\" command reply path to payload buffer");
1495 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1496 reply_payload
.size
, 0);
1497 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1498 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1499 reply_payload
.size
, send_ret
);
1503 if (ret
< 0 && session
) {
1504 session_put(session
);
1506 lttng_dynamic_buffer_reset(&reply_payload
);
1511 * When we have received all the streams and the metadata for a channel,
1512 * we make them visible to the viewer threads.
1514 static void publish_connection_local_streams(struct relay_connection
*conn
)
1516 struct relay_stream
*stream
;
1517 struct relay_session
*session
= conn
->session
;
1520 * We publish all streams belonging to a session atomically wrt
1523 pthread_mutex_lock(&session
->lock
);
1525 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1527 stream_publish(stream
);
1532 * Inform the viewer that there are new streams in the session.
1534 if (session
->viewer_attached
) {
1535 uatomic_set(&session
->new_streams
, 1);
1537 pthread_mutex_unlock(&session
->lock
);
1540 static int conform_channel_path(char *channel_path
)
1544 if (strstr("../", channel_path
)) {
1545 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1551 if (*channel_path
== '/') {
1552 const size_t len
= strlen(channel_path
);
1555 * Channel paths from peers prior to 2.11 are expressed as an
1556 * absolute path that is, in reality, relative to the relay
1557 * daemon's output directory. Remove the leading slash so it
1558 * is correctly interpreted as a relative path later on.
1560 * len (and not len - 1) is used to copy the trailing NULL.
1562 bcopy(channel_path
+ 1, channel_path
, len
);
1569 * relay_add_stream: allocate a new stream for a session
1571 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1572 struct relay_connection
*conn
,
1573 const struct lttng_buffer_view
*payload
)
1577 struct relay_session
*session
= conn
->session
;
1578 struct relay_stream
*stream
= NULL
;
1579 struct lttcomm_relayd_status_stream reply
;
1580 struct ctf_trace
*trace
= NULL
;
1581 uint64_t stream_handle
= -1ULL;
1582 char *path_name
= NULL
, *channel_name
= NULL
;
1583 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1584 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1586 if (!session
|| !conn
->version_check_done
) {
1587 ERR("Trying to add a stream before version check");
1589 goto end_no_session
;
1592 if (session
->minor
== 1) {
1594 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1596 } else if (session
->minor
> 1 && session
->minor
< 11) {
1597 /* From 2.2 to 2.10 */
1598 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1599 &channel_name
, &tracefile_size
, &tracefile_count
);
1601 /* From 2.11 to ... */
1602 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1603 &channel_name
, &tracefile_size
, &tracefile_count
,
1604 &stream_chunk_id
.value
);
1605 stream_chunk_id
.is_set
= true;
1612 if (conform_channel_path(path_name
)) {
1617 * Backward compatibility for --group-output-by-session.
1618 * Prior to lttng 2.11, the complete path is passed by the stream.
1619 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1620 * >=2.11 the chunk is responsible for the output path. When dealing
1621 * with producer < 2.11 the chunk output_path is the root output path
1622 * and the stream carries the complete path (path_name).
1623 * To support --group-output-by-session with older producer (<2.11), we
1624 * need to craft the path based on the stream path.
1626 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1627 if (conn
->minor
< 4) {
1629 * From 2.1 to 2.3, the session_name is not passed on
1630 * the RELAYD_CREATE_SESSION command. The session name
1631 * is necessary to detect the presence of a base_path
1632 * inside the stream path. Without it we cannot perform
1633 * a valid group-output-by-session transformation.
1635 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1636 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1637 session
->id
, path_name
);
1638 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1639 char *group_by_session_path_name
;
1641 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1643 group_by_session_path_name
=
1644 backward_compat_group_by_session(
1646 session
->session_name
,
1647 session
->creation_time
.value
);
1648 if (!group_by_session_path_name
) {
1649 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1654 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1655 path_name
, group_by_session_path_name
);
1658 path_name
= group_by_session_path_name
;
1662 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1667 /* This stream here has one reference on the trace. */
1668 pthread_mutex_lock(&last_relay_stream_id_lock
);
1669 stream_handle
= ++last_relay_stream_id
;
1670 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1672 /* We pass ownership of path_name and channel_name. */
1673 stream
= stream_create(trace
, stream_handle
, path_name
,
1674 channel_name
, tracefile_size
, tracefile_count
);
1676 channel_name
= NULL
;
1679 * Streams are the owners of their trace. Reference to trace is
1680 * kept within stream_create().
1682 ctf_trace_put(trace
);
1685 memset(&reply
, 0, sizeof(reply
));
1686 reply
.handle
= htobe64(stream_handle
);
1688 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1690 reply
.ret_code
= htobe32(LTTNG_OK
);
1693 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1694 sizeof(struct lttcomm_relayd_status_stream
), 0);
1695 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1696 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1708 * relay_close_stream: close a specific stream
1710 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1711 struct relay_connection
*conn
,
1712 const struct lttng_buffer_view
*payload
)
1716 struct relay_session
*session
= conn
->session
;
1717 struct lttcomm_relayd_close_stream stream_info
;
1718 struct lttcomm_relayd_generic_reply reply
;
1719 struct relay_stream
*stream
;
1721 DBG("Close stream received");
1723 if (!session
|| !conn
->version_check_done
) {
1724 ERR("Trying to close a stream before version check");
1726 goto end_no_session
;
1729 if (payload
->size
< sizeof(stream_info
)) {
1730 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1731 sizeof(stream_info
), payload
->size
);
1733 goto end_no_session
;
1735 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1736 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1737 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1739 stream
= stream_get_by_id(stream_info
.stream_id
);
1746 * Set last_net_seq_num before the close flag. Required by data
1749 pthread_mutex_lock(&stream
->lock
);
1750 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1751 pthread_mutex_unlock(&stream
->lock
);
1754 * This is one of the conditions which may trigger a stream close
1755 * with the others being:
1756 * 1) A close command is received for a stream
1757 * 2) The control connection owning the stream is closed
1758 * 3) We have received all of the stream's data _after_ a close
1761 try_stream_close(stream
);
1766 memset(&reply
, 0, sizeof(reply
));
1768 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1770 reply
.ret_code
= htobe32(LTTNG_OK
);
1772 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1773 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1774 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1775 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1785 * relay_reset_metadata: reset a metadata stream
1788 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1789 struct relay_connection
*conn
,
1790 const struct lttng_buffer_view
*payload
)
1794 struct relay_session
*session
= conn
->session
;
1795 struct lttcomm_relayd_reset_metadata stream_info
;
1796 struct lttcomm_relayd_generic_reply reply
;
1797 struct relay_stream
*stream
;
1799 DBG("Reset metadata received");
1801 if (!session
|| !conn
->version_check_done
) {
1802 ERR("Trying to reset a metadata stream before version check");
1804 goto end_no_session
;
1807 if (payload
->size
< sizeof(stream_info
)) {
1808 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1809 sizeof(stream_info
), payload
->size
);
1811 goto end_no_session
;
1813 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1814 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1815 stream_info
.version
= be64toh(stream_info
.version
);
1817 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1819 /* Unsupported for live sessions for now. */
1820 if (session
->live_timer
!= 0) {
1825 stream
= stream_get_by_id(stream_info
.stream_id
);
1830 pthread_mutex_lock(&stream
->lock
);
1831 if (!stream
->is_metadata
) {
1836 ret
= stream_reset_file(stream
);
1838 ERR("Failed to reset metadata stream %" PRIu64
1839 ": stream_path = %s, channel = %s",
1840 stream
->stream_handle
, stream
->path_name
,
1841 stream
->channel_name
);
1845 pthread_mutex_unlock(&stream
->lock
);
1849 memset(&reply
, 0, sizeof(reply
));
1851 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1853 reply
.ret_code
= htobe32(LTTNG_OK
);
1855 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1856 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1857 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1858 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1868 * relay_unknown_command: send -1 if received unknown command
1870 static void relay_unknown_command(struct relay_connection
*conn
)
1872 struct lttcomm_relayd_generic_reply reply
;
1875 memset(&reply
, 0, sizeof(reply
));
1876 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1877 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1878 if (send_ret
< sizeof(reply
)) {
1879 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1884 * relay_start: send an acknowledgment to the client to tell if we are
1885 * ready to receive data. We are ready if a session is established.
1887 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1888 struct relay_connection
*conn
,
1889 const struct lttng_buffer_view
*payload
)
1893 struct lttcomm_relayd_generic_reply reply
;
1894 struct relay_session
*session
= conn
->session
;
1897 DBG("Trying to start the streaming without a session established");
1898 ret
= htobe32(LTTNG_ERR_UNK
);
1901 memset(&reply
, 0, sizeof(reply
));
1902 reply
.ret_code
= htobe32(LTTNG_OK
);
1903 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1905 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1906 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1915 * relay_recv_metadata: receive the metadata for the session.
1917 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1918 struct relay_connection
*conn
,
1919 const struct lttng_buffer_view
*payload
)
1922 struct relay_session
*session
= conn
->session
;
1923 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1924 struct relay_stream
*metadata_stream
;
1925 uint64_t metadata_payload_size
;
1926 struct lttng_buffer_view packet_view
;
1929 ERR("Metadata sent before version check");
1934 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1935 ERR("Incorrect data size");
1939 metadata_payload_size
= recv_hdr
->data_size
-
1940 sizeof(struct lttcomm_relayd_metadata_payload
);
1942 memcpy(&metadata_payload_header
, payload
->data
,
1943 sizeof(metadata_payload_header
));
1944 metadata_payload_header
.stream_id
= be64toh(
1945 metadata_payload_header
.stream_id
);
1946 metadata_payload_header
.padding_size
= be32toh(
1947 metadata_payload_header
.padding_size
);
1949 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1950 if (!metadata_stream
) {
1955 packet_view
= lttng_buffer_view_from_view(payload
,
1956 sizeof(metadata_payload_header
), metadata_payload_size
);
1957 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1958 ERR("Invalid metadata packet length announced by header");
1963 pthread_mutex_lock(&metadata_stream
->lock
);
1964 ret
= stream_write(metadata_stream
, &packet_view
,
1965 metadata_payload_header
.padding_size
);
1966 pthread_mutex_unlock(&metadata_stream
->lock
);
1972 stream_put(metadata_stream
);
1978 * relay_send_version: send relayd version number
1980 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1981 struct relay_connection
*conn
,
1982 const struct lttng_buffer_view
*payload
)
1986 struct lttcomm_relayd_version reply
, msg
;
1987 bool compatible
= true;
1989 conn
->version_check_done
= true;
1991 /* Get version from the other side. */
1992 if (payload
->size
< sizeof(msg
)) {
1993 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1994 sizeof(msg
), payload
->size
);
1999 memcpy(&msg
, payload
->data
, sizeof(msg
));
2000 msg
.major
= be32toh(msg
.major
);
2001 msg
.minor
= be32toh(msg
.minor
);
2003 memset(&reply
, 0, sizeof(reply
));
2004 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2005 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2007 /* Major versions must be the same */
2008 if (reply
.major
!= msg
.major
) {
2009 DBG("Incompatible major versions (%u vs %u), deleting session",
2010 reply
.major
, msg
.major
);
2014 conn
->major
= reply
.major
;
2015 /* We adapt to the lowest compatible version */
2016 if (reply
.minor
<= msg
.minor
) {
2017 conn
->minor
= reply
.minor
;
2019 conn
->minor
= msg
.minor
;
2022 reply
.major
= htobe32(reply
.major
);
2023 reply
.minor
= htobe32(reply
.minor
);
2024 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2026 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2027 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2040 DBG("Version check done using protocol %u.%u", conn
->major
,
2048 * Check for data pending for a given stream id from the session daemon.
2050 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2051 struct relay_connection
*conn
,
2052 const struct lttng_buffer_view
*payload
)
2054 struct relay_session
*session
= conn
->session
;
2055 struct lttcomm_relayd_data_pending msg
;
2056 struct lttcomm_relayd_generic_reply reply
;
2057 struct relay_stream
*stream
;
2060 uint64_t stream_seq
;
2062 DBG("Data pending command received");
2064 if (!session
|| !conn
->version_check_done
) {
2065 ERR("Trying to check for data before version check");
2067 goto end_no_session
;
2070 if (payload
->size
< sizeof(msg
)) {
2071 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2072 sizeof(msg
), payload
->size
);
2074 goto end_no_session
;
2076 memcpy(&msg
, payload
->data
, sizeof(msg
));
2077 msg
.stream_id
= be64toh(msg
.stream_id
);
2078 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2080 stream
= stream_get_by_id(msg
.stream_id
);
2081 if (stream
== NULL
) {
2086 pthread_mutex_lock(&stream
->lock
);
2088 if (session_streams_have_index(session
)) {
2090 * Ensure that both the index and stream data have been
2091 * flushed up to the requested point.
2093 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2095 stream_seq
= stream
->prev_data_seq
;
2097 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2098 ", prev_index_seq %" PRIu64
2099 ", and last_seq %" PRIu64
, msg
.stream_id
,
2100 stream
->prev_data_seq
, stream
->prev_index_seq
,
2101 msg
.last_net_seq_num
);
2103 /* Avoid wrapping issue */
2104 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2105 /* Data has in fact been written and is NOT pending */
2108 /* Data still being streamed thus pending */
2112 stream
->data_pending_check_done
= true;
2113 pthread_mutex_unlock(&stream
->lock
);
2118 memset(&reply
, 0, sizeof(reply
));
2119 reply
.ret_code
= htobe32(ret
);
2120 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2121 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2122 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2132 * Wait for the control socket to reach a quiescent state.
2134 * Note that for now, when receiving this command from the session
2135 * daemon, this means that every subsequent commands or data received on
2136 * the control socket has been handled. So, this is why we simply return
2139 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2140 struct relay_connection
*conn
,
2141 const struct lttng_buffer_view
*payload
)
2145 struct relay_stream
*stream
;
2146 struct lttcomm_relayd_quiescent_control msg
;
2147 struct lttcomm_relayd_generic_reply reply
;
2149 DBG("Checking quiescent state on control socket");
2151 if (!conn
->session
|| !conn
->version_check_done
) {
2152 ERR("Trying to check for data before version check");
2154 goto end_no_session
;
2157 if (payload
->size
< sizeof(msg
)) {
2158 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2159 sizeof(msg
), payload
->size
);
2161 goto end_no_session
;
2163 memcpy(&msg
, payload
->data
, sizeof(msg
));
2164 msg
.stream_id
= be64toh(msg
.stream_id
);
2166 stream
= stream_get_by_id(msg
.stream_id
);
2170 pthread_mutex_lock(&stream
->lock
);
2171 stream
->data_pending_check_done
= true;
2172 pthread_mutex_unlock(&stream
->lock
);
2174 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2177 memset(&reply
, 0, sizeof(reply
));
2178 reply
.ret_code
= htobe32(LTTNG_OK
);
2179 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2180 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2181 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2193 * Initialize a data pending command. This means that a consumer is about
2194 * to ask for data pending for each stream it holds. Simply iterate over
2195 * all streams of a session and set the data_pending_check_done flag.
2197 * This command returns to the client a LTTNG_OK code.
2199 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2200 struct relay_connection
*conn
,
2201 const struct lttng_buffer_view
*payload
)
2205 struct lttng_ht_iter iter
;
2206 struct lttcomm_relayd_begin_data_pending msg
;
2207 struct lttcomm_relayd_generic_reply reply
;
2208 struct relay_stream
*stream
;
2210 LTTNG_ASSERT(recv_hdr
);
2213 DBG("Init streams for data pending");
2215 if (!conn
->session
|| !conn
->version_check_done
) {
2216 ERR("Trying to check for data before version check");
2218 goto end_no_session
;
2221 if (payload
->size
< sizeof(msg
)) {
2222 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2223 sizeof(msg
), payload
->size
);
2225 goto end_no_session
;
2227 memcpy(&msg
, payload
->data
, sizeof(msg
));
2228 msg
.session_id
= be64toh(msg
.session_id
);
2231 * Iterate over all streams to set the begin data pending flag.
2232 * For now, the streams are indexed by stream handle so we have
2233 * to iterate over all streams to find the one associated with
2234 * the right session_id.
2237 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2239 if (!stream_get(stream
)) {
2242 if (stream
->trace
->session
->id
== msg
.session_id
) {
2243 pthread_mutex_lock(&stream
->lock
);
2244 stream
->data_pending_check_done
= false;
2245 pthread_mutex_unlock(&stream
->lock
);
2246 DBG("Set begin data pending flag to stream %" PRIu64
,
2247 stream
->stream_handle
);
2253 memset(&reply
, 0, sizeof(reply
));
2254 /* All good, send back reply. */
2255 reply
.ret_code
= htobe32(LTTNG_OK
);
2257 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2258 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2259 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2271 * End data pending command. This will check, for a given session id, if
2272 * each stream associated with it has its data_pending_check_done flag
2273 * set. If not, this means that the client lost track of the stream but
2274 * the data is still being streamed on our side. In this case, we inform
2275 * the client that data is in flight.
2277 * Return to the client if there is data in flight or not with a ret_code.
2279 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2280 struct relay_connection
*conn
,
2281 const struct lttng_buffer_view
*payload
)
2285 struct lttng_ht_iter iter
;
2286 struct lttcomm_relayd_end_data_pending msg
;
2287 struct lttcomm_relayd_generic_reply reply
;
2288 struct relay_stream
*stream
;
2289 uint32_t is_data_inflight
= 0;
2291 DBG("End data pending command");
2293 if (!conn
->session
|| !conn
->version_check_done
) {
2294 ERR("Trying to check for data before version check");
2296 goto end_no_session
;
2299 if (payload
->size
< sizeof(msg
)) {
2300 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2301 sizeof(msg
), payload
->size
);
2303 goto end_no_session
;
2305 memcpy(&msg
, payload
->data
, sizeof(msg
));
2306 msg
.session_id
= be64toh(msg
.session_id
);
2309 * Iterate over all streams to see if the begin data pending
2313 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2315 if (!stream_get(stream
)) {
2318 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2322 pthread_mutex_lock(&stream
->lock
);
2323 if (!stream
->data_pending_check_done
) {
2324 uint64_t stream_seq
;
2326 if (session_streams_have_index(conn
->session
)) {
2328 * Ensure that both the index and stream data have been
2329 * flushed up to the requested point.
2331 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2333 stream_seq
= stream
->prev_data_seq
;
2335 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2336 is_data_inflight
= 1;
2337 DBG("Data is still in flight for stream %" PRIu64
,
2338 stream
->stream_handle
);
2339 pthread_mutex_unlock(&stream
->lock
);
2344 pthread_mutex_unlock(&stream
->lock
);
2349 memset(&reply
, 0, sizeof(reply
));
2350 /* All good, send back reply. */
2351 reply
.ret_code
= htobe32(is_data_inflight
);
2353 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2354 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2355 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2367 * Receive an index for a specific stream.
2369 * Return 0 on success else a negative value.
2371 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2372 struct relay_connection
*conn
,
2373 const struct lttng_buffer_view
*payload
)
2377 struct relay_session
*session
= conn
->session
;
2378 struct lttcomm_relayd_index index_info
;
2379 struct lttcomm_relayd_generic_reply reply
;
2380 struct relay_stream
*stream
;
2385 DBG("Relay receiving index");
2387 if (!session
|| !conn
->version_check_done
) {
2388 ERR("Trying to close a stream before version check");
2390 goto end_no_session
;
2393 msg_len
= lttcomm_relayd_index_len(
2394 lttng_to_index_major(conn
->major
, conn
->minor
),
2395 lttng_to_index_minor(conn
->major
, conn
->minor
));
2396 if (payload
->size
< msg_len
) {
2397 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2398 msg_len
, payload
->size
);
2400 goto end_no_session
;
2402 memcpy(&index_info
, payload
->data
, msg_len
);
2403 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2404 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2405 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2406 index_info
.content_size
= be64toh(index_info
.content_size
);
2407 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2408 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2409 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2410 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2412 if (conn
->minor
>= 8) {
2413 index_info
.stream_instance_id
=
2414 be64toh(index_info
.stream_instance_id
);
2415 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2417 index_info
.stream_instance_id
= -1ULL;
2418 index_info
.packet_seq_num
= -1ULL;
2421 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2423 ERR("stream_get_by_id not found");
2428 pthread_mutex_lock(&stream
->lock
);
2429 ret
= stream_add_index(stream
, &index_info
);
2430 pthread_mutex_unlock(&stream
->lock
);
2432 goto end_stream_put
;
2438 memset(&reply
, 0, sizeof(reply
));
2440 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2442 reply
.ret_code
= htobe32(LTTNG_OK
);
2444 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2445 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2446 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2455 * Receive the streams_sent message.
2457 * Return 0 on success else a negative value.
2459 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2460 struct relay_connection
*conn
,
2461 const struct lttng_buffer_view
*payload
)
2465 struct lttcomm_relayd_generic_reply reply
;
2469 DBG("Relay receiving streams_sent");
2471 if (!conn
->session
|| !conn
->version_check_done
) {
2472 ERR("Trying to close a stream before version check");
2474 goto end_no_session
;
2478 * Publish every pending stream in the connection recv list which are
2479 * now ready to be used by the viewer.
2481 publish_connection_local_streams(conn
);
2483 memset(&reply
, 0, sizeof(reply
));
2484 reply
.ret_code
= htobe32(LTTNG_OK
);
2485 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2486 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2487 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2499 static ssize_t
relay_unpack_rotate_streams_header(
2500 const struct lttng_buffer_view
*payload
,
2501 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2503 struct lttcomm_relayd_rotate_streams rotate_streams
;
2505 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2506 * This is the smallest version of this structure, but it can be larger;
2507 * this variable is updated once the proper size of the structure is known.
2509 * See comment at the declaration of this structure for more information.
2511 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2512 size_t expected_payload_size_no_padding
,
2513 expected_payload_size_3_bytes_padding
,
2514 expected_payload_size_7_bytes_padding
;
2516 if (payload
->size
< header_len
) {
2517 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2518 header_len
, payload
->size
);
2523 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2524 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2526 * We start by "unpacking" `stream_count` to figure out the padding length
2527 * emited by our peer.
2529 memcpy(&rotate_streams
.stream_count
, payload
->data
,
2530 sizeof(rotate_streams
.stream_count
));
2531 rotate_streams
= (typeof(rotate_streams
)) {
2532 .stream_count
= be32toh(rotate_streams
.stream_count
),
2536 * Payload size expected given the possible padding lengths in
2537 * `struct lttcomm_relayd_rotate_streams`.
2539 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2540 sizeof(*rotate_streams
.rotation_positions
)) +
2541 sizeof(lttcomm_relayd_rotate_streams_packed
);
2542 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2543 sizeof(*rotate_streams
.rotation_positions
)) +
2544 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2545 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2546 sizeof(*rotate_streams
.rotation_positions
)) +
2547 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2549 if (payload
->size
== expected_payload_size_no_padding
) {
2550 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2553 * This handles cases where someone might build with
2554 * -fpack-struct or any other toolchain that wouldn't produce
2555 * padding to align `value`.
2557 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2559 header_len
= sizeof(packed_rotate_streams
);
2560 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2562 /* Unpack the packed structure to the natively-packed version. */
2563 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2564 .stream_count
= be32toh(packed_rotate_streams
.stream_count
),
2565 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2566 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2567 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2570 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2571 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2573 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2575 header_len
= sizeof(padded_rotate_streams
);
2576 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2578 /* Unpack the 3-byte padded structure to the natively-packed version. */
2579 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2580 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2581 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2582 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2583 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2586 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2587 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2589 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2591 header_len
= sizeof(padded_rotate_streams
);
2592 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2594 /* Unpack the 7-byte padded structure to the natively-packed version. */
2595 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2596 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2597 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2598 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2599 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2603 header_len
= sizeof(padded_rotate_streams
);
2605 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2606 expected_payload_size_no_padding
,
2607 expected_payload_size_3_bytes_padding
,
2608 expected_payload_size_7_bytes_padding
,
2619 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2620 * session rotation feature (not the tracefile rotation feature).
2622 static int relay_rotate_session_streams(
2623 const struct lttcomm_relayd_hdr
*recv_hdr
,
2624 struct relay_connection
*conn
,
2625 const struct lttng_buffer_view
*payload
)
2630 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2631 struct relay_session
*session
= conn
->session
;
2632 struct lttcomm_relayd_rotate_streams rotate_streams
;
2633 struct lttcomm_relayd_generic_reply reply
= {};
2634 struct relay_stream
*stream
= NULL
;
2635 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2636 struct lttng_buffer_view stream_positions
;
2637 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2638 const char *chunk_id_str
= "none";
2641 if (!session
|| !conn
->version_check_done
) {
2642 ERR("Trying to rotate a stream before version check");
2647 if (session
->major
== 2 && session
->minor
< 11) {
2648 ERR("Unsupported feature before 2.11");
2653 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2654 if (header_len
< 0) {
2659 if (rotate_streams
.new_chunk_id
.is_set
) {
2661 * Retrieve the trace chunk the stream must transition to. As
2662 * per the protocol, this chunk should have been created
2663 * before this command is received.
2665 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2666 sessiond_trace_chunk_registry
,
2667 session
->sessiond_uuid
,
2668 conn
->session
->id_sessiond
.is_set
?
2669 conn
->session
->id_sessiond
.value
:
2671 rotate_streams
.new_chunk_id
.value
);
2672 if (!next_trace_chunk
) {
2673 char uuid_str
[LTTNG_UUID_STR_LEN
];
2675 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2676 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2677 ", trace_chunk_id = %" PRIu64
,
2678 uuid_str
, session
->id
,
2679 rotate_streams
.new_chunk_id
.value
);
2680 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2685 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2686 rotate_streams
.new_chunk_id
.value
);
2687 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2688 chunk_id_str
= "formatting error";
2690 chunk_id_str
= chunk_id_buf
;
2694 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2695 rotate_streams
.stream_count
, session
->session_name
,
2698 stream_positions
= lttng_buffer_view_from_view(payload
,
2700 if (!stream_positions
.data
||
2701 stream_positions
.size
<
2702 (rotate_streams
.stream_count
*
2703 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2704 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2709 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2710 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2711 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2712 const struct lttcomm_relayd_stream_rotation_position pos
= {
2713 .stream_id
= be64toh(position_comm
->stream_id
),
2714 .rotate_at_seq_num
= be64toh(
2715 position_comm
->rotate_at_seq_num
),
2718 stream
= stream_get_by_id(pos
.stream_id
);
2720 reply_code
= LTTNG_ERR_INVALID
;
2725 pthread_mutex_lock(&stream
->lock
);
2726 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2727 pos
.rotate_at_seq_num
);
2728 pthread_mutex_unlock(&stream
->lock
);
2730 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2738 reply_code
= LTTNG_OK
;
2745 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2746 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2747 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2748 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2749 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2754 lttng_trace_chunk_put(next_trace_chunk
);
2759 * relay_create_trace_chunk: create a new trace chunk
2761 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2762 struct relay_connection
*conn
,
2763 const struct lttng_buffer_view
*payload
)
2767 struct relay_session
*session
= conn
->session
;
2768 struct lttcomm_relayd_create_trace_chunk
*msg
;
2769 struct lttcomm_relayd_generic_reply reply
= {};
2770 struct lttng_buffer_view header_view
;
2771 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2772 enum lttng_error_code reply_code
= LTTNG_OK
;
2773 enum lttng_trace_chunk_status chunk_status
;
2774 const char *new_path
;
2776 if (!session
|| !conn
->version_check_done
) {
2777 ERR("Trying to create a trace chunk before version check");
2782 if (session
->major
== 2 && session
->minor
< 11) {
2783 ERR("Chunk creation command is unsupported before 2.11");
2788 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2789 if (!lttng_buffer_view_is_valid(&header_view
)) {
2790 ERR("Failed to receive payload of chunk creation command");
2795 /* Convert to host endianness. */
2796 msg
= (typeof(msg
)) header_view
.data
;
2797 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2798 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2799 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2801 pthread_mutex_lock(&conn
->session
->lock
);
2802 session
->ongoing_rotation
= true;
2803 if (session
->current_trace_chunk
&&
2804 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2805 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2806 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2807 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2808 ERR("Failed to rename old chunk");
2810 reply_code
= LTTNG_ERR_UNK
;
2814 if (!session
->current_trace_chunk
) {
2815 if (!session
->has_rotated
) {
2821 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2823 chunk
= lttng_trace_chunk_create(
2824 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2826 ERR("Failed to create trace chunk in trace chunk creation command");
2828 reply_code
= LTTNG_ERR_NOMEM
;
2831 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2833 if (msg
->override_name_length
) {
2835 const struct lttng_buffer_view chunk_name_view
=
2836 lttng_buffer_view_from_view(payload
,
2838 msg
->override_name_length
);
2840 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2841 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2843 reply_code
= LTTNG_ERR_INVALID
;
2847 name
= chunk_name_view
.data
;
2848 if (name
[msg
->override_name_length
- 1]) {
2849 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2851 reply_code
= LTTNG_ERR_INVALID
;
2855 chunk_status
= lttng_trace_chunk_override_name(
2856 chunk
, chunk_name_view
.data
);
2857 switch (chunk_status
) {
2858 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2860 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2861 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2862 reply_code
= LTTNG_ERR_INVALID
;
2866 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2867 reply_code
= LTTNG_ERR_UNK
;
2873 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2874 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2875 reply_code
= LTTNG_ERR_UNK
;
2880 LTTNG_ASSERT(conn
->session
->output_directory
);
2881 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2882 conn
->session
->output_directory
);
2883 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2884 reply_code
= LTTNG_ERR_UNK
;
2889 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2890 sessiond_trace_chunk_registry
,
2891 conn
->session
->sessiond_uuid
,
2892 conn
->session
->id_sessiond
.is_set
?
2893 conn
->session
->id_sessiond
.value
:
2896 if (!published_chunk
) {
2897 char uuid_str
[LTTNG_UUID_STR_LEN
];
2899 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2900 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2905 reply_code
= LTTNG_ERR_NOMEM
;
2909 if (conn
->session
->pending_closure_trace_chunk
) {
2911 * Invalid; this means a second create_trace_chunk command was
2912 * received before a close_trace_chunk.
2914 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2915 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2919 conn
->session
->pending_closure_trace_chunk
=
2920 conn
->session
->current_trace_chunk
;
2921 conn
->session
->current_trace_chunk
= published_chunk
;
2922 published_chunk
= NULL
;
2923 if (!conn
->session
->pending_closure_trace_chunk
) {
2924 session
->ongoing_rotation
= false;
2927 pthread_mutex_unlock(&conn
->session
->lock
);
2928 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2929 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2931 sizeof(struct lttcomm_relayd_generic_reply
),
2933 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2934 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2939 lttng_trace_chunk_put(chunk
);
2940 lttng_trace_chunk_put(published_chunk
);
2945 * relay_close_trace_chunk: close a trace chunk
2947 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2948 struct relay_connection
*conn
,
2949 const struct lttng_buffer_view
*payload
)
2951 int ret
= 0, buf_ret
;
2953 struct relay_session
*session
= conn
->session
;
2954 struct lttcomm_relayd_close_trace_chunk
*msg
;
2955 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2956 struct lttng_buffer_view header_view
;
2957 struct lttng_trace_chunk
*chunk
= NULL
;
2958 enum lttng_error_code reply_code
= LTTNG_OK
;
2959 enum lttng_trace_chunk_status chunk_status
;
2961 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2962 time_t close_timestamp
;
2963 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2964 size_t path_length
= 0;
2965 const char *chunk_name
= NULL
;
2966 struct lttng_dynamic_buffer reply_payload
;
2967 const char *new_path
;
2969 lttng_dynamic_buffer_init(&reply_payload
);
2971 if (!session
|| !conn
->version_check_done
) {
2972 ERR("Trying to close a trace chunk before version check");
2977 if (session
->major
== 2 && session
->minor
< 11) {
2978 ERR("Chunk close command is unsupported before 2.11");
2983 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2984 if (!lttng_buffer_view_is_valid(&header_view
)) {
2985 ERR("Failed to receive payload of chunk close command");
2990 /* Convert to host endianness. */
2991 msg
= (typeof(msg
)) header_view
.data
;
2992 chunk_id
= be64toh(msg
->chunk_id
);
2993 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2994 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2995 close_command
.is_set
= msg
->close_command
.is_set
;
2997 chunk
= sessiond_trace_chunk_registry_get_chunk(
2998 sessiond_trace_chunk_registry
,
2999 conn
->session
->sessiond_uuid
,
3000 conn
->session
->id_sessiond
.is_set
?
3001 conn
->session
->id_sessiond
.value
:
3005 char uuid_str
[LTTNG_UUID_STR_LEN
];
3007 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3008 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
3013 reply_code
= LTTNG_ERR_NOMEM
;
3017 pthread_mutex_lock(&session
->lock
);
3018 if (close_command
.is_set
&&
3019 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3021 * Clear command. It is a protocol error to ask for a
3022 * clear on a relay which does not allow it. Querying
3023 * the configuration allows figuring out whether
3024 * clearing is allowed before doing the clear.
3026 if (!opt_allow_clear
) {
3028 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3029 goto end_unlock_session
;
3032 if (session
->pending_closure_trace_chunk
&&
3033 session
->pending_closure_trace_chunk
!= chunk
) {
3034 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3035 session
->session_name
);
3036 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3038 goto end_unlock_session
;
3041 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3042 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3043 if (close_command
.is_set
&&
3044 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3045 !session
->has_rotated
) {
3046 /* New chunk stays in session output directory. */
3049 /* Use chunk name for new chunk. */
3052 /* Rename new chunk path. */
3053 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3055 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3057 goto end_unlock_session
;
3059 session
->ongoing_rotation
= false;
3061 if ((!close_command
.is_set
||
3062 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3063 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3064 const char *old_path
;
3066 if (!session
->has_rotated
) {
3071 /* We need to move back the .tmp_old_chunk to its rightful place. */
3072 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3073 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3075 goto end_unlock_session
;
3078 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3079 chunk
, close_timestamp
);
3080 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3081 ERR("Failed to set trace chunk close timestamp");
3083 reply_code
= LTTNG_ERR_UNK
;
3084 goto end_unlock_session
;
3087 if (close_command
.is_set
) {
3088 chunk_status
= lttng_trace_chunk_set_close_command(
3089 chunk
, close_command
.value
);
3090 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3092 reply_code
= LTTNG_ERR_INVALID
;
3093 goto end_unlock_session
;
3096 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3097 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3098 ERR("Failed to get chunk name");
3100 reply_code
= LTTNG_ERR_UNK
;
3101 goto end_unlock_session
;
3103 if (!session
->has_rotated
&& !session
->snapshot
) {
3104 ret
= lttng_strncpy(closed_trace_chunk_path
,
3105 session
->output_path
,
3106 sizeof(closed_trace_chunk_path
));
3108 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3109 strlen(session
->output_path
),
3110 sizeof(closed_trace_chunk_path
));
3111 reply_code
= LTTNG_ERR_NOMEM
;
3113 goto end_unlock_session
;
3116 if (session
->snapshot
) {
3117 ret
= snprintf(closed_trace_chunk_path
,
3118 sizeof(closed_trace_chunk_path
),
3119 "%s/%s", session
->output_path
,
3122 ret
= snprintf(closed_trace_chunk_path
,
3123 sizeof(closed_trace_chunk_path
),
3124 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3126 session
->output_path
, chunk_name
);
3128 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3129 ERR("Failed to format closed trace chunk resulting path");
3130 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3132 goto end_unlock_session
;
3135 if (close_command
.is_set
&&
3136 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3137 session
->has_rotated
= true;
3139 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3140 path_length
= strlen(closed_trace_chunk_path
) + 1;
3141 if (path_length
> UINT32_MAX
) {
3142 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3144 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3145 goto end_unlock_session
;
3148 if (session
->current_trace_chunk
== chunk
) {
3150 * After a trace chunk close command, no new streams
3151 * referencing the chunk may be created. Hence, on the
3152 * event that no new trace chunk have been created for
3153 * the session, the reference to the current trace chunk
3154 * is released in order to allow it to be reclaimed when
3155 * the last stream releases its reference to it.
3157 lttng_trace_chunk_put(session
->current_trace_chunk
);
3158 session
->current_trace_chunk
= NULL
;
3160 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3161 session
->pending_closure_trace_chunk
= NULL
;
3163 pthread_mutex_unlock(&session
->lock
);
3166 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3167 reply
.path_length
= htobe32((uint32_t) path_length
);
3168 buf_ret
= lttng_dynamic_buffer_append(
3169 &reply_payload
, &reply
, sizeof(reply
));
3171 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3175 if (reply_code
== LTTNG_OK
) {
3176 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3177 closed_trace_chunk_path
, path_length
);
3179 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3184 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3188 if (send_ret
< reply_payload
.size
) {
3189 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3190 reply_payload
.size
, send_ret
);
3195 lttng_trace_chunk_put(chunk
);
3196 lttng_dynamic_buffer_reset(&reply_payload
);
3201 * relay_trace_chunk_exists: check if a trace chunk exists
3203 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3204 struct relay_connection
*conn
,
3205 const struct lttng_buffer_view
*payload
)
3209 struct relay_session
*session
= conn
->session
;
3210 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3211 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3212 struct lttng_buffer_view header_view
;
3216 if (!session
|| !conn
->version_check_done
) {
3217 ERR("Trying to check for the presence of a trace chunk before version check");
3222 if (session
->major
== 2 && session
->minor
< 11) {
3223 ERR("Chunk exists command is unsupported before 2.11");
3228 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3229 if (!lttng_buffer_view_is_valid(&header_view
)) {
3230 ERR("Failed to receive payload of chunk exists command");
3235 /* Convert to host endianness. */
3236 msg
= (typeof(msg
)) header_view
.data
;
3237 chunk_id
= be64toh(msg
->chunk_id
);
3239 ret
= sessiond_trace_chunk_registry_chunk_exists(
3240 sessiond_trace_chunk_registry
,
3241 conn
->session
->sessiond_uuid
,
3243 chunk_id
, &chunk_exists
);
3245 * If ret is not 0, send the reply and report the error to the caller.
3246 * It is a protocol (or internal) error and the session/connection
3247 * should be torn down.
3249 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3250 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3252 send_ret
= conn
->sock
->ops
->sendmsg(
3253 conn
->sock
, &reply
, sizeof(reply
), 0);
3254 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3255 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3264 * relay_get_configuration: query whether feature is available
3266 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3267 struct relay_connection
*conn
,
3268 const struct lttng_buffer_view
*payload
)
3272 struct lttcomm_relayd_get_configuration
*msg
;
3273 struct lttcomm_relayd_get_configuration_reply reply
= {};
3274 struct lttng_buffer_view header_view
;
3275 uint64_t query_flags
= 0;
3276 uint64_t result_flags
= 0;
3278 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3279 if (!lttng_buffer_view_is_valid(&header_view
)) {
3280 ERR("Failed to receive payload of chunk close command");
3285 /* Convert to host endianness. */
3286 msg
= (typeof(msg
)) header_view
.data
;
3287 query_flags
= be64toh(msg
->query_flags
);
3290 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3293 if (opt_allow_clear
) {
3294 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3298 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3299 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3301 send_ret
= conn
->sock
->ops
->sendmsg(
3302 conn
->sock
, &reply
, sizeof(reply
), 0);
3303 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3304 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3312 static int relay_process_control_command(struct relay_connection
*conn
,
3313 const struct lttcomm_relayd_hdr
*header
,
3314 const struct lttng_buffer_view
*payload
)
3318 DBG3("Processing \"%s\" command for socket %i",
3319 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3321 switch (header
->cmd
) {
3322 case RELAYD_CREATE_SESSION
:
3323 ret
= relay_create_session(header
, conn
, payload
);
3325 case RELAYD_ADD_STREAM
:
3326 ret
= relay_add_stream(header
, conn
, payload
);
3328 case RELAYD_START_DATA
:
3329 ret
= relay_start(header
, conn
, payload
);
3331 case RELAYD_SEND_METADATA
:
3332 ret
= relay_recv_metadata(header
, conn
, payload
);
3334 case RELAYD_VERSION
:
3335 ret
= relay_send_version(header
, conn
, payload
);
3337 case RELAYD_CLOSE_STREAM
:
3338 ret
= relay_close_stream(header
, conn
, payload
);
3340 case RELAYD_DATA_PENDING
:
3341 ret
= relay_data_pending(header
, conn
, payload
);
3343 case RELAYD_QUIESCENT_CONTROL
:
3344 ret
= relay_quiescent_control(header
, conn
, payload
);
3346 case RELAYD_BEGIN_DATA_PENDING
:
3347 ret
= relay_begin_data_pending(header
, conn
, payload
);
3349 case RELAYD_END_DATA_PENDING
:
3350 ret
= relay_end_data_pending(header
, conn
, payload
);
3352 case RELAYD_SEND_INDEX
:
3353 ret
= relay_recv_index(header
, conn
, payload
);
3355 case RELAYD_STREAMS_SENT
:
3356 ret
= relay_streams_sent(header
, conn
, payload
);
3358 case RELAYD_RESET_METADATA
:
3359 ret
= relay_reset_metadata(header
, conn
, payload
);
3361 case RELAYD_ROTATE_STREAMS
:
3362 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3364 case RELAYD_CREATE_TRACE_CHUNK
:
3365 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3367 case RELAYD_CLOSE_TRACE_CHUNK
:
3368 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3370 case RELAYD_TRACE_CHUNK_EXISTS
:
3371 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3373 case RELAYD_GET_CONFIGURATION
:
3374 ret
= relay_get_configuration(header
, conn
, payload
);
3376 case RELAYD_UPDATE_SYNC_INFO
:
3378 ERR("Received unknown command (%u)", header
->cmd
);
3379 relay_unknown_command(conn
);
3388 static enum relay_connection_status
relay_process_control_receive_payload(
3389 struct relay_connection
*conn
)
3392 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3393 struct lttng_dynamic_buffer
*reception_buffer
=
3394 &conn
->protocol
.ctrl
.reception_buffer
;
3395 struct ctrl_connection_state_receive_payload
*state
=
3396 &conn
->protocol
.ctrl
.state
.receive_payload
;
3397 struct lttng_buffer_view payload_view
;
3399 if (state
->left_to_receive
== 0) {
3400 /* Short-circuit for payload-less commands. */
3401 goto reception_complete
;
3404 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3405 reception_buffer
->data
+ state
->received
,
3406 state
->left_to_receive
, MSG_DONTWAIT
);
3409 DIAGNOSTIC_IGNORE_LOGICAL_OP
3410 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3412 PERROR("Unable to receive command payload on sock %d",
3414 status
= RELAY_CONNECTION_STATUS_ERROR
;
3417 } else if (ret
== 0) {
3418 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3419 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3423 LTTNG_ASSERT(ret
> 0);
3424 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3426 state
->left_to_receive
-= ret
;
3427 state
->received
+= ret
;
3429 if (state
->left_to_receive
> 0) {
3431 * Can't transition to the protocol's next state, wait to
3432 * receive the rest of the header.
3434 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3435 state
->received
, state
->left_to_receive
,
3441 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3442 conn
->sock
->fd
, state
->received
);
3444 * The payload required to process the command has been received.
3445 * A view to the reception buffer is forwarded to the various
3446 * commands and the state of the control is reset on success.
3448 * Commands are responsible for sending their reply to the peer.
3450 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3452 ret
= relay_process_control_command(conn
,
3453 &state
->header
, &payload_view
);
3455 status
= RELAY_CONNECTION_STATUS_ERROR
;
3459 ret
= connection_reset_protocol_state(conn
);
3461 status
= RELAY_CONNECTION_STATUS_ERROR
;
3467 static enum relay_connection_status
relay_process_control_receive_header(
3468 struct relay_connection
*conn
)
3471 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3472 struct lttcomm_relayd_hdr header
;
3473 struct lttng_dynamic_buffer
*reception_buffer
=
3474 &conn
->protocol
.ctrl
.reception_buffer
;
3475 struct ctrl_connection_state_receive_header
*state
=
3476 &conn
->protocol
.ctrl
.state
.receive_header
;
3478 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3480 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3481 reception_buffer
->data
+ state
->received
,
3482 state
->left_to_receive
, MSG_DONTWAIT
);
3485 DIAGNOSTIC_IGNORE_LOGICAL_OP
3486 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
;
3499 LTTNG_ASSERT(ret
> 0);
3500 LTTNG_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 = %s, cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3528 conn
->sock
->fd
, lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3529 header
.cmd_version
, header
.data_size
);
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 LTTNG_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
);
3599 DIAGNOSTIC_IGNORE_LOGICAL_OP
3600 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3602 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3603 status
= RELAY_CONNECTION_STATUS_ERROR
;
3606 } else if (ret
== 0) {
3607 /* Orderly shutdown. Not necessary to print an error. */
3608 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3609 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3613 LTTNG_ASSERT(ret
> 0);
3614 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3616 state
->left_to_receive
-= ret
;
3617 state
->received
+= ret
;
3619 if (state
->left_to_receive
> 0) {
3621 * Can't transition to the protocol's next state, wait to
3622 * receive the rest of the header.
3624 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3625 state
->received
, state
->left_to_receive
,
3630 /* Transition to next state: receiving the payload. */
3631 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3633 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3634 header
.circuit_id
= be64toh(header
.circuit_id
);
3635 header
.stream_id
= be64toh(header
.stream_id
);
3636 header
.data_size
= be32toh(header
.data_size
);
3637 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3638 header
.padding_size
= be32toh(header
.padding_size
);
3639 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3641 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3643 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3644 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3646 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3647 conn
->sock
->fd
, header
.circuit_id
,
3648 header
.stream_id
, header
.data_size
,
3649 header
.net_seq_num
, header
.padding_size
);
3651 stream
= stream_get_by_id(header
.stream_id
);
3653 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3655 /* Protocol error. */
3656 status
= RELAY_CONNECTION_STATUS_ERROR
;
3660 pthread_mutex_lock(&stream
->lock
);
3661 /* Prepare stream for the reception of a new packet. */
3662 ret
= stream_init_packet(stream
, header
.data_size
,
3663 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3664 pthread_mutex_unlock(&stream
->lock
);
3666 ERR("Failed to rotate stream output file");
3667 status
= RELAY_CONNECTION_STATUS_ERROR
;
3668 goto end_stream_unlock
;
3677 static enum relay_connection_status
relay_process_data_receive_payload(
3678 struct relay_connection
*conn
)
3681 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3682 struct relay_stream
*stream
;
3683 struct data_connection_state_receive_payload
*state
=
3684 &conn
->protocol
.data
.state
.receive_payload
;
3685 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3686 char data_buffer
[chunk_size
];
3687 bool partial_recv
= false;
3688 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3689 uint64_t left_to_receive
= state
->left_to_receive
;
3690 struct relay_session
*session
;
3692 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3693 state
->header
.stream_id
, state
->header
.net_seq_num
,
3694 state
->received
, left_to_receive
);
3696 stream
= stream_get_by_id(state
->header
.stream_id
);
3698 /* Protocol error. */
3699 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3700 state
->header
.stream_id
);
3701 status
= RELAY_CONNECTION_STATUS_ERROR
;
3705 pthread_mutex_lock(&stream
->lock
);
3706 session
= stream
->trace
->session
;
3707 if (!conn
->session
) {
3708 ret
= connection_set_session(conn
, session
);
3710 status
= RELAY_CONNECTION_STATUS_ERROR
;
3711 goto end_stream_unlock
;
3716 * The size of the "chunk" received on any iteration is bounded by:
3717 * - the data left to receive,
3718 * - the data immediately available on the socket,
3719 * - the on-stack data buffer
3721 while (left_to_receive
> 0 && !partial_recv
) {
3722 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3723 struct lttng_buffer_view packet_chunk
;
3725 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3726 recv_size
, MSG_DONTWAIT
);
3729 DIAGNOSTIC_IGNORE_LOGICAL_OP
3730 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3732 PERROR("Socket %d error", conn
->sock
->fd
);
3733 status
= RELAY_CONNECTION_STATUS_ERROR
;
3735 goto end_stream_unlock
;
3736 } else if (ret
== 0) {
3737 /* No more data ready to be consumed on socket. */
3738 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3739 state
->header
.stream_id
);
3740 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3742 } else if (ret
< (int) recv_size
) {
3744 * All the data available on the socket has been
3747 partial_recv
= true;
3751 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3753 LTTNG_ASSERT(packet_chunk
.data
);
3755 ret
= stream_write(stream
, &packet_chunk
, 0);
3757 ERR("Relay error writing data to file");
3758 status
= RELAY_CONNECTION_STATUS_ERROR
;
3759 goto end_stream_unlock
;
3762 left_to_receive
-= recv_size
;
3763 state
->received
+= recv_size
;
3764 state
->left_to_receive
= left_to_receive
;
3767 if (state
->left_to_receive
> 0) {
3769 * Did not receive all the data expected, wait for more data to
3770 * become available on the socket.
3772 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3773 state
->header
.stream_id
, state
->received
,
3774 state
->left_to_receive
);
3775 goto end_stream_unlock
;
3778 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3780 status
= RELAY_CONNECTION_STATUS_ERROR
;
3781 goto end_stream_unlock
;
3784 if (session_streams_have_index(session
)) {
3785 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3786 state
->rotate_index
, &index_flushed
,
3787 state
->header
.data_size
+ state
->header
.padding_size
);
3789 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3790 stream
->stream_handle
,
3791 state
->header
.net_seq_num
, ret
);
3792 status
= RELAY_CONNECTION_STATUS_ERROR
;
3793 goto end_stream_unlock
;
3797 if (stream
->prev_data_seq
== -1ULL) {
3801 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3802 state
->header
.padding_size
, state
->header
.net_seq_num
,
3805 status
= RELAY_CONNECTION_STATUS_ERROR
;
3806 goto end_stream_unlock
;
3810 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3811 * contents of *state which are aliased (union) to the same location as
3812 * the new state. Don't use it beyond this point.
3814 connection_reset_protocol_state(conn
);
3818 close_requested
= stream
->close_requested
;
3819 pthread_mutex_unlock(&stream
->lock
);
3820 if (close_requested
&& left_to_receive
== 0) {
3821 try_stream_close(stream
);
3825 pthread_mutex_lock(&session
->lock
);
3826 uatomic_set(&session
->new_streams
, 1);
3827 pthread_mutex_unlock(&session
->lock
);
3836 * relay_process_data: Process the data received on the data socket
3838 static enum relay_connection_status
relay_process_data(
3839 struct relay_connection
*conn
)
3841 enum relay_connection_status status
;
3843 switch (conn
->protocol
.data
.state_id
) {
3844 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3845 status
= relay_process_data_receive_header(conn
);
3847 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3848 status
= relay_process_data_receive_payload(conn
);
3851 ERR("Unexpected data connection communication state.");
3858 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3862 (void) lttng_poll_del(events
, pollfd
);
3864 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3865 fd_tracker_util_close_fd
, NULL
);
3867 ERR("Closing pollfd %d", pollfd
);
3871 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3872 int pollfd
, struct relay_connection
*conn
)
3874 const char *type_str
;
3876 switch (conn
->type
) {
3881 type_str
= "Control";
3883 case RELAY_VIEWER_COMMAND
:
3884 type_str
= "Viewer Command";
3886 case RELAY_VIEWER_NOTIFICATION
:
3887 type_str
= "Viewer Notification";
3890 type_str
= "Unknown";
3892 cleanup_connection_pollfd(events
, pollfd
);
3893 connection_put(conn
);
3894 DBG("%s connection closed with %d", type_str
, pollfd
);
3898 * This thread does the actual work
3900 static void *relay_thread_worker(void *data
)
3902 int ret
, err
= -1, last_seen_data_fd
= -1;
3904 struct lttng_poll_event events
;
3905 struct lttng_ht
*relay_connections_ht
;
3906 struct lttng_ht_iter iter
;
3907 struct relay_connection
*destroy_conn
= NULL
;
3909 DBG("[thread] Relay worker started");
3911 rcu_register_thread();
3913 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3915 if (testpoint(relayd_thread_worker
)) {
3916 goto error_testpoint
;
3919 health_code_update();
3921 /* table of connections indexed on socket */
3922 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3923 if (!relay_connections_ht
) {
3924 goto relay_connections_ht_error
;
3927 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3929 goto error_poll_create
;
3932 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3939 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3941 health_code_update();
3943 /* Infinite blocking call, waiting for transmission */
3944 DBG3("Relayd worker thread polling...");
3945 health_poll_entry();
3946 ret
= lttng_poll_wait(&events
, -1);
3950 * Restart interrupted system call.
3952 if (errno
== EINTR
) {
3961 * Process control. The control connection is
3962 * prioritized so we don't starve it with high
3963 * throughput tracing data on the data connection.
3965 for (i
= 0; i
< nb_fd
; i
++) {
3966 /* Fetch once the poll data */
3967 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3968 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3970 health_code_update();
3972 /* Thread quit pipe has been closed. Killing thread. */
3973 ret
= check_thread_quit_pipe(pollfd
, revents
);
3979 /* Inspect the relay conn pipe for new connection */
3980 if (pollfd
== relay_conn_pipe
[0]) {
3981 if (revents
& LPOLLIN
) {
3982 struct relay_connection
*conn
;
3984 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3988 ret
= lttng_poll_add(&events
,
3990 LPOLLIN
| LPOLLRDHUP
);
3992 ERR("Failed to add new connection file descriptor to poll set");
3995 connection_ht_add(relay_connections_ht
, conn
);
3996 DBG("Connection socket %d added", conn
->sock
->fd
);
3997 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3998 ERR("Relay connection pipe error");
4001 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4005 struct relay_connection
*ctrl_conn
;
4007 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4008 /* If not found, there is a synchronization issue. */
4009 LTTNG_ASSERT(ctrl_conn
);
4011 if (ctrl_conn
->type
== RELAY_DATA
) {
4012 if (revents
& LPOLLIN
) {
4014 * Flag the last seen data fd not deleted. It will be
4015 * used as the last seen fd if any fd gets deleted in
4018 last_notdel_data_fd
= pollfd
;
4020 goto put_ctrl_connection
;
4022 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4024 if (revents
& LPOLLIN
) {
4025 enum relay_connection_status status
;
4027 status
= relay_process_control(ctrl_conn
);
4028 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4030 * On socket error flag the session as aborted to force
4031 * the cleanup of its stream otherwise it can leak
4032 * during the lifetime of the relayd.
4034 * This prevents situations in which streams can be
4035 * left opened because an index was received, the
4036 * control connection is closed, and the data
4037 * connection is closed (uncleanly) before the packet's
4040 * Since the control connection encountered an error,
4041 * it is okay to be conservative and close the
4042 * session right now as we can't rely on the protocol
4043 * being respected anymore.
4045 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4046 session_abort(ctrl_conn
->session
);
4049 /* Clear the connection on error or close. */
4050 relay_thread_close_connection(&events
,
4055 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4056 relay_thread_close_connection(&events
,
4058 if (last_seen_data_fd
== pollfd
) {
4059 last_seen_data_fd
= last_notdel_data_fd
;
4062 ERR("Unexpected poll events %u for control sock %d",
4064 connection_put(ctrl_conn
);
4067 put_ctrl_connection
:
4068 connection_put(ctrl_conn
);
4073 * The last loop handled a control request, go back to poll to make
4074 * sure we prioritise the control socket.
4080 if (last_seen_data_fd
>= 0) {
4081 for (i
= 0; i
< nb_fd
; i
++) {
4082 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4084 health_code_update();
4086 if (last_seen_data_fd
== pollfd
) {
4093 /* Process data connection. */
4094 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4095 /* Fetch the poll data. */
4096 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4097 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4098 struct relay_connection
*data_conn
;
4100 health_code_update();
4103 /* No activity for this FD (poll implementation). */
4107 /* Skip the command pipe. It's handled in the first loop. */
4108 if (pollfd
== relay_conn_pipe
[0]) {
4112 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4114 /* Skip it. Might be removed before. */
4117 if (data_conn
->type
== RELAY_CONTROL
) {
4118 goto put_data_connection
;
4120 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4122 if (revents
& LPOLLIN
) {
4123 enum relay_connection_status status
;
4125 status
= relay_process_data(data_conn
);
4126 /* Connection closed or error. */
4127 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4129 * On socket error flag the session as aborted to force
4130 * the cleanup of its stream otherwise it can leak
4131 * during the lifetime of the relayd.
4133 * This prevents situations in which streams can be
4134 * left opened because an index was received, the
4135 * control connection is closed, and the data
4136 * connection is closed (uncleanly) before the packet's
4139 * Since the data connection encountered an error,
4140 * it is okay to be conservative and close the
4141 * session right now as we can't rely on the protocol
4142 * being respected anymore.
4144 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4145 session_abort(data_conn
->session
);
4147 relay_thread_close_connection(&events
, pollfd
,
4150 * Every goto restart call sets the last seen fd where
4151 * here we don't really care since we gracefully
4152 * continue the loop after the connection is deleted.
4155 /* Keep last seen port. */
4156 last_seen_data_fd
= pollfd
;
4157 connection_put(data_conn
);
4160 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4161 relay_thread_close_connection(&events
, pollfd
,
4164 ERR("Unknown poll events %u for data sock %d",
4167 put_data_connection
:
4168 connection_put(data_conn
);
4170 last_seen_data_fd
= -1;
4173 /* Normal exit, no error */
4178 /* Cleanup remaining connection object. */
4180 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4183 health_code_update();
4185 session_abort(destroy_conn
->session
);
4188 * No need to grab another ref, because we own
4191 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4196 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4198 lttng_ht_destroy(relay_connections_ht
);
4199 relay_connections_ht_error
:
4200 /* Close relay conn pipes */
4201 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4204 DBG("Thread exited with error");
4206 DBG("Worker thread cleanup complete");
4210 ERR("Health error occurred in %s", __func__
);
4212 health_unregister(health_relayd
);
4213 rcu_unregister_thread();
4214 lttng_relay_stop_threads();
4219 * Create the relay command pipe to wake thread_manage_apps.
4220 * Closed in cleanup().
4222 static int create_relay_conn_pipe(void)
4224 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4225 "Relayd connection pipe", relay_conn_pipe
);
4228 static int stdio_open(void *data
, int *fds
)
4230 fds
[0] = fileno(stdout
);
4231 fds
[1] = fileno(stderr
);
4235 static int track_stdio(void)
4238 const char *names
[] = { "stdout", "stderr" };
4240 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4241 names
, 2, stdio_open
, NULL
);
4247 int main(int argc
, char **argv
)
4249 bool thread_is_rcu_registered
= false;
4250 int ret
= 0, retval
= 0;
4252 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4254 /* Parse environment variables */
4255 ret
= parse_env_options();
4263 * Command line arguments overwrite environment.
4266 if (set_options(argc
, argv
)) {
4271 if (set_signal_handler()) {
4276 relayd_config_log();
4278 if (opt_print_version
) {
4284 ret
= fclose(stdin
);
4286 PERROR("Failed to close stdin");
4290 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4292 /* Try to create directory if -o, --output is specified. */
4293 if (opt_output_path
) {
4294 if (*opt_output_path
!= '/') {
4295 ERR("Please specify an absolute path for -o, --output PATH");
4300 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4303 ERR("Unable to create %s", opt_output_path
);
4310 if (opt_daemon
|| opt_background
) {
4311 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4319 if (opt_working_directory
) {
4320 ret
= utils_change_working_directory(opt_working_directory
);
4322 /* All errors are already logged. */
4327 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4328 if (!sessiond_trace_chunk_registry
) {
4329 ERR("Failed to initialize session daemon trace chunk registry");
4335 * The RCU thread registration (and use, through the fd-tracker's
4336 * creation) is done after the daemonization to allow us to not
4337 * deal with liburcu's fork() management as the call RCU needs to
4340 rcu_register_thread();
4341 thread_is_rcu_registered
= true;
4343 output_path
= create_output_path("");
4345 ERR("Failed to get output path");
4349 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4350 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4353 ERR("Failed to format unlinked file directory path");
4357 the_fd_tracker
= fd_tracker_create(
4358 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4359 free(unlinked_file_directory_path
);
4360 if (!the_fd_tracker
) {
4365 ret
= track_stdio();
4371 /* Initialize thread health monitoring */
4372 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4373 if (!health_relayd
) {
4374 PERROR("health_app_create error");
4379 /* Create thread quit pipe */
4380 if (init_thread_quit_pipe()) {
4385 /* Setup the thread apps communication pipe. */
4386 if (create_relay_conn_pipe()) {
4391 /* Init relay command queue. */
4392 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4394 /* Initialize communication library */
4396 lttcomm_inet_init();
4398 /* tables of sessions indexed by session ID */
4399 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4405 /* tables of streams indexed by stream ID */
4406 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4407 if (!relay_streams_ht
) {
4412 /* tables of streams indexed by stream ID */
4413 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4414 if (!viewer_streams_ht
) {
4419 ret
= init_health_quit_pipe();
4425 /* Create thread to manage the client socket */
4426 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4427 thread_manage_health
, (void *) NULL
);
4430 PERROR("pthread_create health");
4435 /* Setup the dispatcher thread */
4436 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4437 relay_thread_dispatcher
, (void *) NULL
);
4440 PERROR("pthread_create dispatcher");
4442 goto exit_dispatcher_thread
;
4445 /* Setup the worker thread */
4446 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4447 relay_thread_worker
, NULL
);
4450 PERROR("pthread_create worker");
4452 goto exit_worker_thread
;
4455 /* Setup the listener thread */
4456 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4457 relay_thread_listener
, (void *) NULL
);
4460 PERROR("pthread_create listener");
4462 goto exit_listener_thread
;
4465 ret
= relayd_live_create(live_uri
);
4467 ERR("Starting live viewer threads");
4473 * This is where we start awaiting program completion (e.g. through
4474 * signal that asks threads to teardown).
4477 ret
= relayd_live_join();
4483 ret
= pthread_join(listener_thread
, &status
);
4486 PERROR("pthread_join listener_thread");
4490 exit_listener_thread
:
4491 ret
= pthread_join(worker_thread
, &status
);
4494 PERROR("pthread_join worker_thread");
4499 ret
= pthread_join(dispatcher_thread
, &status
);
4502 PERROR("pthread_join dispatcher_thread");
4505 exit_dispatcher_thread
:
4507 ret
= pthread_join(health_thread
, &status
);
4510 PERROR("pthread_join health_thread");
4515 * Wait for all pending call_rcu work to complete before tearing
4516 * down data structures. call_rcu worker may be trying to
4517 * perform lookups in those structures.
4522 /* Ensure all prior call_rcu are done. */
4525 if (thread_is_rcu_registered
) {
4526 rcu_unregister_thread();