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
12 #include "backward-compatibility-group-by.hpp"
14 #include "connection.hpp"
15 #include "ctf-trace.hpp"
16 #include "health-relayd.hpp"
19 #include "lttng-relayd.hpp"
20 #include "session.hpp"
21 #include "sessiond-trace-chunks.hpp"
23 #include "tcp_keep_alive.hpp"
24 #include "testpoint.hpp"
25 #include "tracefile-array.hpp"
27 #include "version.hpp"
28 #include "viewer-session.hpp"
29 #include "viewer-stream.hpp"
31 #include <common/align.hpp>
32 #include <common/buffer-view.hpp>
33 #include <common/common.hpp>
34 #include <common/compat/endian.hpp>
35 #include <common/compat/getenv.hpp>
36 #include <common/compat/poll.hpp>
37 #include <common/compat/socket.hpp>
38 #include <common/daemonize.hpp>
39 #include <common/defaults.hpp>
40 #include <common/dynamic-buffer.hpp>
41 #include <common/fd-tracker/fd-tracker.hpp>
42 #include <common/fd-tracker/utils.hpp>
43 #include <common/futex.hpp>
44 #include <common/ini-config/ini-config.hpp>
45 #include <common/path.hpp>
46 #include <common/pthread-lock.hpp>
47 #include <common/sessiond-comm/inet.hpp>
48 #include <common/sessiond-comm/relayd.hpp>
49 #include <common/sessiond-comm/sessiond-comm.hpp>
50 #include <common/string-utils/format.hpp>
51 #include <common/urcu.hpp>
52 #include <common/uri.hpp>
53 #include <common/utils.hpp>
55 #include <lttng/lttng.h>
71 #include <sys/mount.h>
72 #include <sys/resource.h>
73 #include <sys/socket.h>
75 #include <sys/types.h>
78 #include <urcu/futex.h>
79 #include <urcu/rculist.h>
80 #include <urcu/uatomic.h>
82 static const char *help_msg
=
83 #ifdef LTTNG_EMBED_HELP
84 #include <lttng-relayd.8.h>
90 enum relay_connection_status
{
91 RELAY_CONNECTION_STATUS_OK
,
92 /* An error occurred while processing an event on the connection. */
93 RELAY_CONNECTION_STATUS_ERROR
,
94 /* Connection closed/shutdown cleanly. */
95 RELAY_CONNECTION_STATUS_CLOSED
,
98 /* command line options */
99 char *opt_output_path
, *opt_working_directory
;
100 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
101 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
103 /* Argument variables */
104 int lttng_opt_quiet
; /* not static in error.h */
105 int lttng_opt_verbose
; /* not static in error.h */
106 int lttng_opt_mi
; /* not static in error.h */
109 * We need to wait for listener and live listener threads, as well as
110 * health check thread, before being ready to signal readiness.
112 #define NR_LTTNG_RELAY_READY 3
113 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
115 /* Size of receive buffer. */
116 #define RECV_DATA_BUFFER_SIZE 65536
118 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
119 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
121 static struct lttng_uri
*control_uri
;
122 static struct lttng_uri
*data_uri
;
123 static struct lttng_uri
*live_uri
;
125 const char *progname
;
127 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
128 static int tracing_group_name_override
;
130 const char *const config_section_name
= "relayd";
133 * This pipe is used to inform the worker thread that a command is queued and
134 * ready to be processed.
136 static int relay_conn_pipe
[2] = { -1, -1 };
138 /* Shared between threads */
139 static int dispatch_thread_exit
;
141 static pthread_t listener_thread
;
142 static pthread_t dispatcher_thread
;
143 static pthread_t worker_thread
;
144 static pthread_t health_thread
;
147 * last_relay_stream_id_lock protects last_relay_stream_id increment
148 * atomicity on 32-bit architectures.
150 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
151 static uint64_t last_relay_stream_id
;
154 * Relay command queue.
156 * The relay_thread_listener and relay_thread_dispatcher communicate with this
159 static struct relay_conn_queue relay_conn_queue
;
161 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
162 static unsigned int lttng_opt_fd_pool_size
= -1;
164 /* Global relay stream hash table. */
165 struct lttng_ht
*relay_streams_ht
;
167 /* Global relay viewer stream hash table. */
168 struct lttng_ht
*viewer_streams_ht
;
170 /* Global relay sessions hash table. */
171 struct lttng_ht
*sessions_ht
;
173 /* Global viewer sessions hash table. */
174 struct lttng_ht
*viewer_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
[] = {
245 { "config", 1, nullptr, 'f' },
246 { "version", 0, nullptr, 'V' },
254 "group-output-by-session",
260 "group-output-by-host",
265 { "disallow-clear", 0, nullptr, 'x' },
274 static const char *config_ignore_options
[] = { "help", "config", "version" };
276 static void print_version()
278 fprintf(stdout
, "%s\n", VERSION
);
281 static void relayd_config_log()
283 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
284 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
285 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
286 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
287 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
289 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
290 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
295 * Take an option from the getopt output and set it in the right variable to be
298 * Return 0 on success else a negative value.
300 static int set_option(int opt
, const char *arg
, const char *optname
)
306 if (!strcmp(optname
, "fd-pool-size")) {
310 v
= strtoul(arg
, nullptr, 0);
311 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
312 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
317 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s",
322 lttng_opt_fd_pool_size
= (unsigned int) v
;
324 fprintf(stderr
, "unknown option %s", optname
);
326 fprintf(stderr
, " with arg %s\n", arg
);
331 if (lttng_is_setuid_setgid()) {
332 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
333 "-C, --control-port");
335 ret
= uri_parse(arg
, &control_uri
);
337 ERR("Invalid control URI specified");
340 if (control_uri
->port
== 0) {
341 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
346 if (lttng_is_setuid_setgid()) {
347 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
350 ret
= uri_parse(arg
, &data_uri
);
352 ERR("Invalid data URI specified");
355 if (data_uri
->port
== 0) {
356 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
361 if (lttng_is_setuid_setgid()) {
362 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
365 ret
= uri_parse(arg
, &live_uri
);
367 ERR("Invalid live URI specified");
370 if (live_uri
->port
== 0) {
371 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
382 if (lttng_is_setuid_setgid()) {
383 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
386 tracing_group_name
= strdup(arg
);
387 if (tracing_group_name
== nullptr) {
392 tracing_group_name_override
= 1;
396 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
398 ERR("Cannot show --help for `lttng-relayd`");
403 opt_print_version
= 1;
406 if (lttng_is_setuid_setgid()) {
407 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
410 ret
= asprintf(&opt_output_path
, "%s", arg
);
413 PERROR("asprintf opt_output_path");
419 if (lttng_is_setuid_setgid()) {
420 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
421 "-w, --working-directory");
423 ret
= asprintf(&opt_working_directory
, "%s", arg
);
426 PERROR("asprintf opt_working_directory");
433 /* Verbose level can increase using multiple -v */
435 lttng_opt_verbose
= config_parse_value(arg
);
437 /* Only 3 level of verbosity (-vvv). */
438 if (lttng_opt_verbose
< 3) {
439 lttng_opt_verbose
+= 1;
444 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
445 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
448 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
451 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
452 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
455 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
462 /* Unknown option or other error.
463 * Error is printed by getopt, just return */
476 * config_entry_handler_cb used to handle options read from a config file.
477 * See config_entry_handler_cb comment in common/config/session-config.h for the
478 * return value conventions.
480 static int config_entry_handler(const struct config_entry
*entry
,
481 void *unused
__attribute__((unused
)))
485 if (!entry
|| !entry
->name
|| !entry
->value
) {
490 /* Check if the option is to be ignored */
491 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
492 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
497 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
498 /* Ignore if entry name is not fully matched. */
499 if (strcmp(entry
->name
, long_options
[i
].name
) != 0) {
504 * If the option takes no argument on the command line,
505 * we have to check if the value is "true". We support
506 * non-zero numeric values, true, on and yes.
508 if (!long_options
[i
].has_arg
) {
509 ret
= config_parse_value(entry
->value
);
512 WARN("Invalid configuration value \"%s\" for option %s",
516 /* False, skip boolean config option. */
521 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
525 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
531 static int parse_env_options()
534 char *value
= nullptr;
536 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
538 opt_working_directory
= strdup(value
);
539 if (!opt_working_directory
) {
540 ERR("Failed to allocate working directory string (\"%s\")", value
);
547 static int set_fd_pool_size()
550 struct rlimit rlimit
;
552 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
554 PERROR("Failed to get file descriptor limit");
559 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
560 (uint64_t) rlimit
.rlim_cur
,
561 (uint64_t) rlimit
.rlim_max
);
562 if (lttng_opt_fd_pool_size
== -1) {
563 /* Use default value (soft limit - reserve). */
564 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
565 ERR("The process' file number limit is too low (%" PRIu64
566 "). The process' file number limit must be set to at least %i.",
567 (uint64_t) rlimit
.rlim_cur
,
568 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
572 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
576 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
577 ERR("File descriptor pool size must be set to at least %d",
578 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
583 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
584 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
586 lttng_opt_fd_pool_size
,
587 (uint64_t) rlimit
.rlim_cur
);
592 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
593 lttng_opt_fd_pool_size
,
594 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
595 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
600 static int set_options(int argc
, char **argv
)
602 int c
, ret
= 0, option_index
= 0, retval
= 0;
603 int orig_optopt
= optopt
, orig_optind
= optind
;
604 char *default_address
, *optstring
;
605 char *config_path
= nullptr;
607 optstring
= utils_generate_optstring(long_options
,
608 sizeof(long_options
) / sizeof(struct option
));
614 /* Check for the --config option */
616 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
)) != -1) {
620 } else if (c
!= 'f') {
624 if (lttng_is_setuid_setgid()) {
625 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
629 config_path
= utils_expand_path(optarg
);
631 ERR("Failed to resolve path: %s", optarg
);
636 ret
= config_get_section_entries(
637 config_path
, config_section_name
, config_entry_handler
, nullptr);
640 ERR("Invalid configuration option at line %i", ret
);
646 /* Reset getopt's global state */
647 optopt
= orig_optopt
;
648 optind
= orig_optind
;
650 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
655 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
662 /* assign default values */
663 if (control_uri
== nullptr) {
664 ret
= asprintf(&default_address
,
665 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
666 DEFAULT_NETWORK_CONTROL_PORT
);
668 PERROR("asprintf default data address");
673 ret
= uri_parse(default_address
, &control_uri
);
674 free(default_address
);
676 ERR("Invalid control URI specified");
681 if (data_uri
== nullptr) {
682 ret
= asprintf(&default_address
,
683 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
684 DEFAULT_NETWORK_DATA_PORT
);
686 PERROR("asprintf default data address");
691 ret
= uri_parse(default_address
, &data_uri
);
692 free(default_address
);
694 ERR("Invalid data URI specified");
699 if (live_uri
== nullptr) {
700 ret
= asprintf(&default_address
,
701 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
702 DEFAULT_NETWORK_VIEWER_PORT
);
704 PERROR("asprintf default viewer control address");
709 ret
= uri_parse(default_address
, &live_uri
);
710 free(default_address
);
712 ERR("Invalid viewer control URI specified");
717 ret
= set_fd_pool_size();
723 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
724 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
726 if (opt_allow_clear
) {
727 /* Check if env variable exists. */
728 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
730 ret
= config_parse_value(value
);
732 ERR("Invalid value for %s specified",
733 DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
737 opt_allow_clear
= !ret
;
747 static void print_global_objects()
749 print_viewer_streams();
750 print_relay_streams();
754 static int noop_close(void *data
__attribute__((unused
)), int *fds
__attribute__((unused
)))
759 static void untrack_stdio()
761 int fds
[] = { fileno(stdout
), fileno(stderr
) };
764 * noop_close is used since we don't really want to close
765 * the stdio output fds; we merely want to stop tracking them.
767 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
, fds
, 2, noop_close
, nullptr);
773 static void relayd_cleanup()
775 print_global_objects();
779 if (viewer_streams_ht
)
780 lttng_ht_destroy(viewer_streams_ht
);
781 if (viewer_sessions_ht
) {
782 lttng_ht_destroy(viewer_sessions_ht
);
784 if (relay_streams_ht
)
785 lttng_ht_destroy(relay_streams_ht
);
787 lttng_ht_destroy(sessions_ht
);
788 free(opt_output_path
);
789 free(opt_working_directory
);
792 health_app_destroy(health_relayd
);
794 /* Close thread quit pipes */
795 if (health_quit_pipe
[0] != -1) {
796 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
798 relayd_close_thread_quit_pipe();
799 if (sessiond_trace_chunk_registry
) {
800 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
802 if (the_fd_tracker
) {
805 * fd_tracker_destroy() will log the contents of the fd-tracker
806 * if a leak is detected.
808 fd_tracker_destroy(the_fd_tracker
);
811 uri_free(control_uri
);
813 /* Live URI is freed in the live thread. */
815 if (tracing_group_name_override
) {
816 free((void *) tracing_group_name
);
820 static int notify_health_quit_pipe(int *pipe
)
824 ret
= lttng_write(pipe
[1], "4", 1);
826 PERROR("write relay health quit");
835 * Stop all relayd and relayd-live threads.
837 int lttng_relay_stop_threads()
841 /* Stopping all threads */
842 DBG("Terminating all threads");
843 if (relayd_notify_thread_quit_pipe()) {
844 ERR("write error on thread quit pipe");
848 if (notify_health_quit_pipe(health_quit_pipe
)) {
849 ERR("write error on health quit pipe");
852 /* Dispatch thread */
853 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
854 futex_nto1_wake(&relay_conn_queue
.futex
);
856 if (relayd_live_stop()) {
857 ERR("Error stopping live threads");
864 * Signal handler for the daemon
866 * Simply stop all worker threads, leaving main() return gracefully after
867 * joining all threads and calling cleanup().
869 static void sighandler(int sig
)
873 DBG("SIGINT caught");
874 if (lttng_relay_stop_threads()) {
875 ERR("Error stopping threads");
879 DBG("SIGTERM caught");
880 if (lttng_relay_stop_threads()) {
881 ERR("Error stopping threads");
885 CMM_STORE_SHARED(recv_child_signal
, 1);
893 * Setup signal handler for :
894 * SIGINT, SIGTERM, SIGPIPE
896 static int set_signal_handler()
902 if ((ret
= sigemptyset(&sigset
)) < 0) {
903 PERROR("sigemptyset");
910 sa
.sa_handler
= sighandler
;
911 if ((ret
= sigaction(SIGTERM
, &sa
, nullptr)) < 0) {
916 if ((ret
= sigaction(SIGINT
, &sa
, nullptr)) < 0) {
921 if ((ret
= sigaction(SIGUSR1
, &sa
, nullptr)) < 0) {
926 sa
.sa_handler
= SIG_IGN
;
927 if ((ret
= sigaction(SIGPIPE
, &sa
, nullptr)) < 0) {
932 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
937 void lttng_relay_notify_ready()
939 /* Notify the parent of the fork() process that we are ready. */
940 if (opt_daemon
|| opt_background
) {
941 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
942 kill(child_ppid
, SIGUSR1
);
948 * Init health quit pipe.
950 * Return -1 on error or 0 if all pipes are created.
952 static int init_health_quit_pipe()
954 return fd_tracker_util_pipe_open_cloexec(
955 the_fd_tracker
, "Health quit pipe", health_quit_pipe
);
958 static int create_sock(void *data
, int *out_fd
)
961 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
963 ret
= lttcomm_create_sock(sock
);
973 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
975 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
977 return sock
->ops
->close(sock
);
980 static int accept_sock(void *data
, int *out_fd
)
983 /* Socks is an array of in_sock, out_sock. */
984 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
985 struct lttcomm_sock
*in_sock
= socks
[0];
987 socks
[1] = in_sock
->ops
->accept(in_sock
);
992 *out_fd
= socks
[1]->fd
;
998 * Create and init socket from uri.
1000 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
, const char *name
)
1003 struct lttcomm_sock
*sock
= nullptr;
1004 char uri_str
[PATH_MAX
];
1005 char *formated_name
= nullptr;
1007 sock
= lttcomm_alloc_sock_from_uri(uri
);
1008 if (sock
== nullptr) {
1009 ERR("Allocating socket");
1014 * Don't fail to create the socket if the name can't be built as it is
1015 * only used for debugging purposes.
1017 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1018 uri_str
[sizeof(uri_str
) - 1] = '\0';
1020 ret
= asprintf(&formated_name
, "%s socket @ %s", name
, uri_str
);
1022 formated_name
= nullptr;
1026 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
,
1028 (const char **) (formated_name
? &formated_name
:
1034 PERROR("Failed to open \"%s\" relay socket", formated_name
?: "Unknown");
1037 DBG("Listening on %s socket %d", name
, sock
->fd
);
1039 ret
= sock
->ops
->bind(sock
);
1041 PERROR("Failed to bind socket");
1045 ret
= sock
->ops
->listen(sock
, -1);
1050 free(formated_name
);
1055 lttcomm_destroy_sock(sock
);
1057 free(formated_name
);
1061 static struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1065 struct lttcomm_sock
*socks
[2] = { listening_sock
, nullptr };
1066 struct lttcomm_sock
*new_sock
= nullptr;
1068 ret
= fd_tracker_open_unsuspendable_fd(
1069 the_fd_tracker
, &out_fd
, (const char **) &name
, 1, accept_sock
, &socks
);
1073 new_sock
= socks
[1];
1074 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1080 * This thread manages the listening for new connections on the network
1082 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1084 int i
, ret
, err
= -1;
1086 struct lttng_poll_event events
;
1087 struct lttcomm_sock
*control_sock
, *data_sock
;
1089 DBG("[thread] Relay listener started");
1091 rcu_register_thread();
1092 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1094 health_code_update();
1096 control_sock
= relay_socket_create(control_uri
, "Control listener");
1097 if (!control_sock
) {
1098 goto error_sock_control
;
1101 data_sock
= relay_socket_create(data_uri
, "Data listener");
1103 goto error_sock_relay
;
1107 * Pass 3 as size here for the thread quit pipe, control and
1110 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1112 goto error_create_poll
;
1115 /* Add the control socket */
1116 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1118 goto error_poll_add
;
1121 /* Add the data socket */
1122 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1124 goto error_poll_add
;
1127 lttng_relay_notify_ready();
1129 if (testpoint(relayd_thread_listener
)) {
1130 goto error_testpoint
;
1134 health_code_update();
1136 DBG("Listener accepting connections");
1139 health_poll_entry();
1140 ret
= lttng_poll_wait(&events
, -1);
1144 * Restart interrupted system call.
1146 if (errno
== EINTR
) {
1154 DBG("Relay new connection received");
1155 for (i
= 0; i
< nb_fd
; i
++) {
1156 /* Fetch once the poll data */
1157 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
1158 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1160 health_code_update();
1162 /* Activity on thread quit pipe, exiting. */
1163 if (relayd_is_thread_quit_pipe(pollfd
)) {
1164 DBG("Activity on thread quit pipe");
1169 if (revents
& LPOLLIN
) {
1171 * A new connection is requested, therefore a
1172 * sessiond/consumerd connection is allocated in
1173 * this thread, enqueued to a global queue and
1174 * dequeued (and freed) in the worker thread.
1177 struct relay_connection
*new_conn
;
1178 struct lttcomm_sock
*newsock
= nullptr;
1179 enum connection_type type
;
1181 if (pollfd
== data_sock
->fd
) {
1183 newsock
= accept_relayd_sock(data_sock
,
1184 "Data socket to relayd");
1186 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1187 type
= RELAY_CONTROL
;
1188 newsock
= accept_relayd_sock(control_sock
,
1189 "Control socket to relayd");
1192 PERROR("accepting sock");
1197 newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1199 PERROR("setsockopt inet");
1200 lttcomm_destroy_sock(newsock
);
1204 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1206 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1208 lttcomm_destroy_sock(newsock
);
1212 new_conn
= connection_create(newsock
, type
);
1214 lttcomm_destroy_sock(newsock
);
1218 /* Enqueue request for the dispatcher thread. */
1219 cds_wfcq_head_ptr_t head
;
1220 head
.h
= &relay_conn_queue
.head
;
1221 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
, &new_conn
->qnode
);
1224 * Wake the dispatch queue futex.
1225 * Implicit memory barrier with the
1226 * exchange in cds_wfcq_enqueue.
1228 futex_nto1_wake(&relay_conn_queue
.futex
);
1229 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1230 ERR("socket poll error");
1233 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1243 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1245 if (data_sock
->fd
>= 0) {
1246 int data_sock_fd
= data_sock
->fd
;
1248 ret
= fd_tracker_close_unsuspendable_fd(
1249 the_fd_tracker
, &data_sock_fd
, 1, close_sock
, data_sock
);
1251 PERROR("Failed to close the data listener socket file descriptor");
1255 lttcomm_destroy_sock(data_sock
);
1257 if (control_sock
->fd
>= 0) {
1258 int control_sock_fd
= control_sock
->fd
;
1260 ret
= fd_tracker_close_unsuspendable_fd(
1261 the_fd_tracker
, &control_sock_fd
, 1, close_sock
, control_sock
);
1263 PERROR("Failed to close the control listener socket file descriptor");
1265 control_sock
->fd
= -1;
1267 lttcomm_destroy_sock(control_sock
);
1271 ERR("Health error occurred in %s", __func__
);
1273 health_unregister(health_relayd
);
1274 rcu_unregister_thread();
1275 DBG("Relay listener thread cleanup complete");
1276 lttng_relay_stop_threads();
1281 * This thread manages the dispatching of the requests to worker threads
1283 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1287 struct cds_wfcq_node
*node
;
1288 struct relay_connection
*new_conn
= nullptr;
1290 DBG("[thread] Relay dispatcher started");
1292 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1294 if (testpoint(relayd_thread_dispatcher
)) {
1295 goto error_testpoint
;
1298 health_code_update();
1301 health_code_update();
1303 /* Atomically prepare the queue futex */
1304 futex_nto1_prepare(&relay_conn_queue
.futex
);
1306 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1311 health_code_update();
1313 /* Dequeue commands */
1314 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1315 &relay_conn_queue
.tail
);
1316 if (node
== nullptr) {
1317 DBG("Woken up but nothing in the relay command queue");
1318 /* Continue thread execution */
1321 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1323 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1326 * Inform worker thread of the new request. This
1327 * call is blocking so we can be assured that
1328 * the data will be read at some point in time
1329 * or wait to the end of the world :)
1332 relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
)); /* NOLINT
1339 PERROR("write connection pipe");
1340 connection_put(new_conn
);
1343 } while (node
!= nullptr);
1345 /* Futex wait on queue. Blocking call on futex() */
1346 health_poll_entry();
1347 futex_nto1_wait(&relay_conn_queue
.futex
);
1351 /* Normal exit, no error */
1358 ERR("Health error occurred in %s", __func__
);
1360 health_unregister(health_relayd
);
1361 DBG("Dispatch thread dying");
1362 lttng_relay_stop_threads();
1366 static bool session_streams_have_index(const struct relay_session
*session
)
1368 return session
->minor
>= 4 && !session
->snapshot
;
1372 * Handle the RELAYD_CREATE_SESSION command.
1374 * On success, send back the session id or else return a negative value.
1376 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1377 struct relay_connection
*conn
,
1378 const struct lttng_buffer_view
*payload
)
1382 struct relay_session
*session
= nullptr;
1383 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1384 char session_name
[LTTNG_NAME_MAX
] = {};
1385 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1386 uint32_t live_timer
= 0;
1387 bool snapshot
= false;
1388 bool session_name_contains_creation_timestamp
= false;
1389 /* Left nil for peers < 2.11. */
1390 char base_path
[LTTNG_PATH_MAX
] = {};
1391 lttng_uuid sessiond_uuid
= {};
1392 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1393 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1394 LTTNG_OPTIONAL(time_t) creation_time
= {};
1395 struct lttng_dynamic_buffer reply_payload
;
1397 lttng_dynamic_buffer_init(&reply_payload
);
1399 if (conn
->minor
< 4) {
1400 /* From 2.1 to 2.3 */
1402 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1403 /* From 2.4 to 2.10 */
1404 ret
= cmd_create_session_2_4(
1405 payload
, session_name
, hostname
, &live_timer
, &snapshot
);
1407 bool has_current_chunk
;
1408 uint64_t current_chunk_id_value
;
1409 time_t creation_time_value
;
1410 uint64_t id_sessiond_value
;
1412 /* From 2.11 to ... */
1413 ret
= cmd_create_session_2_11(payload
,
1422 ¤t_chunk_id_value
,
1423 &creation_time_value
,
1424 &session_name_contains_creation_timestamp
);
1425 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1426 /* The nil UUID is reserved for pre-2.11 clients. */
1427 ERR("Illegal nil UUID announced by peer in create session command");
1431 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1432 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1433 if (has_current_chunk
) {
1434 LTTNG_OPTIONAL_SET(¤t_chunk_id
, current_chunk_id_value
);
1442 session
= session_create(session_name
,
1448 id_sessiond
.is_set
? &id_sessiond
.value
: nullptr,
1449 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: nullptr,
1450 creation_time
.is_set
? &creation_time
.value
: nullptr,
1453 session_name_contains_creation_timestamp
);
1458 LTTNG_ASSERT(!conn
->session
);
1459 conn
->session
= session
;
1460 DBG("Created session %" PRIu64
, session
->id
);
1462 reply
.generic
.session_id
= htobe64(session
->id
);
1466 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1468 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1471 if (conn
->minor
< 11) {
1472 /* From 2.1 to 2.10 */
1473 ret
= lttng_dynamic_buffer_append(
1474 &reply_payload
, &reply
.generic
, sizeof(reply
.generic
));
1476 ERR("Failed to append \"create session\" command reply header to payload buffer");
1481 const uint32_t output_path_length
= session
? strlen(session
->output_path
) + 1 : 0;
1483 reply
.output_path_length
= htobe32(output_path_length
);
1484 ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
1486 ERR("Failed to append \"create session\" command reply header to payload buffer");
1490 if (output_path_length
) {
1491 ret
= lttng_dynamic_buffer_append(
1492 &reply_payload
, session
->output_path
, output_path_length
);
1494 ERR("Failed to append \"create session\" command reply path to payload buffer");
1500 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
1501 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1502 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1508 if (ret
< 0 && session
) {
1509 session_put(session
);
1511 lttng_dynamic_buffer_reset(&reply_payload
);
1516 * When we have received all the streams and the metadata for a channel,
1517 * we make them visible to the viewer threads.
1519 static void publish_connection_local_streams(struct relay_connection
*conn
)
1521 struct relay_session
*session
= conn
->session
;
1522 unsigned int created
= 0;
1523 bool closed
= false;
1525 LTTNG_ASSERT(viewer_sessions_ht
);
1528 * We publish all streams belonging to a session atomically wrt
1531 const lttng::pthread::lock_guard
session_lock(session
->lock
);
1534 lttng::urcu::rcu_list_iteration_adapter
<relay_stream
, &relay_stream::recv_node
>(
1535 session
->recv_list
)) {
1536 stream_publish(stream
);
1540 * Inform the viewer that there are new streams in the session.
1542 if (!session
->viewer_attached
) {
1547 * Create viewer_streams for all the newly published streams for this relay session.
1548 * This searches through all known viewer sessions and finds those that are
1549 * attached to this connection's relay session. This is done so that the newer
1550 * viewer streams will hold a reference on any relay streams that already exist,
1551 * but may be unpublished between now and the next GET_NEW_STREAMS from the
1552 * attached live viewer.
1554 for (auto *viewer_session
:
1555 lttng::urcu::lfht_iteration_adapter
<relay_viewer_session
,
1556 decltype(relay_viewer_session::viewer_session_n
),
1557 &relay_viewer_session::viewer_session_n
>(
1558 *viewer_sessions_ht
->ht
)) {
1559 for (auto *session_iter
:
1560 lttng::urcu::rcu_list_iteration_adapter
<relay_session
,
1561 &relay_session::viewer_session_node
>(
1562 viewer_session
->session_list
)) {
1563 if (session
!= session_iter
) {
1566 const int ret
= make_viewer_streams(session
,
1568 LTTNG_VIEWER_SEEK_BEGINNING
,
1574 DBG("Created %d new viewer streams during publication of relay streams for relay session %" PRIu64
,
1577 } else if (ret
< 0) {
1579 * Warning, since the creation of the
1580 * streams will be retried when the viewer
1581 * next sends the GET_NEW_STREAMS again.
1583 WARN("Failed to create new viewer streams during publication of relay streams for relay session %" PRIu64
1584 ", ret=%d, created=%d, closed=%d",
1593 uatomic_set(&session
->new_streams
, 1);
1594 pthread_mutex_unlock(&session
->lock
);
1597 static int conform_channel_path(char *channel_path
)
1601 if (strstr("../", channel_path
)) {
1602 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1608 if (*channel_path
== '/') {
1609 const size_t len
= strlen(channel_path
);
1612 * Channel paths from peers prior to 2.11 are expressed as an
1613 * absolute path that is, in reality, relative to the relay
1614 * daemon's output directory. Remove the leading slash so it
1615 * is correctly interpreted as a relative path later on.
1617 * len (and not len - 1) is used to copy the trailing NULL.
1619 bcopy(channel_path
+ 1, channel_path
, len
);
1626 * relay_add_stream: allocate a new stream for a session
1628 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1629 struct relay_connection
*conn
,
1630 const struct lttng_buffer_view
*payload
)
1634 struct relay_session
*session
= conn
->session
;
1635 struct relay_stream
*stream
= nullptr;
1636 struct lttcomm_relayd_status_stream reply
;
1637 struct ctf_trace
*trace
= nullptr;
1638 uint64_t stream_handle
= -1ULL;
1639 char *path_name
= nullptr, *channel_name
= nullptr;
1640 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1641 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1643 if (!session
|| !conn
->version_check_done
) {
1644 ERR("Trying to add a stream before version check");
1646 goto end_no_session
;
1649 if (session
->minor
== 1) {
1651 ret
= cmd_recv_stream_2_1(payload
, &path_name
, &channel_name
);
1652 } else if (session
->minor
> 1 && session
->minor
< 11) {
1653 /* From 2.2 to 2.10 */
1654 ret
= cmd_recv_stream_2_2(
1655 payload
, &path_name
, &channel_name
, &tracefile_size
, &tracefile_count
);
1657 /* From 2.11 to ... */
1658 ret
= cmd_recv_stream_2_11(payload
,
1663 &stream_chunk_id
.value
);
1664 stream_chunk_id
.is_set
= true;
1671 if (conform_channel_path(path_name
)) {
1676 * Backward compatibility for --group-output-by-session.
1677 * Prior to lttng 2.11, the complete path is passed by the stream.
1678 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1679 * >=2.11 the chunk is responsible for the output path. When dealing
1680 * with producer < 2.11 the chunk output_path is the root output path
1681 * and the stream carries the complete path (path_name).
1682 * To support --group-output-by-session with older producer (<2.11), we
1683 * need to craft the path based on the stream path.
1685 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1686 if (conn
->minor
< 4) {
1688 * From 2.1 to 2.3, the session_name is not passed on
1689 * the RELAYD_CREATE_SESSION command. The session name
1690 * is necessary to detect the presence of a base_path
1691 * inside the stream path. Without it we cannot perform
1692 * a valid group-output-by-session transformation.
1694 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1695 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1698 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1699 char *group_by_session_path_name
;
1701 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1703 group_by_session_path_name
= backward_compat_group_by_session(
1704 path_name
, session
->session_name
, session
->creation_time
.value
);
1705 if (!group_by_session_path_name
) {
1706 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1711 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1713 group_by_session_path_name
);
1716 path_name
= group_by_session_path_name
;
1720 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1725 /* This stream here has one reference on the trace. */
1726 pthread_mutex_lock(&last_relay_stream_id_lock
);
1727 stream_handle
= ++last_relay_stream_id
;
1728 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1730 /* We pass ownership of path_name and channel_name. */
1731 stream
= stream_create(
1732 trace
, stream_handle
, path_name
, channel_name
, tracefile_size
, tracefile_count
);
1733 path_name
= nullptr;
1734 channel_name
= nullptr;
1737 * Streams are the owners of their trace. Reference to trace is
1738 * kept within stream_create().
1740 ctf_trace_put(trace
);
1743 memset(&reply
, 0, sizeof(reply
));
1744 reply
.handle
= htobe64(stream_handle
);
1746 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1748 reply
.ret_code
= htobe32(LTTNG_OK
);
1751 send_ret
= conn
->sock
->ops
->sendmsg(
1752 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_status_stream
), 0);
1753 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1754 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret
);
1765 * relay_close_stream: close a specific stream
1767 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1768 struct relay_connection
*conn
,
1769 const struct lttng_buffer_view
*payload
)
1773 struct relay_session
*session
= conn
->session
;
1774 struct lttcomm_relayd_close_stream stream_info
;
1775 struct lttcomm_relayd_generic_reply reply
;
1776 struct relay_stream
*stream
;
1778 DBG("Close stream received");
1780 if (!session
|| !conn
->version_check_done
) {
1781 ERR("Trying to close a stream before version check");
1783 goto end_no_session
;
1786 if (payload
->size
< sizeof(stream_info
)) {
1787 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1788 sizeof(stream_info
),
1791 goto end_no_session
;
1793 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1794 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1795 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1797 stream
= stream_get_by_id(stream_info
.stream_id
);
1804 * Set last_net_seq_num before the close flag. Required by data
1807 pthread_mutex_lock(&stream
->lock
);
1808 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1809 pthread_mutex_unlock(&stream
->lock
);
1812 * This is one of the conditions which may trigger a stream close
1813 * with the others being:
1814 * 1) A close command is received for a stream
1815 * 2) The control connection owning the stream is closed
1816 * 3) We have received all of the stream's data _after_ a close
1819 try_stream_close(stream
);
1824 memset(&reply
, 0, sizeof(reply
));
1826 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1828 reply
.ret_code
= htobe32(LTTNG_OK
);
1830 send_ret
= conn
->sock
->ops
->sendmsg(
1831 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1832 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1833 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret
);
1842 * relay_reset_metadata: reset a metadata stream
1844 static int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1845 struct relay_connection
*conn
,
1846 const struct lttng_buffer_view
*payload
)
1850 struct relay_session
*session
= conn
->session
;
1851 struct lttcomm_relayd_reset_metadata stream_info
;
1852 struct lttcomm_relayd_generic_reply reply
;
1853 struct relay_stream
*stream
;
1855 DBG("Reset metadata received");
1857 if (!session
|| !conn
->version_check_done
) {
1858 ERR("Trying to reset a metadata stream before version check");
1860 goto end_no_session
;
1863 if (payload
->size
< sizeof(stream_info
)) {
1864 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1865 sizeof(stream_info
),
1868 goto end_no_session
;
1870 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1871 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1872 stream_info
.version
= be64toh(stream_info
.version
);
1874 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1876 /* Unsupported for live sessions for now. */
1877 if (session
->live_timer
!= 0) {
1882 stream
= stream_get_by_id(stream_info
.stream_id
);
1887 pthread_mutex_lock(&stream
->lock
);
1888 if (!stream
->is_metadata
) {
1893 ret
= stream_reset_file(stream
);
1895 ERR("Failed to reset metadata stream %" PRIu64
": stream_path = %s, channel = %s",
1896 stream
->stream_handle
,
1898 stream
->channel_name
);
1902 pthread_mutex_unlock(&stream
->lock
);
1906 memset(&reply
, 0, sizeof(reply
));
1908 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1910 reply
.ret_code
= htobe32(LTTNG_OK
);
1912 send_ret
= conn
->sock
->ops
->sendmsg(
1913 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1914 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1915 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret
);
1924 * relay_unknown_command: send -1 if received unknown command
1926 static void relay_unknown_command(struct relay_connection
*conn
)
1928 struct lttcomm_relayd_generic_reply reply
;
1931 memset(&reply
, 0, sizeof(reply
));
1932 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1933 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1934 if (send_ret
< sizeof(reply
)) {
1935 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1940 * relay_start: send an acknowledgment to the client to tell if we are
1941 * ready to receive data. We are ready if a session is established.
1943 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1944 struct relay_connection
*conn
,
1945 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1949 struct lttcomm_relayd_generic_reply reply
;
1950 struct relay_session
*session
= conn
->session
;
1953 DBG("Trying to start the streaming without a session established");
1954 ret
= htobe32(LTTNG_ERR_UNK
);
1957 memset(&reply
, 0, sizeof(reply
));
1958 reply
.ret_code
= htobe32(LTTNG_OK
);
1959 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1960 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1961 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret
);
1969 * relay_recv_metadata: receive the metadata for the session.
1971 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1972 struct relay_connection
*conn
,
1973 const struct lttng_buffer_view
*payload
)
1976 struct relay_session
*session
= conn
->session
;
1977 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1978 struct relay_stream
*metadata_stream
;
1979 uint64_t metadata_payload_size
;
1980 struct lttng_buffer_view packet_view
;
1983 ERR("Metadata sent before version check");
1988 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1989 ERR("Incorrect data size");
1993 metadata_payload_size
=
1994 recv_hdr
->data_size
- sizeof(struct lttcomm_relayd_metadata_payload
);
1996 memcpy(&metadata_payload_header
, payload
->data
, sizeof(metadata_payload_header
));
1997 metadata_payload_header
.stream_id
= be64toh(metadata_payload_header
.stream_id
);
1998 metadata_payload_header
.padding_size
= be32toh(metadata_payload_header
.padding_size
);
2000 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
2001 if (!metadata_stream
) {
2006 packet_view
= lttng_buffer_view_from_view(
2007 payload
, sizeof(metadata_payload_header
), metadata_payload_size
);
2008 if (!lttng_buffer_view_is_valid(&packet_view
)) {
2009 ERR("Invalid metadata packet length announced by header");
2014 pthread_mutex_lock(&metadata_stream
->lock
);
2015 ret
= stream_write(metadata_stream
, &packet_view
, metadata_payload_header
.padding_size
);
2016 pthread_mutex_unlock(&metadata_stream
->lock
);
2022 stream_put(metadata_stream
);
2028 * relay_send_version: send relayd version number
2030 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2031 struct relay_connection
*conn
,
2032 const struct lttng_buffer_view
*payload
)
2036 struct lttcomm_relayd_version reply
, msg
;
2037 bool compatible
= true;
2039 conn
->version_check_done
= true;
2041 /* Get version from the other side. */
2042 if (payload
->size
< sizeof(msg
)) {
2043 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2050 memcpy(&msg
, payload
->data
, sizeof(msg
));
2051 msg
.major
= be32toh(msg
.major
);
2052 msg
.minor
= be32toh(msg
.minor
);
2054 memset(&reply
, 0, sizeof(reply
));
2055 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2056 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2058 /* Major versions must be the same */
2059 if (reply
.major
!= msg
.major
) {
2060 DBG("Incompatible major versions (%u vs %u), deleting session",
2066 conn
->major
= reply
.major
;
2067 /* We adapt to the lowest compatible version */
2068 if (reply
.minor
<= msg
.minor
) {
2069 conn
->minor
= reply
.minor
;
2071 conn
->minor
= msg
.minor
;
2074 reply
.major
= htobe32(reply
.major
);
2075 reply
.minor
= htobe32(reply
.minor
);
2076 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2077 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2078 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret
);
2090 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
2097 * Check for data pending for a given stream id from the session daemon.
2099 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2100 struct relay_connection
*conn
,
2101 const struct lttng_buffer_view
*payload
)
2103 struct relay_session
*session
= conn
->session
;
2104 struct lttcomm_relayd_data_pending msg
;
2105 struct lttcomm_relayd_generic_reply reply
;
2106 struct relay_stream
*stream
;
2109 uint64_t stream_seq
;
2111 DBG("Data pending command received");
2113 if (!session
|| !conn
->version_check_done
) {
2114 ERR("Trying to check for data before version check");
2116 goto end_no_session
;
2119 if (payload
->size
< sizeof(msg
)) {
2120 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2124 goto end_no_session
;
2126 memcpy(&msg
, payload
->data
, sizeof(msg
));
2127 msg
.stream_id
= be64toh(msg
.stream_id
);
2128 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2130 stream
= stream_get_by_id(msg
.stream_id
);
2131 if (stream
== nullptr) {
2136 pthread_mutex_lock(&stream
->lock
);
2138 if (session_streams_have_index(session
)) {
2140 * Ensure that both the index and stream data have been
2141 * flushed up to the requested point.
2143 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2145 stream_seq
= stream
->prev_data_seq
;
2147 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2148 ", prev_index_seq %" PRIu64
", and last_seq %" PRIu64
,
2150 stream
->prev_data_seq
,
2151 stream
->prev_index_seq
,
2152 msg
.last_net_seq_num
);
2154 /* Avoid wrapping issue */
2155 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2156 /* Data has in fact been written and is NOT pending */
2159 /* Data still being streamed thus pending */
2163 stream
->data_pending_check_done
= true;
2164 pthread_mutex_unlock(&stream
->lock
);
2169 memset(&reply
, 0, sizeof(reply
));
2170 reply
.ret_code
= htobe32(ret
);
2171 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2172 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2173 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret
);
2182 * Wait for the control socket to reach a quiescent state.
2184 * Note that for now, when receiving this command from the session
2185 * daemon, this means that every subsequent commands or data received on
2186 * the control socket has been handled. So, this is why we simply return
2189 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
2190 __attribute__((unused
)),
2191 struct relay_connection
*conn
,
2192 const struct lttng_buffer_view
*payload
)
2196 struct relay_stream
*stream
;
2197 struct lttcomm_relayd_quiescent_control msg
;
2198 struct lttcomm_relayd_generic_reply reply
;
2200 DBG("Checking quiescent state on control socket");
2202 if (!conn
->session
|| !conn
->version_check_done
) {
2203 ERR("Trying to check for data before version check");
2205 goto end_no_session
;
2208 if (payload
->size
< sizeof(msg
)) {
2209 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2213 goto end_no_session
;
2215 memcpy(&msg
, payload
->data
, sizeof(msg
));
2216 msg
.stream_id
= be64toh(msg
.stream_id
);
2218 stream
= stream_get_by_id(msg
.stream_id
);
2222 pthread_mutex_lock(&stream
->lock
);
2223 stream
->data_pending_check_done
= true;
2224 pthread_mutex_unlock(&stream
->lock
);
2226 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2229 memset(&reply
, 0, sizeof(reply
));
2230 reply
.ret_code
= htobe32(LTTNG_OK
);
2231 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2232 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2233 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret
);
2244 * Initialize a data pending command. This means that a consumer is about
2245 * to ask for data pending for each stream it holds. Simply iterate over
2246 * all streams of a session and set the data_pending_check_done flag.
2248 * This command returns to the client a LTTNG_OK code.
2250 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2251 struct relay_connection
*conn
,
2252 const struct lttng_buffer_view
*payload
)
2256 struct lttcomm_relayd_begin_data_pending msg
;
2257 struct lttcomm_relayd_generic_reply reply
;
2259 LTTNG_ASSERT(recv_hdr
);
2262 DBG("Init streams for data pending");
2264 if (!conn
->session
|| !conn
->version_check_done
) {
2265 ERR("Trying to check for data before version check");
2267 goto end_no_session
;
2270 if (payload
->size
< sizeof(msg
)) {
2271 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2275 goto end_no_session
;
2277 memcpy(&msg
, payload
->data
, sizeof(msg
));
2278 msg
.session_id
= be64toh(msg
.session_id
);
2281 * Iterate over all streams to set the begin data pending flag.
2282 * For now, the streams are indexed by stream handle so we have
2283 * to iterate over all streams to find the one associated with
2284 * the right session_id.
2287 lttng::urcu::lfht_iteration_adapter
<relay_stream
,
2288 decltype(relay_stream::node
),
2289 &relay_stream::node
>(*relay_streams_ht
->ht
)) {
2290 if (!stream_get(stream
)) {
2294 if (stream
->trace
->session
->id
== msg
.session_id
) {
2295 pthread_mutex_lock(&stream
->lock
);
2296 stream
->data_pending_check_done
= false;
2297 pthread_mutex_unlock(&stream
->lock
);
2298 DBG("Set begin data pending flag to stream %" PRIu64
,
2299 stream
->stream_handle
);
2305 memset(&reply
, 0, sizeof(reply
));
2306 /* All good, send back reply. */
2307 reply
.ret_code
= htobe32(LTTNG_OK
);
2309 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2310 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2311 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret
);
2322 * End data pending command. This will check, for a given session id, if
2323 * each stream associated with it has its data_pending_check_done flag
2324 * set. If not, this means that the client lost track of the stream but
2325 * the data is still being streamed on our side. In this case, we inform
2326 * the client that data is in flight.
2328 * Return to the client if there is data in flight or not with a ret_code.
2330 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2331 struct relay_connection
*conn
,
2332 const struct lttng_buffer_view
*payload
)
2336 struct lttcomm_relayd_end_data_pending msg
;
2337 struct lttcomm_relayd_generic_reply reply
;
2338 uint32_t is_data_inflight
= 0;
2340 DBG("End data pending command");
2342 if (!conn
->session
|| !conn
->version_check_done
) {
2343 ERR("Trying to check for data before version check");
2345 goto end_no_session
;
2348 if (payload
->size
< sizeof(msg
)) {
2349 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2353 goto end_no_session
;
2355 memcpy(&msg
, payload
->data
, sizeof(msg
));
2356 msg
.session_id
= be64toh(msg
.session_id
);
2359 * Iterate over all streams to see if the begin data pending
2363 lttng::urcu::lfht_iteration_adapter
<relay_stream
,
2364 decltype(relay_stream::node
),
2365 &relay_stream::node
>(*relay_streams_ht
->ht
)) {
2366 if (!stream_get(stream
)) {
2370 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2375 pthread_mutex_lock(&stream
->lock
);
2376 if (!stream
->data_pending_check_done
) {
2377 uint64_t stream_seq
;
2379 if (session_streams_have_index(conn
->session
)) {
2381 * Ensure that both the index and stream data have been
2382 * flushed up to the requested point.
2385 std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2387 stream_seq
= stream
->prev_data_seq
;
2390 if (!stream
->closed
||
2391 !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2392 is_data_inflight
= 1;
2393 DBG("Data is still in flight for stream %" PRIu64
,
2394 stream
->stream_handle
);
2395 pthread_mutex_unlock(&stream
->lock
);
2401 pthread_mutex_unlock(&stream
->lock
);
2405 memset(&reply
, 0, sizeof(reply
));
2406 /* All good, send back reply. */
2407 reply
.ret_code
= htobe32(is_data_inflight
);
2409 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2410 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2411 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret
);
2422 * Receive an index for a specific stream.
2424 * Return 0 on success else a negative value.
2426 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2427 struct relay_connection
*conn
,
2428 const struct lttng_buffer_view
*payload
)
2432 struct relay_session
*session
= conn
->session
;
2433 struct lttcomm_relayd_index index_info
;
2434 struct lttcomm_relayd_generic_reply reply
;
2435 struct relay_stream
*stream
;
2440 DBG("Relay receiving index");
2442 if (!session
|| !conn
->version_check_done
) {
2443 ERR("Trying to close a stream before version check");
2445 goto end_no_session
;
2448 msg_len
= lttcomm_relayd_index_len(lttng_to_index_major(conn
->major
, conn
->minor
),
2449 lttng_to_index_minor(conn
->major
, conn
->minor
));
2450 if (payload
->size
< msg_len
) {
2451 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2455 goto end_no_session
;
2457 memcpy(&index_info
, payload
->data
, msg_len
);
2458 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2459 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2460 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2461 index_info
.content_size
= be64toh(index_info
.content_size
);
2462 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2463 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2464 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2465 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2467 if (conn
->minor
>= 8) {
2468 index_info
.stream_instance_id
= be64toh(index_info
.stream_instance_id
);
2469 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2471 index_info
.stream_instance_id
= -1ULL;
2472 index_info
.packet_seq_num
= -1ULL;
2475 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2477 ERR("stream_get_by_id not found");
2482 pthread_mutex_lock(&stream
->lock
);
2483 ret
= stream_add_index(stream
, &index_info
);
2484 pthread_mutex_unlock(&stream
->lock
);
2486 goto end_stream_put
;
2492 memset(&reply
, 0, sizeof(reply
));
2494 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2496 reply
.ret_code
= htobe32(LTTNG_OK
);
2498 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2499 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2500 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2509 * Receive the streams_sent message.
2511 * Return 0 on success else a negative value.
2513 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2514 struct relay_connection
*conn
,
2515 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2519 struct lttcomm_relayd_generic_reply reply
;
2523 DBG("Relay receiving streams_sent");
2525 if (!conn
->session
|| !conn
->version_check_done
) {
2526 ERR("Trying to close a stream before version check");
2528 goto end_no_session
;
2532 * Publish every pending stream in the connection recv list which are
2533 * now ready to be used by the viewer.
2535 publish_connection_local_streams(conn
);
2537 memset(&reply
, 0, sizeof(reply
));
2538 reply
.ret_code
= htobe32(LTTNG_OK
);
2539 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2540 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2541 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret
);
2553 relay_unpack_rotate_streams_header(const struct lttng_buffer_view
*payload
,
2554 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2556 struct lttcomm_relayd_rotate_streams rotate_streams
;
2558 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2559 * This is the smallest version of this structure, but it can be larger;
2560 * this variable is updated once the proper size of the structure is known.
2562 * See comment at the declaration of this structure for more information.
2564 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2565 size_t expected_payload_size_no_padding
, expected_payload_size_3_bytes_padding
,
2566 expected_payload_size_7_bytes_padding
;
2568 if (payload
->size
< header_len
) {
2569 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2576 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2577 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2579 * We start by "unpacking" `stream_count` to figure out the padding length
2580 * emited by our peer.
2583 decltype(rotate_streams
.stream_count
) stream_count
;
2585 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2586 rotate_streams
.stream_count
= be32toh(stream_count
);
2589 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2592 * Payload size expected given the possible padding lengths in
2593 * `struct lttcomm_relayd_rotate_streams`.
2595 expected_payload_size_no_padding
=
2596 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2597 sizeof(lttcomm_relayd_rotate_streams_packed
);
2598 expected_payload_size_3_bytes_padding
=
2599 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2600 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2601 expected_payload_size_7_bytes_padding
=
2602 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2603 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2605 if (payload
->size
== expected_payload_size_no_padding
) {
2606 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2609 * This handles cases where someone might build with
2610 * -fpack-struct or any other toolchain that wouldn't produce
2611 * padding to align `value`.
2613 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2615 header_len
= sizeof(packed_rotate_streams
);
2616 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2618 /* Unpack the packed structure to the natively-packed version. */
2619 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2620 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2621 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2623 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2624 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2625 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2627 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2629 header_len
= sizeof(padded_rotate_streams
);
2630 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2632 /* Unpack the 3-byte padded structure to the natively-packed version. */
2633 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2634 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2635 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2637 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2638 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2639 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2641 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2643 header_len
= sizeof(padded_rotate_streams
);
2644 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2646 /* Unpack the 7-byte padded structure to the natively-packed version. */
2647 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2648 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2649 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2651 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2653 header_len
= sizeof(padded_rotate_streams
);
2655 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2656 expected_payload_size_no_padding
,
2657 expected_payload_size_3_bytes_padding
,
2658 expected_payload_size_7_bytes_padding
,
2669 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2670 * session rotation feature (not the tracefile rotation feature).
2672 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr
*recv_hdr
2673 __attribute__((unused
)),
2674 struct relay_connection
*conn
,
2675 const struct lttng_buffer_view
*payload
)
2680 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2681 struct relay_session
*session
= conn
->session
;
2682 struct lttcomm_relayd_rotate_streams rotate_streams
;
2683 struct lttcomm_relayd_generic_reply reply
= {};
2684 struct relay_stream
*stream
= nullptr;
2685 struct lttng_trace_chunk
*next_trace_chunk
= nullptr;
2686 struct lttng_buffer_view stream_positions
;
2687 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2688 const char *chunk_id_str
= "none";
2691 if (!session
|| !conn
->version_check_done
) {
2692 ERR("Trying to rotate a stream before version check");
2697 if (session
->major
== 2 && session
->minor
< 11) {
2698 ERR("Unsupported feature before 2.11");
2703 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2704 if (header_len
< 0) {
2709 if (rotate_streams
.new_chunk_id
.is_set
) {
2711 * Retrieve the trace chunk the stream must transition to. As
2712 * per the protocol, this chunk should have been created
2713 * before this command is received.
2715 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2716 sessiond_trace_chunk_registry
,
2717 session
->sessiond_uuid
,
2718 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2720 rotate_streams
.new_chunk_id
.value
);
2721 if (!next_trace_chunk
) {
2722 char uuid_str
[LTTNG_UUID_STR_LEN
];
2724 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2725 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2726 ", trace_chunk_id = %" PRIu64
,
2729 rotate_streams
.new_chunk_id
.value
);
2730 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2735 ret
= snprintf(chunk_id_buf
,
2736 sizeof(chunk_id_buf
),
2738 rotate_streams
.new_chunk_id
.value
);
2739 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2740 chunk_id_str
= "formatting error";
2742 chunk_id_str
= chunk_id_buf
;
2746 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2747 rotate_streams
.stream_count
,
2748 session
->session_name
,
2751 stream_positions
= lttng_buffer_view_from_view(payload
, header_len
, -1);
2752 if (!stream_positions
.data
||
2753 stream_positions
.size
< (rotate_streams
.stream_count
*
2754 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2755 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2760 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2761 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2762 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2763 const struct lttcomm_relayd_stream_rotation_position pos
= {
2764 .stream_id
= be64toh(position_comm
->stream_id
),
2765 .rotate_at_seq_num
= be64toh(position_comm
->rotate_at_seq_num
),
2768 stream
= stream_get_by_id(pos
.stream_id
);
2770 reply_code
= LTTNG_ERR_INVALID
;
2775 pthread_mutex_lock(&stream
->lock
);
2776 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
, pos
.rotate_at_seq_num
);
2777 pthread_mutex_unlock(&stream
->lock
);
2779 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2787 reply_code
= LTTNG_OK
;
2794 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2795 send_ret
= conn
->sock
->ops
->sendmsg(
2796 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2797 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2798 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret
);
2802 lttng_trace_chunk_put(next_trace_chunk
);
2807 * relay_create_trace_chunk: create a new trace chunk
2809 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2810 __attribute__((unused
)),
2811 struct relay_connection
*conn
,
2812 const struct lttng_buffer_view
*payload
)
2816 struct relay_session
*session
= conn
->session
;
2817 struct lttcomm_relayd_create_trace_chunk
*msg
;
2818 struct lttcomm_relayd_generic_reply reply
= {};
2819 struct lttng_buffer_view header_view
;
2820 struct lttng_trace_chunk
*chunk
= nullptr, *published_chunk
= nullptr;
2821 enum lttng_error_code reply_code
= LTTNG_OK
;
2822 enum lttng_trace_chunk_status chunk_status
;
2823 const char *new_path
;
2825 if (!session
|| !conn
->version_check_done
) {
2826 ERR("Trying to create a trace chunk before version check");
2831 if (session
->major
== 2 && session
->minor
< 11) {
2832 ERR("Chunk creation command is unsupported before 2.11");
2837 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2838 if (!lttng_buffer_view_is_valid(&header_view
)) {
2839 ERR("Failed to receive payload of chunk creation command");
2844 /* Convert to host endianness. */
2845 msg
= (typeof(msg
)) header_view
.data
;
2846 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2847 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2848 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2850 pthread_mutex_lock(&conn
->session
->lock
);
2851 session
->ongoing_rotation
= true;
2852 if (session
->current_trace_chunk
&&
2853 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2854 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2855 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2856 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2857 ERR("Failed to rename old chunk");
2859 reply_code
= LTTNG_ERR_UNK
;
2863 if (!session
->current_trace_chunk
) {
2864 if (!session
->has_rotated
) {
2870 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2872 chunk
= lttng_trace_chunk_create(msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2874 ERR("Failed to create trace chunk in trace chunk creation command");
2876 reply_code
= LTTNG_ERR_NOMEM
;
2879 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2881 if (msg
->override_name_length
) {
2883 const struct lttng_buffer_view chunk_name_view
= lttng_buffer_view_from_view(
2884 payload
, sizeof(*msg
), msg
->override_name_length
);
2886 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2887 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2889 reply_code
= LTTNG_ERR_INVALID
;
2893 name
= chunk_name_view
.data
;
2894 if (name
[msg
->override_name_length
- 1]) {
2895 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2897 reply_code
= LTTNG_ERR_INVALID
;
2901 chunk_status
= lttng_trace_chunk_override_name(chunk
, chunk_name_view
.data
);
2902 switch (chunk_status
) {
2903 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2905 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2906 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2907 reply_code
= LTTNG_ERR_INVALID
;
2911 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2912 reply_code
= LTTNG_ERR_UNK
;
2918 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2919 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2920 reply_code
= LTTNG_ERR_UNK
;
2925 LTTNG_ASSERT(conn
->session
->output_directory
);
2926 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, conn
->session
->output_directory
);
2927 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2928 reply_code
= LTTNG_ERR_UNK
;
2933 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2934 sessiond_trace_chunk_registry
,
2935 conn
->session
->sessiond_uuid
,
2936 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2939 if (!published_chunk
) {
2940 char uuid_str
[LTTNG_UUID_STR_LEN
];
2942 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2943 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2944 ", chunk_id = %" PRIu64
,
2949 reply_code
= LTTNG_ERR_NOMEM
;
2953 if (conn
->session
->pending_closure_trace_chunk
) {
2955 * Invalid; this means a second create_trace_chunk command was
2956 * received before a close_trace_chunk.
2958 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2959 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2963 conn
->session
->pending_closure_trace_chunk
= conn
->session
->current_trace_chunk
;
2964 conn
->session
->current_trace_chunk
= published_chunk
;
2965 published_chunk
= nullptr;
2966 if (!conn
->session
->pending_closure_trace_chunk
) {
2967 session
->ongoing_rotation
= false;
2970 pthread_mutex_unlock(&conn
->session
->lock
);
2971 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2972 send_ret
= conn
->sock
->ops
->sendmsg(
2973 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2974 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2975 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
2979 lttng_trace_chunk_put(chunk
);
2980 lttng_trace_chunk_put(published_chunk
);
2985 * relay_close_trace_chunk: close a trace chunk
2987 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2988 __attribute__((unused
)),
2989 struct relay_connection
*conn
,
2990 const struct lttng_buffer_view
*payload
)
2992 int ret
= 0, buf_ret
;
2994 struct relay_session
*session
= conn
->session
;
2995 struct lttcomm_relayd_close_trace_chunk
*msg
;
2996 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2997 struct lttng_buffer_view header_view
;
2998 struct lttng_trace_chunk
*chunk
= nullptr;
2999 enum lttng_error_code reply_code
= LTTNG_OK
;
3000 enum lttng_trace_chunk_status chunk_status
;
3002 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
3003 time_t close_timestamp
;
3004 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
3005 size_t path_length
= 0;
3006 const char *chunk_name
= nullptr;
3007 struct lttng_dynamic_buffer reply_payload
;
3008 const char *new_path
;
3010 lttng_dynamic_buffer_init(&reply_payload
);
3012 if (!session
|| !conn
->version_check_done
) {
3013 ERR("Trying to close a trace chunk before version check");
3018 if (session
->major
== 2 && session
->minor
< 11) {
3019 ERR("Chunk close command is unsupported before 2.11");
3024 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3025 if (!lttng_buffer_view_is_valid(&header_view
)) {
3026 ERR("Failed to receive payload of chunk close command");
3031 /* Convert to host endianness. */
3032 msg
= (typeof(msg
)) header_view
.data
;
3033 chunk_id
= be64toh(msg
->chunk_id
);
3034 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
3035 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
3036 close_command
.is_set
= msg
->close_command
.is_set
;
3038 chunk
= sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry
,
3039 conn
->session
->sessiond_uuid
,
3040 conn
->session
->id_sessiond
.is_set
?
3041 conn
->session
->id_sessiond
.value
:
3045 char uuid_str
[LTTNG_UUID_STR_LEN
];
3047 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3048 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
3049 ", chunk_id = %" PRIu64
,
3054 reply_code
= LTTNG_ERR_NOMEM
;
3058 pthread_mutex_lock(&session
->lock
);
3059 if (close_command
.is_set
&& close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3061 * Clear command. It is a protocol error to ask for a
3062 * clear on a relay which does not allow it. Querying
3063 * the configuration allows figuring out whether
3064 * clearing is allowed before doing the clear.
3066 if (!opt_allow_clear
) {
3068 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3069 goto end_unlock_session
;
3072 if (session
->pending_closure_trace_chunk
&& session
->pending_closure_trace_chunk
!= chunk
) {
3073 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3074 session
->session_name
);
3075 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3077 goto end_unlock_session
;
3080 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3081 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3082 if (close_command
.is_set
&&
3083 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3084 !session
->has_rotated
) {
3085 /* New chunk stays in session output directory. */
3088 /* Use chunk name for new chunk. */
3091 /* Rename new chunk path. */
3093 lttng_trace_chunk_rename_path(session
->current_trace_chunk
, new_path
);
3094 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3096 goto end_unlock_session
;
3098 session
->ongoing_rotation
= false;
3100 if ((!close_command
.is_set
||
3101 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3102 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3103 const char *old_path
;
3105 if (!session
->has_rotated
) {
3110 /* We need to move back the .tmp_old_chunk to its rightful place. */
3111 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3112 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3114 goto end_unlock_session
;
3117 chunk_status
= lttng_trace_chunk_set_close_timestamp(chunk
, close_timestamp
);
3118 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3119 ERR("Failed to set trace chunk close timestamp");
3121 reply_code
= LTTNG_ERR_UNK
;
3122 goto end_unlock_session
;
3125 if (close_command
.is_set
) {
3126 chunk_status
= lttng_trace_chunk_set_close_command(chunk
, close_command
.value
);
3127 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3129 reply_code
= LTTNG_ERR_INVALID
;
3130 goto end_unlock_session
;
3133 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, nullptr);
3134 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3135 ERR("Failed to get chunk name");
3137 reply_code
= LTTNG_ERR_UNK
;
3138 goto end_unlock_session
;
3140 if (!session
->has_rotated
&& !session
->snapshot
) {
3141 ret
= lttng_strncpy(closed_trace_chunk_path
,
3142 session
->output_path
,
3143 sizeof(closed_trace_chunk_path
));
3145 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3146 strlen(session
->output_path
),
3147 sizeof(closed_trace_chunk_path
));
3148 reply_code
= LTTNG_ERR_NOMEM
;
3150 goto end_unlock_session
;
3153 if (session
->snapshot
) {
3154 ret
= snprintf(closed_trace_chunk_path
,
3155 sizeof(closed_trace_chunk_path
),
3157 session
->output_path
,
3160 ret
= snprintf(closed_trace_chunk_path
,
3161 sizeof(closed_trace_chunk_path
),
3162 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
"/%s",
3163 session
->output_path
,
3166 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3167 ERR("Failed to format closed trace chunk resulting path");
3168 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3170 goto end_unlock_session
;
3173 if (close_command
.is_set
&&
3174 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3175 session
->has_rotated
= true;
3177 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3178 path_length
= strlen(closed_trace_chunk_path
) + 1;
3179 if (path_length
> UINT32_MAX
) {
3180 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3182 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3183 goto end_unlock_session
;
3186 if (session
->current_trace_chunk
== chunk
) {
3188 * After a trace chunk close command, no new streams
3189 * referencing the chunk may be created. Hence, on the
3190 * event that no new trace chunk have been created for
3191 * the session, the reference to the current trace chunk
3192 * is released in order to allow it to be reclaimed when
3193 * the last stream releases its reference to it.
3195 lttng_trace_chunk_put(session
->current_trace_chunk
);
3196 session
->current_trace_chunk
= nullptr;
3198 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3199 session
->pending_closure_trace_chunk
= nullptr;
3201 pthread_mutex_unlock(&session
->lock
);
3204 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3205 reply
.path_length
= htobe32((uint32_t) path_length
);
3206 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
3208 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3212 if (reply_code
== LTTNG_OK
) {
3213 buf_ret
= lttng_dynamic_buffer_append(
3214 &reply_payload
, closed_trace_chunk_path
, path_length
);
3216 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3221 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
3222 if (send_ret
< reply_payload
.size
) {
3223 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3230 lttng_trace_chunk_put(chunk
);
3231 lttng_dynamic_buffer_reset(&reply_payload
);
3236 * relay_trace_chunk_exists: check if a trace chunk exists
3238 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
3239 __attribute__((unused
)),
3240 struct relay_connection
*conn
,
3241 const struct lttng_buffer_view
*payload
)
3245 struct relay_session
*session
= conn
->session
;
3246 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3247 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3248 struct lttng_buffer_view header_view
;
3252 if (!session
|| !conn
->version_check_done
) {
3253 ERR("Trying to check for the presence of a trace chunk before version check");
3258 if (session
->major
== 2 && session
->minor
< 11) {
3259 ERR("Chunk exists command is unsupported before 2.11");
3264 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3265 if (!lttng_buffer_view_is_valid(&header_view
)) {
3266 ERR("Failed to receive payload of chunk exists command");
3271 /* Convert to host endianness. */
3272 msg
= (typeof(msg
)) header_view
.data
;
3273 chunk_id
= be64toh(msg
->chunk_id
);
3275 ret
= sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry
,
3276 conn
->session
->sessiond_uuid
,
3281 * If ret is not 0, send the reply and report the error to the caller.
3282 * It is a protocol (or internal) error and the session/connection
3283 * should be torn down.
3285 reply
.generic
.ret_code
=
3286 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3287 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3289 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3290 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3291 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
3299 * relay_get_configuration: query whether feature is available
3301 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
3302 __attribute__((unused
)),
3303 struct relay_connection
*conn
,
3304 const struct lttng_buffer_view
*payload
)
3308 struct lttcomm_relayd_get_configuration
*msg
;
3309 struct lttcomm_relayd_get_configuration_reply reply
= {};
3310 struct lttng_buffer_view header_view
;
3311 uint64_t query_flags
= 0;
3312 uint64_t result_flags
= 0;
3314 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3315 if (!lttng_buffer_view_is_valid(&header_view
)) {
3316 ERR("Failed to receive payload of chunk close command");
3321 /* Convert to host endianness. */
3322 msg
= (typeof(msg
)) header_view
.data
;
3323 query_flags
= be64toh(msg
->query_flags
);
3326 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3329 if (opt_allow_clear
) {
3330 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3334 reply
.generic
.ret_code
=
3335 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3336 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3338 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3339 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3340 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3347 static int relay_process_control_command(struct relay_connection
*conn
,
3348 const struct lttcomm_relayd_hdr
*header
,
3349 const struct lttng_buffer_view
*payload
)
3353 DBG3("Processing \"%s\" command for socket %i",
3354 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3356 switch (header
->cmd
) {
3357 case RELAYD_CREATE_SESSION
:
3358 ret
= relay_create_session(header
, conn
, payload
);
3360 case RELAYD_ADD_STREAM
:
3361 ret
= relay_add_stream(header
, conn
, payload
);
3363 case RELAYD_START_DATA
:
3364 ret
= relay_start(header
, conn
, payload
);
3366 case RELAYD_SEND_METADATA
:
3367 ret
= relay_recv_metadata(header
, conn
, payload
);
3369 case RELAYD_VERSION
:
3370 ret
= relay_send_version(header
, conn
, payload
);
3372 case RELAYD_CLOSE_STREAM
:
3373 ret
= relay_close_stream(header
, conn
, payload
);
3375 case RELAYD_DATA_PENDING
:
3376 ret
= relay_data_pending(header
, conn
, payload
);
3378 case RELAYD_QUIESCENT_CONTROL
:
3379 ret
= relay_quiescent_control(header
, conn
, payload
);
3381 case RELAYD_BEGIN_DATA_PENDING
:
3382 ret
= relay_begin_data_pending(header
, conn
, payload
);
3384 case RELAYD_END_DATA_PENDING
:
3385 ret
= relay_end_data_pending(header
, conn
, payload
);
3387 case RELAYD_SEND_INDEX
:
3388 ret
= relay_recv_index(header
, conn
, payload
);
3390 case RELAYD_STREAMS_SENT
:
3391 ret
= relay_streams_sent(header
, conn
, payload
);
3393 case RELAYD_RESET_METADATA
:
3394 ret
= relay_reset_metadata(header
, conn
, payload
);
3396 case RELAYD_ROTATE_STREAMS
:
3397 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3399 case RELAYD_CREATE_TRACE_CHUNK
:
3400 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3402 case RELAYD_CLOSE_TRACE_CHUNK
:
3403 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3405 case RELAYD_TRACE_CHUNK_EXISTS
:
3406 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3408 case RELAYD_GET_CONFIGURATION
:
3409 ret
= relay_get_configuration(header
, conn
, payload
);
3411 case RELAYD_UPDATE_SYNC_INFO
:
3413 ERR("Received unknown command (%u)", header
->cmd
);
3414 relay_unknown_command(conn
);
3423 static enum relay_connection_status
3424 relay_process_control_receive_payload(struct relay_connection
*conn
)
3427 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3428 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3429 struct ctrl_connection_state_receive_payload
*state
=
3430 &conn
->protocol
.ctrl
.state
.receive_payload
;
3431 struct lttng_buffer_view payload_view
;
3433 if (state
->left_to_receive
== 0) {
3434 /* Short-circuit for payload-less commands. */
3435 goto reception_complete
;
3438 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3439 reception_buffer
->data
+ state
->received
,
3440 state
->left_to_receive
,
3444 DIAGNOSTIC_IGNORE_LOGICAL_OP
3445 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3447 PERROR("Unable to receive command payload on sock %d", conn
->sock
->fd
);
3448 status
= RELAY_CONNECTION_STATUS_ERROR
;
3451 } else if (ret
== 0) {
3452 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3453 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3457 LTTNG_ASSERT(ret
> 0);
3458 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3460 state
->left_to_receive
-= ret
;
3461 state
->received
+= ret
;
3463 if (state
->left_to_receive
> 0) {
3465 * Can't transition to the protocol's next state, wait to
3466 * receive the rest of the header.
3468 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3469 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3471 state
->left_to_receive
,
3477 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3481 * The payload required to process the command has been received.
3482 * A view to the reception buffer is forwarded to the various
3483 * commands and the state of the control is reset on success.
3485 * Commands are responsible for sending their reply to the peer.
3487 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
, 0, -1);
3488 ret
= relay_process_control_command(conn
, &state
->header
, &payload_view
);
3490 status
= RELAY_CONNECTION_STATUS_ERROR
;
3494 ret
= connection_reset_protocol_state(conn
);
3496 status
= RELAY_CONNECTION_STATUS_ERROR
;
3502 static enum relay_connection_status
3503 relay_process_control_receive_header(struct relay_connection
*conn
)
3506 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3507 struct lttcomm_relayd_hdr header
;
3508 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3509 struct ctrl_connection_state_receive_header
*state
=
3510 &conn
->protocol
.ctrl
.state
.receive_header
;
3512 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3514 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3515 reception_buffer
->data
+ state
->received
,
3516 state
->left_to_receive
,
3520 DIAGNOSTIC_IGNORE_LOGICAL_OP
3521 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3523 PERROR("Unable to receive control command header on sock %d",
3525 status
= RELAY_CONNECTION_STATUS_ERROR
;
3528 } else if (ret
== 0) {
3529 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3530 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3534 LTTNG_ASSERT(ret
> 0);
3535 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3537 state
->left_to_receive
-= ret
;
3538 state
->received
+= ret
;
3540 if (state
->left_to_receive
> 0) {
3542 * Can't transition to the protocol's next state, wait to
3543 * receive the rest of the header.
3545 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3546 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3548 state
->left_to_receive
,
3553 /* Transition to next state: receiving the command's payload. */
3554 conn
->protocol
.ctrl
.state_id
= CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3555 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3556 header
.circuit_id
= be64toh(header
.circuit_id
);
3557 header
.data_size
= be64toh(header
.data_size
);
3558 header
.cmd
= be32toh(header
.cmd
);
3559 header
.cmd_version
= be32toh(header
.cmd_version
);
3560 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
, &header
, sizeof(header
));
3562 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3563 ", payload size = %" PRIu64
" bytes",
3565 lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3569 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3570 ERR("Command header indicates a payload (%" PRIu64
3571 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3573 status
= RELAY_CONNECTION_STATUS_ERROR
;
3577 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3578 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3579 ret
= lttng_dynamic_buffer_set_size(reception_buffer
, header
.data_size
);
3581 status
= RELAY_CONNECTION_STATUS_ERROR
;
3585 if (header
.data_size
== 0) {
3587 * Manually invoke the next state as the poll loop
3588 * will not wake-up to allow us to proceed further.
3590 status
= relay_process_control_receive_payload(conn
);
3597 * Process the commands received on the control socket
3599 static enum relay_connection_status
relay_process_control(struct relay_connection
*conn
)
3601 enum relay_connection_status status
;
3603 switch (conn
->protocol
.ctrl
.state_id
) {
3604 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3605 status
= relay_process_control_receive_header(conn
);
3607 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3608 status
= relay_process_control_receive_payload(conn
);
3611 ERR("Unknown control connection protocol state encountered.");
3618 static enum relay_connection_status
relay_process_data_receive_header(struct relay_connection
*conn
)
3621 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3622 struct data_connection_state_receive_header
*state
=
3623 &conn
->protocol
.data
.state
.receive_header
;
3624 struct lttcomm_relayd_data_hdr header
;
3625 struct relay_stream
*stream
;
3627 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3629 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3630 state
->header_reception_buffer
+ state
->received
,
3631 state
->left_to_receive
,
3635 DIAGNOSTIC_IGNORE_LOGICAL_OP
3636 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3638 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3639 status
= RELAY_CONNECTION_STATUS_ERROR
;
3642 } else if (ret
== 0) {
3643 /* Orderly shutdown. Not necessary to print an error. */
3644 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3645 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3649 LTTNG_ASSERT(ret
> 0);
3650 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3652 state
->left_to_receive
-= ret
;
3653 state
->received
+= ret
;
3655 if (state
->left_to_receive
> 0) {
3657 * Can't transition to the protocol's next state, wait to
3658 * receive the rest of the header.
3660 DBG3("Partial reception of data connection header (received %" PRIu64
3661 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3663 state
->left_to_receive
,
3668 /* Transition to next state: receiving the payload. */
3669 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3671 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3672 header
.circuit_id
= be64toh(header
.circuit_id
);
3673 header
.stream_id
= be64toh(header
.stream_id
);
3674 header
.data_size
= be32toh(header
.data_size
);
3675 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3676 header
.padding_size
= be32toh(header
.padding_size
);
3677 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3679 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3680 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3681 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3683 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3684 ", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
3685 ", padding_size = %" PRIu32
,
3691 header
.padding_size
);
3693 stream
= stream_get_by_id(header
.stream_id
);
3695 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3697 /* Protocol error. */
3698 status
= RELAY_CONNECTION_STATUS_ERROR
;
3702 pthread_mutex_lock(&stream
->lock
);
3703 /* Prepare stream for the reception of a new packet. */
3704 ret
= stream_init_packet(
3705 stream
, header
.data_size
, &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3706 pthread_mutex_unlock(&stream
->lock
);
3708 ERR("Failed to rotate stream output file");
3709 status
= RELAY_CONNECTION_STATUS_ERROR
;
3710 goto end_stream_unlock
;
3719 static enum relay_connection_status
3720 relay_process_data_receive_payload(struct relay_connection
*conn
)
3723 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3724 struct relay_stream
*stream
;
3725 struct data_connection_state_receive_payload
*state
=
3726 &conn
->protocol
.data
.state
.receive_payload
;
3727 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3728 char data_buffer
[chunk_size
];
3729 bool partial_recv
= false;
3730 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3731 uint64_t left_to_receive
= state
->left_to_receive
;
3732 struct relay_session
*session
;
3734 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
3735 " bytes received, %" PRIu64
" bytes left to receive",
3736 state
->header
.stream_id
,
3737 state
->header
.net_seq_num
,
3741 stream
= stream_get_by_id(state
->header
.stream_id
);
3743 /* Protocol error. */
3744 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3745 state
->header
.stream_id
);
3746 status
= RELAY_CONNECTION_STATUS_ERROR
;
3750 pthread_mutex_lock(&stream
->lock
);
3751 session
= stream
->trace
->session
;
3752 if (!conn
->session
) {
3753 ret
= connection_set_session(conn
, session
);
3755 status
= RELAY_CONNECTION_STATUS_ERROR
;
3756 goto end_stream_unlock
;
3761 * The size of the "chunk" received on any iteration is bounded by:
3762 * - the data left to receive,
3763 * - the data immediately available on the socket,
3764 * - the on-stack data buffer
3766 while (left_to_receive
> 0 && !partial_recv
) {
3767 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3768 struct lttng_buffer_view packet_chunk
;
3770 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, MSG_DONTWAIT
);
3773 DIAGNOSTIC_IGNORE_LOGICAL_OP
3774 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3776 PERROR("Socket %d error", conn
->sock
->fd
);
3777 status
= RELAY_CONNECTION_STATUS_ERROR
;
3779 goto end_stream_unlock
;
3780 } else if (ret
== 0) {
3781 /* No more data ready to be consumed on socket. */
3782 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3783 state
->header
.stream_id
);
3784 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3786 } else if (ret
< (int) recv_size
) {
3788 * All the data available on the socket has been
3791 partial_recv
= true;
3795 packet_chunk
= lttng_buffer_view_init(data_buffer
, 0, recv_size
);
3796 LTTNG_ASSERT(packet_chunk
.data
);
3798 ret
= stream_write(stream
, &packet_chunk
, 0);
3800 ERR("Relay error writing data to file");
3801 status
= RELAY_CONNECTION_STATUS_ERROR
;
3802 goto end_stream_unlock
;
3805 left_to_receive
-= recv_size
;
3806 state
->received
+= recv_size
;
3807 state
->left_to_receive
= left_to_receive
;
3810 if (state
->left_to_receive
> 0) {
3812 * Did not receive all the data expected, wait for more data to
3813 * become available on the socket.
3815 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
3816 " bytes received, %" PRIu64
" bytes left to receive",
3817 state
->header
.stream_id
,
3819 state
->left_to_receive
);
3820 goto end_stream_unlock
;
3823 ret
= stream_write(stream
, nullptr, state
->header
.padding_size
);
3825 status
= RELAY_CONNECTION_STATUS_ERROR
;
3826 goto end_stream_unlock
;
3829 if (session_streams_have_index(session
)) {
3830 ret
= stream_update_index(stream
,
3831 state
->header
.net_seq_num
,
3832 state
->rotate_index
,
3834 state
->header
.data_size
+ state
->header
.padding_size
);
3836 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
3838 stream
->stream_handle
,
3839 state
->header
.net_seq_num
,
3841 status
= RELAY_CONNECTION_STATUS_ERROR
;
3842 goto end_stream_unlock
;
3846 if (stream
->prev_data_seq
== -1ULL) {
3850 ret
= stream_complete_packet(stream
,
3851 state
->header
.data_size
+ state
->header
.padding_size
,
3852 state
->header
.net_seq_num
,
3855 status
= RELAY_CONNECTION_STATUS_ERROR
;
3856 goto end_stream_unlock
;
3860 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3861 * contents of *state which are aliased (union) to the same location as
3862 * the new state. Don't use it beyond this point.
3864 connection_reset_protocol_state(conn
);
3868 close_requested
= stream
->close_requested
;
3869 pthread_mutex_unlock(&stream
->lock
);
3870 if (close_requested
&& left_to_receive
== 0) {
3871 try_stream_close(stream
);
3875 pthread_mutex_lock(&session
->lock
);
3876 uatomic_set(&session
->new_streams
, 1);
3877 pthread_mutex_unlock(&session
->lock
);
3886 * relay_process_data: Process the data received on the data socket
3888 static enum relay_connection_status
relay_process_data(struct relay_connection
*conn
)
3890 enum relay_connection_status status
;
3892 switch (conn
->protocol
.data
.state_id
) {
3893 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3894 status
= relay_process_data_receive_header(conn
);
3896 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3897 status
= relay_process_data_receive_payload(conn
);
3900 ERR("Unexpected data connection communication state.");
3907 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3911 (void) lttng_poll_del(events
, pollfd
);
3913 ret
= fd_tracker_close_unsuspendable_fd(
3914 the_fd_tracker
, &pollfd
, 1, fd_tracker_util_close_fd
, nullptr);
3916 ERR("Closing pollfd %d", pollfd
);
3920 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3922 struct relay_connection
*conn
)
3924 const char *type_str
;
3926 switch (conn
->type
) {
3931 type_str
= "Control";
3933 case RELAY_VIEWER_COMMAND
:
3934 type_str
= "Viewer Command";
3936 case RELAY_VIEWER_NOTIFICATION
:
3937 type_str
= "Viewer Notification";
3940 type_str
= "Unknown";
3942 cleanup_connection_pollfd(events
, pollfd
);
3943 connection_put(conn
);
3944 DBG("%s connection closed with %d", type_str
, pollfd
);
3948 * This thread does the actual work
3950 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3952 int ret
, err
= -1, last_seen_data_fd
= -1;
3954 struct lttng_poll_event events
;
3955 struct lttng_ht
*relay_connections_ht
;
3957 DBG("[thread] Relay worker started");
3959 rcu_register_thread();
3961 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3963 if (testpoint(relayd_thread_worker
)) {
3964 goto error_testpoint
;
3967 health_code_update();
3969 /* table of connections indexed on socket */
3970 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3971 if (!relay_connections_ht
) {
3972 goto relay_connections_ht_error
;
3975 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3977 goto error_poll_create
;
3980 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3987 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3989 health_code_update();
3991 /* Infinite blocking call, waiting for transmission */
3992 DBG3("Relayd worker thread polling...");
3993 health_poll_entry();
3994 ret
= lttng_poll_wait(&events
, -1);
3998 * Restart interrupted system call.
4000 if (errno
== EINTR
) {
4009 * Process control. The control connection is
4010 * prioritized so we don't starve it with high
4011 * throughput tracing data on the data connection.
4013 for (i
= 0; i
< nb_fd
; i
++) {
4014 /* Fetch once the poll data */
4015 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
4016 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4018 health_code_update();
4020 /* Activity on thread quit pipe, exiting. */
4021 if (relayd_is_thread_quit_pipe(pollfd
)) {
4022 DBG("Activity on thread quit pipe");
4027 /* Inspect the relay conn pipe for new connection */
4028 if (pollfd
== relay_conn_pipe
[0]) {
4029 if (revents
& LPOLLIN
) {
4030 struct relay_connection
*conn
;
4032 ret
= lttng_read(relay_conn_pipe
[0],
4034 sizeof(conn
)); /* NOLINT sizeof used on a
4039 ret
= lttng_poll_add(
4040 &events
, conn
->sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
4042 ERR("Failed to add new connection file descriptor to poll set");
4045 connection_ht_add(relay_connections_ht
, conn
);
4046 DBG("Connection socket %d added", conn
->sock
->fd
);
4047 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4048 ERR("Relay connection pipe error");
4051 ERR("Unexpected poll events %u for sock %d",
4057 struct relay_connection
*ctrl_conn
;
4059 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4060 /* If not found, there is a synchronization issue. */
4061 LTTNG_ASSERT(ctrl_conn
);
4063 if (ctrl_conn
->type
== RELAY_DATA
) {
4064 if (revents
& LPOLLIN
) {
4066 * Flag the last seen data fd not deleted. It will
4067 * be used as the last seen fd if any fd gets
4068 * deleted in this first loop.
4070 last_notdel_data_fd
= pollfd
;
4072 goto put_ctrl_connection
;
4074 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4076 if (revents
& LPOLLIN
) {
4077 enum relay_connection_status status
;
4079 status
= relay_process_control(ctrl_conn
);
4080 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4082 * On socket error flag the session as aborted to
4083 * force the cleanup of its stream otherwise it can
4084 * leak during the lifetime of the relayd.
4086 * This prevents situations in which streams can be
4087 * left opened because an index was received, the
4088 * control connection is closed, and the data
4089 * connection is closed (uncleanly) before the
4090 * packet's data provided.
4092 * Since the control connection encountered an
4093 * error, it is okay to be conservative and close
4094 * the session right now as we can't rely on the
4095 * protocol being respected anymore.
4097 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4098 session_abort(ctrl_conn
->session
);
4101 /* Clear the connection on error or close. */
4102 relay_thread_close_connection(
4103 &events
, pollfd
, ctrl_conn
);
4106 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4107 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
4108 if (last_seen_data_fd
== pollfd
) {
4109 last_seen_data_fd
= last_notdel_data_fd
;
4112 ERR("Unexpected poll events %u for control sock %d",
4115 connection_put(ctrl_conn
);
4118 put_ctrl_connection
:
4119 connection_put(ctrl_conn
);
4124 * The last loop handled a control request, go back to poll to make
4125 * sure we prioritise the control socket.
4131 if (last_seen_data_fd
>= 0) {
4132 for (i
= 0; i
< nb_fd
; i
++) {
4133 const int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4135 health_code_update();
4137 if (last_seen_data_fd
== pollfd
) {
4144 /* Process data connection. */
4145 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4146 /* Fetch the poll data. */
4147 const uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4148 const int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4149 struct relay_connection
*data_conn
;
4151 health_code_update();
4154 /* No activity for this FD (poll implementation). */
4158 /* Skip the command pipe. It's handled in the first loop. */
4159 if (pollfd
== relay_conn_pipe
[0]) {
4163 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4165 /* Skip it. Might be removed before. */
4168 if (data_conn
->type
== RELAY_CONTROL
) {
4169 goto put_data_connection
;
4171 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4173 if (revents
& LPOLLIN
) {
4174 enum relay_connection_status status
;
4176 status
= relay_process_data(data_conn
);
4177 /* Connection closed or error. */
4178 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4180 * On socket error flag the session as aborted to force
4181 * the cleanup of its stream otherwise it can leak
4182 * during the lifetime of the relayd.
4184 * This prevents situations in which streams can be
4185 * left opened because an index was received, the
4186 * control connection is closed, and the data
4187 * connection is closed (uncleanly) before the packet's
4190 * Since the data connection encountered an error,
4191 * it is okay to be conservative and close the
4192 * session right now as we can't rely on the protocol
4193 * being respected anymore.
4195 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4196 session_abort(data_conn
->session
);
4198 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4200 * Every goto restart call sets the last seen fd where
4201 * here we don't really care since we gracefully
4202 * continue the loop after the connection is deleted.
4205 /* Keep last seen port. */
4206 last_seen_data_fd
= pollfd
;
4207 connection_put(data_conn
);
4210 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4211 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4213 ERR("Unknown poll events %u for data sock %d", revents
, pollfd
);
4215 put_data_connection
:
4216 connection_put(data_conn
);
4218 last_seen_data_fd
= -1;
4221 /* Normal exit, no error */
4226 /* Cleanup remaining connection object. */
4227 for (auto *destroy_conn
:
4228 lttng::urcu::lfht_iteration_adapter
<relay_connection
,
4229 decltype(relay_connection::sock_n
),
4230 &relay_connection::sock_n
>(
4231 *relay_connections_ht
->ht
)) {
4232 health_code_update();
4234 session_abort(destroy_conn
->session
);
4237 * No need to grab another ref, because we own
4240 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
, destroy_conn
);
4243 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4245 lttng_ht_destroy(relay_connections_ht
);
4246 relay_connections_ht_error
:
4247 /* Close relay conn pipes */
4248 (void) fd_tracker_util_pipe_close(the_fd_tracker
, relay_conn_pipe
);
4250 DBG("Thread exited with error");
4252 DBG("Worker thread cleanup complete");
4256 ERR("Health error occurred in %s", __func__
);
4258 health_unregister(health_relayd
);
4259 rcu_unregister_thread();
4260 lttng_relay_stop_threads();
4265 * Create the relay command pipe to wake thread_manage_apps.
4266 * Closed in cleanup().
4268 static int create_relay_conn_pipe()
4270 return fd_tracker_util_pipe_open_cloexec(
4271 the_fd_tracker
, "Relayd connection pipe", relay_conn_pipe
);
4274 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4276 fds
[0] = fileno(stdout
);
4277 fds
[1] = fileno(stderr
);
4281 static int track_stdio()
4284 const char *names
[] = { "stdout", "stderr" };
4286 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
, names
, 2, stdio_open
, nullptr);
4292 int main(int argc
, char **argv
)
4294 bool thread_is_rcu_registered
= false;
4295 int ret
= 0, retval
= 0;
4297 char *unlinked_file_directory_path
= nullptr, *output_path
= nullptr;
4299 /* Parse environment variables */
4300 ret
= parse_env_options();
4308 * Command line arguments overwrite environment.
4311 if (set_options(argc
, argv
)) {
4316 if (set_signal_handler()) {
4321 relayd_config_log();
4323 if (opt_print_version
) {
4329 ret
= fclose(stdin
);
4331 PERROR("Failed to close stdin");
4335 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4337 /* Try to create directory if -o, --output is specified. */
4338 if (opt_output_path
) {
4339 if (*opt_output_path
!= '/') {
4340 ERR("Please specify an absolute path for -o, --output PATH");
4345 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
, -1, -1);
4347 ERR("Unable to create %s", opt_output_path
);
4354 if (opt_daemon
|| opt_background
) {
4355 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
, !opt_background
);
4362 if (opt_working_directory
) {
4363 ret
= utils_change_working_directory(opt_working_directory
);
4365 /* All errors are already logged. */
4370 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4371 if (!sessiond_trace_chunk_registry
) {
4372 ERR("Failed to initialize session daemon trace chunk registry");
4378 * The RCU thread registration (and use, through the fd-tracker's
4379 * creation) is done after the daemonization to allow us to not
4380 * deal with liburcu's fork() management as the call RCU needs to
4383 rcu_register_thread();
4384 thread_is_rcu_registered
= true;
4386 output_path
= create_output_path("");
4388 ERR("Failed to get output path");
4392 ret
= asprintf(&unlinked_file_directory_path
,
4395 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4398 ERR("Failed to format unlinked file directory path");
4402 the_fd_tracker
= fd_tracker_create(unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4403 free(unlinked_file_directory_path
);
4404 if (!the_fd_tracker
) {
4409 ret
= track_stdio();
4415 /* Initialize thread health monitoring */
4416 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4417 if (!health_relayd
) {
4418 PERROR("health_app_create error");
4423 /* Create thread quit pipe */
4424 if (relayd_init_thread_quit_pipe()) {
4429 /* Setup the thread apps communication pipe. */
4430 if (create_relay_conn_pipe()) {
4435 /* Init relay command queue. */
4436 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4438 /* Initialize communication library */
4440 lttcomm_inet_init();
4442 /* tables of sessions indexed by session ID */
4443 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4449 /* tables of streams indexed by stream ID */
4450 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4451 if (!relay_streams_ht
) {
4456 /* tables of viewer sessions indexed by session ID */
4457 viewer_sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4458 if (!viewer_sessions_ht
) {
4463 /* tables of streams indexed by stream ID */
4464 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4465 if (!viewer_streams_ht
) {
4470 ret
= init_health_quit_pipe();
4476 /* Create thread to manage the client socket */
4477 ret
= pthread_create(&health_thread
,
4478 default_pthread_attr(),
4479 thread_manage_health_relayd
,
4483 PERROR("pthread_create health");
4488 /* Setup the dispatcher thread */
4489 ret
= pthread_create(&dispatcher_thread
,
4490 default_pthread_attr(),
4491 relay_thread_dispatcher
,
4495 PERROR("pthread_create dispatcher");
4497 goto exit_dispatcher_thread
;
4500 /* Setup the worker thread */
4501 ret
= pthread_create(&worker_thread
, default_pthread_attr(), relay_thread_worker
, nullptr);
4504 PERROR("pthread_create worker");
4506 goto exit_worker_thread
;
4509 /* Setup the listener thread */
4510 ret
= pthread_create(
4511 &listener_thread
, default_pthread_attr(), relay_thread_listener
, (void *) nullptr);
4514 PERROR("pthread_create listener");
4516 goto exit_listener_thread
;
4519 ret
= relayd_live_create(live_uri
);
4521 ERR("Starting live viewer threads");
4527 * This is where we start awaiting program completion (e.g. through
4528 * signal that asks threads to teardown).
4531 ret
= relayd_live_join();
4537 ret
= pthread_join(listener_thread
, &status
);
4540 PERROR("pthread_join listener_thread");
4544 exit_listener_thread
:
4545 ret
= pthread_join(worker_thread
, &status
);
4548 PERROR("pthread_join worker_thread");
4553 ret
= pthread_join(dispatcher_thread
, &status
);
4556 PERROR("pthread_join dispatcher_thread");
4559 exit_dispatcher_thread
:
4561 ret
= pthread_join(health_thread
, &status
);
4564 PERROR("pthread_join health_thread");
4569 * Wait for all pending call_rcu work to complete before tearing
4570 * down data structures. call_rcu worker may be trying to
4571 * perform lookups in those structures.
4576 /* Ensure all prior call_rcu are done. */
4579 if (thread_is_rcu_registered
) {
4580 rcu_unregister_thread();