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-stream.hpp"
30 #include <common/align.hpp>
31 #include <common/buffer-view.hpp>
32 #include <common/common.hpp>
33 #include <common/compat/endian.hpp>
34 #include <common/compat/getenv.hpp>
35 #include <common/compat/poll.hpp>
36 #include <common/compat/socket.hpp>
37 #include <common/daemonize.hpp>
38 #include <common/defaults.hpp>
39 #include <common/dynamic-buffer.hpp>
40 #include <common/fd-tracker/fd-tracker.hpp>
41 #include <common/fd-tracker/utils.hpp>
42 #include <common/futex.hpp>
43 #include <common/ini-config/ini-config.hpp>
44 #include <common/path.hpp>
45 #include <common/sessiond-comm/inet.hpp>
46 #include <common/sessiond-comm/relayd.hpp>
47 #include <common/sessiond-comm/sessiond-comm.hpp>
48 #include <common/string-utils/format.hpp>
49 #include <common/uri.hpp>
50 #include <common/utils.hpp>
52 #include <lttng/lttng.h>
68 #include <sys/mount.h>
69 #include <sys/resource.h>
70 #include <sys/socket.h>
72 #include <sys/types.h>
75 #include <urcu/futex.h>
76 #include <urcu/rculist.h>
77 #include <urcu/uatomic.h>
79 static const char *help_msg
=
80 #ifdef LTTNG_EMBED_HELP
81 #include <lttng-relayd.8.h>
87 enum relay_connection_status
{
88 RELAY_CONNECTION_STATUS_OK
,
89 /* An error occurred while processing an event on the connection. */
90 RELAY_CONNECTION_STATUS_ERROR
,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED
,
95 /* command line options */
96 char *opt_output_path
, *opt_working_directory
;
97 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
98 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
100 /* Argument variables */
101 int lttng_opt_quiet
; /* not static in error.h */
102 int lttng_opt_verbose
; /* not static in error.h */
103 int lttng_opt_mi
; /* not static in error.h */
106 * We need to wait for listener and live listener threads, as well as
107 * health check thread, before being ready to signal readiness.
109 #define NR_LTTNG_RELAY_READY 3
110 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
112 /* Size of receive buffer. */
113 #define RECV_DATA_BUFFER_SIZE 65536
115 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
116 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
118 static struct lttng_uri
*control_uri
;
119 static struct lttng_uri
*data_uri
;
120 static struct lttng_uri
*live_uri
;
122 const char *progname
;
124 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
125 static int tracing_group_name_override
;
127 const char *const config_section_name
= "relayd";
130 * This pipe is used to inform the worker thread that a command is queued and
131 * ready to be processed.
133 static int relay_conn_pipe
[2] = { -1, -1 };
135 /* Shared between threads */
136 static int dispatch_thread_exit
;
138 static pthread_t listener_thread
;
139 static pthread_t dispatcher_thread
;
140 static pthread_t worker_thread
;
141 static pthread_t health_thread
;
144 * last_relay_stream_id_lock protects last_relay_stream_id increment
145 * atomicity on 32-bit architectures.
147 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
148 static uint64_t last_relay_stream_id
;
151 * Relay command queue.
153 * The relay_thread_listener and relay_thread_dispatcher communicate with this
156 static struct relay_conn_queue relay_conn_queue
;
158 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
159 static unsigned int lttng_opt_fd_pool_size
= -1;
161 /* Global relay stream hash table. */
162 struct lttng_ht
*relay_streams_ht
;
164 /* Global relay viewer stream hash table. */
165 struct lttng_ht
*viewer_streams_ht
;
167 /* Global relay sessions hash table. */
168 struct lttng_ht
*sessions_ht
;
170 /* Relayd health monitoring */
171 struct health_app
*health_relayd
;
173 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
175 /* Global fd tracker. */
176 struct fd_tracker
*the_fd_tracker
;
178 static struct option long_options
[] = {
239 { "config", 1, nullptr, 'f' },
240 { "version", 0, nullptr, 'V' },
248 "group-output-by-session",
254 "group-output-by-host",
259 { "disallow-clear", 0, nullptr, 'x' },
268 static const char *config_ignore_options
[] = { "help", "config", "version" };
270 static void print_version()
272 fprintf(stdout
, "%s\n", VERSION
);
275 static void relayd_config_log()
277 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
278 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
279 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
280 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
281 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
283 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
284 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
289 * Take an option from the getopt output and set it in the right variable to be
292 * Return 0 on success else a negative value.
294 static int set_option(int opt
, const char *arg
, const char *optname
)
300 if (!strcmp(optname
, "fd-pool-size")) {
304 v
= strtoul(arg
, nullptr, 0);
305 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
306 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
311 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s",
316 lttng_opt_fd_pool_size
= (unsigned int) v
;
318 fprintf(stderr
, "unknown option %s", optname
);
320 fprintf(stderr
, " with arg %s\n", arg
);
325 if (lttng_is_setuid_setgid()) {
326 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
327 "-C, --control-port");
329 ret
= uri_parse(arg
, &control_uri
);
331 ERR("Invalid control URI specified");
334 if (control_uri
->port
== 0) {
335 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
340 if (lttng_is_setuid_setgid()) {
341 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
344 ret
= uri_parse(arg
, &data_uri
);
346 ERR("Invalid data URI specified");
349 if (data_uri
->port
== 0) {
350 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
355 if (lttng_is_setuid_setgid()) {
356 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
359 ret
= uri_parse(arg
, &live_uri
);
361 ERR("Invalid live URI specified");
364 if (live_uri
->port
== 0) {
365 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
376 if (lttng_is_setuid_setgid()) {
377 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
380 tracing_group_name
= strdup(arg
);
381 if (tracing_group_name
== nullptr) {
386 tracing_group_name_override
= 1;
390 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
392 ERR("Cannot show --help for `lttng-relayd`");
397 opt_print_version
= 1;
400 if (lttng_is_setuid_setgid()) {
401 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
404 ret
= asprintf(&opt_output_path
, "%s", arg
);
407 PERROR("asprintf opt_output_path");
413 if (lttng_is_setuid_setgid()) {
414 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
415 "-w, --working-directory");
417 ret
= asprintf(&opt_working_directory
, "%s", arg
);
420 PERROR("asprintf opt_working_directory");
427 /* Verbose level can increase using multiple -v */
429 lttng_opt_verbose
= config_parse_value(arg
);
431 /* Only 3 level of verbosity (-vvv). */
432 if (lttng_opt_verbose
< 3) {
433 lttng_opt_verbose
+= 1;
438 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
439 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
442 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
445 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
446 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
449 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
456 /* Unknown option or other error.
457 * Error is printed by getopt, just return */
470 * config_entry_handler_cb used to handle options read from a config file.
471 * See config_entry_handler_cb comment in common/config/session-config.h for the
472 * return value conventions.
474 static int config_entry_handler(const struct config_entry
*entry
,
475 void *unused
__attribute__((unused
)))
479 if (!entry
|| !entry
->name
|| !entry
->value
) {
484 /* Check if the option is to be ignored */
485 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
486 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
491 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
492 /* Ignore if entry name is not fully matched. */
493 if (strcmp(entry
->name
, long_options
[i
].name
) != 0) {
498 * If the option takes no argument on the command line,
499 * we have to check if the value is "true". We support
500 * non-zero numeric values, true, on and yes.
502 if (!long_options
[i
].has_arg
) {
503 ret
= config_parse_value(entry
->value
);
506 WARN("Invalid configuration value \"%s\" for option %s",
510 /* False, skip boolean config option. */
515 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
519 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
525 static int parse_env_options()
528 char *value
= nullptr;
530 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
532 opt_working_directory
= strdup(value
);
533 if (!opt_working_directory
) {
534 ERR("Failed to allocate working directory string (\"%s\")", value
);
541 static int set_fd_pool_size()
544 struct rlimit rlimit
;
546 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
548 PERROR("Failed to get file descriptor limit");
553 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
554 (uint64_t) rlimit
.rlim_cur
,
555 (uint64_t) rlimit
.rlim_max
);
556 if (lttng_opt_fd_pool_size
== -1) {
557 /* Use default value (soft limit - reserve). */
558 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
559 ERR("The process' file number limit is too low (%" PRIu64
560 "). The process' file number limit must be set to at least %i.",
561 (uint64_t) rlimit
.rlim_cur
,
562 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
566 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
570 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
571 ERR("File descriptor pool size must be set to at least %d",
572 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
577 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
578 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
580 lttng_opt_fd_pool_size
,
581 (uint64_t) rlimit
.rlim_cur
);
586 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
587 lttng_opt_fd_pool_size
,
588 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
589 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
594 static int set_options(int argc
, char **argv
)
596 int c
, ret
= 0, option_index
= 0, retval
= 0;
597 int orig_optopt
= optopt
, orig_optind
= optind
;
598 char *default_address
, *optstring
;
599 char *config_path
= nullptr;
601 optstring
= utils_generate_optstring(long_options
,
602 sizeof(long_options
) / sizeof(struct option
));
608 /* Check for the --config option */
610 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
)) != -1) {
614 } else if (c
!= 'f') {
618 if (lttng_is_setuid_setgid()) {
619 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
623 config_path
= utils_expand_path(optarg
);
625 ERR("Failed to resolve path: %s", optarg
);
630 ret
= config_get_section_entries(
631 config_path
, config_section_name
, config_entry_handler
, nullptr);
634 ERR("Invalid configuration option at line %i", ret
);
640 /* Reset getopt's global state */
641 optopt
= orig_optopt
;
642 optind
= orig_optind
;
644 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
649 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
656 /* assign default values */
657 if (control_uri
== nullptr) {
658 ret
= asprintf(&default_address
,
659 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
660 DEFAULT_NETWORK_CONTROL_PORT
);
662 PERROR("asprintf default data address");
667 ret
= uri_parse(default_address
, &control_uri
);
668 free(default_address
);
670 ERR("Invalid control URI specified");
675 if (data_uri
== nullptr) {
676 ret
= asprintf(&default_address
,
677 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
678 DEFAULT_NETWORK_DATA_PORT
);
680 PERROR("asprintf default data address");
685 ret
= uri_parse(default_address
, &data_uri
);
686 free(default_address
);
688 ERR("Invalid data URI specified");
693 if (live_uri
== nullptr) {
694 ret
= asprintf(&default_address
,
695 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
696 DEFAULT_NETWORK_VIEWER_PORT
);
698 PERROR("asprintf default viewer control address");
703 ret
= uri_parse(default_address
, &live_uri
);
704 free(default_address
);
706 ERR("Invalid viewer control URI specified");
711 ret
= set_fd_pool_size();
717 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
718 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
720 if (opt_allow_clear
) {
721 /* Check if env variable exists. */
722 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
724 ret
= config_parse_value(value
);
726 ERR("Invalid value for %s specified",
727 DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
731 opt_allow_clear
= !ret
;
741 static void print_global_objects()
743 print_viewer_streams();
744 print_relay_streams();
748 static int noop_close(void *data
__attribute__((unused
)), int *fds
__attribute__((unused
)))
753 static void untrack_stdio()
755 int fds
[] = { fileno(stdout
), fileno(stderr
) };
758 * noop_close is used since we don't really want to close
759 * the stdio output fds; we merely want to stop tracking them.
761 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
, fds
, 2, noop_close
, nullptr);
767 static void relayd_cleanup()
769 print_global_objects();
773 if (viewer_streams_ht
)
774 lttng_ht_destroy(viewer_streams_ht
);
775 if (relay_streams_ht
)
776 lttng_ht_destroy(relay_streams_ht
);
778 lttng_ht_destroy(sessions_ht
);
780 free(opt_output_path
);
781 free(opt_working_directory
);
784 health_app_destroy(health_relayd
);
786 /* Close thread quit pipes */
787 if (health_quit_pipe
[0] != -1) {
788 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
790 relayd_close_thread_quit_pipe();
791 if (sessiond_trace_chunk_registry
) {
792 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
794 if (the_fd_tracker
) {
797 * fd_tracker_destroy() will log the contents of the fd-tracker
798 * if a leak is detected.
800 fd_tracker_destroy(the_fd_tracker
);
803 uri_free(control_uri
);
805 /* Live URI is freed in the live thread. */
807 if (tracing_group_name_override
) {
808 free((void *) tracing_group_name
);
812 static int notify_health_quit_pipe(int *pipe
)
816 ret
= lttng_write(pipe
[1], "4", 1);
818 PERROR("write relay health quit");
827 * Stop all relayd and relayd-live threads.
829 int lttng_relay_stop_threads()
833 /* Stopping all threads */
834 DBG("Terminating all threads");
835 if (relayd_notify_thread_quit_pipe()) {
836 ERR("write error on thread quit pipe");
840 if (notify_health_quit_pipe(health_quit_pipe
)) {
841 ERR("write error on health quit pipe");
844 /* Dispatch thread */
845 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
846 futex_nto1_wake(&relay_conn_queue
.futex
);
848 if (relayd_live_stop()) {
849 ERR("Error stopping live threads");
856 * Signal handler for the daemon
858 * Simply stop all worker threads, leaving main() return gracefully after
859 * joining all threads and calling cleanup().
861 static void sighandler(int sig
)
865 DBG("SIGINT caught");
866 if (lttng_relay_stop_threads()) {
867 ERR("Error stopping threads");
871 DBG("SIGTERM caught");
872 if (lttng_relay_stop_threads()) {
873 ERR("Error stopping threads");
877 CMM_STORE_SHARED(recv_child_signal
, 1);
885 * Setup signal handler for :
886 * SIGINT, SIGTERM, SIGPIPE
888 static int set_signal_handler()
894 if ((ret
= sigemptyset(&sigset
)) < 0) {
895 PERROR("sigemptyset");
902 sa
.sa_handler
= sighandler
;
903 if ((ret
= sigaction(SIGTERM
, &sa
, nullptr)) < 0) {
908 if ((ret
= sigaction(SIGINT
, &sa
, nullptr)) < 0) {
913 if ((ret
= sigaction(SIGUSR1
, &sa
, nullptr)) < 0) {
918 sa
.sa_handler
= SIG_IGN
;
919 if ((ret
= sigaction(SIGPIPE
, &sa
, nullptr)) < 0) {
924 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
929 void lttng_relay_notify_ready()
931 /* Notify the parent of the fork() process that we are ready. */
932 if (opt_daemon
|| opt_background
) {
933 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
934 kill(child_ppid
, SIGUSR1
);
940 * Init health quit pipe.
942 * Return -1 on error or 0 if all pipes are created.
944 static int init_health_quit_pipe()
946 return fd_tracker_util_pipe_open_cloexec(
947 the_fd_tracker
, "Health quit pipe", health_quit_pipe
);
950 static int create_sock(void *data
, int *out_fd
)
953 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
955 ret
= lttcomm_create_sock(sock
);
965 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
967 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
969 return sock
->ops
->close(sock
);
972 static int accept_sock(void *data
, int *out_fd
)
975 /* Socks is an array of in_sock, out_sock. */
976 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
977 struct lttcomm_sock
*in_sock
= socks
[0];
979 socks
[1] = in_sock
->ops
->accept(in_sock
);
984 *out_fd
= socks
[1]->fd
;
990 * Create and init socket from uri.
992 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
, const char *name
)
995 struct lttcomm_sock
*sock
= nullptr;
996 char uri_str
[PATH_MAX
];
997 char *formated_name
= nullptr;
999 sock
= lttcomm_alloc_sock_from_uri(uri
);
1000 if (sock
== nullptr) {
1001 ERR("Allocating socket");
1006 * Don't fail to create the socket if the name can't be built as it is
1007 * only used for debugging purposes.
1009 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1010 uri_str
[sizeof(uri_str
) - 1] = '\0';
1012 ret
= asprintf(&formated_name
, "%s socket @ %s", name
, uri_str
);
1014 formated_name
= nullptr;
1018 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
,
1020 (const char **) (formated_name
? &formated_name
:
1026 PERROR("Failed to open \"%s\" relay socket", formated_name
?: "Unknown");
1029 DBG("Listening on %s socket %d", name
, sock
->fd
);
1031 ret
= sock
->ops
->bind(sock
);
1033 PERROR("Failed to bind socket");
1037 ret
= sock
->ops
->listen(sock
, -1);
1042 free(formated_name
);
1047 lttcomm_destroy_sock(sock
);
1049 free(formated_name
);
1053 static struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1057 struct lttcomm_sock
*socks
[2] = { listening_sock
, nullptr };
1058 struct lttcomm_sock
*new_sock
= nullptr;
1060 ret
= fd_tracker_open_unsuspendable_fd(
1061 the_fd_tracker
, &out_fd
, (const char **) &name
, 1, accept_sock
, &socks
);
1065 new_sock
= socks
[1];
1066 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1072 * This thread manages the listening for new connections on the network
1074 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1076 int i
, ret
, err
= -1;
1078 struct lttng_poll_event events
;
1079 struct lttcomm_sock
*control_sock
, *data_sock
;
1081 DBG("[thread] Relay listener started");
1083 rcu_register_thread();
1084 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1086 health_code_update();
1088 control_sock
= relay_socket_create(control_uri
, "Control listener");
1089 if (!control_sock
) {
1090 goto error_sock_control
;
1093 data_sock
= relay_socket_create(data_uri
, "Data listener");
1095 goto error_sock_relay
;
1099 * Pass 3 as size here for the thread quit pipe, control and
1102 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1104 goto error_create_poll
;
1107 /* Add the control socket */
1108 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1110 goto error_poll_add
;
1113 /* Add the data socket */
1114 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1116 goto error_poll_add
;
1119 lttng_relay_notify_ready();
1121 if (testpoint(relayd_thread_listener
)) {
1122 goto error_testpoint
;
1126 health_code_update();
1128 DBG("Listener accepting connections");
1131 health_poll_entry();
1132 ret
= lttng_poll_wait(&events
, -1);
1136 * Restart interrupted system call.
1138 if (errno
== EINTR
) {
1146 DBG("Relay new connection received");
1147 for (i
= 0; i
< nb_fd
; i
++) {
1148 /* Fetch once the poll data */
1149 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
1150 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1152 health_code_update();
1154 /* Activity on thread quit pipe, exiting. */
1155 if (relayd_is_thread_quit_pipe(pollfd
)) {
1156 DBG("Activity on thread quit pipe");
1161 if (revents
& LPOLLIN
) {
1163 * A new connection is requested, therefore a
1164 * sessiond/consumerd connection is allocated in
1165 * this thread, enqueued to a global queue and
1166 * dequeued (and freed) in the worker thread.
1169 struct relay_connection
*new_conn
;
1170 struct lttcomm_sock
*newsock
= nullptr;
1171 enum connection_type type
;
1173 if (pollfd
== data_sock
->fd
) {
1175 newsock
= accept_relayd_sock(data_sock
,
1176 "Data socket to relayd");
1178 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1179 type
= RELAY_CONTROL
;
1180 newsock
= accept_relayd_sock(control_sock
,
1181 "Control socket to relayd");
1184 PERROR("accepting sock");
1189 newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1191 PERROR("setsockopt inet");
1192 lttcomm_destroy_sock(newsock
);
1196 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1198 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1200 lttcomm_destroy_sock(newsock
);
1204 new_conn
= connection_create(newsock
, type
);
1206 lttcomm_destroy_sock(newsock
);
1210 /* Enqueue request for the dispatcher thread. */
1211 cds_wfcq_head_ptr_t head
;
1212 head
.h
= &relay_conn_queue
.head
;
1213 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
, &new_conn
->qnode
);
1216 * Wake the dispatch queue futex.
1217 * Implicit memory barrier with the
1218 * exchange in cds_wfcq_enqueue.
1220 futex_nto1_wake(&relay_conn_queue
.futex
);
1221 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1222 ERR("socket poll error");
1225 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1235 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1237 if (data_sock
->fd
>= 0) {
1238 int data_sock_fd
= data_sock
->fd
;
1240 ret
= fd_tracker_close_unsuspendable_fd(
1241 the_fd_tracker
, &data_sock_fd
, 1, close_sock
, data_sock
);
1243 PERROR("Failed to close the data listener socket file descriptor");
1247 lttcomm_destroy_sock(data_sock
);
1249 if (control_sock
->fd
>= 0) {
1250 int control_sock_fd
= control_sock
->fd
;
1252 ret
= fd_tracker_close_unsuspendable_fd(
1253 the_fd_tracker
, &control_sock_fd
, 1, close_sock
, control_sock
);
1255 PERROR("Failed to close the control listener socket file descriptor");
1257 control_sock
->fd
= -1;
1259 lttcomm_destroy_sock(control_sock
);
1263 ERR("Health error occurred in %s", __func__
);
1265 health_unregister(health_relayd
);
1266 rcu_unregister_thread();
1267 DBG("Relay listener thread cleanup complete");
1268 lttng_relay_stop_threads();
1273 * This thread manages the dispatching of the requests to worker threads
1275 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1279 struct cds_wfcq_node
*node
;
1280 struct relay_connection
*new_conn
= nullptr;
1282 DBG("[thread] Relay dispatcher started");
1284 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1286 if (testpoint(relayd_thread_dispatcher
)) {
1287 goto error_testpoint
;
1290 health_code_update();
1293 health_code_update();
1295 /* Atomically prepare the queue futex */
1296 futex_nto1_prepare(&relay_conn_queue
.futex
);
1298 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1303 health_code_update();
1305 /* Dequeue commands */
1306 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1307 &relay_conn_queue
.tail
);
1308 if (node
== nullptr) {
1309 DBG("Woken up but nothing in the relay command queue");
1310 /* Continue thread execution */
1313 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1315 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1318 * Inform worker thread of the new request. This
1319 * call is blocking so we can be assured that
1320 * the data will be read at some point in time
1321 * or wait to the end of the world :)
1323 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
)); /* NOLINT
1330 PERROR("write connection pipe");
1331 connection_put(new_conn
);
1334 } while (node
!= nullptr);
1336 /* Futex wait on queue. Blocking call on futex() */
1337 health_poll_entry();
1338 futex_nto1_wait(&relay_conn_queue
.futex
);
1342 /* Normal exit, no error */
1349 ERR("Health error occurred in %s", __func__
);
1351 health_unregister(health_relayd
);
1352 DBG("Dispatch thread dying");
1353 lttng_relay_stop_threads();
1357 static bool session_streams_have_index(const struct relay_session
*session
)
1359 return session
->minor
>= 4 && !session
->snapshot
;
1363 * Handle the RELAYD_CREATE_SESSION command.
1365 * On success, send back the session id or else return a negative value.
1367 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1368 struct relay_connection
*conn
,
1369 const struct lttng_buffer_view
*payload
)
1373 struct relay_session
*session
= nullptr;
1374 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1375 char session_name
[LTTNG_NAME_MAX
] = {};
1376 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1377 uint32_t live_timer
= 0;
1378 bool snapshot
= false;
1379 bool session_name_contains_creation_timestamp
= false;
1380 /* Left nil for peers < 2.11. */
1381 char base_path
[LTTNG_PATH_MAX
] = {};
1382 lttng_uuid sessiond_uuid
= {};
1383 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1384 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1385 LTTNG_OPTIONAL(time_t) creation_time
= {};
1386 struct lttng_dynamic_buffer reply_payload
;
1388 lttng_dynamic_buffer_init(&reply_payload
);
1390 if (conn
->minor
< 4) {
1391 /* From 2.1 to 2.3 */
1393 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1394 /* From 2.4 to 2.10 */
1395 ret
= cmd_create_session_2_4(
1396 payload
, session_name
, hostname
, &live_timer
, &snapshot
);
1398 bool has_current_chunk
;
1399 uint64_t current_chunk_id_value
;
1400 time_t creation_time_value
;
1401 uint64_t id_sessiond_value
;
1403 /* From 2.11 to ... */
1404 ret
= cmd_create_session_2_11(payload
,
1413 ¤t_chunk_id_value
,
1414 &creation_time_value
,
1415 &session_name_contains_creation_timestamp
);
1416 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1417 /* The nil UUID is reserved for pre-2.11 clients. */
1418 ERR("Illegal nil UUID announced by peer in create session command");
1422 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1423 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1424 if (has_current_chunk
) {
1425 LTTNG_OPTIONAL_SET(¤t_chunk_id
, current_chunk_id_value
);
1433 session
= session_create(session_name
,
1439 id_sessiond
.is_set
? &id_sessiond
.value
: nullptr,
1440 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: nullptr,
1441 creation_time
.is_set
? &creation_time
.value
: nullptr,
1444 session_name_contains_creation_timestamp
);
1449 LTTNG_ASSERT(!conn
->session
);
1450 conn
->session
= session
;
1451 DBG("Created session %" PRIu64
, session
->id
);
1453 reply
.generic
.session_id
= htobe64(session
->id
);
1457 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1459 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1462 if (conn
->minor
< 11) {
1463 /* From 2.1 to 2.10 */
1464 ret
= lttng_dynamic_buffer_append(
1465 &reply_payload
, &reply
.generic
, sizeof(reply
.generic
));
1467 ERR("Failed to append \"create session\" command reply header to payload buffer");
1472 const uint32_t output_path_length
= session
? strlen(session
->output_path
) + 1 : 0;
1474 reply
.output_path_length
= htobe32(output_path_length
);
1475 ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
1477 ERR("Failed to append \"create session\" command reply header to payload buffer");
1481 if (output_path_length
) {
1482 ret
= lttng_dynamic_buffer_append(
1483 &reply_payload
, session
->output_path
, output_path_length
);
1485 ERR("Failed to append \"create session\" command reply path to payload buffer");
1491 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
1492 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1493 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1499 if (ret
< 0 && session
) {
1500 session_put(session
);
1502 lttng_dynamic_buffer_reset(&reply_payload
);
1507 * When we have received all the streams and the metadata for a channel,
1508 * we make them visible to the viewer threads.
1510 static void publish_connection_local_streams(struct relay_connection
*conn
)
1512 struct relay_stream
*stream
;
1513 struct relay_session
*session
= conn
->session
;
1516 * We publish all streams belonging to a session atomically wrt
1519 pthread_mutex_lock(&session
->lock
);
1521 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
, recv_node
)
1523 stream_publish(stream
);
1528 * Inform the viewer that there are new streams in the session.
1530 if (session
->viewer_attached
) {
1531 uatomic_set(&session
->new_streams
, 1);
1533 pthread_mutex_unlock(&session
->lock
);
1536 static int conform_channel_path(char *channel_path
)
1540 if (strstr("../", channel_path
)) {
1541 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1547 if (*channel_path
== '/') {
1548 const size_t len
= strlen(channel_path
);
1551 * Channel paths from peers prior to 2.11 are expressed as an
1552 * absolute path that is, in reality, relative to the relay
1553 * daemon's output directory. Remove the leading slash so it
1554 * is correctly interpreted as a relative path later on.
1556 * len (and not len - 1) is used to copy the trailing NULL.
1558 bcopy(channel_path
+ 1, channel_path
, len
);
1565 * relay_add_stream: allocate a new stream for a session
1567 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1568 struct relay_connection
*conn
,
1569 const struct lttng_buffer_view
*payload
)
1573 struct relay_session
*session
= conn
->session
;
1574 struct relay_stream
*stream
= nullptr;
1575 struct lttcomm_relayd_status_stream reply
;
1576 struct ctf_trace
*trace
= nullptr;
1577 uint64_t stream_handle
= -1ULL;
1578 char *path_name
= nullptr, *channel_name
= nullptr;
1579 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1580 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1582 if (!session
|| !conn
->version_check_done
) {
1583 ERR("Trying to add a stream before version check");
1585 goto end_no_session
;
1588 if (session
->minor
== 1) {
1590 ret
= cmd_recv_stream_2_1(payload
, &path_name
, &channel_name
);
1591 } else if (session
->minor
> 1 && session
->minor
< 11) {
1592 /* From 2.2 to 2.10 */
1593 ret
= cmd_recv_stream_2_2(
1594 payload
, &path_name
, &channel_name
, &tracefile_size
, &tracefile_count
);
1596 /* From 2.11 to ... */
1597 ret
= cmd_recv_stream_2_11(payload
,
1602 &stream_chunk_id
.value
);
1603 stream_chunk_id
.is_set
= true;
1610 if (conform_channel_path(path_name
)) {
1615 * Backward compatibility for --group-output-by-session.
1616 * Prior to lttng 2.11, the complete path is passed by the stream.
1617 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1618 * >=2.11 the chunk is responsible for the output path. When dealing
1619 * with producer < 2.11 the chunk output_path is the root output path
1620 * and the stream carries the complete path (path_name).
1621 * To support --group-output-by-session with older producer (<2.11), we
1622 * need to craft the path based on the stream path.
1624 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1625 if (conn
->minor
< 4) {
1627 * From 2.1 to 2.3, the session_name is not passed on
1628 * the RELAYD_CREATE_SESSION command. The session name
1629 * is necessary to detect the presence of a base_path
1630 * inside the stream path. Without it we cannot perform
1631 * a valid group-output-by-session transformation.
1633 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1634 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1637 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1638 char *group_by_session_path_name
;
1640 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1642 group_by_session_path_name
= backward_compat_group_by_session(
1643 path_name
, session
->session_name
, session
->creation_time
.value
);
1644 if (!group_by_session_path_name
) {
1645 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1650 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1652 group_by_session_path_name
);
1655 path_name
= group_by_session_path_name
;
1659 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1664 /* This stream here has one reference on the trace. */
1665 pthread_mutex_lock(&last_relay_stream_id_lock
);
1666 stream_handle
= ++last_relay_stream_id
;
1667 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1669 /* We pass ownership of path_name and channel_name. */
1670 stream
= stream_create(
1671 trace
, stream_handle
, path_name
, channel_name
, tracefile_size
, tracefile_count
);
1672 path_name
= nullptr;
1673 channel_name
= nullptr;
1676 * Streams are the owners of their trace. Reference to trace is
1677 * kept within stream_create().
1679 ctf_trace_put(trace
);
1682 memset(&reply
, 0, sizeof(reply
));
1683 reply
.handle
= htobe64(stream_handle
);
1685 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1687 reply
.ret_code
= htobe32(LTTNG_OK
);
1690 send_ret
= conn
->sock
->ops
->sendmsg(
1691 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_status_stream
), 0);
1692 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1693 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret
);
1704 * relay_close_stream: close a specific stream
1706 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1707 struct relay_connection
*conn
,
1708 const struct lttng_buffer_view
*payload
)
1712 struct relay_session
*session
= conn
->session
;
1713 struct lttcomm_relayd_close_stream stream_info
;
1714 struct lttcomm_relayd_generic_reply reply
;
1715 struct relay_stream
*stream
;
1717 DBG("Close stream received");
1719 if (!session
|| !conn
->version_check_done
) {
1720 ERR("Trying to close a stream before version check");
1722 goto end_no_session
;
1725 if (payload
->size
< sizeof(stream_info
)) {
1726 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1727 sizeof(stream_info
),
1730 goto end_no_session
;
1732 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1733 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1734 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1736 stream
= stream_get_by_id(stream_info
.stream_id
);
1743 * Set last_net_seq_num before the close flag. Required by data
1746 pthread_mutex_lock(&stream
->lock
);
1747 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1748 pthread_mutex_unlock(&stream
->lock
);
1751 * This is one of the conditions which may trigger a stream close
1752 * with the others being:
1753 * 1) A close command is received for a stream
1754 * 2) The control connection owning the stream is closed
1755 * 3) We have received all of the stream's data _after_ a close
1758 try_stream_close(stream
);
1763 memset(&reply
, 0, sizeof(reply
));
1765 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1767 reply
.ret_code
= htobe32(LTTNG_OK
);
1769 send_ret
= conn
->sock
->ops
->sendmsg(
1770 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1771 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1772 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret
);
1781 * relay_reset_metadata: reset a metadata stream
1783 static int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1784 struct relay_connection
*conn
,
1785 const struct lttng_buffer_view
*payload
)
1789 struct relay_session
*session
= conn
->session
;
1790 struct lttcomm_relayd_reset_metadata stream_info
;
1791 struct lttcomm_relayd_generic_reply reply
;
1792 struct relay_stream
*stream
;
1794 DBG("Reset metadata received");
1796 if (!session
|| !conn
->version_check_done
) {
1797 ERR("Trying to reset a metadata stream before version check");
1799 goto end_no_session
;
1802 if (payload
->size
< sizeof(stream_info
)) {
1803 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1804 sizeof(stream_info
),
1807 goto end_no_session
;
1809 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1810 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1811 stream_info
.version
= be64toh(stream_info
.version
);
1813 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1815 /* Unsupported for live sessions for now. */
1816 if (session
->live_timer
!= 0) {
1821 stream
= stream_get_by_id(stream_info
.stream_id
);
1826 pthread_mutex_lock(&stream
->lock
);
1827 if (!stream
->is_metadata
) {
1832 ret
= stream_reset_file(stream
);
1834 ERR("Failed to reset metadata stream %" PRIu64
": stream_path = %s, channel = %s",
1835 stream
->stream_handle
,
1837 stream
->channel_name
);
1841 pthread_mutex_unlock(&stream
->lock
);
1845 memset(&reply
, 0, sizeof(reply
));
1847 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1849 reply
.ret_code
= htobe32(LTTNG_OK
);
1851 send_ret
= conn
->sock
->ops
->sendmsg(
1852 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1853 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1854 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret
);
1863 * relay_unknown_command: send -1 if received unknown command
1865 static void relay_unknown_command(struct relay_connection
*conn
)
1867 struct lttcomm_relayd_generic_reply reply
;
1870 memset(&reply
, 0, sizeof(reply
));
1871 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1872 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1873 if (send_ret
< sizeof(reply
)) {
1874 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1879 * relay_start: send an acknowledgment to the client to tell if we are
1880 * ready to receive data. We are ready if a session is established.
1882 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1883 struct relay_connection
*conn
,
1884 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1888 struct lttcomm_relayd_generic_reply reply
;
1889 struct relay_session
*session
= conn
->session
;
1892 DBG("Trying to start the streaming without a session established");
1893 ret
= htobe32(LTTNG_ERR_UNK
);
1896 memset(&reply
, 0, sizeof(reply
));
1897 reply
.ret_code
= htobe32(LTTNG_OK
);
1898 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1899 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1900 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret
);
1908 * relay_recv_metadata: receive the metadata for the session.
1910 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1911 struct relay_connection
*conn
,
1912 const struct lttng_buffer_view
*payload
)
1915 struct relay_session
*session
= conn
->session
;
1916 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1917 struct relay_stream
*metadata_stream
;
1918 uint64_t metadata_payload_size
;
1919 struct lttng_buffer_view packet_view
;
1922 ERR("Metadata sent before version check");
1927 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1928 ERR("Incorrect data size");
1932 metadata_payload_size
=
1933 recv_hdr
->data_size
- sizeof(struct lttcomm_relayd_metadata_payload
);
1935 memcpy(&metadata_payload_header
, payload
->data
, sizeof(metadata_payload_header
));
1936 metadata_payload_header
.stream_id
= be64toh(metadata_payload_header
.stream_id
);
1937 metadata_payload_header
.padding_size
= be32toh(metadata_payload_header
.padding_size
);
1939 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1940 if (!metadata_stream
) {
1945 packet_view
= lttng_buffer_view_from_view(
1946 payload
, sizeof(metadata_payload_header
), metadata_payload_size
);
1947 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1948 ERR("Invalid metadata packet length announced by header");
1953 pthread_mutex_lock(&metadata_stream
->lock
);
1954 ret
= stream_write(metadata_stream
, &packet_view
, metadata_payload_header
.padding_size
);
1955 pthread_mutex_unlock(&metadata_stream
->lock
);
1961 stream_put(metadata_stream
);
1967 * relay_send_version: send relayd version number
1969 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1970 struct relay_connection
*conn
,
1971 const struct lttng_buffer_view
*payload
)
1975 struct lttcomm_relayd_version reply
, msg
;
1976 bool compatible
= true;
1978 conn
->version_check_done
= true;
1980 /* Get version from the other side. */
1981 if (payload
->size
< sizeof(msg
)) {
1982 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1989 memcpy(&msg
, payload
->data
, sizeof(msg
));
1990 msg
.major
= be32toh(msg
.major
);
1991 msg
.minor
= be32toh(msg
.minor
);
1993 memset(&reply
, 0, sizeof(reply
));
1994 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1995 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1997 /* Major versions must be the same */
1998 if (reply
.major
!= msg
.major
) {
1999 DBG("Incompatible major versions (%u vs %u), deleting session",
2005 conn
->major
= reply
.major
;
2006 /* We adapt to the lowest compatible version */
2007 if (reply
.minor
<= msg
.minor
) {
2008 conn
->minor
= reply
.minor
;
2010 conn
->minor
= msg
.minor
;
2013 reply
.major
= htobe32(reply
.major
);
2014 reply
.minor
= htobe32(reply
.minor
);
2015 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2016 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2017 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret
);
2029 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
2036 * Check for data pending for a given stream id from the session daemon.
2038 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2039 struct relay_connection
*conn
,
2040 const struct lttng_buffer_view
*payload
)
2042 struct relay_session
*session
= conn
->session
;
2043 struct lttcomm_relayd_data_pending msg
;
2044 struct lttcomm_relayd_generic_reply reply
;
2045 struct relay_stream
*stream
;
2048 uint64_t stream_seq
;
2050 DBG("Data pending command received");
2052 if (!session
|| !conn
->version_check_done
) {
2053 ERR("Trying to check for data before version check");
2055 goto end_no_session
;
2058 if (payload
->size
< sizeof(msg
)) {
2059 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2063 goto end_no_session
;
2065 memcpy(&msg
, payload
->data
, sizeof(msg
));
2066 msg
.stream_id
= be64toh(msg
.stream_id
);
2067 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2069 stream
= stream_get_by_id(msg
.stream_id
);
2070 if (stream
== nullptr) {
2075 pthread_mutex_lock(&stream
->lock
);
2077 if (session_streams_have_index(session
)) {
2079 * Ensure that both the index and stream data have been
2080 * flushed up to the requested point.
2082 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2084 stream_seq
= stream
->prev_data_seq
;
2086 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2087 ", prev_index_seq %" PRIu64
", and last_seq %" PRIu64
,
2089 stream
->prev_data_seq
,
2090 stream
->prev_index_seq
,
2091 msg
.last_net_seq_num
);
2093 /* Avoid wrapping issue */
2094 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2095 /* Data has in fact been written and is NOT pending */
2098 /* Data still being streamed thus pending */
2102 stream
->data_pending_check_done
= true;
2103 pthread_mutex_unlock(&stream
->lock
);
2108 memset(&reply
, 0, sizeof(reply
));
2109 reply
.ret_code
= htobe32(ret
);
2110 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2111 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2112 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret
);
2121 * Wait for the control socket to reach a quiescent state.
2123 * Note that for now, when receiving this command from the session
2124 * daemon, this means that every subsequent commands or data received on
2125 * the control socket has been handled. So, this is why we simply return
2128 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
2129 __attribute__((unused
)),
2130 struct relay_connection
*conn
,
2131 const struct lttng_buffer_view
*payload
)
2135 struct relay_stream
*stream
;
2136 struct lttcomm_relayd_quiescent_control msg
;
2137 struct lttcomm_relayd_generic_reply reply
;
2139 DBG("Checking quiescent state on control socket");
2141 if (!conn
->session
|| !conn
->version_check_done
) {
2142 ERR("Trying to check for data before version check");
2144 goto end_no_session
;
2147 if (payload
->size
< sizeof(msg
)) {
2148 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2152 goto end_no_session
;
2154 memcpy(&msg
, payload
->data
, sizeof(msg
));
2155 msg
.stream_id
= be64toh(msg
.stream_id
);
2157 stream
= stream_get_by_id(msg
.stream_id
);
2161 pthread_mutex_lock(&stream
->lock
);
2162 stream
->data_pending_check_done
= true;
2163 pthread_mutex_unlock(&stream
->lock
);
2165 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2168 memset(&reply
, 0, sizeof(reply
));
2169 reply
.ret_code
= htobe32(LTTNG_OK
);
2170 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2171 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2172 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret
);
2183 * Initialize a data pending command. This means that a consumer is about
2184 * to ask for data pending for each stream it holds. Simply iterate over
2185 * all streams of a session and set the data_pending_check_done flag.
2187 * This command returns to the client a LTTNG_OK code.
2189 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2190 struct relay_connection
*conn
,
2191 const struct lttng_buffer_view
*payload
)
2195 struct lttng_ht_iter iter
;
2196 struct lttcomm_relayd_begin_data_pending msg
;
2197 struct lttcomm_relayd_generic_reply reply
;
2198 struct relay_stream
*stream
;
2200 LTTNG_ASSERT(recv_hdr
);
2203 DBG("Init streams for data pending");
2205 if (!conn
->session
|| !conn
->version_check_done
) {
2206 ERR("Trying to check for data before version check");
2208 goto end_no_session
;
2211 if (payload
->size
< sizeof(msg
)) {
2212 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2216 goto end_no_session
;
2218 memcpy(&msg
, payload
->data
, sizeof(msg
));
2219 msg
.session_id
= be64toh(msg
.session_id
);
2222 * Iterate over all streams to set the begin data pending flag.
2223 * For now, the streams are indexed by stream handle so we have
2224 * to iterate over all streams to find the one associated with
2225 * the right session_id.
2228 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2229 if (!stream_get(stream
)) {
2232 if (stream
->trace
->session
->id
== msg
.session_id
) {
2233 pthread_mutex_lock(&stream
->lock
);
2234 stream
->data_pending_check_done
= false;
2235 pthread_mutex_unlock(&stream
->lock
);
2236 DBG("Set begin data pending flag to stream %" PRIu64
,
2237 stream
->stream_handle
);
2243 memset(&reply
, 0, sizeof(reply
));
2244 /* All good, send back reply. */
2245 reply
.ret_code
= htobe32(LTTNG_OK
);
2247 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2248 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2249 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret
);
2260 * End data pending command. This will check, for a given session id, if
2261 * each stream associated with it has its data_pending_check_done flag
2262 * set. If not, this means that the client lost track of the stream but
2263 * the data is still being streamed on our side. In this case, we inform
2264 * the client that data is in flight.
2266 * Return to the client if there is data in flight or not with a ret_code.
2268 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2269 struct relay_connection
*conn
,
2270 const struct lttng_buffer_view
*payload
)
2274 struct lttng_ht_iter iter
;
2275 struct lttcomm_relayd_end_data_pending msg
;
2276 struct lttcomm_relayd_generic_reply reply
;
2277 struct relay_stream
*stream
;
2278 uint32_t is_data_inflight
= 0;
2280 DBG("End data pending command");
2282 if (!conn
->session
|| !conn
->version_check_done
) {
2283 ERR("Trying to check for data before version check");
2285 goto end_no_session
;
2288 if (payload
->size
< sizeof(msg
)) {
2289 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2293 goto end_no_session
;
2295 memcpy(&msg
, payload
->data
, sizeof(msg
));
2296 msg
.session_id
= be64toh(msg
.session_id
);
2299 * Iterate over all streams to see if the begin data pending
2303 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2304 if (!stream_get(stream
)) {
2307 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2311 pthread_mutex_lock(&stream
->lock
);
2312 if (!stream
->data_pending_check_done
) {
2313 uint64_t stream_seq
;
2315 if (session_streams_have_index(conn
->session
)) {
2317 * Ensure that both the index and stream data have been
2318 * flushed up to the requested point.
2321 std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2323 stream_seq
= stream
->prev_data_seq
;
2325 if (!stream
->closed
||
2326 !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2327 is_data_inflight
= 1;
2328 DBG("Data is still in flight for stream %" PRIu64
,
2329 stream
->stream_handle
);
2330 pthread_mutex_unlock(&stream
->lock
);
2335 pthread_mutex_unlock(&stream
->lock
);
2340 memset(&reply
, 0, sizeof(reply
));
2341 /* All good, send back reply. */
2342 reply
.ret_code
= htobe32(is_data_inflight
);
2344 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2345 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2346 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret
);
2357 * Receive an index for a specific stream.
2359 * Return 0 on success else a negative value.
2361 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2362 struct relay_connection
*conn
,
2363 const struct lttng_buffer_view
*payload
)
2367 struct relay_session
*session
= conn
->session
;
2368 struct lttcomm_relayd_index index_info
;
2369 struct lttcomm_relayd_generic_reply reply
;
2370 struct relay_stream
*stream
;
2375 DBG("Relay receiving index");
2377 if (!session
|| !conn
->version_check_done
) {
2378 ERR("Trying to close a stream before version check");
2380 goto end_no_session
;
2383 msg_len
= lttcomm_relayd_index_len(lttng_to_index_major(conn
->major
, conn
->minor
),
2384 lttng_to_index_minor(conn
->major
, conn
->minor
));
2385 if (payload
->size
< msg_len
) {
2386 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2390 goto end_no_session
;
2392 memcpy(&index_info
, payload
->data
, msg_len
);
2393 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2394 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2395 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2396 index_info
.content_size
= be64toh(index_info
.content_size
);
2397 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2398 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2399 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2400 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2402 if (conn
->minor
>= 8) {
2403 index_info
.stream_instance_id
= be64toh(index_info
.stream_instance_id
);
2404 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2406 index_info
.stream_instance_id
= -1ULL;
2407 index_info
.packet_seq_num
= -1ULL;
2410 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2412 ERR("stream_get_by_id not found");
2417 pthread_mutex_lock(&stream
->lock
);
2418 ret
= stream_add_index(stream
, &index_info
);
2419 pthread_mutex_unlock(&stream
->lock
);
2421 goto end_stream_put
;
2427 memset(&reply
, 0, sizeof(reply
));
2429 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2431 reply
.ret_code
= htobe32(LTTNG_OK
);
2433 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2434 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2435 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2444 * Receive the streams_sent message.
2446 * Return 0 on success else a negative value.
2448 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2449 struct relay_connection
*conn
,
2450 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2454 struct lttcomm_relayd_generic_reply reply
;
2458 DBG("Relay receiving streams_sent");
2460 if (!conn
->session
|| !conn
->version_check_done
) {
2461 ERR("Trying to close a stream before version check");
2463 goto end_no_session
;
2467 * Publish every pending stream in the connection recv list which are
2468 * now ready to be used by the viewer.
2470 publish_connection_local_streams(conn
);
2472 memset(&reply
, 0, sizeof(reply
));
2473 reply
.ret_code
= htobe32(LTTNG_OK
);
2474 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2475 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2476 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret
);
2488 relay_unpack_rotate_streams_header(const struct lttng_buffer_view
*payload
,
2489 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2491 struct lttcomm_relayd_rotate_streams rotate_streams
;
2493 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2494 * This is the smallest version of this structure, but it can be larger;
2495 * this variable is updated once the proper size of the structure is known.
2497 * See comment at the declaration of this structure for more information.
2499 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2500 size_t expected_payload_size_no_padding
, expected_payload_size_3_bytes_padding
,
2501 expected_payload_size_7_bytes_padding
;
2503 if (payload
->size
< header_len
) {
2504 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2511 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2512 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2514 * We start by "unpacking" `stream_count` to figure out the padding length
2515 * emited by our peer.
2518 decltype(rotate_streams
.stream_count
) stream_count
;
2520 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2521 rotate_streams
.stream_count
= be32toh(stream_count
);
2524 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2527 * Payload size expected given the possible padding lengths in
2528 * `struct lttcomm_relayd_rotate_streams`.
2530 expected_payload_size_no_padding
=
2531 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2532 sizeof(lttcomm_relayd_rotate_streams_packed
);
2533 expected_payload_size_3_bytes_padding
=
2534 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2535 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2536 expected_payload_size_7_bytes_padding
=
2537 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2538 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2540 if (payload
->size
== expected_payload_size_no_padding
) {
2541 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2544 * This handles cases where someone might build with
2545 * -fpack-struct or any other toolchain that wouldn't produce
2546 * padding to align `value`.
2548 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2550 header_len
= sizeof(packed_rotate_streams
);
2551 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2553 /* Unpack the packed structure to the natively-packed version. */
2554 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2555 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2556 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2558 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2559 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2560 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2562 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2564 header_len
= sizeof(padded_rotate_streams
);
2565 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2567 /* Unpack the 3-byte padded structure to the natively-packed version. */
2568 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2569 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2570 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2572 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2573 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2574 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2576 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2578 header_len
= sizeof(padded_rotate_streams
);
2579 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2581 /* Unpack the 7-byte padded structure to the natively-packed version. */
2582 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2583 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2584 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2586 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2588 header_len
= sizeof(padded_rotate_streams
);
2590 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2591 expected_payload_size_no_padding
,
2592 expected_payload_size_3_bytes_padding
,
2593 expected_payload_size_7_bytes_padding
,
2604 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2605 * session rotation feature (not the tracefile rotation feature).
2607 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr
*recv_hdr
2608 __attribute__((unused
)),
2609 struct relay_connection
*conn
,
2610 const struct lttng_buffer_view
*payload
)
2615 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2616 struct relay_session
*session
= conn
->session
;
2617 struct lttcomm_relayd_rotate_streams rotate_streams
;
2618 struct lttcomm_relayd_generic_reply reply
= {};
2619 struct relay_stream
*stream
= nullptr;
2620 struct lttng_trace_chunk
*next_trace_chunk
= nullptr;
2621 struct lttng_buffer_view stream_positions
;
2622 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2623 const char *chunk_id_str
= "none";
2626 if (!session
|| !conn
->version_check_done
) {
2627 ERR("Trying to rotate a stream before version check");
2632 if (session
->major
== 2 && session
->minor
< 11) {
2633 ERR("Unsupported feature before 2.11");
2638 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2639 if (header_len
< 0) {
2644 if (rotate_streams
.new_chunk_id
.is_set
) {
2646 * Retrieve the trace chunk the stream must transition to. As
2647 * per the protocol, this chunk should have been created
2648 * before this command is received.
2650 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2651 sessiond_trace_chunk_registry
,
2652 session
->sessiond_uuid
,
2653 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2655 rotate_streams
.new_chunk_id
.value
);
2656 if (!next_trace_chunk
) {
2657 char uuid_str
[LTTNG_UUID_STR_LEN
];
2659 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2660 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2661 ", trace_chunk_id = %" PRIu64
,
2664 rotate_streams
.new_chunk_id
.value
);
2665 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2670 ret
= snprintf(chunk_id_buf
,
2671 sizeof(chunk_id_buf
),
2673 rotate_streams
.new_chunk_id
.value
);
2674 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2675 chunk_id_str
= "formatting error";
2677 chunk_id_str
= chunk_id_buf
;
2681 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2682 rotate_streams
.stream_count
,
2683 session
->session_name
,
2686 stream_positions
= lttng_buffer_view_from_view(payload
, header_len
, -1);
2687 if (!stream_positions
.data
||
2688 stream_positions
.size
< (rotate_streams
.stream_count
*
2689 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2690 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2695 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2696 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2697 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2698 const struct lttcomm_relayd_stream_rotation_position pos
= {
2699 .stream_id
= be64toh(position_comm
->stream_id
),
2700 .rotate_at_seq_num
= be64toh(position_comm
->rotate_at_seq_num
),
2703 stream
= stream_get_by_id(pos
.stream_id
);
2705 reply_code
= LTTNG_ERR_INVALID
;
2710 pthread_mutex_lock(&stream
->lock
);
2711 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
, pos
.rotate_at_seq_num
);
2712 pthread_mutex_unlock(&stream
->lock
);
2714 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2722 reply_code
= LTTNG_OK
;
2729 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2730 send_ret
= conn
->sock
->ops
->sendmsg(
2731 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2732 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2733 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret
);
2737 lttng_trace_chunk_put(next_trace_chunk
);
2742 * relay_create_trace_chunk: create a new trace chunk
2744 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2745 __attribute__((unused
)),
2746 struct relay_connection
*conn
,
2747 const struct lttng_buffer_view
*payload
)
2751 struct relay_session
*session
= conn
->session
;
2752 struct lttcomm_relayd_create_trace_chunk
*msg
;
2753 struct lttcomm_relayd_generic_reply reply
= {};
2754 struct lttng_buffer_view header_view
;
2755 struct lttng_trace_chunk
*chunk
= nullptr, *published_chunk
= nullptr;
2756 enum lttng_error_code reply_code
= LTTNG_OK
;
2757 enum lttng_trace_chunk_status chunk_status
;
2758 const char *new_path
;
2760 if (!session
|| !conn
->version_check_done
) {
2761 ERR("Trying to create a trace chunk before version check");
2766 if (session
->major
== 2 && session
->minor
< 11) {
2767 ERR("Chunk creation command is unsupported before 2.11");
2772 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2773 if (!lttng_buffer_view_is_valid(&header_view
)) {
2774 ERR("Failed to receive payload of chunk creation command");
2779 /* Convert to host endianness. */
2780 msg
= (typeof(msg
)) header_view
.data
;
2781 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2782 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2783 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2785 pthread_mutex_lock(&conn
->session
->lock
);
2786 session
->ongoing_rotation
= true;
2787 if (session
->current_trace_chunk
&&
2788 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2789 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2790 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2791 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2792 ERR("Failed to rename old chunk");
2794 reply_code
= LTTNG_ERR_UNK
;
2798 if (!session
->current_trace_chunk
) {
2799 if (!session
->has_rotated
) {
2805 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2807 chunk
= lttng_trace_chunk_create(msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2809 ERR("Failed to create trace chunk in trace chunk creation command");
2811 reply_code
= LTTNG_ERR_NOMEM
;
2814 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2816 if (msg
->override_name_length
) {
2818 const struct lttng_buffer_view chunk_name_view
= lttng_buffer_view_from_view(
2819 payload
, sizeof(*msg
), msg
->override_name_length
);
2821 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2822 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2824 reply_code
= LTTNG_ERR_INVALID
;
2828 name
= chunk_name_view
.data
;
2829 if (name
[msg
->override_name_length
- 1]) {
2830 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2832 reply_code
= LTTNG_ERR_INVALID
;
2836 chunk_status
= lttng_trace_chunk_override_name(chunk
, chunk_name_view
.data
);
2837 switch (chunk_status
) {
2838 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2840 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2841 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2842 reply_code
= LTTNG_ERR_INVALID
;
2846 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2847 reply_code
= LTTNG_ERR_UNK
;
2853 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2854 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2855 reply_code
= LTTNG_ERR_UNK
;
2860 LTTNG_ASSERT(conn
->session
->output_directory
);
2861 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, conn
->session
->output_directory
);
2862 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2863 reply_code
= LTTNG_ERR_UNK
;
2868 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2869 sessiond_trace_chunk_registry
,
2870 conn
->session
->sessiond_uuid
,
2871 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2874 if (!published_chunk
) {
2875 char uuid_str
[LTTNG_UUID_STR_LEN
];
2877 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2878 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2879 ", chunk_id = %" PRIu64
,
2884 reply_code
= LTTNG_ERR_NOMEM
;
2888 if (conn
->session
->pending_closure_trace_chunk
) {
2890 * Invalid; this means a second create_trace_chunk command was
2891 * received before a close_trace_chunk.
2893 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2894 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2898 conn
->session
->pending_closure_trace_chunk
= conn
->session
->current_trace_chunk
;
2899 conn
->session
->current_trace_chunk
= published_chunk
;
2900 published_chunk
= nullptr;
2901 if (!conn
->session
->pending_closure_trace_chunk
) {
2902 session
->ongoing_rotation
= false;
2905 pthread_mutex_unlock(&conn
->session
->lock
);
2906 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2907 send_ret
= conn
->sock
->ops
->sendmsg(
2908 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2909 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2910 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
2914 lttng_trace_chunk_put(chunk
);
2915 lttng_trace_chunk_put(published_chunk
);
2920 * relay_close_trace_chunk: close a trace chunk
2922 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2923 __attribute__((unused
)),
2924 struct relay_connection
*conn
,
2925 const struct lttng_buffer_view
*payload
)
2927 int ret
= 0, buf_ret
;
2929 struct relay_session
*session
= conn
->session
;
2930 struct lttcomm_relayd_close_trace_chunk
*msg
;
2931 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2932 struct lttng_buffer_view header_view
;
2933 struct lttng_trace_chunk
*chunk
= nullptr;
2934 enum lttng_error_code reply_code
= LTTNG_OK
;
2935 enum lttng_trace_chunk_status chunk_status
;
2937 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2938 time_t close_timestamp
;
2939 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2940 size_t path_length
= 0;
2941 const char *chunk_name
= nullptr;
2942 struct lttng_dynamic_buffer reply_payload
;
2943 const char *new_path
;
2945 lttng_dynamic_buffer_init(&reply_payload
);
2947 if (!session
|| !conn
->version_check_done
) {
2948 ERR("Trying to close a trace chunk before version check");
2953 if (session
->major
== 2 && session
->minor
< 11) {
2954 ERR("Chunk close command is unsupported before 2.11");
2959 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2960 if (!lttng_buffer_view_is_valid(&header_view
)) {
2961 ERR("Failed to receive payload of chunk close command");
2966 /* Convert to host endianness. */
2967 msg
= (typeof(msg
)) header_view
.data
;
2968 chunk_id
= be64toh(msg
->chunk_id
);
2969 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2970 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2971 close_command
.is_set
= msg
->close_command
.is_set
;
2973 chunk
= sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry
,
2974 conn
->session
->sessiond_uuid
,
2975 conn
->session
->id_sessiond
.is_set
?
2976 conn
->session
->id_sessiond
.value
:
2980 char uuid_str
[LTTNG_UUID_STR_LEN
];
2982 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2983 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
2984 ", chunk_id = %" PRIu64
,
2989 reply_code
= LTTNG_ERR_NOMEM
;
2993 pthread_mutex_lock(&session
->lock
);
2994 if (close_command
.is_set
&& close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
2996 * Clear command. It is a protocol error to ask for a
2997 * clear on a relay which does not allow it. Querying
2998 * the configuration allows figuring out whether
2999 * clearing is allowed before doing the clear.
3001 if (!opt_allow_clear
) {
3003 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3004 goto end_unlock_session
;
3007 if (session
->pending_closure_trace_chunk
&& session
->pending_closure_trace_chunk
!= chunk
) {
3008 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3009 session
->session_name
);
3010 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3012 goto end_unlock_session
;
3015 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3016 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3017 if (close_command
.is_set
&&
3018 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3019 !session
->has_rotated
) {
3020 /* New chunk stays in session output directory. */
3023 /* Use chunk name for new chunk. */
3026 /* Rename new chunk path. */
3028 lttng_trace_chunk_rename_path(session
->current_trace_chunk
, new_path
);
3029 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3031 goto end_unlock_session
;
3033 session
->ongoing_rotation
= false;
3035 if ((!close_command
.is_set
||
3036 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3037 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3038 const char *old_path
;
3040 if (!session
->has_rotated
) {
3045 /* We need to move back the .tmp_old_chunk to its rightful place. */
3046 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3047 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3049 goto end_unlock_session
;
3052 chunk_status
= lttng_trace_chunk_set_close_timestamp(chunk
, close_timestamp
);
3053 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3054 ERR("Failed to set trace chunk close timestamp");
3056 reply_code
= LTTNG_ERR_UNK
;
3057 goto end_unlock_session
;
3060 if (close_command
.is_set
) {
3061 chunk_status
= lttng_trace_chunk_set_close_command(chunk
, close_command
.value
);
3062 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3064 reply_code
= LTTNG_ERR_INVALID
;
3065 goto end_unlock_session
;
3068 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, nullptr);
3069 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3070 ERR("Failed to get chunk name");
3072 reply_code
= LTTNG_ERR_UNK
;
3073 goto end_unlock_session
;
3075 if (!session
->has_rotated
&& !session
->snapshot
) {
3076 ret
= lttng_strncpy(closed_trace_chunk_path
,
3077 session
->output_path
,
3078 sizeof(closed_trace_chunk_path
));
3080 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3081 strlen(session
->output_path
),
3082 sizeof(closed_trace_chunk_path
));
3083 reply_code
= LTTNG_ERR_NOMEM
;
3085 goto end_unlock_session
;
3088 if (session
->snapshot
) {
3089 ret
= snprintf(closed_trace_chunk_path
,
3090 sizeof(closed_trace_chunk_path
),
3092 session
->output_path
,
3095 ret
= snprintf(closed_trace_chunk_path
,
3096 sizeof(closed_trace_chunk_path
),
3097 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
"/%s",
3098 session
->output_path
,
3101 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3102 ERR("Failed to format closed trace chunk resulting path");
3103 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3105 goto end_unlock_session
;
3108 if (close_command
.is_set
&&
3109 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3110 session
->has_rotated
= true;
3112 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3113 path_length
= strlen(closed_trace_chunk_path
) + 1;
3114 if (path_length
> UINT32_MAX
) {
3115 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3117 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3118 goto end_unlock_session
;
3121 if (session
->current_trace_chunk
== chunk
) {
3123 * After a trace chunk close command, no new streams
3124 * referencing the chunk may be created. Hence, on the
3125 * event that no new trace chunk have been created for
3126 * the session, the reference to the current trace chunk
3127 * is released in order to allow it to be reclaimed when
3128 * the last stream releases its reference to it.
3130 lttng_trace_chunk_put(session
->current_trace_chunk
);
3131 session
->current_trace_chunk
= nullptr;
3133 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3134 session
->pending_closure_trace_chunk
= nullptr;
3136 pthread_mutex_unlock(&session
->lock
);
3139 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3140 reply
.path_length
= htobe32((uint32_t) path_length
);
3141 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
3143 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3147 if (reply_code
== LTTNG_OK
) {
3148 buf_ret
= lttng_dynamic_buffer_append(
3149 &reply_payload
, closed_trace_chunk_path
, path_length
);
3151 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3156 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
3157 if (send_ret
< reply_payload
.size
) {
3158 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3165 lttng_trace_chunk_put(chunk
);
3166 lttng_dynamic_buffer_reset(&reply_payload
);
3171 * relay_trace_chunk_exists: check if a trace chunk exists
3173 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
3174 __attribute__((unused
)),
3175 struct relay_connection
*conn
,
3176 const struct lttng_buffer_view
*payload
)
3180 struct relay_session
*session
= conn
->session
;
3181 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3182 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3183 struct lttng_buffer_view header_view
;
3187 if (!session
|| !conn
->version_check_done
) {
3188 ERR("Trying to check for the presence of a trace chunk before version check");
3193 if (session
->major
== 2 && session
->minor
< 11) {
3194 ERR("Chunk exists command is unsupported before 2.11");
3199 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3200 if (!lttng_buffer_view_is_valid(&header_view
)) {
3201 ERR("Failed to receive payload of chunk exists command");
3206 /* Convert to host endianness. */
3207 msg
= (typeof(msg
)) header_view
.data
;
3208 chunk_id
= be64toh(msg
->chunk_id
);
3210 ret
= sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry
,
3211 conn
->session
->sessiond_uuid
,
3216 * If ret is not 0, send the reply and report the error to the caller.
3217 * It is a protocol (or internal) error and the session/connection
3218 * should be torn down.
3220 reply
.generic
.ret_code
=
3221 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3222 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3224 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3225 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3226 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
3234 * relay_get_configuration: query whether feature is available
3236 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
3237 __attribute__((unused
)),
3238 struct relay_connection
*conn
,
3239 const struct lttng_buffer_view
*payload
)
3243 struct lttcomm_relayd_get_configuration
*msg
;
3244 struct lttcomm_relayd_get_configuration_reply reply
= {};
3245 struct lttng_buffer_view header_view
;
3246 uint64_t query_flags
= 0;
3247 uint64_t result_flags
= 0;
3249 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3250 if (!lttng_buffer_view_is_valid(&header_view
)) {
3251 ERR("Failed to receive payload of chunk close command");
3256 /* Convert to host endianness. */
3257 msg
= (typeof(msg
)) header_view
.data
;
3258 query_flags
= be64toh(msg
->query_flags
);
3261 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3264 if (opt_allow_clear
) {
3265 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3269 reply
.generic
.ret_code
=
3270 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3271 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3273 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3274 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3275 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3282 static int relay_process_control_command(struct relay_connection
*conn
,
3283 const struct lttcomm_relayd_hdr
*header
,
3284 const struct lttng_buffer_view
*payload
)
3288 DBG3("Processing \"%s\" command for socket %i",
3289 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3291 switch (header
->cmd
) {
3292 case RELAYD_CREATE_SESSION
:
3293 ret
= relay_create_session(header
, conn
, payload
);
3295 case RELAYD_ADD_STREAM
:
3296 ret
= relay_add_stream(header
, conn
, payload
);
3298 case RELAYD_START_DATA
:
3299 ret
= relay_start(header
, conn
, payload
);
3301 case RELAYD_SEND_METADATA
:
3302 ret
= relay_recv_metadata(header
, conn
, payload
);
3304 case RELAYD_VERSION
:
3305 ret
= relay_send_version(header
, conn
, payload
);
3307 case RELAYD_CLOSE_STREAM
:
3308 ret
= relay_close_stream(header
, conn
, payload
);
3310 case RELAYD_DATA_PENDING
:
3311 ret
= relay_data_pending(header
, conn
, payload
);
3313 case RELAYD_QUIESCENT_CONTROL
:
3314 ret
= relay_quiescent_control(header
, conn
, payload
);
3316 case RELAYD_BEGIN_DATA_PENDING
:
3317 ret
= relay_begin_data_pending(header
, conn
, payload
);
3319 case RELAYD_END_DATA_PENDING
:
3320 ret
= relay_end_data_pending(header
, conn
, payload
);
3322 case RELAYD_SEND_INDEX
:
3323 ret
= relay_recv_index(header
, conn
, payload
);
3325 case RELAYD_STREAMS_SENT
:
3326 ret
= relay_streams_sent(header
, conn
, payload
);
3328 case RELAYD_RESET_METADATA
:
3329 ret
= relay_reset_metadata(header
, conn
, payload
);
3331 case RELAYD_ROTATE_STREAMS
:
3332 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3334 case RELAYD_CREATE_TRACE_CHUNK
:
3335 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3337 case RELAYD_CLOSE_TRACE_CHUNK
:
3338 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3340 case RELAYD_TRACE_CHUNK_EXISTS
:
3341 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3343 case RELAYD_GET_CONFIGURATION
:
3344 ret
= relay_get_configuration(header
, conn
, payload
);
3346 case RELAYD_UPDATE_SYNC_INFO
:
3348 ERR("Received unknown command (%u)", header
->cmd
);
3349 relay_unknown_command(conn
);
3358 static enum relay_connection_status
3359 relay_process_control_receive_payload(struct relay_connection
*conn
)
3362 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3363 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3364 struct ctrl_connection_state_receive_payload
*state
=
3365 &conn
->protocol
.ctrl
.state
.receive_payload
;
3366 struct lttng_buffer_view payload_view
;
3368 if (state
->left_to_receive
== 0) {
3369 /* Short-circuit for payload-less commands. */
3370 goto reception_complete
;
3373 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3374 reception_buffer
->data
+ state
->received
,
3375 state
->left_to_receive
,
3379 DIAGNOSTIC_IGNORE_LOGICAL_OP
3380 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3382 PERROR("Unable to receive command payload on sock %d", conn
->sock
->fd
);
3383 status
= RELAY_CONNECTION_STATUS_ERROR
;
3386 } else if (ret
== 0) {
3387 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3388 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3392 LTTNG_ASSERT(ret
> 0);
3393 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3395 state
->left_to_receive
-= ret
;
3396 state
->received
+= ret
;
3398 if (state
->left_to_receive
> 0) {
3400 * Can't transition to the protocol's next state, wait to
3401 * receive the rest of the header.
3403 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3404 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3406 state
->left_to_receive
,
3412 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3416 * The payload required to process the command has been received.
3417 * A view to the reception buffer is forwarded to the various
3418 * commands and the state of the control is reset on success.
3420 * Commands are responsible for sending their reply to the peer.
3422 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
, 0, -1);
3423 ret
= relay_process_control_command(conn
, &state
->header
, &payload_view
);
3425 status
= RELAY_CONNECTION_STATUS_ERROR
;
3429 ret
= connection_reset_protocol_state(conn
);
3431 status
= RELAY_CONNECTION_STATUS_ERROR
;
3437 static enum relay_connection_status
3438 relay_process_control_receive_header(struct relay_connection
*conn
)
3441 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3442 struct lttcomm_relayd_hdr header
;
3443 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3444 struct ctrl_connection_state_receive_header
*state
=
3445 &conn
->protocol
.ctrl
.state
.receive_header
;
3447 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3449 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3450 reception_buffer
->data
+ state
->received
,
3451 state
->left_to_receive
,
3455 DIAGNOSTIC_IGNORE_LOGICAL_OP
3456 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3458 PERROR("Unable to receive control command header on sock %d",
3460 status
= RELAY_CONNECTION_STATUS_ERROR
;
3463 } else if (ret
== 0) {
3464 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3465 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3469 LTTNG_ASSERT(ret
> 0);
3470 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3472 state
->left_to_receive
-= ret
;
3473 state
->received
+= ret
;
3475 if (state
->left_to_receive
> 0) {
3477 * Can't transition to the protocol's next state, wait to
3478 * receive the rest of the header.
3480 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3481 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3483 state
->left_to_receive
,
3488 /* Transition to next state: receiving the command's payload. */
3489 conn
->protocol
.ctrl
.state_id
= CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3490 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3491 header
.circuit_id
= be64toh(header
.circuit_id
);
3492 header
.data_size
= be64toh(header
.data_size
);
3493 header
.cmd
= be32toh(header
.cmd
);
3494 header
.cmd_version
= be32toh(header
.cmd_version
);
3495 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
, &header
, sizeof(header
));
3497 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3498 ", payload size = %" PRIu64
" bytes",
3500 lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3504 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3505 ERR("Command header indicates a payload (%" PRIu64
3506 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3508 status
= RELAY_CONNECTION_STATUS_ERROR
;
3512 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3513 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3514 ret
= lttng_dynamic_buffer_set_size(reception_buffer
, header
.data_size
);
3516 status
= RELAY_CONNECTION_STATUS_ERROR
;
3520 if (header
.data_size
== 0) {
3522 * Manually invoke the next state as the poll loop
3523 * will not wake-up to allow us to proceed further.
3525 status
= relay_process_control_receive_payload(conn
);
3532 * Process the commands received on the control socket
3534 static enum relay_connection_status
relay_process_control(struct relay_connection
*conn
)
3536 enum relay_connection_status status
;
3538 switch (conn
->protocol
.ctrl
.state_id
) {
3539 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3540 status
= relay_process_control_receive_header(conn
);
3542 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3543 status
= relay_process_control_receive_payload(conn
);
3546 ERR("Unknown control connection protocol state encountered.");
3553 static enum relay_connection_status
relay_process_data_receive_header(struct relay_connection
*conn
)
3556 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3557 struct data_connection_state_receive_header
*state
=
3558 &conn
->protocol
.data
.state
.receive_header
;
3559 struct lttcomm_relayd_data_hdr header
;
3560 struct relay_stream
*stream
;
3562 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3564 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3565 state
->header_reception_buffer
+ state
->received
,
3566 state
->left_to_receive
,
3570 DIAGNOSTIC_IGNORE_LOGICAL_OP
3571 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3573 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3574 status
= RELAY_CONNECTION_STATUS_ERROR
;
3577 } else if (ret
== 0) {
3578 /* Orderly shutdown. Not necessary to print an error. */
3579 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3580 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3584 LTTNG_ASSERT(ret
> 0);
3585 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3587 state
->left_to_receive
-= ret
;
3588 state
->received
+= ret
;
3590 if (state
->left_to_receive
> 0) {
3592 * Can't transition to the protocol's next state, wait to
3593 * receive the rest of the header.
3595 DBG3("Partial reception of data connection header (received %" PRIu64
3596 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3598 state
->left_to_receive
,
3603 /* Transition to next state: receiving the payload. */
3604 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3606 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3607 header
.circuit_id
= be64toh(header
.circuit_id
);
3608 header
.stream_id
= be64toh(header
.stream_id
);
3609 header
.data_size
= be32toh(header
.data_size
);
3610 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3611 header
.padding_size
= be32toh(header
.padding_size
);
3612 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3614 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3615 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3616 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3618 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3619 ", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
3620 ", padding_size = %" PRIu32
,
3626 header
.padding_size
);
3628 stream
= stream_get_by_id(header
.stream_id
);
3630 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3632 /* Protocol error. */
3633 status
= RELAY_CONNECTION_STATUS_ERROR
;
3637 pthread_mutex_lock(&stream
->lock
);
3638 /* Prepare stream for the reception of a new packet. */
3639 ret
= stream_init_packet(
3640 stream
, header
.data_size
, &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3641 pthread_mutex_unlock(&stream
->lock
);
3643 ERR("Failed to rotate stream output file");
3644 status
= RELAY_CONNECTION_STATUS_ERROR
;
3645 goto end_stream_unlock
;
3654 static enum relay_connection_status
3655 relay_process_data_receive_payload(struct relay_connection
*conn
)
3658 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3659 struct relay_stream
*stream
;
3660 struct data_connection_state_receive_payload
*state
=
3661 &conn
->protocol
.data
.state
.receive_payload
;
3662 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3663 char data_buffer
[chunk_size
];
3664 bool partial_recv
= false;
3665 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3666 uint64_t left_to_receive
= state
->left_to_receive
;
3667 struct relay_session
*session
;
3669 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
3670 " bytes received, %" PRIu64
" bytes left to receive",
3671 state
->header
.stream_id
,
3672 state
->header
.net_seq_num
,
3676 stream
= stream_get_by_id(state
->header
.stream_id
);
3678 /* Protocol error. */
3679 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3680 state
->header
.stream_id
);
3681 status
= RELAY_CONNECTION_STATUS_ERROR
;
3685 pthread_mutex_lock(&stream
->lock
);
3686 session
= stream
->trace
->session
;
3687 if (!conn
->session
) {
3688 ret
= connection_set_session(conn
, session
);
3690 status
= RELAY_CONNECTION_STATUS_ERROR
;
3691 goto end_stream_unlock
;
3696 * The size of the "chunk" received on any iteration is bounded by:
3697 * - the data left to receive,
3698 * - the data immediately available on the socket,
3699 * - the on-stack data buffer
3701 while (left_to_receive
> 0 && !partial_recv
) {
3702 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3703 struct lttng_buffer_view packet_chunk
;
3705 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, MSG_DONTWAIT
);
3708 DIAGNOSTIC_IGNORE_LOGICAL_OP
3709 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3711 PERROR("Socket %d error", conn
->sock
->fd
);
3712 status
= RELAY_CONNECTION_STATUS_ERROR
;
3714 goto end_stream_unlock
;
3715 } else if (ret
== 0) {
3716 /* No more data ready to be consumed on socket. */
3717 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3718 state
->header
.stream_id
);
3719 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3721 } else if (ret
< (int) recv_size
) {
3723 * All the data available on the socket has been
3726 partial_recv
= true;
3730 packet_chunk
= lttng_buffer_view_init(data_buffer
, 0, recv_size
);
3731 LTTNG_ASSERT(packet_chunk
.data
);
3733 ret
= stream_write(stream
, &packet_chunk
, 0);
3735 ERR("Relay error writing data to file");
3736 status
= RELAY_CONNECTION_STATUS_ERROR
;
3737 goto end_stream_unlock
;
3740 left_to_receive
-= recv_size
;
3741 state
->received
+= recv_size
;
3742 state
->left_to_receive
= left_to_receive
;
3745 if (state
->left_to_receive
> 0) {
3747 * Did not receive all the data expected, wait for more data to
3748 * become available on the socket.
3750 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
3751 " bytes received, %" PRIu64
" bytes left to receive",
3752 state
->header
.stream_id
,
3754 state
->left_to_receive
);
3755 goto end_stream_unlock
;
3758 ret
= stream_write(stream
, nullptr, state
->header
.padding_size
);
3760 status
= RELAY_CONNECTION_STATUS_ERROR
;
3761 goto end_stream_unlock
;
3764 if (session_streams_have_index(session
)) {
3765 ret
= stream_update_index(stream
,
3766 state
->header
.net_seq_num
,
3767 state
->rotate_index
,
3769 state
->header
.data_size
+ state
->header
.padding_size
);
3771 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
3773 stream
->stream_handle
,
3774 state
->header
.net_seq_num
,
3776 status
= RELAY_CONNECTION_STATUS_ERROR
;
3777 goto end_stream_unlock
;
3781 if (stream
->prev_data_seq
== -1ULL) {
3785 ret
= stream_complete_packet(stream
,
3786 state
->header
.data_size
+ state
->header
.padding_size
,
3787 state
->header
.net_seq_num
,
3790 status
= RELAY_CONNECTION_STATUS_ERROR
;
3791 goto end_stream_unlock
;
3795 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3796 * contents of *state which are aliased (union) to the same location as
3797 * the new state. Don't use it beyond this point.
3799 connection_reset_protocol_state(conn
);
3803 close_requested
= stream
->close_requested
;
3804 pthread_mutex_unlock(&stream
->lock
);
3805 if (close_requested
&& left_to_receive
== 0) {
3806 try_stream_close(stream
);
3810 pthread_mutex_lock(&session
->lock
);
3811 uatomic_set(&session
->new_streams
, 1);
3812 pthread_mutex_unlock(&session
->lock
);
3821 * relay_process_data: Process the data received on the data socket
3823 static enum relay_connection_status
relay_process_data(struct relay_connection
*conn
)
3825 enum relay_connection_status status
;
3827 switch (conn
->protocol
.data
.state_id
) {
3828 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3829 status
= relay_process_data_receive_header(conn
);
3831 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3832 status
= relay_process_data_receive_payload(conn
);
3835 ERR("Unexpected data connection communication state.");
3842 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3846 (void) lttng_poll_del(events
, pollfd
);
3848 ret
= fd_tracker_close_unsuspendable_fd(
3849 the_fd_tracker
, &pollfd
, 1, fd_tracker_util_close_fd
, nullptr);
3851 ERR("Closing pollfd %d", pollfd
);
3855 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3857 struct relay_connection
*conn
)
3859 const char *type_str
;
3861 switch (conn
->type
) {
3866 type_str
= "Control";
3868 case RELAY_VIEWER_COMMAND
:
3869 type_str
= "Viewer Command";
3871 case RELAY_VIEWER_NOTIFICATION
:
3872 type_str
= "Viewer Notification";
3875 type_str
= "Unknown";
3877 cleanup_connection_pollfd(events
, pollfd
);
3878 connection_put(conn
);
3879 DBG("%s connection closed with %d", type_str
, pollfd
);
3883 * This thread does the actual work
3885 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3887 int ret
, err
= -1, last_seen_data_fd
= -1;
3889 struct lttng_poll_event events
;
3890 struct lttng_ht
*relay_connections_ht
;
3891 struct lttng_ht_iter iter
;
3892 struct relay_connection
*destroy_conn
= nullptr;
3894 DBG("[thread] Relay worker started");
3896 rcu_register_thread();
3898 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3900 if (testpoint(relayd_thread_worker
)) {
3901 goto error_testpoint
;
3904 health_code_update();
3906 /* table of connections indexed on socket */
3907 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3908 if (!relay_connections_ht
) {
3909 goto relay_connections_ht_error
;
3912 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3914 goto error_poll_create
;
3917 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3924 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3926 health_code_update();
3928 /* Infinite blocking call, waiting for transmission */
3929 DBG3("Relayd worker thread polling...");
3930 health_poll_entry();
3931 ret
= lttng_poll_wait(&events
, -1);
3935 * Restart interrupted system call.
3937 if (errno
== EINTR
) {
3946 * Process control. The control connection is
3947 * prioritized so we don't starve it with high
3948 * throughput tracing data on the data connection.
3950 for (i
= 0; i
< nb_fd
; i
++) {
3951 /* Fetch once the poll data */
3952 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
3953 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3955 health_code_update();
3957 /* Activity on thread quit pipe, exiting. */
3958 if (relayd_is_thread_quit_pipe(pollfd
)) {
3959 DBG("Activity on thread quit pipe");
3964 /* Inspect the relay conn pipe for new connection */
3965 if (pollfd
== relay_conn_pipe
[0]) {
3966 if (revents
& LPOLLIN
) {
3967 struct relay_connection
*conn
;
3969 ret
= lttng_read(relay_conn_pipe
[0],
3971 sizeof(conn
)); /* NOLINT sizeof used on a
3976 ret
= lttng_poll_add(
3977 &events
, conn
->sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
3979 ERR("Failed to add new connection file descriptor to poll set");
3982 connection_ht_add(relay_connections_ht
, conn
);
3983 DBG("Connection socket %d added", conn
->sock
->fd
);
3984 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3985 ERR("Relay connection pipe error");
3988 ERR("Unexpected poll events %u for sock %d",
3994 struct relay_connection
*ctrl_conn
;
3996 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3997 /* If not found, there is a synchronization issue. */
3998 LTTNG_ASSERT(ctrl_conn
);
4000 if (ctrl_conn
->type
== RELAY_DATA
) {
4001 if (revents
& LPOLLIN
) {
4003 * Flag the last seen data fd not deleted. It will
4004 * be used as the last seen fd if any fd gets
4005 * deleted in this first loop.
4007 last_notdel_data_fd
= pollfd
;
4009 goto put_ctrl_connection
;
4011 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4013 if (revents
& LPOLLIN
) {
4014 enum relay_connection_status status
;
4016 status
= relay_process_control(ctrl_conn
);
4017 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4019 * On socket error flag the session as aborted to
4020 * force the cleanup of its stream otherwise it can
4021 * leak during the lifetime of the relayd.
4023 * This prevents situations in which streams can be
4024 * left opened because an index was received, the
4025 * control connection is closed, and the data
4026 * connection is closed (uncleanly) before the
4027 * packet's data provided.
4029 * Since the control connection encountered an
4030 * error, it is okay to be conservative and close
4031 * the session right now as we can't rely on the
4032 * protocol being respected anymore.
4034 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4035 session_abort(ctrl_conn
->session
);
4038 /* Clear the connection on error or close. */
4039 relay_thread_close_connection(
4040 &events
, pollfd
, ctrl_conn
);
4043 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4044 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
4045 if (last_seen_data_fd
== pollfd
) {
4046 last_seen_data_fd
= last_notdel_data_fd
;
4049 ERR("Unexpected poll events %u for control sock %d",
4052 connection_put(ctrl_conn
);
4055 put_ctrl_connection
:
4056 connection_put(ctrl_conn
);
4061 * The last loop handled a control request, go back to poll to make
4062 * sure we prioritise the control socket.
4068 if (last_seen_data_fd
>= 0) {
4069 for (i
= 0; i
< nb_fd
; i
++) {
4070 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4072 health_code_update();
4074 if (last_seen_data_fd
== pollfd
) {
4081 /* Process data connection. */
4082 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4083 /* Fetch the poll data. */
4084 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4085 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4086 struct relay_connection
*data_conn
;
4088 health_code_update();
4091 /* No activity for this FD (poll implementation). */
4095 /* Skip the command pipe. It's handled in the first loop. */
4096 if (pollfd
== relay_conn_pipe
[0]) {
4100 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4102 /* Skip it. Might be removed before. */
4105 if (data_conn
->type
== RELAY_CONTROL
) {
4106 goto put_data_connection
;
4108 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4110 if (revents
& LPOLLIN
) {
4111 enum relay_connection_status status
;
4113 status
= relay_process_data(data_conn
);
4114 /* Connection closed or error. */
4115 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4117 * On socket error flag the session as aborted to force
4118 * the cleanup of its stream otherwise it can leak
4119 * during the lifetime of the relayd.
4121 * This prevents situations in which streams can be
4122 * left opened because an index was received, the
4123 * control connection is closed, and the data
4124 * connection is closed (uncleanly) before the packet's
4127 * Since the data connection encountered an error,
4128 * it is okay to be conservative and close the
4129 * session right now as we can't rely on the protocol
4130 * being respected anymore.
4132 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4133 session_abort(data_conn
->session
);
4135 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4137 * Every goto restart call sets the last seen fd where
4138 * here we don't really care since we gracefully
4139 * continue the loop after the connection is deleted.
4142 /* Keep last seen port. */
4143 last_seen_data_fd
= pollfd
;
4144 connection_put(data_conn
);
4147 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4148 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4150 ERR("Unknown poll events %u for data sock %d", revents
, pollfd
);
4152 put_data_connection
:
4153 connection_put(data_conn
);
4155 last_seen_data_fd
= -1;
4158 /* Normal exit, no error */
4163 /* Cleanup remaining connection object. */
4165 cds_lfht_for_each_entry (relay_connections_ht
->ht
, &iter
.iter
, destroy_conn
, sock_n
.node
) {
4166 health_code_update();
4168 session_abort(destroy_conn
->session
);
4171 * No need to grab another ref, because we own
4174 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
, destroy_conn
);
4178 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4180 lttng_ht_destroy(relay_connections_ht
);
4181 relay_connections_ht_error
:
4182 /* Close relay conn pipes */
4183 (void) fd_tracker_util_pipe_close(the_fd_tracker
, relay_conn_pipe
);
4185 DBG("Thread exited with error");
4187 DBG("Worker thread cleanup complete");
4191 ERR("Health error occurred in %s", __func__
);
4193 health_unregister(health_relayd
);
4194 rcu_unregister_thread();
4195 lttng_relay_stop_threads();
4200 * Create the relay command pipe to wake thread_manage_apps.
4201 * Closed in cleanup().
4203 static int create_relay_conn_pipe()
4205 return fd_tracker_util_pipe_open_cloexec(
4206 the_fd_tracker
, "Relayd connection pipe", relay_conn_pipe
);
4209 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4211 fds
[0] = fileno(stdout
);
4212 fds
[1] = fileno(stderr
);
4216 static int track_stdio()
4219 const char *names
[] = { "stdout", "stderr" };
4221 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
, names
, 2, stdio_open
, nullptr);
4227 int main(int argc
, char **argv
)
4229 bool thread_is_rcu_registered
= false;
4230 int ret
= 0, retval
= 0;
4232 char *unlinked_file_directory_path
= nullptr, *output_path
= nullptr;
4234 /* Parse environment variables */
4235 ret
= parse_env_options();
4243 * Command line arguments overwrite environment.
4246 if (set_options(argc
, argv
)) {
4251 if (set_signal_handler()) {
4256 relayd_config_log();
4258 if (opt_print_version
) {
4264 ret
= fclose(stdin
);
4266 PERROR("Failed to close stdin");
4270 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4272 /* Try to create directory if -o, --output is specified. */
4273 if (opt_output_path
) {
4274 if (*opt_output_path
!= '/') {
4275 ERR("Please specify an absolute path for -o, --output PATH");
4280 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
, -1, -1);
4282 ERR("Unable to create %s", opt_output_path
);
4289 if (opt_daemon
|| opt_background
) {
4290 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
, !opt_background
);
4297 if (opt_working_directory
) {
4298 ret
= utils_change_working_directory(opt_working_directory
);
4300 /* All errors are already logged. */
4305 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4306 if (!sessiond_trace_chunk_registry
) {
4307 ERR("Failed to initialize session daemon trace chunk registry");
4313 * The RCU thread registration (and use, through the fd-tracker's
4314 * creation) is done after the daemonization to allow us to not
4315 * deal with liburcu's fork() management as the call RCU needs to
4318 rcu_register_thread();
4319 thread_is_rcu_registered
= true;
4321 output_path
= create_output_path("");
4323 ERR("Failed to get output path");
4327 ret
= asprintf(&unlinked_file_directory_path
,
4330 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4333 ERR("Failed to format unlinked file directory path");
4337 the_fd_tracker
= fd_tracker_create(unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4338 free(unlinked_file_directory_path
);
4339 if (!the_fd_tracker
) {
4344 ret
= track_stdio();
4350 /* Initialize thread health monitoring */
4351 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4352 if (!health_relayd
) {
4353 PERROR("health_app_create error");
4358 /* Create thread quit pipe */
4359 if (relayd_init_thread_quit_pipe()) {
4364 /* Setup the thread apps communication pipe. */
4365 if (create_relay_conn_pipe()) {
4370 /* Init relay command queue. */
4371 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4373 /* Initialize communication library */
4375 lttcomm_inet_init();
4377 /* tables of sessions indexed by session ID */
4378 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4384 /* tables of streams indexed by stream ID */
4385 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4386 if (!relay_streams_ht
) {
4391 /* tables of streams indexed by stream ID */
4392 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4393 if (!viewer_streams_ht
) {
4398 ret
= init_health_quit_pipe();
4404 /* Create thread to manage the client socket */
4405 ret
= pthread_create(&health_thread
,
4406 default_pthread_attr(),
4407 thread_manage_health_relayd
,
4411 PERROR("pthread_create health");
4416 /* Setup the dispatcher thread */
4417 ret
= pthread_create(&dispatcher_thread
,
4418 default_pthread_attr(),
4419 relay_thread_dispatcher
,
4423 PERROR("pthread_create dispatcher");
4425 goto exit_dispatcher_thread
;
4428 /* Setup the worker thread */
4429 ret
= pthread_create(&worker_thread
, default_pthread_attr(), relay_thread_worker
, nullptr);
4432 PERROR("pthread_create worker");
4434 goto exit_worker_thread
;
4437 /* Setup the listener thread */
4438 ret
= pthread_create(
4439 &listener_thread
, default_pthread_attr(), relay_thread_listener
, (void *) nullptr);
4442 PERROR("pthread_create listener");
4444 goto exit_listener_thread
;
4447 ret
= relayd_live_create(live_uri
);
4449 ERR("Starting live viewer threads");
4455 * This is where we start awaiting program completion (e.g. through
4456 * signal that asks threads to teardown).
4459 ret
= relayd_live_join();
4465 ret
= pthread_join(listener_thread
, &status
);
4468 PERROR("pthread_join listener_thread");
4472 exit_listener_thread
:
4473 ret
= pthread_join(worker_thread
, &status
);
4476 PERROR("pthread_join worker_thread");
4481 ret
= pthread_join(dispatcher_thread
, &status
);
4484 PERROR("pthread_join dispatcher_thread");
4487 exit_dispatcher_thread
:
4489 ret
= pthread_join(health_thread
, &status
);
4492 PERROR("pthread_join health_thread");
4497 * Wait for all pending call_rcu work to complete before tearing
4498 * down data structures. call_rcu worker may be trying to
4499 * perform lookups in those structures.
4504 /* Ensure all prior call_rcu are done. */
4507 if (thread_is_rcu_registered
) {
4508 rcu_unregister_thread();