2 * Copyright (C) 2012 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * SPDX-License-Identifier: GPL-2.0-only
12 #include "backward-compatibility-group-by.hpp"
14 #include "connection.hpp"
15 #include "ctf-trace.hpp"
16 #include "health-relayd.hpp"
19 #include "lttng-relayd.hpp"
20 #include "session.hpp"
21 #include "sessiond-trace-chunks.hpp"
23 #include "tcp_keep_alive.hpp"
24 #include "testpoint.hpp"
25 #include "tracefile-array.hpp"
27 #include "version.hpp"
28 #include "viewer-stream.hpp"
30 #include <common/align.hpp>
31 #include <common/buffer-view.hpp>
32 #include <common/common.hpp>
33 #include <common/compat/endian.hpp>
34 #include <common/compat/getenv.hpp>
35 #include <common/compat/poll.hpp>
36 #include <common/compat/socket.hpp>
37 #include <common/daemonize.hpp>
38 #include <common/defaults.hpp>
39 #include <common/dynamic-buffer.hpp>
40 #include <common/fd-tracker/fd-tracker.hpp>
41 #include <common/fd-tracker/utils.hpp>
42 #include <common/futex.hpp>
43 #include <common/ini-config/ini-config.hpp>
44 #include <common/path.hpp>
45 #include <common/sessiond-comm/inet.hpp>
46 #include <common/sessiond-comm/relayd.hpp>
47 #include <common/sessiond-comm/sessiond-comm.hpp>
48 #include <common/string-utils/format.hpp>
49 #include <common/urcu.hpp>
50 #include <common/uri.hpp>
51 #include <common/utils.hpp>
53 #include <lttng/lttng.h>
69 #include <sys/mount.h>
70 #include <sys/resource.h>
71 #include <sys/socket.h>
73 #include <sys/types.h>
76 #include <urcu/futex.h>
77 #include <urcu/rculist.h>
78 #include <urcu/uatomic.h>
80 static const char *help_msg
=
81 #ifdef LTTNG_EMBED_HELP
82 #include <lttng-relayd.8.h>
88 enum relay_connection_status
{
89 RELAY_CONNECTION_STATUS_OK
,
90 /* An error occurred while processing an event on the connection. */
91 RELAY_CONNECTION_STATUS_ERROR
,
92 /* Connection closed/shutdown cleanly. */
93 RELAY_CONNECTION_STATUS_CLOSED
,
96 /* command line options */
97 char *opt_output_path
, *opt_working_directory
;
98 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
99 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
101 /* Argument variables */
102 int lttng_opt_quiet
; /* not static in error.h */
103 int lttng_opt_verbose
; /* not static in error.h */
104 int lttng_opt_mi
; /* not static in error.h */
107 * We need to wait for listener and live listener threads, as well as
108 * health check thread, before being ready to signal readiness.
110 #define NR_LTTNG_RELAY_READY 3
111 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
113 /* Size of receive buffer. */
114 #define RECV_DATA_BUFFER_SIZE 65536
116 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
117 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
119 static struct lttng_uri
*control_uri
;
120 static struct lttng_uri
*data_uri
;
121 static struct lttng_uri
*live_uri
;
123 const char *progname
;
125 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
126 static int tracing_group_name_override
;
128 const char *const config_section_name
= "relayd";
131 * This pipe is used to inform the worker thread that a command is queued and
132 * ready to be processed.
134 static int relay_conn_pipe
[2] = { -1, -1 };
136 /* Shared between threads */
137 static int dispatch_thread_exit
;
139 static pthread_t listener_thread
;
140 static pthread_t dispatcher_thread
;
141 static pthread_t worker_thread
;
142 static pthread_t health_thread
;
145 * last_relay_stream_id_lock protects last_relay_stream_id increment
146 * atomicity on 32-bit architectures.
148 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
149 static uint64_t last_relay_stream_id
;
152 * Relay command queue.
154 * The relay_thread_listener and relay_thread_dispatcher communicate with this
157 static struct relay_conn_queue relay_conn_queue
;
159 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
160 static unsigned int lttng_opt_fd_pool_size
= -1;
162 /* Global relay stream hash table. */
163 struct lttng_ht
*relay_streams_ht
;
165 /* Global relay viewer stream hash table. */
166 struct lttng_ht
*viewer_streams_ht
;
168 /* Global relay sessions hash table. */
169 struct lttng_ht
*sessions_ht
;
171 /* Relayd health monitoring */
172 struct health_app
*health_relayd
;
174 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
176 /* Global fd tracker. */
177 struct fd_tracker
*the_fd_tracker
;
179 static struct option long_options
[] = {
240 { "config", 1, nullptr, 'f' },
241 { "version", 0, nullptr, 'V' },
249 "group-output-by-session",
255 "group-output-by-host",
260 { "disallow-clear", 0, nullptr, 'x' },
269 static const char *config_ignore_options
[] = { "help", "config", "version" };
271 static void print_version()
273 fprintf(stdout
, "%s\n", VERSION
);
276 static void relayd_config_log()
278 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
279 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
280 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
281 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
282 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
284 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
285 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
290 * Take an option from the getopt output and set it in the right variable to be
293 * Return 0 on success else a negative value.
295 static int set_option(int opt
, const char *arg
, const char *optname
)
301 if (!strcmp(optname
, "fd-pool-size")) {
305 v
= strtoul(arg
, nullptr, 0);
306 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
307 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
312 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s",
317 lttng_opt_fd_pool_size
= (unsigned int) v
;
319 fprintf(stderr
, "unknown option %s", optname
);
321 fprintf(stderr
, " with arg %s\n", arg
);
326 if (lttng_is_setuid_setgid()) {
327 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
328 "-C, --control-port");
330 ret
= uri_parse(arg
, &control_uri
);
332 ERR("Invalid control URI specified");
335 if (control_uri
->port
== 0) {
336 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
341 if (lttng_is_setuid_setgid()) {
342 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
345 ret
= uri_parse(arg
, &data_uri
);
347 ERR("Invalid data URI specified");
350 if (data_uri
->port
== 0) {
351 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
356 if (lttng_is_setuid_setgid()) {
357 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
360 ret
= uri_parse(arg
, &live_uri
);
362 ERR("Invalid live URI specified");
365 if (live_uri
->port
== 0) {
366 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
377 if (lttng_is_setuid_setgid()) {
378 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
381 tracing_group_name
= strdup(arg
);
382 if (tracing_group_name
== nullptr) {
387 tracing_group_name_override
= 1;
391 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
393 ERR("Cannot show --help for `lttng-relayd`");
398 opt_print_version
= 1;
401 if (lttng_is_setuid_setgid()) {
402 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
405 ret
= asprintf(&opt_output_path
, "%s", arg
);
408 PERROR("asprintf opt_output_path");
414 if (lttng_is_setuid_setgid()) {
415 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
416 "-w, --working-directory");
418 ret
= asprintf(&opt_working_directory
, "%s", arg
);
421 PERROR("asprintf opt_working_directory");
428 /* Verbose level can increase using multiple -v */
430 lttng_opt_verbose
= config_parse_value(arg
);
432 /* Only 3 level of verbosity (-vvv). */
433 if (lttng_opt_verbose
< 3) {
434 lttng_opt_verbose
+= 1;
439 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
440 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
443 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
446 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
447 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
450 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
457 /* Unknown option or other error.
458 * Error is printed by getopt, just return */
471 * config_entry_handler_cb used to handle options read from a config file.
472 * See config_entry_handler_cb comment in common/config/session-config.h for the
473 * return value conventions.
475 static int config_entry_handler(const struct config_entry
*entry
,
476 void *unused
__attribute__((unused
)))
480 if (!entry
|| !entry
->name
|| !entry
->value
) {
485 /* Check if the option is to be ignored */
486 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
487 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
492 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
493 /* Ignore if entry name is not fully matched. */
494 if (strcmp(entry
->name
, long_options
[i
].name
) != 0) {
499 * If the option takes no argument on the command line,
500 * we have to check if the value is "true". We support
501 * non-zero numeric values, true, on and yes.
503 if (!long_options
[i
].has_arg
) {
504 ret
= config_parse_value(entry
->value
);
507 WARN("Invalid configuration value \"%s\" for option %s",
511 /* False, skip boolean config option. */
516 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
520 WARN("Unrecognized option \"%s\" in daemon configuration file.", entry
->name
);
526 static int parse_env_options()
529 char *value
= nullptr;
531 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
533 opt_working_directory
= strdup(value
);
534 if (!opt_working_directory
) {
535 ERR("Failed to allocate working directory string (\"%s\")", value
);
542 static int set_fd_pool_size()
545 struct rlimit rlimit
;
547 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
549 PERROR("Failed to get file descriptor limit");
554 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
555 (uint64_t) rlimit
.rlim_cur
,
556 (uint64_t) rlimit
.rlim_max
);
557 if (lttng_opt_fd_pool_size
== -1) {
558 /* Use default value (soft limit - reserve). */
559 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
560 ERR("The process' file number limit is too low (%" PRIu64
561 "). The process' file number limit must be set to at least %i.",
562 (uint64_t) rlimit
.rlim_cur
,
563 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
567 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
571 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
572 ERR("File descriptor pool size must be set to at least %d",
573 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
578 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
579 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
581 lttng_opt_fd_pool_size
,
582 (uint64_t) rlimit
.rlim_cur
);
587 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
588 lttng_opt_fd_pool_size
,
589 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
590 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
595 static int set_options(int argc
, char **argv
)
597 int c
, ret
= 0, option_index
= 0, retval
= 0;
598 int orig_optopt
= optopt
, orig_optind
= optind
;
599 char *default_address
, *optstring
;
600 char *config_path
= nullptr;
602 optstring
= utils_generate_optstring(long_options
,
603 sizeof(long_options
) / sizeof(struct option
));
609 /* Check for the --config option */
611 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
)) != -1) {
615 } else if (c
!= 'f') {
619 if (lttng_is_setuid_setgid()) {
620 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
624 config_path
= utils_expand_path(optarg
);
626 ERR("Failed to resolve path: %s", optarg
);
631 ret
= config_get_section_entries(
632 config_path
, config_section_name
, config_entry_handler
, nullptr);
635 ERR("Invalid configuration option at line %i", ret
);
641 /* Reset getopt's global state */
642 optopt
= orig_optopt
;
643 optind
= orig_optind
;
645 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
650 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
657 /* assign default values */
658 if (control_uri
== nullptr) {
659 ret
= asprintf(&default_address
,
660 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
661 DEFAULT_NETWORK_CONTROL_PORT
);
663 PERROR("asprintf default data address");
668 ret
= uri_parse(default_address
, &control_uri
);
669 free(default_address
);
671 ERR("Invalid control URI specified");
676 if (data_uri
== nullptr) {
677 ret
= asprintf(&default_address
,
678 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
679 DEFAULT_NETWORK_DATA_PORT
);
681 PERROR("asprintf default data address");
686 ret
= uri_parse(default_address
, &data_uri
);
687 free(default_address
);
689 ERR("Invalid data URI specified");
694 if (live_uri
== nullptr) {
695 ret
= asprintf(&default_address
,
696 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
697 DEFAULT_NETWORK_VIEWER_PORT
);
699 PERROR("asprintf default viewer control address");
704 ret
= uri_parse(default_address
, &live_uri
);
705 free(default_address
);
707 ERR("Invalid viewer control URI specified");
712 ret
= set_fd_pool_size();
718 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
719 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
721 if (opt_allow_clear
) {
722 /* Check if env variable exists. */
723 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
725 ret
= config_parse_value(value
);
727 ERR("Invalid value for %s specified",
728 DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
732 opt_allow_clear
= !ret
;
742 static void print_global_objects()
744 print_viewer_streams();
745 print_relay_streams();
749 static int noop_close(void *data
__attribute__((unused
)), int *fds
__attribute__((unused
)))
754 static void untrack_stdio()
756 int fds
[] = { fileno(stdout
), fileno(stderr
) };
759 * noop_close is used since we don't really want to close
760 * the stdio output fds; we merely want to stop tracking them.
762 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
, fds
, 2, noop_close
, nullptr);
768 static void relayd_cleanup()
770 print_global_objects();
774 if (viewer_streams_ht
)
775 lttng_ht_destroy(viewer_streams_ht
);
776 if (relay_streams_ht
)
777 lttng_ht_destroy(relay_streams_ht
);
779 lttng_ht_destroy(sessions_ht
);
781 free(opt_output_path
);
782 free(opt_working_directory
);
785 health_app_destroy(health_relayd
);
787 /* Close thread quit pipes */
788 if (health_quit_pipe
[0] != -1) {
789 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
791 relayd_close_thread_quit_pipe();
792 if (sessiond_trace_chunk_registry
) {
793 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
795 if (the_fd_tracker
) {
798 * fd_tracker_destroy() will log the contents of the fd-tracker
799 * if a leak is detected.
801 fd_tracker_destroy(the_fd_tracker
);
804 uri_free(control_uri
);
806 /* Live URI is freed in the live thread. */
808 if (tracing_group_name_override
) {
809 free((void *) tracing_group_name
);
813 static int notify_health_quit_pipe(int *pipe
)
817 ret
= lttng_write(pipe
[1], "4", 1);
819 PERROR("write relay health quit");
828 * Stop all relayd and relayd-live threads.
830 int lttng_relay_stop_threads()
834 /* Stopping all threads */
835 DBG("Terminating all threads");
836 if (relayd_notify_thread_quit_pipe()) {
837 ERR("write error on thread quit pipe");
841 if (notify_health_quit_pipe(health_quit_pipe
)) {
842 ERR("write error on health quit pipe");
845 /* Dispatch thread */
846 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
847 futex_nto1_wake(&relay_conn_queue
.futex
);
849 if (relayd_live_stop()) {
850 ERR("Error stopping live threads");
857 * Signal handler for the daemon
859 * Simply stop all worker threads, leaving main() return gracefully after
860 * joining all threads and calling cleanup().
862 static void sighandler(int sig
)
866 DBG("SIGINT caught");
867 if (lttng_relay_stop_threads()) {
868 ERR("Error stopping threads");
872 DBG("SIGTERM caught");
873 if (lttng_relay_stop_threads()) {
874 ERR("Error stopping threads");
878 CMM_STORE_SHARED(recv_child_signal
, 1);
886 * Setup signal handler for :
887 * SIGINT, SIGTERM, SIGPIPE
889 static int set_signal_handler()
895 if ((ret
= sigemptyset(&sigset
)) < 0) {
896 PERROR("sigemptyset");
903 sa
.sa_handler
= sighandler
;
904 if ((ret
= sigaction(SIGTERM
, &sa
, nullptr)) < 0) {
909 if ((ret
= sigaction(SIGINT
, &sa
, nullptr)) < 0) {
914 if ((ret
= sigaction(SIGUSR1
, &sa
, nullptr)) < 0) {
919 sa
.sa_handler
= SIG_IGN
;
920 if ((ret
= sigaction(SIGPIPE
, &sa
, nullptr)) < 0) {
925 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
930 void lttng_relay_notify_ready()
932 /* Notify the parent of the fork() process that we are ready. */
933 if (opt_daemon
|| opt_background
) {
934 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
935 kill(child_ppid
, SIGUSR1
);
941 * Init health quit pipe.
943 * Return -1 on error or 0 if all pipes are created.
945 static int init_health_quit_pipe()
947 return fd_tracker_util_pipe_open_cloexec(
948 the_fd_tracker
, "Health quit pipe", health_quit_pipe
);
951 static int create_sock(void *data
, int *out_fd
)
954 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
956 ret
= lttcomm_create_sock(sock
);
966 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
968 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
970 return sock
->ops
->close(sock
);
973 static int accept_sock(void *data
, int *out_fd
)
976 /* Socks is an array of in_sock, out_sock. */
977 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
978 struct lttcomm_sock
*in_sock
= socks
[0];
980 socks
[1] = in_sock
->ops
->accept(in_sock
);
985 *out_fd
= socks
[1]->fd
;
991 * Create and init socket from uri.
993 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
, const char *name
)
996 struct lttcomm_sock
*sock
= nullptr;
997 char uri_str
[PATH_MAX
];
998 char *formated_name
= nullptr;
1000 sock
= lttcomm_alloc_sock_from_uri(uri
);
1001 if (sock
== nullptr) {
1002 ERR("Allocating socket");
1007 * Don't fail to create the socket if the name can't be built as it is
1008 * only used for debugging purposes.
1010 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1011 uri_str
[sizeof(uri_str
) - 1] = '\0';
1013 ret
= asprintf(&formated_name
, "%s socket @ %s", name
, uri_str
);
1015 formated_name
= nullptr;
1019 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
,
1021 (const char **) (formated_name
? &formated_name
:
1027 PERROR("Failed to open \"%s\" relay socket", formated_name
?: "Unknown");
1030 DBG("Listening on %s socket %d", name
, sock
->fd
);
1032 ret
= sock
->ops
->bind(sock
);
1034 PERROR("Failed to bind socket");
1038 ret
= sock
->ops
->listen(sock
, -1);
1043 free(formated_name
);
1048 lttcomm_destroy_sock(sock
);
1050 free(formated_name
);
1054 static struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1058 struct lttcomm_sock
*socks
[2] = { listening_sock
, nullptr };
1059 struct lttcomm_sock
*new_sock
= nullptr;
1061 ret
= fd_tracker_open_unsuspendable_fd(
1062 the_fd_tracker
, &out_fd
, (const char **) &name
, 1, accept_sock
, &socks
);
1066 new_sock
= socks
[1];
1067 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1073 * This thread manages the listening for new connections on the network
1075 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1077 int i
, ret
, err
= -1;
1079 struct lttng_poll_event events
;
1080 struct lttcomm_sock
*control_sock
, *data_sock
;
1082 DBG("[thread] Relay listener started");
1084 rcu_register_thread();
1085 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1087 health_code_update();
1089 control_sock
= relay_socket_create(control_uri
, "Control listener");
1090 if (!control_sock
) {
1091 goto error_sock_control
;
1094 data_sock
= relay_socket_create(data_uri
, "Data listener");
1096 goto error_sock_relay
;
1100 * Pass 3 as size here for the thread quit pipe, control and
1103 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1105 goto error_create_poll
;
1108 /* Add the control socket */
1109 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1111 goto error_poll_add
;
1114 /* Add the data socket */
1115 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1117 goto error_poll_add
;
1120 lttng_relay_notify_ready();
1122 if (testpoint(relayd_thread_listener
)) {
1123 goto error_testpoint
;
1127 health_code_update();
1129 DBG("Listener accepting connections");
1132 health_poll_entry();
1133 ret
= lttng_poll_wait(&events
, -1);
1137 * Restart interrupted system call.
1139 if (errno
== EINTR
) {
1147 DBG("Relay new connection received");
1148 for (i
= 0; i
< nb_fd
; i
++) {
1149 /* Fetch once the poll data */
1150 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
1151 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1153 health_code_update();
1155 /* Activity on thread quit pipe, exiting. */
1156 if (relayd_is_thread_quit_pipe(pollfd
)) {
1157 DBG("Activity on thread quit pipe");
1162 if (revents
& LPOLLIN
) {
1164 * A new connection is requested, therefore a
1165 * sessiond/consumerd connection is allocated in
1166 * this thread, enqueued to a global queue and
1167 * dequeued (and freed) in the worker thread.
1170 struct relay_connection
*new_conn
;
1171 struct lttcomm_sock
*newsock
= nullptr;
1172 enum connection_type type
;
1174 if (pollfd
== data_sock
->fd
) {
1176 newsock
= accept_relayd_sock(data_sock
,
1177 "Data socket to relayd");
1179 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1180 type
= RELAY_CONTROL
;
1181 newsock
= accept_relayd_sock(control_sock
,
1182 "Control socket to relayd");
1185 PERROR("accepting sock");
1190 newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
));
1192 PERROR("setsockopt inet");
1193 lttcomm_destroy_sock(newsock
);
1197 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1199 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1201 lttcomm_destroy_sock(newsock
);
1205 new_conn
= connection_create(newsock
, type
);
1207 lttcomm_destroy_sock(newsock
);
1211 /* Enqueue request for the dispatcher thread. */
1212 cds_wfcq_head_ptr_t head
;
1213 head
.h
= &relay_conn_queue
.head
;
1214 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
, &new_conn
->qnode
);
1217 * Wake the dispatch queue futex.
1218 * Implicit memory barrier with the
1219 * exchange in cds_wfcq_enqueue.
1221 futex_nto1_wake(&relay_conn_queue
.futex
);
1222 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1223 ERR("socket poll error");
1226 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1236 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1238 if (data_sock
->fd
>= 0) {
1239 int data_sock_fd
= data_sock
->fd
;
1241 ret
= fd_tracker_close_unsuspendable_fd(
1242 the_fd_tracker
, &data_sock_fd
, 1, close_sock
, data_sock
);
1244 PERROR("Failed to close the data listener socket file descriptor");
1248 lttcomm_destroy_sock(data_sock
);
1250 if (control_sock
->fd
>= 0) {
1251 int control_sock_fd
= control_sock
->fd
;
1253 ret
= fd_tracker_close_unsuspendable_fd(
1254 the_fd_tracker
, &control_sock_fd
, 1, close_sock
, control_sock
);
1256 PERROR("Failed to close the control listener socket file descriptor");
1258 control_sock
->fd
= -1;
1260 lttcomm_destroy_sock(control_sock
);
1264 ERR("Health error occurred in %s", __func__
);
1266 health_unregister(health_relayd
);
1267 rcu_unregister_thread();
1268 DBG("Relay listener thread cleanup complete");
1269 lttng_relay_stop_threads();
1274 * This thread manages the dispatching of the requests to worker threads
1276 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1280 struct cds_wfcq_node
*node
;
1281 struct relay_connection
*new_conn
= nullptr;
1283 DBG("[thread] Relay dispatcher started");
1285 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1287 if (testpoint(relayd_thread_dispatcher
)) {
1288 goto error_testpoint
;
1291 health_code_update();
1294 health_code_update();
1296 /* Atomically prepare the queue futex */
1297 futex_nto1_prepare(&relay_conn_queue
.futex
);
1299 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1304 health_code_update();
1306 /* Dequeue commands */
1307 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1308 &relay_conn_queue
.tail
);
1309 if (node
== nullptr) {
1310 DBG("Woken up but nothing in the relay command queue");
1311 /* Continue thread execution */
1314 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1316 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1319 * Inform worker thread of the new request. This
1320 * call is blocking so we can be assured that
1321 * the data will be read at some point in time
1322 * or wait to the end of the world :)
1325 relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
)); /* NOLINT
1332 PERROR("write connection pipe");
1333 connection_put(new_conn
);
1336 } while (node
!= nullptr);
1338 /* Futex wait on queue. Blocking call on futex() */
1339 health_poll_entry();
1340 futex_nto1_wait(&relay_conn_queue
.futex
);
1344 /* Normal exit, no error */
1351 ERR("Health error occurred in %s", __func__
);
1353 health_unregister(health_relayd
);
1354 DBG("Dispatch thread dying");
1355 lttng_relay_stop_threads();
1359 static bool session_streams_have_index(const struct relay_session
*session
)
1361 return session
->minor
>= 4 && !session
->snapshot
;
1365 * Handle the RELAYD_CREATE_SESSION command.
1367 * On success, send back the session id or else return a negative value.
1369 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1370 struct relay_connection
*conn
,
1371 const struct lttng_buffer_view
*payload
)
1375 struct relay_session
*session
= nullptr;
1376 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1377 char session_name
[LTTNG_NAME_MAX
] = {};
1378 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1379 uint32_t live_timer
= 0;
1380 bool snapshot
= false;
1381 bool session_name_contains_creation_timestamp
= false;
1382 /* Left nil for peers < 2.11. */
1383 char base_path
[LTTNG_PATH_MAX
] = {};
1384 lttng_uuid sessiond_uuid
= {};
1385 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1386 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1387 LTTNG_OPTIONAL(time_t) creation_time
= {};
1388 struct lttng_dynamic_buffer reply_payload
;
1390 lttng_dynamic_buffer_init(&reply_payload
);
1392 if (conn
->minor
< 4) {
1393 /* From 2.1 to 2.3 */
1395 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1396 /* From 2.4 to 2.10 */
1397 ret
= cmd_create_session_2_4(
1398 payload
, session_name
, hostname
, &live_timer
, &snapshot
);
1400 bool has_current_chunk
;
1401 uint64_t current_chunk_id_value
;
1402 time_t creation_time_value
;
1403 uint64_t id_sessiond_value
;
1405 /* From 2.11 to ... */
1406 ret
= cmd_create_session_2_11(payload
,
1415 ¤t_chunk_id_value
,
1416 &creation_time_value
,
1417 &session_name_contains_creation_timestamp
);
1418 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1419 /* The nil UUID is reserved for pre-2.11 clients. */
1420 ERR("Illegal nil UUID announced by peer in create session command");
1424 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1425 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1426 if (has_current_chunk
) {
1427 LTTNG_OPTIONAL_SET(¤t_chunk_id
, current_chunk_id_value
);
1435 session
= session_create(session_name
,
1441 id_sessiond
.is_set
? &id_sessiond
.value
: nullptr,
1442 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: nullptr,
1443 creation_time
.is_set
? &creation_time
.value
: nullptr,
1446 session_name_contains_creation_timestamp
);
1451 LTTNG_ASSERT(!conn
->session
);
1452 conn
->session
= session
;
1453 DBG("Created session %" PRIu64
, session
->id
);
1455 reply
.generic
.session_id
= htobe64(session
->id
);
1459 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1461 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1464 if (conn
->minor
< 11) {
1465 /* From 2.1 to 2.10 */
1466 ret
= lttng_dynamic_buffer_append(
1467 &reply_payload
, &reply
.generic
, sizeof(reply
.generic
));
1469 ERR("Failed to append \"create session\" command reply header to payload buffer");
1474 const uint32_t output_path_length
= session
? strlen(session
->output_path
) + 1 : 0;
1476 reply
.output_path_length
= htobe32(output_path_length
);
1477 ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
1479 ERR("Failed to append \"create session\" command reply header to payload buffer");
1483 if (output_path_length
) {
1484 ret
= lttng_dynamic_buffer_append(
1485 &reply_payload
, session
->output_path
, output_path_length
);
1487 ERR("Failed to append \"create session\" command reply path to payload buffer");
1493 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
1494 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1495 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1501 if (ret
< 0 && session
) {
1502 session_put(session
);
1504 lttng_dynamic_buffer_reset(&reply_payload
);
1509 * When we have received all the streams and the metadata for a channel,
1510 * we make them visible to the viewer threads.
1512 static void publish_connection_local_streams(struct relay_connection
*conn
)
1514 struct relay_stream
*stream
;
1515 struct relay_session
*session
= conn
->session
;
1518 * We publish all streams belonging to a session atomically wrt
1521 pthread_mutex_lock(&session
->lock
);
1522 lttng::urcu::read_lock_guard read_lock
;
1523 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
, recv_node
)
1525 stream_publish(stream
);
1529 * Inform the viewer that there are new streams in the session.
1531 if (session
->viewer_attached
) {
1532 uatomic_set(&session
->new_streams
, 1);
1534 pthread_mutex_unlock(&session
->lock
);
1537 static int conform_channel_path(char *channel_path
)
1541 if (strstr("../", channel_path
)) {
1542 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1548 if (*channel_path
== '/') {
1549 const size_t len
= strlen(channel_path
);
1552 * Channel paths from peers prior to 2.11 are expressed as an
1553 * absolute path that is, in reality, relative to the relay
1554 * daemon's output directory. Remove the leading slash so it
1555 * is correctly interpreted as a relative path later on.
1557 * len (and not len - 1) is used to copy the trailing NULL.
1559 bcopy(channel_path
+ 1, channel_path
, len
);
1566 * relay_add_stream: allocate a new stream for a session
1568 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1569 struct relay_connection
*conn
,
1570 const struct lttng_buffer_view
*payload
)
1574 struct relay_session
*session
= conn
->session
;
1575 struct relay_stream
*stream
= nullptr;
1576 struct lttcomm_relayd_status_stream reply
;
1577 struct ctf_trace
*trace
= nullptr;
1578 uint64_t stream_handle
= -1ULL;
1579 char *path_name
= nullptr, *channel_name
= nullptr;
1580 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1581 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1583 if (!session
|| !conn
->version_check_done
) {
1584 ERR("Trying to add a stream before version check");
1586 goto end_no_session
;
1589 if (session
->minor
== 1) {
1591 ret
= cmd_recv_stream_2_1(payload
, &path_name
, &channel_name
);
1592 } else if (session
->minor
> 1 && session
->minor
< 11) {
1593 /* From 2.2 to 2.10 */
1594 ret
= cmd_recv_stream_2_2(
1595 payload
, &path_name
, &channel_name
, &tracefile_size
, &tracefile_count
);
1597 /* From 2.11 to ... */
1598 ret
= cmd_recv_stream_2_11(payload
,
1603 &stream_chunk_id
.value
);
1604 stream_chunk_id
.is_set
= true;
1611 if (conform_channel_path(path_name
)) {
1616 * Backward compatibility for --group-output-by-session.
1617 * Prior to lttng 2.11, the complete path is passed by the stream.
1618 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1619 * >=2.11 the chunk is responsible for the output path. When dealing
1620 * with producer < 2.11 the chunk output_path is the root output path
1621 * and the stream carries the complete path (path_name).
1622 * To support --group-output-by-session with older producer (<2.11), we
1623 * need to craft the path based on the stream path.
1625 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1626 if (conn
->minor
< 4) {
1628 * From 2.1 to 2.3, the session_name is not passed on
1629 * the RELAYD_CREATE_SESSION command. The session name
1630 * is necessary to detect the presence of a base_path
1631 * inside the stream path. Without it we cannot perform
1632 * a valid group-output-by-session transformation.
1634 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1635 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1638 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1639 char *group_by_session_path_name
;
1641 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1643 group_by_session_path_name
= backward_compat_group_by_session(
1644 path_name
, session
->session_name
, session
->creation_time
.value
);
1645 if (!group_by_session_path_name
) {
1646 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1651 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1653 group_by_session_path_name
);
1656 path_name
= group_by_session_path_name
;
1660 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1665 /* This stream here has one reference on the trace. */
1666 pthread_mutex_lock(&last_relay_stream_id_lock
);
1667 stream_handle
= ++last_relay_stream_id
;
1668 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1670 /* We pass ownership of path_name and channel_name. */
1671 stream
= stream_create(
1672 trace
, stream_handle
, path_name
, channel_name
, tracefile_size
, tracefile_count
);
1673 path_name
= nullptr;
1674 channel_name
= nullptr;
1677 * Streams are the owners of their trace. Reference to trace is
1678 * kept within stream_create().
1680 ctf_trace_put(trace
);
1683 memset(&reply
, 0, sizeof(reply
));
1684 reply
.handle
= htobe64(stream_handle
);
1686 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1688 reply
.ret_code
= htobe32(LTTNG_OK
);
1691 send_ret
= conn
->sock
->ops
->sendmsg(
1692 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_status_stream
), 0);
1693 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1694 ERR("Failed to send \"add stream\" command reply (ret = %zd)", send_ret
);
1705 * relay_close_stream: close a specific stream
1707 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1708 struct relay_connection
*conn
,
1709 const struct lttng_buffer_view
*payload
)
1713 struct relay_session
*session
= conn
->session
;
1714 struct lttcomm_relayd_close_stream stream_info
;
1715 struct lttcomm_relayd_generic_reply reply
;
1716 struct relay_stream
*stream
;
1718 DBG("Close stream received");
1720 if (!session
|| !conn
->version_check_done
) {
1721 ERR("Trying to close a stream before version check");
1723 goto end_no_session
;
1726 if (payload
->size
< sizeof(stream_info
)) {
1727 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1728 sizeof(stream_info
),
1731 goto end_no_session
;
1733 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1734 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1735 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1737 stream
= stream_get_by_id(stream_info
.stream_id
);
1744 * Set last_net_seq_num before the close flag. Required by data
1747 pthread_mutex_lock(&stream
->lock
);
1748 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1749 pthread_mutex_unlock(&stream
->lock
);
1752 * This is one of the conditions which may trigger a stream close
1753 * with the others being:
1754 * 1) A close command is received for a stream
1755 * 2) The control connection owning the stream is closed
1756 * 3) We have received all of the stream's data _after_ a close
1759 try_stream_close(stream
);
1764 memset(&reply
, 0, sizeof(reply
));
1766 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1768 reply
.ret_code
= htobe32(LTTNG_OK
);
1770 send_ret
= conn
->sock
->ops
->sendmsg(
1771 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1772 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1773 ERR("Failed to send \"close stream\" command reply (ret = %zd)", send_ret
);
1782 * relay_reset_metadata: reset a metadata stream
1784 static int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1785 struct relay_connection
*conn
,
1786 const struct lttng_buffer_view
*payload
)
1790 struct relay_session
*session
= conn
->session
;
1791 struct lttcomm_relayd_reset_metadata stream_info
;
1792 struct lttcomm_relayd_generic_reply reply
;
1793 struct relay_stream
*stream
;
1795 DBG("Reset metadata received");
1797 if (!session
|| !conn
->version_check_done
) {
1798 ERR("Trying to reset a metadata stream before version check");
1800 goto end_no_session
;
1803 if (payload
->size
< sizeof(stream_info
)) {
1804 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1805 sizeof(stream_info
),
1808 goto end_no_session
;
1810 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1811 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1812 stream_info
.version
= be64toh(stream_info
.version
);
1814 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1816 /* Unsupported for live sessions for now. */
1817 if (session
->live_timer
!= 0) {
1822 stream
= stream_get_by_id(stream_info
.stream_id
);
1827 pthread_mutex_lock(&stream
->lock
);
1828 if (!stream
->is_metadata
) {
1833 ret
= stream_reset_file(stream
);
1835 ERR("Failed to reset metadata stream %" PRIu64
": stream_path = %s, channel = %s",
1836 stream
->stream_handle
,
1838 stream
->channel_name
);
1842 pthread_mutex_unlock(&stream
->lock
);
1846 memset(&reply
, 0, sizeof(reply
));
1848 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1850 reply
.ret_code
= htobe32(LTTNG_OK
);
1852 send_ret
= conn
->sock
->ops
->sendmsg(
1853 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
1854 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1855 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)", send_ret
);
1864 * relay_unknown_command: send -1 if received unknown command
1866 static void relay_unknown_command(struct relay_connection
*conn
)
1868 struct lttcomm_relayd_generic_reply reply
;
1871 memset(&reply
, 0, sizeof(reply
));
1872 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1873 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1874 if (send_ret
< sizeof(reply
)) {
1875 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1880 * relay_start: send an acknowledgment to the client to tell if we are
1881 * ready to receive data. We are ready if a session is established.
1883 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1884 struct relay_connection
*conn
,
1885 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1889 struct lttcomm_relayd_generic_reply reply
;
1890 struct relay_session
*session
= conn
->session
;
1893 DBG("Trying to start the streaming without a session established");
1894 ret
= htobe32(LTTNG_ERR_UNK
);
1897 memset(&reply
, 0, sizeof(reply
));
1898 reply
.ret_code
= htobe32(LTTNG_OK
);
1899 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1900 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1901 ERR("Failed to send \"relay_start\" command reply (ret = %zd)", send_ret
);
1909 * relay_recv_metadata: receive the metadata for the session.
1911 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1912 struct relay_connection
*conn
,
1913 const struct lttng_buffer_view
*payload
)
1916 struct relay_session
*session
= conn
->session
;
1917 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1918 struct relay_stream
*metadata_stream
;
1919 uint64_t metadata_payload_size
;
1920 struct lttng_buffer_view packet_view
;
1923 ERR("Metadata sent before version check");
1928 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1929 ERR("Incorrect data size");
1933 metadata_payload_size
=
1934 recv_hdr
->data_size
- sizeof(struct lttcomm_relayd_metadata_payload
);
1936 memcpy(&metadata_payload_header
, payload
->data
, sizeof(metadata_payload_header
));
1937 metadata_payload_header
.stream_id
= be64toh(metadata_payload_header
.stream_id
);
1938 metadata_payload_header
.padding_size
= be32toh(metadata_payload_header
.padding_size
);
1940 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1941 if (!metadata_stream
) {
1946 packet_view
= lttng_buffer_view_from_view(
1947 payload
, sizeof(metadata_payload_header
), metadata_payload_size
);
1948 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1949 ERR("Invalid metadata packet length announced by header");
1954 pthread_mutex_lock(&metadata_stream
->lock
);
1955 ret
= stream_write(metadata_stream
, &packet_view
, metadata_payload_header
.padding_size
);
1956 pthread_mutex_unlock(&metadata_stream
->lock
);
1962 stream_put(metadata_stream
);
1968 * relay_send_version: send relayd version number
1970 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1971 struct relay_connection
*conn
,
1972 const struct lttng_buffer_view
*payload
)
1976 struct lttcomm_relayd_version reply
, msg
;
1977 bool compatible
= true;
1979 conn
->version_check_done
= true;
1981 /* Get version from the other side. */
1982 if (payload
->size
< sizeof(msg
)) {
1983 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1990 memcpy(&msg
, payload
->data
, sizeof(msg
));
1991 msg
.major
= be32toh(msg
.major
);
1992 msg
.minor
= be32toh(msg
.minor
);
1994 memset(&reply
, 0, sizeof(reply
));
1995 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1996 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1998 /* Major versions must be the same */
1999 if (reply
.major
!= msg
.major
) {
2000 DBG("Incompatible major versions (%u vs %u), deleting session",
2006 conn
->major
= reply
.major
;
2007 /* We adapt to the lowest compatible version */
2008 if (reply
.minor
<= msg
.minor
) {
2009 conn
->minor
= reply
.minor
;
2011 conn
->minor
= msg
.minor
;
2014 reply
.major
= htobe32(reply
.major
);
2015 reply
.minor
= htobe32(reply
.minor
);
2016 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2017 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2018 ERR("Failed to send \"send version\" command reply (ret = %zd)", send_ret
);
2030 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
2037 * Check for data pending for a given stream id from the session daemon.
2039 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2040 struct relay_connection
*conn
,
2041 const struct lttng_buffer_view
*payload
)
2043 struct relay_session
*session
= conn
->session
;
2044 struct lttcomm_relayd_data_pending msg
;
2045 struct lttcomm_relayd_generic_reply reply
;
2046 struct relay_stream
*stream
;
2049 uint64_t stream_seq
;
2051 DBG("Data pending command received");
2053 if (!session
|| !conn
->version_check_done
) {
2054 ERR("Trying to check for data before version check");
2056 goto end_no_session
;
2059 if (payload
->size
< sizeof(msg
)) {
2060 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2064 goto end_no_session
;
2066 memcpy(&msg
, payload
->data
, sizeof(msg
));
2067 msg
.stream_id
= be64toh(msg
.stream_id
);
2068 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2070 stream
= stream_get_by_id(msg
.stream_id
);
2071 if (stream
== nullptr) {
2076 pthread_mutex_lock(&stream
->lock
);
2078 if (session_streams_have_index(session
)) {
2080 * Ensure that both the index and stream data have been
2081 * flushed up to the requested point.
2083 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2085 stream_seq
= stream
->prev_data_seq
;
2087 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2088 ", prev_index_seq %" PRIu64
", and last_seq %" PRIu64
,
2090 stream
->prev_data_seq
,
2091 stream
->prev_index_seq
,
2092 msg
.last_net_seq_num
);
2094 /* Avoid wrapping issue */
2095 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2096 /* Data has in fact been written and is NOT pending */
2099 /* Data still being streamed thus pending */
2103 stream
->data_pending_check_done
= true;
2104 pthread_mutex_unlock(&stream
->lock
);
2109 memset(&reply
, 0, sizeof(reply
));
2110 reply
.ret_code
= htobe32(ret
);
2111 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2112 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2113 ERR("Failed to send \"data pending\" command reply (ret = %zd)", send_ret
);
2122 * Wait for the control socket to reach a quiescent state.
2124 * Note that for now, when receiving this command from the session
2125 * daemon, this means that every subsequent commands or data received on
2126 * the control socket has been handled. So, this is why we simply return
2129 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
2130 __attribute__((unused
)),
2131 struct relay_connection
*conn
,
2132 const struct lttng_buffer_view
*payload
)
2136 struct relay_stream
*stream
;
2137 struct lttcomm_relayd_quiescent_control msg
;
2138 struct lttcomm_relayd_generic_reply reply
;
2140 DBG("Checking quiescent state on control socket");
2142 if (!conn
->session
|| !conn
->version_check_done
) {
2143 ERR("Trying to check for data before version check");
2145 goto end_no_session
;
2148 if (payload
->size
< sizeof(msg
)) {
2149 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2153 goto end_no_session
;
2155 memcpy(&msg
, payload
->data
, sizeof(msg
));
2156 msg
.stream_id
= be64toh(msg
.stream_id
);
2158 stream
= stream_get_by_id(msg
.stream_id
);
2162 pthread_mutex_lock(&stream
->lock
);
2163 stream
->data_pending_check_done
= true;
2164 pthread_mutex_unlock(&stream
->lock
);
2166 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2169 memset(&reply
, 0, sizeof(reply
));
2170 reply
.ret_code
= htobe32(LTTNG_OK
);
2171 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2172 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2173 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)", send_ret
);
2184 * Initialize a data pending command. This means that a consumer is about
2185 * to ask for data pending for each stream it holds. Simply iterate over
2186 * all streams of a session and set the data_pending_check_done flag.
2188 * This command returns to the client a LTTNG_OK code.
2190 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2191 struct relay_connection
*conn
,
2192 const struct lttng_buffer_view
*payload
)
2196 struct lttng_ht_iter iter
;
2197 struct lttcomm_relayd_begin_data_pending msg
;
2198 struct lttcomm_relayd_generic_reply reply
;
2199 struct relay_stream
*stream
;
2201 LTTNG_ASSERT(recv_hdr
);
2204 DBG("Init streams for data pending");
2206 if (!conn
->session
|| !conn
->version_check_done
) {
2207 ERR("Trying to check for data before version check");
2209 goto end_no_session
;
2212 if (payload
->size
< sizeof(msg
)) {
2213 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2217 goto end_no_session
;
2219 memcpy(&msg
, payload
->data
, sizeof(msg
));
2220 msg
.session_id
= be64toh(msg
.session_id
);
2223 * Iterate over all streams to set the begin data pending flag.
2224 * For now, the streams are indexed by stream handle so we have
2225 * to iterate over all streams to find the one associated with
2226 * the right session_id.
2229 lttng::urcu::read_lock_guard read_lock
;
2231 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2232 if (!stream_get(stream
)) {
2236 if (stream
->trace
->session
->id
== msg
.session_id
) {
2237 pthread_mutex_lock(&stream
->lock
);
2238 stream
->data_pending_check_done
= false;
2239 pthread_mutex_unlock(&stream
->lock
);
2240 DBG("Set begin data pending flag to stream %" PRIu64
,
2241 stream
->stream_handle
);
2248 memset(&reply
, 0, sizeof(reply
));
2249 /* All good, send back reply. */
2250 reply
.ret_code
= htobe32(LTTNG_OK
);
2252 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2253 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2254 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)", send_ret
);
2265 * End data pending command. This will check, for a given session id, if
2266 * each stream associated with it has its data_pending_check_done flag
2267 * set. If not, this means that the client lost track of the stream but
2268 * the data is still being streamed on our side. In this case, we inform
2269 * the client that data is in flight.
2271 * Return to the client if there is data in flight or not with a ret_code.
2273 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2274 struct relay_connection
*conn
,
2275 const struct lttng_buffer_view
*payload
)
2279 struct lttng_ht_iter iter
;
2280 struct lttcomm_relayd_end_data_pending msg
;
2281 struct lttcomm_relayd_generic_reply reply
;
2282 struct relay_stream
*stream
;
2283 uint32_t is_data_inflight
= 0;
2285 DBG("End data pending command");
2287 if (!conn
->session
|| !conn
->version_check_done
) {
2288 ERR("Trying to check for data before version check");
2290 goto end_no_session
;
2293 if (payload
->size
< sizeof(msg
)) {
2294 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2298 goto end_no_session
;
2300 memcpy(&msg
, payload
->data
, sizeof(msg
));
2301 msg
.session_id
= be64toh(msg
.session_id
);
2304 * Iterate over all streams to see if the begin data pending
2308 lttng::urcu::read_lock_guard read_lock
;
2310 cds_lfht_for_each_entry (relay_streams_ht
->ht
, &iter
.iter
, stream
, node
.node
) {
2311 if (!stream_get(stream
)) {
2315 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2320 pthread_mutex_lock(&stream
->lock
);
2321 if (!stream
->data_pending_check_done
) {
2322 uint64_t stream_seq
;
2324 if (session_streams_have_index(conn
->session
)) {
2326 * Ensure that both the index and stream data have been
2327 * flushed up to the requested point.
2329 stream_seq
= std::min(stream
->prev_data_seq
,
2330 stream
->prev_index_seq
);
2332 stream_seq
= stream
->prev_data_seq
;
2335 if (!stream
->closed
||
2336 !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2337 is_data_inflight
= 1;
2338 DBG("Data is still in flight for stream %" PRIu64
,
2339 stream
->stream_handle
);
2340 pthread_mutex_unlock(&stream
->lock
);
2346 pthread_mutex_unlock(&stream
->lock
);
2351 memset(&reply
, 0, sizeof(reply
));
2352 /* All good, send back reply. */
2353 reply
.ret_code
= htobe32(is_data_inflight
);
2355 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2356 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2357 ERR("Failed to send \"end data pending\" command reply (ret = %zd)", send_ret
);
2368 * Receive an index for a specific stream.
2370 * Return 0 on success else a negative value.
2372 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2373 struct relay_connection
*conn
,
2374 const struct lttng_buffer_view
*payload
)
2378 struct relay_session
*session
= conn
->session
;
2379 struct lttcomm_relayd_index index_info
;
2380 struct lttcomm_relayd_generic_reply reply
;
2381 struct relay_stream
*stream
;
2386 DBG("Relay receiving index");
2388 if (!session
|| !conn
->version_check_done
) {
2389 ERR("Trying to close a stream before version check");
2391 goto end_no_session
;
2394 msg_len
= lttcomm_relayd_index_len(lttng_to_index_major(conn
->major
, conn
->minor
),
2395 lttng_to_index_minor(conn
->major
, conn
->minor
));
2396 if (payload
->size
< msg_len
) {
2397 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2401 goto end_no_session
;
2403 memcpy(&index_info
, payload
->data
, msg_len
);
2404 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2405 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2406 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2407 index_info
.content_size
= be64toh(index_info
.content_size
);
2408 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2409 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2410 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2411 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2413 if (conn
->minor
>= 8) {
2414 index_info
.stream_instance_id
= be64toh(index_info
.stream_instance_id
);
2415 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2417 index_info
.stream_instance_id
= -1ULL;
2418 index_info
.packet_seq_num
= -1ULL;
2421 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2423 ERR("stream_get_by_id not found");
2428 pthread_mutex_lock(&stream
->lock
);
2429 ret
= stream_add_index(stream
, &index_info
);
2430 pthread_mutex_unlock(&stream
->lock
);
2432 goto end_stream_put
;
2438 memset(&reply
, 0, sizeof(reply
));
2440 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2442 reply
.ret_code
= htobe32(LTTNG_OK
);
2444 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2445 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2446 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2455 * Receive the streams_sent message.
2457 * Return 0 on success else a negative value.
2459 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2460 struct relay_connection
*conn
,
2461 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2465 struct lttcomm_relayd_generic_reply reply
;
2469 DBG("Relay receiving streams_sent");
2471 if (!conn
->session
|| !conn
->version_check_done
) {
2472 ERR("Trying to close a stream before version check");
2474 goto end_no_session
;
2478 * Publish every pending stream in the connection recv list which are
2479 * now ready to be used by the viewer.
2481 publish_connection_local_streams(conn
);
2483 memset(&reply
, 0, sizeof(reply
));
2484 reply
.ret_code
= htobe32(LTTNG_OK
);
2485 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2486 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2487 ERR("Failed to send \"streams sent\" command reply (ret = %zd)", send_ret
);
2499 relay_unpack_rotate_streams_header(const struct lttng_buffer_view
*payload
,
2500 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2502 struct lttcomm_relayd_rotate_streams rotate_streams
;
2504 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2505 * This is the smallest version of this structure, but it can be larger;
2506 * this variable is updated once the proper size of the structure is known.
2508 * See comment at the declaration of this structure for more information.
2510 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2511 size_t expected_payload_size_no_padding
, expected_payload_size_3_bytes_padding
,
2512 expected_payload_size_7_bytes_padding
;
2514 if (payload
->size
< header_len
) {
2515 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2522 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2523 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2525 * We start by "unpacking" `stream_count` to figure out the padding length
2526 * emited by our peer.
2529 decltype(rotate_streams
.stream_count
) stream_count
;
2531 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2532 rotate_streams
.stream_count
= be32toh(stream_count
);
2535 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2538 * Payload size expected given the possible padding lengths in
2539 * `struct lttcomm_relayd_rotate_streams`.
2541 expected_payload_size_no_padding
=
2542 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2543 sizeof(lttcomm_relayd_rotate_streams_packed
);
2544 expected_payload_size_3_bytes_padding
=
2545 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2546 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2547 expected_payload_size_7_bytes_padding
=
2548 (rotate_streams
.stream_count
* sizeof(*rotate_streams
.rotation_positions
)) +
2549 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2551 if (payload
->size
== expected_payload_size_no_padding
) {
2552 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2555 * This handles cases where someone might build with
2556 * -fpack-struct or any other toolchain that wouldn't produce
2557 * padding to align `value`.
2559 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2561 header_len
= sizeof(packed_rotate_streams
);
2562 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2564 /* Unpack the packed structure to the natively-packed version. */
2565 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2566 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2567 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2569 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2570 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2571 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2573 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2575 header_len
= sizeof(padded_rotate_streams
);
2576 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2578 /* Unpack the 3-byte padded structure to the natively-packed version. */
2579 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2580 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2581 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2583 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2584 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2585 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2587 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2589 header_len
= sizeof(padded_rotate_streams
);
2590 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2592 /* Unpack the 7-byte padded structure to the natively-packed version. */
2593 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2594 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2595 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2597 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2599 header_len
= sizeof(padded_rotate_streams
);
2601 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2602 expected_payload_size_no_padding
,
2603 expected_payload_size_3_bytes_padding
,
2604 expected_payload_size_7_bytes_padding
,
2615 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2616 * session rotation feature (not the tracefile rotation feature).
2618 static int relay_rotate_session_streams(const struct lttcomm_relayd_hdr
*recv_hdr
2619 __attribute__((unused
)),
2620 struct relay_connection
*conn
,
2621 const struct lttng_buffer_view
*payload
)
2626 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2627 struct relay_session
*session
= conn
->session
;
2628 struct lttcomm_relayd_rotate_streams rotate_streams
;
2629 struct lttcomm_relayd_generic_reply reply
= {};
2630 struct relay_stream
*stream
= nullptr;
2631 struct lttng_trace_chunk
*next_trace_chunk
= nullptr;
2632 struct lttng_buffer_view stream_positions
;
2633 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2634 const char *chunk_id_str
= "none";
2637 if (!session
|| !conn
->version_check_done
) {
2638 ERR("Trying to rotate a stream before version check");
2643 if (session
->major
== 2 && session
->minor
< 11) {
2644 ERR("Unsupported feature before 2.11");
2649 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2650 if (header_len
< 0) {
2655 if (rotate_streams
.new_chunk_id
.is_set
) {
2657 * Retrieve the trace chunk the stream must transition to. As
2658 * per the protocol, this chunk should have been created
2659 * before this command is received.
2661 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2662 sessiond_trace_chunk_registry
,
2663 session
->sessiond_uuid
,
2664 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2666 rotate_streams
.new_chunk_id
.value
);
2667 if (!next_trace_chunk
) {
2668 char uuid_str
[LTTNG_UUID_STR_LEN
];
2670 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2671 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2672 ", trace_chunk_id = %" PRIu64
,
2675 rotate_streams
.new_chunk_id
.value
);
2676 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2681 ret
= snprintf(chunk_id_buf
,
2682 sizeof(chunk_id_buf
),
2684 rotate_streams
.new_chunk_id
.value
);
2685 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2686 chunk_id_str
= "formatting error";
2688 chunk_id_str
= chunk_id_buf
;
2692 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2693 rotate_streams
.stream_count
,
2694 session
->session_name
,
2697 stream_positions
= lttng_buffer_view_from_view(payload
, header_len
, -1);
2698 if (!stream_positions
.data
||
2699 stream_positions
.size
< (rotate_streams
.stream_count
*
2700 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2701 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2706 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2707 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2708 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2709 const struct lttcomm_relayd_stream_rotation_position pos
= {
2710 .stream_id
= be64toh(position_comm
->stream_id
),
2711 .rotate_at_seq_num
= be64toh(position_comm
->rotate_at_seq_num
),
2714 stream
= stream_get_by_id(pos
.stream_id
);
2716 reply_code
= LTTNG_ERR_INVALID
;
2721 pthread_mutex_lock(&stream
->lock
);
2722 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
, pos
.rotate_at_seq_num
);
2723 pthread_mutex_unlock(&stream
->lock
);
2725 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2733 reply_code
= LTTNG_OK
;
2740 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2741 send_ret
= conn
->sock
->ops
->sendmsg(
2742 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2743 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2744 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)", send_ret
);
2748 lttng_trace_chunk_put(next_trace_chunk
);
2753 * relay_create_trace_chunk: create a new trace chunk
2755 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2756 __attribute__((unused
)),
2757 struct relay_connection
*conn
,
2758 const struct lttng_buffer_view
*payload
)
2762 struct relay_session
*session
= conn
->session
;
2763 struct lttcomm_relayd_create_trace_chunk
*msg
;
2764 struct lttcomm_relayd_generic_reply reply
= {};
2765 struct lttng_buffer_view header_view
;
2766 struct lttng_trace_chunk
*chunk
= nullptr, *published_chunk
= nullptr;
2767 enum lttng_error_code reply_code
= LTTNG_OK
;
2768 enum lttng_trace_chunk_status chunk_status
;
2769 const char *new_path
;
2771 if (!session
|| !conn
->version_check_done
) {
2772 ERR("Trying to create a trace chunk before version check");
2777 if (session
->major
== 2 && session
->minor
< 11) {
2778 ERR("Chunk creation command is unsupported before 2.11");
2783 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2784 if (!lttng_buffer_view_is_valid(&header_view
)) {
2785 ERR("Failed to receive payload of chunk creation command");
2790 /* Convert to host endianness. */
2791 msg
= (typeof(msg
)) header_view
.data
;
2792 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2793 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2794 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2796 pthread_mutex_lock(&conn
->session
->lock
);
2797 session
->ongoing_rotation
= true;
2798 if (session
->current_trace_chunk
&&
2799 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2800 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2801 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2802 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2803 ERR("Failed to rename old chunk");
2805 reply_code
= LTTNG_ERR_UNK
;
2809 if (!session
->current_trace_chunk
) {
2810 if (!session
->has_rotated
) {
2816 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2818 chunk
= lttng_trace_chunk_create(msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2820 ERR("Failed to create trace chunk in trace chunk creation command");
2822 reply_code
= LTTNG_ERR_NOMEM
;
2825 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2827 if (msg
->override_name_length
) {
2829 const struct lttng_buffer_view chunk_name_view
= lttng_buffer_view_from_view(
2830 payload
, sizeof(*msg
), msg
->override_name_length
);
2832 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2833 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2835 reply_code
= LTTNG_ERR_INVALID
;
2839 name
= chunk_name_view
.data
;
2840 if (name
[msg
->override_name_length
- 1]) {
2841 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2843 reply_code
= LTTNG_ERR_INVALID
;
2847 chunk_status
= lttng_trace_chunk_override_name(chunk
, chunk_name_view
.data
);
2848 switch (chunk_status
) {
2849 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2851 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2852 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2853 reply_code
= LTTNG_ERR_INVALID
;
2857 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2858 reply_code
= LTTNG_ERR_UNK
;
2864 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2865 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2866 reply_code
= LTTNG_ERR_UNK
;
2871 LTTNG_ASSERT(conn
->session
->output_directory
);
2872 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, conn
->session
->output_directory
);
2873 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2874 reply_code
= LTTNG_ERR_UNK
;
2879 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2880 sessiond_trace_chunk_registry
,
2881 conn
->session
->sessiond_uuid
,
2882 conn
->session
->id_sessiond
.is_set
? conn
->session
->id_sessiond
.value
:
2885 if (!published_chunk
) {
2886 char uuid_str
[LTTNG_UUID_STR_LEN
];
2888 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2889 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
2890 ", chunk_id = %" PRIu64
,
2895 reply_code
= LTTNG_ERR_NOMEM
;
2899 if (conn
->session
->pending_closure_trace_chunk
) {
2901 * Invalid; this means a second create_trace_chunk command was
2902 * received before a close_trace_chunk.
2904 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2905 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2909 conn
->session
->pending_closure_trace_chunk
= conn
->session
->current_trace_chunk
;
2910 conn
->session
->current_trace_chunk
= published_chunk
;
2911 published_chunk
= nullptr;
2912 if (!conn
->session
->pending_closure_trace_chunk
) {
2913 session
->ongoing_rotation
= false;
2916 pthread_mutex_unlock(&conn
->session
->lock
);
2917 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2918 send_ret
= conn
->sock
->ops
->sendmsg(
2919 conn
->sock
, &reply
, sizeof(struct lttcomm_relayd_generic_reply
), 0);
2920 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2921 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
2925 lttng_trace_chunk_put(chunk
);
2926 lttng_trace_chunk_put(published_chunk
);
2931 * relay_close_trace_chunk: close a trace chunk
2933 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
2934 __attribute__((unused
)),
2935 struct relay_connection
*conn
,
2936 const struct lttng_buffer_view
*payload
)
2938 int ret
= 0, buf_ret
;
2940 struct relay_session
*session
= conn
->session
;
2941 struct lttcomm_relayd_close_trace_chunk
*msg
;
2942 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2943 struct lttng_buffer_view header_view
;
2944 struct lttng_trace_chunk
*chunk
= nullptr;
2945 enum lttng_error_code reply_code
= LTTNG_OK
;
2946 enum lttng_trace_chunk_status chunk_status
;
2948 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2949 time_t close_timestamp
;
2950 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2951 size_t path_length
= 0;
2952 const char *chunk_name
= nullptr;
2953 struct lttng_dynamic_buffer reply_payload
;
2954 const char *new_path
;
2956 lttng_dynamic_buffer_init(&reply_payload
);
2958 if (!session
|| !conn
->version_check_done
) {
2959 ERR("Trying to close a trace chunk before version check");
2964 if (session
->major
== 2 && session
->minor
< 11) {
2965 ERR("Chunk close command is unsupported before 2.11");
2970 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2971 if (!lttng_buffer_view_is_valid(&header_view
)) {
2972 ERR("Failed to receive payload of chunk close command");
2977 /* Convert to host endianness. */
2978 msg
= (typeof(msg
)) header_view
.data
;
2979 chunk_id
= be64toh(msg
->chunk_id
);
2980 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2981 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2982 close_command
.is_set
= msg
->close_command
.is_set
;
2984 chunk
= sessiond_trace_chunk_registry_get_chunk(sessiond_trace_chunk_registry
,
2985 conn
->session
->sessiond_uuid
,
2986 conn
->session
->id_sessiond
.is_set
?
2987 conn
->session
->id_sessiond
.value
:
2991 char uuid_str
[LTTNG_UUID_STR_LEN
];
2993 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2994 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
2995 ", chunk_id = %" PRIu64
,
3000 reply_code
= LTTNG_ERR_NOMEM
;
3004 pthread_mutex_lock(&session
->lock
);
3005 if (close_command
.is_set
&& close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3007 * Clear command. It is a protocol error to ask for a
3008 * clear on a relay which does not allow it. Querying
3009 * the configuration allows figuring out whether
3010 * clearing is allowed before doing the clear.
3012 if (!opt_allow_clear
) {
3014 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3015 goto end_unlock_session
;
3018 if (session
->pending_closure_trace_chunk
&& session
->pending_closure_trace_chunk
!= chunk
) {
3019 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3020 session
->session_name
);
3021 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3023 goto end_unlock_session
;
3026 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3027 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3028 if (close_command
.is_set
&&
3029 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3030 !session
->has_rotated
) {
3031 /* New chunk stays in session output directory. */
3034 /* Use chunk name for new chunk. */
3037 /* Rename new chunk path. */
3039 lttng_trace_chunk_rename_path(session
->current_trace_chunk
, new_path
);
3040 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3042 goto end_unlock_session
;
3044 session
->ongoing_rotation
= false;
3046 if ((!close_command
.is_set
||
3047 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3048 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3049 const char *old_path
;
3051 if (!session
->has_rotated
) {
3056 /* We need to move back the .tmp_old_chunk to its rightful place. */
3057 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3058 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3060 goto end_unlock_session
;
3063 chunk_status
= lttng_trace_chunk_set_close_timestamp(chunk
, close_timestamp
);
3064 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3065 ERR("Failed to set trace chunk close timestamp");
3067 reply_code
= LTTNG_ERR_UNK
;
3068 goto end_unlock_session
;
3071 if (close_command
.is_set
) {
3072 chunk_status
= lttng_trace_chunk_set_close_command(chunk
, close_command
.value
);
3073 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3075 reply_code
= LTTNG_ERR_INVALID
;
3076 goto end_unlock_session
;
3079 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, nullptr);
3080 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3081 ERR("Failed to get chunk name");
3083 reply_code
= LTTNG_ERR_UNK
;
3084 goto end_unlock_session
;
3086 if (!session
->has_rotated
&& !session
->snapshot
) {
3087 ret
= lttng_strncpy(closed_trace_chunk_path
,
3088 session
->output_path
,
3089 sizeof(closed_trace_chunk_path
));
3091 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3092 strlen(session
->output_path
),
3093 sizeof(closed_trace_chunk_path
));
3094 reply_code
= LTTNG_ERR_NOMEM
;
3096 goto end_unlock_session
;
3099 if (session
->snapshot
) {
3100 ret
= snprintf(closed_trace_chunk_path
,
3101 sizeof(closed_trace_chunk_path
),
3103 session
->output_path
,
3106 ret
= snprintf(closed_trace_chunk_path
,
3107 sizeof(closed_trace_chunk_path
),
3108 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
"/%s",
3109 session
->output_path
,
3112 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3113 ERR("Failed to format closed trace chunk resulting path");
3114 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3116 goto end_unlock_session
;
3119 if (close_command
.is_set
&&
3120 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3121 session
->has_rotated
= true;
3123 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3124 path_length
= strlen(closed_trace_chunk_path
) + 1;
3125 if (path_length
> UINT32_MAX
) {
3126 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3128 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3129 goto end_unlock_session
;
3132 if (session
->current_trace_chunk
== chunk
) {
3134 * After a trace chunk close command, no new streams
3135 * referencing the chunk may be created. Hence, on the
3136 * event that no new trace chunk have been created for
3137 * the session, the reference to the current trace chunk
3138 * is released in order to allow it to be reclaimed when
3139 * the last stream releases its reference to it.
3141 lttng_trace_chunk_put(session
->current_trace_chunk
);
3142 session
->current_trace_chunk
= nullptr;
3144 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3145 session
->pending_closure_trace_chunk
= nullptr;
3147 pthread_mutex_unlock(&session
->lock
);
3150 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3151 reply
.path_length
= htobe32((uint32_t) path_length
);
3152 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
, &reply
, sizeof(reply
));
3154 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3158 if (reply_code
== LTTNG_OK
) {
3159 buf_ret
= lttng_dynamic_buffer_append(
3160 &reply_payload
, closed_trace_chunk_path
, path_length
);
3162 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3167 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
, reply_payload
.size
, 0);
3168 if (send_ret
< reply_payload
.size
) {
3169 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3176 lttng_trace_chunk_put(chunk
);
3177 lttng_dynamic_buffer_reset(&reply_payload
);
3182 * relay_trace_chunk_exists: check if a trace chunk exists
3184 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
3185 __attribute__((unused
)),
3186 struct relay_connection
*conn
,
3187 const struct lttng_buffer_view
*payload
)
3191 struct relay_session
*session
= conn
->session
;
3192 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3193 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3194 struct lttng_buffer_view header_view
;
3198 if (!session
|| !conn
->version_check_done
) {
3199 ERR("Trying to check for the presence of a trace chunk before version check");
3204 if (session
->major
== 2 && session
->minor
< 11) {
3205 ERR("Chunk exists command is unsupported before 2.11");
3210 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3211 if (!lttng_buffer_view_is_valid(&header_view
)) {
3212 ERR("Failed to receive payload of chunk exists command");
3217 /* Convert to host endianness. */
3218 msg
= (typeof(msg
)) header_view
.data
;
3219 chunk_id
= be64toh(msg
->chunk_id
);
3221 ret
= sessiond_trace_chunk_registry_chunk_exists(sessiond_trace_chunk_registry
,
3222 conn
->session
->sessiond_uuid
,
3227 * If ret is not 0, send the reply and report the error to the caller.
3228 * It is a protocol (or internal) error and the session/connection
3229 * should be torn down.
3231 reply
.generic
.ret_code
=
3232 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3233 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3235 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3236 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3237 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)", send_ret
);
3245 * relay_get_configuration: query whether feature is available
3247 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
3248 __attribute__((unused
)),
3249 struct relay_connection
*conn
,
3250 const struct lttng_buffer_view
*payload
)
3254 struct lttcomm_relayd_get_configuration
*msg
;
3255 struct lttcomm_relayd_get_configuration_reply reply
= {};
3256 struct lttng_buffer_view header_view
;
3257 uint64_t query_flags
= 0;
3258 uint64_t result_flags
= 0;
3260 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3261 if (!lttng_buffer_view_is_valid(&header_view
)) {
3262 ERR("Failed to receive payload of chunk close command");
3267 /* Convert to host endianness. */
3268 msg
= (typeof(msg
)) header_view
.data
;
3269 query_flags
= be64toh(msg
->query_flags
);
3272 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3275 if (opt_allow_clear
) {
3276 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3280 reply
.generic
.ret_code
=
3281 htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3282 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3284 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
3285 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3286 ERR("Failed to send \"get configuration\" command reply (ret = %zd)", send_ret
);
3293 static int relay_process_control_command(struct relay_connection
*conn
,
3294 const struct lttcomm_relayd_hdr
*header
,
3295 const struct lttng_buffer_view
*payload
)
3299 DBG3("Processing \"%s\" command for socket %i",
3300 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3302 switch (header
->cmd
) {
3303 case RELAYD_CREATE_SESSION
:
3304 ret
= relay_create_session(header
, conn
, payload
);
3306 case RELAYD_ADD_STREAM
:
3307 ret
= relay_add_stream(header
, conn
, payload
);
3309 case RELAYD_START_DATA
:
3310 ret
= relay_start(header
, conn
, payload
);
3312 case RELAYD_SEND_METADATA
:
3313 ret
= relay_recv_metadata(header
, conn
, payload
);
3315 case RELAYD_VERSION
:
3316 ret
= relay_send_version(header
, conn
, payload
);
3318 case RELAYD_CLOSE_STREAM
:
3319 ret
= relay_close_stream(header
, conn
, payload
);
3321 case RELAYD_DATA_PENDING
:
3322 ret
= relay_data_pending(header
, conn
, payload
);
3324 case RELAYD_QUIESCENT_CONTROL
:
3325 ret
= relay_quiescent_control(header
, conn
, payload
);
3327 case RELAYD_BEGIN_DATA_PENDING
:
3328 ret
= relay_begin_data_pending(header
, conn
, payload
);
3330 case RELAYD_END_DATA_PENDING
:
3331 ret
= relay_end_data_pending(header
, conn
, payload
);
3333 case RELAYD_SEND_INDEX
:
3334 ret
= relay_recv_index(header
, conn
, payload
);
3336 case RELAYD_STREAMS_SENT
:
3337 ret
= relay_streams_sent(header
, conn
, payload
);
3339 case RELAYD_RESET_METADATA
:
3340 ret
= relay_reset_metadata(header
, conn
, payload
);
3342 case RELAYD_ROTATE_STREAMS
:
3343 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3345 case RELAYD_CREATE_TRACE_CHUNK
:
3346 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3348 case RELAYD_CLOSE_TRACE_CHUNK
:
3349 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3351 case RELAYD_TRACE_CHUNK_EXISTS
:
3352 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3354 case RELAYD_GET_CONFIGURATION
:
3355 ret
= relay_get_configuration(header
, conn
, payload
);
3357 case RELAYD_UPDATE_SYNC_INFO
:
3359 ERR("Received unknown command (%u)", header
->cmd
);
3360 relay_unknown_command(conn
);
3369 static enum relay_connection_status
3370 relay_process_control_receive_payload(struct relay_connection
*conn
)
3373 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3374 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3375 struct ctrl_connection_state_receive_payload
*state
=
3376 &conn
->protocol
.ctrl
.state
.receive_payload
;
3377 struct lttng_buffer_view payload_view
;
3379 if (state
->left_to_receive
== 0) {
3380 /* Short-circuit for payload-less commands. */
3381 goto reception_complete
;
3384 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3385 reception_buffer
->data
+ state
->received
,
3386 state
->left_to_receive
,
3390 DIAGNOSTIC_IGNORE_LOGICAL_OP
3391 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3393 PERROR("Unable to receive command payload on sock %d", conn
->sock
->fd
);
3394 status
= RELAY_CONNECTION_STATUS_ERROR
;
3397 } else if (ret
== 0) {
3398 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3399 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3403 LTTNG_ASSERT(ret
> 0);
3404 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3406 state
->left_to_receive
-= ret
;
3407 state
->received
+= ret
;
3409 if (state
->left_to_receive
> 0) {
3411 * Can't transition to the protocol's next state, wait to
3412 * receive the rest of the header.
3414 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
3415 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3417 state
->left_to_receive
,
3423 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3427 * The payload required to process the command has been received.
3428 * A view to the reception buffer is forwarded to the various
3429 * commands and the state of the control is reset on success.
3431 * Commands are responsible for sending their reply to the peer.
3433 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
, 0, -1);
3434 ret
= relay_process_control_command(conn
, &state
->header
, &payload_view
);
3436 status
= RELAY_CONNECTION_STATUS_ERROR
;
3440 ret
= connection_reset_protocol_state(conn
);
3442 status
= RELAY_CONNECTION_STATUS_ERROR
;
3448 static enum relay_connection_status
3449 relay_process_control_receive_header(struct relay_connection
*conn
)
3452 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3453 struct lttcomm_relayd_hdr header
;
3454 struct lttng_dynamic_buffer
*reception_buffer
= &conn
->protocol
.ctrl
.reception_buffer
;
3455 struct ctrl_connection_state_receive_header
*state
=
3456 &conn
->protocol
.ctrl
.state
.receive_header
;
3458 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3460 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3461 reception_buffer
->data
+ state
->received
,
3462 state
->left_to_receive
,
3466 DIAGNOSTIC_IGNORE_LOGICAL_OP
3467 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3469 PERROR("Unable to receive control command header on sock %d",
3471 status
= RELAY_CONNECTION_STATUS_ERROR
;
3474 } else if (ret
== 0) {
3475 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3476 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3480 LTTNG_ASSERT(ret
> 0);
3481 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3483 state
->left_to_receive
-= ret
;
3484 state
->received
+= ret
;
3486 if (state
->left_to_receive
> 0) {
3488 * Can't transition to the protocol's next state, wait to
3489 * receive the rest of the header.
3491 DBG3("Partial reception of control connection protocol header (received %" PRIu64
3492 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3494 state
->left_to_receive
,
3499 /* Transition to next state: receiving the command's payload. */
3500 conn
->protocol
.ctrl
.state_id
= CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3501 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3502 header
.circuit_id
= be64toh(header
.circuit_id
);
3503 header
.data_size
= be64toh(header
.data_size
);
3504 header
.cmd
= be32toh(header
.cmd
);
3505 header
.cmd_version
= be32toh(header
.cmd_version
);
3506 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
, &header
, sizeof(header
));
3508 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
3509 ", payload size = %" PRIu64
" bytes",
3511 lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3515 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3516 ERR("Command header indicates a payload (%" PRIu64
3517 " bytes) that exceeds the maximal payload size allowed on a control connection.",
3519 status
= RELAY_CONNECTION_STATUS_ERROR
;
3523 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3524 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3525 ret
= lttng_dynamic_buffer_set_size(reception_buffer
, header
.data_size
);
3527 status
= RELAY_CONNECTION_STATUS_ERROR
;
3531 if (header
.data_size
== 0) {
3533 * Manually invoke the next state as the poll loop
3534 * will not wake-up to allow us to proceed further.
3536 status
= relay_process_control_receive_payload(conn
);
3543 * Process the commands received on the control socket
3545 static enum relay_connection_status
relay_process_control(struct relay_connection
*conn
)
3547 enum relay_connection_status status
;
3549 switch (conn
->protocol
.ctrl
.state_id
) {
3550 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3551 status
= relay_process_control_receive_header(conn
);
3553 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3554 status
= relay_process_control_receive_payload(conn
);
3557 ERR("Unknown control connection protocol state encountered.");
3564 static enum relay_connection_status
relay_process_data_receive_header(struct relay_connection
*conn
)
3567 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3568 struct data_connection_state_receive_header
*state
=
3569 &conn
->protocol
.data
.state
.receive_header
;
3570 struct lttcomm_relayd_data_hdr header
;
3571 struct relay_stream
*stream
;
3573 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3575 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3576 state
->header_reception_buffer
+ state
->received
,
3577 state
->left_to_receive
,
3581 DIAGNOSTIC_IGNORE_LOGICAL_OP
3582 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3584 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3585 status
= RELAY_CONNECTION_STATUS_ERROR
;
3588 } else if (ret
== 0) {
3589 /* Orderly shutdown. Not necessary to print an error. */
3590 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3591 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3595 LTTNG_ASSERT(ret
> 0);
3596 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3598 state
->left_to_receive
-= ret
;
3599 state
->received
+= ret
;
3601 if (state
->left_to_receive
> 0) {
3603 * Can't transition to the protocol's next state, wait to
3604 * receive the rest of the header.
3606 DBG3("Partial reception of data connection header (received %" PRIu64
3607 " bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3609 state
->left_to_receive
,
3614 /* Transition to next state: receiving the payload. */
3615 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3617 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3618 header
.circuit_id
= be64toh(header
.circuit_id
);
3619 header
.stream_id
= be64toh(header
.stream_id
);
3620 header
.data_size
= be32toh(header
.data_size
);
3621 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3622 header
.padding_size
= be32toh(header
.padding_size
);
3623 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3625 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
= header
.data_size
;
3626 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3627 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3629 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
3630 ", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
3631 ", padding_size = %" PRIu32
,
3637 header
.padding_size
);
3639 stream
= stream_get_by_id(header
.stream_id
);
3641 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3643 /* Protocol error. */
3644 status
= RELAY_CONNECTION_STATUS_ERROR
;
3648 pthread_mutex_lock(&stream
->lock
);
3649 /* Prepare stream for the reception of a new packet. */
3650 ret
= stream_init_packet(
3651 stream
, header
.data_size
, &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3652 pthread_mutex_unlock(&stream
->lock
);
3654 ERR("Failed to rotate stream output file");
3655 status
= RELAY_CONNECTION_STATUS_ERROR
;
3656 goto end_stream_unlock
;
3665 static enum relay_connection_status
3666 relay_process_data_receive_payload(struct relay_connection
*conn
)
3669 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3670 struct relay_stream
*stream
;
3671 struct data_connection_state_receive_payload
*state
=
3672 &conn
->protocol
.data
.state
.receive_payload
;
3673 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3674 char data_buffer
[chunk_size
];
3675 bool partial_recv
= false;
3676 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3677 uint64_t left_to_receive
= state
->left_to_receive
;
3678 struct relay_session
*session
;
3680 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
3681 " bytes received, %" PRIu64
" bytes left to receive",
3682 state
->header
.stream_id
,
3683 state
->header
.net_seq_num
,
3687 stream
= stream_get_by_id(state
->header
.stream_id
);
3689 /* Protocol error. */
3690 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3691 state
->header
.stream_id
);
3692 status
= RELAY_CONNECTION_STATUS_ERROR
;
3696 pthread_mutex_lock(&stream
->lock
);
3697 session
= stream
->trace
->session
;
3698 if (!conn
->session
) {
3699 ret
= connection_set_session(conn
, session
);
3701 status
= RELAY_CONNECTION_STATUS_ERROR
;
3702 goto end_stream_unlock
;
3707 * The size of the "chunk" received on any iteration is bounded by:
3708 * - the data left to receive,
3709 * - the data immediately available on the socket,
3710 * - the on-stack data buffer
3712 while (left_to_receive
> 0 && !partial_recv
) {
3713 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3714 struct lttng_buffer_view packet_chunk
;
3716 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, MSG_DONTWAIT
);
3719 DIAGNOSTIC_IGNORE_LOGICAL_OP
3720 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3722 PERROR("Socket %d error", conn
->sock
->fd
);
3723 status
= RELAY_CONNECTION_STATUS_ERROR
;
3725 goto end_stream_unlock
;
3726 } else if (ret
== 0) {
3727 /* No more data ready to be consumed on socket. */
3728 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3729 state
->header
.stream_id
);
3730 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3732 } else if (ret
< (int) recv_size
) {
3734 * All the data available on the socket has been
3737 partial_recv
= true;
3741 packet_chunk
= lttng_buffer_view_init(data_buffer
, 0, recv_size
);
3742 LTTNG_ASSERT(packet_chunk
.data
);
3744 ret
= stream_write(stream
, &packet_chunk
, 0);
3746 ERR("Relay error writing data to file");
3747 status
= RELAY_CONNECTION_STATUS_ERROR
;
3748 goto end_stream_unlock
;
3751 left_to_receive
-= recv_size
;
3752 state
->received
+= recv_size
;
3753 state
->left_to_receive
= left_to_receive
;
3756 if (state
->left_to_receive
> 0) {
3758 * Did not receive all the data expected, wait for more data to
3759 * become available on the socket.
3761 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
3762 " bytes received, %" PRIu64
" bytes left to receive",
3763 state
->header
.stream_id
,
3765 state
->left_to_receive
);
3766 goto end_stream_unlock
;
3769 ret
= stream_write(stream
, nullptr, state
->header
.padding_size
);
3771 status
= RELAY_CONNECTION_STATUS_ERROR
;
3772 goto end_stream_unlock
;
3775 if (session_streams_have_index(session
)) {
3776 ret
= stream_update_index(stream
,
3777 state
->header
.net_seq_num
,
3778 state
->rotate_index
,
3780 state
->header
.data_size
+ state
->header
.padding_size
);
3782 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
3784 stream
->stream_handle
,
3785 state
->header
.net_seq_num
,
3787 status
= RELAY_CONNECTION_STATUS_ERROR
;
3788 goto end_stream_unlock
;
3792 if (stream
->prev_data_seq
== -1ULL) {
3796 ret
= stream_complete_packet(stream
,
3797 state
->header
.data_size
+ state
->header
.padding_size
,
3798 state
->header
.net_seq_num
,
3801 status
= RELAY_CONNECTION_STATUS_ERROR
;
3802 goto end_stream_unlock
;
3806 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3807 * contents of *state which are aliased (union) to the same location as
3808 * the new state. Don't use it beyond this point.
3810 connection_reset_protocol_state(conn
);
3814 close_requested
= stream
->close_requested
;
3815 pthread_mutex_unlock(&stream
->lock
);
3816 if (close_requested
&& left_to_receive
== 0) {
3817 try_stream_close(stream
);
3821 pthread_mutex_lock(&session
->lock
);
3822 uatomic_set(&session
->new_streams
, 1);
3823 pthread_mutex_unlock(&session
->lock
);
3832 * relay_process_data: Process the data received on the data socket
3834 static enum relay_connection_status
relay_process_data(struct relay_connection
*conn
)
3836 enum relay_connection_status status
;
3838 switch (conn
->protocol
.data
.state_id
) {
3839 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3840 status
= relay_process_data_receive_header(conn
);
3842 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3843 status
= relay_process_data_receive_payload(conn
);
3846 ERR("Unexpected data connection communication state.");
3853 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3857 (void) lttng_poll_del(events
, pollfd
);
3859 ret
= fd_tracker_close_unsuspendable_fd(
3860 the_fd_tracker
, &pollfd
, 1, fd_tracker_util_close_fd
, nullptr);
3862 ERR("Closing pollfd %d", pollfd
);
3866 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3868 struct relay_connection
*conn
)
3870 const char *type_str
;
3872 switch (conn
->type
) {
3877 type_str
= "Control";
3879 case RELAY_VIEWER_COMMAND
:
3880 type_str
= "Viewer Command";
3882 case RELAY_VIEWER_NOTIFICATION
:
3883 type_str
= "Viewer Notification";
3886 type_str
= "Unknown";
3888 cleanup_connection_pollfd(events
, pollfd
);
3889 connection_put(conn
);
3890 DBG("%s connection closed with %d", type_str
, pollfd
);
3894 * This thread does the actual work
3896 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3898 int ret
, err
= -1, last_seen_data_fd
= -1;
3900 struct lttng_poll_event events
;
3901 struct lttng_ht
*relay_connections_ht
;
3902 struct lttng_ht_iter iter
;
3903 struct relay_connection
*destroy_conn
= nullptr;
3905 DBG("[thread] Relay worker started");
3907 rcu_register_thread();
3909 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3911 if (testpoint(relayd_thread_worker
)) {
3912 goto error_testpoint
;
3915 health_code_update();
3917 /* table of connections indexed on socket */
3918 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3919 if (!relay_connections_ht
) {
3920 goto relay_connections_ht_error
;
3923 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3925 goto error_poll_create
;
3928 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3935 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3937 health_code_update();
3939 /* Infinite blocking call, waiting for transmission */
3940 DBG3("Relayd worker thread polling...");
3941 health_poll_entry();
3942 ret
= lttng_poll_wait(&events
, -1);
3946 * Restart interrupted system call.
3948 if (errno
== EINTR
) {
3957 * Process control. The control connection is
3958 * prioritized so we don't starve it with high
3959 * throughput tracing data on the data connection.
3961 for (i
= 0; i
< nb_fd
; i
++) {
3962 /* Fetch once the poll data */
3963 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
3964 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3966 health_code_update();
3968 /* Activity on thread quit pipe, exiting. */
3969 if (relayd_is_thread_quit_pipe(pollfd
)) {
3970 DBG("Activity on thread quit pipe");
3975 /* Inspect the relay conn pipe for new connection */
3976 if (pollfd
== relay_conn_pipe
[0]) {
3977 if (revents
& LPOLLIN
) {
3978 struct relay_connection
*conn
;
3980 ret
= lttng_read(relay_conn_pipe
[0],
3982 sizeof(conn
)); /* NOLINT sizeof used on a
3987 ret
= lttng_poll_add(
3988 &events
, conn
->sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
3990 ERR("Failed to add new connection file descriptor to poll set");
3993 connection_ht_add(relay_connections_ht
, conn
);
3994 DBG("Connection socket %d added", conn
->sock
->fd
);
3995 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3996 ERR("Relay connection pipe error");
3999 ERR("Unexpected poll events %u for sock %d",
4005 struct relay_connection
*ctrl_conn
;
4007 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4008 /* If not found, there is a synchronization issue. */
4009 LTTNG_ASSERT(ctrl_conn
);
4011 if (ctrl_conn
->type
== RELAY_DATA
) {
4012 if (revents
& LPOLLIN
) {
4014 * Flag the last seen data fd not deleted. It will
4015 * be used as the last seen fd if any fd gets
4016 * deleted in this first loop.
4018 last_notdel_data_fd
= pollfd
;
4020 goto put_ctrl_connection
;
4022 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
4024 if (revents
& LPOLLIN
) {
4025 enum relay_connection_status status
;
4027 status
= relay_process_control(ctrl_conn
);
4028 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4030 * On socket error flag the session as aborted to
4031 * force the cleanup of its stream otherwise it can
4032 * leak during the lifetime of the relayd.
4034 * This prevents situations in which streams can be
4035 * left opened because an index was received, the
4036 * control connection is closed, and the data
4037 * connection is closed (uncleanly) before the
4038 * packet's data provided.
4040 * Since the control connection encountered an
4041 * error, it is okay to be conservative and close
4042 * the session right now as we can't rely on the
4043 * protocol being respected anymore.
4045 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4046 session_abort(ctrl_conn
->session
);
4049 /* Clear the connection on error or close. */
4050 relay_thread_close_connection(
4051 &events
, pollfd
, ctrl_conn
);
4054 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4055 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
4056 if (last_seen_data_fd
== pollfd
) {
4057 last_seen_data_fd
= last_notdel_data_fd
;
4060 ERR("Unexpected poll events %u for control sock %d",
4063 connection_put(ctrl_conn
);
4066 put_ctrl_connection
:
4067 connection_put(ctrl_conn
);
4072 * The last loop handled a control request, go back to poll to make
4073 * sure we prioritise the control socket.
4079 if (last_seen_data_fd
>= 0) {
4080 for (i
= 0; i
< nb_fd
; i
++) {
4081 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4083 health_code_update();
4085 if (last_seen_data_fd
== pollfd
) {
4092 /* Process data connection. */
4093 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4094 /* Fetch the poll data. */
4095 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4096 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4097 struct relay_connection
*data_conn
;
4099 health_code_update();
4102 /* No activity for this FD (poll implementation). */
4106 /* Skip the command pipe. It's handled in the first loop. */
4107 if (pollfd
== relay_conn_pipe
[0]) {
4111 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4113 /* Skip it. Might be removed before. */
4116 if (data_conn
->type
== RELAY_CONTROL
) {
4117 goto put_data_connection
;
4119 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4121 if (revents
& LPOLLIN
) {
4122 enum relay_connection_status status
;
4124 status
= relay_process_data(data_conn
);
4125 /* Connection closed or error. */
4126 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4128 * On socket error flag the session as aborted to force
4129 * the cleanup of its stream otherwise it can leak
4130 * during the lifetime of the relayd.
4132 * This prevents situations in which streams can be
4133 * left opened because an index was received, the
4134 * control connection is closed, and the data
4135 * connection is closed (uncleanly) before the packet's
4138 * Since the data connection encountered an error,
4139 * it is okay to be conservative and close the
4140 * session right now as we can't rely on the protocol
4141 * being respected anymore.
4143 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4144 session_abort(data_conn
->session
);
4146 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4148 * Every goto restart call sets the last seen fd where
4149 * here we don't really care since we gracefully
4150 * continue the loop after the connection is deleted.
4153 /* Keep last seen port. */
4154 last_seen_data_fd
= pollfd
;
4155 connection_put(data_conn
);
4158 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4159 relay_thread_close_connection(&events
, pollfd
, data_conn
);
4161 ERR("Unknown poll events %u for data sock %d", revents
, pollfd
);
4163 put_data_connection
:
4164 connection_put(data_conn
);
4166 last_seen_data_fd
= -1;
4169 /* Normal exit, no error */
4174 /* Cleanup remaining connection object. */
4176 lttng::urcu::read_lock_guard read_lock
;
4178 cds_lfht_for_each_entry (
4179 relay_connections_ht
->ht
, &iter
.iter
, destroy_conn
, sock_n
.node
) {
4180 health_code_update();
4182 session_abort(destroy_conn
->session
);
4185 * No need to grab another ref, because we own
4188 relay_thread_close_connection(
4189 &events
, destroy_conn
->sock
->fd
, destroy_conn
);
4193 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4195 lttng_ht_destroy(relay_connections_ht
);
4196 relay_connections_ht_error
:
4197 /* Close relay conn pipes */
4198 (void) fd_tracker_util_pipe_close(the_fd_tracker
, relay_conn_pipe
);
4200 DBG("Thread exited with error");
4202 DBG("Worker thread cleanup complete");
4206 ERR("Health error occurred in %s", __func__
);
4208 health_unregister(health_relayd
);
4209 rcu_unregister_thread();
4210 lttng_relay_stop_threads();
4215 * Create the relay command pipe to wake thread_manage_apps.
4216 * Closed in cleanup().
4218 static int create_relay_conn_pipe()
4220 return fd_tracker_util_pipe_open_cloexec(
4221 the_fd_tracker
, "Relayd connection pipe", relay_conn_pipe
);
4224 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4226 fds
[0] = fileno(stdout
);
4227 fds
[1] = fileno(stderr
);
4231 static int track_stdio()
4234 const char *names
[] = { "stdout", "stderr" };
4236 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
, names
, 2, stdio_open
, nullptr);
4242 int main(int argc
, char **argv
)
4244 bool thread_is_rcu_registered
= false;
4245 int ret
= 0, retval
= 0;
4247 char *unlinked_file_directory_path
= nullptr, *output_path
= nullptr;
4249 /* Parse environment variables */
4250 ret
= parse_env_options();
4258 * Command line arguments overwrite environment.
4261 if (set_options(argc
, argv
)) {
4266 if (set_signal_handler()) {
4271 relayd_config_log();
4273 if (opt_print_version
) {
4279 ret
= fclose(stdin
);
4281 PERROR("Failed to close stdin");
4285 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4287 /* Try to create directory if -o, --output is specified. */
4288 if (opt_output_path
) {
4289 if (*opt_output_path
!= '/') {
4290 ERR("Please specify an absolute path for -o, --output PATH");
4295 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
, -1, -1);
4297 ERR("Unable to create %s", opt_output_path
);
4304 if (opt_daemon
|| opt_background
) {
4305 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
, !opt_background
);
4312 if (opt_working_directory
) {
4313 ret
= utils_change_working_directory(opt_working_directory
);
4315 /* All errors are already logged. */
4320 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4321 if (!sessiond_trace_chunk_registry
) {
4322 ERR("Failed to initialize session daemon trace chunk registry");
4328 * The RCU thread registration (and use, through the fd-tracker's
4329 * creation) is done after the daemonization to allow us to not
4330 * deal with liburcu's fork() management as the call RCU needs to
4333 rcu_register_thread();
4334 thread_is_rcu_registered
= true;
4336 output_path
= create_output_path("");
4338 ERR("Failed to get output path");
4342 ret
= asprintf(&unlinked_file_directory_path
,
4345 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4348 ERR("Failed to format unlinked file directory path");
4352 the_fd_tracker
= fd_tracker_create(unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4353 free(unlinked_file_directory_path
);
4354 if (!the_fd_tracker
) {
4359 ret
= track_stdio();
4365 /* Initialize thread health monitoring */
4366 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4367 if (!health_relayd
) {
4368 PERROR("health_app_create error");
4373 /* Create thread quit pipe */
4374 if (relayd_init_thread_quit_pipe()) {
4379 /* Setup the thread apps communication pipe. */
4380 if (create_relay_conn_pipe()) {
4385 /* Init relay command queue. */
4386 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4388 /* Initialize communication library */
4390 lttcomm_inet_init();
4392 /* tables of sessions indexed by session ID */
4393 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4399 /* tables of streams indexed by stream ID */
4400 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4401 if (!relay_streams_ht
) {
4406 /* tables of streams indexed by stream ID */
4407 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4408 if (!viewer_streams_ht
) {
4413 ret
= init_health_quit_pipe();
4419 /* Create thread to manage the client socket */
4420 ret
= pthread_create(&health_thread
,
4421 default_pthread_attr(),
4422 thread_manage_health_relayd
,
4426 PERROR("pthread_create health");
4431 /* Setup the dispatcher thread */
4432 ret
= pthread_create(&dispatcher_thread
,
4433 default_pthread_attr(),
4434 relay_thread_dispatcher
,
4438 PERROR("pthread_create dispatcher");
4440 goto exit_dispatcher_thread
;
4443 /* Setup the worker thread */
4444 ret
= pthread_create(&worker_thread
, default_pthread_attr(), relay_thread_worker
, nullptr);
4447 PERROR("pthread_create worker");
4449 goto exit_worker_thread
;
4452 /* Setup the listener thread */
4453 ret
= pthread_create(
4454 &listener_thread
, default_pthread_attr(), relay_thread_listener
, (void *) nullptr);
4457 PERROR("pthread_create listener");
4459 goto exit_listener_thread
;
4462 ret
= relayd_live_create(live_uri
);
4464 ERR("Starting live viewer threads");
4470 * This is where we start awaiting program completion (e.g. through
4471 * signal that asks threads to teardown).
4474 ret
= relayd_live_join();
4480 ret
= pthread_join(listener_thread
, &status
);
4483 PERROR("pthread_join listener_thread");
4487 exit_listener_thread
:
4488 ret
= pthread_join(worker_thread
, &status
);
4491 PERROR("pthread_join worker_thread");
4496 ret
= pthread_join(dispatcher_thread
, &status
);
4499 PERROR("pthread_join dispatcher_thread");
4502 exit_dispatcher_thread
:
4504 ret
= pthread_join(health_thread
, &status
);
4507 PERROR("pthread_join health_thread");
4512 * Wait for all pending call_rcu work to complete before tearing
4513 * down data structures. call_rcu worker may be trying to
4514 * perform lookups in those structures.
4519 /* Ensure all prior call_rcu are done. */
4522 if (thread_is_rcu_registered
) {
4523 rcu_unregister_thread();