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
21 #include <sys/mount.h>
22 #include <sys/resource.h>
23 #include <sys/socket.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
29 #include <urcu/futex.h>
30 #include <urcu/uatomic.h>
31 #include <urcu/rculist.h>
38 #include <lttng/lttng.h>
39 #include <common/common.hpp>
40 #include <common/compat/poll.hpp>
41 #include <common/compat/socket.hpp>
42 #include <common/compat/endian.hpp>
43 #include <common/compat/getenv.hpp>
44 #include <common/defaults.hpp>
45 #include <common/daemonize.hpp>
46 #include <common/futex.hpp>
47 #include <common/sessiond-comm/sessiond-comm.hpp>
48 #include <common/sessiond-comm/inet.hpp>
49 #include <common/sessiond-comm/relayd.hpp>
50 #include <common/uri.hpp>
51 #include <common/utils.hpp>
52 #include <common/path.hpp>
53 #include <common/align.hpp>
54 #include <common/ini-config/ini-config.hpp>
55 #include <common/dynamic-buffer.hpp>
56 #include <common/buffer-view.hpp>
57 #include <common/string-utils/format.hpp>
58 #include <common/fd-tracker/fd-tracker.hpp>
59 #include <common/fd-tracker/utils.hpp>
61 #include "backward-compatibility-group-by.hpp"
63 #include "connection.hpp"
64 #include "ctf-trace.hpp"
65 #include "health-relayd.hpp"
68 #include "lttng-relayd.hpp"
69 #include "session.hpp"
70 #include "sessiond-trace-chunks.hpp"
72 #include "tcp_keep_alive.hpp"
73 #include "testpoint.hpp"
74 #include "tracefile-array.hpp"
76 #include "version.hpp"
77 #include "viewer-stream.hpp"
79 static const char *help_msg
=
80 #ifdef LTTNG_EMBED_HELP
81 #include <lttng-relayd.8.h>
87 enum relay_connection_status
{
88 RELAY_CONNECTION_STATUS_OK
,
89 /* An error occurred while processing an event on the connection. */
90 RELAY_CONNECTION_STATUS_ERROR
,
91 /* Connection closed/shutdown cleanly. */
92 RELAY_CONNECTION_STATUS_CLOSED
,
95 /* command line options */
96 char *opt_output_path
, *opt_working_directory
;
97 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
98 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
100 /* Argument variables */
101 int lttng_opt_quiet
; /* not static in error.h */
102 int lttng_opt_verbose
; /* not static in error.h */
103 int lttng_opt_mi
; /* not static in error.h */
106 * We need to wait for listener and live listener threads, as well as
107 * health check thread, before being ready to signal readiness.
109 #define NR_LTTNG_RELAY_READY 3
110 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
112 /* Size of receive buffer. */
113 #define RECV_DATA_BUFFER_SIZE 65536
115 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
116 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
118 static struct lttng_uri
*control_uri
;
119 static struct lttng_uri
*data_uri
;
120 static struct lttng_uri
*live_uri
;
122 const char *progname
;
124 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
125 static int tracing_group_name_override
;
127 const char * const config_section_name
= "relayd";
130 * This pipe is used to inform the worker thread that a command is queued and
131 * ready to be processed.
133 static int relay_conn_pipe
[2] = { -1, -1 };
135 /* Shared between threads */
136 static int dispatch_thread_exit
;
138 static pthread_t listener_thread
;
139 static pthread_t dispatcher_thread
;
140 static pthread_t worker_thread
;
141 static pthread_t health_thread
;
144 * last_relay_stream_id_lock protects last_relay_stream_id increment
145 * atomicity on 32-bit architectures.
147 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
148 static uint64_t last_relay_stream_id
;
151 * Relay command queue.
153 * The relay_thread_listener and relay_thread_dispatcher communicate with this
156 static struct relay_conn_queue relay_conn_queue
;
158 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
159 static unsigned int lttng_opt_fd_pool_size
= -1;
161 /* Global relay stream hash table. */
162 struct lttng_ht
*relay_streams_ht
;
164 /* Global relay viewer stream hash table. */
165 struct lttng_ht
*viewer_streams_ht
;
167 /* Global relay sessions hash table. */
168 struct lttng_ht
*sessions_ht
;
170 /* Relayd health monitoring */
171 struct health_app
*health_relayd
;
173 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
175 /* Global fd tracker. */
176 struct fd_tracker
*the_fd_tracker
;
178 static struct option long_options
[] = {
179 { "control-port", 1, 0, 'C', },
180 { "data-port", 1, 0, 'D', },
181 { "live-port", 1, 0, 'L', },
182 { "daemonize", 0, 0, 'd', },
183 { "background", 0, 0, 'b', },
184 { "group", 1, 0, 'g', },
185 { "fd-pool-size", 1, 0, '\0', },
186 { "help", 0, 0, 'h', },
187 { "output", 1, 0, 'o', },
188 { "verbose", 0, 0, 'v', },
189 { "config", 1, 0, 'f' },
190 { "version", 0, 0, 'V' },
191 { "working-directory", 1, 0, 'w', },
192 { "group-output-by-session", 0, 0, 's', },
193 { "group-output-by-host", 0, 0, 'p', },
194 { "disallow-clear", 0, 0, 'x' },
198 static const char *config_ignore_options
[] = { "help", "config", "version" };
200 static void print_version(void) {
201 fprintf(stdout
, "%s\n", VERSION
);
204 static void relayd_config_log(void)
206 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
207 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
208 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
209 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
210 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
212 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
213 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
218 * Take an option from the getopt output and set it in the right variable to be
221 * Return 0 on success else a negative value.
223 static int set_option(int opt
, const char *arg
, const char *optname
)
229 if (!strcmp(optname
, "fd-pool-size")) {
233 v
= strtoul(arg
, NULL
, 0);
234 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
235 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
240 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
244 lttng_opt_fd_pool_size
= (unsigned int) v
;
246 fprintf(stderr
, "unknown option %s", optname
);
248 fprintf(stderr
, " with arg %s\n", arg
);
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
255 "-C, --control-port");
257 ret
= uri_parse(arg
, &control_uri
);
259 ERR("Invalid control URI specified");
262 if (control_uri
->port
== 0) {
263 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
268 if (lttng_is_setuid_setgid()) {
269 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
272 ret
= uri_parse(arg
, &data_uri
);
274 ERR("Invalid data URI specified");
277 if (data_uri
->port
== 0) {
278 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
283 if (lttng_is_setuid_setgid()) {
284 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
287 ret
= uri_parse(arg
, &live_uri
);
289 ERR("Invalid live URI specified");
292 if (live_uri
->port
== 0) {
293 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
304 if (lttng_is_setuid_setgid()) {
305 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
308 tracing_group_name
= strdup(arg
);
309 if (tracing_group_name
== NULL
) {
314 tracing_group_name_override
= 1;
318 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
320 ERR("Cannot show --help for `lttng-relayd`");
325 opt_print_version
= 1;
328 if (lttng_is_setuid_setgid()) {
329 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
332 ret
= asprintf(&opt_output_path
, "%s", arg
);
335 PERROR("asprintf opt_output_path");
341 if (lttng_is_setuid_setgid()) {
342 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
343 "-w, --working-directory");
345 ret
= asprintf(&opt_working_directory
, "%s", arg
);
348 PERROR("asprintf opt_working_directory");
355 /* Verbose level can increase using multiple -v */
357 lttng_opt_verbose
= config_parse_value(arg
);
359 /* Only 3 level of verbosity (-vvv). */
360 if (lttng_opt_verbose
< 3) {
361 lttng_opt_verbose
+= 1;
366 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
367 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
370 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
373 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
374 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
377 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
384 /* Unknown option or other error.
385 * Error is printed by getopt, just return */
398 * config_entry_handler_cb used to handle options read from a config file.
399 * See config_entry_handler_cb comment in common/config/session-config.h for the
400 * return value conventions.
402 static int config_entry_handler(const struct config_entry
*entry
,
403 void *unused
__attribute__((unused
)))
407 if (!entry
|| !entry
->name
|| !entry
->value
) {
412 /* Check if the option is to be ignored */
413 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
414 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
419 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
420 /* Ignore if entry name is not fully matched. */
421 if (strcmp(entry
->name
, long_options
[i
].name
)) {
426 * If the option takes no argument on the command line,
427 * we have to check if the value is "true". We support
428 * non-zero numeric values, true, on and yes.
430 if (!long_options
[i
].has_arg
) {
431 ret
= config_parse_value(entry
->value
);
434 WARN("Invalid configuration value \"%s\" for option %s",
435 entry
->value
, entry
->name
);
437 /* False, skip boolean config option. */
442 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
446 WARN("Unrecognized option \"%s\" in daemon configuration file.",
453 static int parse_env_options(void)
458 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
460 opt_working_directory
= strdup(value
);
461 if (!opt_working_directory
) {
462 ERR("Failed to allocate working directory string (\"%s\")",
470 static int set_fd_pool_size(void)
473 struct rlimit rlimit
;
475 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
477 PERROR("Failed to get file descriptor limit");
482 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
483 (uint64_t) rlimit
.rlim_cur
,
484 (uint64_t) rlimit
.rlim_max
);
485 if (lttng_opt_fd_pool_size
== -1) {
486 /* Use default value (soft limit - reserve). */
487 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
488 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
489 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
493 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
494 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
498 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
499 ERR("File descriptor pool size must be set to at least %d",
500 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
505 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
506 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
507 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
512 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
513 lttng_opt_fd_pool_size
,
514 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
515 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
520 static int set_options(int argc
, char **argv
)
522 int c
, ret
= 0, option_index
= 0, retval
= 0;
523 int orig_optopt
= optopt
, orig_optind
= optind
;
524 char *default_address
, *optstring
;
525 char *config_path
= NULL
;
527 optstring
= utils_generate_optstring(long_options
,
528 sizeof(long_options
) / sizeof(struct option
));
534 /* Check for the --config option */
536 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
537 &option_index
)) != -1) {
541 } else if (c
!= 'f') {
545 if (lttng_is_setuid_setgid()) {
546 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
550 config_path
= utils_expand_path(optarg
);
552 ERR("Failed to resolve path: %s", optarg
);
557 ret
= config_get_section_entries(config_path
, config_section_name
,
558 config_entry_handler
, NULL
);
561 ERR("Invalid configuration option at line %i", ret
);
567 /* Reset getopt's global state */
568 optopt
= orig_optopt
;
569 optind
= orig_optind
;
571 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
576 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
583 /* assign default values */
584 if (control_uri
== NULL
) {
585 ret
= asprintf(&default_address
,
586 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
587 DEFAULT_NETWORK_CONTROL_PORT
);
589 PERROR("asprintf default data address");
594 ret
= uri_parse(default_address
, &control_uri
);
595 free(default_address
);
597 ERR("Invalid control URI specified");
602 if (data_uri
== NULL
) {
603 ret
= asprintf(&default_address
,
604 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
605 DEFAULT_NETWORK_DATA_PORT
);
607 PERROR("asprintf default data address");
612 ret
= uri_parse(default_address
, &data_uri
);
613 free(default_address
);
615 ERR("Invalid data URI specified");
620 if (live_uri
== NULL
) {
621 ret
= asprintf(&default_address
,
622 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
623 DEFAULT_NETWORK_VIEWER_PORT
);
625 PERROR("asprintf default viewer control address");
630 ret
= uri_parse(default_address
, &live_uri
);
631 free(default_address
);
633 ERR("Invalid viewer control URI specified");
638 ret
= set_fd_pool_size();
644 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
645 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
647 if (opt_allow_clear
) {
648 /* Check if env variable exists. */
649 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
651 ret
= config_parse_value(value
);
653 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
657 opt_allow_clear
= !ret
;
667 static void print_global_objects(void)
669 print_viewer_streams();
670 print_relay_streams();
674 static int noop_close(void *data
__attribute__((unused
)),
675 int *fds
__attribute__((unused
)))
680 static void untrack_stdio(void)
682 int fds
[] = { fileno(stdout
), fileno(stderr
) };
685 * noop_close is used since we don't really want to close
686 * the stdio output fds; we merely want to stop tracking them.
688 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
689 fds
, 2, noop_close
, NULL
);
695 static void relayd_cleanup(void)
697 print_global_objects();
701 if (viewer_streams_ht
)
702 lttng_ht_destroy(viewer_streams_ht
);
703 if (relay_streams_ht
)
704 lttng_ht_destroy(relay_streams_ht
);
706 lttng_ht_destroy(sessions_ht
);
708 free(opt_output_path
);
709 free(opt_working_directory
);
712 health_app_destroy(health_relayd
);
714 /* Close thread quit pipes */
715 if (health_quit_pipe
[0] != -1) {
716 (void) fd_tracker_util_pipe_close(
717 the_fd_tracker
, health_quit_pipe
);
719 relayd_close_thread_quit_pipe();
720 if (sessiond_trace_chunk_registry
) {
721 sessiond_trace_chunk_registry_destroy(
722 sessiond_trace_chunk_registry
);
724 if (the_fd_tracker
) {
727 * fd_tracker_destroy() will log the contents of the fd-tracker
728 * if a leak is detected.
730 fd_tracker_destroy(the_fd_tracker
);
733 uri_free(control_uri
);
735 /* Live URI is freed in the live thread. */
737 if (tracing_group_name_override
) {
738 free((void *) tracing_group_name
);
742 static int notify_health_quit_pipe(int *pipe
)
746 ret
= lttng_write(pipe
[1], "4", 1);
748 PERROR("write relay health quit");
757 * Stop all relayd and relayd-live threads.
759 int lttng_relay_stop_threads(void)
763 /* Stopping all threads */
764 DBG("Terminating all threads");
765 if (relayd_notify_thread_quit_pipe()) {
766 ERR("write error on thread quit pipe");
770 if (notify_health_quit_pipe(health_quit_pipe
)) {
771 ERR("write error on health quit pipe");
774 /* Dispatch thread */
775 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
776 futex_nto1_wake(&relay_conn_queue
.futex
);
778 if (relayd_live_stop()) {
779 ERR("Error stopping live threads");
786 * Signal handler for the daemon
788 * Simply stop all worker threads, leaving main() return gracefully after
789 * joining all threads and calling cleanup().
791 static void sighandler(int sig
)
795 DBG("SIGINT caught");
796 if (lttng_relay_stop_threads()) {
797 ERR("Error stopping threads");
801 DBG("SIGTERM caught");
802 if (lttng_relay_stop_threads()) {
803 ERR("Error stopping threads");
807 CMM_STORE_SHARED(recv_child_signal
, 1);
815 * Setup signal handler for :
816 * SIGINT, SIGTERM, SIGPIPE
818 static int set_signal_handler(void)
824 if ((ret
= sigemptyset(&sigset
)) < 0) {
825 PERROR("sigemptyset");
832 sa
.sa_handler
= sighandler
;
833 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
838 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
843 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
848 sa
.sa_handler
= SIG_IGN
;
849 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
854 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
859 void lttng_relay_notify_ready(void)
861 /* Notify the parent of the fork() process that we are ready. */
862 if (opt_daemon
|| opt_background
) {
863 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
864 kill(child_ppid
, SIGUSR1
);
870 * Init health quit pipe.
872 * Return -1 on error or 0 if all pipes are created.
874 static int init_health_quit_pipe(void)
876 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
877 "Health quit pipe", health_quit_pipe
);
880 static int create_sock(void *data
, int *out_fd
)
883 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
885 ret
= lttcomm_create_sock(sock
);
895 static int close_sock(void *data
, int *in_fd
__attribute__((unused
)))
897 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
899 return sock
->ops
->close(sock
);
902 static int accept_sock(void *data
, int *out_fd
)
905 /* Socks is an array of in_sock, out_sock. */
906 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
907 struct lttcomm_sock
*in_sock
= socks
[0];
909 socks
[1] = in_sock
->ops
->accept(in_sock
);
914 *out_fd
= socks
[1]->fd
;
920 * Create and init socket from uri.
922 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
926 struct lttcomm_sock
*sock
= NULL
;
927 char uri_str
[PATH_MAX
];
928 char *formated_name
= NULL
;
930 sock
= lttcomm_alloc_sock_from_uri(uri
);
932 ERR("Allocating socket");
937 * Don't fail to create the socket if the name can't be built as it is
938 * only used for debugging purposes.
940 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
941 uri_str
[sizeof(uri_str
) - 1] = '\0';
943 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
946 formated_name
= NULL
;
950 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
951 (const char **) (formated_name
? &formated_name
: NULL
),
952 1, create_sock
, sock
);
954 PERROR("Failed to open \"%s\" relay socket",
955 formated_name
?: "Unknown");
958 DBG("Listening on %s socket %d", name
, sock
->fd
);
960 ret
= sock
->ops
->bind(sock
);
962 PERROR("Failed to bind socket");
966 ret
= sock
->ops
->listen(sock
, -1);
977 lttcomm_destroy_sock(sock
);
984 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
988 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
989 struct lttcomm_sock
*new_sock
= NULL
;
991 ret
= fd_tracker_open_unsuspendable_fd(
992 the_fd_tracker
, &out_fd
,
993 (const char **) &name
,
994 1, accept_sock
, &socks
);
999 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1005 * This thread manages the listening for new connections on the network
1007 static void *relay_thread_listener(void *data
__attribute__((unused
)))
1009 int i
, ret
, err
= -1;
1011 struct lttng_poll_event events
;
1012 struct lttcomm_sock
*control_sock
, *data_sock
;
1014 DBG("[thread] Relay listener started");
1016 rcu_register_thread();
1017 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1019 health_code_update();
1021 control_sock
= relay_socket_create(control_uri
, "Control listener");
1022 if (!control_sock
) {
1023 goto error_sock_control
;
1026 data_sock
= relay_socket_create(data_uri
, "Data listener");
1028 goto error_sock_relay
;
1032 * Pass 3 as size here for the thread quit pipe, control and
1035 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1037 goto error_create_poll
;
1040 /* Add the control socket */
1041 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1043 goto error_poll_add
;
1046 /* Add the data socket */
1047 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1049 goto error_poll_add
;
1052 lttng_relay_notify_ready();
1054 if (testpoint(relayd_thread_listener
)) {
1055 goto error_testpoint
;
1059 health_code_update();
1061 DBG("Listener accepting connections");
1064 health_poll_entry();
1065 ret
= lttng_poll_wait(&events
, -1);
1069 * Restart interrupted system call.
1071 if (errno
== EINTR
) {
1079 DBG("Relay new connection received");
1080 for (i
= 0; i
< nb_fd
; i
++) {
1081 /* Fetch once the poll data */
1082 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
1083 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1085 health_code_update();
1087 /* Activity on thread quit pipe, exiting. */
1088 if (relayd_is_thread_quit_pipe(pollfd
)) {
1089 DBG("Activity on thread quit pipe");
1094 if (revents
& LPOLLIN
) {
1096 * A new connection is requested, therefore a
1097 * sessiond/consumerd connection is allocated in
1098 * this thread, enqueued to a global queue and
1099 * dequeued (and freed) in the worker thread.
1102 struct relay_connection
*new_conn
;
1103 struct lttcomm_sock
*newsock
= NULL
;
1104 enum connection_type type
;
1106 if (pollfd
== data_sock
->fd
) {
1108 newsock
= accept_relayd_sock(data_sock
,
1109 "Data socket to relayd");
1111 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1112 type
= RELAY_CONTROL
;
1113 newsock
= accept_relayd_sock(control_sock
,
1114 "Control socket to relayd");
1117 PERROR("accepting sock");
1121 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1124 PERROR("setsockopt inet");
1125 lttcomm_destroy_sock(newsock
);
1129 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1131 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1133 lttcomm_destroy_sock(newsock
);
1137 new_conn
= connection_create(newsock
, type
);
1139 lttcomm_destroy_sock(newsock
);
1143 /* Enqueue request for the dispatcher thread. */
1144 cds_wfcq_head_ptr_t head
;
1145 head
.h
= &relay_conn_queue
.head
;
1146 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
,
1150 * Wake the dispatch queue futex.
1151 * Implicit memory barrier with the
1152 * exchange in cds_wfcq_enqueue.
1154 futex_nto1_wake(&relay_conn_queue
.futex
);
1155 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1156 ERR("socket poll error");
1159 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1169 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1171 if (data_sock
->fd
>= 0) {
1172 int data_sock_fd
= data_sock
->fd
;
1174 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1175 &data_sock_fd
, 1, close_sock
,
1178 PERROR("Failed to close the data listener socket file descriptor");
1182 lttcomm_destroy_sock(data_sock
);
1184 if (control_sock
->fd
>= 0) {
1185 int control_sock_fd
= control_sock
->fd
;
1187 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1188 &control_sock_fd
, 1, close_sock
,
1191 PERROR("Failed to close the control listener socket file descriptor");
1193 control_sock
->fd
= -1;
1195 lttcomm_destroy_sock(control_sock
);
1199 ERR("Health error occurred in %s", __func__
);
1201 health_unregister(health_relayd
);
1202 rcu_unregister_thread();
1203 DBG("Relay listener thread cleanup complete");
1204 lttng_relay_stop_threads();
1209 * This thread manages the dispatching of the requests to worker threads
1211 static void *relay_thread_dispatcher(void *data
__attribute__((unused
)))
1215 struct cds_wfcq_node
*node
;
1216 struct relay_connection
*new_conn
= NULL
;
1218 DBG("[thread] Relay dispatcher started");
1220 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1222 if (testpoint(relayd_thread_dispatcher
)) {
1223 goto error_testpoint
;
1226 health_code_update();
1229 health_code_update();
1231 /* Atomically prepare the queue futex */
1232 futex_nto1_prepare(&relay_conn_queue
.futex
);
1234 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1239 health_code_update();
1241 /* Dequeue commands */
1242 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1243 &relay_conn_queue
.tail
);
1245 DBG("Woken up but nothing in the relay command queue");
1246 /* Continue thread execution */
1249 new_conn
= lttng::utils::container_of(node
, &relay_connection::qnode
);
1251 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1254 * Inform worker thread of the new request. This
1255 * call is blocking so we can be assured that
1256 * the data will be read at some point in time
1257 * or wait to the end of the world :)
1259 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1261 PERROR("write connection pipe");
1262 connection_put(new_conn
);
1265 } while (node
!= NULL
);
1267 /* Futex wait on queue. Blocking call on futex() */
1268 health_poll_entry();
1269 futex_nto1_wait(&relay_conn_queue
.futex
);
1273 /* Normal exit, no error */
1280 ERR("Health error occurred in %s", __func__
);
1282 health_unregister(health_relayd
);
1283 DBG("Dispatch thread dying");
1284 lttng_relay_stop_threads();
1288 static bool session_streams_have_index(const struct relay_session
*session
)
1290 return session
->minor
>= 4 && !session
->snapshot
;
1294 * Handle the RELAYD_CREATE_SESSION command.
1296 * On success, send back the session id or else return a negative value.
1298 static int relay_create_session(
1299 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1300 struct relay_connection
*conn
,
1301 const struct lttng_buffer_view
*payload
)
1305 struct relay_session
*session
= NULL
;
1306 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1307 char session_name
[LTTNG_NAME_MAX
] = {};
1308 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1309 uint32_t live_timer
= 0;
1310 bool snapshot
= false;
1311 bool session_name_contains_creation_timestamp
= false;
1312 /* Left nil for peers < 2.11. */
1313 char base_path
[LTTNG_PATH_MAX
] = {};
1314 lttng_uuid sessiond_uuid
= {};
1315 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1316 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1317 LTTNG_OPTIONAL(time_t) creation_time
= {};
1318 struct lttng_dynamic_buffer reply_payload
;
1320 lttng_dynamic_buffer_init(&reply_payload
);
1322 if (conn
->minor
< 4) {
1323 /* From 2.1 to 2.3 */
1325 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1326 /* From 2.4 to 2.10 */
1327 ret
= cmd_create_session_2_4(payload
, session_name
,
1328 hostname
, &live_timer
, &snapshot
);
1330 bool has_current_chunk
;
1331 uint64_t current_chunk_id_value
;
1332 time_t creation_time_value
;
1333 uint64_t id_sessiond_value
;
1335 /* From 2.11 to ... */
1336 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1337 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1338 sessiond_uuid
, &has_current_chunk
,
1339 ¤t_chunk_id_value
, &creation_time_value
,
1340 &session_name_contains_creation_timestamp
);
1341 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1342 /* The nil UUID is reserved for pre-2.11 clients. */
1343 ERR("Illegal nil UUID announced by peer in create session command");
1347 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1348 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1349 if (has_current_chunk
) {
1350 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1351 current_chunk_id_value
);
1359 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1360 snapshot
, sessiond_uuid
,
1361 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1362 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1363 creation_time
.is_set
? &creation_time
.value
: NULL
,
1364 conn
->major
, conn
->minor
,
1365 session_name_contains_creation_timestamp
);
1370 LTTNG_ASSERT(!conn
->session
);
1371 conn
->session
= session
;
1372 DBG("Created session %" PRIu64
, session
->id
);
1374 reply
.generic
.session_id
= htobe64(session
->id
);
1378 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1380 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1383 if (conn
->minor
< 11) {
1384 /* From 2.1 to 2.10 */
1385 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1386 &reply
.generic
, sizeof(reply
.generic
));
1388 ERR("Failed to append \"create session\" command reply header to payload buffer");
1393 const uint32_t output_path_length
=
1394 session
? strlen(session
->output_path
) + 1 : 0;
1396 reply
.output_path_length
= htobe32(output_path_length
);
1397 ret
= lttng_dynamic_buffer_append(
1398 &reply_payload
, &reply
, sizeof(reply
));
1400 ERR("Failed to append \"create session\" command reply header to payload buffer");
1404 if (output_path_length
) {
1405 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1406 session
->output_path
,
1407 output_path_length
);
1409 ERR("Failed to append \"create session\" command reply path to payload buffer");
1415 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1416 reply_payload
.size
, 0);
1417 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1418 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1419 reply_payload
.size
, send_ret
);
1423 if (ret
< 0 && session
) {
1424 session_put(session
);
1426 lttng_dynamic_buffer_reset(&reply_payload
);
1431 * When we have received all the streams and the metadata for a channel,
1432 * we make them visible to the viewer threads.
1434 static void publish_connection_local_streams(struct relay_connection
*conn
)
1436 struct relay_stream
*stream
;
1437 struct relay_session
*session
= conn
->session
;
1440 * We publish all streams belonging to a session atomically wrt
1443 pthread_mutex_lock(&session
->lock
);
1445 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1447 stream_publish(stream
);
1452 * Inform the viewer that there are new streams in the session.
1454 if (session
->viewer_attached
) {
1455 uatomic_set(&session
->new_streams
, 1);
1457 pthread_mutex_unlock(&session
->lock
);
1460 static int conform_channel_path(char *channel_path
)
1464 if (strstr("../", channel_path
)) {
1465 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1471 if (*channel_path
== '/') {
1472 const size_t len
= strlen(channel_path
);
1475 * Channel paths from peers prior to 2.11 are expressed as an
1476 * absolute path that is, in reality, relative to the relay
1477 * daemon's output directory. Remove the leading slash so it
1478 * is correctly interpreted as a relative path later on.
1480 * len (and not len - 1) is used to copy the trailing NULL.
1482 bcopy(channel_path
+ 1, channel_path
, len
);
1489 * relay_add_stream: allocate a new stream for a session
1491 static int relay_add_stream(
1492 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1493 struct relay_connection
*conn
,
1494 const struct lttng_buffer_view
*payload
)
1498 struct relay_session
*session
= conn
->session
;
1499 struct relay_stream
*stream
= NULL
;
1500 struct lttcomm_relayd_status_stream reply
;
1501 struct ctf_trace
*trace
= NULL
;
1502 uint64_t stream_handle
= -1ULL;
1503 char *path_name
= NULL
, *channel_name
= NULL
;
1504 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1505 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1507 if (!session
|| !conn
->version_check_done
) {
1508 ERR("Trying to add a stream before version check");
1510 goto end_no_session
;
1513 if (session
->minor
== 1) {
1515 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1517 } else if (session
->minor
> 1 && session
->minor
< 11) {
1518 /* From 2.2 to 2.10 */
1519 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1520 &channel_name
, &tracefile_size
, &tracefile_count
);
1522 /* From 2.11 to ... */
1523 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1524 &channel_name
, &tracefile_size
, &tracefile_count
,
1525 &stream_chunk_id
.value
);
1526 stream_chunk_id
.is_set
= true;
1533 if (conform_channel_path(path_name
)) {
1538 * Backward compatibility for --group-output-by-session.
1539 * Prior to lttng 2.11, the complete path is passed by the stream.
1540 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1541 * >=2.11 the chunk is responsible for the output path. When dealing
1542 * with producer < 2.11 the chunk output_path is the root output path
1543 * and the stream carries the complete path (path_name).
1544 * To support --group-output-by-session with older producer (<2.11), we
1545 * need to craft the path based on the stream path.
1547 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1548 if (conn
->minor
< 4) {
1550 * From 2.1 to 2.3, the session_name is not passed on
1551 * the RELAYD_CREATE_SESSION command. The session name
1552 * is necessary to detect the presence of a base_path
1553 * inside the stream path. Without it we cannot perform
1554 * a valid group-output-by-session transformation.
1556 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1557 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1558 session
->id
, path_name
);
1559 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1560 char *group_by_session_path_name
;
1562 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1564 group_by_session_path_name
=
1565 backward_compat_group_by_session(
1567 session
->session_name
,
1568 session
->creation_time
.value
);
1569 if (!group_by_session_path_name
) {
1570 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1575 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1576 path_name
, group_by_session_path_name
);
1579 path_name
= group_by_session_path_name
;
1583 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1588 /* This stream here has one reference on the trace. */
1589 pthread_mutex_lock(&last_relay_stream_id_lock
);
1590 stream_handle
= ++last_relay_stream_id
;
1591 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1593 /* We pass ownership of path_name and channel_name. */
1594 stream
= stream_create(trace
, stream_handle
, path_name
,
1595 channel_name
, tracefile_size
, tracefile_count
);
1597 channel_name
= NULL
;
1600 * Streams are the owners of their trace. Reference to trace is
1601 * kept within stream_create().
1603 ctf_trace_put(trace
);
1606 memset(&reply
, 0, sizeof(reply
));
1607 reply
.handle
= htobe64(stream_handle
);
1609 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1611 reply
.ret_code
= htobe32(LTTNG_OK
);
1614 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1615 sizeof(struct lttcomm_relayd_status_stream
), 0);
1616 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1617 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1629 * relay_close_stream: close a specific stream
1631 static int relay_close_stream(
1632 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1633 struct relay_connection
*conn
,
1634 const struct lttng_buffer_view
*payload
)
1638 struct relay_session
*session
= conn
->session
;
1639 struct lttcomm_relayd_close_stream stream_info
;
1640 struct lttcomm_relayd_generic_reply reply
;
1641 struct relay_stream
*stream
;
1643 DBG("Close stream received");
1645 if (!session
|| !conn
->version_check_done
) {
1646 ERR("Trying to close a stream before version check");
1648 goto end_no_session
;
1651 if (payload
->size
< sizeof(stream_info
)) {
1652 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1653 sizeof(stream_info
), payload
->size
);
1655 goto end_no_session
;
1657 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1658 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1659 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1661 stream
= stream_get_by_id(stream_info
.stream_id
);
1668 * Set last_net_seq_num before the close flag. Required by data
1671 pthread_mutex_lock(&stream
->lock
);
1672 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1673 pthread_mutex_unlock(&stream
->lock
);
1676 * This is one of the conditions which may trigger a stream close
1677 * with the others being:
1678 * 1) A close command is received for a stream
1679 * 2) The control connection owning the stream is closed
1680 * 3) We have received all of the stream's data _after_ a close
1683 try_stream_close(stream
);
1688 memset(&reply
, 0, sizeof(reply
));
1690 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1692 reply
.ret_code
= htobe32(LTTNG_OK
);
1694 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1695 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1696 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1697 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1707 * relay_reset_metadata: reset a metadata stream
1710 int relay_reset_metadata(
1711 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1712 struct relay_connection
*conn
,
1713 const struct lttng_buffer_view
*payload
)
1717 struct relay_session
*session
= conn
->session
;
1718 struct lttcomm_relayd_reset_metadata stream_info
;
1719 struct lttcomm_relayd_generic_reply reply
;
1720 struct relay_stream
*stream
;
1722 DBG("Reset metadata received");
1724 if (!session
|| !conn
->version_check_done
) {
1725 ERR("Trying to reset a metadata stream before version check");
1727 goto end_no_session
;
1730 if (payload
->size
< sizeof(stream_info
)) {
1731 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1732 sizeof(stream_info
), payload
->size
);
1734 goto end_no_session
;
1736 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1737 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1738 stream_info
.version
= be64toh(stream_info
.version
);
1740 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1742 /* Unsupported for live sessions for now. */
1743 if (session
->live_timer
!= 0) {
1748 stream
= stream_get_by_id(stream_info
.stream_id
);
1753 pthread_mutex_lock(&stream
->lock
);
1754 if (!stream
->is_metadata
) {
1759 ret
= stream_reset_file(stream
);
1761 ERR("Failed to reset metadata stream %" PRIu64
1762 ": stream_path = %s, channel = %s",
1763 stream
->stream_handle
, stream
->path_name
,
1764 stream
->channel_name
);
1768 pthread_mutex_unlock(&stream
->lock
);
1772 memset(&reply
, 0, sizeof(reply
));
1774 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1776 reply
.ret_code
= htobe32(LTTNG_OK
);
1778 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1779 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1780 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1781 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1791 * relay_unknown_command: send -1 if received unknown command
1793 static void relay_unknown_command(struct relay_connection
*conn
)
1795 struct lttcomm_relayd_generic_reply reply
;
1798 memset(&reply
, 0, sizeof(reply
));
1799 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1800 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1801 if (send_ret
< sizeof(reply
)) {
1802 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1807 * relay_start: send an acknowledgment to the client to tell if we are
1808 * ready to receive data. We are ready if a session is established.
1810 static int relay_start(
1811 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1812 struct relay_connection
*conn
,
1813 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
1817 struct lttcomm_relayd_generic_reply reply
;
1818 struct relay_session
*session
= conn
->session
;
1821 DBG("Trying to start the streaming without a session established");
1822 ret
= htobe32(LTTNG_ERR_UNK
);
1825 memset(&reply
, 0, sizeof(reply
));
1826 reply
.ret_code
= htobe32(LTTNG_OK
);
1827 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1829 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1830 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1839 * relay_recv_metadata: receive the metadata for the session.
1841 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1842 struct relay_connection
*conn
,
1843 const struct lttng_buffer_view
*payload
)
1846 struct relay_session
*session
= conn
->session
;
1847 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1848 struct relay_stream
*metadata_stream
;
1849 uint64_t metadata_payload_size
;
1850 struct lttng_buffer_view packet_view
;
1853 ERR("Metadata sent before version check");
1858 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1859 ERR("Incorrect data size");
1863 metadata_payload_size
= recv_hdr
->data_size
-
1864 sizeof(struct lttcomm_relayd_metadata_payload
);
1866 memcpy(&metadata_payload_header
, payload
->data
,
1867 sizeof(metadata_payload_header
));
1868 metadata_payload_header
.stream_id
= be64toh(
1869 metadata_payload_header
.stream_id
);
1870 metadata_payload_header
.padding_size
= be32toh(
1871 metadata_payload_header
.padding_size
);
1873 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1874 if (!metadata_stream
) {
1879 packet_view
= lttng_buffer_view_from_view(payload
,
1880 sizeof(metadata_payload_header
), metadata_payload_size
);
1881 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1882 ERR("Invalid metadata packet length announced by header");
1887 pthread_mutex_lock(&metadata_stream
->lock
);
1888 ret
= stream_write(metadata_stream
, &packet_view
,
1889 metadata_payload_header
.padding_size
);
1890 pthread_mutex_unlock(&metadata_stream
->lock
);
1896 stream_put(metadata_stream
);
1902 * relay_send_version: send relayd version number
1904 static int relay_send_version(
1905 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1906 struct relay_connection
*conn
,
1907 const struct lttng_buffer_view
*payload
)
1911 struct lttcomm_relayd_version reply
, msg
;
1912 bool compatible
= true;
1914 conn
->version_check_done
= true;
1916 /* Get version from the other side. */
1917 if (payload
->size
< sizeof(msg
)) {
1918 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1919 sizeof(msg
), payload
->size
);
1924 memcpy(&msg
, payload
->data
, sizeof(msg
));
1925 msg
.major
= be32toh(msg
.major
);
1926 msg
.minor
= be32toh(msg
.minor
);
1928 memset(&reply
, 0, sizeof(reply
));
1929 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1930 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1932 /* Major versions must be the same */
1933 if (reply
.major
!= msg
.major
) {
1934 DBG("Incompatible major versions (%u vs %u), deleting session",
1935 reply
.major
, msg
.major
);
1939 conn
->major
= reply
.major
;
1940 /* We adapt to the lowest compatible version */
1941 if (reply
.minor
<= msg
.minor
) {
1942 conn
->minor
= reply
.minor
;
1944 conn
->minor
= msg
.minor
;
1947 reply
.major
= htobe32(reply
.major
);
1948 reply
.minor
= htobe32(reply
.minor
);
1949 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1951 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1952 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1965 DBG("Version check done using protocol %u.%u", conn
->major
,
1973 * Check for data pending for a given stream id from the session daemon.
1975 static int relay_data_pending(
1976 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
1977 struct relay_connection
*conn
,
1978 const struct lttng_buffer_view
*payload
)
1980 struct relay_session
*session
= conn
->session
;
1981 struct lttcomm_relayd_data_pending msg
;
1982 struct lttcomm_relayd_generic_reply reply
;
1983 struct relay_stream
*stream
;
1986 uint64_t stream_seq
;
1988 DBG("Data pending command received");
1990 if (!session
|| !conn
->version_check_done
) {
1991 ERR("Trying to check for data before version check");
1993 goto end_no_session
;
1996 if (payload
->size
< sizeof(msg
)) {
1997 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1998 sizeof(msg
), payload
->size
);
2000 goto end_no_session
;
2002 memcpy(&msg
, payload
->data
, sizeof(msg
));
2003 msg
.stream_id
= be64toh(msg
.stream_id
);
2004 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2006 stream
= stream_get_by_id(msg
.stream_id
);
2007 if (stream
== NULL
) {
2012 pthread_mutex_lock(&stream
->lock
);
2014 if (session_streams_have_index(session
)) {
2016 * Ensure that both the index and stream data have been
2017 * flushed up to the requested point.
2019 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2021 stream_seq
= stream
->prev_data_seq
;
2023 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2024 ", prev_index_seq %" PRIu64
2025 ", and last_seq %" PRIu64
, msg
.stream_id
,
2026 stream
->prev_data_seq
, stream
->prev_index_seq
,
2027 msg
.last_net_seq_num
);
2029 /* Avoid wrapping issue */
2030 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2031 /* Data has in fact been written and is NOT pending */
2034 /* Data still being streamed thus pending */
2038 stream
->data_pending_check_done
= true;
2039 pthread_mutex_unlock(&stream
->lock
);
2044 memset(&reply
, 0, sizeof(reply
));
2045 reply
.ret_code
= htobe32(ret
);
2046 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2047 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2048 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2058 * Wait for the control socket to reach a quiescent state.
2060 * Note that for now, when receiving this command from the session
2061 * daemon, this means that every subsequent commands or data received on
2062 * the control socket has been handled. So, this is why we simply return
2065 static int relay_quiescent_control(
2066 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2067 struct relay_connection
*conn
,
2068 const struct lttng_buffer_view
*payload
)
2072 struct relay_stream
*stream
;
2073 struct lttcomm_relayd_quiescent_control msg
;
2074 struct lttcomm_relayd_generic_reply reply
;
2076 DBG("Checking quiescent state on control socket");
2078 if (!conn
->session
|| !conn
->version_check_done
) {
2079 ERR("Trying to check for data before version check");
2081 goto end_no_session
;
2084 if (payload
->size
< sizeof(msg
)) {
2085 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2086 sizeof(msg
), payload
->size
);
2088 goto end_no_session
;
2090 memcpy(&msg
, payload
->data
, sizeof(msg
));
2091 msg
.stream_id
= be64toh(msg
.stream_id
);
2093 stream
= stream_get_by_id(msg
.stream_id
);
2097 pthread_mutex_lock(&stream
->lock
);
2098 stream
->data_pending_check_done
= true;
2099 pthread_mutex_unlock(&stream
->lock
);
2101 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2104 memset(&reply
, 0, sizeof(reply
));
2105 reply
.ret_code
= htobe32(LTTNG_OK
);
2106 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2107 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2108 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2120 * Initialize a data pending command. This means that a consumer is about
2121 * to ask for data pending for each stream it holds. Simply iterate over
2122 * all streams of a session and set the data_pending_check_done flag.
2124 * This command returns to the client a LTTNG_OK code.
2126 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2127 struct relay_connection
*conn
,
2128 const struct lttng_buffer_view
*payload
)
2132 struct lttng_ht_iter iter
;
2133 struct lttcomm_relayd_begin_data_pending msg
;
2134 struct lttcomm_relayd_generic_reply reply
;
2135 struct relay_stream
*stream
;
2137 LTTNG_ASSERT(recv_hdr
);
2140 DBG("Init streams for data pending");
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_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2150 sizeof(msg
), payload
->size
);
2152 goto end_no_session
;
2154 memcpy(&msg
, payload
->data
, sizeof(msg
));
2155 msg
.session_id
= be64toh(msg
.session_id
);
2158 * Iterate over all streams to set the begin data pending flag.
2159 * For now, the streams are indexed by stream handle so we have
2160 * to iterate over all streams to find the one associated with
2161 * the right session_id.
2164 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2166 if (!stream_get(stream
)) {
2169 if (stream
->trace
->session
->id
== msg
.session_id
) {
2170 pthread_mutex_lock(&stream
->lock
);
2171 stream
->data_pending_check_done
= false;
2172 pthread_mutex_unlock(&stream
->lock
);
2173 DBG("Set begin data pending flag to stream %" PRIu64
,
2174 stream
->stream_handle
);
2180 memset(&reply
, 0, sizeof(reply
));
2181 /* All good, send back reply. */
2182 reply
.ret_code
= htobe32(LTTNG_OK
);
2184 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2185 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2186 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2198 * End data pending command. This will check, for a given session id, if
2199 * each stream associated with it has its data_pending_check_done flag
2200 * set. If not, this means that the client lost track of the stream but
2201 * the data is still being streamed on our side. In this case, we inform
2202 * the client that data is in flight.
2204 * Return to the client if there is data in flight or not with a ret_code.
2206 static int relay_end_data_pending(
2207 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2208 struct relay_connection
*conn
,
2209 const struct lttng_buffer_view
*payload
)
2213 struct lttng_ht_iter iter
;
2214 struct lttcomm_relayd_end_data_pending msg
;
2215 struct lttcomm_relayd_generic_reply reply
;
2216 struct relay_stream
*stream
;
2217 uint32_t is_data_inflight
= 0;
2219 DBG("End data pending command");
2221 if (!conn
->session
|| !conn
->version_check_done
) {
2222 ERR("Trying to check for data before version check");
2224 goto end_no_session
;
2227 if (payload
->size
< sizeof(msg
)) {
2228 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2229 sizeof(msg
), payload
->size
);
2231 goto end_no_session
;
2233 memcpy(&msg
, payload
->data
, sizeof(msg
));
2234 msg
.session_id
= be64toh(msg
.session_id
);
2237 * Iterate over all streams to see if the begin data pending
2241 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2243 if (!stream_get(stream
)) {
2246 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2250 pthread_mutex_lock(&stream
->lock
);
2251 if (!stream
->data_pending_check_done
) {
2252 uint64_t stream_seq
;
2254 if (session_streams_have_index(conn
->session
)) {
2256 * Ensure that both the index and stream data have been
2257 * flushed up to the requested point.
2259 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2261 stream_seq
= stream
->prev_data_seq
;
2263 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2264 is_data_inflight
= 1;
2265 DBG("Data is still in flight for stream %" PRIu64
,
2266 stream
->stream_handle
);
2267 pthread_mutex_unlock(&stream
->lock
);
2272 pthread_mutex_unlock(&stream
->lock
);
2277 memset(&reply
, 0, sizeof(reply
));
2278 /* All good, send back reply. */
2279 reply
.ret_code
= htobe32(is_data_inflight
);
2281 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2282 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2283 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2295 * Receive an index for a specific stream.
2297 * Return 0 on success else a negative value.
2299 static int relay_recv_index(
2300 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2301 struct relay_connection
*conn
,
2302 const struct lttng_buffer_view
*payload
)
2306 struct relay_session
*session
= conn
->session
;
2307 struct lttcomm_relayd_index index_info
;
2308 struct lttcomm_relayd_generic_reply reply
;
2309 struct relay_stream
*stream
;
2314 DBG("Relay receiving index");
2316 if (!session
|| !conn
->version_check_done
) {
2317 ERR("Trying to close a stream before version check");
2319 goto end_no_session
;
2322 msg_len
= lttcomm_relayd_index_len(
2323 lttng_to_index_major(conn
->major
, conn
->minor
),
2324 lttng_to_index_minor(conn
->major
, conn
->minor
));
2325 if (payload
->size
< msg_len
) {
2326 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2327 msg_len
, payload
->size
);
2329 goto end_no_session
;
2331 memcpy(&index_info
, payload
->data
, msg_len
);
2332 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2333 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2334 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2335 index_info
.content_size
= be64toh(index_info
.content_size
);
2336 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2337 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2338 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2339 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2341 if (conn
->minor
>= 8) {
2342 index_info
.stream_instance_id
=
2343 be64toh(index_info
.stream_instance_id
);
2344 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2346 index_info
.stream_instance_id
= -1ULL;
2347 index_info
.packet_seq_num
= -1ULL;
2350 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2352 ERR("stream_get_by_id not found");
2357 pthread_mutex_lock(&stream
->lock
);
2358 ret
= stream_add_index(stream
, &index_info
);
2359 pthread_mutex_unlock(&stream
->lock
);
2361 goto end_stream_put
;
2367 memset(&reply
, 0, sizeof(reply
));
2369 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2371 reply
.ret_code
= htobe32(LTTNG_OK
);
2373 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2374 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2375 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2384 * Receive the streams_sent message.
2386 * Return 0 on success else a negative value.
2388 static int relay_streams_sent(
2389 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2390 struct relay_connection
*conn
,
2391 const struct lttng_buffer_view
*payload
__attribute__((unused
)))
2395 struct lttcomm_relayd_generic_reply reply
;
2399 DBG("Relay receiving streams_sent");
2401 if (!conn
->session
|| !conn
->version_check_done
) {
2402 ERR("Trying to close a stream before version check");
2404 goto end_no_session
;
2408 * Publish every pending stream in the connection recv list which are
2409 * now ready to be used by the viewer.
2411 publish_connection_local_streams(conn
);
2413 memset(&reply
, 0, sizeof(reply
));
2414 reply
.ret_code
= htobe32(LTTNG_OK
);
2415 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2416 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2417 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2429 static ssize_t
relay_unpack_rotate_streams_header(
2430 const struct lttng_buffer_view
*payload
,
2431 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2433 struct lttcomm_relayd_rotate_streams rotate_streams
;
2435 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2436 * This is the smallest version of this structure, but it can be larger;
2437 * this variable is updated once the proper size of the structure is known.
2439 * See comment at the declaration of this structure for more information.
2441 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2442 size_t expected_payload_size_no_padding
,
2443 expected_payload_size_3_bytes_padding
,
2444 expected_payload_size_7_bytes_padding
;
2446 if (payload
->size
< header_len
) {
2447 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2448 header_len
, payload
->size
);
2453 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2454 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2456 * We start by "unpacking" `stream_count` to figure out the padding length
2457 * emited by our peer.
2460 decltype(rotate_streams
.stream_count
) stream_count
;
2462 memcpy(&stream_count
, payload
->data
, sizeof(stream_count
));
2463 rotate_streams
.stream_count
= be32toh(stream_count
);
2466 rotate_streams
.new_chunk_id
= LTTNG_OPTIONAL_INIT_UNSET
;
2469 * Payload size expected given the possible padding lengths in
2470 * `struct lttcomm_relayd_rotate_streams`.
2472 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2473 sizeof(*rotate_streams
.rotation_positions
)) +
2474 sizeof(lttcomm_relayd_rotate_streams_packed
);
2475 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2476 sizeof(*rotate_streams
.rotation_positions
)) +
2477 sizeof(lttcomm_relayd_rotate_streams_3_bytes_padding
);
2478 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2479 sizeof(*rotate_streams
.rotation_positions
)) +
2480 sizeof(lttcomm_relayd_rotate_streams_7_bytes_padding
);
2482 if (payload
->size
== expected_payload_size_no_padding
) {
2483 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2486 * This handles cases where someone might build with
2487 * -fpack-struct or any other toolchain that wouldn't produce
2488 * padding to align `value`.
2490 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2492 header_len
= sizeof(packed_rotate_streams
);
2493 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2495 /* Unpack the packed structure to the natively-packed version. */
2496 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2497 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2498 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2500 _rotate_streams
->stream_count
= be32toh(packed_rotate_streams
.stream_count
);
2501 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2502 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2504 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2506 header_len
= sizeof(padded_rotate_streams
);
2507 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2509 /* Unpack the 3-byte padded structure to the natively-packed version. */
2510 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2511 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2512 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2514 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2515 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2516 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2518 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2520 header_len
= sizeof(padded_rotate_streams
);
2521 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2523 /* Unpack the 7-byte padded structure to the natively-packed version. */
2524 _rotate_streams
->new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)){
2525 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2526 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2528 _rotate_streams
->stream_count
= be32toh(padded_rotate_streams
.stream_count
);
2530 header_len
= sizeof(padded_rotate_streams
);
2532 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2533 expected_payload_size_no_padding
,
2534 expected_payload_size_3_bytes_padding
,
2535 expected_payload_size_7_bytes_padding
,
2546 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2547 * session rotation feature (not the tracefile rotation feature).
2549 static int relay_rotate_session_streams(
2550 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2551 struct relay_connection
*conn
,
2552 const struct lttng_buffer_view
*payload
)
2557 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2558 struct relay_session
*session
= conn
->session
;
2559 struct lttcomm_relayd_rotate_streams rotate_streams
;
2560 struct lttcomm_relayd_generic_reply reply
= {};
2561 struct relay_stream
*stream
= NULL
;
2562 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2563 struct lttng_buffer_view stream_positions
;
2564 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2565 const char *chunk_id_str
= "none";
2568 if (!session
|| !conn
->version_check_done
) {
2569 ERR("Trying to rotate a stream before version check");
2574 if (session
->major
== 2 && session
->minor
< 11) {
2575 ERR("Unsupported feature before 2.11");
2580 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2581 if (header_len
< 0) {
2586 if (rotate_streams
.new_chunk_id
.is_set
) {
2588 * Retrieve the trace chunk the stream must transition to. As
2589 * per the protocol, this chunk should have been created
2590 * before this command is received.
2592 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2593 sessiond_trace_chunk_registry
,
2594 session
->sessiond_uuid
,
2595 conn
->session
->id_sessiond
.is_set
?
2596 conn
->session
->id_sessiond
.value
:
2598 rotate_streams
.new_chunk_id
.value
);
2599 if (!next_trace_chunk
) {
2600 char uuid_str
[LTTNG_UUID_STR_LEN
];
2602 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2603 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2604 ", trace_chunk_id = %" PRIu64
,
2605 uuid_str
, session
->id
,
2606 rotate_streams
.new_chunk_id
.value
);
2607 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2612 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2613 rotate_streams
.new_chunk_id
.value
);
2614 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2615 chunk_id_str
= "formatting error";
2617 chunk_id_str
= chunk_id_buf
;
2621 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2622 rotate_streams
.stream_count
, session
->session_name
,
2625 stream_positions
= lttng_buffer_view_from_view(payload
,
2627 if (!stream_positions
.data
||
2628 stream_positions
.size
<
2629 (rotate_streams
.stream_count
*
2630 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2631 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2636 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2637 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2638 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2639 const struct lttcomm_relayd_stream_rotation_position pos
= {
2640 .stream_id
= be64toh(position_comm
->stream_id
),
2641 .rotate_at_seq_num
= be64toh(
2642 position_comm
->rotate_at_seq_num
),
2645 stream
= stream_get_by_id(pos
.stream_id
);
2647 reply_code
= LTTNG_ERR_INVALID
;
2652 pthread_mutex_lock(&stream
->lock
);
2653 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2654 pos
.rotate_at_seq_num
);
2655 pthread_mutex_unlock(&stream
->lock
);
2657 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2665 reply_code
= LTTNG_OK
;
2672 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2673 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2674 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2675 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2676 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2681 lttng_trace_chunk_put(next_trace_chunk
);
2686 * relay_create_trace_chunk: create a new trace chunk
2688 static int relay_create_trace_chunk(
2689 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2690 struct relay_connection
*conn
,
2691 const struct lttng_buffer_view
*payload
)
2695 struct relay_session
*session
= conn
->session
;
2696 struct lttcomm_relayd_create_trace_chunk
*msg
;
2697 struct lttcomm_relayd_generic_reply reply
= {};
2698 struct lttng_buffer_view header_view
;
2699 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2700 enum lttng_error_code reply_code
= LTTNG_OK
;
2701 enum lttng_trace_chunk_status chunk_status
;
2702 const char *new_path
;
2704 if (!session
|| !conn
->version_check_done
) {
2705 ERR("Trying to create a trace chunk before version check");
2710 if (session
->major
== 2 && session
->minor
< 11) {
2711 ERR("Chunk creation command is unsupported before 2.11");
2716 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2717 if (!lttng_buffer_view_is_valid(&header_view
)) {
2718 ERR("Failed to receive payload of chunk creation command");
2723 /* Convert to host endianness. */
2724 msg
= (typeof(msg
)) header_view
.data
;
2725 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2726 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2727 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2729 pthread_mutex_lock(&conn
->session
->lock
);
2730 session
->ongoing_rotation
= true;
2731 if (session
->current_trace_chunk
&&
2732 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2733 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2734 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2735 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2736 ERR("Failed to rename old chunk");
2738 reply_code
= LTTNG_ERR_UNK
;
2742 if (!session
->current_trace_chunk
) {
2743 if (!session
->has_rotated
) {
2749 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2751 chunk
= lttng_trace_chunk_create(
2752 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2754 ERR("Failed to create trace chunk in trace chunk creation command");
2756 reply_code
= LTTNG_ERR_NOMEM
;
2759 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2761 if (msg
->override_name_length
) {
2763 const struct lttng_buffer_view chunk_name_view
=
2764 lttng_buffer_view_from_view(payload
,
2766 msg
->override_name_length
);
2768 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2769 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2771 reply_code
= LTTNG_ERR_INVALID
;
2775 name
= chunk_name_view
.data
;
2776 if (name
[msg
->override_name_length
- 1]) {
2777 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2779 reply_code
= LTTNG_ERR_INVALID
;
2783 chunk_status
= lttng_trace_chunk_override_name(
2784 chunk
, chunk_name_view
.data
);
2785 switch (chunk_status
) {
2786 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2788 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2789 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2790 reply_code
= LTTNG_ERR_INVALID
;
2794 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2795 reply_code
= LTTNG_ERR_UNK
;
2801 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2802 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2803 reply_code
= LTTNG_ERR_UNK
;
2808 LTTNG_ASSERT(conn
->session
->output_directory
);
2809 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2810 conn
->session
->output_directory
);
2811 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2812 reply_code
= LTTNG_ERR_UNK
;
2817 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2818 sessiond_trace_chunk_registry
,
2819 conn
->session
->sessiond_uuid
,
2820 conn
->session
->id_sessiond
.is_set
?
2821 conn
->session
->id_sessiond
.value
:
2824 if (!published_chunk
) {
2825 char uuid_str
[LTTNG_UUID_STR_LEN
];
2827 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2828 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2833 reply_code
= LTTNG_ERR_NOMEM
;
2837 if (conn
->session
->pending_closure_trace_chunk
) {
2839 * Invalid; this means a second create_trace_chunk command was
2840 * received before a close_trace_chunk.
2842 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2843 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2847 conn
->session
->pending_closure_trace_chunk
=
2848 conn
->session
->current_trace_chunk
;
2849 conn
->session
->current_trace_chunk
= published_chunk
;
2850 published_chunk
= NULL
;
2851 if (!conn
->session
->pending_closure_trace_chunk
) {
2852 session
->ongoing_rotation
= false;
2855 pthread_mutex_unlock(&conn
->session
->lock
);
2856 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2857 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2859 sizeof(struct lttcomm_relayd_generic_reply
),
2861 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2862 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2867 lttng_trace_chunk_put(chunk
);
2868 lttng_trace_chunk_put(published_chunk
);
2873 * relay_close_trace_chunk: close a trace chunk
2875 static int relay_close_trace_chunk(
2876 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
2877 struct relay_connection
*conn
,
2878 const struct lttng_buffer_view
*payload
)
2880 int ret
= 0, buf_ret
;
2882 struct relay_session
*session
= conn
->session
;
2883 struct lttcomm_relayd_close_trace_chunk
*msg
;
2884 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2885 struct lttng_buffer_view header_view
;
2886 struct lttng_trace_chunk
*chunk
= NULL
;
2887 enum lttng_error_code reply_code
= LTTNG_OK
;
2888 enum lttng_trace_chunk_status chunk_status
;
2890 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2891 time_t close_timestamp
;
2892 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2893 size_t path_length
= 0;
2894 const char *chunk_name
= NULL
;
2895 struct lttng_dynamic_buffer reply_payload
;
2896 const char *new_path
;
2898 lttng_dynamic_buffer_init(&reply_payload
);
2900 if (!session
|| !conn
->version_check_done
) {
2901 ERR("Trying to close a trace chunk before version check");
2906 if (session
->major
== 2 && session
->minor
< 11) {
2907 ERR("Chunk close command is unsupported before 2.11");
2912 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2913 if (!lttng_buffer_view_is_valid(&header_view
)) {
2914 ERR("Failed to receive payload of chunk close command");
2919 /* Convert to host endianness. */
2920 msg
= (typeof(msg
)) header_view
.data
;
2921 chunk_id
= be64toh(msg
->chunk_id
);
2922 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2923 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2924 close_command
.is_set
= msg
->close_command
.is_set
;
2926 chunk
= sessiond_trace_chunk_registry_get_chunk(
2927 sessiond_trace_chunk_registry
,
2928 conn
->session
->sessiond_uuid
,
2929 conn
->session
->id_sessiond
.is_set
?
2930 conn
->session
->id_sessiond
.value
:
2934 char uuid_str
[LTTNG_UUID_STR_LEN
];
2936 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2937 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2942 reply_code
= LTTNG_ERR_NOMEM
;
2946 pthread_mutex_lock(&session
->lock
);
2947 if (close_command
.is_set
&&
2948 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
2950 * Clear command. It is a protocol error to ask for a
2951 * clear on a relay which does not allow it. Querying
2952 * the configuration allows figuring out whether
2953 * clearing is allowed before doing the clear.
2955 if (!opt_allow_clear
) {
2957 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2958 goto end_unlock_session
;
2961 if (session
->pending_closure_trace_chunk
&&
2962 session
->pending_closure_trace_chunk
!= chunk
) {
2963 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2964 session
->session_name
);
2965 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2967 goto end_unlock_session
;
2970 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
2971 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2972 if (close_command
.is_set
&&
2973 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
2974 !session
->has_rotated
) {
2975 /* New chunk stays in session output directory. */
2978 /* Use chunk name for new chunk. */
2981 /* Rename new chunk path. */
2982 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2984 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2986 goto end_unlock_session
;
2988 session
->ongoing_rotation
= false;
2990 if ((!close_command
.is_set
||
2991 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
2992 !lttng_trace_chunk_get_name_overridden(chunk
)) {
2993 const char *old_path
;
2995 if (!session
->has_rotated
) {
3000 /* We need to move back the .tmp_old_chunk to its rightful place. */
3001 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3002 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3004 goto end_unlock_session
;
3007 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3008 chunk
, close_timestamp
);
3009 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3010 ERR("Failed to set trace chunk close timestamp");
3012 reply_code
= LTTNG_ERR_UNK
;
3013 goto end_unlock_session
;
3016 if (close_command
.is_set
) {
3017 chunk_status
= lttng_trace_chunk_set_close_command(
3018 chunk
, close_command
.value
);
3019 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3021 reply_code
= LTTNG_ERR_INVALID
;
3022 goto end_unlock_session
;
3025 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3026 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3027 ERR("Failed to get chunk name");
3029 reply_code
= LTTNG_ERR_UNK
;
3030 goto end_unlock_session
;
3032 if (!session
->has_rotated
&& !session
->snapshot
) {
3033 ret
= lttng_strncpy(closed_trace_chunk_path
,
3034 session
->output_path
,
3035 sizeof(closed_trace_chunk_path
));
3037 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3038 strlen(session
->output_path
),
3039 sizeof(closed_trace_chunk_path
));
3040 reply_code
= LTTNG_ERR_NOMEM
;
3042 goto end_unlock_session
;
3045 if (session
->snapshot
) {
3046 ret
= snprintf(closed_trace_chunk_path
,
3047 sizeof(closed_trace_chunk_path
),
3048 "%s/%s", session
->output_path
,
3051 ret
= snprintf(closed_trace_chunk_path
,
3052 sizeof(closed_trace_chunk_path
),
3053 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3055 session
->output_path
, chunk_name
);
3057 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3058 ERR("Failed to format closed trace chunk resulting path");
3059 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3061 goto end_unlock_session
;
3064 if (close_command
.is_set
&&
3065 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3066 session
->has_rotated
= true;
3068 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3069 path_length
= strlen(closed_trace_chunk_path
) + 1;
3070 if (path_length
> UINT32_MAX
) {
3071 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3073 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3074 goto end_unlock_session
;
3077 if (session
->current_trace_chunk
== chunk
) {
3079 * After a trace chunk close command, no new streams
3080 * referencing the chunk may be created. Hence, on the
3081 * event that no new trace chunk have been created for
3082 * the session, the reference to the current trace chunk
3083 * is released in order to allow it to be reclaimed when
3084 * the last stream releases its reference to it.
3086 lttng_trace_chunk_put(session
->current_trace_chunk
);
3087 session
->current_trace_chunk
= NULL
;
3089 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3090 session
->pending_closure_trace_chunk
= NULL
;
3092 pthread_mutex_unlock(&session
->lock
);
3095 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3096 reply
.path_length
= htobe32((uint32_t) path_length
);
3097 buf_ret
= lttng_dynamic_buffer_append(
3098 &reply_payload
, &reply
, sizeof(reply
));
3100 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3104 if (reply_code
== LTTNG_OK
) {
3105 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3106 closed_trace_chunk_path
, path_length
);
3108 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3113 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3117 if (send_ret
< reply_payload
.size
) {
3118 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3119 reply_payload
.size
, send_ret
);
3124 lttng_trace_chunk_put(chunk
);
3125 lttng_dynamic_buffer_reset(&reply_payload
);
3130 * relay_trace_chunk_exists: check if a trace chunk exists
3132 static int relay_trace_chunk_exists(
3133 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
3134 struct relay_connection
*conn
,
3135 const struct lttng_buffer_view
*payload
)
3139 struct relay_session
*session
= conn
->session
;
3140 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3141 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3142 struct lttng_buffer_view header_view
;
3146 if (!session
|| !conn
->version_check_done
) {
3147 ERR("Trying to check for the presence of a trace chunk before version check");
3152 if (session
->major
== 2 && session
->minor
< 11) {
3153 ERR("Chunk exists command is unsupported before 2.11");
3158 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3159 if (!lttng_buffer_view_is_valid(&header_view
)) {
3160 ERR("Failed to receive payload of chunk exists command");
3165 /* Convert to host endianness. */
3166 msg
= (typeof(msg
)) header_view
.data
;
3167 chunk_id
= be64toh(msg
->chunk_id
);
3169 ret
= sessiond_trace_chunk_registry_chunk_exists(
3170 sessiond_trace_chunk_registry
,
3171 conn
->session
->sessiond_uuid
,
3173 chunk_id
, &chunk_exists
);
3175 * If ret is not 0, send the reply and report the error to the caller.
3176 * It is a protocol (or internal) error and the session/connection
3177 * should be torn down.
3179 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3180 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3182 send_ret
= conn
->sock
->ops
->sendmsg(
3183 conn
->sock
, &reply
, sizeof(reply
), 0);
3184 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3185 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3194 * relay_get_configuration: query whether feature is available
3196 static int relay_get_configuration(
3197 const struct lttcomm_relayd_hdr
*recv_hdr
__attribute__((unused
)),
3198 struct relay_connection
*conn
,
3199 const struct lttng_buffer_view
*payload
)
3203 struct lttcomm_relayd_get_configuration
*msg
;
3204 struct lttcomm_relayd_get_configuration_reply reply
= {};
3205 struct lttng_buffer_view header_view
;
3206 uint64_t query_flags
= 0;
3207 uint64_t result_flags
= 0;
3209 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3210 if (!lttng_buffer_view_is_valid(&header_view
)) {
3211 ERR("Failed to receive payload of chunk close command");
3216 /* Convert to host endianness. */
3217 msg
= (typeof(msg
)) header_view
.data
;
3218 query_flags
= be64toh(msg
->query_flags
);
3221 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3224 if (opt_allow_clear
) {
3225 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3229 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3230 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3232 send_ret
= conn
->sock
->ops
->sendmsg(
3233 conn
->sock
, &reply
, sizeof(reply
), 0);
3234 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3235 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3243 static int relay_process_control_command(struct relay_connection
*conn
,
3244 const struct lttcomm_relayd_hdr
*header
,
3245 const struct lttng_buffer_view
*payload
)
3249 DBG3("Processing \"%s\" command for socket %i",
3250 lttcomm_relayd_command_str((lttcomm_relayd_command
) header
->cmd
),
3252 switch (header
->cmd
) {
3253 case RELAYD_CREATE_SESSION
:
3254 ret
= relay_create_session(header
, conn
, payload
);
3256 case RELAYD_ADD_STREAM
:
3257 ret
= relay_add_stream(header
, conn
, payload
);
3259 case RELAYD_START_DATA
:
3260 ret
= relay_start(header
, conn
, payload
);
3262 case RELAYD_SEND_METADATA
:
3263 ret
= relay_recv_metadata(header
, conn
, payload
);
3265 case RELAYD_VERSION
:
3266 ret
= relay_send_version(header
, conn
, payload
);
3268 case RELAYD_CLOSE_STREAM
:
3269 ret
= relay_close_stream(header
, conn
, payload
);
3271 case RELAYD_DATA_PENDING
:
3272 ret
= relay_data_pending(header
, conn
, payload
);
3274 case RELAYD_QUIESCENT_CONTROL
:
3275 ret
= relay_quiescent_control(header
, conn
, payload
);
3277 case RELAYD_BEGIN_DATA_PENDING
:
3278 ret
= relay_begin_data_pending(header
, conn
, payload
);
3280 case RELAYD_END_DATA_PENDING
:
3281 ret
= relay_end_data_pending(header
, conn
, payload
);
3283 case RELAYD_SEND_INDEX
:
3284 ret
= relay_recv_index(header
, conn
, payload
);
3286 case RELAYD_STREAMS_SENT
:
3287 ret
= relay_streams_sent(header
, conn
, payload
);
3289 case RELAYD_RESET_METADATA
:
3290 ret
= relay_reset_metadata(header
, conn
, payload
);
3292 case RELAYD_ROTATE_STREAMS
:
3293 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3295 case RELAYD_CREATE_TRACE_CHUNK
:
3296 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3298 case RELAYD_CLOSE_TRACE_CHUNK
:
3299 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3301 case RELAYD_TRACE_CHUNK_EXISTS
:
3302 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3304 case RELAYD_GET_CONFIGURATION
:
3305 ret
= relay_get_configuration(header
, conn
, payload
);
3307 case RELAYD_UPDATE_SYNC_INFO
:
3309 ERR("Received unknown command (%u)", header
->cmd
);
3310 relay_unknown_command(conn
);
3319 static enum relay_connection_status
relay_process_control_receive_payload(
3320 struct relay_connection
*conn
)
3323 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3324 struct lttng_dynamic_buffer
*reception_buffer
=
3325 &conn
->protocol
.ctrl
.reception_buffer
;
3326 struct ctrl_connection_state_receive_payload
*state
=
3327 &conn
->protocol
.ctrl
.state
.receive_payload
;
3328 struct lttng_buffer_view payload_view
;
3330 if (state
->left_to_receive
== 0) {
3331 /* Short-circuit for payload-less commands. */
3332 goto reception_complete
;
3335 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3336 reception_buffer
->data
+ state
->received
,
3337 state
->left_to_receive
, MSG_DONTWAIT
);
3340 DIAGNOSTIC_IGNORE_LOGICAL_OP
3341 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3343 PERROR("Unable to receive command payload on sock %d",
3345 status
= RELAY_CONNECTION_STATUS_ERROR
;
3348 } else if (ret
== 0) {
3349 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3350 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3354 LTTNG_ASSERT(ret
> 0);
3355 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3357 state
->left_to_receive
-= ret
;
3358 state
->received
+= ret
;
3360 if (state
->left_to_receive
> 0) {
3362 * Can't transition to the protocol's next state, wait to
3363 * receive the rest of the header.
3365 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3366 state
->received
, state
->left_to_receive
,
3372 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3373 conn
->sock
->fd
, state
->received
);
3375 * The payload required to process the command has been received.
3376 * A view to the reception buffer is forwarded to the various
3377 * commands and the state of the control is reset on success.
3379 * Commands are responsible for sending their reply to the peer.
3381 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3383 ret
= relay_process_control_command(conn
,
3384 &state
->header
, &payload_view
);
3386 status
= RELAY_CONNECTION_STATUS_ERROR
;
3390 ret
= connection_reset_protocol_state(conn
);
3392 status
= RELAY_CONNECTION_STATUS_ERROR
;
3398 static enum relay_connection_status
relay_process_control_receive_header(
3399 struct relay_connection
*conn
)
3402 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3403 struct lttcomm_relayd_hdr header
;
3404 struct lttng_dynamic_buffer
*reception_buffer
=
3405 &conn
->protocol
.ctrl
.reception_buffer
;
3406 struct ctrl_connection_state_receive_header
*state
=
3407 &conn
->protocol
.ctrl
.state
.receive_header
;
3409 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3411 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3412 reception_buffer
->data
+ state
->received
,
3413 state
->left_to_receive
, MSG_DONTWAIT
);
3416 DIAGNOSTIC_IGNORE_LOGICAL_OP
3417 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3419 PERROR("Unable to receive control command header on sock %d",
3421 status
= RELAY_CONNECTION_STATUS_ERROR
;
3424 } else if (ret
== 0) {
3425 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3426 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3430 LTTNG_ASSERT(ret
> 0);
3431 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3433 state
->left_to_receive
-= ret
;
3434 state
->received
+= ret
;
3436 if (state
->left_to_receive
> 0) {
3438 * Can't transition to the protocol's next state, wait to
3439 * receive the rest of the header.
3441 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3442 state
->received
, state
->left_to_receive
,
3447 /* Transition to next state: receiving the command's payload. */
3448 conn
->protocol
.ctrl
.state_id
=
3449 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3450 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3451 header
.circuit_id
= be64toh(header
.circuit_id
);
3452 header
.data_size
= be64toh(header
.data_size
);
3453 header
.cmd
= be32toh(header
.cmd
);
3454 header
.cmd_version
= be32toh(header
.cmd_version
);
3455 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3456 &header
, sizeof(header
));
3458 DBG("Done receiving control command header: fd = %i, cmd = %s, cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3459 conn
->sock
->fd
, lttcomm_relayd_command_str((enum lttcomm_relayd_command
) header
.cmd
),
3460 header
.cmd_version
, header
.data_size
);
3462 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3463 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3465 status
= RELAY_CONNECTION_STATUS_ERROR
;
3469 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3471 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3472 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3475 status
= RELAY_CONNECTION_STATUS_ERROR
;
3479 if (header
.data_size
== 0) {
3481 * Manually invoke the next state as the poll loop
3482 * will not wake-up to allow us to proceed further.
3484 status
= relay_process_control_receive_payload(conn
);
3491 * Process the commands received on the control socket
3493 static enum relay_connection_status
relay_process_control(
3494 struct relay_connection
*conn
)
3496 enum relay_connection_status status
;
3498 switch (conn
->protocol
.ctrl
.state_id
) {
3499 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3500 status
= relay_process_control_receive_header(conn
);
3502 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3503 status
= relay_process_control_receive_payload(conn
);
3506 ERR("Unknown control connection protocol state encountered.");
3513 static enum relay_connection_status
relay_process_data_receive_header(
3514 struct relay_connection
*conn
)
3517 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3518 struct data_connection_state_receive_header
*state
=
3519 &conn
->protocol
.data
.state
.receive_header
;
3520 struct lttcomm_relayd_data_hdr header
;
3521 struct relay_stream
*stream
;
3523 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3525 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3526 state
->header_reception_buffer
+ state
->received
,
3527 state
->left_to_receive
, MSG_DONTWAIT
);
3530 DIAGNOSTIC_IGNORE_LOGICAL_OP
3531 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3533 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3534 status
= RELAY_CONNECTION_STATUS_ERROR
;
3537 } else if (ret
== 0) {
3538 /* Orderly shutdown. Not necessary to print an error. */
3539 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3540 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3544 LTTNG_ASSERT(ret
> 0);
3545 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3547 state
->left_to_receive
-= ret
;
3548 state
->received
+= ret
;
3550 if (state
->left_to_receive
> 0) {
3552 * Can't transition to the protocol's next state, wait to
3553 * receive the rest of the header.
3555 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3556 state
->received
, state
->left_to_receive
,
3561 /* Transition to next state: receiving the payload. */
3562 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3564 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3565 header
.circuit_id
= be64toh(header
.circuit_id
);
3566 header
.stream_id
= be64toh(header
.stream_id
);
3567 header
.data_size
= be32toh(header
.data_size
);
3568 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3569 header
.padding_size
= be32toh(header
.padding_size
);
3570 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3572 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3574 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3575 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3577 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3578 conn
->sock
->fd
, header
.circuit_id
,
3579 header
.stream_id
, header
.data_size
,
3580 header
.net_seq_num
, header
.padding_size
);
3582 stream
= stream_get_by_id(header
.stream_id
);
3584 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3586 /* Protocol error. */
3587 status
= RELAY_CONNECTION_STATUS_ERROR
;
3591 pthread_mutex_lock(&stream
->lock
);
3592 /* Prepare stream for the reception of a new packet. */
3593 ret
= stream_init_packet(stream
, header
.data_size
,
3594 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3595 pthread_mutex_unlock(&stream
->lock
);
3597 ERR("Failed to rotate stream output file");
3598 status
= RELAY_CONNECTION_STATUS_ERROR
;
3599 goto end_stream_unlock
;
3608 static enum relay_connection_status
relay_process_data_receive_payload(
3609 struct relay_connection
*conn
)
3612 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3613 struct relay_stream
*stream
;
3614 struct data_connection_state_receive_payload
*state
=
3615 &conn
->protocol
.data
.state
.receive_payload
;
3616 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3617 char data_buffer
[chunk_size
];
3618 bool partial_recv
= false;
3619 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3620 uint64_t left_to_receive
= state
->left_to_receive
;
3621 struct relay_session
*session
;
3623 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3624 state
->header
.stream_id
, state
->header
.net_seq_num
,
3625 state
->received
, left_to_receive
);
3627 stream
= stream_get_by_id(state
->header
.stream_id
);
3629 /* Protocol error. */
3630 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3631 state
->header
.stream_id
);
3632 status
= RELAY_CONNECTION_STATUS_ERROR
;
3636 pthread_mutex_lock(&stream
->lock
);
3637 session
= stream
->trace
->session
;
3638 if (!conn
->session
) {
3639 ret
= connection_set_session(conn
, session
);
3641 status
= RELAY_CONNECTION_STATUS_ERROR
;
3642 goto end_stream_unlock
;
3647 * The size of the "chunk" received on any iteration is bounded by:
3648 * - the data left to receive,
3649 * - the data immediately available on the socket,
3650 * - the on-stack data buffer
3652 while (left_to_receive
> 0 && !partial_recv
) {
3653 size_t recv_size
= std::min
<uint64_t>(left_to_receive
, chunk_size
);
3654 struct lttng_buffer_view packet_chunk
;
3656 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3657 recv_size
, MSG_DONTWAIT
);
3660 DIAGNOSTIC_IGNORE_LOGICAL_OP
3661 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3663 PERROR("Socket %d error", conn
->sock
->fd
);
3664 status
= RELAY_CONNECTION_STATUS_ERROR
;
3666 goto end_stream_unlock
;
3667 } else if (ret
== 0) {
3668 /* No more data ready to be consumed on socket. */
3669 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3670 state
->header
.stream_id
);
3671 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3673 } else if (ret
< (int) recv_size
) {
3675 * All the data available on the socket has been
3678 partial_recv
= true;
3682 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3684 LTTNG_ASSERT(packet_chunk
.data
);
3686 ret
= stream_write(stream
, &packet_chunk
, 0);
3688 ERR("Relay error writing data to file");
3689 status
= RELAY_CONNECTION_STATUS_ERROR
;
3690 goto end_stream_unlock
;
3693 left_to_receive
-= recv_size
;
3694 state
->received
+= recv_size
;
3695 state
->left_to_receive
= left_to_receive
;
3698 if (state
->left_to_receive
> 0) {
3700 * Did not receive all the data expected, wait for more data to
3701 * become available on the socket.
3703 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3704 state
->header
.stream_id
, state
->received
,
3705 state
->left_to_receive
);
3706 goto end_stream_unlock
;
3709 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3711 status
= RELAY_CONNECTION_STATUS_ERROR
;
3712 goto end_stream_unlock
;
3715 if (session_streams_have_index(session
)) {
3716 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3717 state
->rotate_index
, &index_flushed
,
3718 state
->header
.data_size
+ state
->header
.padding_size
);
3720 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3721 stream
->stream_handle
,
3722 state
->header
.net_seq_num
, ret
);
3723 status
= RELAY_CONNECTION_STATUS_ERROR
;
3724 goto end_stream_unlock
;
3728 if (stream
->prev_data_seq
== -1ULL) {
3732 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3733 state
->header
.padding_size
, state
->header
.net_seq_num
,
3736 status
= RELAY_CONNECTION_STATUS_ERROR
;
3737 goto end_stream_unlock
;
3741 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3742 * contents of *state which are aliased (union) to the same location as
3743 * the new state. Don't use it beyond this point.
3745 connection_reset_protocol_state(conn
);
3749 close_requested
= stream
->close_requested
;
3750 pthread_mutex_unlock(&stream
->lock
);
3751 if (close_requested
&& left_to_receive
== 0) {
3752 try_stream_close(stream
);
3756 pthread_mutex_lock(&session
->lock
);
3757 uatomic_set(&session
->new_streams
, 1);
3758 pthread_mutex_unlock(&session
->lock
);
3767 * relay_process_data: Process the data received on the data socket
3769 static enum relay_connection_status
relay_process_data(
3770 struct relay_connection
*conn
)
3772 enum relay_connection_status status
;
3774 switch (conn
->protocol
.data
.state_id
) {
3775 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3776 status
= relay_process_data_receive_header(conn
);
3778 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3779 status
= relay_process_data_receive_payload(conn
);
3782 ERR("Unexpected data connection communication state.");
3789 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3793 (void) lttng_poll_del(events
, pollfd
);
3795 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3796 fd_tracker_util_close_fd
, NULL
);
3798 ERR("Closing pollfd %d", pollfd
);
3802 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3803 int pollfd
, struct relay_connection
*conn
)
3805 const char *type_str
;
3807 switch (conn
->type
) {
3812 type_str
= "Control";
3814 case RELAY_VIEWER_COMMAND
:
3815 type_str
= "Viewer Command";
3817 case RELAY_VIEWER_NOTIFICATION
:
3818 type_str
= "Viewer Notification";
3821 type_str
= "Unknown";
3823 cleanup_connection_pollfd(events
, pollfd
);
3824 connection_put(conn
);
3825 DBG("%s connection closed with %d", type_str
, pollfd
);
3829 * This thread does the actual work
3831 static void *relay_thread_worker(void *data
__attribute__((unused
)))
3833 int ret
, err
= -1, last_seen_data_fd
= -1;
3835 struct lttng_poll_event events
;
3836 struct lttng_ht
*relay_connections_ht
;
3837 struct lttng_ht_iter iter
;
3838 struct relay_connection
*destroy_conn
= NULL
;
3840 DBG("[thread] Relay worker started");
3842 rcu_register_thread();
3844 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3846 if (testpoint(relayd_thread_worker
)) {
3847 goto error_testpoint
;
3850 health_code_update();
3852 /* table of connections indexed on socket */
3853 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3854 if (!relay_connections_ht
) {
3855 goto relay_connections_ht_error
;
3858 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3860 goto error_poll_create
;
3863 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3870 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3872 health_code_update();
3874 /* Infinite blocking call, waiting for transmission */
3875 DBG3("Relayd worker thread polling...");
3876 health_poll_entry();
3877 ret
= lttng_poll_wait(&events
, -1);
3881 * Restart interrupted system call.
3883 if (errno
== EINTR
) {
3892 * Process control. The control connection is
3893 * prioritized so we don't starve it with high
3894 * throughput tracing data on the data connection.
3896 for (i
= 0; i
< nb_fd
; i
++) {
3897 /* Fetch once the poll data */
3898 const auto revents
= LTTNG_POLL_GETEV(&events
, i
);
3899 const auto pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3901 health_code_update();
3903 /* Activity on thread quit pipe, exiting. */
3904 if (relayd_is_thread_quit_pipe(pollfd
)) {
3905 DBG("Activity on thread quit pipe");
3910 /* Inspect the relay conn pipe for new connection */
3911 if (pollfd
== relay_conn_pipe
[0]) {
3912 if (revents
& LPOLLIN
) {
3913 struct relay_connection
*conn
;
3915 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3919 ret
= lttng_poll_add(&events
,
3921 LPOLLIN
| LPOLLRDHUP
);
3923 ERR("Failed to add new connection file descriptor to poll set");
3926 connection_ht_add(relay_connections_ht
, conn
);
3927 DBG("Connection socket %d added", conn
->sock
->fd
);
3928 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3929 ERR("Relay connection pipe error");
3932 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3936 struct relay_connection
*ctrl_conn
;
3938 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3939 /* If not found, there is a synchronization issue. */
3940 LTTNG_ASSERT(ctrl_conn
);
3942 if (ctrl_conn
->type
== RELAY_DATA
) {
3943 if (revents
& LPOLLIN
) {
3945 * Flag the last seen data fd not deleted. It will be
3946 * used as the last seen fd if any fd gets deleted in
3949 last_notdel_data_fd
= pollfd
;
3951 goto put_ctrl_connection
;
3953 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
3955 if (revents
& LPOLLIN
) {
3956 enum relay_connection_status status
;
3958 status
= relay_process_control(ctrl_conn
);
3959 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3961 * On socket error flag the session as aborted to force
3962 * the cleanup of its stream otherwise it can leak
3963 * during the lifetime of the relayd.
3965 * This prevents situations in which streams can be
3966 * left opened because an index was received, the
3967 * control connection is closed, and the data
3968 * connection is closed (uncleanly) before the packet's
3971 * Since the control connection encountered an error,
3972 * it is okay to be conservative and close the
3973 * session right now as we can't rely on the protocol
3974 * being respected anymore.
3976 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3977 session_abort(ctrl_conn
->session
);
3980 /* Clear the connection on error or close. */
3981 relay_thread_close_connection(&events
,
3986 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3987 relay_thread_close_connection(&events
,
3989 if (last_seen_data_fd
== pollfd
) {
3990 last_seen_data_fd
= last_notdel_data_fd
;
3993 ERR("Unexpected poll events %u for control sock %d",
3995 connection_put(ctrl_conn
);
3998 put_ctrl_connection
:
3999 connection_put(ctrl_conn
);
4004 * The last loop handled a control request, go back to poll to make
4005 * sure we prioritise the control socket.
4011 if (last_seen_data_fd
>= 0) {
4012 for (i
= 0; i
< nb_fd
; i
++) {
4013 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4015 health_code_update();
4017 if (last_seen_data_fd
== pollfd
) {
4024 /* Process data connection. */
4025 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4026 /* Fetch the poll data. */
4027 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4028 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4029 struct relay_connection
*data_conn
;
4031 health_code_update();
4034 /* No activity for this FD (poll implementation). */
4038 /* Skip the command pipe. It's handled in the first loop. */
4039 if (pollfd
== relay_conn_pipe
[0]) {
4043 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4045 /* Skip it. Might be removed before. */
4048 if (data_conn
->type
== RELAY_CONTROL
) {
4049 goto put_data_connection
;
4051 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4053 if (revents
& LPOLLIN
) {
4054 enum relay_connection_status status
;
4056 status
= relay_process_data(data_conn
);
4057 /* Connection closed or error. */
4058 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4060 * On socket error flag the session as aborted to force
4061 * the cleanup of its stream otherwise it can leak
4062 * during the lifetime of the relayd.
4064 * This prevents situations in which streams can be
4065 * left opened because an index was received, the
4066 * control connection is closed, and the data
4067 * connection is closed (uncleanly) before the packet's
4070 * Since the data connection encountered an error,
4071 * it is okay to be conservative and close the
4072 * session right now as we can't rely on the protocol
4073 * being respected anymore.
4075 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4076 session_abort(data_conn
->session
);
4078 relay_thread_close_connection(&events
, pollfd
,
4081 * Every goto restart call sets the last seen fd where
4082 * here we don't really care since we gracefully
4083 * continue the loop after the connection is deleted.
4086 /* Keep last seen port. */
4087 last_seen_data_fd
= pollfd
;
4088 connection_put(data_conn
);
4091 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4092 relay_thread_close_connection(&events
, pollfd
,
4095 ERR("Unknown poll events %u for data sock %d",
4098 put_data_connection
:
4099 connection_put(data_conn
);
4101 last_seen_data_fd
= -1;
4104 /* Normal exit, no error */
4109 /* Cleanup remaining connection object. */
4111 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4114 health_code_update();
4116 session_abort(destroy_conn
->session
);
4119 * No need to grab another ref, because we own
4122 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4127 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4129 lttng_ht_destroy(relay_connections_ht
);
4130 relay_connections_ht_error
:
4131 /* Close relay conn pipes */
4132 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4135 DBG("Thread exited with error");
4137 DBG("Worker thread cleanup complete");
4141 ERR("Health error occurred in %s", __func__
);
4143 health_unregister(health_relayd
);
4144 rcu_unregister_thread();
4145 lttng_relay_stop_threads();
4150 * Create the relay command pipe to wake thread_manage_apps.
4151 * Closed in cleanup().
4153 static int create_relay_conn_pipe(void)
4155 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4156 "Relayd connection pipe", relay_conn_pipe
);
4159 static int stdio_open(void *data
__attribute__((unused
)), int *fds
)
4161 fds
[0] = fileno(stdout
);
4162 fds
[1] = fileno(stderr
);
4166 static int track_stdio(void)
4169 const char *names
[] = { "stdout", "stderr" };
4171 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4172 names
, 2, stdio_open
, NULL
);
4178 int main(int argc
, char **argv
)
4180 bool thread_is_rcu_registered
= false;
4181 int ret
= 0, retval
= 0;
4183 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4185 /* Parse environment variables */
4186 ret
= parse_env_options();
4194 * Command line arguments overwrite environment.
4197 if (set_options(argc
, argv
)) {
4202 if (set_signal_handler()) {
4207 relayd_config_log();
4209 if (opt_print_version
) {
4215 ret
= fclose(stdin
);
4217 PERROR("Failed to close stdin");
4221 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4223 /* Try to create directory if -o, --output is specified. */
4224 if (opt_output_path
) {
4225 if (*opt_output_path
!= '/') {
4226 ERR("Please specify an absolute path for -o, --output PATH");
4231 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4234 ERR("Unable to create %s", opt_output_path
);
4241 if (opt_daemon
|| opt_background
) {
4242 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4250 if (opt_working_directory
) {
4251 ret
= utils_change_working_directory(opt_working_directory
);
4253 /* All errors are already logged. */
4258 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4259 if (!sessiond_trace_chunk_registry
) {
4260 ERR("Failed to initialize session daemon trace chunk registry");
4266 * The RCU thread registration (and use, through the fd-tracker's
4267 * creation) is done after the daemonization to allow us to not
4268 * deal with liburcu's fork() management as the call RCU needs to
4271 rcu_register_thread();
4272 thread_is_rcu_registered
= true;
4274 output_path
= create_output_path("");
4276 ERR("Failed to get output path");
4280 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4281 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4284 ERR("Failed to format unlinked file directory path");
4288 the_fd_tracker
= fd_tracker_create(
4289 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4290 free(unlinked_file_directory_path
);
4291 if (!the_fd_tracker
) {
4296 ret
= track_stdio();
4302 /* Initialize thread health monitoring */
4303 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4304 if (!health_relayd
) {
4305 PERROR("health_app_create error");
4310 /* Create thread quit pipe */
4311 if (relayd_init_thread_quit_pipe()) {
4316 /* Setup the thread apps communication pipe. */
4317 if (create_relay_conn_pipe()) {
4322 /* Init relay command queue. */
4323 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4325 /* Initialize communication library */
4327 lttcomm_inet_init();
4329 /* tables of sessions indexed by session ID */
4330 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4336 /* tables of streams indexed by stream ID */
4337 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4338 if (!relay_streams_ht
) {
4343 /* tables of streams indexed by stream ID */
4344 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4345 if (!viewer_streams_ht
) {
4350 ret
= init_health_quit_pipe();
4356 /* Create thread to manage the client socket */
4357 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4358 thread_manage_health_relayd
, (void *) NULL
);
4361 PERROR("pthread_create health");
4366 /* Setup the dispatcher thread */
4367 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4368 relay_thread_dispatcher
, (void *) NULL
);
4371 PERROR("pthread_create dispatcher");
4373 goto exit_dispatcher_thread
;
4376 /* Setup the worker thread */
4377 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4378 relay_thread_worker
, NULL
);
4381 PERROR("pthread_create worker");
4383 goto exit_worker_thread
;
4386 /* Setup the listener thread */
4387 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4388 relay_thread_listener
, (void *) NULL
);
4391 PERROR("pthread_create listener");
4393 goto exit_listener_thread
;
4396 ret
= relayd_live_create(live_uri
);
4398 ERR("Starting live viewer threads");
4404 * This is where we start awaiting program completion (e.g. through
4405 * signal that asks threads to teardown).
4408 ret
= relayd_live_join();
4414 ret
= pthread_join(listener_thread
, &status
);
4417 PERROR("pthread_join listener_thread");
4421 exit_listener_thread
:
4422 ret
= pthread_join(worker_thread
, &status
);
4425 PERROR("pthread_join worker_thread");
4430 ret
= pthread_join(dispatcher_thread
, &status
);
4433 PERROR("pthread_join dispatcher_thread");
4436 exit_dispatcher_thread
:
4438 ret
= pthread_join(health_thread
, &status
);
4441 PERROR("pthread_join health_thread");
4446 * Wait for all pending call_rcu work to complete before tearing
4447 * down data structures. call_rcu worker may be trying to
4448 * perform lookups in those structures.
4453 /* Ensure all prior call_rcu are done. */
4456 if (thread_is_rcu_registered
) {
4457 rcu_unregister_thread();