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>
37 #include <lttng/lttng.h>
38 #include <common/common.h>
39 #include <common/compat/poll.h>
40 #include <common/compat/socket.h>
41 #include <common/compat/endian.h>
42 #include <common/compat/getenv.h>
43 #include <common/defaults.h>
44 #include <common/daemonize.h>
45 #include <common/futex.h>
46 #include <common/sessiond-comm/sessiond-comm.h>
47 #include <common/sessiond-comm/inet.h>
48 #include <common/sessiond-comm/relayd.h>
49 #include <common/uri.h>
50 #include <common/utils.h>
51 #include <common/path.h>
52 #include <common/align.h>
53 #include <common/config/session-config.h>
54 #include <common/dynamic-buffer.h>
55 #include <common/buffer-view.h>
56 #include <common/string-utils/format.h>
57 #include <common/fd-tracker/fd-tracker.h>
58 #include <common/fd-tracker/utils.h>
60 #include "backward-compatibility-group-by.h"
62 #include "connection.h"
63 #include "ctf-trace.h"
64 #include "health-relayd.h"
67 #include "lttng-relayd.h"
69 #include "sessiond-trace-chunks.h"
71 #include "tcp_keep_alive.h"
72 #include "testpoint.h"
73 #include "tracefile-array.h"
76 #include "viewer-stream.h"
78 static const char *help_msg
=
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
86 enum relay_connection_status
{
87 RELAY_CONNECTION_STATUS_OK
,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR
,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED
,
94 /* command line options */
95 char *opt_output_path
, *opt_working_directory
;
96 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
97 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
103 #define NR_LTTNG_RELAY_READY 3
104 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
106 /* Size of receive buffer. */
107 #define RECV_DATA_BUFFER_SIZE 65536
109 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
110 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
112 static struct lttng_uri
*control_uri
;
113 static struct lttng_uri
*data_uri
;
114 static struct lttng_uri
*live_uri
;
116 const char *progname
;
118 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
119 static int tracing_group_name_override
;
121 const char * const config_section_name
= "relayd";
124 * Quit pipe for all threads. This permits a single cancellation point
125 * for all threads when receiving an event on the pipe.
127 int thread_quit_pipe
[2] = { -1, -1 };
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
, void *unused
)
406 if (!entry
|| !entry
->name
|| !entry
->value
) {
411 /* Check if the option is to be ignored */
412 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
413 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
418 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
419 /* Ignore if entry name is not fully matched. */
420 if (strcmp(entry
->name
, long_options
[i
].name
)) {
425 * If the option takes no argument on the command line,
426 * we have to check if the value is "true". We support
427 * non-zero numeric values, true, on and yes.
429 if (!long_options
[i
].has_arg
) {
430 ret
= config_parse_value(entry
->value
);
433 WARN("Invalid configuration value \"%s\" for option %s",
434 entry
->value
, entry
->name
);
436 /* False, skip boolean config option. */
441 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
445 WARN("Unrecognized option \"%s\" in daemon configuration file.",
452 static int parse_env_options(void)
457 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
459 opt_working_directory
= strdup(value
);
460 if (!opt_working_directory
) {
461 ERR("Failed to allocate working directory string (\"%s\")",
469 static int set_fd_pool_size(void)
472 struct rlimit rlimit
;
474 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
476 PERROR("Failed to get file descriptor limit");
481 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
482 (uint64_t) rlimit
.rlim_cur
,
483 (uint64_t) rlimit
.rlim_max
);
484 if (lttng_opt_fd_pool_size
== -1) {
485 /* Use default value (soft limit - reserve). */
486 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
487 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
488 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
492 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
493 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
497 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
498 ERR("File descriptor pool size must be set to at least %d",
499 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
504 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
505 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
506 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
511 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
512 lttng_opt_fd_pool_size
,
513 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
514 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
519 static int set_options(int argc
, char **argv
)
521 int c
, ret
= 0, option_index
= 0, retval
= 0;
522 int orig_optopt
= optopt
, orig_optind
= optind
;
523 char *default_address
, *optstring
;
524 char *config_path
= NULL
;
526 optstring
= utils_generate_optstring(long_options
,
527 sizeof(long_options
) / sizeof(struct option
));
533 /* Check for the --config option */
535 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
536 &option_index
)) != -1) {
540 } else if (c
!= 'f') {
544 if (lttng_is_setuid_setgid()) {
545 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
549 config_path
= utils_expand_path(optarg
);
551 ERR("Failed to resolve path: %s", optarg
);
556 ret
= config_get_section_entries(config_path
, config_section_name
,
557 config_entry_handler
, NULL
);
560 ERR("Invalid configuration option at line %i", ret
);
566 /* Reset getopt's global state */
567 optopt
= orig_optopt
;
568 optind
= orig_optind
;
570 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
575 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
582 /* assign default values */
583 if (control_uri
== NULL
) {
584 ret
= asprintf(&default_address
,
585 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
586 DEFAULT_NETWORK_CONTROL_PORT
);
588 PERROR("asprintf default data address");
593 ret
= uri_parse(default_address
, &control_uri
);
594 free(default_address
);
596 ERR("Invalid control URI specified");
601 if (data_uri
== NULL
) {
602 ret
= asprintf(&default_address
,
603 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
604 DEFAULT_NETWORK_DATA_PORT
);
606 PERROR("asprintf default data address");
611 ret
= uri_parse(default_address
, &data_uri
);
612 free(default_address
);
614 ERR("Invalid data URI specified");
619 if (live_uri
== NULL
) {
620 ret
= asprintf(&default_address
,
621 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
622 DEFAULT_NETWORK_VIEWER_PORT
);
624 PERROR("asprintf default viewer control address");
629 ret
= uri_parse(default_address
, &live_uri
);
630 free(default_address
);
632 ERR("Invalid viewer control URI specified");
637 ret
= set_fd_pool_size();
643 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
644 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
646 if (opt_allow_clear
) {
647 /* Check if env variable exists. */
648 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
650 ret
= config_parse_value(value
);
652 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
656 opt_allow_clear
= !ret
;
666 static void print_global_objects(void)
668 print_viewer_streams();
669 print_relay_streams();
673 static int noop_close(void *data
, int *fds
)
678 static void untrack_stdio(void)
680 int fds
[] = { fileno(stdout
), fileno(stderr
) };
683 * noop_close is used since we don't really want to close
684 * the stdio output fds; we merely want to stop tracking them.
686 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
687 fds
, 2, noop_close
, NULL
);
693 static void relayd_cleanup(void)
695 print_global_objects();
699 if (viewer_streams_ht
)
700 lttng_ht_destroy(viewer_streams_ht
);
701 if (relay_streams_ht
)
702 lttng_ht_destroy(relay_streams_ht
);
704 lttng_ht_destroy(sessions_ht
);
706 free(opt_output_path
);
707 free(opt_working_directory
);
710 health_app_destroy(health_relayd
);
712 /* Close thread quit pipes */
713 if (health_quit_pipe
[0] != -1) {
714 (void) fd_tracker_util_pipe_close(
715 the_fd_tracker
, health_quit_pipe
);
717 if (thread_quit_pipe
[0] != -1) {
718 (void) fd_tracker_util_pipe_close(
719 the_fd_tracker
, thread_quit_pipe
);
721 if (sessiond_trace_chunk_registry
) {
722 sessiond_trace_chunk_registry_destroy(
723 sessiond_trace_chunk_registry
);
725 if (the_fd_tracker
) {
728 * fd_tracker_destroy() will log the contents of the fd-tracker
729 * if a leak is detected.
731 fd_tracker_destroy(the_fd_tracker
);
734 uri_free(control_uri
);
736 /* Live URI is freed in the live thread. */
738 if (tracing_group_name_override
) {
739 free((void *) tracing_group_name
);
744 * Write to writable pipe used to notify a thread.
746 static int notify_thread_pipe(int wpipe
)
750 ret
= lttng_write(wpipe
, "!", 1);
752 PERROR("write poll pipe");
760 static int notify_health_quit_pipe(int *pipe
)
764 ret
= lttng_write(pipe
[1], "4", 1);
766 PERROR("write relay health quit");
775 * Stop all relayd and relayd-live threads.
777 int lttng_relay_stop_threads(void)
781 /* Stopping all threads */
782 DBG("Terminating all threads");
783 if (notify_thread_pipe(thread_quit_pipe
[1])) {
784 ERR("write error on thread quit pipe");
788 if (notify_health_quit_pipe(health_quit_pipe
)) {
789 ERR("write error on health quit pipe");
792 /* Dispatch thread */
793 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
794 futex_nto1_wake(&relay_conn_queue
.futex
);
796 if (relayd_live_stop()) {
797 ERR("Error stopping live threads");
804 * Signal handler for the daemon
806 * Simply stop all worker threads, leaving main() return gracefully after
807 * joining all threads and calling cleanup().
809 static void sighandler(int sig
)
813 DBG("SIGINT caught");
814 if (lttng_relay_stop_threads()) {
815 ERR("Error stopping threads");
819 DBG("SIGTERM caught");
820 if (lttng_relay_stop_threads()) {
821 ERR("Error stopping threads");
825 CMM_STORE_SHARED(recv_child_signal
, 1);
833 * Setup signal handler for :
834 * SIGINT, SIGTERM, SIGPIPE
836 static int set_signal_handler(void)
842 if ((ret
= sigemptyset(&sigset
)) < 0) {
843 PERROR("sigemptyset");
850 sa
.sa_handler
= sighandler
;
851 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
856 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
861 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
866 sa
.sa_handler
= SIG_IGN
;
867 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
872 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
877 void lttng_relay_notify_ready(void)
879 /* Notify the parent of the fork() process that we are ready. */
880 if (opt_daemon
|| opt_background
) {
881 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
882 kill(child_ppid
, SIGUSR1
);
888 * Init thread quit pipe.
890 * Return -1 on error or 0 if all pipes are created.
892 static int init_thread_quit_pipe(void)
894 return fd_tracker_util_pipe_open_cloexec(
895 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
899 * Init health quit pipe.
901 * Return -1 on error or 0 if all pipes are created.
903 static int init_health_quit_pipe(void)
905 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
906 "Health quit pipe", health_quit_pipe
);
910 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
912 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
913 int size
, const char *name
)
917 if (events
== NULL
|| size
== 0) {
922 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
923 name
, events
, 1, LTTNG_CLOEXEC
);
925 PERROR("Failed to create \"%s\" poll file descriptor", name
);
930 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
942 * Check if the thread quit pipe was triggered.
944 * Return 1 if it was triggered else 0;
946 static int check_thread_quit_pipe(int fd
, uint32_t events
)
948 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
955 static int create_sock(void *data
, int *out_fd
)
958 struct lttcomm_sock
*sock
= data
;
960 ret
= lttcomm_create_sock(sock
);
970 static int close_sock(void *data
, int *in_fd
)
972 struct lttcomm_sock
*sock
= data
;
974 return sock
->ops
->close(sock
);
977 static int accept_sock(void *data
, int *out_fd
)
980 /* Socks is an array of in_sock, out_sock. */
981 struct lttcomm_sock
**socks
= data
;
982 struct lttcomm_sock
*in_sock
= socks
[0];
984 socks
[1] = in_sock
->ops
->accept(in_sock
);
989 *out_fd
= socks
[1]->fd
;
995 * Create and init socket from uri.
997 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
1001 struct lttcomm_sock
*sock
= NULL
;
1002 char uri_str
[PATH_MAX
];
1003 char *formated_name
= NULL
;
1005 sock
= lttcomm_alloc_sock_from_uri(uri
);
1007 ERR("Allocating socket");
1012 * Don't fail to create the socket if the name can't be built as it is
1013 * only used for debugging purposes.
1015 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1016 uri_str
[sizeof(uri_str
) - 1] = '\0';
1018 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1021 formated_name
= NULL
;
1025 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1026 (const char **) (formated_name
? &formated_name
: NULL
),
1027 1, create_sock
, sock
);
1029 PERROR("Failed to open \"%s\" relay socket",
1030 formated_name
?: "Unknown");
1033 DBG("Listening on %s socket %d", name
, sock
->fd
);
1035 ret
= sock
->ops
->bind(sock
);
1037 PERROR("Failed to bind socket");
1041 ret
= sock
->ops
->listen(sock
, -1);
1047 free(formated_name
);
1052 lttcomm_destroy_sock(sock
);
1054 free(formated_name
);
1059 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1063 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1064 struct lttcomm_sock
*new_sock
= NULL
;
1066 ret
= fd_tracker_open_unsuspendable_fd(
1067 the_fd_tracker
, &out_fd
,
1068 (const char **) &name
,
1069 1, accept_sock
, &socks
);
1073 new_sock
= socks
[1];
1074 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1080 * This thread manages the listening for new connections on the network
1082 static void *relay_thread_listener(void *data
)
1084 int i
, ret
, pollfd
, err
= -1;
1085 uint32_t revents
, nb_fd
;
1086 struct lttng_poll_event events
;
1087 struct lttcomm_sock
*control_sock
, *data_sock
;
1089 DBG("[thread] Relay listener started");
1091 rcu_register_thread();
1092 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1094 health_code_update();
1096 control_sock
= relay_socket_create(control_uri
, "Control listener");
1097 if (!control_sock
) {
1098 goto error_sock_control
;
1101 data_sock
= relay_socket_create(data_uri
, "Data listener");
1103 goto error_sock_relay
;
1107 * Pass 3 as size here for the thread quit pipe, control and
1110 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1112 goto error_create_poll
;
1115 /* Add the control socket */
1116 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1118 goto error_poll_add
;
1121 /* Add the data socket */
1122 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1124 goto error_poll_add
;
1127 lttng_relay_notify_ready();
1129 if (testpoint(relayd_thread_listener
)) {
1130 goto error_testpoint
;
1134 health_code_update();
1136 DBG("Listener accepting connections");
1139 health_poll_entry();
1140 ret
= lttng_poll_wait(&events
, -1);
1144 * Restart interrupted system call.
1146 if (errno
== EINTR
) {
1154 DBG("Relay new connection received");
1155 for (i
= 0; i
< nb_fd
; i
++) {
1156 health_code_update();
1158 /* Fetch once the poll data */
1159 revents
= LTTNG_POLL_GETEV(&events
, i
);
1160 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1162 /* Thread quit pipe has been closed. Killing thread. */
1163 ret
= check_thread_quit_pipe(pollfd
, revents
);
1169 if (revents
& LPOLLIN
) {
1171 * A new connection is requested, therefore a
1172 * sessiond/consumerd connection is allocated in
1173 * this thread, enqueued to a global queue and
1174 * dequeued (and freed) in the worker thread.
1177 struct relay_connection
*new_conn
;
1178 struct lttcomm_sock
*newsock
= NULL
;
1179 enum connection_type type
;
1181 if (pollfd
== data_sock
->fd
) {
1183 newsock
= accept_relayd_sock(data_sock
,
1184 "Data socket to relayd");
1186 assert(pollfd
== control_sock
->fd
);
1187 type
= RELAY_CONTROL
;
1188 newsock
= accept_relayd_sock(control_sock
,
1189 "Control socket to relayd");
1192 PERROR("accepting sock");
1196 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1199 PERROR("setsockopt inet");
1200 lttcomm_destroy_sock(newsock
);
1204 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1206 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1208 lttcomm_destroy_sock(newsock
);
1212 new_conn
= connection_create(newsock
, type
);
1214 lttcomm_destroy_sock(newsock
);
1218 /* Enqueue request for the dispatcher thread. */
1219 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1223 * Wake the dispatch queue futex.
1224 * Implicit memory barrier with the
1225 * exchange in cds_wfcq_enqueue.
1227 futex_nto1_wake(&relay_conn_queue
.futex
);
1228 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1229 ERR("socket poll error");
1232 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1242 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1244 if (data_sock
->fd
>= 0) {
1245 int data_sock_fd
= data_sock
->fd
;
1247 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1248 &data_sock_fd
, 1, close_sock
,
1251 PERROR("Failed to close the data listener socket file descriptor");
1255 lttcomm_destroy_sock(data_sock
);
1257 if (control_sock
->fd
>= 0) {
1258 int control_sock_fd
= control_sock
->fd
;
1260 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1261 &control_sock_fd
, 1, close_sock
,
1264 PERROR("Failed to close the control listener socket file descriptor");
1266 control_sock
->fd
= -1;
1268 lttcomm_destroy_sock(control_sock
);
1272 ERR("Health error occurred in %s", __func__
);
1274 health_unregister(health_relayd
);
1275 rcu_unregister_thread();
1276 DBG("Relay listener thread cleanup complete");
1277 lttng_relay_stop_threads();
1282 * This thread manages the dispatching of the requests to worker threads
1284 static void *relay_thread_dispatcher(void *data
)
1288 struct cds_wfcq_node
*node
;
1289 struct relay_connection
*new_conn
= NULL
;
1291 DBG("[thread] Relay dispatcher started");
1293 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1295 if (testpoint(relayd_thread_dispatcher
)) {
1296 goto error_testpoint
;
1299 health_code_update();
1302 health_code_update();
1304 /* Atomically prepare the queue futex */
1305 futex_nto1_prepare(&relay_conn_queue
.futex
);
1307 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1312 health_code_update();
1314 /* Dequeue commands */
1315 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1316 &relay_conn_queue
.tail
);
1318 DBG("Woken up but nothing in the relay command queue");
1319 /* Continue thread execution */
1322 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1324 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1327 * Inform worker thread of the new request. This
1328 * call is blocking so we can be assured that
1329 * the data will be read at some point in time
1330 * or wait to the end of the world :)
1332 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1334 PERROR("write connection pipe");
1335 connection_put(new_conn
);
1338 } while (node
!= NULL
);
1340 /* Futex wait on queue. Blocking call on futex() */
1341 health_poll_entry();
1342 futex_nto1_wait(&relay_conn_queue
.futex
);
1346 /* Normal exit, no error */
1353 ERR("Health error occurred in %s", __func__
);
1355 health_unregister(health_relayd
);
1356 DBG("Dispatch thread dying");
1357 lttng_relay_stop_threads();
1361 static bool session_streams_have_index(const struct relay_session
*session
)
1363 return session
->minor
>= 4 && !session
->snapshot
;
1367 * Handle the RELAYD_CREATE_SESSION command.
1369 * On success, send back the session id or else return a negative value.
1371 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1372 struct relay_connection
*conn
,
1373 const struct lttng_buffer_view
*payload
)
1377 struct relay_session
*session
= NULL
;
1378 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1379 char session_name
[LTTNG_NAME_MAX
] = {};
1380 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1381 uint32_t live_timer
= 0;
1382 bool snapshot
= false;
1383 bool session_name_contains_creation_timestamp
= false;
1384 /* Left nil for peers < 2.11. */
1385 char base_path
[LTTNG_PATH_MAX
] = {};
1386 lttng_uuid sessiond_uuid
= {};
1387 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1388 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1389 LTTNG_OPTIONAL(time_t) creation_time
= {};
1390 struct lttng_dynamic_buffer reply_payload
;
1392 lttng_dynamic_buffer_init(&reply_payload
);
1394 if (conn
->minor
< 4) {
1395 /* From 2.1 to 2.3 */
1397 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1398 /* From 2.4 to 2.10 */
1399 ret
= cmd_create_session_2_4(payload
, session_name
,
1400 hostname
, &live_timer
, &snapshot
);
1402 bool has_current_chunk
;
1403 uint64_t current_chunk_id_value
;
1404 time_t creation_time_value
;
1405 uint64_t id_sessiond_value
;
1407 /* From 2.11 to ... */
1408 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1409 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1410 sessiond_uuid
, &has_current_chunk
,
1411 ¤t_chunk_id_value
, &creation_time_value
,
1412 &session_name_contains_creation_timestamp
);
1413 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1414 /* The nil UUID is reserved for pre-2.11 clients. */
1415 ERR("Illegal nil UUID announced by peer in create session command");
1419 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1420 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1421 if (has_current_chunk
) {
1422 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1423 current_chunk_id_value
);
1431 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1432 snapshot
, sessiond_uuid
,
1433 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1434 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1435 creation_time
.is_set
? &creation_time
.value
: NULL
,
1436 conn
->major
, conn
->minor
,
1437 session_name_contains_creation_timestamp
);
1442 assert(!conn
->session
);
1443 conn
->session
= session
;
1444 DBG("Created session %" PRIu64
, session
->id
);
1446 reply
.generic
.session_id
= htobe64(session
->id
);
1450 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1452 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1455 if (conn
->minor
< 11) {
1456 /* From 2.1 to 2.10 */
1457 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1458 &reply
.generic
, sizeof(reply
.generic
));
1460 ERR("Failed to append \"create session\" command reply header to payload buffer");
1465 const uint32_t output_path_length
=
1466 session
? strlen(session
->output_path
) + 1 : 0;
1468 reply
.output_path_length
= htobe32(output_path_length
);
1469 ret
= lttng_dynamic_buffer_append(
1470 &reply_payload
, &reply
, sizeof(reply
));
1472 ERR("Failed to append \"create session\" command reply header to payload buffer");
1476 if (output_path_length
) {
1477 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1478 session
->output_path
,
1479 output_path_length
);
1481 ERR("Failed to append \"create session\" command reply path to payload buffer");
1487 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1488 reply_payload
.size
, 0);
1489 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1490 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1491 reply_payload
.size
, send_ret
);
1495 if (ret
< 0 && session
) {
1496 session_put(session
);
1498 lttng_dynamic_buffer_reset(&reply_payload
);
1503 * When we have received all the streams and the metadata for a channel,
1504 * we make them visible to the viewer threads.
1506 static void publish_connection_local_streams(struct relay_connection
*conn
)
1508 struct relay_stream
*stream
;
1509 struct relay_session
*session
= conn
->session
;
1512 * We publish all streams belonging to a session atomically wrt
1515 pthread_mutex_lock(&session
->lock
);
1517 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1519 stream_publish(stream
);
1524 * Inform the viewer that there are new streams in the session.
1526 if (session
->viewer_attached
) {
1527 uatomic_set(&session
->new_streams
, 1);
1530 pthread_mutex_unlock(&session
->lock
);
1533 static int conform_channel_path(char *channel_path
)
1537 if (strstr("../", channel_path
)) {
1538 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1544 if (*channel_path
== '/') {
1545 const size_t len
= strlen(channel_path
);
1548 * Channel paths from peers prior to 2.11 are expressed as an
1549 * absolute path that is, in reality, relative to the relay
1550 * daemon's output directory. Remove the leading slash so it
1551 * is correctly interpreted as a relative path later on.
1553 * len (and not len - 1) is used to copy the trailing NULL.
1555 bcopy(channel_path
+ 1, channel_path
, len
);
1562 * relay_add_stream: allocate a new stream for a session
1564 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1565 struct relay_connection
*conn
,
1566 const struct lttng_buffer_view
*payload
)
1570 struct relay_session
*session
= conn
->session
;
1571 struct relay_stream
*stream
= NULL
;
1572 struct lttcomm_relayd_status_stream reply
;
1573 struct ctf_trace
*trace
= NULL
;
1574 uint64_t stream_handle
= -1ULL;
1575 char *path_name
= NULL
, *channel_name
= NULL
;
1576 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1577 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1579 if (!session
|| !conn
->version_check_done
) {
1580 ERR("Trying to add a stream before version check");
1582 goto end_no_session
;
1585 if (session
->minor
== 1) {
1587 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1589 } else if (session
->minor
> 1 && session
->minor
< 11) {
1590 /* From 2.2 to 2.10 */
1591 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1592 &channel_name
, &tracefile_size
, &tracefile_count
);
1594 /* From 2.11 to ... */
1595 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1596 &channel_name
, &tracefile_size
, &tracefile_count
,
1597 &stream_chunk_id
.value
);
1598 stream_chunk_id
.is_set
= true;
1605 if (conform_channel_path(path_name
)) {
1610 * Backward compatibility for --group-output-by-session.
1611 * Prior to lttng 2.11, the complete path is passed by the stream.
1612 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1613 * >=2.11 the chunk is responsible for the output path. When dealing
1614 * with producer < 2.11 the chunk output_path is the root output path
1615 * and the stream carries the complete path (path_name).
1616 * To support --group-output-by-session with older producer (<2.11), we
1617 * need to craft the path based on the stream path.
1619 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1620 if (conn
->minor
< 4) {
1622 * From 2.1 to 2.3, the session_name is not passed on
1623 * the RELAYD_CREATE_SESSION command. The session name
1624 * is necessary to detect the presence of a base_path
1625 * inside the stream path. Without it we cannot perform
1626 * a valid group-output-by-session transformation.
1628 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1629 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1630 session
->id
, path_name
);
1631 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1632 char *group_by_session_path_name
;
1634 assert(session
->session_name
[0] != '\0');
1636 group_by_session_path_name
=
1637 backward_compat_group_by_session(
1639 session
->session_name
,
1640 session
->creation_time
.value
);
1641 if (!group_by_session_path_name
) {
1642 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1647 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1648 path_name
, group_by_session_path_name
);
1651 path_name
= group_by_session_path_name
;
1655 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1660 /* This stream here has one reference on the trace. */
1661 pthread_mutex_lock(&last_relay_stream_id_lock
);
1662 stream_handle
= ++last_relay_stream_id
;
1663 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1665 /* We pass ownership of path_name and channel_name. */
1666 stream
= stream_create(trace
, stream_handle
, path_name
,
1667 channel_name
, tracefile_size
, tracefile_count
);
1669 channel_name
= NULL
;
1672 * Streams are the owners of their trace. Reference to trace is
1673 * kept within stream_create().
1675 ctf_trace_put(trace
);
1678 memset(&reply
, 0, sizeof(reply
));
1679 reply
.handle
= htobe64(stream_handle
);
1681 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1683 reply
.ret_code
= htobe32(LTTNG_OK
);
1686 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1687 sizeof(struct lttcomm_relayd_status_stream
), 0);
1688 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1689 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1701 * relay_close_stream: close a specific stream
1703 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1704 struct relay_connection
*conn
,
1705 const struct lttng_buffer_view
*payload
)
1709 struct relay_session
*session
= conn
->session
;
1710 struct lttcomm_relayd_close_stream stream_info
;
1711 struct lttcomm_relayd_generic_reply reply
;
1712 struct relay_stream
*stream
;
1714 DBG("Close stream received");
1716 if (!session
|| !conn
->version_check_done
) {
1717 ERR("Trying to close a stream before version check");
1719 goto end_no_session
;
1722 if (payload
->size
< sizeof(stream_info
)) {
1723 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1724 sizeof(stream_info
), payload
->size
);
1726 goto end_no_session
;
1728 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1729 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1730 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1732 stream
= stream_get_by_id(stream_info
.stream_id
);
1739 * Set last_net_seq_num before the close flag. Required by data
1742 pthread_mutex_lock(&stream
->lock
);
1743 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1744 pthread_mutex_unlock(&stream
->lock
);
1747 * This is one of the conditions which may trigger a stream close
1748 * with the others being:
1749 * 1) A close command is received for a stream
1750 * 2) The control connection owning the stream is closed
1751 * 3) We have received all of the stream's data _after_ a close
1754 try_stream_close(stream
);
1759 memset(&reply
, 0, sizeof(reply
));
1761 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1763 reply
.ret_code
= htobe32(LTTNG_OK
);
1765 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1766 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1767 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1768 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1778 * relay_reset_metadata: reset a metadata stream
1781 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1782 struct relay_connection
*conn
,
1783 const struct lttng_buffer_view
*payload
)
1787 struct relay_session
*session
= conn
->session
;
1788 struct lttcomm_relayd_reset_metadata stream_info
;
1789 struct lttcomm_relayd_generic_reply reply
;
1790 struct relay_stream
*stream
;
1792 DBG("Reset metadata received");
1794 if (!session
|| !conn
->version_check_done
) {
1795 ERR("Trying to reset a metadata stream before version check");
1797 goto end_no_session
;
1800 if (payload
->size
< sizeof(stream_info
)) {
1801 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1802 sizeof(stream_info
), payload
->size
);
1804 goto end_no_session
;
1806 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1807 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1808 stream_info
.version
= be64toh(stream_info
.version
);
1810 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1812 /* Unsupported for live sessions for now. */
1813 if (session
->live_timer
!= 0) {
1818 stream
= stream_get_by_id(stream_info
.stream_id
);
1823 pthread_mutex_lock(&stream
->lock
);
1824 if (!stream
->is_metadata
) {
1829 ret
= stream_reset_file(stream
);
1831 ERR("Failed to reset metadata stream %" PRIu64
1832 ": stream_path = %s, channel = %s",
1833 stream
->stream_handle
, stream
->path_name
,
1834 stream
->channel_name
);
1838 pthread_mutex_unlock(&stream
->lock
);
1842 memset(&reply
, 0, sizeof(reply
));
1844 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1846 reply
.ret_code
= htobe32(LTTNG_OK
);
1848 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1849 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1850 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1851 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1861 * relay_unknown_command: send -1 if received unknown command
1863 static void relay_unknown_command(struct relay_connection
*conn
)
1865 struct lttcomm_relayd_generic_reply reply
;
1868 memset(&reply
, 0, sizeof(reply
));
1869 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1870 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1871 if (send_ret
< sizeof(reply
)) {
1872 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1877 * relay_start: send an acknowledgment to the client to tell if we are
1878 * ready to receive data. We are ready if a session is established.
1880 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1881 struct relay_connection
*conn
,
1882 const struct lttng_buffer_view
*payload
)
1886 struct lttcomm_relayd_generic_reply reply
;
1887 struct relay_session
*session
= conn
->session
;
1890 DBG("Trying to start the streaming without a session established");
1891 ret
= htobe32(LTTNG_ERR_UNK
);
1894 memset(&reply
, 0, sizeof(reply
));
1895 reply
.ret_code
= htobe32(LTTNG_OK
);
1896 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1898 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1899 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1908 * relay_recv_metadata: receive the metadata for the session.
1910 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1911 struct relay_connection
*conn
,
1912 const struct lttng_buffer_view
*payload
)
1915 struct relay_session
*session
= conn
->session
;
1916 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1917 struct relay_stream
*metadata_stream
;
1918 uint64_t metadata_payload_size
;
1919 struct lttng_buffer_view packet_view
;
1922 ERR("Metadata sent before version check");
1927 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1928 ERR("Incorrect data size");
1932 metadata_payload_size
= recv_hdr
->data_size
-
1933 sizeof(struct lttcomm_relayd_metadata_payload
);
1935 memcpy(&metadata_payload_header
, payload
->data
,
1936 sizeof(metadata_payload_header
));
1937 metadata_payload_header
.stream_id
= be64toh(
1938 metadata_payload_header
.stream_id
);
1939 metadata_payload_header
.padding_size
= be32toh(
1940 metadata_payload_header
.padding_size
);
1942 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1943 if (!metadata_stream
) {
1948 packet_view
= lttng_buffer_view_from_view(payload
,
1949 sizeof(metadata_payload_header
), metadata_payload_size
);
1950 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1951 ERR("Invalid metadata packet length announced by header");
1956 pthread_mutex_lock(&metadata_stream
->lock
);
1957 ret
= stream_write(metadata_stream
, &packet_view
,
1958 metadata_payload_header
.padding_size
);
1959 pthread_mutex_unlock(&metadata_stream
->lock
);
1965 stream_put(metadata_stream
);
1971 * relay_send_version: send relayd version number
1973 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1974 struct relay_connection
*conn
,
1975 const struct lttng_buffer_view
*payload
)
1979 struct lttcomm_relayd_version reply
, msg
;
1980 bool compatible
= true;
1982 conn
->version_check_done
= true;
1984 /* Get version from the other side. */
1985 if (payload
->size
< sizeof(msg
)) {
1986 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1987 sizeof(msg
), payload
->size
);
1992 memcpy(&msg
, payload
->data
, sizeof(msg
));
1993 msg
.major
= be32toh(msg
.major
);
1994 msg
.minor
= be32toh(msg
.minor
);
1996 memset(&reply
, 0, sizeof(reply
));
1997 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1998 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2000 /* Major versions must be the same */
2001 if (reply
.major
!= msg
.major
) {
2002 DBG("Incompatible major versions (%u vs %u), deleting session",
2003 reply
.major
, msg
.major
);
2007 conn
->major
= reply
.major
;
2008 /* We adapt to the lowest compatible version */
2009 if (reply
.minor
<= msg
.minor
) {
2010 conn
->minor
= reply
.minor
;
2012 conn
->minor
= msg
.minor
;
2015 reply
.major
= htobe32(reply
.major
);
2016 reply
.minor
= htobe32(reply
.minor
);
2017 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2019 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2020 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2033 DBG("Version check done using protocol %u.%u", conn
->major
,
2041 * Check for data pending for a given stream id from the session daemon.
2043 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2044 struct relay_connection
*conn
,
2045 const struct lttng_buffer_view
*payload
)
2047 struct relay_session
*session
= conn
->session
;
2048 struct lttcomm_relayd_data_pending msg
;
2049 struct lttcomm_relayd_generic_reply reply
;
2050 struct relay_stream
*stream
;
2053 uint64_t stream_seq
;
2055 DBG("Data pending command received");
2057 if (!session
|| !conn
->version_check_done
) {
2058 ERR("Trying to check for data before version check");
2060 goto end_no_session
;
2063 if (payload
->size
< sizeof(msg
)) {
2064 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2065 sizeof(msg
), payload
->size
);
2067 goto end_no_session
;
2069 memcpy(&msg
, payload
->data
, sizeof(msg
));
2070 msg
.stream_id
= be64toh(msg
.stream_id
);
2071 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2073 stream
= stream_get_by_id(msg
.stream_id
);
2074 if (stream
== NULL
) {
2079 pthread_mutex_lock(&stream
->lock
);
2081 if (session_streams_have_index(session
)) {
2083 * Ensure that both the index and stream data have been
2084 * flushed up to the requested point.
2086 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2088 stream_seq
= stream
->prev_data_seq
;
2090 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2091 ", prev_index_seq %" PRIu64
2092 ", and last_seq %" PRIu64
, msg
.stream_id
,
2093 stream
->prev_data_seq
, stream
->prev_index_seq
,
2094 msg
.last_net_seq_num
);
2096 /* Avoid wrapping issue */
2097 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2098 /* Data has in fact been written and is NOT pending */
2101 /* Data still being streamed thus pending */
2105 stream
->data_pending_check_done
= true;
2106 pthread_mutex_unlock(&stream
->lock
);
2111 memset(&reply
, 0, sizeof(reply
));
2112 reply
.ret_code
= htobe32(ret
);
2113 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2114 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2115 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2125 * Wait for the control socket to reach a quiescent state.
2127 * Note that for now, when receiving this command from the session
2128 * daemon, this means that every subsequent commands or data received on
2129 * the control socket has been handled. So, this is why we simply return
2132 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2133 struct relay_connection
*conn
,
2134 const struct lttng_buffer_view
*payload
)
2138 struct relay_stream
*stream
;
2139 struct lttcomm_relayd_quiescent_control msg
;
2140 struct lttcomm_relayd_generic_reply reply
;
2142 DBG("Checking quiescent state on control socket");
2144 if (!conn
->session
|| !conn
->version_check_done
) {
2145 ERR("Trying to check for data before version check");
2147 goto end_no_session
;
2150 if (payload
->size
< sizeof(msg
)) {
2151 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2152 sizeof(msg
), payload
->size
);
2154 goto end_no_session
;
2156 memcpy(&msg
, payload
->data
, sizeof(msg
));
2157 msg
.stream_id
= be64toh(msg
.stream_id
);
2159 stream
= stream_get_by_id(msg
.stream_id
);
2163 pthread_mutex_lock(&stream
->lock
);
2164 stream
->data_pending_check_done
= true;
2165 pthread_mutex_unlock(&stream
->lock
);
2167 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2170 memset(&reply
, 0, sizeof(reply
));
2171 reply
.ret_code
= htobe32(LTTNG_OK
);
2172 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2173 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2174 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2186 * Initialize a data pending command. This means that a consumer is about
2187 * to ask for data pending for each stream it holds. Simply iterate over
2188 * all streams of a session and set the data_pending_check_done flag.
2190 * This command returns to the client a LTTNG_OK code.
2192 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2193 struct relay_connection
*conn
,
2194 const struct lttng_buffer_view
*payload
)
2198 struct lttng_ht_iter iter
;
2199 struct lttcomm_relayd_begin_data_pending msg
;
2200 struct lttcomm_relayd_generic_reply reply
;
2201 struct relay_stream
*stream
;
2206 DBG("Init streams for data pending");
2208 if (!conn
->session
|| !conn
->version_check_done
) {
2209 ERR("Trying to check for data before version check");
2211 goto end_no_session
;
2214 if (payload
->size
< sizeof(msg
)) {
2215 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2216 sizeof(msg
), payload
->size
);
2218 goto end_no_session
;
2220 memcpy(&msg
, payload
->data
, sizeof(msg
));
2221 msg
.session_id
= be64toh(msg
.session_id
);
2224 * Iterate over all streams to set the begin data pending flag.
2225 * For now, the streams are indexed by stream handle so we have
2226 * to iterate over all streams to find the one associated with
2227 * the right session_id.
2230 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2232 if (!stream_get(stream
)) {
2235 if (stream
->trace
->session
->id
== msg
.session_id
) {
2236 pthread_mutex_lock(&stream
->lock
);
2237 stream
->data_pending_check_done
= false;
2238 pthread_mutex_unlock(&stream
->lock
);
2239 DBG("Set begin data pending flag to stream %" PRIu64
,
2240 stream
->stream_handle
);
2246 memset(&reply
, 0, sizeof(reply
));
2247 /* All good, send back reply. */
2248 reply
.ret_code
= htobe32(LTTNG_OK
);
2250 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2251 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2252 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2264 * End data pending command. This will check, for a given session id, if
2265 * each stream associated with it has its data_pending_check_done flag
2266 * set. If not, this means that the client lost track of the stream but
2267 * the data is still being streamed on our side. In this case, we inform
2268 * the client that data is in flight.
2270 * Return to the client if there is data in flight or not with a ret_code.
2272 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2273 struct relay_connection
*conn
,
2274 const struct lttng_buffer_view
*payload
)
2278 struct lttng_ht_iter iter
;
2279 struct lttcomm_relayd_end_data_pending msg
;
2280 struct lttcomm_relayd_generic_reply reply
;
2281 struct relay_stream
*stream
;
2282 uint32_t is_data_inflight
= 0;
2284 DBG("End data pending command");
2286 if (!conn
->session
|| !conn
->version_check_done
) {
2287 ERR("Trying to check for data before version check");
2289 goto end_no_session
;
2292 if (payload
->size
< sizeof(msg
)) {
2293 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2294 sizeof(msg
), payload
->size
);
2296 goto end_no_session
;
2298 memcpy(&msg
, payload
->data
, sizeof(msg
));
2299 msg
.session_id
= be64toh(msg
.session_id
);
2302 * Iterate over all streams to see if the begin data pending
2306 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2308 if (!stream_get(stream
)) {
2311 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2315 pthread_mutex_lock(&stream
->lock
);
2316 if (!stream
->data_pending_check_done
) {
2317 uint64_t stream_seq
;
2319 if (session_streams_have_index(conn
->session
)) {
2321 * Ensure that both the index and stream data have been
2322 * flushed up to the requested point.
2324 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2326 stream_seq
= stream
->prev_data_seq
;
2328 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2329 is_data_inflight
= 1;
2330 DBG("Data is still in flight for stream %" PRIu64
,
2331 stream
->stream_handle
);
2332 pthread_mutex_unlock(&stream
->lock
);
2337 pthread_mutex_unlock(&stream
->lock
);
2342 memset(&reply
, 0, sizeof(reply
));
2343 /* All good, send back reply. */
2344 reply
.ret_code
= htobe32(is_data_inflight
);
2346 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2347 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2348 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2360 * Receive an index for a specific stream.
2362 * Return 0 on success else a negative value.
2364 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2365 struct relay_connection
*conn
,
2366 const struct lttng_buffer_view
*payload
)
2370 struct relay_session
*session
= conn
->session
;
2371 struct lttcomm_relayd_index index_info
;
2372 struct lttcomm_relayd_generic_reply reply
;
2373 struct relay_stream
*stream
;
2378 DBG("Relay receiving index");
2380 if (!session
|| !conn
->version_check_done
) {
2381 ERR("Trying to close a stream before version check");
2383 goto end_no_session
;
2386 msg_len
= lttcomm_relayd_index_len(
2387 lttng_to_index_major(conn
->major
, conn
->minor
),
2388 lttng_to_index_minor(conn
->major
, conn
->minor
));
2389 if (payload
->size
< msg_len
) {
2390 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2391 msg_len
, payload
->size
);
2393 goto end_no_session
;
2395 memcpy(&index_info
, payload
->data
, msg_len
);
2396 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2397 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2398 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2399 index_info
.content_size
= be64toh(index_info
.content_size
);
2400 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2401 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2402 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2403 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2405 if (conn
->minor
>= 8) {
2406 index_info
.stream_instance_id
=
2407 be64toh(index_info
.stream_instance_id
);
2408 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2410 index_info
.stream_instance_id
= -1ULL;
2411 index_info
.packet_seq_num
= -1ULL;
2414 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2416 ERR("stream_get_by_id not found");
2421 pthread_mutex_lock(&stream
->lock
);
2422 ret
= stream_add_index(stream
, &index_info
);
2423 pthread_mutex_unlock(&stream
->lock
);
2425 goto end_stream_put
;
2431 memset(&reply
, 0, sizeof(reply
));
2433 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2435 reply
.ret_code
= htobe32(LTTNG_OK
);
2437 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2438 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2439 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2448 * Receive the streams_sent message.
2450 * Return 0 on success else a negative value.
2452 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2453 struct relay_connection
*conn
,
2454 const struct lttng_buffer_view
*payload
)
2458 struct lttcomm_relayd_generic_reply reply
;
2462 DBG("Relay receiving streams_sent");
2464 if (!conn
->session
|| !conn
->version_check_done
) {
2465 ERR("Trying to close a stream before version check");
2467 goto end_no_session
;
2471 * Publish every pending stream in the connection recv list which are
2472 * now ready to be used by the viewer.
2474 publish_connection_local_streams(conn
);
2476 memset(&reply
, 0, sizeof(reply
));
2477 reply
.ret_code
= htobe32(LTTNG_OK
);
2478 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2479 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2480 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2492 static ssize_t
relay_unpack_rotate_streams_header(
2493 const struct lttng_buffer_view
*payload
,
2494 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2496 struct lttcomm_relayd_rotate_streams rotate_streams
;
2498 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2499 * This is the smallest version of this structure, but it can be larger;
2500 * this variable is updated once the proper size of the structure is known.
2502 * See comment at the declaration of this structure for more information.
2504 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2505 size_t expected_payload_size_no_padding
,
2506 expected_payload_size_3_bytes_padding
,
2507 expected_payload_size_7_bytes_padding
;
2509 if (payload
->size
< header_len
) {
2510 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2511 header_len
, payload
->size
);
2516 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2517 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2519 * We start by "unpacking" `stream_count` to figure out the padding length
2520 * emited by our peer.
2522 memcpy(&rotate_streams
.stream_count
, payload
->data
,
2523 sizeof(rotate_streams
.stream_count
));
2524 rotate_streams
= (typeof(rotate_streams
)) {
2525 .stream_count
= be32toh(rotate_streams
.stream_count
),
2529 * Payload size expected given the possible padding lengths in
2530 * `struct lttcomm_relayd_rotate_streams`.
2532 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2533 sizeof(*rotate_streams
.rotation_positions
)) +
2534 sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2535 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2536 sizeof(*rotate_streams
.rotation_positions
)) +
2537 sizeof(struct lttcomm_relayd_rotate_streams_3_bytes_padding
);
2538 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2539 sizeof(*rotate_streams
.rotation_positions
)) +
2540 sizeof(struct lttcomm_relayd_rotate_streams_7_bytes_padding
);
2542 if (payload
->size
== expected_payload_size_no_padding
) {
2543 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2546 * This handles cases where someone might build with
2547 * -fpack-struct or any other toolchain that wouldn't produce
2548 * padding to align `value`.
2550 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2552 header_len
= sizeof(packed_rotate_streams
);
2553 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2555 /* Unpack the packed structure to the natively-packed version. */
2556 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2557 .stream_count
= be32toh(packed_rotate_streams
.stream_count
),
2558 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2559 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2560 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2563 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2564 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2566 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2568 header_len
= sizeof(padded_rotate_streams
);
2569 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2571 /* Unpack the 3-byte padded structure to the natively-packed version. */
2572 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2573 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2574 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2575 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2576 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2579 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2580 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2582 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2584 header_len
= sizeof(padded_rotate_streams
);
2585 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2587 /* Unpack the 7-byte padded structure to the natively-packed version. */
2588 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2589 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2590 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2591 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2592 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2596 header_len
= sizeof(padded_rotate_streams
);
2598 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2599 expected_payload_size_no_padding
,
2600 expected_payload_size_3_bytes_padding
,
2601 expected_payload_size_7_bytes_padding
,
2612 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2613 * session rotation feature (not the tracefile rotation feature).
2615 static int relay_rotate_session_streams(
2616 const struct lttcomm_relayd_hdr
*recv_hdr
,
2617 struct relay_connection
*conn
,
2618 const struct lttng_buffer_view
*payload
)
2623 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2624 struct relay_session
*session
= conn
->session
;
2625 struct lttcomm_relayd_rotate_streams rotate_streams
;
2626 struct lttcomm_relayd_generic_reply reply
= {};
2627 struct relay_stream
*stream
= NULL
;
2628 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2629 struct lttng_buffer_view stream_positions
;
2630 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2631 const char *chunk_id_str
= "none";
2634 if (!session
|| !conn
->version_check_done
) {
2635 ERR("Trying to rotate a stream before version check");
2640 if (session
->major
== 2 && session
->minor
< 11) {
2641 ERR("Unsupported feature before 2.11");
2646 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2647 if (header_len
< 0) {
2652 if (rotate_streams
.new_chunk_id
.is_set
) {
2654 * Retrieve the trace chunk the stream must transition to. As
2655 * per the protocol, this chunk should have been created
2656 * before this command is received.
2658 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2659 sessiond_trace_chunk_registry
,
2660 session
->sessiond_uuid
,
2661 conn
->session
->id_sessiond
.is_set
?
2662 conn
->session
->id_sessiond
.value
:
2664 rotate_streams
.new_chunk_id
.value
);
2665 if (!next_trace_chunk
) {
2666 char uuid_str
[LTTNG_UUID_STR_LEN
];
2668 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2669 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2670 ", trace_chunk_id = %" PRIu64
,
2671 uuid_str
, session
->id
,
2672 rotate_streams
.new_chunk_id
.value
);
2673 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2678 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2679 rotate_streams
.new_chunk_id
.value
);
2680 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2681 chunk_id_str
= "formatting error";
2683 chunk_id_str
= chunk_id_buf
;
2687 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2688 rotate_streams
.stream_count
, session
->session_name
,
2691 stream_positions
= lttng_buffer_view_from_view(payload
,
2693 if (!stream_positions
.data
||
2694 stream_positions
.size
<
2695 (rotate_streams
.stream_count
*
2696 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2697 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2702 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2703 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2704 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2705 const struct lttcomm_relayd_stream_rotation_position pos
= {
2706 .stream_id
= be64toh(position_comm
->stream_id
),
2707 .rotate_at_seq_num
= be64toh(
2708 position_comm
->rotate_at_seq_num
),
2711 stream
= stream_get_by_id(pos
.stream_id
);
2713 reply_code
= LTTNG_ERR_INVALID
;
2718 pthread_mutex_lock(&stream
->lock
);
2719 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2720 pos
.rotate_at_seq_num
);
2721 pthread_mutex_unlock(&stream
->lock
);
2723 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2731 reply_code
= LTTNG_OK
;
2738 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2739 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2740 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2741 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2742 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2747 lttng_trace_chunk_put(next_trace_chunk
);
2752 * relay_create_trace_chunk: create a new trace chunk
2754 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2755 struct relay_connection
*conn
,
2756 const struct lttng_buffer_view
*payload
)
2760 struct relay_session
*session
= conn
->session
;
2761 struct lttcomm_relayd_create_trace_chunk
*msg
;
2762 struct lttcomm_relayd_generic_reply reply
= {};
2763 struct lttng_buffer_view header_view
;
2764 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2765 enum lttng_error_code reply_code
= LTTNG_OK
;
2766 enum lttng_trace_chunk_status chunk_status
;
2767 const char *new_path
;
2769 if (!session
|| !conn
->version_check_done
) {
2770 ERR("Trying to create a trace chunk before version check");
2775 if (session
->major
== 2 && session
->minor
< 11) {
2776 ERR("Chunk creation command is unsupported before 2.11");
2781 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2782 if (!lttng_buffer_view_is_valid(&header_view
)) {
2783 ERR("Failed to receive payload of chunk creation command");
2788 /* Convert to host endianness. */
2789 msg
= (typeof(msg
)) header_view
.data
;
2790 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2791 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2792 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2794 pthread_mutex_lock(&conn
->session
->lock
);
2795 session
->ongoing_rotation
= true;
2796 if (session
->current_trace_chunk
&&
2797 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2798 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2799 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2800 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2801 ERR("Failed to rename old chunk");
2803 reply_code
= LTTNG_ERR_UNK
;
2807 if (!session
->current_trace_chunk
) {
2808 if (!session
->has_rotated
) {
2814 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2816 chunk
= lttng_trace_chunk_create(
2817 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2819 ERR("Failed to create trace chunk in trace chunk creation command");
2821 reply_code
= LTTNG_ERR_NOMEM
;
2824 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2826 if (msg
->override_name_length
) {
2828 const struct lttng_buffer_view chunk_name_view
=
2829 lttng_buffer_view_from_view(payload
,
2831 msg
->override_name_length
);
2833 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2834 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2836 reply_code
= LTTNG_ERR_INVALID
;
2840 name
= chunk_name_view
.data
;
2841 if (name
[msg
->override_name_length
- 1]) {
2842 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2844 reply_code
= LTTNG_ERR_INVALID
;
2848 chunk_status
= lttng_trace_chunk_override_name(
2849 chunk
, chunk_name_view
.data
);
2850 switch (chunk_status
) {
2851 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2853 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2854 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2855 reply_code
= LTTNG_ERR_INVALID
;
2859 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2860 reply_code
= LTTNG_ERR_UNK
;
2866 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2867 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2868 reply_code
= LTTNG_ERR_UNK
;
2873 assert(conn
->session
->output_directory
);
2874 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2875 conn
->session
->output_directory
);
2876 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2877 reply_code
= LTTNG_ERR_UNK
;
2882 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2883 sessiond_trace_chunk_registry
,
2884 conn
->session
->sessiond_uuid
,
2885 conn
->session
->id_sessiond
.is_set
?
2886 conn
->session
->id_sessiond
.value
:
2889 if (!published_chunk
) {
2890 char uuid_str
[LTTNG_UUID_STR_LEN
];
2892 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2893 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2898 reply_code
= LTTNG_ERR_NOMEM
;
2902 if (conn
->session
->pending_closure_trace_chunk
) {
2904 * Invalid; this means a second create_trace_chunk command was
2905 * received before a close_trace_chunk.
2907 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2908 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2912 conn
->session
->pending_closure_trace_chunk
=
2913 conn
->session
->current_trace_chunk
;
2914 conn
->session
->current_trace_chunk
= published_chunk
;
2915 published_chunk
= NULL
;
2916 if (!conn
->session
->pending_closure_trace_chunk
) {
2917 session
->ongoing_rotation
= false;
2920 pthread_mutex_unlock(&conn
->session
->lock
);
2921 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2922 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2924 sizeof(struct lttcomm_relayd_generic_reply
),
2926 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2927 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2932 lttng_trace_chunk_put(chunk
);
2933 lttng_trace_chunk_put(published_chunk
);
2938 * relay_close_trace_chunk: close a trace chunk
2940 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2941 struct relay_connection
*conn
,
2942 const struct lttng_buffer_view
*payload
)
2944 int ret
= 0, buf_ret
;
2946 struct relay_session
*session
= conn
->session
;
2947 struct lttcomm_relayd_close_trace_chunk
*msg
;
2948 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2949 struct lttng_buffer_view header_view
;
2950 struct lttng_trace_chunk
*chunk
= NULL
;
2951 enum lttng_error_code reply_code
= LTTNG_OK
;
2952 enum lttng_trace_chunk_status chunk_status
;
2954 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2955 time_t close_timestamp
;
2956 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2957 size_t path_length
= 0;
2958 const char *chunk_name
= NULL
;
2959 struct lttng_dynamic_buffer reply_payload
;
2960 const char *new_path
;
2962 lttng_dynamic_buffer_init(&reply_payload
);
2964 if (!session
|| !conn
->version_check_done
) {
2965 ERR("Trying to close a trace chunk before version check");
2970 if (session
->major
== 2 && session
->minor
< 11) {
2971 ERR("Chunk close command is unsupported before 2.11");
2976 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2977 if (!lttng_buffer_view_is_valid(&header_view
)) {
2978 ERR("Failed to receive payload of chunk close command");
2983 /* Convert to host endianness. */
2984 msg
= (typeof(msg
)) header_view
.data
;
2985 chunk_id
= be64toh(msg
->chunk_id
);
2986 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2987 close_command
= (typeof(close_command
)){
2988 .value
= be32toh(msg
->close_command
.value
),
2989 .is_set
= msg
->close_command
.is_set
,
2992 chunk
= sessiond_trace_chunk_registry_get_chunk(
2993 sessiond_trace_chunk_registry
,
2994 conn
->session
->sessiond_uuid
,
2995 conn
->session
->id_sessiond
.is_set
?
2996 conn
->session
->id_sessiond
.value
:
3000 char uuid_str
[LTTNG_UUID_STR_LEN
];
3002 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3003 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
3008 reply_code
= LTTNG_ERR_NOMEM
;
3012 pthread_mutex_lock(&session
->lock
);
3013 if (close_command
.is_set
&&
3014 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3016 * Clear command. It is a protocol error to ask for a
3017 * clear on a relay which does not allow it. Querying
3018 * the configuration allows figuring out whether
3019 * clearing is allowed before doing the clear.
3021 if (!opt_allow_clear
) {
3023 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3024 goto end_unlock_session
;
3027 if (session
->pending_closure_trace_chunk
&&
3028 session
->pending_closure_trace_chunk
!= chunk
) {
3029 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3030 session
->session_name
);
3031 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3033 goto end_unlock_session
;
3036 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3037 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3038 if (close_command
.is_set
&&
3039 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3040 !session
->has_rotated
) {
3041 /* New chunk stays in session output directory. */
3044 /* Use chunk name for new chunk. */
3047 /* Rename new chunk path. */
3048 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3050 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3052 goto end_unlock_session
;
3054 session
->ongoing_rotation
= false;
3056 if ((!close_command
.is_set
||
3057 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3058 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3059 const char *old_path
;
3061 if (!session
->has_rotated
) {
3066 /* We need to move back the .tmp_old_chunk to its rightful place. */
3067 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3068 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3070 goto end_unlock_session
;
3073 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3074 chunk
, close_timestamp
);
3075 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3076 ERR("Failed to set trace chunk close timestamp");
3078 reply_code
= LTTNG_ERR_UNK
;
3079 goto end_unlock_session
;
3082 if (close_command
.is_set
) {
3083 chunk_status
= lttng_trace_chunk_set_close_command(
3084 chunk
, close_command
.value
);
3085 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3087 reply_code
= LTTNG_ERR_INVALID
;
3088 goto end_unlock_session
;
3091 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3092 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3093 ERR("Failed to get chunk name");
3095 reply_code
= LTTNG_ERR_UNK
;
3096 goto end_unlock_session
;
3098 if (!session
->has_rotated
&& !session
->snapshot
) {
3099 ret
= lttng_strncpy(closed_trace_chunk_path
,
3100 session
->output_path
,
3101 sizeof(closed_trace_chunk_path
));
3103 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3104 strlen(session
->output_path
),
3105 sizeof(closed_trace_chunk_path
));
3106 reply_code
= LTTNG_ERR_NOMEM
;
3108 goto end_unlock_session
;
3111 if (session
->snapshot
) {
3112 ret
= snprintf(closed_trace_chunk_path
,
3113 sizeof(closed_trace_chunk_path
),
3114 "%s/%s", session
->output_path
,
3117 ret
= snprintf(closed_trace_chunk_path
,
3118 sizeof(closed_trace_chunk_path
),
3119 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3121 session
->output_path
, chunk_name
);
3123 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3124 ERR("Failed to format closed trace chunk resulting path");
3125 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3127 goto end_unlock_session
;
3130 if (close_command
.is_set
&&
3131 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3132 session
->has_rotated
= true;
3134 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3135 path_length
= strlen(closed_trace_chunk_path
) + 1;
3136 if (path_length
> UINT32_MAX
) {
3137 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3139 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3140 goto end_unlock_session
;
3143 if (session
->current_trace_chunk
== chunk
) {
3145 * After a trace chunk close command, no new streams
3146 * referencing the chunk may be created. Hence, on the
3147 * event that no new trace chunk have been created for
3148 * the session, the reference to the current trace chunk
3149 * is released in order to allow it to be reclaimed when
3150 * the last stream releases its reference to it.
3152 lttng_trace_chunk_put(session
->current_trace_chunk
);
3153 session
->current_trace_chunk
= NULL
;
3155 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3156 session
->pending_closure_trace_chunk
= NULL
;
3158 pthread_mutex_unlock(&session
->lock
);
3161 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3162 reply
.path_length
= htobe32((uint32_t) path_length
);
3163 buf_ret
= lttng_dynamic_buffer_append(
3164 &reply_payload
, &reply
, sizeof(reply
));
3166 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3170 if (reply_code
== LTTNG_OK
) {
3171 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3172 closed_trace_chunk_path
, path_length
);
3174 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3179 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3183 if (send_ret
< reply_payload
.size
) {
3184 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3185 reply_payload
.size
, send_ret
);
3190 lttng_trace_chunk_put(chunk
);
3191 lttng_dynamic_buffer_reset(&reply_payload
);
3196 * relay_trace_chunk_exists: check if a trace chunk exists
3198 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3199 struct relay_connection
*conn
,
3200 const struct lttng_buffer_view
*payload
)
3204 struct relay_session
*session
= conn
->session
;
3205 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3206 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3207 struct lttng_buffer_view header_view
;
3211 if (!session
|| !conn
->version_check_done
) {
3212 ERR("Trying to check for the existance of a trace chunk before version check");
3217 if (session
->major
== 2 && session
->minor
< 11) {
3218 ERR("Chunk exists command is unsupported before 2.11");
3223 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3224 if (!lttng_buffer_view_is_valid(&header_view
)) {
3225 ERR("Failed to receive payload of chunk exists command");
3230 /* Convert to host endianness. */
3231 msg
= (typeof(msg
)) header_view
.data
;
3232 chunk_id
= be64toh(msg
->chunk_id
);
3234 ret
= sessiond_trace_chunk_registry_chunk_exists(
3235 sessiond_trace_chunk_registry
,
3236 conn
->session
->sessiond_uuid
,
3238 chunk_id
, &chunk_exists
);
3240 * If ret is not 0, send the reply and report the error to the caller.
3241 * It is a protocol (or internal) error and the session/connection
3242 * should be torn down.
3244 reply
= (typeof(reply
)){
3245 .generic
.ret_code
= htobe32((uint32_t)
3246 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3247 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
3249 send_ret
= conn
->sock
->ops
->sendmsg(
3250 conn
->sock
, &reply
, sizeof(reply
), 0);
3251 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3252 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3261 * relay_get_configuration: query whether feature is available
3263 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3264 struct relay_connection
*conn
,
3265 const struct lttng_buffer_view
*payload
)
3269 struct lttcomm_relayd_get_configuration
*msg
;
3270 struct lttcomm_relayd_get_configuration_reply reply
= {};
3271 struct lttng_buffer_view header_view
;
3272 uint64_t query_flags
= 0;
3273 uint64_t result_flags
= 0;
3275 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3276 if (!lttng_buffer_view_is_valid(&header_view
)) {
3277 ERR("Failed to receive payload of chunk close command");
3282 /* Convert to host endianness. */
3283 msg
= (typeof(msg
)) header_view
.data
;
3284 query_flags
= be64toh(msg
->query_flags
);
3287 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3290 if (opt_allow_clear
) {
3291 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3295 reply
= (typeof(reply
)){
3296 .generic
.ret_code
= htobe32((uint32_t)
3297 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3298 .relayd_configuration_flags
= htobe64(result_flags
),
3300 send_ret
= conn
->sock
->ops
->sendmsg(
3301 conn
->sock
, &reply
, sizeof(reply
), 0);
3302 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3303 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3311 #define DBG_CMD(cmd_name, conn) \
3312 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3314 static int relay_process_control_command(struct relay_connection
*conn
,
3315 const struct lttcomm_relayd_hdr
*header
,
3316 const struct lttng_buffer_view
*payload
)
3320 switch (header
->cmd
) {
3321 case RELAYD_CREATE_SESSION
:
3322 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3323 ret
= relay_create_session(header
, conn
, payload
);
3325 case RELAYD_ADD_STREAM
:
3326 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3327 ret
= relay_add_stream(header
, conn
, payload
);
3329 case RELAYD_START_DATA
:
3330 DBG_CMD("RELAYD_START_DATA", conn
);
3331 ret
= relay_start(header
, conn
, payload
);
3333 case RELAYD_SEND_METADATA
:
3334 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3335 ret
= relay_recv_metadata(header
, conn
, payload
);
3337 case RELAYD_VERSION
:
3338 DBG_CMD("RELAYD_VERSION", conn
);
3339 ret
= relay_send_version(header
, conn
, payload
);
3341 case RELAYD_CLOSE_STREAM
:
3342 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3343 ret
= relay_close_stream(header
, conn
, payload
);
3345 case RELAYD_DATA_PENDING
:
3346 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3347 ret
= relay_data_pending(header
, conn
, payload
);
3349 case RELAYD_QUIESCENT_CONTROL
:
3350 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3351 ret
= relay_quiescent_control(header
, conn
, payload
);
3353 case RELAYD_BEGIN_DATA_PENDING
:
3354 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3355 ret
= relay_begin_data_pending(header
, conn
, payload
);
3357 case RELAYD_END_DATA_PENDING
:
3358 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3359 ret
= relay_end_data_pending(header
, conn
, payload
);
3361 case RELAYD_SEND_INDEX
:
3362 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3363 ret
= relay_recv_index(header
, conn
, payload
);
3365 case RELAYD_STREAMS_SENT
:
3366 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3367 ret
= relay_streams_sent(header
, conn
, payload
);
3369 case RELAYD_RESET_METADATA
:
3370 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3371 ret
= relay_reset_metadata(header
, conn
, payload
);
3373 case RELAYD_ROTATE_STREAMS
:
3374 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3375 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3377 case RELAYD_CREATE_TRACE_CHUNK
:
3378 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3379 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3381 case RELAYD_CLOSE_TRACE_CHUNK
:
3382 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3383 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3385 case RELAYD_TRACE_CHUNK_EXISTS
:
3386 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3387 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3389 case RELAYD_GET_CONFIGURATION
:
3390 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3391 ret
= relay_get_configuration(header
, conn
, payload
);
3393 case RELAYD_UPDATE_SYNC_INFO
:
3395 ERR("Received unknown command (%u)", header
->cmd
);
3396 relay_unknown_command(conn
);
3405 static enum relay_connection_status
relay_process_control_receive_payload(
3406 struct relay_connection
*conn
)
3409 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3410 struct lttng_dynamic_buffer
*reception_buffer
=
3411 &conn
->protocol
.ctrl
.reception_buffer
;
3412 struct ctrl_connection_state_receive_payload
*state
=
3413 &conn
->protocol
.ctrl
.state
.receive_payload
;
3414 struct lttng_buffer_view payload_view
;
3416 if (state
->left_to_receive
== 0) {
3417 /* Short-circuit for payload-less commands. */
3418 goto reception_complete
;
3421 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3422 reception_buffer
->data
+ state
->received
,
3423 state
->left_to_receive
, MSG_DONTWAIT
);
3425 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3426 PERROR("Unable to receive command payload on sock %d",
3428 status
= RELAY_CONNECTION_STATUS_ERROR
;
3431 } else if (ret
== 0) {
3432 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3433 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3438 assert(ret
<= state
->left_to_receive
);
3440 state
->left_to_receive
-= ret
;
3441 state
->received
+= ret
;
3443 if (state
->left_to_receive
> 0) {
3445 * Can't transition to the protocol's next state, wait to
3446 * receive the rest of the header.
3448 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3449 state
->received
, state
->left_to_receive
,
3455 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3456 conn
->sock
->fd
, state
->received
);
3458 * The payload required to process the command has been received.
3459 * A view to the reception buffer is forwarded to the various
3460 * commands and the state of the control is reset on success.
3462 * Commands are responsible for sending their reply to the peer.
3464 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3466 ret
= relay_process_control_command(conn
,
3467 &state
->header
, &payload_view
);
3469 status
= RELAY_CONNECTION_STATUS_ERROR
;
3473 ret
= connection_reset_protocol_state(conn
);
3475 status
= RELAY_CONNECTION_STATUS_ERROR
;
3481 static enum relay_connection_status
relay_process_control_receive_header(
3482 struct relay_connection
*conn
)
3485 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3486 struct lttcomm_relayd_hdr header
;
3487 struct lttng_dynamic_buffer
*reception_buffer
=
3488 &conn
->protocol
.ctrl
.reception_buffer
;
3489 struct ctrl_connection_state_receive_header
*state
=
3490 &conn
->protocol
.ctrl
.state
.receive_header
;
3492 assert(state
->left_to_receive
!= 0);
3494 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3495 reception_buffer
->data
+ state
->received
,
3496 state
->left_to_receive
, MSG_DONTWAIT
);
3498 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3499 PERROR("Unable to receive control command header on sock %d",
3501 status
= RELAY_CONNECTION_STATUS_ERROR
;
3504 } else if (ret
== 0) {
3505 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3506 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3511 assert(ret
<= state
->left_to_receive
);
3513 state
->left_to_receive
-= ret
;
3514 state
->received
+= ret
;
3516 if (state
->left_to_receive
> 0) {
3518 * Can't transition to the protocol's next state, wait to
3519 * receive the rest of the header.
3521 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3522 state
->received
, state
->left_to_receive
,
3527 /* Transition to next state: receiving the command's payload. */
3528 conn
->protocol
.ctrl
.state_id
=
3529 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3530 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3531 header
.circuit_id
= be64toh(header
.circuit_id
);
3532 header
.data_size
= be64toh(header
.data_size
);
3533 header
.cmd
= be32toh(header
.cmd
);
3534 header
.cmd_version
= be32toh(header
.cmd_version
);
3535 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3536 &header
, sizeof(header
));
3538 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3539 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3542 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3543 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3545 status
= RELAY_CONNECTION_STATUS_ERROR
;
3549 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3551 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3552 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3555 status
= RELAY_CONNECTION_STATUS_ERROR
;
3559 if (header
.data_size
== 0) {
3561 * Manually invoke the next state as the poll loop
3562 * will not wake-up to allow us to proceed further.
3564 status
= relay_process_control_receive_payload(conn
);
3571 * Process the commands received on the control socket
3573 static enum relay_connection_status
relay_process_control(
3574 struct relay_connection
*conn
)
3576 enum relay_connection_status status
;
3578 switch (conn
->protocol
.ctrl
.state_id
) {
3579 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3580 status
= relay_process_control_receive_header(conn
);
3582 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3583 status
= relay_process_control_receive_payload(conn
);
3586 ERR("Unknown control connection protocol state encountered.");
3593 static enum relay_connection_status
relay_process_data_receive_header(
3594 struct relay_connection
*conn
)
3597 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3598 struct data_connection_state_receive_header
*state
=
3599 &conn
->protocol
.data
.state
.receive_header
;
3600 struct lttcomm_relayd_data_hdr header
;
3601 struct relay_stream
*stream
;
3603 assert(state
->left_to_receive
!= 0);
3605 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3606 state
->header_reception_buffer
+ state
->received
,
3607 state
->left_to_receive
, MSG_DONTWAIT
);
3609 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3610 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3611 status
= RELAY_CONNECTION_STATUS_ERROR
;
3614 } else if (ret
== 0) {
3615 /* Orderly shutdown. Not necessary to print an error. */
3616 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3617 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3622 assert(ret
<= state
->left_to_receive
);
3624 state
->left_to_receive
-= ret
;
3625 state
->received
+= ret
;
3627 if (state
->left_to_receive
> 0) {
3629 * Can't transition to the protocol's next state, wait to
3630 * receive the rest of the header.
3632 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3633 state
->received
, state
->left_to_receive
,
3638 /* Transition to next state: receiving the payload. */
3639 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3641 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3642 header
.circuit_id
= be64toh(header
.circuit_id
);
3643 header
.stream_id
= be64toh(header
.stream_id
);
3644 header
.data_size
= be32toh(header
.data_size
);
3645 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3646 header
.padding_size
= be32toh(header
.padding_size
);
3647 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3649 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3651 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3652 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3654 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3655 conn
->sock
->fd
, header
.circuit_id
,
3656 header
.stream_id
, header
.data_size
,
3657 header
.net_seq_num
, header
.padding_size
);
3659 stream
= stream_get_by_id(header
.stream_id
);
3661 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3663 /* Protocol error. */
3664 status
= RELAY_CONNECTION_STATUS_ERROR
;
3668 pthread_mutex_lock(&stream
->lock
);
3669 /* Prepare stream for the reception of a new packet. */
3670 ret
= stream_init_packet(stream
, header
.data_size
,
3671 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3672 pthread_mutex_unlock(&stream
->lock
);
3674 ERR("Failed to rotate stream output file");
3675 status
= RELAY_CONNECTION_STATUS_ERROR
;
3676 goto end_stream_unlock
;
3685 static enum relay_connection_status
relay_process_data_receive_payload(
3686 struct relay_connection
*conn
)
3689 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3690 struct relay_stream
*stream
;
3691 struct data_connection_state_receive_payload
*state
=
3692 &conn
->protocol
.data
.state
.receive_payload
;
3693 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3694 char data_buffer
[chunk_size
];
3695 bool partial_recv
= false;
3696 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3697 uint64_t left_to_receive
= state
->left_to_receive
;
3698 struct relay_session
*session
;
3700 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3701 state
->header
.stream_id
, state
->header
.net_seq_num
,
3702 state
->received
, left_to_receive
);
3704 stream
= stream_get_by_id(state
->header
.stream_id
);
3706 /* Protocol error. */
3707 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3708 state
->header
.stream_id
);
3709 status
= RELAY_CONNECTION_STATUS_ERROR
;
3713 pthread_mutex_lock(&stream
->lock
);
3714 session
= stream
->trace
->session
;
3715 if (!conn
->session
) {
3716 ret
= connection_set_session(conn
, session
);
3718 status
= RELAY_CONNECTION_STATUS_ERROR
;
3719 goto end_stream_unlock
;
3724 * The size of the "chunk" received on any iteration is bounded by:
3725 * - the data left to receive,
3726 * - the data immediately available on the socket,
3727 * - the on-stack data buffer
3729 while (left_to_receive
> 0 && !partial_recv
) {
3730 size_t recv_size
= min(left_to_receive
, chunk_size
);
3731 struct lttng_buffer_view packet_chunk
;
3733 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3734 recv_size
, MSG_DONTWAIT
);
3736 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3737 PERROR("Socket %d error", conn
->sock
->fd
);
3738 status
= RELAY_CONNECTION_STATUS_ERROR
;
3740 goto end_stream_unlock
;
3741 } else if (ret
== 0) {
3742 /* No more data ready to be consumed on socket. */
3743 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3744 state
->header
.stream_id
);
3745 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3747 } else if (ret
< (int) recv_size
) {
3749 * All the data available on the socket has been
3752 partial_recv
= true;
3756 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3758 assert(packet_chunk
.data
);
3760 ret
= stream_write(stream
, &packet_chunk
, 0);
3762 ERR("Relay error writing data to file");
3763 status
= RELAY_CONNECTION_STATUS_ERROR
;
3764 goto end_stream_unlock
;
3767 left_to_receive
-= recv_size
;
3768 state
->received
+= recv_size
;
3769 state
->left_to_receive
= left_to_receive
;
3772 if (state
->left_to_receive
> 0) {
3774 * Did not receive all the data expected, wait for more data to
3775 * become available on the socket.
3777 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3778 state
->header
.stream_id
, state
->received
,
3779 state
->left_to_receive
);
3780 goto end_stream_unlock
;
3783 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3785 status
= RELAY_CONNECTION_STATUS_ERROR
;
3786 goto end_stream_unlock
;
3789 if (session_streams_have_index(session
)) {
3790 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3791 state
->rotate_index
, &index_flushed
,
3792 state
->header
.data_size
+ state
->header
.padding_size
);
3794 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3795 stream
->stream_handle
,
3796 state
->header
.net_seq_num
, ret
);
3797 status
= RELAY_CONNECTION_STATUS_ERROR
;
3798 goto end_stream_unlock
;
3802 if (stream
->prev_data_seq
== -1ULL) {
3806 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3807 state
->header
.padding_size
, state
->header
.net_seq_num
,
3810 status
= RELAY_CONNECTION_STATUS_ERROR
;
3811 goto end_stream_unlock
;
3815 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3816 * contents of *state which are aliased (union) to the same location as
3817 * the new state. Don't use it beyond this point.
3819 connection_reset_protocol_state(conn
);
3823 close_requested
= stream
->close_requested
;
3824 pthread_mutex_unlock(&stream
->lock
);
3825 if (close_requested
&& left_to_receive
== 0) {
3826 try_stream_close(stream
);
3830 pthread_mutex_lock(&session
->lock
);
3831 uatomic_set(&session
->new_streams
, 1);
3832 pthread_mutex_unlock(&session
->lock
);
3841 * relay_process_data: Process the data received on the data socket
3843 static enum relay_connection_status
relay_process_data(
3844 struct relay_connection
*conn
)
3846 enum relay_connection_status status
;
3848 switch (conn
->protocol
.data
.state_id
) {
3849 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3850 status
= relay_process_data_receive_header(conn
);
3852 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3853 status
= relay_process_data_receive_payload(conn
);
3856 ERR("Unexpected data connection communication state.");
3863 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3867 (void) lttng_poll_del(events
, pollfd
);
3869 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3870 fd_tracker_util_close_fd
, NULL
);
3872 ERR("Closing pollfd %d", pollfd
);
3876 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3877 int pollfd
, struct relay_connection
*conn
)
3879 const char *type_str
;
3881 switch (conn
->type
) {
3886 type_str
= "Control";
3888 case RELAY_VIEWER_COMMAND
:
3889 type_str
= "Viewer Command";
3891 case RELAY_VIEWER_NOTIFICATION
:
3892 type_str
= "Viewer Notification";
3895 type_str
= "Unknown";
3897 cleanup_connection_pollfd(events
, pollfd
);
3898 connection_put(conn
);
3899 DBG("%s connection closed with %d", type_str
, pollfd
);
3903 * This thread does the actual work
3905 static void *relay_thread_worker(void *data
)
3907 int ret
, err
= -1, last_seen_data_fd
= -1;
3909 struct lttng_poll_event events
;
3910 struct lttng_ht
*relay_connections_ht
;
3911 struct lttng_ht_iter iter
;
3912 struct relay_connection
*destroy_conn
= NULL
;
3914 DBG("[thread] Relay worker started");
3916 rcu_register_thread();
3918 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3920 if (testpoint(relayd_thread_worker
)) {
3921 goto error_testpoint
;
3924 health_code_update();
3926 /* table of connections indexed on socket */
3927 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3928 if (!relay_connections_ht
) {
3929 goto relay_connections_ht_error
;
3932 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3934 goto error_poll_create
;
3937 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3944 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3946 health_code_update();
3948 /* Infinite blocking call, waiting for transmission */
3949 DBG3("Relayd worker thread polling...");
3950 health_poll_entry();
3951 ret
= lttng_poll_wait(&events
, -1);
3955 * Restart interrupted system call.
3957 if (errno
== EINTR
) {
3966 * Process control. The control connection is
3967 * prioritized so we don't starve it with high
3968 * throughput tracing data on the data connection.
3970 for (i
= 0; i
< nb_fd
; i
++) {
3971 /* Fetch once the poll data */
3972 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3973 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3975 health_code_update();
3977 /* Thread quit pipe has been closed. Killing thread. */
3978 ret
= check_thread_quit_pipe(pollfd
, revents
);
3984 /* Inspect the relay conn pipe for new connection */
3985 if (pollfd
== relay_conn_pipe
[0]) {
3986 if (revents
& LPOLLIN
) {
3987 struct relay_connection
*conn
;
3989 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3993 ret
= lttng_poll_add(&events
,
3995 LPOLLIN
| LPOLLRDHUP
);
3997 ERR("Failed to add new connection file descriptor to poll set");
4000 connection_ht_add(relay_connections_ht
, conn
);
4001 DBG("Connection socket %d added", conn
->sock
->fd
);
4002 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4003 ERR("Relay connection pipe error");
4006 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4010 struct relay_connection
*ctrl_conn
;
4012 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4013 /* If not found, there is a synchronization issue. */
4016 if (ctrl_conn
->type
== RELAY_DATA
) {
4017 if (revents
& LPOLLIN
) {
4019 * Flag the last seen data fd not deleted. It will be
4020 * used as the last seen fd if any fd gets deleted in
4023 last_notdel_data_fd
= pollfd
;
4025 goto put_ctrl_connection
;
4027 assert(ctrl_conn
->type
== RELAY_CONTROL
);
4029 if (revents
& LPOLLIN
) {
4030 enum relay_connection_status status
;
4032 status
= relay_process_control(ctrl_conn
);
4033 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4035 * On socket error flag the session as aborted to force
4036 * the cleanup of its stream otherwise it can leak
4037 * during the lifetime of the relayd.
4039 * This prevents situations in which streams can be
4040 * left opened because an index was received, the
4041 * control connection is closed, and the data
4042 * connection is closed (uncleanly) before the packet's
4045 * Since the control connection encountered an error,
4046 * it is okay to be conservative and close the
4047 * session right now as we can't rely on the protocol
4048 * being respected anymore.
4050 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4051 session_abort(ctrl_conn
->session
);
4054 /* Clear the connection on error or close. */
4055 relay_thread_close_connection(&events
,
4060 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4061 relay_thread_close_connection(&events
,
4063 if (last_seen_data_fd
== pollfd
) {
4064 last_seen_data_fd
= last_notdel_data_fd
;
4067 ERR("Unexpected poll events %u for control sock %d",
4069 connection_put(ctrl_conn
);
4072 put_ctrl_connection
:
4073 connection_put(ctrl_conn
);
4078 * The last loop handled a control request, go back to poll to make
4079 * sure we prioritise the control socket.
4085 if (last_seen_data_fd
>= 0) {
4086 for (i
= 0; i
< nb_fd
; i
++) {
4087 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4089 health_code_update();
4091 if (last_seen_data_fd
== pollfd
) {
4098 /* Process data connection. */
4099 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4100 /* Fetch the poll data. */
4101 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4102 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4103 struct relay_connection
*data_conn
;
4105 health_code_update();
4108 /* No activity for this FD (poll implementation). */
4112 /* Skip the command pipe. It's handled in the first loop. */
4113 if (pollfd
== relay_conn_pipe
[0]) {
4117 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4119 /* Skip it. Might be removed before. */
4122 if (data_conn
->type
== RELAY_CONTROL
) {
4123 goto put_data_connection
;
4125 assert(data_conn
->type
== RELAY_DATA
);
4127 if (revents
& LPOLLIN
) {
4128 enum relay_connection_status status
;
4130 status
= relay_process_data(data_conn
);
4131 /* Connection closed or error. */
4132 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4134 * On socket error flag the session as aborted to force
4135 * the cleanup of its stream otherwise it can leak
4136 * during the lifetime of the relayd.
4138 * This prevents situations in which streams can be
4139 * left opened because an index was received, the
4140 * control connection is closed, and the data
4141 * connection is closed (uncleanly) before the packet's
4144 * Since the data connection encountered an error,
4145 * it is okay to be conservative and close the
4146 * session right now as we can't rely on the protocol
4147 * being respected anymore.
4149 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4150 session_abort(data_conn
->session
);
4152 relay_thread_close_connection(&events
, pollfd
,
4155 * Every goto restart call sets the last seen fd where
4156 * here we don't really care since we gracefully
4157 * continue the loop after the connection is deleted.
4160 /* Keep last seen port. */
4161 last_seen_data_fd
= pollfd
;
4162 connection_put(data_conn
);
4165 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4166 relay_thread_close_connection(&events
, pollfd
,
4169 ERR("Unknown poll events %u for data sock %d",
4172 put_data_connection
:
4173 connection_put(data_conn
);
4175 last_seen_data_fd
= -1;
4178 /* Normal exit, no error */
4183 /* Cleanup remaining connection object. */
4185 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4188 health_code_update();
4190 session_abort(destroy_conn
->session
);
4193 * No need to grab another ref, because we own
4196 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4201 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4203 lttng_ht_destroy(relay_connections_ht
);
4204 relay_connections_ht_error
:
4205 /* Close relay conn pipes */
4206 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4209 DBG("Thread exited with error");
4211 DBG("Worker thread cleanup complete");
4215 ERR("Health error occurred in %s", __func__
);
4217 health_unregister(health_relayd
);
4218 rcu_unregister_thread();
4219 lttng_relay_stop_threads();
4224 * Create the relay command pipe to wake thread_manage_apps.
4225 * Closed in cleanup().
4227 static int create_relay_conn_pipe(void)
4229 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4230 "Relayd connection pipe", relay_conn_pipe
);
4233 static int stdio_open(void *data
, int *fds
)
4235 fds
[0] = fileno(stdout
);
4236 fds
[1] = fileno(stderr
);
4240 static int track_stdio(void)
4243 const char *names
[] = { "stdout", "stderr" };
4245 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4246 names
, 2, stdio_open
, NULL
);
4252 int main(int argc
, char **argv
)
4254 bool thread_is_rcu_registered
= false;
4255 int ret
= 0, retval
= 0;
4257 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4259 /* Parse environment variables */
4260 ret
= parse_env_options();
4268 * Command line arguments overwrite environment.
4271 if (set_options(argc
, argv
)) {
4276 if (set_signal_handler()) {
4281 relayd_config_log();
4283 if (opt_print_version
) {
4289 ret
= fclose(stdin
);
4291 PERROR("Failed to close stdin");
4295 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4297 /* Try to create directory if -o, --output is specified. */
4298 if (opt_output_path
) {
4299 if (*opt_output_path
!= '/') {
4300 ERR("Please specify an absolute path for -o, --output PATH");
4305 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4308 ERR("Unable to create %s", opt_output_path
);
4315 if (opt_daemon
|| opt_background
) {
4316 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4324 if (opt_working_directory
) {
4325 ret
= utils_change_working_directory(opt_working_directory
);
4327 /* All errors are already logged. */
4332 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4333 if (!sessiond_trace_chunk_registry
) {
4334 ERR("Failed to initialize session daemon trace chunk registry");
4340 * The RCU thread registration (and use, through the fd-tracker's
4341 * creation) is done after the daemonization to allow us to not
4342 * deal with liburcu's fork() management as the call RCU needs to
4345 rcu_register_thread();
4346 thread_is_rcu_registered
= true;
4348 output_path
= create_output_path("");
4350 ERR("Failed to get output path");
4354 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4355 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4358 ERR("Failed to format unlinked file directory path");
4362 the_fd_tracker
= fd_tracker_create(
4363 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4364 free(unlinked_file_directory_path
);
4365 if (!the_fd_tracker
) {
4370 ret
= track_stdio();
4376 /* Initialize thread health monitoring */
4377 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4378 if (!health_relayd
) {
4379 PERROR("health_app_create error");
4384 /* Create thread quit pipe */
4385 if (init_thread_quit_pipe()) {
4390 /* Setup the thread apps communication pipe. */
4391 if (create_relay_conn_pipe()) {
4396 /* Init relay command queue. */
4397 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4399 /* Initialize communication library */
4401 lttcomm_inet_init();
4403 /* tables of sessions indexed by session ID */
4404 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4410 /* tables of streams indexed by stream ID */
4411 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4412 if (!relay_streams_ht
) {
4417 /* tables of streams indexed by stream ID */
4418 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4419 if (!viewer_streams_ht
) {
4424 ret
= init_health_quit_pipe();
4430 /* Create thread to manage the client socket */
4431 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4432 thread_manage_health
, (void *) NULL
);
4435 PERROR("pthread_create health");
4440 /* Setup the dispatcher thread */
4441 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4442 relay_thread_dispatcher
, (void *) NULL
);
4445 PERROR("pthread_create dispatcher");
4447 goto exit_dispatcher_thread
;
4450 /* Setup the worker thread */
4451 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4452 relay_thread_worker
, NULL
);
4455 PERROR("pthread_create worker");
4457 goto exit_worker_thread
;
4460 /* Setup the listener thread */
4461 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4462 relay_thread_listener
, (void *) NULL
);
4465 PERROR("pthread_create listener");
4467 goto exit_listener_thread
;
4470 ret
= relayd_live_create(live_uri
);
4472 ERR("Starting live viewer threads");
4478 * This is where we start awaiting program completion (e.g. through
4479 * signal that asks threads to teardown).
4482 ret
= relayd_live_join();
4488 ret
= pthread_join(listener_thread
, &status
);
4491 PERROR("pthread_join listener_thread");
4495 exit_listener_thread
:
4496 ret
= pthread_join(worker_thread
, &status
);
4499 PERROR("pthread_join worker_thread");
4504 ret
= pthread_join(dispatcher_thread
, &status
);
4507 PERROR("pthread_join dispatcher_thread");
4510 exit_dispatcher_thread
:
4512 ret
= pthread_join(health_thread
, &status
);
4515 PERROR("pthread_join health_thread");
4520 * Wait for all pending call_rcu work to complete before tearing
4521 * down data structures. call_rcu worker may be trying to
4522 * perform lookups in those structures.
4527 /* Ensure all prior call_rcu are done. */
4530 if (thread_is_rcu_registered
) {
4531 rcu_unregister_thread();