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
);
3408 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3409 PERROR("Unable to receive command payload on sock %d",
3411 status
= RELAY_CONNECTION_STATUS_ERROR
;
3414 } else if (ret
== 0) {
3415 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3416 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3420 LTTNG_ASSERT(ret
> 0);
3421 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3423 state
->left_to_receive
-= ret
;
3424 state
->received
+= ret
;
3426 if (state
->left_to_receive
> 0) {
3428 * Can't transition to the protocol's next state, wait to
3429 * receive the rest of the header.
3431 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3432 state
->received
, state
->left_to_receive
,
3438 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3439 conn
->sock
->fd
, state
->received
);
3441 * The payload required to process the command has been received.
3442 * A view to the reception buffer is forwarded to the various
3443 * commands and the state of the control is reset on success.
3445 * Commands are responsible for sending their reply to the peer.
3447 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3449 ret
= relay_process_control_command(conn
,
3450 &state
->header
, &payload_view
);
3452 status
= RELAY_CONNECTION_STATUS_ERROR
;
3456 ret
= connection_reset_protocol_state(conn
);
3458 status
= RELAY_CONNECTION_STATUS_ERROR
;
3464 static enum relay_connection_status
relay_process_control_receive_header(
3465 struct relay_connection
*conn
)
3468 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3469 struct lttcomm_relayd_hdr header
;
3470 struct lttng_dynamic_buffer
*reception_buffer
=
3471 &conn
->protocol
.ctrl
.reception_buffer
;
3472 struct ctrl_connection_state_receive_header
*state
=
3473 &conn
->protocol
.ctrl
.state
.receive_header
;
3475 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3477 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3478 reception_buffer
->data
+ state
->received
,
3479 state
->left_to_receive
, MSG_DONTWAIT
);
3481 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3482 PERROR("Unable to receive control command header on sock %d",
3484 status
= RELAY_CONNECTION_STATUS_ERROR
;
3487 } else if (ret
== 0) {
3488 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3489 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3493 LTTNG_ASSERT(ret
> 0);
3494 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3496 state
->left_to_receive
-= ret
;
3497 state
->received
+= ret
;
3499 if (state
->left_to_receive
> 0) {
3501 * Can't transition to the protocol's next state, wait to
3502 * receive the rest of the header.
3504 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3505 state
->received
, state
->left_to_receive
,
3510 /* Transition to next state: receiving the command's payload. */
3511 conn
->protocol
.ctrl
.state_id
=
3512 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3513 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3514 header
.circuit_id
= be64toh(header
.circuit_id
);
3515 header
.data_size
= be64toh(header
.data_size
);
3516 header
.cmd
= be32toh(header
.cmd
);
3517 header
.cmd_version
= be32toh(header
.cmd_version
);
3518 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3519 &header
, sizeof(header
));
3521 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3522 conn
->sock
->fd
, lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3523 header
.cmd_version
, header
.data_size
);
3525 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3526 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3528 status
= RELAY_CONNECTION_STATUS_ERROR
;
3532 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3534 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3535 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3538 status
= RELAY_CONNECTION_STATUS_ERROR
;
3542 if (header
.data_size
== 0) {
3544 * Manually invoke the next state as the poll loop
3545 * will not wake-up to allow us to proceed further.
3547 status
= relay_process_control_receive_payload(conn
);
3554 * Process the commands received on the control socket
3556 static enum relay_connection_status
relay_process_control(
3557 struct relay_connection
*conn
)
3559 enum relay_connection_status status
;
3561 switch (conn
->protocol
.ctrl
.state_id
) {
3562 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3563 status
= relay_process_control_receive_header(conn
);
3565 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3566 status
= relay_process_control_receive_payload(conn
);
3569 ERR("Unknown control connection protocol state encountered.");
3576 static enum relay_connection_status
relay_process_data_receive_header(
3577 struct relay_connection
*conn
)
3580 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3581 struct data_connection_state_receive_header
*state
=
3582 &conn
->protocol
.data
.state
.receive_header
;
3583 struct lttcomm_relayd_data_hdr header
;
3584 struct relay_stream
*stream
;
3586 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3588 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3589 state
->header_reception_buffer
+ state
->received
,
3590 state
->left_to_receive
, MSG_DONTWAIT
);
3592 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3593 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3594 status
= RELAY_CONNECTION_STATUS_ERROR
;
3597 } else if (ret
== 0) {
3598 /* Orderly shutdown. Not necessary to print an error. */
3599 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3600 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3604 LTTNG_ASSERT(ret
> 0);
3605 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3607 state
->left_to_receive
-= ret
;
3608 state
->received
+= ret
;
3610 if (state
->left_to_receive
> 0) {
3612 * Can't transition to the protocol's next state, wait to
3613 * receive the rest of the header.
3615 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3616 state
->received
, state
->left_to_receive
,
3621 /* Transition to next state: receiving the payload. */
3622 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3624 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3625 header
.circuit_id
= be64toh(header
.circuit_id
);
3626 header
.stream_id
= be64toh(header
.stream_id
);
3627 header
.data_size
= be32toh(header
.data_size
);
3628 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3629 header
.padding_size
= be32toh(header
.padding_size
);
3630 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3632 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3634 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3635 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3637 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3638 conn
->sock
->fd
, header
.circuit_id
,
3639 header
.stream_id
, header
.data_size
,
3640 header
.net_seq_num
, header
.padding_size
);
3642 stream
= stream_get_by_id(header
.stream_id
);
3644 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3646 /* Protocol error. */
3647 status
= RELAY_CONNECTION_STATUS_ERROR
;
3651 pthread_mutex_lock(&stream
->lock
);
3652 /* Prepare stream for the reception of a new packet. */
3653 ret
= stream_init_packet(stream
, header
.data_size
,
3654 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3655 pthread_mutex_unlock(&stream
->lock
);
3657 ERR("Failed to rotate stream output file");
3658 status
= RELAY_CONNECTION_STATUS_ERROR
;
3659 goto end_stream_unlock
;
3668 static enum relay_connection_status
relay_process_data_receive_payload(
3669 struct relay_connection
*conn
)
3672 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3673 struct relay_stream
*stream
;
3674 struct data_connection_state_receive_payload
*state
=
3675 &conn
->protocol
.data
.state
.receive_payload
;
3676 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3677 char data_buffer
[chunk_size
];
3678 bool partial_recv
= false;
3679 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3680 uint64_t left_to_receive
= state
->left_to_receive
;
3681 struct relay_session
*session
;
3683 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3684 state
->header
.stream_id
, state
->header
.net_seq_num
,
3685 state
->received
, left_to_receive
);
3687 stream
= stream_get_by_id(state
->header
.stream_id
);
3689 /* Protocol error. */
3690 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3691 state
->header
.stream_id
);
3692 status
= RELAY_CONNECTION_STATUS_ERROR
;
3696 pthread_mutex_lock(&stream
->lock
);
3697 session
= stream
->trace
->session
;
3698 if (!conn
->session
) {
3699 ret
= connection_set_session(conn
, session
);
3701 status
= RELAY_CONNECTION_STATUS_ERROR
;
3702 goto end_stream_unlock
;
3707 * The size of the "chunk" received on any iteration is bounded by:
3708 * - the data left to receive,
3709 * - the data immediately available on the socket,
3710 * - the on-stack data buffer
3712 while (left_to_receive
> 0 && !partial_recv
) {
3713 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3714 struct lttng_buffer_view packet_chunk
;
3716 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3717 recv_size
, MSG_DONTWAIT
);
3719 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3720 PERROR("Socket %d error", conn
->sock
->fd
);
3721 status
= RELAY_CONNECTION_STATUS_ERROR
;
3723 goto end_stream_unlock
;
3724 } else if (ret
== 0) {
3725 /* No more data ready to be consumed on socket. */
3726 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3727 state
->header
.stream_id
);
3728 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3730 } else if (ret
< (int) recv_size
) {
3732 * All the data available on the socket has been
3735 partial_recv
= true;
3739 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3741 LTTNG_ASSERT(packet_chunk
.data
);
3743 ret
= stream_write(stream
, &packet_chunk
, 0);
3745 ERR("Relay error writing data to file");
3746 status
= RELAY_CONNECTION_STATUS_ERROR
;
3747 goto end_stream_unlock
;
3750 left_to_receive
-= recv_size
;
3751 state
->received
+= recv_size
;
3752 state
->left_to_receive
= left_to_receive
;
3755 if (state
->left_to_receive
> 0) {
3757 * Did not receive all the data expected, wait for more data to
3758 * become available on the socket.
3760 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3761 state
->header
.stream_id
, state
->received
,
3762 state
->left_to_receive
);
3763 goto end_stream_unlock
;
3766 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3768 status
= RELAY_CONNECTION_STATUS_ERROR
;
3769 goto end_stream_unlock
;
3772 if (session_streams_have_index(session
)) {
3773 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3774 state
->rotate_index
, &index_flushed
,
3775 state
->header
.data_size
+ state
->header
.padding_size
);
3777 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3778 stream
->stream_handle
,
3779 state
->header
.net_seq_num
, ret
);
3780 status
= RELAY_CONNECTION_STATUS_ERROR
;
3781 goto end_stream_unlock
;
3785 if (stream
->prev_data_seq
== -1ULL) {
3789 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3790 state
->header
.padding_size
, state
->header
.net_seq_num
,
3793 status
= RELAY_CONNECTION_STATUS_ERROR
;
3794 goto end_stream_unlock
;
3798 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3799 * contents of *state which are aliased (union) to the same location as
3800 * the new state. Don't use it beyond this point.
3802 connection_reset_protocol_state(conn
);
3806 close_requested
= stream
->close_requested
;
3807 pthread_mutex_unlock(&stream
->lock
);
3808 if (close_requested
&& left_to_receive
== 0) {
3809 try_stream_close(stream
);
3813 pthread_mutex_lock(&session
->lock
);
3814 uatomic_set(&session
->new_streams
, 1);
3815 pthread_mutex_unlock(&session
->lock
);
3824 * relay_process_data: Process the data received on the data socket
3826 static enum relay_connection_status
relay_process_data(
3827 struct relay_connection
*conn
)
3829 enum relay_connection_status status
;
3831 switch (conn
->protocol
.data
.state_id
) {
3832 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3833 status
= relay_process_data_receive_header(conn
);
3835 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3836 status
= relay_process_data_receive_payload(conn
);
3839 ERR("Unexpected data connection communication state.");
3846 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3850 (void) lttng_poll_del(events
, pollfd
);
3852 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3853 fd_tracker_util_close_fd
, NULL
);
3855 ERR("Closing pollfd %d", pollfd
);
3859 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3860 int pollfd
, struct relay_connection
*conn
)
3862 const char *type_str
;
3864 switch (conn
->type
) {
3869 type_str
= "Control";
3871 case RELAY_VIEWER_COMMAND
:
3872 type_str
= "Viewer Command";
3874 case RELAY_VIEWER_NOTIFICATION
:
3875 type_str
= "Viewer Notification";
3878 type_str
= "Unknown";
3880 cleanup_connection_pollfd(events
, pollfd
);
3881 connection_put(conn
);
3882 DBG("%s connection closed with %d", type_str
, pollfd
);
3886 * This thread does the actual work
3888 static void *relay_thread_worker(void *data
)
3890 int ret
, err
= -1, last_seen_data_fd
= -1;
3892 struct lttng_poll_event events
;
3893 struct lttng_ht
*relay_connections_ht
;
3894 struct lttng_ht_iter iter
;
3895 struct relay_connection
*destroy_conn
= NULL
;
3897 DBG("[thread] Relay worker started");
3899 rcu_register_thread();
3901 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3903 if (testpoint(relayd_thread_worker
)) {
3904 goto error_testpoint
;
3907 health_code_update();
3909 /* table of connections indexed on socket */
3910 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3911 if (!relay_connections_ht
) {
3912 goto relay_connections_ht_error
;
3915 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3917 goto error_poll_create
;
3920 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3927 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3929 health_code_update();
3931 /* Infinite blocking call, waiting for transmission */
3932 DBG3("Relayd worker thread polling...");
3933 health_poll_entry();
3934 ret
= lttng_poll_wait(&events
, -1);
3938 * Restart interrupted system call.
3940 if (errno
== EINTR
) {
3949 * Process control. The control connection is
3950 * prioritized so we don't starve it with high
3951 * throughput tracing data on the data connection.
3953 for (i
= 0; i
< nb_fd
; i
++) {
3954 /* Fetch once the poll data */
3955 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3956 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3958 health_code_update();
3960 /* Thread quit pipe has been closed. Killing thread. */
3961 ret
= check_thread_quit_pipe(pollfd
, revents
);
3967 /* Inspect the relay conn pipe for new connection */
3968 if (pollfd
== relay_conn_pipe
[0]) {
3969 if (revents
& LPOLLIN
) {
3970 struct relay_connection
*conn
;
3972 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3976 ret
= lttng_poll_add(&events
,
3978 LPOLLIN
| LPOLLRDHUP
);
3980 ERR("Failed to add new connection file descriptor to poll set");
3983 connection_ht_add(relay_connections_ht
, conn
);
3984 DBG("Connection socket %d added", conn
->sock
->fd
);
3985 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3986 ERR("Relay connection pipe error");
3989 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3993 struct relay_connection
*ctrl_conn
;
3995 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3996 /* If not found, there is a synchronization issue. */
3997 LTTNG_ASSERT(ctrl_conn
);
3999 if (ctrl_conn
->type
== RELAY_DATA
) {
4000 if (revents
& LPOLLIN
) {
4002 * Flag the last seen data fd not deleted. It will be
4003 * used as the last seen fd if any fd gets deleted in
4006 last_notdel_data_fd
= pollfd
;
4008 goto put_ctrl_connection
;
4010 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4012 if (revents
& LPOLLIN
) {
4013 enum relay_connection_status status
;
4015 status
= relay_process_control(ctrl_conn
);
4016 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4018 * On socket error flag the session as aborted to force
4019 * the cleanup of its stream otherwise it can leak
4020 * during the lifetime of the relayd.
4022 * This prevents situations in which streams can be
4023 * left opened because an index was received, the
4024 * control connection is closed, and the data
4025 * connection is closed (uncleanly) before the packet's
4028 * Since the control connection encountered an error,
4029 * it is okay to be conservative and close the
4030 * session right now as we can't rely on the protocol
4031 * being respected anymore.
4033 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4034 session_abort(ctrl_conn
->session
);
4037 /* Clear the connection on error or close. */
4038 relay_thread_close_connection(&events
,
4043 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4044 relay_thread_close_connection(&events
,
4046 if (last_seen_data_fd
== pollfd
) {
4047 last_seen_data_fd
= last_notdel_data_fd
;
4050 ERR("Unexpected poll events %u for control sock %d",
4052 connection_put(ctrl_conn
);
4055 put_ctrl_connection
:
4056 connection_put(ctrl_conn
);
4061 * The last loop handled a control request, go back to poll to make
4062 * sure we prioritise the control socket.
4068 if (last_seen_data_fd
>= 0) {
4069 for (i
= 0; i
< nb_fd
; i
++) {
4070 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4072 health_code_update();
4074 if (last_seen_data_fd
== pollfd
) {
4081 /* Process data connection. */
4082 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4083 /* Fetch the poll data. */
4084 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4085 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4086 struct relay_connection
*data_conn
;
4088 health_code_update();
4091 /* No activity for this FD (poll implementation). */
4095 /* Skip the command pipe. It's handled in the first loop. */
4096 if (pollfd
== relay_conn_pipe
[0]) {
4100 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4102 /* Skip it. Might be removed before. */
4105 if (data_conn
->type
== RELAY_CONTROL
) {
4106 goto put_data_connection
;
4108 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4110 if (revents
& LPOLLIN
) {
4111 enum relay_connection_status status
;
4113 status
= relay_process_data(data_conn
);
4114 /* Connection closed or error. */
4115 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4117 * On socket error flag the session as aborted to force
4118 * the cleanup of its stream otherwise it can leak
4119 * during the lifetime of the relayd.
4121 * This prevents situations in which streams can be
4122 * left opened because an index was received, the
4123 * control connection is closed, and the data
4124 * connection is closed (uncleanly) before the packet's
4127 * Since the data connection encountered an error,
4128 * it is okay to be conservative and close the
4129 * session right now as we can't rely on the protocol
4130 * being respected anymore.
4132 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4133 session_abort(data_conn
->session
);
4135 relay_thread_close_connection(&events
, pollfd
,
4138 * Every goto restart call sets the last seen fd where
4139 * here we don't really care since we gracefully
4140 * continue the loop after the connection is deleted.
4143 /* Keep last seen port. */
4144 last_seen_data_fd
= pollfd
;
4145 connection_put(data_conn
);
4148 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4149 relay_thread_close_connection(&events
, pollfd
,
4152 ERR("Unknown poll events %u for data sock %d",
4155 put_data_connection
:
4156 connection_put(data_conn
);
4158 last_seen_data_fd
= -1;
4161 /* Normal exit, no error */
4166 /* Cleanup remaining connection object. */
4168 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4171 health_code_update();
4173 session_abort(destroy_conn
->session
);
4176 * No need to grab another ref, because we own
4179 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4184 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4186 lttng_ht_destroy(relay_connections_ht
);
4187 relay_connections_ht_error
:
4188 /* Close relay conn pipes */
4189 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4192 DBG("Thread exited with error");
4194 DBG("Worker thread cleanup complete");
4198 ERR("Health error occurred in %s", __func__
);
4200 health_unregister(health_relayd
);
4201 rcu_unregister_thread();
4202 lttng_relay_stop_threads();
4207 * Create the relay command pipe to wake thread_manage_apps.
4208 * Closed in cleanup().
4210 static int create_relay_conn_pipe(void)
4212 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4213 "Relayd connection pipe", relay_conn_pipe
);
4216 static int stdio_open(void *data
, int *fds
)
4218 fds
[0] = fileno(stdout
);
4219 fds
[1] = fileno(stderr
);
4223 static int track_stdio(void)
4226 const char *names
[] = { "stdout", "stderr" };
4228 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4229 names
, 2, stdio_open
, NULL
);
4235 int main(int argc
, char **argv
)
4237 bool thread_is_rcu_registered
= false;
4238 int ret
= 0, retval
= 0;
4240 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4242 /* Parse environment variables */
4243 ret
= parse_env_options();
4251 * Command line arguments overwrite environment.
4254 if (set_options(argc
, argv
)) {
4259 if (set_signal_handler()) {
4264 relayd_config_log();
4266 if (opt_print_version
) {
4272 ret
= fclose(stdin
);
4274 PERROR("Failed to close stdin");
4278 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4280 /* Try to create directory if -o, --output is specified. */
4281 if (opt_output_path
) {
4282 if (*opt_output_path
!= '/') {
4283 ERR("Please specify an absolute path for -o, --output PATH");
4288 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4291 ERR("Unable to create %s", opt_output_path
);
4298 if (opt_daemon
|| opt_background
) {
4299 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4307 if (opt_working_directory
) {
4308 ret
= utils_change_working_directory(opt_working_directory
);
4310 /* All errors are already logged. */
4315 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4316 if (!sessiond_trace_chunk_registry
) {
4317 ERR("Failed to initialize session daemon trace chunk registry");
4323 * The RCU thread registration (and use, through the fd-tracker's
4324 * creation) is done after the daemonization to allow us to not
4325 * deal with liburcu's fork() management as the call RCU needs to
4328 rcu_register_thread();
4329 thread_is_rcu_registered
= true;
4331 output_path
= create_output_path("");
4333 ERR("Failed to get output path");
4337 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4338 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4341 ERR("Failed to format unlinked file directory path");
4345 the_fd_tracker
= fd_tracker_create(
4346 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4347 free(unlinked_file_directory_path
);
4348 if (!the_fd_tracker
) {
4353 ret
= track_stdio();
4359 /* Initialize thread health monitoring */
4360 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4361 if (!health_relayd
) {
4362 PERROR("health_app_create error");
4367 /* Create thread quit pipe */
4368 if (init_thread_quit_pipe()) {
4373 /* Setup the thread apps communication pipe. */
4374 if (create_relay_conn_pipe()) {
4379 /* Init relay command queue. */
4380 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4382 /* Initialize communication library */
4384 lttcomm_inet_init();
4386 /* tables of sessions indexed by session ID */
4387 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4393 /* tables of streams indexed by stream ID */
4394 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4395 if (!relay_streams_ht
) {
4400 /* tables of streams indexed by stream ID */
4401 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4402 if (!viewer_streams_ht
) {
4407 ret
= init_health_quit_pipe();
4413 /* Create thread to manage the client socket */
4414 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4415 thread_manage_health
, (void *) NULL
);
4418 PERROR("pthread_create health");
4423 /* Setup the dispatcher thread */
4424 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4425 relay_thread_dispatcher
, (void *) NULL
);
4428 PERROR("pthread_create dispatcher");
4430 goto exit_dispatcher_thread
;
4433 /* Setup the worker thread */
4434 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4435 relay_thread_worker
, NULL
);
4438 PERROR("pthread_create worker");
4440 goto exit_worker_thread
;
4443 /* Setup the listener thread */
4444 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4445 relay_thread_listener
, (void *) NULL
);
4448 PERROR("pthread_create listener");
4450 goto exit_listener_thread
;
4453 ret
= relayd_live_create(live_uri
);
4455 ERR("Starting live viewer threads");
4461 * This is where we start awaiting program completion (e.g. through
4462 * signal that asks threads to teardown).
4465 ret
= relayd_live_join();
4471 ret
= pthread_join(listener_thread
, &status
);
4474 PERROR("pthread_join listener_thread");
4478 exit_listener_thread
:
4479 ret
= pthread_join(worker_thread
, &status
);
4482 PERROR("pthread_join worker_thread");
4487 ret
= pthread_join(dispatcher_thread
, &status
);
4490 PERROR("pthread_join dispatcher_thread");
4493 exit_dispatcher_thread
:
4495 ret
= pthread_join(health_thread
, &status
);
4498 PERROR("pthread_join health_thread");
4503 * Wait for all pending call_rcu work to complete before tearing
4504 * down data structures. call_rcu worker may be trying to
4505 * perform lookups in those structures.
4510 /* Ensure all prior call_rcu are done. */
4513 if (thread_is_rcu_registered
) {
4514 rcu_unregister_thread();