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/urcu.hpp>
50 #include <common/uri.hpp>
51 #include <common/utils.hpp>
53 #include <lttng/lttng.h>
69 #include <sys/mount.h>
70 #include <sys/resource.h>
71 #include <sys/socket.h>
73 #include <sys/types.h>
76 #include <urcu/futex.h>
77 #include <urcu/rculist.h>
78 #include <urcu/uatomic.h>
80 static const char *help_msg
=
81 #ifdef LTTNG_EMBED_HELP
82 #include <lttng-relayd.8.h>
88 enum relay_connection_status
{
89 RELAY_CONNECTION_STATUS_OK
,
90 /* An error occurred while processing an event on the connection. */
91 RELAY_CONNECTION_STATUS_ERROR
,
92 /* Connection closed/shutdown cleanly. */
93 RELAY_CONNECTION_STATUS_CLOSED
,
96 /* command line options */
97 char *opt_output_path
, *opt_working_directory
;
98 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
99 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
101 /* Argument variables */
102 int lttng_opt_quiet
; /* not static in error.h */
103 int lttng_opt_verbose
; /* not static in error.h */
104 int lttng_opt_mi
; /* not static in error.h */
107 * We need to wait for listener and live listener threads, as well as
108 * health check thread, before being ready to signal readiness.
110 #define NR_LTTNG_RELAY_READY 3
111 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
113 /* Size of receive buffer. */
114 #define RECV_DATA_BUFFER_SIZE 65536
116 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
117 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
119 static struct lttng_uri
*control_uri
;
120 static struct lttng_uri
*data_uri
;
121 static struct lttng_uri
*live_uri
;
123 const char *progname
;
125 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
126 static int tracing_group_name_override
;
128 const char *const config_section_name
= "relayd";
131 * This pipe is used to inform the worker thread that a command is queued and
132 * ready to be processed.
134 static int relay_conn_pipe
[2] = { -1, -1 };
136 /* Shared between threads */
137 static int dispatch_thread_exit
;
139 static pthread_t listener_thread
;
140 static pthread_t dispatcher_thread
;
141 static pthread_t worker_thread
;
142 static pthread_t health_thread
;
145 * last_relay_stream_id_lock protects last_relay_stream_id increment
146 * atomicity on 32-bit architectures.
148 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
149 static uint64_t last_relay_stream_id
;
152 * Relay command queue.
154 * The relay_thread_listener and relay_thread_dispatcher communicate with this
157 static struct relay_conn_queue relay_conn_queue
;
159 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
160 static unsigned int lttng_opt_fd_pool_size
= -1;
162 /* Global relay stream hash table. */
163 struct lttng_ht
*relay_streams_ht
;
165 /* Global relay viewer stream hash table. */
166 struct lttng_ht
*viewer_streams_ht
;
168 /* Global relay sessions hash table. */
169 struct lttng_ht
*sessions_ht
;
171 /* Relayd health monitoring */
172 struct health_app
*health_relayd
;
174 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
176 /* Global fd tracker. */
177 struct fd_tracker
*the_fd_tracker
;
179 static struct option long_options
[] = {
240 { "config", 1, nullptr, 'f' },
241 { "version", 0, nullptr, 'V' },
249 "group-output-by-session",
255 "group-output-by-host",
260 { "disallow-clear", 0, nullptr, 'x' },
269 static const char *config_ignore_options
[] = { "help", "config", "version" };
271 static void print_version()
273 fprintf(stdout
, "%s\n", VERSION
);
276 static void relayd_config_log()
278 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
279 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
280 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
281 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
282 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
284 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
285 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
290 * Take an option from the getopt output and set it in the right variable to be
293 * Return 0 on success else a negative value.
295 static int set_option(int opt
, const char *arg
, const char *optname
)
301 if (!strcmp(optname
, "fd-pool-size")) {
305 v
= strtoul(arg
, nullptr, 0);
306 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
307 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
312 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s",
317 lttng_opt_fd_pool_size
= (unsigned int) v
;
319 fprintf(stderr
, "unknown option %s", optname
);
321 fprintf(stderr
, " with arg %s\n", arg
);
326 if (lttng_is_setuid_setgid()) {
327 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
328 "-C, --control-port");
330 ret
= uri_parse(arg
, &control_uri
);
332 ERR("Invalid control URI specified");
335 if (control_uri
->port
== 0) {
336 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
341 if (lttng_is_setuid_setgid()) {
342 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
345 ret
= uri_parse(arg
, &data_uri
);
347 ERR("Invalid data URI specified");
350 if (data_uri
->port
== 0) {
351 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
356 if (lttng_is_setuid_setgid()) {
357 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
360 ret
= uri_parse(arg
, &live_uri
);
362 ERR("Invalid live URI specified");
365 if (live_uri
->port
== 0) {
366 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
377 if (lttng_is_setuid_setgid()) {
378 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
381 tracing_group_name
= strdup(arg
);
382 if (tracing_group_name
== nullptr) {
387 tracing_group_name_override
= 1;
391 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
393 ERR("Cannot show --help for `lttng-relayd`");
398 opt_print_version
= 1;
401 if (lttng_is_setuid_setgid()) {
402 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
405 ret
= asprintf(&opt_output_path
, "%s", arg
);
408 PERROR("asprintf opt_output_path");
414 if (lttng_is_setuid_setgid()) {
415 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
416 "-w, --working-directory");
418 ret
= asprintf(&opt_working_directory
, "%s", arg
);
421 PERROR("asprintf opt_working_directory");
428 /* Verbose level can increase using multiple -v */
430 lttng_opt_verbose
= config_parse_value(arg
);
432 /* Only 3 level of verbosity (-vvv). */
433 if (lttng_opt_verbose
< 3) {
434 lttng_opt_verbose
+= 1;
439 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
440 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
443 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
446 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
447 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
450 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
457 /* Unknown option or other error.
458 * Error is printed by getopt, just return */
471 * config_entry_handler_cb used to handle options read from a config file.
472 * See config_entry_handler_cb comment in common/config/session-config.h for the
473 * return value conventions.
475 static int config_entry_handler(const struct config_entry
*entry
,
476 void *unused
__attribute__((unused
)))
480 if (!entry
|| !entry
->name
|| !entry
->value
) {
485 /* Check if the option is to be ignored */
486 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
487 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
492 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
493 /* Ignore if entry name is not fully matched. */
494 if (strcmp(entry
->name
, long_options
[i
].name
) != 0) {
499 * If the option takes no argument on the command line,
500 * we have to check if the value is "true". We support
501 * non-zero numeric values, true, on and yes.
503 if (!long_options
[i
].has_arg
) {
504 ret
= config_parse_value(entry
->value
);
507 WARN("Invalid configuration value \"%s\" for option %s",
511 /* False, skip boolean config option. */
516 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
520 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
526 static int parse_env_options()
529 char *value
= nullptr;
531 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
533 opt_working_directory
= strdup(value
);
534 if (!opt_working_directory
) {
535 ERR("Failed to allocate working directory string (\"%s\")", value
);
542 static int set_fd_pool_size()
545 struct rlimit rlimit
;
547 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
549 PERROR("Failed to get file descriptor limit");
554 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
555 (uint64_t) rlimit
.rlim_cur
,
556 (uint64_t) rlimit
.rlim_max
);
557 if (lttng_opt_fd_pool_size
== -1) {
558 /* Use default value (soft limit - reserve). */
559 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
560 ERR("The process' file number limit is too low (%" PRIu64
561 "). The process' file number limit must be set to at least %i.",
562 (uint64_t) rlimit
.rlim_cur
,
563 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
567 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
571 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
572 ERR("File descriptor pool size must be set to at least %d",
573 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
578 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
579 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
581 lttng_opt_fd_pool_size
,
582 (uint64_t) rlimit
.rlim_cur
);
587 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
588 lttng_opt_fd_pool_size
,
589 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
590 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
595 static int set_options(int argc
, char **argv
)
597 int c
, ret
= 0, option_index
= 0, retval
= 0;
598 int orig_optopt
= optopt
, orig_optind
= optind
;
599 char *default_address
, *optstring
;
600 char *config_path
= nullptr;
602 optstring
= utils_generate_optstring(long_options
,
603 sizeof(long_options
) / sizeof(struct option
));
609 /* Check for the --config option */
611 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
)) != -1) {
615 } else if (c
!= 'f') {
619 if (lttng_is_setuid_setgid()) {
620 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
624 config_path
= utils_expand_path(optarg
);
626 ERR("Failed to resolve path: %s", optarg
);
631 ret
= config_get_section_entries(
632 config_path
, config_section_name
, config_entry_handler
, nullptr);
635 ERR("Invalid configuration option at line %i", ret
);
641 /* Reset getopt's global state */
642 optopt
= orig_optopt
;
643 optind
= orig_optind
;
645 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
650 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
657 /* assign default values */
658 if (control_uri
== nullptr) {
659 ret
= asprintf(&default_address
,
660 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
661 DEFAULT_NETWORK_CONTROL_PORT
);
663 PERROR("asprintf default data address");
668 ret
= uri_parse(default_address
, &control_uri
);
669 free(default_address
);
671 ERR("Invalid control URI specified");
676 if (data_uri
== nullptr) {
677 ret
= asprintf(&default_address
,
678 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
679 DEFAULT_NETWORK_DATA_PORT
);
681 PERROR("asprintf default data address");
686 ret
= uri_parse(default_address
, &data_uri
);
687 free(default_address
);
689 ERR("Invalid data URI specified");
694 if (live_uri
== nullptr) {
695 ret
= asprintf(&default_address
,
696 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
697 DEFAULT_NETWORK_VIEWER_PORT
);
699 PERROR("asprintf default viewer control address");
704 ret
= uri_parse(default_address
, &live_uri
);
705 free(default_address
);
707 ERR("Invalid viewer control URI specified");
712 ret
= set_fd_pool_size();
718 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
719 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
721 if (opt_allow_clear
) {
722 /* Check if env variable exists. */
723 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
725 ret
= config_parse_value(value
);
727 ERR("Invalid value for %s specified",
728 DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
732 opt_allow_clear
= !ret
;
742 static void print_global_objects()
744 print_viewer_streams();
745 print_relay_streams();
749 static int noop_close(void *data
__attribute__((unused
)), int *fds
__attribute__((unused
)))
754 static void untrack_stdio()
756 int fds
[] = { fileno(stdout
), fileno(stderr
) };
759 * noop_close is used since we don't really want to close
760 * the stdio output fds; we merely want to stop tracking them.
762 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
, fds
, 2, noop_close
, nullptr);
768 static void relayd_cleanup()
770 print_global_objects();
774 if (viewer_streams_ht
)
775 lttng_ht_destroy(viewer_streams_ht
);
776 if (relay_streams_ht
)
777 lttng_ht_destroy(relay_streams_ht
);
779 lttng_ht_destroy(sessions_ht
);
781 free(opt_output_path
);
782 free(opt_working_directory
);
785 health_app_destroy(health_relayd
);
787 /* Close thread quit pipes */
788 if (health_quit_pipe
[0] != -1) {
789 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
791 relayd_close_thread_quit_pipe();
792 if (sessiond_trace_chunk_registry
) {
793 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
795 if (the_fd_tracker
) {
798 * fd_tracker_destroy() will log the contents of the fd-tracker
799 * if a leak is detected.
801 fd_tracker_destroy(the_fd_tracker
);
804 uri_free(control_uri
);
806 /* Live URI is freed in the live thread. */
808 if (tracing_group_name_override
) {
809 free((void *) tracing_group_name
);
813 static int notify_health_quit_pipe(int *pipe
)
817 ret
= lttng_write(pipe
[1], "4", 1);
819 PERROR("write relay health quit");
828 * Stop all relayd and relayd-live threads.
830 int lttng_relay_stop_threads()
834 /* Stopping all threads */
835 DBG("Terminating all threads");
836 if (relayd_notify_thread_quit_pipe()) {
837 ERR("write error on thread quit pipe");
841 if (notify_health_quit_pipe(health_quit_pipe
)) {
842 ERR("write error on health quit pipe");
845 /* Dispatch thread */
846 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
847 futex_nto1_wake(&relay_conn_queue
.futex
);
849 if (relayd_live_stop()) {
850 ERR("Error stopping live threads");
857 * Signal handler for the daemon
859 * Simply stop all worker threads, leaving main() return gracefully after
860 * joining all threads and calling cleanup().
862 static void sighandler(int sig
)
866 DBG("SIGINT caught");
867 if (lttng_relay_stop_threads()) {
868 ERR("Error stopping threads");
872 DBG("SIGTERM caught");
873 if (lttng_relay_stop_threads()) {
874 ERR("Error stopping threads");
878 CMM_STORE_SHARED(recv_child_signal
, 1);
886 * Setup signal handler for :
887 * SIGINT, SIGTERM, SIGPIPE
889 static int set_signal_handler()
895 if ((ret
= sigemptyset(&sigset
)) < 0) {
896 PERROR("sigemptyset");
903 sa
.sa_handler
= sighandler
;
904 if ((ret
= sigaction(SIGTERM
, &sa
, nullptr)) < 0) {
909 if ((ret
= sigaction(SIGINT
, &sa
, nullptr)) < 0) {
914 if ((ret
= sigaction(SIGUSR1
, &sa
, nullptr)) < 0) {
919 sa
.sa_handler
= SIG_IGN
;
920 if ((ret
= sigaction(SIGPIPE
, &sa
, nullptr)) < 0) {
925 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
930 void lttng_relay_notify_ready()
932 /* Notify the parent of the fork() process that we are ready. */
933 if (opt_daemon
|| opt_background
) {
934 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
935 kill(child_ppid
, SIGUSR1
);
941 * Init health quit pipe.
943 * Return -1 on error or 0 if all pipes are created.
945 static int init_health_quit_pipe()
947 return fd_tracker_util_pipe_open_cloexec(
948 the_fd_tracker
, "Health quit pipe", health_quit_pipe
);
951 static int create_sock(void *data
, int *out_fd
)
954 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
956 ret
= lttcomm_create_sock(sock
);
966 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
968 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
970 return sock
->ops
->close(sock
);
973 static int accept_sock(void *data
, int *out_fd
)
976 /* Socks is an array of in_sock, out_sock. */
977 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
978 struct lttcomm_sock
*in_sock
= socks
[0];
980 socks
[1] = in_sock
->ops
->accept(in_sock
);
985 *out_fd
= socks
[1]->fd
;
991 * Create and init socket from uri.
993 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
, const char *name
)
996 struct lttcomm_sock
*sock
= nullptr;
997 char uri_str
[PATH_MAX
];
998 char *formated_name
= nullptr;
1000 sock
= lttcomm_alloc_sock_from_uri(uri
);
1001 if (sock
== nullptr) {
1002 ERR("Allocating socket");
1007 * Don't fail to create the socket if the name can't be built as it is
1008 * only used for debugging purposes.
1010 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1011 uri_str
[sizeof(uri_str
) - 1] = '\0';
1013 ret
= asprintf(&formated_name
, "%s socket @ %s", name
, uri_str
);
1015 formated_name
= nullptr;
1019 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
,
1021 (const char **) (formated_name
? &formated_name
:
1027 PERROR("Failed to open \"%s\" relay socket", formated_name
?: "Unknown");
1030 DBG("Listening on %s socket %d", name
, sock
->fd
);
1032 ret
= sock
->ops
->bind(sock
);
1034 PERROR("Failed to bind socket");
1038 ret
= sock
->ops
->listen(sock
, -1);
1043 free(formated_name
);
1048 lttcomm_destroy_sock(sock
);
1050 free(formated_name
);
1054 static struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1058 struct lttcomm_sock
*socks
[2] = { listening_sock
, nullptr };
1059 struct lttcomm_sock
*new_sock
= nullptr;
1061 ret
= fd_tracker_open_unsuspendable_fd(
1062 the_fd_tracker
, &out_fd
, (const char **) &name
, 1, accept_sock
, &socks
);
1066 new_sock
= socks
[1];
1067 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1073 * This thread manages the listening for new connections on the network
1075 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1077 int i
, ret
, err
= -1;
1079 struct lttng_poll_event events
;
1080 struct lttcomm_sock
*control_sock
, *data_sock
;
1082 DBG("[thread] Relay listener started");
1084 rcu_register_thread();
1085 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1087 health_code_update();
1089 control_sock
= relay_socket_create(control_uri
, "Control listener");
1090 if (!control_sock
) {
1091 goto error_sock_control
;
1094 data_sock
= relay_socket_create(data_uri
, "Data listener");
1096 goto error_sock_relay
;
1100 * Pass 3 as size here for the thread quit pipe, control and
1103 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1105 goto error_create_poll
;
1108 /* Add the control socket */
1109 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1111 goto error_poll_add
;
1114 /* Add the data socket */
1115 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1117 goto error_poll_add
;
1120 lttng_relay_notify_ready();
1122 if (testpoint(relayd_thread_listener
)) {
1123 goto error_testpoint
;
1127 health_code_update();
1129 DBG("Listener accepting connections");
1132 health_poll_entry();
1133 ret
= lttng_poll_wait(&events
, -1);
1137 * Restart interrupted system call.
1139 if (errno
== EINTR
) {
1147 DBG("Relay new connection received");
1148 for (i
= 0; i
< nb_fd
; i
++) {
1149 /* Fetch once the poll data */
1150 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
1151 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1153 health_code_update();
1155 /* Activity on thread quit pipe, exiting. */
1156 if (relayd_is_thread_quit_pipe(pollfd
)) {
1157 DBG("Activity on thread quit pipe");
1162 if (revents
& LPOLLIN
) {
1164 * A new connection is requested, therefore a
1165 * sessiond/consumerd connection is allocated in
1166 * this thread, enqueued to a global queue and
1167 * dequeued (and freed) in the worker thread.
1170 struct relay_connection
*new_conn
;
1171 struct lttcomm_sock
*newsock
= nullptr;
1172 enum connection_type type
;
1174 if (pollfd
== data_sock
->fd
) {
1176 newsock
= accept_relayd_sock(data_sock
,
1177 "Data socket to relayd");
1179 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1180 type
= RELAY_CONTROL
;
1181 newsock
= accept_relayd_sock(control_sock
,
1182 "Control socket to relayd");
1185 PERROR("accepting sock");
1190 newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1192 PERROR("setsockopt inet");
1193 lttcomm_destroy_sock(newsock
);
1197 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1199 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1201 lttcomm_destroy_sock(newsock
);
1205 new_conn
= connection_create(newsock
, type
);
1207 lttcomm_destroy_sock(newsock
);
1211 /* Enqueue request for the dispatcher thread. */
1212 cds_wfcq_head_ptr_t head
;
1213 head
.h
= &relay_conn_queue
.head
;
1214 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
, &new_conn
->qnode
);
1217 * Wake the dispatch queue futex.
1218 * Implicit memory barrier with the
1219 * exchange in cds_wfcq_enqueue.
1221 futex_nto1_wake(&relay_conn_queue
.futex
);
1222 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1223 ERR("socket poll error");
1226 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1236 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1238 if (data_sock
->fd
>= 0) {
1239 int data_sock_fd
= data_sock
->fd
;
1241 ret
= fd_tracker_close_unsuspendable_fd(
1242 the_fd_tracker
, &data_sock_fd
, 1, close_sock
, data_sock
);
1244 PERROR("Failed to close the data listener socket file descriptor");
1248 lttcomm_destroy_sock(data_sock
);
1250 if (control_sock
->fd
>= 0) {
1251 int control_sock_fd
= control_sock
->fd
;
1253 ret
= fd_tracker_close_unsuspendable_fd(
1254 the_fd_tracker
, &control_sock_fd
, 1, close_sock
, control_sock
);
1256 PERROR("Failed to close the control listener socket file descriptor");
1258 control_sock
->fd
= -1;
1260 lttcomm_destroy_sock(control_sock
);
1264 ERR("Health error occurred in %s", __func__
);
1266 health_unregister(health_relayd
);
1267 rcu_unregister_thread();
1268 DBG("Relay listener thread cleanup complete");
1269 lttng_relay_stop_threads();
1274 * This thread manages the dispatching of the requests to worker threads
1276 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1280 struct cds_wfcq_node
*node
;
1281 struct relay_connection
*new_conn
= nullptr;
1283 DBG("[thread] Relay dispatcher started");
1285 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1287 if (testpoint(relayd_thread_dispatcher
)) {
1288 goto error_testpoint
;
1291 health_code_update();
1294 health_code_update();
1296 /* Atomically prepare the queue futex */
1297 futex_nto1_prepare(&relay_conn_queue
.futex
);
1299 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1304 health_code_update();
1306 /* Dequeue commands */
1307 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1308 &relay_conn_queue
.tail
);
1309 if (node
== nullptr) {
1310 DBG("Woken up but nothing in the relay command queue");
1311 /* Continue thread execution */
1314 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1316 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1319 * Inform worker thread of the new request. This
1320 * call is blocking so we can be assured that
1321 * the data will be read at some point in time
1322 * or wait to the end of the world :)
1325 relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
)); /* NOLINT
1332 PERROR("write connection pipe");
1333 connection_put(new_conn
);
1336 } while (node
!= nullptr);
1338 /* Futex wait on queue. Blocking call on futex() */
1339 health_poll_entry();
1340 futex_nto1_wait(&relay_conn_queue
.futex
);
1344 /* Normal exit, no error */
1351 ERR("Health error occurred in %s", __func__
);
1353 health_unregister(health_relayd
);
1354 DBG("Dispatch thread dying");
1355 lttng_relay_stop_threads();
1359 static bool session_streams_have_index(const struct relay_session
*session
)
1361 return session
->minor
>= 4 && !session
->snapshot
;
1365 * Handle the RELAYD_CREATE_SESSION command.
1367 * On success, send back the session id or else return a negative value.
1369 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1370 struct relay_connection
*conn
,
1371 const struct lttng_buffer_view
*payload
)
1375 struct relay_session
*session
= nullptr;
1376 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1377 char session_name
[LTTNG_NAME_MAX
] = {};
1378 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1379 uint32_t live_timer
= 0;
1380 bool snapshot
= false;
1381 bool session_name_contains_creation_timestamp
= false;
1382 /* Left nil for peers < 2.11. */
1383 char base_path
[LTTNG_PATH_MAX
] = {};
1384 lttng_uuid sessiond_uuid
= {};
1385 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1386 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1387 LTTNG_OPTIONAL(time_t) creation_time
= {};
1388 struct lttng_dynamic_buffer reply_payload
;
1390 lttng_dynamic_buffer_init(&reply_payload
);
1392 if (conn
->minor
< 4) {
1393 /* From 2.1 to 2.3 */
1395 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1396 /* From 2.4 to 2.10 */
1397 ret
= cmd_create_session_2_4(
1398 payload
, session_name
, hostname
, &live_timer
, &snapshot
);
1400 bool has_current_chunk
;
1401 uint64_t current_chunk_id_value
;
1402 time_t creation_time_value
;
1403 uint64_t id_sessiond_value
;
1405 /* From 2.11 to ... */
1406 ret
= cmd_create_session_2_11(payload
,
1415 ¤t_chunk_id_value
,
1416 &creation_time_value
,
1417 &session_name_contains_creation_timestamp
);
1418 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1419 /* The nil UUID is reserved for pre-2.11 clients. */
1420 ERR("Illegal nil UUID announced by peer in create session command");
1424 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1425 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1426 if (has_current_chunk
) {
1427 LTTNG_OPTIONAL_SET(¤t_chunk_id
, current_chunk_id_value
);
1435 session
= session_create(session_name
,
1441 id_sessiond
.is_set
? &id_sessiond
.value
: nullptr,
1442 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: nullptr,
1443 creation_time
.is_set
? &creation_time
.value
: nullptr,
1446 session_name_contains_creation_timestamp
);
1451 LTTNG_ASSERT(!conn
->session
);
1452 conn
->session
= session
;
1453 DBG("Created session %" PRIu64
, session
->id
);
1455 reply
.generic
.session_id
= htobe64(session
->id
);
1459 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1461 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1464 if (conn
->minor
< 11) {
1465 /* From 2.1 to 2.10 */
1466 ret
= lttng_dynamic_buffer_append(
1467 &reply_payload
, &reply
.generic
, sizeof(reply
.generic
));
1469 ERR("Failed to append \"create session\" command reply header to payload buffer");
1474 const uint32_t output_path_length
= session
? strlen(session
->output_path
) + 1 : 0;
1476 reply
.output_path_length
= htobe32(output_path_length
);
1477 ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
1479 ERR("Failed to append \"create session\" command reply header to payload buffer");
1483 if (output_path_length
) {
1484 ret
= lttng_dynamic_buffer_append(
1485 &reply_payload
, session
->output_path
, output_path_length
);
1487 ERR("Failed to append \"create session\" command reply path to payload buffer");
1493 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
1494 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1495 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1501 if (ret
< 0 && session
) {
1502 session_put(session
);
1504 lttng_dynamic_buffer_reset(&reply_payload
);
1509 * When we have received all the streams and the metadata for a channel,
1510 * we make them visible to the viewer threads.
1512 static void publish_connection_local_streams(struct relay_connection
*conn
)
1514 struct relay_stream
*stream
;
1515 struct relay_session
*session
= conn
->session
;
1518 * We publish all streams belonging to a session atomically wrt
1521 pthread_mutex_lock(&session
->lock
);
1522 const lttng::urcu::read_lock_guard read_lock
;
1523 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
, recv_node
)
1525 stream_publish(stream
);
1529 * Inform the viewer that there are new streams in the session.
1531 if (session
->viewer_attached
) {
1532 uatomic_set(&session
->new_streams
, 1);
1535 pthread_mutex_unlock(&session
->lock
);
1538 static int conform_channel_path(char *channel_path
)
1542 if (strstr("../", channel_path
)) {
1543 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1549 if (*channel_path
== '/') {
1550 const size_t len
= strlen(channel_path
);
1553 * Channel paths from peers prior to 2.11 are expressed as an
1554 * absolute path that is, in reality, relative to the relay
1555 * daemon's output directory. Remove the leading slash so it
1556 * is correctly interpreted as a relative path later on.
1558 * len (and not len - 1) is used to copy the trailing NULL.
1560 bcopy(channel_path
+ 1, channel_path
, len
);
1567 * relay_add_stream: allocate a new stream for a session
1569 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1570 struct relay_connection
*conn
,
1571 const struct lttng_buffer_view
*payload
)
1575 struct relay_session
*session
= conn
->session
;
1576 struct relay_stream
*stream
= nullptr;
1577 struct lttcomm_relayd_status_stream reply
;
1578 struct ctf_trace
*trace
= nullptr;
1579 uint64_t stream_handle
= -1ULL;
1580 char *path_name
= nullptr, *channel_name
= nullptr;
1581 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1582 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1584 if (!session
|| !conn
->version_check_done
) {
1585 ERR("Trying to add a stream before version check");
1587 goto end_no_session
;
1590 if (session
->minor
== 1) {
1592 ret
= cmd_recv_stream_2_1(payload
, &path_name
, &channel_name
);
1593 } else if (session
->minor
> 1 && session
->minor
< 11) {
1594 /* From 2.2 to 2.10 */
1595 ret
= cmd_recv_stream_2_2(
1596 payload
, &path_name
, &channel_name
, &tracefile_size
, &tracefile_count
);
1598 /* From 2.11 to ... */
1599 ret
= cmd_recv_stream_2_11(payload
,
1604 &stream_chunk_id
.value
);
1605 stream_chunk_id
.is_set
= true;
1612 if (conform_channel_path(path_name
)) {
1617 * Backward compatibility for --group-output-by-session.
1618 * Prior to lttng 2.11, the complete path is passed by the stream.
1619 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1620 * >=2.11 the chunk is responsible for the output path. When dealing
1621 * with producer < 2.11 the chunk output_path is the root output path
1622 * and the stream carries the complete path (path_name).
1623 * To support --group-output-by-session with older producer (<2.11), we
1624 * need to craft the path based on the stream path.
1626 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1627 if (conn
->minor
< 4) {
1629 * From 2.1 to 2.3, the session_name is not passed on
1630 * the RELAYD_CREATE_SESSION command. The session name
1631 * is necessary to detect the presence of a base_path
1632 * inside the stream path. Without it we cannot perform
1633 * a valid group-output-by-session transformation.
1635 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1636 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1639 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1640 char *group_by_session_path_name
;
1642 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1644 group_by_session_path_name
= backward_compat_group_by_session(
1645 path_name
, session
->session_name
, session
->creation_time
.value
);
1646 if (!group_by_session_path_name
) {
1647 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1652 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1654 group_by_session_path_name
);
1657 path_name
= group_by_session_path_name
;
1661 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1666 /* This stream here has one reference on the trace. */
1667 pthread_mutex_lock(&last_relay_stream_id_lock
);
1668 stream_handle
= ++last_relay_stream_id
;
1669 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1671 /* We pass ownership of path_name and channel_name. */
1672 stream
= stream_create(
1673 trace
, stream_handle
, path_name
, channel_name
, tracefile_size
, tracefile_count
);
1674 path_name
= nullptr;
1675 channel_name
= nullptr;
1678 * Streams are the owners of their trace. Reference to trace is
1679 * kept within stream_create().
1681 ctf_trace_put(trace
);
1684 memset(&reply
, 0, sizeof(reply
));
1685 reply
.handle
= htobe64(stream_handle
);
1687 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1689 reply
.ret_code
= htobe32(LTTNG_OK
);
1692 send_ret
= conn
->sock
->ops
->sendmsg(
1693 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_status_stream
), 0);
1694 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1695 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret
);
1706 * relay_close_stream: close a specific stream
1708 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1709 struct relay_connection
*conn
,
1710 const struct lttng_buffer_view
*payload
)
1714 struct relay_session
*session
= conn
->session
;
1715 struct lttcomm_relayd_close_stream stream_info
;
1716 struct lttcomm_relayd_generic_reply reply
;
1717 struct relay_stream
*stream
;
1719 DBG("Close stream received");
1721 if (!session
|| !conn
->version_check_done
) {
1722 ERR("Trying to close a stream before version check");
1724 goto end_no_session
;
1727 if (payload
->size
< sizeof(stream_info
)) {
1728 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1729 sizeof(stream_info
),
1732 goto end_no_session
;
1734 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1735 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1736 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1738 stream
= stream_get_by_id(stream_info
.stream_id
);
1745 * Set last_net_seq_num before the close flag. Required by data
1748 pthread_mutex_lock(&stream
->lock
);
1749 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1750 pthread_mutex_unlock(&stream
->lock
);
1753 * This is one of the conditions which may trigger a stream close
1754 * with the others being:
1755 * 1) A close command is received for a stream
1756 * 2) The control connection owning the stream is closed
1757 * 3) We have received all of the stream's data _after_ a close
1760 try_stream_close(stream
);
1765 memset(&reply
, 0, sizeof(reply
));
1767 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1769 reply
.ret_code
= htobe32(LTTNG_OK
);
1771 send_ret
= conn
->sock
->ops
->sendmsg(
1772 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1773 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1774 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret
);
1783 * relay_reset_metadata: reset a metadata stream
1785 static int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1786 struct relay_connection
*conn
,
1787 const struct lttng_buffer_view
*payload
)
1791 struct relay_session
*session
= conn
->session
;
1792 struct lttcomm_relayd_reset_metadata stream_info
;
1793 struct lttcomm_relayd_generic_reply reply
;
1794 struct relay_stream
*stream
;
1796 DBG("Reset metadata received");
1798 if (!session
|| !conn
->version_check_done
) {
1799 ERR("Trying to reset a metadata stream before version check");
1801 goto end_no_session
;
1804 if (payload
->size
< sizeof(stream_info
)) {
1805 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1806 sizeof(stream_info
),
1809 goto end_no_session
;
1811 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1812 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1813 stream_info
.version
= be64toh(stream_info
.version
);
1815 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1817 /* Unsupported for live sessions for now. */
1818 if (session
->live_timer
!= 0) {
1823 stream
= stream_get_by_id(stream_info
.stream_id
);
1828 pthread_mutex_lock(&stream
->lock
);
1829 if (!stream
->is_metadata
) {
1834 ret
= stream_reset_file(stream
);
1836 ERR("Failed to reset metadata stream %" PRIu64
": stream_path = %s, channel = %s",
1837 stream
->stream_handle
,
1839 stream
->channel_name
);
1843 pthread_mutex_unlock(&stream
->lock
);
1847 memset(&reply
, 0, sizeof(reply
));
1849 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1851 reply
.ret_code
= htobe32(LTTNG_OK
);
1853 send_ret
= conn
->sock
->ops
->sendmsg(
1854 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1855 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1856 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret
);
1865 * relay_unknown_command: send -1 if received unknown command
1867 static void relay_unknown_command(struct relay_connection
*conn
)
1869 struct lttcomm_relayd_generic_reply reply
;
1872 memset(&reply
, 0, sizeof(reply
));
1873 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1874 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1875 if (send_ret
< sizeof(reply
)) {
1876 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1881 * relay_start: send an acknowledgment to the client to tell if we are
1882 * ready to receive data. We are ready if a session is established.
1884 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1885 struct relay_connection
*conn
,
1886 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1890 struct lttcomm_relayd_generic_reply reply
;
1891 struct relay_session
*session
= conn
->session
;
1894 DBG("Trying to start the streaming without a session established");
1895 ret
= htobe32(LTTNG_ERR_UNK
);
1898 memset(&reply
, 0, sizeof(reply
));
1899 reply
.ret_code
= htobe32(LTTNG_OK
);
1900 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1901 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1902 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret
);
1910 * relay_recv_metadata: receive the metadata for the session.
1912 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1913 struct relay_connection
*conn
,
1914 const struct lttng_buffer_view
*payload
)
1917 struct relay_session
*session
= conn
->session
;
1918 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1919 struct relay_stream
*metadata_stream
;
1920 uint64_t metadata_payload_size
;
1921 struct lttng_buffer_view packet_view
;
1924 ERR("Metadata sent before version check");
1929 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1930 ERR("Incorrect data size");
1934 metadata_payload_size
=
1935 recv_hdr
->data_size
- sizeof(struct lttcomm_relayd_metadata_payload
);
1937 memcpy(&metadata_payload_header
, payload
->data
, sizeof(metadata_payload_header
));
1938 metadata_payload_header
.stream_id
= be64toh(metadata_payload_header
.stream_id
);
1939 metadata_payload_header
.padding_size
= be32toh(metadata_payload_header
.padding_size
);
1941 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1942 if (!metadata_stream
) {
1947 packet_view
= lttng_buffer_view_from_view(
1948 payload
, sizeof(metadata_payload_header
), metadata_payload_size
);
1949 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1950 ERR("Invalid metadata packet length announced by header");
1955 pthread_mutex_lock(&metadata_stream
->lock
);
1956 ret
= stream_write(metadata_stream
, &packet_view
, metadata_payload_header
.padding_size
);
1957 pthread_mutex_unlock(&metadata_stream
->lock
);
1963 stream_put(metadata_stream
);
1969 * relay_send_version: send relayd version number
1971 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1972 struct relay_connection
*conn
,
1973 const struct lttng_buffer_view
*payload
)
1977 struct lttcomm_relayd_version reply
, msg
;
1978 bool compatible
= true;
1980 conn
->version_check_done
= true;
1982 /* Get version from the other side. */
1983 if (payload
->size
< sizeof(msg
)) {
1984 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1991 memcpy(&msg
, payload
->data
, sizeof(msg
));
1992 msg
.major
= be32toh(msg
.major
);
1993 msg
.minor
= be32toh(msg
.minor
);
1995 memset(&reply
, 0, sizeof(reply
));
1996 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1997 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1999 /* Major versions must be the same */
2000 if (reply
.major
!= msg
.major
) {
2001 DBG("Incompatible major versions (%u vs %u), deleting session",
2007 conn
->major
= reply
.major
;
2008 /* We adapt to the lowest compatible version */
2009 if (reply
.minor
<= msg
.minor
) {
2010 conn
->minor
= reply
.minor
;
2012 conn
->minor
= msg
.minor
;
2015 reply
.major
= htobe32(reply
.major
);
2016 reply
.minor
= htobe32(reply
.minor
);
2017 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2018 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2019 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret
);
2031 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
2038 * Check for data pending for a given stream id from the session daemon.
2040 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2041 struct relay_connection
*conn
,
2042 const struct lttng_buffer_view
*payload
)
2044 struct relay_session
*session
= conn
->session
;
2045 struct lttcomm_relayd_data_pending msg
;
2046 struct lttcomm_relayd_generic_reply reply
;
2047 struct relay_stream
*stream
;
2050 uint64_t stream_seq
;
2052 DBG("Data pending command received");
2054 if (!session
|| !conn
->version_check_done
) {
2055 ERR("Trying to check for data before version check");
2057 goto end_no_session
;
2060 if (payload
->size
< sizeof(msg
)) {
2061 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2065 goto end_no_session
;
2067 memcpy(&msg
, payload
->data
, sizeof(msg
));
2068 msg
.stream_id
= be64toh(msg
.stream_id
);
2069 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2071 stream
= stream_get_by_id(msg
.stream_id
);
2072 if (stream
== nullptr) {
2077 pthread_mutex_lock(&stream
->lock
);
2079 if (session_streams_have_index(session
)) {
2081 * Ensure that both the index and stream data have been
2082 * flushed up to the requested point.
2084 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2086 stream_seq
= stream
->prev_data_seq
;
2088 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2089 ", prev_index_seq %" PRIu64
", and last_seq %" PRIu64
,
2091 stream
->prev_data_seq
,
2092 stream
->prev_index_seq
,
2093 msg
.last_net_seq_num
);
2095 /* Avoid wrapping issue */
2096 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2097 /* Data has in fact been written and is NOT pending */
2100 /* Data still being streamed thus pending */
2104 stream
->data_pending_check_done
= true;
2105 pthread_mutex_unlock(&stream
->lock
);
2110 memset(&reply
, 0, sizeof(reply
));
2111 reply
.ret_code
= htobe32(ret
);
2112 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2113 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2114 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret
);
2123 * Wait for the control socket to reach a quiescent state.
2125 * Note that for now, when receiving this command from the session
2126 * daemon, this means that every subsequent commands or data received on
2127 * the control socket has been handled. So, this is why we simply return
2130 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
2131 __attribute__((unused
)),
2132 struct relay_connection
*conn
,
2133 const struct lttng_buffer_view
*payload
)
2137 struct relay_stream
*stream
;
2138 struct lttcomm_relayd_quiescent_control msg
;
2139 struct lttcomm_relayd_generic_reply reply
;
2141 DBG("Checking quiescent state on control socket");
2143 if (!conn
->session
|| !conn
->version_check_done
) {
2144 ERR("Trying to check for data before version check");
2146 goto end_no_session
;
2149 if (payload
->size
< sizeof(msg
)) {
2150 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2154 goto end_no_session
;
2156 memcpy(&msg
, payload
->data
, sizeof(msg
));
2157 msg
.stream_id
= be64toh(msg
.stream_id
);
2159 stream
= stream_get_by_id(msg
.stream_id
);
2163 pthread_mutex_lock(&stream
->lock
);
2164 stream
->data_pending_check_done
= true;
2165 pthread_mutex_unlock(&stream
->lock
);
2167 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2170 memset(&reply
, 0, sizeof(reply
));
2171 reply
.ret_code
= htobe32(LTTNG_OK
);
2172 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2173 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2174 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret
);
2185 * Initialize a data pending command. This means that a consumer is about
2186 * to ask for data pending for each stream it holds. Simply iterate over
2187 * all streams of a session and set the data_pending_check_done flag.
2189 * This command returns to the client a LTTNG_OK code.
2191 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2192 struct relay_connection
*conn
,
2193 const struct lttng_buffer_view
*payload
)
2197 struct lttng_ht_iter iter
;
2198 struct lttcomm_relayd_begin_data_pending msg
;
2199 struct lttcomm_relayd_generic_reply reply
;
2200 struct relay_stream
*stream
;
2202 LTTNG_ASSERT(recv_hdr
);
2205 DBG("Init streams for data pending");
2207 if (!conn
->session
|| !conn
->version_check_done
) {
2208 ERR("Trying to check for data before version check");
2210 goto end_no_session
;
2213 if (payload
->size
< sizeof(msg
)) {
2214 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2218 goto end_no_session
;
2220 memcpy(&msg
, payload
->data
, sizeof(msg
));
2221 msg
.session_id
= be64toh(msg
.session_id
);
2224 * Iterate over all streams to set the begin data pending flag.
2225 * For now, the streams are indexed by stream handle so we have
2226 * to iterate over all streams to find the one associated with
2227 * the right session_id.
2230 const lttng::urcu::read_lock_guard read_lock
;
2232 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2233 if (!stream_get(stream
)) {
2237 if (stream
->trace
->session
->id
== msg
.session_id
) {
2238 pthread_mutex_lock(&stream
->lock
);
2239 stream
->data_pending_check_done
= false;
2240 pthread_mutex_unlock(&stream
->lock
);
2241 DBG("Set begin data pending flag to stream %" PRIu64
,
2242 stream
->stream_handle
);
2249 memset(&reply
, 0, sizeof(reply
));
2250 /* All good, send back reply. */
2251 reply
.ret_code
= htobe32(LTTNG_OK
);
2253 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2254 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2255 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret
);
2266 * End data pending command. This will check, for a given session id, if
2267 * each stream associated with it has its data_pending_check_done flag
2268 * set. If not, this means that the client lost track of the stream but
2269 * the data is still being streamed on our side. In this case, we inform
2270 * the client that data is in flight.
2272 * Return to the client if there is data in flight or not with a ret_code.
2274 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2275 struct relay_connection
*conn
,
2276 const struct lttng_buffer_view
*payload
)
2280 struct lttng_ht_iter iter
;
2281 struct lttcomm_relayd_end_data_pending msg
;
2282 struct lttcomm_relayd_generic_reply reply
;
2283 struct relay_stream
*stream
;
2284 uint32_t is_data_inflight
= 0;
2286 DBG("End data pending command");
2288 if (!conn
->session
|| !conn
->version_check_done
) {
2289 ERR("Trying to check for data before version check");
2291 goto end_no_session
;
2294 if (payload
->size
< sizeof(msg
)) {
2295 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2299 goto end_no_session
;
2301 memcpy(&msg
, payload
->data
, sizeof(msg
));
2302 msg
.session_id
= be64toh(msg
.session_id
);
2305 * Iterate over all streams to see if the begin data pending
2309 const lttng::urcu::read_lock_guard read_lock
;
2311 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2312 if (!stream_get(stream
)) {
2316 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2321 pthread_mutex_lock(&stream
->lock
);
2322 if (!stream
->data_pending_check_done
) {
2323 uint64_t stream_seq
;
2325 if (session_streams_have_index(conn
->session
)) {
2327 * Ensure that both the index and stream data have been
2328 * flushed up to the requested point.
2330 stream_seq
= std::min(stream
->prev_data_seq
,
2331 stream
->prev_index_seq
);
2333 stream_seq
= stream
->prev_data_seq
;
2336 if (!stream
->closed
||
2337 !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2338 is_data_inflight
= 1;
2339 DBG("Data is still in flight for stream %" PRIu64
,
2340 stream
->stream_handle
);
2341 pthread_mutex_unlock(&stream
->lock
);
2347 pthread_mutex_unlock(&stream
->lock
);
2352 memset(&reply
, 0, sizeof(reply
));
2353 /* All good, send back reply. */
2354 reply
.ret_code
= htobe32(is_data_inflight
);
2356 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2357 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2358 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret
);
2369 * Receive an index for a specific stream.
2371 * Return 0 on success else a negative value.
2373 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2374 struct relay_connection
*conn
,
2375 const struct lttng_buffer_view
*payload
)
2379 struct relay_session
*session
= conn
->session
;
2380 struct lttcomm_relayd_index index_info
;
2381 struct lttcomm_relayd_generic_reply reply
;
2382 struct relay_stream
*stream
;
2387 DBG("Relay receiving index");
2389 if (!session
|| !conn
->version_check_done
) {
2390 ERR("Trying to close a stream before version check");
2392 goto end_no_session
;
2395 msg_len
= lttcomm_relayd_index_len(lttng_to_index_major(conn
->major
, conn
->minor
),
2396 lttng_to_index_minor(conn
->major
, conn
->minor
));
2397 if (payload
->size
< msg_len
) {
2398 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2402 goto end_no_session
;
2404 memcpy(&index_info
, payload
->data
, msg_len
);
2405 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2406 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2407 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2408 index_info
.content_size
= be64toh(index_info
.content_size
);
2409 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2410 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2411 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2412 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2414 if (conn
->minor
>= 8) {
2415 index_info
.stream_instance_id
= be64toh(index_info
.stream_instance_id
);
2416 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2418 index_info
.stream_instance_id
= -1ULL;
2419 index_info
.packet_seq_num
= -1ULL;
2422 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2424 ERR("stream_get_by_id not found");
2429 pthread_mutex_lock(&stream
->lock
);
2430 ret
= stream_add_index(stream
, &index_info
);
2431 pthread_mutex_unlock(&stream
->lock
);
2433 goto end_stream_put
;
2439 memset(&reply
, 0, sizeof(reply
));
2441 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2443 reply
.ret_code
= htobe32(LTTNG_OK
);
2445 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2446 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2447 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2456 * Receive the streams_sent message.
2458 * Return 0 on success else a negative value.
2460 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2461 struct relay_connection
*conn
,
2462 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2466 struct lttcomm_relayd_generic_reply reply
;
2470 DBG("Relay receiving streams_sent");
2472 if (!conn
->session
|| !conn
->version_check_done
) {
2473 ERR("Trying to close a stream before version check");
2475 goto end_no_session
;
2479 * Publish every pending stream in the connection recv list which are
2480 * now ready to be used by the viewer.
2482 publish_connection_local_streams(conn
);
2484 memset(&reply
, 0, sizeof(reply
));
2485 reply
.ret_code
= htobe32(LTTNG_OK
);
2486 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2487 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2488 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret
);
2500 relay_unpack_rotate_streams_header(const struct lttng_buffer_view
*payload
,
2501 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2503 struct lttcomm_relayd_rotate_streams rotate_streams
;
2505 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2506 * This is the smallest version of this structure, but it can be larger;
2507 * this variable is updated once the proper size of the structure is known.
2509 * See comment at the declaration of this structure for more information.
2511 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2512 size_t expected_payload_size_no_padding
, expected_payload_size_3_bytes_padding
,
2513 expected_payload_size_7_bytes_padding
;
2515 if (payload
->size
< header_len
) {
2516 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2523 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2524 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2526 * We start by "unpacking" `stream_count` to figure out the padding length
2527 * emited by our peer.
2530 decltype(rotate_streams
.stream_count
) stream_count
;
2532 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2533 rotate_streams
.stream_count
= be32toh(stream_count
);
2536 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2539 * Payload size expected given the possible padding lengths in
2540 * `struct lttcomm_relayd_rotate_streams`.
2542 expected_payload_size_no_padding
=
2543 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2544 sizeof(lttcomm_relayd_rotate_streams_packed
);
2545 expected_payload_size_3_bytes_padding
=
2546 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2547 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2548 expected_payload_size_7_bytes_padding
=
2549 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2550 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2552 if (payload
->size
== expected_payload_size_no_padding
) {
2553 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2556 * This handles cases where someone might build with
2557 * -fpack-struct or any other toolchain that wouldn't produce
2558 * padding to align `value`.
2560 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2562 header_len
= sizeof(packed_rotate_streams
);
2563 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2565 /* Unpack the packed structure to the natively-packed version. */
2566 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2567 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2568 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2570 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2571 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2572 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2574 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2576 header_len
= sizeof(padded_rotate_streams
);
2577 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2579 /* Unpack the 3-byte padded structure to the natively-packed version. */
2580 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2581 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2582 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2584 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2585 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2586 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2588 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2590 header_len
= sizeof(padded_rotate_streams
);
2591 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2593 /* Unpack the 7-byte padded structure to the natively-packed version. */
2594 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2595 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2596 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2598 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2600 header_len
= sizeof(padded_rotate_streams
);
2602 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2603 expected_payload_size_no_padding
,
2604 expected_payload_size_3_bytes_padding
,
2605 expected_payload_size_7_bytes_padding
,
2616 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2617 * session rotation feature (not the tracefile rotation feature).
2619 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr
*recv_hdr
2620 __attribute__((unused
)),
2621 struct relay_connection
*conn
,
2622 const struct lttng_buffer_view
*payload
)
2627 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2628 struct relay_session
*session
= conn
->session
;
2629 struct lttcomm_relayd_rotate_streams rotate_streams
;
2630 struct lttcomm_relayd_generic_reply reply
= {};
2631 struct relay_stream
*stream
= nullptr;
2632 struct lttng_trace_chunk
*next_trace_chunk
= nullptr;
2633 struct lttng_buffer_view stream_positions
;
2634 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2635 const char *chunk_id_str
= "none";
2638 if (!session
|| !conn
->version_check_done
) {
2639 ERR("Trying to rotate a stream before version check");
2644 if (session
->major
== 2 && session
->minor
< 11) {
2645 ERR("Unsupported feature before 2.11");
2650 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2651 if (header_len
< 0) {
2656 if (rotate_streams
.new_chunk_id
.is_set
) {
2658 * Retrieve the trace chunk the stream must transition to. As
2659 * per the protocol, this chunk should have been created
2660 * before this command is received.
2662 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2663 sessiond_trace_chunk_registry
,
2664 session
->sessiond_uuid
,
2665 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2667 rotate_streams
.new_chunk_id
.value
);
2668 if (!next_trace_chunk
) {
2669 char uuid_str
[LTTNG_UUID_STR_LEN
];
2671 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2672 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2673 ", trace_chunk_id = %" PRIu64
,
2676 rotate_streams
.new_chunk_id
.value
);
2677 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2682 ret
= snprintf(chunk_id_buf
,
2683 sizeof(chunk_id_buf
),
2685 rotate_streams
.new_chunk_id
.value
);
2686 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2687 chunk_id_str
= "formatting error";
2689 chunk_id_str
= chunk_id_buf
;
2693 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2694 rotate_streams
.stream_count
,
2695 session
->session_name
,
2698 stream_positions
= lttng_buffer_view_from_view(payload
, header_len
, -1);
2699 if (!stream_positions
.data
||
2700 stream_positions
.size
< (rotate_streams
.stream_count
*
2701 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2702 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2707 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2708 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2709 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2710 const struct lttcomm_relayd_stream_rotation_position pos
= {
2711 .stream_id
= be64toh(position_comm
->stream_id
),
2712 .rotate_at_seq_num
= be64toh(position_comm
->rotate_at_seq_num
),
2715 stream
= stream_get_by_id(pos
.stream_id
);
2717 reply_code
= LTTNG_ERR_INVALID
;
2722 pthread_mutex_lock(&stream
->lock
);
2723 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
, pos
.rotate_at_seq_num
);
2724 pthread_mutex_unlock(&stream
->lock
);
2726 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2734 reply_code
= LTTNG_OK
;
2741 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2742 send_ret
= conn
->sock
->ops
->sendmsg(
2743 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2744 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2745 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret
);
2749 lttng_trace_chunk_put(next_trace_chunk
);
2754 * relay_create_trace_chunk: create a new trace chunk
2756 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2757 __attribute__((unused
)),
2758 struct relay_connection
*conn
,
2759 const struct lttng_buffer_view
*payload
)
2763 struct relay_session
*session
= conn
->session
;
2764 struct lttcomm_relayd_create_trace_chunk
*msg
;
2765 struct lttcomm_relayd_generic_reply reply
= {};
2766 struct lttng_buffer_view header_view
;
2767 struct lttng_trace_chunk
*chunk
= nullptr, *published_chunk
= nullptr;
2768 enum lttng_error_code reply_code
= LTTNG_OK
;
2769 enum lttng_trace_chunk_status chunk_status
;
2770 const char *new_path
;
2772 if (!session
|| !conn
->version_check_done
) {
2773 ERR("Trying to create a trace chunk before version check");
2778 if (session
->major
== 2 && session
->minor
< 11) {
2779 ERR("Chunk creation command is unsupported before 2.11");
2784 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2785 if (!lttng_buffer_view_is_valid(&header_view
)) {
2786 ERR("Failed to receive payload of chunk creation command");
2791 /* Convert to host endianness. */
2792 msg
= (typeof(msg
)) header_view
.data
;
2793 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2794 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2795 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2797 pthread_mutex_lock(&conn
->session
->lock
);
2798 session
->ongoing_rotation
= true;
2799 if (session
->current_trace_chunk
&&
2800 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2801 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2802 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2803 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2804 ERR("Failed to rename old chunk");
2806 reply_code
= LTTNG_ERR_UNK
;
2810 if (!session
->current_trace_chunk
) {
2811 if (!session
->has_rotated
) {
2817 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2819 chunk
= lttng_trace_chunk_create(msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2821 ERR("Failed to create trace chunk in trace chunk creation command");
2823 reply_code
= LTTNG_ERR_NOMEM
;
2826 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2828 if (msg
->override_name_length
) {
2830 const struct lttng_buffer_view chunk_name_view
= lttng_buffer_view_from_view(
2831 payload
, sizeof(*msg
), msg
->override_name_length
);
2833 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2834 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2836 reply_code
= LTTNG_ERR_INVALID
;
2840 name
= chunk_name_view
.data
;
2841 if (name
[msg
->override_name_length
- 1]) {
2842 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2844 reply_code
= LTTNG_ERR_INVALID
;
2848 chunk_status
= lttng_trace_chunk_override_name(chunk
, chunk_name_view
.data
);
2849 switch (chunk_status
) {
2850 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2852 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2853 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2854 reply_code
= LTTNG_ERR_INVALID
;
2858 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2859 reply_code
= LTTNG_ERR_UNK
;
2865 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2866 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2867 reply_code
= LTTNG_ERR_UNK
;
2872 LTTNG_ASSERT(conn
->session
->output_directory
);
2873 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, conn
->session
->output_directory
);
2874 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2875 reply_code
= LTTNG_ERR_UNK
;
2880 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2881 sessiond_trace_chunk_registry
,
2882 conn
->session
->sessiond_uuid
,
2883 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2886 if (!published_chunk
) {
2887 char uuid_str
[LTTNG_UUID_STR_LEN
];
2889 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2890 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2891 ", chunk_id = %" PRIu64
,
2896 reply_code
= LTTNG_ERR_NOMEM
;
2900 if (conn
->session
->pending_closure_trace_chunk
) {
2902 * Invalid; this means a second create_trace_chunk command was
2903 * received before a close_trace_chunk.
2905 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2906 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2910 conn
->session
->pending_closure_trace_chunk
= conn
->session
->current_trace_chunk
;
2911 conn
->session
->current_trace_chunk
= published_chunk
;
2912 published_chunk
= nullptr;
2913 if (!conn
->session
->pending_closure_trace_chunk
) {
2914 session
->ongoing_rotation
= false;
2917 pthread_mutex_unlock(&conn
->session
->lock
);
2918 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2919 send_ret
= conn
->sock
->ops
->sendmsg(
2920 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2921 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2922 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
2926 lttng_trace_chunk_put(chunk
);
2927 lttng_trace_chunk_put(published_chunk
);
2932 * relay_close_trace_chunk: close a trace chunk
2934 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2935 __attribute__((unused
)),
2936 struct relay_connection
*conn
,
2937 const struct lttng_buffer_view
*payload
)
2939 int ret
= 0, buf_ret
;
2941 struct relay_session
*session
= conn
->session
;
2942 struct lttcomm_relayd_close_trace_chunk
*msg
;
2943 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2944 struct lttng_buffer_view header_view
;
2945 struct lttng_trace_chunk
*chunk
= nullptr;
2946 enum lttng_error_code reply_code
= LTTNG_OK
;
2947 enum lttng_trace_chunk_status chunk_status
;
2949 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2950 time_t close_timestamp
;
2951 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2952 size_t path_length
= 0;
2953 const char *chunk_name
= nullptr;
2954 struct lttng_dynamic_buffer reply_payload
;
2955 const char *new_path
;
2957 lttng_dynamic_buffer_init(&reply_payload
);
2959 if (!session
|| !conn
->version_check_done
) {
2960 ERR("Trying to close a trace chunk before version check");
2965 if (session
->major
== 2 && session
->minor
< 11) {
2966 ERR("Chunk close command is unsupported before 2.11");
2971 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2972 if (!lttng_buffer_view_is_valid(&header_view
)) {
2973 ERR("Failed to receive payload of chunk close command");
2978 /* Convert to host endianness. */
2979 msg
= (typeof(msg
)) header_view
.data
;
2980 chunk_id
= be64toh(msg
->chunk_id
);
2981 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2982 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2983 close_command
.is_set
= msg
->close_command
.is_set
;
2985 chunk
= sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry
,
2986 conn
->session
->sessiond_uuid
,
2987 conn
->session
->id_sessiond
.is_set
?
2988 conn
->session
->id_sessiond
.value
:
2992 char uuid_str
[LTTNG_UUID_STR_LEN
];
2994 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2995 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
2996 ", chunk_id = %" PRIu64
,
3001 reply_code
= LTTNG_ERR_NOMEM
;
3005 pthread_mutex_lock(&session
->lock
);
3006 if (close_command
.is_set
&& close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3008 * Clear command. It is a protocol error to ask for a
3009 * clear on a relay which does not allow it. Querying
3010 * the configuration allows figuring out whether
3011 * clearing is allowed before doing the clear.
3013 if (!opt_allow_clear
) {
3015 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3016 goto end_unlock_session
;
3019 if (session
->pending_closure_trace_chunk
&& session
->pending_closure_trace_chunk
!= chunk
) {
3020 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3021 session
->session_name
);
3022 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3024 goto end_unlock_session
;
3027 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3028 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3029 if (close_command
.is_set
&&
3030 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3031 !session
->has_rotated
) {
3032 /* New chunk stays in session output directory. */
3035 /* Use chunk name for new chunk. */
3038 /* Rename new chunk path. */
3040 lttng_trace_chunk_rename_path(session
->current_trace_chunk
, new_path
);
3041 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3043 goto end_unlock_session
;
3045 session
->ongoing_rotation
= false;
3047 if ((!close_command
.is_set
||
3048 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3049 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3050 const char *old_path
;
3052 if (!session
->has_rotated
) {
3057 /* We need to move back the .tmp_old_chunk to its rightful place. */
3058 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3059 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3061 goto end_unlock_session
;
3064 chunk_status
= lttng_trace_chunk_set_close_timestamp(chunk
, close_timestamp
);
3065 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3066 ERR("Failed to set trace chunk close timestamp");
3068 reply_code
= LTTNG_ERR_UNK
;
3069 goto end_unlock_session
;
3072 if (close_command
.is_set
) {
3073 chunk_status
= lttng_trace_chunk_set_close_command(chunk
, close_command
.value
);
3074 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3076 reply_code
= LTTNG_ERR_INVALID
;
3077 goto end_unlock_session
;
3080 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, nullptr);
3081 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3082 ERR("Failed to get chunk name");
3084 reply_code
= LTTNG_ERR_UNK
;
3085 goto end_unlock_session
;
3087 if (!session
->has_rotated
&& !session
->snapshot
) {
3088 ret
= lttng_strncpy(closed_trace_chunk_path
,
3089 session
->output_path
,
3090 sizeof(closed_trace_chunk_path
));
3092 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3093 strlen(session
->output_path
),
3094 sizeof(closed_trace_chunk_path
));
3095 reply_code
= LTTNG_ERR_NOMEM
;
3097 goto end_unlock_session
;
3100 if (session
->snapshot
) {
3101 ret
= snprintf(closed_trace_chunk_path
,
3102 sizeof(closed_trace_chunk_path
),
3104 session
->output_path
,
3107 ret
= snprintf(closed_trace_chunk_path
,
3108 sizeof(closed_trace_chunk_path
),
3109 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
"/%s",
3110 session
->output_path
,
3113 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3114 ERR("Failed to format closed trace chunk resulting path");
3115 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3117 goto end_unlock_session
;
3120 if (close_command
.is_set
&&
3121 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3122 session
->has_rotated
= true;
3124 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3125 path_length
= strlen(closed_trace_chunk_path
) + 1;
3126 if (path_length
> UINT32_MAX
) {
3127 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3129 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3130 goto end_unlock_session
;
3133 if (session
->current_trace_chunk
== chunk
) {
3135 * After a trace chunk close command, no new streams
3136 * referencing the chunk may be created. Hence, on the
3137 * event that no new trace chunk have been created for
3138 * the session, the reference to the current trace chunk
3139 * is released in order to allow it to be reclaimed when
3140 * the last stream releases its reference to it.
3142 lttng_trace_chunk_put(session
->current_trace_chunk
);
3143 session
->current_trace_chunk
= nullptr;
3145 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3146 session
->pending_closure_trace_chunk
= nullptr;
3148 pthread_mutex_unlock(&session
->lock
);
3151 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3152 reply
.path_length
= htobe32((uint32_t) path_length
);
3153 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
3155 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3159 if (reply_code
== LTTNG_OK
) {
3160 buf_ret
= lttng_dynamic_buffer_append(
3161 &reply_payload
, closed_trace_chunk_path
, path_length
);
3163 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3168 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
3169 if (send_ret
< reply_payload
.size
) {
3170 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3177 lttng_trace_chunk_put(chunk
);
3178 lttng_dynamic_buffer_reset(&reply_payload
);
3183 * relay_trace_chunk_exists: check if a trace chunk exists
3185 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
3186 __attribute__((unused
)),
3187 struct relay_connection
*conn
,
3188 const struct lttng_buffer_view
*payload
)
3192 struct relay_session
*session
= conn
->session
;
3193 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3194 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3195 struct lttng_buffer_view header_view
;
3199 if (!session
|| !conn
->version_check_done
) {
3200 ERR("Trying to check for the presence of a trace chunk before version check");
3205 if (session
->major
== 2 && session
->minor
< 11) {
3206 ERR("Chunk exists command is unsupported before 2.11");
3211 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3212 if (!lttng_buffer_view_is_valid(&header_view
)) {
3213 ERR("Failed to receive payload of chunk exists command");
3218 /* Convert to host endianness. */
3219 msg
= (typeof(msg
)) header_view
.data
;
3220 chunk_id
= be64toh(msg
->chunk_id
);
3222 ret
= sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry
,
3223 conn
->session
->sessiond_uuid
,
3228 * If ret is not 0, send the reply and report the error to the caller.
3229 * It is a protocol (or internal) error and the session/connection
3230 * should be torn down.
3232 reply
.generic
.ret_code
=
3233 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3234 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3236 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3237 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3238 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
3246 * relay_get_configuration: query whether feature is available
3248 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
3249 __attribute__((unused
)),
3250 struct relay_connection
*conn
,
3251 const struct lttng_buffer_view
*payload
)
3255 struct lttcomm_relayd_get_configuration
*msg
;
3256 struct lttcomm_relayd_get_configuration_reply reply
= {};
3257 struct lttng_buffer_view header_view
;
3258 uint64_t query_flags
= 0;
3259 uint64_t result_flags
= 0;
3261 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3262 if (!lttng_buffer_view_is_valid(&header_view
)) {
3263 ERR("Failed to receive payload of chunk close command");
3268 /* Convert to host endianness. */
3269 msg
= (typeof(msg
)) header_view
.data
;
3270 query_flags
= be64toh(msg
->query_flags
);
3273 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3276 if (opt_allow_clear
) {
3277 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3281 reply
.generic
.ret_code
=
3282 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3283 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3285 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3286 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3287 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3294 static int relay_process_control_command(struct relay_connection
*conn
,
3295 const struct lttcomm_relayd_hdr
*header
,
3296 const struct lttng_buffer_view
*payload
)
3300 DBG3("Processing \"%s\" command for socket %i",
3301 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3303 switch (header
->cmd
) {
3304 case RELAYD_CREATE_SESSION
:
3305 ret
= relay_create_session(header
, conn
, payload
);
3307 case RELAYD_ADD_STREAM
:
3308 ret
= relay_add_stream(header
, conn
, payload
);
3310 case RELAYD_START_DATA
:
3311 ret
= relay_start(header
, conn
, payload
);
3313 case RELAYD_SEND_METADATA
:
3314 ret
= relay_recv_metadata(header
, conn
, payload
);
3316 case RELAYD_VERSION
:
3317 ret
= relay_send_version(header
, conn
, payload
);
3319 case RELAYD_CLOSE_STREAM
:
3320 ret
= relay_close_stream(header
, conn
, payload
);
3322 case RELAYD_DATA_PENDING
:
3323 ret
= relay_data_pending(header
, conn
, payload
);
3325 case RELAYD_QUIESCENT_CONTROL
:
3326 ret
= relay_quiescent_control(header
, conn
, payload
);
3328 case RELAYD_BEGIN_DATA_PENDING
:
3329 ret
= relay_begin_data_pending(header
, conn
, payload
);
3331 case RELAYD_END_DATA_PENDING
:
3332 ret
= relay_end_data_pending(header
, conn
, payload
);
3334 case RELAYD_SEND_INDEX
:
3335 ret
= relay_recv_index(header
, conn
, payload
);
3337 case RELAYD_STREAMS_SENT
:
3338 ret
= relay_streams_sent(header
, conn
, payload
);
3340 case RELAYD_RESET_METADATA
:
3341 ret
= relay_reset_metadata(header
, conn
, payload
);
3343 case RELAYD_ROTATE_STREAMS
:
3344 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3346 case RELAYD_CREATE_TRACE_CHUNK
:
3347 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3349 case RELAYD_CLOSE_TRACE_CHUNK
:
3350 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3352 case RELAYD_TRACE_CHUNK_EXISTS
:
3353 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3355 case RELAYD_GET_CONFIGURATION
:
3356 ret
= relay_get_configuration(header
, conn
, payload
);
3358 case RELAYD_UPDATE_SYNC_INFO
:
3360 ERR("Received unknown command (%u)", header
->cmd
);
3361 relay_unknown_command(conn
);
3370 static enum relay_connection_status
3371 relay_process_control_receive_payload(struct relay_connection
*conn
)
3374 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3375 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3376 struct ctrl_connection_state_receive_payload
*state
=
3377 &conn
->protocol
.ctrl
.state
.receive_payload
;
3378 struct lttng_buffer_view payload_view
;
3380 if (state
->left_to_receive
== 0) {
3381 /* Short-circuit for payload-less commands. */
3382 goto reception_complete
;
3385 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3386 reception_buffer
->data
+ state
->received
,
3387 state
->left_to_receive
,
3391 DIAGNOSTIC_IGNORE_LOGICAL_OP
3392 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3394 PERROR("Unable to receive command payload on sock %d", conn
->sock
->fd
);
3395 status
= RELAY_CONNECTION_STATUS_ERROR
;
3398 } else if (ret
== 0) {
3399 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3400 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3404 LTTNG_ASSERT(ret
> 0);
3405 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3407 state
->left_to_receive
-= ret
;
3408 state
->received
+= ret
;
3410 if (state
->left_to_receive
> 0) {
3412 * Can't transition to the protocol's next state, wait to
3413 * receive the rest of the header.
3415 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3416 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3418 state
->left_to_receive
,
3424 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3428 * The payload required to process the command has been received.
3429 * A view to the reception buffer is forwarded to the various
3430 * commands and the state of the control is reset on success.
3432 * Commands are responsible for sending their reply to the peer.
3434 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
, 0, -1);
3435 ret
= relay_process_control_command(conn
, &state
->header
, &payload_view
);
3437 status
= RELAY_CONNECTION_STATUS_ERROR
;
3441 ret
= connection_reset_protocol_state(conn
);
3443 status
= RELAY_CONNECTION_STATUS_ERROR
;
3449 static enum relay_connection_status
3450 relay_process_control_receive_header(struct relay_connection
*conn
)
3453 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3454 struct lttcomm_relayd_hdr header
;
3455 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3456 struct ctrl_connection_state_receive_header
*state
=
3457 &conn
->protocol
.ctrl
.state
.receive_header
;
3459 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3461 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3462 reception_buffer
->data
+ state
->received
,
3463 state
->left_to_receive
,
3467 DIAGNOSTIC_IGNORE_LOGICAL_OP
3468 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3470 PERROR("Unable to receive control command header on sock %d",
3472 status
= RELAY_CONNECTION_STATUS_ERROR
;
3475 } else if (ret
== 0) {
3476 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3477 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3481 LTTNG_ASSERT(ret
> 0);
3482 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3484 state
->left_to_receive
-= ret
;
3485 state
->received
+= ret
;
3487 if (state
->left_to_receive
> 0) {
3489 * Can't transition to the protocol's next state, wait to
3490 * receive the rest of the header.
3492 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3493 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3495 state
->left_to_receive
,
3500 /* Transition to next state: receiving the command's payload. */
3501 conn
->protocol
.ctrl
.state_id
= CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3502 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3503 header
.circuit_id
= be64toh(header
.circuit_id
);
3504 header
.data_size
= be64toh(header
.data_size
);
3505 header
.cmd
= be32toh(header
.cmd
);
3506 header
.cmd_version
= be32toh(header
.cmd_version
);
3507 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
, &header
, sizeof(header
));
3509 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3510 ", payload size = %" PRIu64
" bytes",
3512 lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3516 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3517 ERR("Command header indicates a payload (%" PRIu64
3518 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3520 status
= RELAY_CONNECTION_STATUS_ERROR
;
3524 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3525 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3526 ret
= lttng_dynamic_buffer_set_size(reception_buffer
, header
.data_size
);
3528 status
= RELAY_CONNECTION_STATUS_ERROR
;
3532 if (header
.data_size
== 0) {
3534 * Manually invoke the next state as the poll loop
3535 * will not wake-up to allow us to proceed further.
3537 status
= relay_process_control_receive_payload(conn
);
3544 * Process the commands received on the control socket
3546 static enum relay_connection_status
relay_process_control(struct relay_connection
*conn
)
3548 enum relay_connection_status status
;
3550 switch (conn
->protocol
.ctrl
.state_id
) {
3551 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3552 status
= relay_process_control_receive_header(conn
);
3554 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3555 status
= relay_process_control_receive_payload(conn
);
3558 ERR("Unknown control connection protocol state encountered.");
3565 static enum relay_connection_status
relay_process_data_receive_header(struct relay_connection
*conn
)
3568 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3569 struct data_connection_state_receive_header
*state
=
3570 &conn
->protocol
.data
.state
.receive_header
;
3571 struct lttcomm_relayd_data_hdr header
;
3572 struct relay_stream
*stream
;
3574 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3576 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3577 state
->header_reception_buffer
+ state
->received
,
3578 state
->left_to_receive
,
3582 DIAGNOSTIC_IGNORE_LOGICAL_OP
3583 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3585 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3586 status
= RELAY_CONNECTION_STATUS_ERROR
;
3589 } else if (ret
== 0) {
3590 /* Orderly shutdown. Not necessary to print an error. */
3591 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3592 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3596 LTTNG_ASSERT(ret
> 0);
3597 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3599 state
->left_to_receive
-= ret
;
3600 state
->received
+= ret
;
3602 if (state
->left_to_receive
> 0) {
3604 * Can't transition to the protocol's next state, wait to
3605 * receive the rest of the header.
3607 DBG3("Partial reception of data connection header (received %" PRIu64
3608 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3610 state
->left_to_receive
,
3615 /* Transition to next state: receiving the payload. */
3616 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3618 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3619 header
.circuit_id
= be64toh(header
.circuit_id
);
3620 header
.stream_id
= be64toh(header
.stream_id
);
3621 header
.data_size
= be32toh(header
.data_size
);
3622 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3623 header
.padding_size
= be32toh(header
.padding_size
);
3624 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3626 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3627 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3628 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3630 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3631 ", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
3632 ", padding_size = %" PRIu32
,
3638 header
.padding_size
);
3640 stream
= stream_get_by_id(header
.stream_id
);
3642 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3644 /* Protocol error. */
3645 status
= RELAY_CONNECTION_STATUS_ERROR
;
3649 pthread_mutex_lock(&stream
->lock
);
3650 /* Prepare stream for the reception of a new packet. */
3651 ret
= stream_init_packet(
3652 stream
, header
.data_size
, &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3653 pthread_mutex_unlock(&stream
->lock
);
3655 ERR("Failed to rotate stream output file");
3656 status
= RELAY_CONNECTION_STATUS_ERROR
;
3657 goto end_stream_unlock
;
3666 static enum relay_connection_status
3667 relay_process_data_receive_payload(struct relay_connection
*conn
)
3670 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3671 struct relay_stream
*stream
;
3672 struct data_connection_state_receive_payload
*state
=
3673 &conn
->protocol
.data
.state
.receive_payload
;
3674 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3675 char data_buffer
[chunk_size
];
3676 bool partial_recv
= false;
3677 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3678 uint64_t left_to_receive
= state
->left_to_receive
;
3679 struct relay_session
*session
;
3681 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
3682 " bytes received, %" PRIu64
" bytes left to receive",
3683 state
->header
.stream_id
,
3684 state
->header
.net_seq_num
,
3688 stream
= stream_get_by_id(state
->header
.stream_id
);
3690 /* Protocol error. */
3691 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3692 state
->header
.stream_id
);
3693 status
= RELAY_CONNECTION_STATUS_ERROR
;
3697 pthread_mutex_lock(&stream
->lock
);
3698 session
= stream
->trace
->session
;
3699 if (!conn
->session
) {
3700 ret
= connection_set_session(conn
, session
);
3702 status
= RELAY_CONNECTION_STATUS_ERROR
;
3703 goto end_stream_unlock
;
3708 * The size of the "chunk" received on any iteration is bounded by:
3709 * - the data left to receive,
3710 * - the data immediately available on the socket,
3711 * - the on-stack data buffer
3713 while (left_to_receive
> 0 && !partial_recv
) {
3714 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3715 struct lttng_buffer_view packet_chunk
;
3717 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, MSG_DONTWAIT
);
3720 DIAGNOSTIC_IGNORE_LOGICAL_OP
3721 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3723 PERROR("Socket %d error", conn
->sock
->fd
);
3724 status
= RELAY_CONNECTION_STATUS_ERROR
;
3726 goto end_stream_unlock
;
3727 } else if (ret
== 0) {
3728 /* No more data ready to be consumed on socket. */
3729 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3730 state
->header
.stream_id
);
3731 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3733 } else if (ret
< (int) recv_size
) {
3735 * All the data available on the socket has been
3738 partial_recv
= true;
3742 packet_chunk
= lttng_buffer_view_init(data_buffer
, 0, recv_size
);
3743 LTTNG_ASSERT(packet_chunk
.data
);
3745 ret
= stream_write(stream
, &packet_chunk
, 0);
3747 ERR("Relay error writing data to file");
3748 status
= RELAY_CONNECTION_STATUS_ERROR
;
3749 goto end_stream_unlock
;
3752 left_to_receive
-= recv_size
;
3753 state
->received
+= recv_size
;
3754 state
->left_to_receive
= left_to_receive
;
3757 if (state
->left_to_receive
> 0) {
3759 * Did not receive all the data expected, wait for more data to
3760 * become available on the socket.
3762 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
3763 " bytes received, %" PRIu64
" bytes left to receive",
3764 state
->header
.stream_id
,
3766 state
->left_to_receive
);
3767 goto end_stream_unlock
;
3770 ret
= stream_write(stream
, nullptr, state
->header
.padding_size
);
3772 status
= RELAY_CONNECTION_STATUS_ERROR
;
3773 goto end_stream_unlock
;
3776 if (session_streams_have_index(session
)) {
3777 ret
= stream_update_index(stream
,
3778 state
->header
.net_seq_num
,
3779 state
->rotate_index
,
3781 state
->header
.data_size
+ state
->header
.padding_size
);
3783 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
3785 stream
->stream_handle
,
3786 state
->header
.net_seq_num
,
3788 status
= RELAY_CONNECTION_STATUS_ERROR
;
3789 goto end_stream_unlock
;
3793 if (stream
->prev_data_seq
== -1ULL) {
3797 ret
= stream_complete_packet(stream
,
3798 state
->header
.data_size
+ state
->header
.padding_size
,
3799 state
->header
.net_seq_num
,
3802 status
= RELAY_CONNECTION_STATUS_ERROR
;
3803 goto end_stream_unlock
;
3807 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3808 * contents of *state which are aliased (union) to the same location as
3809 * the new state. Don't use it beyond this point.
3811 connection_reset_protocol_state(conn
);
3815 close_requested
= stream
->close_requested
;
3816 pthread_mutex_unlock(&stream
->lock
);
3817 if (close_requested
&& left_to_receive
== 0) {
3818 try_stream_close(stream
);
3822 pthread_mutex_lock(&session
->lock
);
3823 uatomic_set(&session
->new_streams
, 1);
3824 pthread_mutex_unlock(&session
->lock
);
3833 * relay_process_data: Process the data received on the data socket
3835 static enum relay_connection_status
relay_process_data(struct relay_connection
*conn
)
3837 enum relay_connection_status status
;
3839 switch (conn
->protocol
.data
.state_id
) {
3840 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3841 status
= relay_process_data_receive_header(conn
);
3843 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3844 status
= relay_process_data_receive_payload(conn
);
3847 ERR("Unexpected data connection communication state.");
3854 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3858 (void) lttng_poll_del(events
, pollfd
);
3860 ret
= fd_tracker_close_unsuspendable_fd(
3861 the_fd_tracker
, &pollfd
, 1, fd_tracker_util_close_fd
, nullptr);
3863 ERR("Closing pollfd %d", pollfd
);
3867 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3869 struct relay_connection
*conn
)
3871 const char *type_str
;
3873 switch (conn
->type
) {
3878 type_str
= "Control";
3880 case RELAY_VIEWER_COMMAND
:
3881 type_str
= "Viewer Command";
3883 case RELAY_VIEWER_NOTIFICATION
:
3884 type_str
= "Viewer Notification";
3887 type_str
= "Unknown";
3889 cleanup_connection_pollfd(events
, pollfd
);
3890 connection_put(conn
);
3891 DBG("%s connection closed with %d", type_str
, pollfd
);
3895 * This thread does the actual work
3897 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3899 int ret
, err
= -1, last_seen_data_fd
= -1;
3901 struct lttng_poll_event events
;
3902 struct lttng_ht
*relay_connections_ht
;
3903 struct lttng_ht_iter iter
;
3904 struct relay_connection
*destroy_conn
= nullptr;
3906 DBG("[thread] Relay worker started");
3908 rcu_register_thread();
3910 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3912 if (testpoint(relayd_thread_worker
)) {
3913 goto error_testpoint
;
3916 health_code_update();
3918 /* table of connections indexed on socket */
3919 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3920 if (!relay_connections_ht
) {
3921 goto relay_connections_ht_error
;
3924 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3926 goto error_poll_create
;
3929 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3936 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3938 health_code_update();
3940 /* Infinite blocking call, waiting for transmission */
3941 DBG3("Relayd worker thread polling...");
3942 health_poll_entry();
3943 ret
= lttng_poll_wait(&events
, -1);
3947 * Restart interrupted system call.
3949 if (errno
== EINTR
) {
3958 * Process control. The control connection is
3959 * prioritized so we don't starve it with high
3960 * throughput tracing data on the data connection.
3962 for (i
= 0; i
< nb_fd
; i
++) {
3963 /* Fetch once the poll data */
3964 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
3965 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3967 health_code_update();
3969 /* Activity on thread quit pipe, exiting. */
3970 if (relayd_is_thread_quit_pipe(pollfd
)) {
3971 DBG("Activity on thread quit pipe");
3976 /* Inspect the relay conn pipe for new connection */
3977 if (pollfd
== relay_conn_pipe
[0]) {
3978 if (revents
& LPOLLIN
) {
3979 struct relay_connection
*conn
;
3981 ret
= lttng_read(relay_conn_pipe
[0],
3983 sizeof(conn
)); /* NOLINT sizeof used on a
3988 ret
= lttng_poll_add(
3989 &events
, conn
->sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
3991 ERR("Failed to add new connection file descriptor to poll set");
3994 connection_ht_add(relay_connections_ht
, conn
);
3995 DBG("Connection socket %d added", conn
->sock
->fd
);
3996 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3997 ERR("Relay connection pipe error");
4000 ERR("Unexpected poll events %u for sock %d",
4006 struct relay_connection
*ctrl_conn
;
4008 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4009 /* If not found, there is a synchronization issue. */
4010 LTTNG_ASSERT(ctrl_conn
);
4012 if (ctrl_conn
->type
== RELAY_DATA
) {
4013 if (revents
& LPOLLIN
) {
4015 * Flag the last seen data fd not deleted. It will
4016 * be used as the last seen fd if any fd gets
4017 * deleted in this first loop.
4019 last_notdel_data_fd
= pollfd
;
4021 goto put_ctrl_connection
;
4023 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4025 if (revents
& LPOLLIN
) {
4026 enum relay_connection_status status
;
4028 status
= relay_process_control(ctrl_conn
);
4029 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4031 * On socket error flag the session as aborted to
4032 * force the cleanup of its stream otherwise it can
4033 * leak during the lifetime of the relayd.
4035 * This prevents situations in which streams can be
4036 * left opened because an index was received, the
4037 * control connection is closed, and the data
4038 * connection is closed (uncleanly) before the
4039 * packet's data provided.
4041 * Since the control connection encountered an
4042 * error, it is okay to be conservative and close
4043 * the session right now as we can't rely on the
4044 * protocol being respected anymore.
4046 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4047 session_abort(ctrl_conn
->session
);
4050 /* Clear the connection on error or close. */
4051 relay_thread_close_connection(
4052 &events
, pollfd
, ctrl_conn
);
4055 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4056 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
4057 if (last_seen_data_fd
== pollfd
) {
4058 last_seen_data_fd
= last_notdel_data_fd
;
4061 ERR("Unexpected poll events %u for control sock %d",
4064 connection_put(ctrl_conn
);
4067 put_ctrl_connection
:
4068 connection_put(ctrl_conn
);
4073 * The last loop handled a control request, go back to poll to make
4074 * sure we prioritise the control socket.
4080 if (last_seen_data_fd
>= 0) {
4081 for (i
= 0; i
< nb_fd
; i
++) {
4082 const int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4084 health_code_update();
4086 if (last_seen_data_fd
== pollfd
) {
4093 /* Process data connection. */
4094 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4095 /* Fetch the poll data. */
4096 const uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4097 const int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4098 struct relay_connection
*data_conn
;
4100 health_code_update();
4103 /* No activity for this FD (poll implementation). */
4107 /* Skip the command pipe. It's handled in the first loop. */
4108 if (pollfd
== relay_conn_pipe
[0]) {
4112 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4114 /* Skip it. Might be removed before. */
4117 if (data_conn
->type
== RELAY_CONTROL
) {
4118 goto put_data_connection
;
4120 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4122 if (revents
& LPOLLIN
) {
4123 enum relay_connection_status status
;
4125 status
= relay_process_data(data_conn
);
4126 /* Connection closed or error. */
4127 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4129 * On socket error flag the session as aborted to force
4130 * the cleanup of its stream otherwise it can leak
4131 * during the lifetime of the relayd.
4133 * This prevents situations in which streams can be
4134 * left opened because an index was received, the
4135 * control connection is closed, and the data
4136 * connection is closed (uncleanly) before the packet's
4139 * Since the data connection encountered an error,
4140 * it is okay to be conservative and close the
4141 * session right now as we can't rely on the protocol
4142 * being respected anymore.
4144 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4145 session_abort(data_conn
->session
);
4147 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4149 * Every goto restart call sets the last seen fd where
4150 * here we don't really care since we gracefully
4151 * continue the loop after the connection is deleted.
4154 /* Keep last seen port. */
4155 last_seen_data_fd
= pollfd
;
4156 connection_put(data_conn
);
4159 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4160 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4162 ERR("Unknown poll events %u for data sock %d", revents
, pollfd
);
4164 put_data_connection
:
4165 connection_put(data_conn
);
4167 last_seen_data_fd
= -1;
4170 /* Normal exit, no error */
4175 /* Cleanup remaining connection object. */
4177 const lttng::urcu::read_lock_guard read_lock
;
4179 cds_lfht_for_each_entry (
4180 relay_connections_ht
->ht
, &iter
.iter
, destroy_conn
, sock_n
.node
) {
4181 health_code_update();
4183 session_abort(destroy_conn
->session
);
4186 * No need to grab another ref, because we own
4189 relay_thread_close_connection(
4190 &events
, destroy_conn
->sock
->fd
, destroy_conn
);
4194 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4196 lttng_ht_destroy(relay_connections_ht
);
4197 relay_connections_ht_error
:
4198 /* Close relay conn pipes */
4199 (void) fd_tracker_util_pipe_close(the_fd_tracker
, relay_conn_pipe
);
4201 DBG("Thread exited with error");
4203 DBG("Worker thread cleanup complete");
4207 ERR("Health error occurred in %s", __func__
);
4209 health_unregister(health_relayd
);
4210 rcu_unregister_thread();
4211 lttng_relay_stop_threads();
4216 * Create the relay command pipe to wake thread_manage_apps.
4217 * Closed in cleanup().
4219 static int create_relay_conn_pipe()
4221 return fd_tracker_util_pipe_open_cloexec(
4222 the_fd_tracker
, "Relayd connection pipe", relay_conn_pipe
);
4225 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4227 fds
[0] = fileno(stdout
);
4228 fds
[1] = fileno(stderr
);
4232 static int track_stdio()
4235 const char *names
[] = { "stdout", "stderr" };
4237 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
, names
, 2, stdio_open
, nullptr);
4243 int main(int argc
, char **argv
)
4245 bool thread_is_rcu_registered
= false;
4246 int ret
= 0, retval
= 0;
4248 char *unlinked_file_directory_path
= nullptr, *output_path
= nullptr;
4250 /* Parse environment variables */
4251 ret
= parse_env_options();
4259 * Command line arguments overwrite environment.
4262 if (set_options(argc
, argv
)) {
4267 if (set_signal_handler()) {
4272 relayd_config_log();
4274 if (opt_print_version
) {
4280 ret
= fclose(stdin
);
4282 PERROR("Failed to close stdin");
4286 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4288 /* Try to create directory if -o, --output is specified. */
4289 if (opt_output_path
) {
4290 if (*opt_output_path
!= '/') {
4291 ERR("Please specify an absolute path for -o, --output PATH");
4296 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
, -1, -1);
4298 ERR("Unable to create %s", opt_output_path
);
4305 if (opt_daemon
|| opt_background
) {
4306 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
, !opt_background
);
4313 if (opt_working_directory
) {
4314 ret
= utils_change_working_directory(opt_working_directory
);
4316 /* All errors are already logged. */
4321 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4322 if (!sessiond_trace_chunk_registry
) {
4323 ERR("Failed to initialize session daemon trace chunk registry");
4329 * The RCU thread registration (and use, through the fd-tracker's
4330 * creation) is done after the daemonization to allow us to not
4331 * deal with liburcu's fork() management as the call RCU needs to
4334 rcu_register_thread();
4335 thread_is_rcu_registered
= true;
4337 output_path
= create_output_path("");
4339 ERR("Failed to get output path");
4343 ret
= asprintf(&unlinked_file_directory_path
,
4346 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4349 ERR("Failed to format unlinked file directory path");
4353 the_fd_tracker
= fd_tracker_create(unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4354 free(unlinked_file_directory_path
);
4355 if (!the_fd_tracker
) {
4360 ret
= track_stdio();
4366 /* Initialize thread health monitoring */
4367 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4368 if (!health_relayd
) {
4369 PERROR("health_app_create error");
4374 /* Create thread quit pipe */
4375 if (relayd_init_thread_quit_pipe()) {
4380 /* Setup the thread apps communication pipe. */
4381 if (create_relay_conn_pipe()) {
4386 /* Init relay command queue. */
4387 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4389 /* Initialize communication library */
4391 lttcomm_inet_init();
4393 /* tables of sessions indexed by session ID */
4394 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4400 /* tables of streams indexed by stream ID */
4401 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4402 if (!relay_streams_ht
) {
4407 /* tables of streams indexed by stream ID */
4408 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4409 if (!viewer_streams_ht
) {
4414 ret
= init_health_quit_pipe();
4420 /* Create thread to manage the client socket */
4421 ret
= pthread_create(&health_thread
,
4422 default_pthread_attr(),
4423 thread_manage_health_relayd
,
4427 PERROR("pthread_create health");
4432 /* Setup the dispatcher thread */
4433 ret
= pthread_create(&dispatcher_thread
,
4434 default_pthread_attr(),
4435 relay_thread_dispatcher
,
4439 PERROR("pthread_create dispatcher");
4441 goto exit_dispatcher_thread
;
4444 /* Setup the worker thread */
4445 ret
= pthread_create(&worker_thread
, default_pthread_attr(), relay_thread_worker
, nullptr);
4448 PERROR("pthread_create worker");
4450 goto exit_worker_thread
;
4453 /* Setup the listener thread */
4454 ret
= pthread_create(
4455 &listener_thread
, default_pthread_attr(), relay_thread_listener
, (void *) nullptr);
4458 PERROR("pthread_create listener");
4460 goto exit_listener_thread
;
4463 ret
= relayd_live_create(live_uri
);
4465 ERR("Starting live viewer threads");
4471 * This is where we start awaiting program completion (e.g. through
4472 * signal that asks threads to teardown).
4475 ret
= relayd_live_join();
4481 ret
= pthread_join(listener_thread
, &status
);
4484 PERROR("pthread_join listener_thread");
4488 exit_listener_thread
:
4489 ret
= pthread_join(worker_thread
, &status
);
4492 PERROR("pthread_join worker_thread");
4497 ret
= pthread_join(dispatcher_thread
, &status
);
4500 PERROR("pthread_join dispatcher_thread");
4503 exit_dispatcher_thread
:
4505 ret
= pthread_join(health_thread
, &status
);
4508 PERROR("pthread_join health_thread");
4513 * Wait for all pending call_rcu work to complete before tearing
4514 * down data structures. call_rcu worker may be trying to
4515 * perform lookups in those structures.
4520 /* Ensure all prior call_rcu are done. */
4523 if (thread_is_rcu_registered
) {
4524 rcu_unregister_thread();