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 :)
1324 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
)); /* NOLINT
1331 PERROR("write connection pipe");
1332 connection_put(new_conn
);
1335 } while (node
!= nullptr);
1337 /* Futex wait on queue. Blocking call on futex() */
1338 health_poll_entry();
1339 futex_nto1_wait(&relay_conn_queue
.futex
);
1343 /* Normal exit, no error */
1350 ERR("Health error occurred in %s", __func__
);
1352 health_unregister(health_relayd
);
1353 DBG("Dispatch thread dying");
1354 lttng_relay_stop_threads();
1358 static bool session_streams_have_index(const struct relay_session
*session
)
1360 return session
->minor
>= 4 && !session
->snapshot
;
1364 * Handle the RELAYD_CREATE_SESSION command.
1366 * On success, send back the session id or else return a negative value.
1368 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1369 struct relay_connection
*conn
,
1370 const struct lttng_buffer_view
*payload
)
1374 struct relay_session
*session
= nullptr;
1375 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1376 char session_name
[LTTNG_NAME_MAX
] = {};
1377 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1378 uint32_t live_timer
= 0;
1379 bool snapshot
= false;
1380 bool session_name_contains_creation_timestamp
= false;
1381 /* Left nil for peers < 2.11. */
1382 char base_path
[LTTNG_PATH_MAX
] = {};
1383 lttng_uuid sessiond_uuid
= {};
1384 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1385 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1386 LTTNG_OPTIONAL(time_t) creation_time
= {};
1387 struct lttng_dynamic_buffer reply_payload
;
1389 lttng_dynamic_buffer_init(&reply_payload
);
1391 if (conn
->minor
< 4) {
1392 /* From 2.1 to 2.3 */
1394 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1395 /* From 2.4 to 2.10 */
1396 ret
= cmd_create_session_2_4(
1397 payload
, session_name
, hostname
, &live_timer
, &snapshot
);
1399 bool has_current_chunk
;
1400 uint64_t current_chunk_id_value
;
1401 time_t creation_time_value
;
1402 uint64_t id_sessiond_value
;
1404 /* From 2.11 to ... */
1405 ret
= cmd_create_session_2_11(payload
,
1414 ¤t_chunk_id_value
,
1415 &creation_time_value
,
1416 &session_name_contains_creation_timestamp
);
1417 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1418 /* The nil UUID is reserved for pre-2.11 clients. */
1419 ERR("Illegal nil UUID announced by peer in create session command");
1423 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1424 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1425 if (has_current_chunk
) {
1426 LTTNG_OPTIONAL_SET(¤t_chunk_id
, current_chunk_id_value
);
1434 session
= session_create(session_name
,
1440 id_sessiond
.is_set
? &id_sessiond
.value
: nullptr,
1441 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: nullptr,
1442 creation_time
.is_set
? &creation_time
.value
: nullptr,
1445 session_name_contains_creation_timestamp
);
1450 LTTNG_ASSERT(!conn
->session
);
1451 conn
->session
= session
;
1452 DBG("Created session %" PRIu64
, session
->id
);
1454 reply
.generic
.session_id
= htobe64(session
->id
);
1458 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1460 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1463 if (conn
->minor
< 11) {
1464 /* From 2.1 to 2.10 */
1465 ret
= lttng_dynamic_buffer_append(
1466 &reply_payload
, &reply
.generic
, sizeof(reply
.generic
));
1468 ERR("Failed to append \"create session\" command reply header to payload buffer");
1473 const uint32_t output_path_length
= session
? strlen(session
->output_path
) + 1 : 0;
1475 reply
.output_path_length
= htobe32(output_path_length
);
1476 ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
1478 ERR("Failed to append \"create session\" command reply header to payload buffer");
1482 if (output_path_length
) {
1483 ret
= lttng_dynamic_buffer_append(
1484 &reply_payload
, session
->output_path
, output_path_length
);
1486 ERR("Failed to append \"create session\" command reply path to payload buffer");
1492 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
1493 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1494 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1500 if (ret
< 0 && session
) {
1501 session_put(session
);
1503 lttng_dynamic_buffer_reset(&reply_payload
);
1508 * When we have received all the streams and the metadata for a channel,
1509 * we make them visible to the viewer threads.
1511 static void publish_connection_local_streams(struct relay_connection
*conn
)
1513 struct relay_stream
*stream
;
1514 struct relay_session
*session
= conn
->session
;
1517 * We publish all streams belonging to a session atomically wrt
1520 pthread_mutex_lock(&session
->lock
);
1521 lttng::urcu::read_lock_guard read_lock
;
1522 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
, recv_node
)
1524 stream_publish(stream
);
1528 * Inform the viewer that there are new streams in the session.
1530 if (session
->viewer_attached
) {
1531 uatomic_set(&session
->new_streams
, 1);
1533 pthread_mutex_unlock(&session
->lock
);
1536 static int conform_channel_path(char *channel_path
)
1540 if (strstr("../", channel_path
)) {
1541 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1547 if (*channel_path
== '/') {
1548 const size_t len
= strlen(channel_path
);
1551 * Channel paths from peers prior to 2.11 are expressed as an
1552 * absolute path that is, in reality, relative to the relay
1553 * daemon's output directory. Remove the leading slash so it
1554 * is correctly interpreted as a relative path later on.
1556 * len (and not len - 1) is used to copy the trailing NULL.
1558 bcopy(channel_path
+ 1, channel_path
, len
);
1565 * relay_add_stream: allocate a new stream for a session
1567 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1568 struct relay_connection
*conn
,
1569 const struct lttng_buffer_view
*payload
)
1573 struct relay_session
*session
= conn
->session
;
1574 struct relay_stream
*stream
= nullptr;
1575 struct lttcomm_relayd_status_stream reply
;
1576 struct ctf_trace
*trace
= nullptr;
1577 uint64_t stream_handle
= -1ULL;
1578 char *path_name
= nullptr, *channel_name
= nullptr;
1579 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1580 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1582 if (!session
|| !conn
->version_check_done
) {
1583 ERR("Trying to add a stream before version check");
1585 goto end_no_session
;
1588 if (session
->minor
== 1) {
1590 ret
= cmd_recv_stream_2_1(payload
, &path_name
, &channel_name
);
1591 } else if (session
->minor
> 1 && session
->minor
< 11) {
1592 /* From 2.2 to 2.10 */
1593 ret
= cmd_recv_stream_2_2(
1594 payload
, &path_name
, &channel_name
, &tracefile_size
, &tracefile_count
);
1596 /* From 2.11 to ... */
1597 ret
= cmd_recv_stream_2_11(payload
,
1602 &stream_chunk_id
.value
);
1603 stream_chunk_id
.is_set
= true;
1610 if (conform_channel_path(path_name
)) {
1615 * Backward compatibility for --group-output-by-session.
1616 * Prior to lttng 2.11, the complete path is passed by the stream.
1617 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1618 * >=2.11 the chunk is responsible for the output path. When dealing
1619 * with producer < 2.11 the chunk output_path is the root output path
1620 * and the stream carries the complete path (path_name).
1621 * To support --group-output-by-session with older producer (<2.11), we
1622 * need to craft the path based on the stream path.
1624 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1625 if (conn
->minor
< 4) {
1627 * From 2.1 to 2.3, the session_name is not passed on
1628 * the RELAYD_CREATE_SESSION command. The session name
1629 * is necessary to detect the presence of a base_path
1630 * inside the stream path. Without it we cannot perform
1631 * a valid group-output-by-session transformation.
1633 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1634 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1637 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1638 char *group_by_session_path_name
;
1640 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1642 group_by_session_path_name
= backward_compat_group_by_session(
1643 path_name
, session
->session_name
, session
->creation_time
.value
);
1644 if (!group_by_session_path_name
) {
1645 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1650 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1652 group_by_session_path_name
);
1655 path_name
= group_by_session_path_name
;
1659 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1664 /* This stream here has one reference on the trace. */
1665 pthread_mutex_lock(&last_relay_stream_id_lock
);
1666 stream_handle
= ++last_relay_stream_id
;
1667 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1669 /* We pass ownership of path_name and channel_name. */
1670 stream
= stream_create(
1671 trace
, stream_handle
, path_name
, channel_name
, tracefile_size
, tracefile_count
);
1672 path_name
= nullptr;
1673 channel_name
= nullptr;
1676 * Streams are the owners of their trace. Reference to trace is
1677 * kept within stream_create().
1679 ctf_trace_put(trace
);
1682 memset(&reply
, 0, sizeof(reply
));
1683 reply
.handle
= htobe64(stream_handle
);
1685 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1687 reply
.ret_code
= htobe32(LTTNG_OK
);
1690 send_ret
= conn
->sock
->ops
->sendmsg(
1691 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_status_stream
), 0);
1692 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1693 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret
);
1704 * relay_close_stream: close a specific stream
1706 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1707 struct relay_connection
*conn
,
1708 const struct lttng_buffer_view
*payload
)
1712 struct relay_session
*session
= conn
->session
;
1713 struct lttcomm_relayd_close_stream stream_info
;
1714 struct lttcomm_relayd_generic_reply reply
;
1715 struct relay_stream
*stream
;
1717 DBG("Close stream received");
1719 if (!session
|| !conn
->version_check_done
) {
1720 ERR("Trying to close a stream before version check");
1722 goto end_no_session
;
1725 if (payload
->size
< sizeof(stream_info
)) {
1726 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1727 sizeof(stream_info
),
1730 goto end_no_session
;
1732 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1733 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1734 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1736 stream
= stream_get_by_id(stream_info
.stream_id
);
1743 * Set last_net_seq_num before the close flag. Required by data
1746 pthread_mutex_lock(&stream
->lock
);
1747 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1748 pthread_mutex_unlock(&stream
->lock
);
1751 * This is one of the conditions which may trigger a stream close
1752 * with the others being:
1753 * 1) A close command is received for a stream
1754 * 2) The control connection owning the stream is closed
1755 * 3) We have received all of the stream's data _after_ a close
1758 try_stream_close(stream
);
1763 memset(&reply
, 0, sizeof(reply
));
1765 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1767 reply
.ret_code
= htobe32(LTTNG_OK
);
1769 send_ret
= conn
->sock
->ops
->sendmsg(
1770 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1771 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1772 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret
);
1781 * relay_reset_metadata: reset a metadata stream
1783 static int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1784 struct relay_connection
*conn
,
1785 const struct lttng_buffer_view
*payload
)
1789 struct relay_session
*session
= conn
->session
;
1790 struct lttcomm_relayd_reset_metadata stream_info
;
1791 struct lttcomm_relayd_generic_reply reply
;
1792 struct relay_stream
*stream
;
1794 DBG("Reset metadata received");
1796 if (!session
|| !conn
->version_check_done
) {
1797 ERR("Trying to reset a metadata stream before version check");
1799 goto end_no_session
;
1802 if (payload
->size
< sizeof(stream_info
)) {
1803 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1804 sizeof(stream_info
),
1807 goto end_no_session
;
1809 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1810 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1811 stream_info
.version
= be64toh(stream_info
.version
);
1813 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1815 /* Unsupported for live sessions for now. */
1816 if (session
->live_timer
!= 0) {
1821 stream
= stream_get_by_id(stream_info
.stream_id
);
1826 pthread_mutex_lock(&stream
->lock
);
1827 if (!stream
->is_metadata
) {
1832 ret
= stream_reset_file(stream
);
1834 ERR("Failed to reset metadata stream %" PRIu64
": stream_path = %s, channel = %s",
1835 stream
->stream_handle
,
1837 stream
->channel_name
);
1841 pthread_mutex_unlock(&stream
->lock
);
1845 memset(&reply
, 0, sizeof(reply
));
1847 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1849 reply
.ret_code
= htobe32(LTTNG_OK
);
1851 send_ret
= conn
->sock
->ops
->sendmsg(
1852 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1853 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1854 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret
);
1863 * relay_unknown_command: send -1 if received unknown command
1865 static void relay_unknown_command(struct relay_connection
*conn
)
1867 struct lttcomm_relayd_generic_reply reply
;
1870 memset(&reply
, 0, sizeof(reply
));
1871 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1872 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1873 if (send_ret
< sizeof(reply
)) {
1874 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1879 * relay_start: send an acknowledgment to the client to tell if we are
1880 * ready to receive data. We are ready if a session is established.
1882 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1883 struct relay_connection
*conn
,
1884 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1888 struct lttcomm_relayd_generic_reply reply
;
1889 struct relay_session
*session
= conn
->session
;
1892 DBG("Trying to start the streaming without a session established");
1893 ret
= htobe32(LTTNG_ERR_UNK
);
1896 memset(&reply
, 0, sizeof(reply
));
1897 reply
.ret_code
= htobe32(LTTNG_OK
);
1898 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1899 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1900 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret
);
1908 * relay_recv_metadata: receive the metadata for the session.
1910 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1911 struct relay_connection
*conn
,
1912 const struct lttng_buffer_view
*payload
)
1915 struct relay_session
*session
= conn
->session
;
1916 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1917 struct relay_stream
*metadata_stream
;
1918 uint64_t metadata_payload_size
;
1919 struct lttng_buffer_view packet_view
;
1922 ERR("Metadata sent before version check");
1927 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1928 ERR("Incorrect data size");
1932 metadata_payload_size
=
1933 recv_hdr
->data_size
- sizeof(struct lttcomm_relayd_metadata_payload
);
1935 memcpy(&metadata_payload_header
, payload
->data
, sizeof(metadata_payload_header
));
1936 metadata_payload_header
.stream_id
= be64toh(metadata_payload_header
.stream_id
);
1937 metadata_payload_header
.padding_size
= be32toh(metadata_payload_header
.padding_size
);
1939 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1940 if (!metadata_stream
) {
1945 packet_view
= lttng_buffer_view_from_view(
1946 payload
, sizeof(metadata_payload_header
), metadata_payload_size
);
1947 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1948 ERR("Invalid metadata packet length announced by header");
1953 pthread_mutex_lock(&metadata_stream
->lock
);
1954 ret
= stream_write(metadata_stream
, &packet_view
, metadata_payload_header
.padding_size
);
1955 pthread_mutex_unlock(&metadata_stream
->lock
);
1961 stream_put(metadata_stream
);
1967 * relay_send_version: send relayd version number
1969 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1970 struct relay_connection
*conn
,
1971 const struct lttng_buffer_view
*payload
)
1975 struct lttcomm_relayd_version reply
, msg
;
1976 bool compatible
= true;
1978 conn
->version_check_done
= true;
1980 /* Get version from the other side. */
1981 if (payload
->size
< sizeof(msg
)) {
1982 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1989 memcpy(&msg
, payload
->data
, sizeof(msg
));
1990 msg
.major
= be32toh(msg
.major
);
1991 msg
.minor
= be32toh(msg
.minor
);
1993 memset(&reply
, 0, sizeof(reply
));
1994 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1995 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1997 /* Major versions must be the same */
1998 if (reply
.major
!= msg
.major
) {
1999 DBG("Incompatible major versions (%u vs %u), deleting session",
2005 conn
->major
= reply
.major
;
2006 /* We adapt to the lowest compatible version */
2007 if (reply
.minor
<= msg
.minor
) {
2008 conn
->minor
= reply
.minor
;
2010 conn
->minor
= msg
.minor
;
2013 reply
.major
= htobe32(reply
.major
);
2014 reply
.minor
= htobe32(reply
.minor
);
2015 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2016 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2017 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret
);
2029 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
2036 * Check for data pending for a given stream id from the session daemon.
2038 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2039 struct relay_connection
*conn
,
2040 const struct lttng_buffer_view
*payload
)
2042 struct relay_session
*session
= conn
->session
;
2043 struct lttcomm_relayd_data_pending msg
;
2044 struct lttcomm_relayd_generic_reply reply
;
2045 struct relay_stream
*stream
;
2048 uint64_t stream_seq
;
2050 DBG("Data pending command received");
2052 if (!session
|| !conn
->version_check_done
) {
2053 ERR("Trying to check for data before version check");
2055 goto end_no_session
;
2058 if (payload
->size
< sizeof(msg
)) {
2059 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2063 goto end_no_session
;
2065 memcpy(&msg
, payload
->data
, sizeof(msg
));
2066 msg
.stream_id
= be64toh(msg
.stream_id
);
2067 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2069 stream
= stream_get_by_id(msg
.stream_id
);
2070 if (stream
== nullptr) {
2075 pthread_mutex_lock(&stream
->lock
);
2077 if (session_streams_have_index(session
)) {
2079 * Ensure that both the index and stream data have been
2080 * flushed up to the requested point.
2082 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2084 stream_seq
= stream
->prev_data_seq
;
2086 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2087 ", prev_index_seq %" PRIu64
", and last_seq %" PRIu64
,
2089 stream
->prev_data_seq
,
2090 stream
->prev_index_seq
,
2091 msg
.last_net_seq_num
);
2093 /* Avoid wrapping issue */
2094 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2095 /* Data has in fact been written and is NOT pending */
2098 /* Data still being streamed thus pending */
2102 stream
->data_pending_check_done
= true;
2103 pthread_mutex_unlock(&stream
->lock
);
2108 memset(&reply
, 0, sizeof(reply
));
2109 reply
.ret_code
= htobe32(ret
);
2110 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2111 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2112 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret
);
2121 * Wait for the control socket to reach a quiescent state.
2123 * Note that for now, when receiving this command from the session
2124 * daemon, this means that every subsequent commands or data received on
2125 * the control socket has been handled. So, this is why we simply return
2128 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
2129 __attribute__((unused
)),
2130 struct relay_connection
*conn
,
2131 const struct lttng_buffer_view
*payload
)
2135 struct relay_stream
*stream
;
2136 struct lttcomm_relayd_quiescent_control msg
;
2137 struct lttcomm_relayd_generic_reply reply
;
2139 DBG("Checking quiescent state on control socket");
2141 if (!conn
->session
|| !conn
->version_check_done
) {
2142 ERR("Trying to check for data before version check");
2144 goto end_no_session
;
2147 if (payload
->size
< sizeof(msg
)) {
2148 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2152 goto end_no_session
;
2154 memcpy(&msg
, payload
->data
, sizeof(msg
));
2155 msg
.stream_id
= be64toh(msg
.stream_id
);
2157 stream
= stream_get_by_id(msg
.stream_id
);
2161 pthread_mutex_lock(&stream
->lock
);
2162 stream
->data_pending_check_done
= true;
2163 pthread_mutex_unlock(&stream
->lock
);
2165 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2168 memset(&reply
, 0, sizeof(reply
));
2169 reply
.ret_code
= htobe32(LTTNG_OK
);
2170 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2171 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2172 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret
);
2183 * Initialize a data pending command. This means that a consumer is about
2184 * to ask for data pending for each stream it holds. Simply iterate over
2185 * all streams of a session and set the data_pending_check_done flag.
2187 * This command returns to the client a LTTNG_OK code.
2189 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2190 struct relay_connection
*conn
,
2191 const struct lttng_buffer_view
*payload
)
2195 struct lttng_ht_iter iter
;
2196 struct lttcomm_relayd_begin_data_pending msg
;
2197 struct lttcomm_relayd_generic_reply reply
;
2198 struct relay_stream
*stream
;
2200 LTTNG_ASSERT(recv_hdr
);
2203 DBG("Init streams for data pending");
2205 if (!conn
->session
|| !conn
->version_check_done
) {
2206 ERR("Trying to check for data before version check");
2208 goto end_no_session
;
2211 if (payload
->size
< sizeof(msg
)) {
2212 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2216 goto end_no_session
;
2218 memcpy(&msg
, payload
->data
, sizeof(msg
));
2219 msg
.session_id
= be64toh(msg
.session_id
);
2222 * Iterate over all streams to set the begin data pending flag.
2223 * For now, the streams are indexed by stream handle so we have
2224 * to iterate over all streams to find the one associated with
2225 * the right session_id.
2228 lttng::urcu::read_lock_guard read_lock
;
2230 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2231 if (!stream_get(stream
)) {
2235 if (stream
->trace
->session
->id
== msg
.session_id
) {
2236 pthread_mutex_lock(&stream
->lock
);
2237 stream
->data_pending_check_done
= false;
2238 pthread_mutex_unlock(&stream
->lock
);
2239 DBG("Set begin data pending flag to stream %" PRIu64
,
2240 stream
->stream_handle
);
2247 memset(&reply
, 0, sizeof(reply
));
2248 /* All good, send back reply. */
2249 reply
.ret_code
= htobe32(LTTNG_OK
);
2251 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2252 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2253 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret
);
2264 * End data pending command. This will check, for a given session id, if
2265 * each stream associated with it has its data_pending_check_done flag
2266 * set. If not, this means that the client lost track of the stream but
2267 * the data is still being streamed on our side. In this case, we inform
2268 * the client that data is in flight.
2270 * Return to the client if there is data in flight or not with a ret_code.
2272 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2273 struct relay_connection
*conn
,
2274 const struct lttng_buffer_view
*payload
)
2278 struct lttng_ht_iter iter
;
2279 struct lttcomm_relayd_end_data_pending msg
;
2280 struct lttcomm_relayd_generic_reply reply
;
2281 struct relay_stream
*stream
;
2282 uint32_t is_data_inflight
= 0;
2284 DBG("End data pending command");
2286 if (!conn
->session
|| !conn
->version_check_done
) {
2287 ERR("Trying to check for data before version check");
2289 goto end_no_session
;
2292 if (payload
->size
< sizeof(msg
)) {
2293 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2297 goto end_no_session
;
2299 memcpy(&msg
, payload
->data
, sizeof(msg
));
2300 msg
.session_id
= be64toh(msg
.session_id
);
2303 * Iterate over all streams to see if the begin data pending
2307 lttng::urcu::read_lock_guard read_lock
;
2309 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2310 if (!stream_get(stream
)) {
2314 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2319 pthread_mutex_lock(&stream
->lock
);
2320 if (!stream
->data_pending_check_done
) {
2321 uint64_t stream_seq
;
2323 if (session_streams_have_index(conn
->session
)) {
2325 * Ensure that both the index and stream data have been
2326 * flushed up to the requested point.
2328 stream_seq
= std::min(stream
->prev_data_seq
,
2329 stream
->prev_index_seq
);
2331 stream_seq
= stream
->prev_data_seq
;
2334 if (!stream
->closed
||
2335 !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2336 is_data_inflight
= 1;
2337 DBG("Data is still in flight for stream %" PRIu64
,
2338 stream
->stream_handle
);
2339 pthread_mutex_unlock(&stream
->lock
);
2345 pthread_mutex_unlock(&stream
->lock
);
2350 memset(&reply
, 0, sizeof(reply
));
2351 /* All good, send back reply. */
2352 reply
.ret_code
= htobe32(is_data_inflight
);
2354 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2355 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2356 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret
);
2367 * Receive an index for a specific stream.
2369 * Return 0 on success else a negative value.
2371 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2372 struct relay_connection
*conn
,
2373 const struct lttng_buffer_view
*payload
)
2377 struct relay_session
*session
= conn
->session
;
2378 struct lttcomm_relayd_index index_info
;
2379 struct lttcomm_relayd_generic_reply reply
;
2380 struct relay_stream
*stream
;
2385 DBG("Relay receiving index");
2387 if (!session
|| !conn
->version_check_done
) {
2388 ERR("Trying to close a stream before version check");
2390 goto end_no_session
;
2393 msg_len
= lttcomm_relayd_index_len(lttng_to_index_major(conn
->major
, conn
->minor
),
2394 lttng_to_index_minor(conn
->major
, conn
->minor
));
2395 if (payload
->size
< msg_len
) {
2396 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2400 goto end_no_session
;
2402 memcpy(&index_info
, payload
->data
, msg_len
);
2403 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2404 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2405 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2406 index_info
.content_size
= be64toh(index_info
.content_size
);
2407 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2408 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2409 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2410 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2412 if (conn
->minor
>= 8) {
2413 index_info
.stream_instance_id
= be64toh(index_info
.stream_instance_id
);
2414 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2416 index_info
.stream_instance_id
= -1ULL;
2417 index_info
.packet_seq_num
= -1ULL;
2420 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2422 ERR("stream_get_by_id not found");
2427 pthread_mutex_lock(&stream
->lock
);
2428 ret
= stream_add_index(stream
, &index_info
);
2429 pthread_mutex_unlock(&stream
->lock
);
2431 goto end_stream_put
;
2437 memset(&reply
, 0, sizeof(reply
));
2439 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2441 reply
.ret_code
= htobe32(LTTNG_OK
);
2443 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2444 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2445 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2454 * Receive the streams_sent message.
2456 * Return 0 on success else a negative value.
2458 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2459 struct relay_connection
*conn
,
2460 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2464 struct lttcomm_relayd_generic_reply reply
;
2468 DBG("Relay receiving streams_sent");
2470 if (!conn
->session
|| !conn
->version_check_done
) {
2471 ERR("Trying to close a stream before version check");
2473 goto end_no_session
;
2477 * Publish every pending stream in the connection recv list which are
2478 * now ready to be used by the viewer.
2480 publish_connection_local_streams(conn
);
2482 memset(&reply
, 0, sizeof(reply
));
2483 reply
.ret_code
= htobe32(LTTNG_OK
);
2484 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2485 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2486 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret
);
2498 relay_unpack_rotate_streams_header(const struct lttng_buffer_view
*payload
,
2499 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2501 struct lttcomm_relayd_rotate_streams rotate_streams
;
2503 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2504 * This is the smallest version of this structure, but it can be larger;
2505 * this variable is updated once the proper size of the structure is known.
2507 * See comment at the declaration of this structure for more information.
2509 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2510 size_t expected_payload_size_no_padding
, expected_payload_size_3_bytes_padding
,
2511 expected_payload_size_7_bytes_padding
;
2513 if (payload
->size
< header_len
) {
2514 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2521 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2522 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2524 * We start by "unpacking" `stream_count` to figure out the padding length
2525 * emited by our peer.
2528 decltype(rotate_streams
.stream_count
) stream_count
;
2530 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2531 rotate_streams
.stream_count
= be32toh(stream_count
);
2534 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2537 * Payload size expected given the possible padding lengths in
2538 * `struct lttcomm_relayd_rotate_streams`.
2540 expected_payload_size_no_padding
=
2541 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2542 sizeof(lttcomm_relayd_rotate_streams_packed
);
2543 expected_payload_size_3_bytes_padding
=
2544 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2545 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2546 expected_payload_size_7_bytes_padding
=
2547 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2548 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2550 if (payload
->size
== expected_payload_size_no_padding
) {
2551 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2554 * This handles cases where someone might build with
2555 * -fpack-struct or any other toolchain that wouldn't produce
2556 * padding to align `value`.
2558 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2560 header_len
= sizeof(packed_rotate_streams
);
2561 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2563 /* Unpack the packed structure to the natively-packed version. */
2564 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2565 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2566 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2568 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2569 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2570 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2572 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2574 header_len
= sizeof(padded_rotate_streams
);
2575 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2577 /* Unpack the 3-byte padded structure to the natively-packed version. */
2578 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2579 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2580 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2582 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2583 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2584 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2586 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2588 header_len
= sizeof(padded_rotate_streams
);
2589 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2591 /* Unpack the 7-byte padded structure to the natively-packed version. */
2592 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2593 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2594 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2596 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2598 header_len
= sizeof(padded_rotate_streams
);
2600 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2601 expected_payload_size_no_padding
,
2602 expected_payload_size_3_bytes_padding
,
2603 expected_payload_size_7_bytes_padding
,
2614 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2615 * session rotation feature (not the tracefile rotation feature).
2617 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr
*recv_hdr
2618 __attribute__((unused
)),
2619 struct relay_connection
*conn
,
2620 const struct lttng_buffer_view
*payload
)
2625 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2626 struct relay_session
*session
= conn
->session
;
2627 struct lttcomm_relayd_rotate_streams rotate_streams
;
2628 struct lttcomm_relayd_generic_reply reply
= {};
2629 struct relay_stream
*stream
= nullptr;
2630 struct lttng_trace_chunk
*next_trace_chunk
= nullptr;
2631 struct lttng_buffer_view stream_positions
;
2632 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2633 const char *chunk_id_str
= "none";
2636 if (!session
|| !conn
->version_check_done
) {
2637 ERR("Trying to rotate a stream before version check");
2642 if (session
->major
== 2 && session
->minor
< 11) {
2643 ERR("Unsupported feature before 2.11");
2648 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2649 if (header_len
< 0) {
2654 if (rotate_streams
.new_chunk_id
.is_set
) {
2656 * Retrieve the trace chunk the stream must transition to. As
2657 * per the protocol, this chunk should have been created
2658 * before this command is received.
2660 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2661 sessiond_trace_chunk_registry
,
2662 session
->sessiond_uuid
,
2663 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2665 rotate_streams
.new_chunk_id
.value
);
2666 if (!next_trace_chunk
) {
2667 char uuid_str
[LTTNG_UUID_STR_LEN
];
2669 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2670 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2671 ", trace_chunk_id = %" PRIu64
,
2674 rotate_streams
.new_chunk_id
.value
);
2675 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2680 ret
= snprintf(chunk_id_buf
,
2681 sizeof(chunk_id_buf
),
2683 rotate_streams
.new_chunk_id
.value
);
2684 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2685 chunk_id_str
= "formatting error";
2687 chunk_id_str
= chunk_id_buf
;
2691 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2692 rotate_streams
.stream_count
,
2693 session
->session_name
,
2696 stream_positions
= lttng_buffer_view_from_view(payload
, header_len
, -1);
2697 if (!stream_positions
.data
||
2698 stream_positions
.size
< (rotate_streams
.stream_count
*
2699 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2700 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2705 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2706 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2707 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2708 const struct lttcomm_relayd_stream_rotation_position pos
= {
2709 .stream_id
= be64toh(position_comm
->stream_id
),
2710 .rotate_at_seq_num
= be64toh(position_comm
->rotate_at_seq_num
),
2713 stream
= stream_get_by_id(pos
.stream_id
);
2715 reply_code
= LTTNG_ERR_INVALID
;
2720 pthread_mutex_lock(&stream
->lock
);
2721 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
, pos
.rotate_at_seq_num
);
2722 pthread_mutex_unlock(&stream
->lock
);
2724 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2732 reply_code
= LTTNG_OK
;
2739 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2740 send_ret
= conn
->sock
->ops
->sendmsg(
2741 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2742 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2743 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret
);
2747 lttng_trace_chunk_put(next_trace_chunk
);
2752 * relay_create_trace_chunk: create a new trace chunk
2754 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2755 __attribute__((unused
)),
2756 struct relay_connection
*conn
,
2757 const struct lttng_buffer_view
*payload
)
2761 struct relay_session
*session
= conn
->session
;
2762 struct lttcomm_relayd_create_trace_chunk
*msg
;
2763 struct lttcomm_relayd_generic_reply reply
= {};
2764 struct lttng_buffer_view header_view
;
2765 struct lttng_trace_chunk
*chunk
= nullptr, *published_chunk
= nullptr;
2766 enum lttng_error_code reply_code
= LTTNG_OK
;
2767 enum lttng_trace_chunk_status chunk_status
;
2768 const char *new_path
;
2770 if (!session
|| !conn
->version_check_done
) {
2771 ERR("Trying to create a trace chunk before version check");
2776 if (session
->major
== 2 && session
->minor
< 11) {
2777 ERR("Chunk creation command is unsupported before 2.11");
2782 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2783 if (!lttng_buffer_view_is_valid(&header_view
)) {
2784 ERR("Failed to receive payload of chunk creation command");
2789 /* Convert to host endianness. */
2790 msg
= (typeof(msg
)) header_view
.data
;
2791 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2792 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2793 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2795 pthread_mutex_lock(&conn
->session
->lock
);
2796 session
->ongoing_rotation
= true;
2797 if (session
->current_trace_chunk
&&
2798 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2799 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2800 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2801 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2802 ERR("Failed to rename old chunk");
2804 reply_code
= LTTNG_ERR_UNK
;
2808 if (!session
->current_trace_chunk
) {
2809 if (!session
->has_rotated
) {
2815 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2817 chunk
= lttng_trace_chunk_create(msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2819 ERR("Failed to create trace chunk in trace chunk creation command");
2821 reply_code
= LTTNG_ERR_NOMEM
;
2824 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2826 if (msg
->override_name_length
) {
2828 const struct lttng_buffer_view chunk_name_view
= lttng_buffer_view_from_view(
2829 payload
, sizeof(*msg
), msg
->override_name_length
);
2831 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2832 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2834 reply_code
= LTTNG_ERR_INVALID
;
2838 name
= chunk_name_view
.data
;
2839 if (name
[msg
->override_name_length
- 1]) {
2840 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2842 reply_code
= LTTNG_ERR_INVALID
;
2846 chunk_status
= lttng_trace_chunk_override_name(chunk
, chunk_name_view
.data
);
2847 switch (chunk_status
) {
2848 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2850 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2851 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2852 reply_code
= LTTNG_ERR_INVALID
;
2856 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2857 reply_code
= LTTNG_ERR_UNK
;
2863 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2864 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2865 reply_code
= LTTNG_ERR_UNK
;
2870 LTTNG_ASSERT(conn
->session
->output_directory
);
2871 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, conn
->session
->output_directory
);
2872 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2873 reply_code
= LTTNG_ERR_UNK
;
2878 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2879 sessiond_trace_chunk_registry
,
2880 conn
->session
->sessiond_uuid
,
2881 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2884 if (!published_chunk
) {
2885 char uuid_str
[LTTNG_UUID_STR_LEN
];
2887 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2888 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2889 ", chunk_id = %" PRIu64
,
2894 reply_code
= LTTNG_ERR_NOMEM
;
2898 if (conn
->session
->pending_closure_trace_chunk
) {
2900 * Invalid; this means a second create_trace_chunk command was
2901 * received before a close_trace_chunk.
2903 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2904 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2908 conn
->session
->pending_closure_trace_chunk
= conn
->session
->current_trace_chunk
;
2909 conn
->session
->current_trace_chunk
= published_chunk
;
2910 published_chunk
= nullptr;
2911 if (!conn
->session
->pending_closure_trace_chunk
) {
2912 session
->ongoing_rotation
= false;
2915 pthread_mutex_unlock(&conn
->session
->lock
);
2916 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2917 send_ret
= conn
->sock
->ops
->sendmsg(
2918 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2919 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2920 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
2924 lttng_trace_chunk_put(chunk
);
2925 lttng_trace_chunk_put(published_chunk
);
2930 * relay_close_trace_chunk: close a trace chunk
2932 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2933 __attribute__((unused
)),
2934 struct relay_connection
*conn
,
2935 const struct lttng_buffer_view
*payload
)
2937 int ret
= 0, buf_ret
;
2939 struct relay_session
*session
= conn
->session
;
2940 struct lttcomm_relayd_close_trace_chunk
*msg
;
2941 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2942 struct lttng_buffer_view header_view
;
2943 struct lttng_trace_chunk
*chunk
= nullptr;
2944 enum lttng_error_code reply_code
= LTTNG_OK
;
2945 enum lttng_trace_chunk_status chunk_status
;
2947 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2948 time_t close_timestamp
;
2949 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2950 size_t path_length
= 0;
2951 const char *chunk_name
= nullptr;
2952 struct lttng_dynamic_buffer reply_payload
;
2953 const char *new_path
;
2955 lttng_dynamic_buffer_init(&reply_payload
);
2957 if (!session
|| !conn
->version_check_done
) {
2958 ERR("Trying to close a trace chunk before version check");
2963 if (session
->major
== 2 && session
->minor
< 11) {
2964 ERR("Chunk close command is unsupported before 2.11");
2969 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2970 if (!lttng_buffer_view_is_valid(&header_view
)) {
2971 ERR("Failed to receive payload of chunk close command");
2976 /* Convert to host endianness. */
2977 msg
= (typeof(msg
)) header_view
.data
;
2978 chunk_id
= be64toh(msg
->chunk_id
);
2979 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2980 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2981 close_command
.is_set
= msg
->close_command
.is_set
;
2983 chunk
= sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry
,
2984 conn
->session
->sessiond_uuid
,
2985 conn
->session
->id_sessiond
.is_set
?
2986 conn
->session
->id_sessiond
.value
:
2990 char uuid_str
[LTTNG_UUID_STR_LEN
];
2992 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2993 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
2994 ", chunk_id = %" PRIu64
,
2999 reply_code
= LTTNG_ERR_NOMEM
;
3003 pthread_mutex_lock(&session
->lock
);
3004 if (close_command
.is_set
&& close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3006 * Clear command. It is a protocol error to ask for a
3007 * clear on a relay which does not allow it. Querying
3008 * the configuration allows figuring out whether
3009 * clearing is allowed before doing the clear.
3011 if (!opt_allow_clear
) {
3013 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3014 goto end_unlock_session
;
3017 if (session
->pending_closure_trace_chunk
&& session
->pending_closure_trace_chunk
!= chunk
) {
3018 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3019 session
->session_name
);
3020 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3022 goto end_unlock_session
;
3025 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3026 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3027 if (close_command
.is_set
&&
3028 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3029 !session
->has_rotated
) {
3030 /* New chunk stays in session output directory. */
3033 /* Use chunk name for new chunk. */
3036 /* Rename new chunk path. */
3038 lttng_trace_chunk_rename_path(session
->current_trace_chunk
, new_path
);
3039 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3041 goto end_unlock_session
;
3043 session
->ongoing_rotation
= false;
3045 if ((!close_command
.is_set
||
3046 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3047 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3048 const char *old_path
;
3050 if (!session
->has_rotated
) {
3055 /* We need to move back the .tmp_old_chunk to its rightful place. */
3056 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3057 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3059 goto end_unlock_session
;
3062 chunk_status
= lttng_trace_chunk_set_close_timestamp(chunk
, close_timestamp
);
3063 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3064 ERR("Failed to set trace chunk close timestamp");
3066 reply_code
= LTTNG_ERR_UNK
;
3067 goto end_unlock_session
;
3070 if (close_command
.is_set
) {
3071 chunk_status
= lttng_trace_chunk_set_close_command(chunk
, close_command
.value
);
3072 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3074 reply_code
= LTTNG_ERR_INVALID
;
3075 goto end_unlock_session
;
3078 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, nullptr);
3079 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3080 ERR("Failed to get chunk name");
3082 reply_code
= LTTNG_ERR_UNK
;
3083 goto end_unlock_session
;
3085 if (!session
->has_rotated
&& !session
->snapshot
) {
3086 ret
= lttng_strncpy(closed_trace_chunk_path
,
3087 session
->output_path
,
3088 sizeof(closed_trace_chunk_path
));
3090 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3091 strlen(session
->output_path
),
3092 sizeof(closed_trace_chunk_path
));
3093 reply_code
= LTTNG_ERR_NOMEM
;
3095 goto end_unlock_session
;
3098 if (session
->snapshot
) {
3099 ret
= snprintf(closed_trace_chunk_path
,
3100 sizeof(closed_trace_chunk_path
),
3102 session
->output_path
,
3105 ret
= snprintf(closed_trace_chunk_path
,
3106 sizeof(closed_trace_chunk_path
),
3107 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
"/%s",
3108 session
->output_path
,
3111 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3112 ERR("Failed to format closed trace chunk resulting path");
3113 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3115 goto end_unlock_session
;
3118 if (close_command
.is_set
&&
3119 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3120 session
->has_rotated
= true;
3122 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3123 path_length
= strlen(closed_trace_chunk_path
) + 1;
3124 if (path_length
> UINT32_MAX
) {
3125 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3127 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3128 goto end_unlock_session
;
3131 if (session
->current_trace_chunk
== chunk
) {
3133 * After a trace chunk close command, no new streams
3134 * referencing the chunk may be created. Hence, on the
3135 * event that no new trace chunk have been created for
3136 * the session, the reference to the current trace chunk
3137 * is released in order to allow it to be reclaimed when
3138 * the last stream releases its reference to it.
3140 lttng_trace_chunk_put(session
->current_trace_chunk
);
3141 session
->current_trace_chunk
= nullptr;
3143 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3144 session
->pending_closure_trace_chunk
= nullptr;
3146 pthread_mutex_unlock(&session
->lock
);
3149 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3150 reply
.path_length
= htobe32((uint32_t) path_length
);
3151 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
3153 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3157 if (reply_code
== LTTNG_OK
) {
3158 buf_ret
= lttng_dynamic_buffer_append(
3159 &reply_payload
, closed_trace_chunk_path
, path_length
);
3161 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3166 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
3167 if (send_ret
< reply_payload
.size
) {
3168 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3175 lttng_trace_chunk_put(chunk
);
3176 lttng_dynamic_buffer_reset(&reply_payload
);
3181 * relay_trace_chunk_exists: check if a trace chunk exists
3183 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
3184 __attribute__((unused
)),
3185 struct relay_connection
*conn
,
3186 const struct lttng_buffer_view
*payload
)
3190 struct relay_session
*session
= conn
->session
;
3191 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3192 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3193 struct lttng_buffer_view header_view
;
3197 if (!session
|| !conn
->version_check_done
) {
3198 ERR("Trying to check for the presence of a trace chunk before version check");
3203 if (session
->major
== 2 && session
->minor
< 11) {
3204 ERR("Chunk exists command is unsupported before 2.11");
3209 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3210 if (!lttng_buffer_view_is_valid(&header_view
)) {
3211 ERR("Failed to receive payload of chunk exists command");
3216 /* Convert to host endianness. */
3217 msg
= (typeof(msg
)) header_view
.data
;
3218 chunk_id
= be64toh(msg
->chunk_id
);
3220 ret
= sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry
,
3221 conn
->session
->sessiond_uuid
,
3226 * If ret is not 0, send the reply and report the error to the caller.
3227 * It is a protocol (or internal) error and the session/connection
3228 * should be torn down.
3230 reply
.generic
.ret_code
=
3231 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3232 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3234 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3235 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3236 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
3244 * relay_get_configuration: query whether feature is available
3246 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
3247 __attribute__((unused
)),
3248 struct relay_connection
*conn
,
3249 const struct lttng_buffer_view
*payload
)
3253 struct lttcomm_relayd_get_configuration
*msg
;
3254 struct lttcomm_relayd_get_configuration_reply reply
= {};
3255 struct lttng_buffer_view header_view
;
3256 uint64_t query_flags
= 0;
3257 uint64_t result_flags
= 0;
3259 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3260 if (!lttng_buffer_view_is_valid(&header_view
)) {
3261 ERR("Failed to receive payload of chunk close command");
3266 /* Convert to host endianness. */
3267 msg
= (typeof(msg
)) header_view
.data
;
3268 query_flags
= be64toh(msg
->query_flags
);
3271 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3274 if (opt_allow_clear
) {
3275 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3279 reply
.generic
.ret_code
=
3280 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3281 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3283 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3284 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3285 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3292 static int relay_process_control_command(struct relay_connection
*conn
,
3293 const struct lttcomm_relayd_hdr
*header
,
3294 const struct lttng_buffer_view
*payload
)
3298 DBG3("Processing \"%s\" command for socket %i",
3299 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3301 switch (header
->cmd
) {
3302 case RELAYD_CREATE_SESSION
:
3303 ret
= relay_create_session(header
, conn
, payload
);
3305 case RELAYD_ADD_STREAM
:
3306 ret
= relay_add_stream(header
, conn
, payload
);
3308 case RELAYD_START_DATA
:
3309 ret
= relay_start(header
, conn
, payload
);
3311 case RELAYD_SEND_METADATA
:
3312 ret
= relay_recv_metadata(header
, conn
, payload
);
3314 case RELAYD_VERSION
:
3315 ret
= relay_send_version(header
, conn
, payload
);
3317 case RELAYD_CLOSE_STREAM
:
3318 ret
= relay_close_stream(header
, conn
, payload
);
3320 case RELAYD_DATA_PENDING
:
3321 ret
= relay_data_pending(header
, conn
, payload
);
3323 case RELAYD_QUIESCENT_CONTROL
:
3324 ret
= relay_quiescent_control(header
, conn
, payload
);
3326 case RELAYD_BEGIN_DATA_PENDING
:
3327 ret
= relay_begin_data_pending(header
, conn
, payload
);
3329 case RELAYD_END_DATA_PENDING
:
3330 ret
= relay_end_data_pending(header
, conn
, payload
);
3332 case RELAYD_SEND_INDEX
:
3333 ret
= relay_recv_index(header
, conn
, payload
);
3335 case RELAYD_STREAMS_SENT
:
3336 ret
= relay_streams_sent(header
, conn
, payload
);
3338 case RELAYD_RESET_METADATA
:
3339 ret
= relay_reset_metadata(header
, conn
, payload
);
3341 case RELAYD_ROTATE_STREAMS
:
3342 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3344 case RELAYD_CREATE_TRACE_CHUNK
:
3345 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3347 case RELAYD_CLOSE_TRACE_CHUNK
:
3348 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3350 case RELAYD_TRACE_CHUNK_EXISTS
:
3351 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3353 case RELAYD_GET_CONFIGURATION
:
3354 ret
= relay_get_configuration(header
, conn
, payload
);
3356 case RELAYD_UPDATE_SYNC_INFO
:
3358 ERR("Received unknown command (%u)", header
->cmd
);
3359 relay_unknown_command(conn
);
3368 static enum relay_connection_status
3369 relay_process_control_receive_payload(struct relay_connection
*conn
)
3372 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3373 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3374 struct ctrl_connection_state_receive_payload
*state
=
3375 &conn
->protocol
.ctrl
.state
.receive_payload
;
3376 struct lttng_buffer_view payload_view
;
3378 if (state
->left_to_receive
== 0) {
3379 /* Short-circuit for payload-less commands. */
3380 goto reception_complete
;
3383 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3384 reception_buffer
->data
+ state
->received
,
3385 state
->left_to_receive
,
3389 DIAGNOSTIC_IGNORE_LOGICAL_OP
3390 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3392 PERROR("Unable to receive command payload on sock %d", conn
->sock
->fd
);
3393 status
= RELAY_CONNECTION_STATUS_ERROR
;
3396 } else if (ret
== 0) {
3397 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3398 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3402 LTTNG_ASSERT(ret
> 0);
3403 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3405 state
->left_to_receive
-= ret
;
3406 state
->received
+= ret
;
3408 if (state
->left_to_receive
> 0) {
3410 * Can't transition to the protocol's next state, wait to
3411 * receive the rest of the header.
3413 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3414 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3416 state
->left_to_receive
,
3422 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3426 * The payload required to process the command has been received.
3427 * A view to the reception buffer is forwarded to the various
3428 * commands and the state of the control is reset on success.
3430 * Commands are responsible for sending their reply to the peer.
3432 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
, 0, -1);
3433 ret
= relay_process_control_command(conn
, &state
->header
, &payload_view
);
3435 status
= RELAY_CONNECTION_STATUS_ERROR
;
3439 ret
= connection_reset_protocol_state(conn
);
3441 status
= RELAY_CONNECTION_STATUS_ERROR
;
3447 static enum relay_connection_status
3448 relay_process_control_receive_header(struct relay_connection
*conn
)
3451 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3452 struct lttcomm_relayd_hdr header
;
3453 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3454 struct ctrl_connection_state_receive_header
*state
=
3455 &conn
->protocol
.ctrl
.state
.receive_header
;
3457 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3459 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3460 reception_buffer
->data
+ state
->received
,
3461 state
->left_to_receive
,
3465 DIAGNOSTIC_IGNORE_LOGICAL_OP
3466 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3468 PERROR("Unable to receive control command header on sock %d",
3470 status
= RELAY_CONNECTION_STATUS_ERROR
;
3473 } else if (ret
== 0) {
3474 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3475 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3479 LTTNG_ASSERT(ret
> 0);
3480 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3482 state
->left_to_receive
-= ret
;
3483 state
->received
+= ret
;
3485 if (state
->left_to_receive
> 0) {
3487 * Can't transition to the protocol's next state, wait to
3488 * receive the rest of the header.
3490 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3491 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3493 state
->left_to_receive
,
3498 /* Transition to next state: receiving the command's payload. */
3499 conn
->protocol
.ctrl
.state_id
= CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3500 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3501 header
.circuit_id
= be64toh(header
.circuit_id
);
3502 header
.data_size
= be64toh(header
.data_size
);
3503 header
.cmd
= be32toh(header
.cmd
);
3504 header
.cmd_version
= be32toh(header
.cmd_version
);
3505 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
, &header
, sizeof(header
));
3507 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3508 ", payload size = %" PRIu64
" bytes",
3510 lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3514 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3515 ERR("Command header indicates a payload (%" PRIu64
3516 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3518 status
= RELAY_CONNECTION_STATUS_ERROR
;
3522 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3523 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3524 ret
= lttng_dynamic_buffer_set_size(reception_buffer
, header
.data_size
);
3526 status
= RELAY_CONNECTION_STATUS_ERROR
;
3530 if (header
.data_size
== 0) {
3532 * Manually invoke the next state as the poll loop
3533 * will not wake-up to allow us to proceed further.
3535 status
= relay_process_control_receive_payload(conn
);
3542 * Process the commands received on the control socket
3544 static enum relay_connection_status
relay_process_control(struct relay_connection
*conn
)
3546 enum relay_connection_status status
;
3548 switch (conn
->protocol
.ctrl
.state_id
) {
3549 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3550 status
= relay_process_control_receive_header(conn
);
3552 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3553 status
= relay_process_control_receive_payload(conn
);
3556 ERR("Unknown control connection protocol state encountered.");
3563 static enum relay_connection_status
relay_process_data_receive_header(struct relay_connection
*conn
)
3566 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3567 struct data_connection_state_receive_header
*state
=
3568 &conn
->protocol
.data
.state
.receive_header
;
3569 struct lttcomm_relayd_data_hdr header
;
3570 struct relay_stream
*stream
;
3572 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3574 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3575 state
->header_reception_buffer
+ state
->received
,
3576 state
->left_to_receive
,
3580 DIAGNOSTIC_IGNORE_LOGICAL_OP
3581 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3583 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3584 status
= RELAY_CONNECTION_STATUS_ERROR
;
3587 } else if (ret
== 0) {
3588 /* Orderly shutdown. Not necessary to print an error. */
3589 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3590 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3594 LTTNG_ASSERT(ret
> 0);
3595 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3597 state
->left_to_receive
-= ret
;
3598 state
->received
+= ret
;
3600 if (state
->left_to_receive
> 0) {
3602 * Can't transition to the protocol's next state, wait to
3603 * receive the rest of the header.
3605 DBG3("Partial reception of data connection header (received %" PRIu64
3606 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3608 state
->left_to_receive
,
3613 /* Transition to next state: receiving the payload. */
3614 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3616 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3617 header
.circuit_id
= be64toh(header
.circuit_id
);
3618 header
.stream_id
= be64toh(header
.stream_id
);
3619 header
.data_size
= be32toh(header
.data_size
);
3620 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3621 header
.padding_size
= be32toh(header
.padding_size
);
3622 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3624 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3625 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3626 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3628 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3629 ", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
3630 ", padding_size = %" PRIu32
,
3636 header
.padding_size
);
3638 stream
= stream_get_by_id(header
.stream_id
);
3640 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3642 /* Protocol error. */
3643 status
= RELAY_CONNECTION_STATUS_ERROR
;
3647 pthread_mutex_lock(&stream
->lock
);
3648 /* Prepare stream for the reception of a new packet. */
3649 ret
= stream_init_packet(
3650 stream
, header
.data_size
, &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3651 pthread_mutex_unlock(&stream
->lock
);
3653 ERR("Failed to rotate stream output file");
3654 status
= RELAY_CONNECTION_STATUS_ERROR
;
3655 goto end_stream_unlock
;
3664 static enum relay_connection_status
3665 relay_process_data_receive_payload(struct relay_connection
*conn
)
3668 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3669 struct relay_stream
*stream
;
3670 struct data_connection_state_receive_payload
*state
=
3671 &conn
->protocol
.data
.state
.receive_payload
;
3672 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3673 char data_buffer
[chunk_size
];
3674 bool partial_recv
= false;
3675 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3676 uint64_t left_to_receive
= state
->left_to_receive
;
3677 struct relay_session
*session
;
3679 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
3680 " bytes received, %" PRIu64
" bytes left to receive",
3681 state
->header
.stream_id
,
3682 state
->header
.net_seq_num
,
3686 stream
= stream_get_by_id(state
->header
.stream_id
);
3688 /* Protocol error. */
3689 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3690 state
->header
.stream_id
);
3691 status
= RELAY_CONNECTION_STATUS_ERROR
;
3695 pthread_mutex_lock(&stream
->lock
);
3696 session
= stream
->trace
->session
;
3697 if (!conn
->session
) {
3698 ret
= connection_set_session(conn
, session
);
3700 status
= RELAY_CONNECTION_STATUS_ERROR
;
3701 goto end_stream_unlock
;
3706 * The size of the "chunk" received on any iteration is bounded by:
3707 * - the data left to receive,
3708 * - the data immediately available on the socket,
3709 * - the on-stack data buffer
3711 while (left_to_receive
> 0 && !partial_recv
) {
3712 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3713 struct lttng_buffer_view packet_chunk
;
3715 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, MSG_DONTWAIT
);
3718 DIAGNOSTIC_IGNORE_LOGICAL_OP
3719 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3721 PERROR("Socket %d error", conn
->sock
->fd
);
3722 status
= RELAY_CONNECTION_STATUS_ERROR
;
3724 goto end_stream_unlock
;
3725 } else if (ret
== 0) {
3726 /* No more data ready to be consumed on socket. */
3727 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3728 state
->header
.stream_id
);
3729 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3731 } else if (ret
< (int) recv_size
) {
3733 * All the data available on the socket has been
3736 partial_recv
= true;
3740 packet_chunk
= lttng_buffer_view_init(data_buffer
, 0, recv_size
);
3741 LTTNG_ASSERT(packet_chunk
.data
);
3743 ret
= stream_write(stream
, &packet_chunk
, 0);
3745 ERR("Relay error writing data to file");
3746 status
= RELAY_CONNECTION_STATUS_ERROR
;
3747 goto end_stream_unlock
;
3750 left_to_receive
-= recv_size
;
3751 state
->received
+= recv_size
;
3752 state
->left_to_receive
= left_to_receive
;
3755 if (state
->left_to_receive
> 0) {
3757 * Did not receive all the data expected, wait for more data to
3758 * become available on the socket.
3760 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
3761 " bytes received, %" PRIu64
" bytes left to receive",
3762 state
->header
.stream_id
,
3764 state
->left_to_receive
);
3765 goto end_stream_unlock
;
3768 ret
= stream_write(stream
, nullptr, state
->header
.padding_size
);
3770 status
= RELAY_CONNECTION_STATUS_ERROR
;
3771 goto end_stream_unlock
;
3774 if (session_streams_have_index(session
)) {
3775 ret
= stream_update_index(stream
,
3776 state
->header
.net_seq_num
,
3777 state
->rotate_index
,
3779 state
->header
.data_size
+ state
->header
.padding_size
);
3781 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
3783 stream
->stream_handle
,
3784 state
->header
.net_seq_num
,
3786 status
= RELAY_CONNECTION_STATUS_ERROR
;
3787 goto end_stream_unlock
;
3791 if (stream
->prev_data_seq
== -1ULL) {
3795 ret
= stream_complete_packet(stream
,
3796 state
->header
.data_size
+ state
->header
.padding_size
,
3797 state
->header
.net_seq_num
,
3800 status
= RELAY_CONNECTION_STATUS_ERROR
;
3801 goto end_stream_unlock
;
3805 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3806 * contents of *state which are aliased (union) to the same location as
3807 * the new state. Don't use it beyond this point.
3809 connection_reset_protocol_state(conn
);
3813 close_requested
= stream
->close_requested
;
3814 pthread_mutex_unlock(&stream
->lock
);
3815 if (close_requested
&& left_to_receive
== 0) {
3816 try_stream_close(stream
);
3820 pthread_mutex_lock(&session
->lock
);
3821 uatomic_set(&session
->new_streams
, 1);
3822 pthread_mutex_unlock(&session
->lock
);
3831 * relay_process_data: Process the data received on the data socket
3833 static enum relay_connection_status
relay_process_data(struct relay_connection
*conn
)
3835 enum relay_connection_status status
;
3837 switch (conn
->protocol
.data
.state_id
) {
3838 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3839 status
= relay_process_data_receive_header(conn
);
3841 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3842 status
= relay_process_data_receive_payload(conn
);
3845 ERR("Unexpected data connection communication state.");
3852 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3856 (void) lttng_poll_del(events
, pollfd
);
3858 ret
= fd_tracker_close_unsuspendable_fd(
3859 the_fd_tracker
, &pollfd
, 1, fd_tracker_util_close_fd
, nullptr);
3861 ERR("Closing pollfd %d", pollfd
);
3865 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3867 struct relay_connection
*conn
)
3869 const char *type_str
;
3871 switch (conn
->type
) {
3876 type_str
= "Control";
3878 case RELAY_VIEWER_COMMAND
:
3879 type_str
= "Viewer Command";
3881 case RELAY_VIEWER_NOTIFICATION
:
3882 type_str
= "Viewer Notification";
3885 type_str
= "Unknown";
3887 cleanup_connection_pollfd(events
, pollfd
);
3888 connection_put(conn
);
3889 DBG("%s connection closed with %d", type_str
, pollfd
);
3893 * This thread does the actual work
3895 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3897 int ret
, err
= -1, last_seen_data_fd
= -1;
3899 struct lttng_poll_event events
;
3900 struct lttng_ht
*relay_connections_ht
;
3901 struct lttng_ht_iter iter
;
3902 struct relay_connection
*destroy_conn
= nullptr;
3904 DBG("[thread] Relay worker started");
3906 rcu_register_thread();
3908 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3910 if (testpoint(relayd_thread_worker
)) {
3911 goto error_testpoint
;
3914 health_code_update();
3916 /* table of connections indexed on socket */
3917 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3918 if (!relay_connections_ht
) {
3919 goto relay_connections_ht_error
;
3922 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3924 goto error_poll_create
;
3927 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3934 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3936 health_code_update();
3938 /* Infinite blocking call, waiting for transmission */
3939 DBG3("Relayd worker thread polling...");
3940 health_poll_entry();
3941 ret
= lttng_poll_wait(&events
, -1);
3945 * Restart interrupted system call.
3947 if (errno
== EINTR
) {
3956 * Process control. The control connection is
3957 * prioritized so we don't starve it with high
3958 * throughput tracing data on the data connection.
3960 for (i
= 0; i
< nb_fd
; i
++) {
3961 /* Fetch once the poll data */
3962 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
3963 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3965 health_code_update();
3967 /* Activity on thread quit pipe, exiting. */
3968 if (relayd_is_thread_quit_pipe(pollfd
)) {
3969 DBG("Activity on thread quit pipe");
3974 /* Inspect the relay conn pipe for new connection */
3975 if (pollfd
== relay_conn_pipe
[0]) {
3976 if (revents
& LPOLLIN
) {
3977 struct relay_connection
*conn
;
3979 ret
= lttng_read(relay_conn_pipe
[0],
3981 sizeof(conn
)); /* NOLINT sizeof used on a
3986 ret
= lttng_poll_add(
3987 &events
, conn
->sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
3989 ERR("Failed to add new connection file descriptor to poll set");
3992 connection_ht_add(relay_connections_ht
, conn
);
3993 DBG("Connection socket %d added", conn
->sock
->fd
);
3994 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3995 ERR("Relay connection pipe error");
3998 ERR("Unexpected poll events %u for sock %d",
4004 struct relay_connection
*ctrl_conn
;
4006 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4007 /* If not found, there is a synchronization issue. */
4008 LTTNG_ASSERT(ctrl_conn
);
4010 if (ctrl_conn
->type
== RELAY_DATA
) {
4011 if (revents
& LPOLLIN
) {
4013 * Flag the last seen data fd not deleted. It will
4014 * be used as the last seen fd if any fd gets
4015 * deleted in this first loop.
4017 last_notdel_data_fd
= pollfd
;
4019 goto put_ctrl_connection
;
4021 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4023 if (revents
& LPOLLIN
) {
4024 enum relay_connection_status status
;
4026 status
= relay_process_control(ctrl_conn
);
4027 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4029 * On socket error flag the session as aborted to
4030 * force the cleanup of its stream otherwise it can
4031 * leak during the lifetime of the relayd.
4033 * This prevents situations in which streams can be
4034 * left opened because an index was received, the
4035 * control connection is closed, and the data
4036 * connection is closed (uncleanly) before the
4037 * packet's data provided.
4039 * Since the control connection encountered an
4040 * error, it is okay to be conservative and close
4041 * the session right now as we can't rely on the
4042 * protocol being respected anymore.
4044 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4045 session_abort(ctrl_conn
->session
);
4048 /* Clear the connection on error or close. */
4049 relay_thread_close_connection(
4050 &events
, pollfd
, ctrl_conn
);
4053 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4054 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
4055 if (last_seen_data_fd
== pollfd
) {
4056 last_seen_data_fd
= last_notdel_data_fd
;
4059 ERR("Unexpected poll events %u for control sock %d",
4062 connection_put(ctrl_conn
);
4065 put_ctrl_connection
:
4066 connection_put(ctrl_conn
);
4071 * The last loop handled a control request, go back to poll to make
4072 * sure we prioritise the control socket.
4078 if (last_seen_data_fd
>= 0) {
4079 for (i
= 0; i
< nb_fd
; i
++) {
4080 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4082 health_code_update();
4084 if (last_seen_data_fd
== pollfd
) {
4091 /* Process data connection. */
4092 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4093 /* Fetch the poll data. */
4094 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4095 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4096 struct relay_connection
*data_conn
;
4098 health_code_update();
4101 /* No activity for this FD (poll implementation). */
4105 /* Skip the command pipe. It's handled in the first loop. */
4106 if (pollfd
== relay_conn_pipe
[0]) {
4110 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4112 /* Skip it. Might be removed before. */
4115 if (data_conn
->type
== RELAY_CONTROL
) {
4116 goto put_data_connection
;
4118 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4120 if (revents
& LPOLLIN
) {
4121 enum relay_connection_status status
;
4123 status
= relay_process_data(data_conn
);
4124 /* Connection closed or error. */
4125 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4127 * On socket error flag the session as aborted to force
4128 * the cleanup of its stream otherwise it can leak
4129 * during the lifetime of the relayd.
4131 * This prevents situations in which streams can be
4132 * left opened because an index was received, the
4133 * control connection is closed, and the data
4134 * connection is closed (uncleanly) before the packet's
4137 * Since the data connection encountered an error,
4138 * it is okay to be conservative and close the
4139 * session right now as we can't rely on the protocol
4140 * being respected anymore.
4142 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4143 session_abort(data_conn
->session
);
4145 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4147 * Every goto restart call sets the last seen fd where
4148 * here we don't really care since we gracefully
4149 * continue the loop after the connection is deleted.
4152 /* Keep last seen port. */
4153 last_seen_data_fd
= pollfd
;
4154 connection_put(data_conn
);
4157 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4158 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4160 ERR("Unknown poll events %u for data sock %d", revents
, pollfd
);
4162 put_data_connection
:
4163 connection_put(data_conn
);
4165 last_seen_data_fd
= -1;
4168 /* Normal exit, no error */
4173 /* Cleanup remaining connection object. */
4175 lttng::urcu::read_lock_guard read_lock
;
4177 cds_lfht_for_each_entry (
4178 relay_connections_ht
->ht
, &iter
.iter
, destroy_conn
, sock_n
.node
) {
4179 health_code_update();
4181 session_abort(destroy_conn
->session
);
4184 * No need to grab another ref, because we own
4187 relay_thread_close_connection(
4188 &events
, destroy_conn
->sock
->fd
, destroy_conn
);
4192 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4194 lttng_ht_destroy(relay_connections_ht
);
4195 relay_connections_ht_error
:
4196 /* Close relay conn pipes */
4197 (void) fd_tracker_util_pipe_close(the_fd_tracker
, relay_conn_pipe
);
4199 DBG("Thread exited with error");
4201 DBG("Worker thread cleanup complete");
4205 ERR("Health error occurred in %s", __func__
);
4207 health_unregister(health_relayd
);
4208 rcu_unregister_thread();
4209 lttng_relay_stop_threads();
4214 * Create the relay command pipe to wake thread_manage_apps.
4215 * Closed in cleanup().
4217 static int create_relay_conn_pipe()
4219 return fd_tracker_util_pipe_open_cloexec(
4220 the_fd_tracker
, "Relayd connection pipe", relay_conn_pipe
);
4223 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4225 fds
[0] = fileno(stdout
);
4226 fds
[1] = fileno(stderr
);
4230 static int track_stdio()
4233 const char *names
[] = { "stdout", "stderr" };
4235 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
, names
, 2, stdio_open
, nullptr);
4241 int main(int argc
, char **argv
)
4243 bool thread_is_rcu_registered
= false;
4244 int ret
= 0, retval
= 0;
4246 char *unlinked_file_directory_path
= nullptr, *output_path
= nullptr;
4248 /* Parse environment variables */
4249 ret
= parse_env_options();
4257 * Command line arguments overwrite environment.
4260 if (set_options(argc
, argv
)) {
4265 if (set_signal_handler()) {
4270 relayd_config_log();
4272 if (opt_print_version
) {
4278 ret
= fclose(stdin
);
4280 PERROR("Failed to close stdin");
4284 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4286 /* Try to create directory if -o, --output is specified. */
4287 if (opt_output_path
) {
4288 if (*opt_output_path
!= '/') {
4289 ERR("Please specify an absolute path for -o, --output PATH");
4294 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
, -1, -1);
4296 ERR("Unable to create %s", opt_output_path
);
4303 if (opt_daemon
|| opt_background
) {
4304 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
, !opt_background
);
4311 if (opt_working_directory
) {
4312 ret
= utils_change_working_directory(opt_working_directory
);
4314 /* All errors are already logged. */
4319 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4320 if (!sessiond_trace_chunk_registry
) {
4321 ERR("Failed to initialize session daemon trace chunk registry");
4327 * The RCU thread registration (and use, through the fd-tracker's
4328 * creation) is done after the daemonization to allow us to not
4329 * deal with liburcu's fork() management as the call RCU needs to
4332 rcu_register_thread();
4333 thread_is_rcu_registered
= true;
4335 output_path
= create_output_path("");
4337 ERR("Failed to get output path");
4341 ret
= asprintf(&unlinked_file_directory_path
,
4344 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4347 ERR("Failed to format unlinked file directory path");
4351 the_fd_tracker
= fd_tracker_create(unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4352 free(unlinked_file_directory_path
);
4353 if (!the_fd_tracker
) {
4358 ret
= track_stdio();
4364 /* Initialize thread health monitoring */
4365 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4366 if (!health_relayd
) {
4367 PERROR("health_app_create error");
4372 /* Create thread quit pipe */
4373 if (relayd_init_thread_quit_pipe()) {
4378 /* Setup the thread apps communication pipe. */
4379 if (create_relay_conn_pipe()) {
4384 /* Init relay command queue. */
4385 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4387 /* Initialize communication library */
4389 lttcomm_inet_init();
4391 /* tables of sessions indexed by session ID */
4392 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4398 /* tables of streams indexed by stream ID */
4399 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4400 if (!relay_streams_ht
) {
4405 /* tables of streams indexed by stream ID */
4406 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4407 if (!viewer_streams_ht
) {
4412 ret
= init_health_quit_pipe();
4418 /* Create thread to manage the client socket */
4419 ret
= pthread_create(&health_thread
,
4420 default_pthread_attr(),
4421 thread_manage_health_relayd
,
4425 PERROR("pthread_create health");
4430 /* Setup the dispatcher thread */
4431 ret
= pthread_create(&dispatcher_thread
,
4432 default_pthread_attr(),
4433 relay_thread_dispatcher
,
4437 PERROR("pthread_create dispatcher");
4439 goto exit_dispatcher_thread
;
4442 /* Setup the worker thread */
4443 ret
= pthread_create(&worker_thread
, default_pthread_attr(), relay_thread_worker
, nullptr);
4446 PERROR("pthread_create worker");
4448 goto exit_worker_thread
;
4451 /* Setup the listener thread */
4452 ret
= pthread_create(
4453 &listener_thread
, default_pthread_attr(), relay_thread_listener
, (void *) nullptr);
4456 PERROR("pthread_create listener");
4458 goto exit_listener_thread
;
4461 ret
= relayd_live_create(live_uri
);
4463 ERR("Starting live viewer threads");
4469 * This is where we start awaiting program completion (e.g. through
4470 * signal that asks threads to teardown).
4473 ret
= relayd_live_join();
4479 ret
= pthread_join(listener_thread
, &status
);
4482 PERROR("pthread_join listener_thread");
4486 exit_listener_thread
:
4487 ret
= pthread_join(worker_thread
, &status
);
4490 PERROR("pthread_join worker_thread");
4495 ret
= pthread_join(dispatcher_thread
, &status
);
4498 PERROR("pthread_join dispatcher_thread");
4501 exit_dispatcher_thread
:
4503 ret
= pthread_join(health_thread
, &status
);
4506 PERROR("pthread_join health_thread");
4511 * Wait for all pending call_rcu work to complete before tearing
4512 * down data structures. call_rcu worker may be trying to
4513 * perform lookups in those structures.
4518 /* Ensure all prior call_rcu are done. */
4521 if (thread_is_rcu_registered
) {
4522 rcu_unregister_thread();