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);
1529 pthread_mutex_unlock(&session
->lock
);
1532 static int conform_channel_path(char *channel_path
)
1536 if (strstr("../", channel_path
)) {
1537 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1543 if (*channel_path
== '/') {
1544 const size_t len
= strlen(channel_path
);
1547 * Channel paths from peers prior to 2.11 are expressed as an
1548 * absolute path that is, in reality, relative to the relay
1549 * daemon's output directory. Remove the leading slash so it
1550 * is correctly interpreted as a relative path later on.
1552 * len (and not len - 1) is used to copy the trailing NULL.
1554 bcopy(channel_path
+ 1, channel_path
, len
);
1561 * relay_add_stream: allocate a new stream for a session
1563 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1564 struct relay_connection
*conn
,
1565 const struct lttng_buffer_view
*payload
)
1569 struct relay_session
*session
= conn
->session
;
1570 struct relay_stream
*stream
= NULL
;
1571 struct lttcomm_relayd_status_stream reply
;
1572 struct ctf_trace
*trace
= NULL
;
1573 uint64_t stream_handle
= -1ULL;
1574 char *path_name
= NULL
, *channel_name
= NULL
;
1575 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1576 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1578 if (!session
|| !conn
->version_check_done
) {
1579 ERR("Trying to add a stream before version check");
1581 goto end_no_session
;
1584 if (session
->minor
== 1) {
1586 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1588 } else if (session
->minor
> 1 && session
->minor
< 11) {
1589 /* From 2.2 to 2.10 */
1590 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1591 &channel_name
, &tracefile_size
, &tracefile_count
);
1593 /* From 2.11 to ... */
1594 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1595 &channel_name
, &tracefile_size
, &tracefile_count
,
1596 &stream_chunk_id
.value
);
1597 stream_chunk_id
.is_set
= true;
1604 if (conform_channel_path(path_name
)) {
1609 * Backward compatibility for --group-output-by-session.
1610 * Prior to lttng 2.11, the complete path is passed by the stream.
1611 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1612 * >=2.11 the chunk is responsible for the output path. When dealing
1613 * with producer < 2.11 the chunk output_path is the root output path
1614 * and the stream carries the complete path (path_name).
1615 * To support --group-output-by-session with older producer (<2.11), we
1616 * need to craft the path based on the stream path.
1618 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1619 if (conn
->minor
< 4) {
1621 * From 2.1 to 2.3, the session_name is not passed on
1622 * the RELAYD_CREATE_SESSION command. The session name
1623 * is necessary to detect the presence of a base_path
1624 * inside the stream path. Without it we cannot perform
1625 * a valid group-output-by-session transformation.
1627 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1628 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1629 session
->id
, path_name
);
1630 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1631 char *group_by_session_path_name
;
1633 assert(session
->session_name
[0] != '\0');
1635 group_by_session_path_name
=
1636 backward_compat_group_by_session(
1638 session
->session_name
,
1639 session
->creation_time
.value
);
1640 if (!group_by_session_path_name
) {
1641 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1646 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1647 path_name
, group_by_session_path_name
);
1650 path_name
= group_by_session_path_name
;
1654 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1659 /* This stream here has one reference on the trace. */
1660 pthread_mutex_lock(&last_relay_stream_id_lock
);
1661 stream_handle
= ++last_relay_stream_id
;
1662 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1664 /* We pass ownership of path_name and channel_name. */
1665 stream
= stream_create(trace
, stream_handle
, path_name
,
1666 channel_name
, tracefile_size
, tracefile_count
);
1668 channel_name
= NULL
;
1671 * Streams are the owners of their trace. Reference to trace is
1672 * kept within stream_create().
1674 ctf_trace_put(trace
);
1677 memset(&reply
, 0, sizeof(reply
));
1678 reply
.handle
= htobe64(stream_handle
);
1680 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1682 reply
.ret_code
= htobe32(LTTNG_OK
);
1685 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1686 sizeof(struct lttcomm_relayd_status_stream
), 0);
1687 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1688 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1700 * relay_close_stream: close a specific stream
1702 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1703 struct relay_connection
*conn
,
1704 const struct lttng_buffer_view
*payload
)
1708 struct relay_session
*session
= conn
->session
;
1709 struct lttcomm_relayd_close_stream stream_info
;
1710 struct lttcomm_relayd_generic_reply reply
;
1711 struct relay_stream
*stream
;
1713 DBG("Close stream received");
1715 if (!session
|| !conn
->version_check_done
) {
1716 ERR("Trying to close a stream before version check");
1718 goto end_no_session
;
1721 if (payload
->size
< sizeof(stream_info
)) {
1722 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1723 sizeof(stream_info
), payload
->size
);
1725 goto end_no_session
;
1727 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1728 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1729 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1731 stream
= stream_get_by_id(stream_info
.stream_id
);
1738 * Set last_net_seq_num before the close flag. Required by data
1741 pthread_mutex_lock(&stream
->lock
);
1742 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1743 pthread_mutex_unlock(&stream
->lock
);
1746 * This is one of the conditions which may trigger a stream close
1747 * with the others being:
1748 * 1) A close command is received for a stream
1749 * 2) The control connection owning the stream is closed
1750 * 3) We have received all of the stream's data _after_ a close
1753 try_stream_close(stream
);
1758 memset(&reply
, 0, sizeof(reply
));
1760 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1762 reply
.ret_code
= htobe32(LTTNG_OK
);
1764 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1765 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1766 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1767 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1777 * relay_reset_metadata: reset a metadata stream
1780 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1781 struct relay_connection
*conn
,
1782 const struct lttng_buffer_view
*payload
)
1786 struct relay_session
*session
= conn
->session
;
1787 struct lttcomm_relayd_reset_metadata stream_info
;
1788 struct lttcomm_relayd_generic_reply reply
;
1789 struct relay_stream
*stream
;
1791 DBG("Reset metadata received");
1793 if (!session
|| !conn
->version_check_done
) {
1794 ERR("Trying to reset a metadata stream before version check");
1796 goto end_no_session
;
1799 if (payload
->size
< sizeof(stream_info
)) {
1800 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1801 sizeof(stream_info
), payload
->size
);
1803 goto end_no_session
;
1805 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1806 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1807 stream_info
.version
= be64toh(stream_info
.version
);
1809 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1811 /* Unsupported for live sessions for now. */
1812 if (session
->live_timer
!= 0) {
1817 stream
= stream_get_by_id(stream_info
.stream_id
);
1822 pthread_mutex_lock(&stream
->lock
);
1823 if (!stream
->is_metadata
) {
1828 ret
= stream_reset_file(stream
);
1830 ERR("Failed to reset metadata stream %" PRIu64
1831 ": stream_path = %s, channel = %s",
1832 stream
->stream_handle
, stream
->path_name
,
1833 stream
->channel_name
);
1837 pthread_mutex_unlock(&stream
->lock
);
1841 memset(&reply
, 0, sizeof(reply
));
1843 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1845 reply
.ret_code
= htobe32(LTTNG_OK
);
1847 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1848 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1849 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1850 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1860 * relay_unknown_command: send -1 if received unknown command
1862 static void relay_unknown_command(struct relay_connection
*conn
)
1864 struct lttcomm_relayd_generic_reply reply
;
1867 memset(&reply
, 0, sizeof(reply
));
1868 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1869 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1870 if (send_ret
< sizeof(reply
)) {
1871 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1876 * relay_start: send an acknowledgment to the client to tell if we are
1877 * ready to receive data. We are ready if a session is established.
1879 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1880 struct relay_connection
*conn
,
1881 const struct lttng_buffer_view
*payload
)
1885 struct lttcomm_relayd_generic_reply reply
;
1886 struct relay_session
*session
= conn
->session
;
1889 DBG("Trying to start the streaming without a session established");
1890 ret
= htobe32(LTTNG_ERR_UNK
);
1893 memset(&reply
, 0, sizeof(reply
));
1894 reply
.ret_code
= htobe32(LTTNG_OK
);
1895 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1897 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1898 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1907 * relay_recv_metadata: receive the metadata for the session.
1909 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1910 struct relay_connection
*conn
,
1911 const struct lttng_buffer_view
*payload
)
1914 struct relay_session
*session
= conn
->session
;
1915 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1916 struct relay_stream
*metadata_stream
;
1917 uint64_t metadata_payload_size
;
1918 struct lttng_buffer_view packet_view
;
1921 ERR("Metadata sent before version check");
1926 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1927 ERR("Incorrect data size");
1931 metadata_payload_size
= recv_hdr
->data_size
-
1932 sizeof(struct lttcomm_relayd_metadata_payload
);
1934 memcpy(&metadata_payload_header
, payload
->data
,
1935 sizeof(metadata_payload_header
));
1936 metadata_payload_header
.stream_id
= be64toh(
1937 metadata_payload_header
.stream_id
);
1938 metadata_payload_header
.padding_size
= be32toh(
1939 metadata_payload_header
.padding_size
);
1941 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1942 if (!metadata_stream
) {
1947 packet_view
= lttng_buffer_view_from_view(payload
,
1948 sizeof(metadata_payload_header
), metadata_payload_size
);
1949 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1950 ERR("Invalid metadata packet length announced by header");
1955 pthread_mutex_lock(&metadata_stream
->lock
);
1956 ret
= stream_write(metadata_stream
, &packet_view
,
1957 metadata_payload_header
.padding_size
);
1958 pthread_mutex_unlock(&metadata_stream
->lock
);
1964 stream_put(metadata_stream
);
1970 * relay_send_version: send relayd version number
1972 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1973 struct relay_connection
*conn
,
1974 const struct lttng_buffer_view
*payload
)
1978 struct lttcomm_relayd_version reply
, msg
;
1979 bool compatible
= true;
1981 conn
->version_check_done
= true;
1983 /* Get version from the other side. */
1984 if (payload
->size
< sizeof(msg
)) {
1985 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1986 sizeof(msg
), payload
->size
);
1991 memcpy(&msg
, payload
->data
, sizeof(msg
));
1992 msg
.major
= be32toh(msg
.major
);
1993 msg
.minor
= be32toh(msg
.minor
);
1995 memset(&reply
, 0, sizeof(reply
));
1996 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1997 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1999 /* Major versions must be the same */
2000 if (reply
.major
!= msg
.major
) {
2001 DBG("Incompatible major versions (%u vs %u), deleting session",
2002 reply
.major
, msg
.major
);
2006 conn
->major
= reply
.major
;
2007 /* We adapt to the lowest compatible version */
2008 if (reply
.minor
<= msg
.minor
) {
2009 conn
->minor
= reply
.minor
;
2011 conn
->minor
= msg
.minor
;
2014 reply
.major
= htobe32(reply
.major
);
2015 reply
.minor
= htobe32(reply
.minor
);
2016 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2018 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2019 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2032 DBG("Version check done using protocol %u.%u", conn
->major
,
2040 * Check for data pending for a given stream id from the session daemon.
2042 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2043 struct relay_connection
*conn
,
2044 const struct lttng_buffer_view
*payload
)
2046 struct relay_session
*session
= conn
->session
;
2047 struct lttcomm_relayd_data_pending msg
;
2048 struct lttcomm_relayd_generic_reply reply
;
2049 struct relay_stream
*stream
;
2052 uint64_t stream_seq
;
2054 DBG("Data pending command received");
2056 if (!session
|| !conn
->version_check_done
) {
2057 ERR("Trying to check for data before version check");
2059 goto end_no_session
;
2062 if (payload
->size
< sizeof(msg
)) {
2063 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2064 sizeof(msg
), payload
->size
);
2066 goto end_no_session
;
2068 memcpy(&msg
, payload
->data
, sizeof(msg
));
2069 msg
.stream_id
= be64toh(msg
.stream_id
);
2070 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2072 stream
= stream_get_by_id(msg
.stream_id
);
2073 if (stream
== NULL
) {
2078 pthread_mutex_lock(&stream
->lock
);
2080 if (session_streams_have_index(session
)) {
2082 * Ensure that both the index and stream data have been
2083 * flushed up to the requested point.
2085 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2087 stream_seq
= stream
->prev_data_seq
;
2089 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2090 ", prev_index_seq %" PRIu64
2091 ", and last_seq %" PRIu64
, msg
.stream_id
,
2092 stream
->prev_data_seq
, stream
->prev_index_seq
,
2093 msg
.last_net_seq_num
);
2095 /* Avoid wrapping issue */
2096 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2097 /* Data has in fact been written and is NOT pending */
2100 /* Data still being streamed thus pending */
2104 stream
->data_pending_check_done
= true;
2105 pthread_mutex_unlock(&stream
->lock
);
2110 memset(&reply
, 0, sizeof(reply
));
2111 reply
.ret_code
= htobe32(ret
);
2112 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2113 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2114 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2124 * Wait for the control socket to reach a quiescent state.
2126 * Note that for now, when receiving this command from the session
2127 * daemon, this means that every subsequent commands or data received on
2128 * the control socket has been handled. So, this is why we simply return
2131 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2132 struct relay_connection
*conn
,
2133 const struct lttng_buffer_view
*payload
)
2137 struct relay_stream
*stream
;
2138 struct lttcomm_relayd_quiescent_control msg
;
2139 struct lttcomm_relayd_generic_reply reply
;
2141 DBG("Checking quiescent state on control socket");
2143 if (!conn
->session
|| !conn
->version_check_done
) {
2144 ERR("Trying to check for data before version check");
2146 goto end_no_session
;
2149 if (payload
->size
< sizeof(msg
)) {
2150 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2151 sizeof(msg
), payload
->size
);
2153 goto end_no_session
;
2155 memcpy(&msg
, payload
->data
, sizeof(msg
));
2156 msg
.stream_id
= be64toh(msg
.stream_id
);
2158 stream
= stream_get_by_id(msg
.stream_id
);
2162 pthread_mutex_lock(&stream
->lock
);
2163 stream
->data_pending_check_done
= true;
2164 pthread_mutex_unlock(&stream
->lock
);
2166 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2169 memset(&reply
, 0, sizeof(reply
));
2170 reply
.ret_code
= htobe32(LTTNG_OK
);
2171 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2172 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2173 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2185 * Initialize a data pending command. This means that a consumer is about
2186 * to ask for data pending for each stream it holds. Simply iterate over
2187 * all streams of a session and set the data_pending_check_done flag.
2189 * This command returns to the client a LTTNG_OK code.
2191 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2192 struct relay_connection
*conn
,
2193 const struct lttng_buffer_view
*payload
)
2197 struct lttng_ht_iter iter
;
2198 struct lttcomm_relayd_begin_data_pending msg
;
2199 struct lttcomm_relayd_generic_reply reply
;
2200 struct relay_stream
*stream
;
2205 DBG("Init streams for data pending");
2207 if (!conn
->session
|| !conn
->version_check_done
) {
2208 ERR("Trying to check for data before version check");
2210 goto end_no_session
;
2213 if (payload
->size
< sizeof(msg
)) {
2214 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2215 sizeof(msg
), payload
->size
);
2217 goto end_no_session
;
2219 memcpy(&msg
, payload
->data
, sizeof(msg
));
2220 msg
.session_id
= be64toh(msg
.session_id
);
2223 * Iterate over all streams to set the begin data pending flag.
2224 * For now, the streams are indexed by stream handle so we have
2225 * to iterate over all streams to find the one associated with
2226 * the right session_id.
2229 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2231 if (!stream_get(stream
)) {
2234 if (stream
->trace
->session
->id
== msg
.session_id
) {
2235 pthread_mutex_lock(&stream
->lock
);
2236 stream
->data_pending_check_done
= false;
2237 pthread_mutex_unlock(&stream
->lock
);
2238 DBG("Set begin data pending flag to stream %" PRIu64
,
2239 stream
->stream_handle
);
2245 memset(&reply
, 0, sizeof(reply
));
2246 /* All good, send back reply. */
2247 reply
.ret_code
= htobe32(LTTNG_OK
);
2249 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2250 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2251 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2263 * End data pending command. This will check, for a given session id, if
2264 * each stream associated with it has its data_pending_check_done flag
2265 * set. If not, this means that the client lost track of the stream but
2266 * the data is still being streamed on our side. In this case, we inform
2267 * the client that data is in flight.
2269 * Return to the client if there is data in flight or not with a ret_code.
2271 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2272 struct relay_connection
*conn
,
2273 const struct lttng_buffer_view
*payload
)
2277 struct lttng_ht_iter iter
;
2278 struct lttcomm_relayd_end_data_pending msg
;
2279 struct lttcomm_relayd_generic_reply reply
;
2280 struct relay_stream
*stream
;
2281 uint32_t is_data_inflight
= 0;
2283 DBG("End data pending command");
2285 if (!conn
->session
|| !conn
->version_check_done
) {
2286 ERR("Trying to check for data before version check");
2288 goto end_no_session
;
2291 if (payload
->size
< sizeof(msg
)) {
2292 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2293 sizeof(msg
), payload
->size
);
2295 goto end_no_session
;
2297 memcpy(&msg
, payload
->data
, sizeof(msg
));
2298 msg
.session_id
= be64toh(msg
.session_id
);
2301 * Iterate over all streams to see if the begin data pending
2305 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2307 if (!stream_get(stream
)) {
2310 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2314 pthread_mutex_lock(&stream
->lock
);
2315 if (!stream
->data_pending_check_done
) {
2316 uint64_t stream_seq
;
2318 if (session_streams_have_index(conn
->session
)) {
2320 * Ensure that both the index and stream data have been
2321 * flushed up to the requested point.
2323 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2325 stream_seq
= stream
->prev_data_seq
;
2327 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2328 is_data_inflight
= 1;
2329 DBG("Data is still in flight for stream %" PRIu64
,
2330 stream
->stream_handle
);
2331 pthread_mutex_unlock(&stream
->lock
);
2336 pthread_mutex_unlock(&stream
->lock
);
2341 memset(&reply
, 0, sizeof(reply
));
2342 /* All good, send back reply. */
2343 reply
.ret_code
= htobe32(is_data_inflight
);
2345 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2346 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2347 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2359 * Receive an index for a specific stream.
2361 * Return 0 on success else a negative value.
2363 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2364 struct relay_connection
*conn
,
2365 const struct lttng_buffer_view
*payload
)
2369 struct relay_session
*session
= conn
->session
;
2370 struct lttcomm_relayd_index index_info
;
2371 struct lttcomm_relayd_generic_reply reply
;
2372 struct relay_stream
*stream
;
2377 DBG("Relay receiving index");
2379 if (!session
|| !conn
->version_check_done
) {
2380 ERR("Trying to close a stream before version check");
2382 goto end_no_session
;
2385 msg_len
= lttcomm_relayd_index_len(
2386 lttng_to_index_major(conn
->major
, conn
->minor
),
2387 lttng_to_index_minor(conn
->major
, conn
->minor
));
2388 if (payload
->size
< msg_len
) {
2389 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2390 msg_len
, payload
->size
);
2392 goto end_no_session
;
2394 memcpy(&index_info
, payload
->data
, msg_len
);
2395 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2396 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2397 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2398 index_info
.content_size
= be64toh(index_info
.content_size
);
2399 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2400 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2401 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2402 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2404 if (conn
->minor
>= 8) {
2405 index_info
.stream_instance_id
=
2406 be64toh(index_info
.stream_instance_id
);
2407 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2409 index_info
.stream_instance_id
= -1ULL;
2410 index_info
.packet_seq_num
= -1ULL;
2413 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2415 ERR("stream_get_by_id not found");
2420 pthread_mutex_lock(&stream
->lock
);
2421 ret
= stream_add_index(stream
, &index_info
);
2422 pthread_mutex_unlock(&stream
->lock
);
2424 goto end_stream_put
;
2430 memset(&reply
, 0, sizeof(reply
));
2432 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2434 reply
.ret_code
= htobe32(LTTNG_OK
);
2436 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2437 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2438 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2447 * Receive the streams_sent message.
2449 * Return 0 on success else a negative value.
2451 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2452 struct relay_connection
*conn
,
2453 const struct lttng_buffer_view
*payload
)
2457 struct lttcomm_relayd_generic_reply reply
;
2461 DBG("Relay receiving streams_sent");
2463 if (!conn
->session
|| !conn
->version_check_done
) {
2464 ERR("Trying to close a stream before version check");
2466 goto end_no_session
;
2470 * Publish every pending stream in the connection recv list which are
2471 * now ready to be used by the viewer.
2473 publish_connection_local_streams(conn
);
2475 memset(&reply
, 0, sizeof(reply
));
2476 reply
.ret_code
= htobe32(LTTNG_OK
);
2477 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2478 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2479 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2491 static ssize_t
relay_unpack_rotate_streams_header(
2492 const struct lttng_buffer_view
*payload
,
2493 struct lttcomm_relayd_rotate_streams
*_rotate_streams
)
2495 struct lttcomm_relayd_rotate_streams rotate_streams
;
2497 * Set to the smallest version (packed) of `lttcomm_relayd_rotate_streams`.
2498 * This is the smallest version of this structure, but it can be larger;
2499 * this variable is updated once the proper size of the structure is known.
2501 * See comment at the declaration of this structure for more information.
2503 ssize_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2504 size_t expected_payload_size_no_padding
,
2505 expected_payload_size_3_bytes_padding
,
2506 expected_payload_size_7_bytes_padding
;
2508 if (payload
->size
< header_len
) {
2509 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2510 header_len
, payload
->size
);
2515 * Some versions incorrectly omitted the LTTNG_PACKED annotation on the
2516 * `new_chunk_id` optional field of struct lttcomm_relayd_rotate_streams.
2518 * We start by "unpacking" `stream_count` to figure out the padding length
2519 * emited by our peer.
2521 memcpy(&rotate_streams
.stream_count
, payload
->data
,
2522 sizeof(rotate_streams
.stream_count
));
2523 rotate_streams
= (typeof(rotate_streams
)) {
2524 .stream_count
= be32toh(rotate_streams
.stream_count
),
2528 * Payload size expected given the possible padding lengths in
2529 * `struct lttcomm_relayd_rotate_streams`.
2531 expected_payload_size_no_padding
= (rotate_streams
.stream_count
*
2532 sizeof(*rotate_streams
.rotation_positions
)) +
2533 sizeof(struct lttcomm_relayd_rotate_streams_packed
);
2534 expected_payload_size_3_bytes_padding
= (rotate_streams
.stream_count
*
2535 sizeof(*rotate_streams
.rotation_positions
)) +
2536 sizeof(struct lttcomm_relayd_rotate_streams_3_bytes_padding
);
2537 expected_payload_size_7_bytes_padding
= (rotate_streams
.stream_count
*
2538 sizeof(*rotate_streams
.rotation_positions
)) +
2539 sizeof(struct lttcomm_relayd_rotate_streams_7_bytes_padding
);
2541 if (payload
->size
== expected_payload_size_no_padding
) {
2542 struct lttcomm_relayd_rotate_streams_packed packed_rotate_streams
;
2545 * This handles cases where someone might build with
2546 * -fpack-struct or any other toolchain that wouldn't produce
2547 * padding to align `value`.
2549 DBG("Received `struct lttcomm_relayd_rotate_streams` with no padding");
2551 header_len
= sizeof(packed_rotate_streams
);
2552 memcpy(&packed_rotate_streams
, payload
->data
, header_len
);
2554 /* Unpack the packed structure to the natively-packed version. */
2555 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2556 .stream_count
= be32toh(packed_rotate_streams
.stream_count
),
2557 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2558 .is_set
= !!packed_rotate_streams
.new_chunk_id
.is_set
,
2559 .value
= be64toh(packed_rotate_streams
.new_chunk_id
.value
),
2562 } else if (payload
->size
== expected_payload_size_3_bytes_padding
) {
2563 struct lttcomm_relayd_rotate_streams_3_bytes_padding padded_rotate_streams
;
2565 DBG("Received `struct lttcomm_relayd_rotate_streams` with 3 bytes of padding (4-byte aligned peer)");
2567 header_len
= sizeof(padded_rotate_streams
);
2568 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2570 /* Unpack the 3-byte padded structure to the natively-packed version. */
2571 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2572 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2573 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2574 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2575 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2578 } else if (payload
->size
== expected_payload_size_7_bytes_padding
) {
2579 struct lttcomm_relayd_rotate_streams_7_bytes_padding padded_rotate_streams
;
2581 DBG("Received `struct lttcomm_relayd_rotate_streams` with 7 bytes of padding (8-byte aligned peer)");
2583 header_len
= sizeof(padded_rotate_streams
);
2584 memcpy(&padded_rotate_streams
, payload
->data
, header_len
);
2586 /* Unpack the 7-byte padded structure to the natively-packed version. */
2587 *_rotate_streams
= (typeof(*_rotate_streams
)) {
2588 .stream_count
= be32toh(padded_rotate_streams
.stream_count
),
2589 .new_chunk_id
= (typeof(_rotate_streams
->new_chunk_id
)) {
2590 .is_set
= !!padded_rotate_streams
.new_chunk_id
.is_set
,
2591 .value
= be64toh(padded_rotate_streams
.new_chunk_id
.value
),
2595 header_len
= sizeof(padded_rotate_streams
);
2597 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected %zu, %zu or %zu bytes, got %zu bytes",
2598 expected_payload_size_no_padding
,
2599 expected_payload_size_3_bytes_padding
,
2600 expected_payload_size_7_bytes_padding
,
2611 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2612 * session rotation feature (not the tracefile rotation feature).
2614 static int relay_rotate_session_streams(
2615 const struct lttcomm_relayd_hdr
*recv_hdr
,
2616 struct relay_connection
*conn
,
2617 const struct lttng_buffer_view
*payload
)
2622 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2623 struct relay_session
*session
= conn
->session
;
2624 struct lttcomm_relayd_rotate_streams rotate_streams
;
2625 struct lttcomm_relayd_generic_reply reply
= {};
2626 struct relay_stream
*stream
= NULL
;
2627 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2628 struct lttng_buffer_view stream_positions
;
2629 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2630 const char *chunk_id_str
= "none";
2633 if (!session
|| !conn
->version_check_done
) {
2634 ERR("Trying to rotate a stream before version check");
2639 if (session
->major
== 2 && session
->minor
< 11) {
2640 ERR("Unsupported feature before 2.11");
2645 header_len
= relay_unpack_rotate_streams_header(payload
, &rotate_streams
);
2646 if (header_len
< 0) {
2651 if (rotate_streams
.new_chunk_id
.is_set
) {
2653 * Retrieve the trace chunk the stream must transition to. As
2654 * per the protocol, this chunk should have been created
2655 * before this command is received.
2657 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2658 sessiond_trace_chunk_registry
,
2659 session
->sessiond_uuid
,
2660 conn
->session
->id_sessiond
.is_set
?
2661 conn
->session
->id_sessiond
.value
:
2663 rotate_streams
.new_chunk_id
.value
);
2664 if (!next_trace_chunk
) {
2665 char uuid_str
[LTTNG_UUID_STR_LEN
];
2667 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2668 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2669 ", trace_chunk_id = %" PRIu64
,
2670 uuid_str
, session
->id
,
2671 rotate_streams
.new_chunk_id
.value
);
2672 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2677 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2678 rotate_streams
.new_chunk_id
.value
);
2679 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2680 chunk_id_str
= "formatting error";
2682 chunk_id_str
= chunk_id_buf
;
2686 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2687 rotate_streams
.stream_count
, session
->session_name
,
2690 stream_positions
= lttng_buffer_view_from_view(payload
,
2692 if (!stream_positions
.data
||
2693 stream_positions
.size
<
2694 (rotate_streams
.stream_count
*
2695 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2696 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2701 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2702 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2703 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2704 const struct lttcomm_relayd_stream_rotation_position pos
= {
2705 .stream_id
= be64toh(position_comm
->stream_id
),
2706 .rotate_at_seq_num
= be64toh(
2707 position_comm
->rotate_at_seq_num
),
2710 stream
= stream_get_by_id(pos
.stream_id
);
2712 reply_code
= LTTNG_ERR_INVALID
;
2717 pthread_mutex_lock(&stream
->lock
);
2718 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2719 pos
.rotate_at_seq_num
);
2720 pthread_mutex_unlock(&stream
->lock
);
2722 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2730 reply_code
= LTTNG_OK
;
2737 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2738 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2739 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2740 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2741 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2746 lttng_trace_chunk_put(next_trace_chunk
);
2751 * relay_create_trace_chunk: create a new trace chunk
2753 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2754 struct relay_connection
*conn
,
2755 const struct lttng_buffer_view
*payload
)
2759 struct relay_session
*session
= conn
->session
;
2760 struct lttcomm_relayd_create_trace_chunk
*msg
;
2761 struct lttcomm_relayd_generic_reply reply
= {};
2762 struct lttng_buffer_view header_view
;
2763 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2764 enum lttng_error_code reply_code
= LTTNG_OK
;
2765 enum lttng_trace_chunk_status chunk_status
;
2766 const char *new_path
;
2768 if (!session
|| !conn
->version_check_done
) {
2769 ERR("Trying to create a trace chunk before version check");
2774 if (session
->major
== 2 && session
->minor
< 11) {
2775 ERR("Chunk creation command is unsupported before 2.11");
2780 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2781 if (!lttng_buffer_view_is_valid(&header_view
)) {
2782 ERR("Failed to receive payload of chunk creation command");
2787 /* Convert to host endianness. */
2788 msg
= (typeof(msg
)) header_view
.data
;
2789 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2790 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2791 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2793 pthread_mutex_lock(&conn
->session
->lock
);
2794 session
->ongoing_rotation
= true;
2795 if (session
->current_trace_chunk
&&
2796 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2797 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2798 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2799 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2800 ERR("Failed to rename old chunk");
2802 reply_code
= LTTNG_ERR_UNK
;
2806 if (!session
->current_trace_chunk
) {
2807 if (!session
->has_rotated
) {
2813 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2815 chunk
= lttng_trace_chunk_create(
2816 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2818 ERR("Failed to create trace chunk in trace chunk creation command");
2820 reply_code
= LTTNG_ERR_NOMEM
;
2823 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2825 if (msg
->override_name_length
) {
2827 const struct lttng_buffer_view chunk_name_view
=
2828 lttng_buffer_view_from_view(payload
,
2830 msg
->override_name_length
);
2832 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2833 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2835 reply_code
= LTTNG_ERR_INVALID
;
2839 name
= chunk_name_view
.data
;
2840 if (name
[msg
->override_name_length
- 1]) {
2841 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2843 reply_code
= LTTNG_ERR_INVALID
;
2847 chunk_status
= lttng_trace_chunk_override_name(
2848 chunk
, chunk_name_view
.data
);
2849 switch (chunk_status
) {
2850 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2852 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2853 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2854 reply_code
= LTTNG_ERR_INVALID
;
2858 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2859 reply_code
= LTTNG_ERR_UNK
;
2865 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2866 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2867 reply_code
= LTTNG_ERR_UNK
;
2872 assert(conn
->session
->output_directory
);
2873 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2874 conn
->session
->output_directory
);
2875 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2876 reply_code
= LTTNG_ERR_UNK
;
2881 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2882 sessiond_trace_chunk_registry
,
2883 conn
->session
->sessiond_uuid
,
2884 conn
->session
->id_sessiond
.is_set
?
2885 conn
->session
->id_sessiond
.value
:
2888 if (!published_chunk
) {
2889 char uuid_str
[LTTNG_UUID_STR_LEN
];
2891 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2892 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2897 reply_code
= LTTNG_ERR_NOMEM
;
2901 if (conn
->session
->pending_closure_trace_chunk
) {
2903 * Invalid; this means a second create_trace_chunk command was
2904 * received before a close_trace_chunk.
2906 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2907 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2911 conn
->session
->pending_closure_trace_chunk
=
2912 conn
->session
->current_trace_chunk
;
2913 conn
->session
->current_trace_chunk
= published_chunk
;
2914 published_chunk
= NULL
;
2915 if (!conn
->session
->pending_closure_trace_chunk
) {
2916 session
->ongoing_rotation
= false;
2919 pthread_mutex_unlock(&conn
->session
->lock
);
2920 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2921 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2923 sizeof(struct lttcomm_relayd_generic_reply
),
2925 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2926 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2931 lttng_trace_chunk_put(chunk
);
2932 lttng_trace_chunk_put(published_chunk
);
2937 * relay_close_trace_chunk: close a trace chunk
2939 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2940 struct relay_connection
*conn
,
2941 const struct lttng_buffer_view
*payload
)
2943 int ret
= 0, buf_ret
;
2945 struct relay_session
*session
= conn
->session
;
2946 struct lttcomm_relayd_close_trace_chunk
*msg
;
2947 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2948 struct lttng_buffer_view header_view
;
2949 struct lttng_trace_chunk
*chunk
= NULL
;
2950 enum lttng_error_code reply_code
= LTTNG_OK
;
2951 enum lttng_trace_chunk_status chunk_status
;
2953 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2954 time_t close_timestamp
;
2955 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2956 size_t path_length
= 0;
2957 const char *chunk_name
= NULL
;
2958 struct lttng_dynamic_buffer reply_payload
;
2959 const char *new_path
;
2961 lttng_dynamic_buffer_init(&reply_payload
);
2963 if (!session
|| !conn
->version_check_done
) {
2964 ERR("Trying to close a trace chunk before version check");
2969 if (session
->major
== 2 && session
->minor
< 11) {
2970 ERR("Chunk close command is unsupported before 2.11");
2975 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2976 if (!lttng_buffer_view_is_valid(&header_view
)) {
2977 ERR("Failed to receive payload of chunk close command");
2982 /* Convert to host endianness. */
2983 msg
= (typeof(msg
)) header_view
.data
;
2984 chunk_id
= be64toh(msg
->chunk_id
);
2985 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2986 close_command
= (typeof(close_command
)){
2987 .value
= be32toh(msg
->close_command
.value
),
2988 .is_set
= msg
->close_command
.is_set
,
2991 chunk
= sessiond_trace_chunk_registry_get_chunk(
2992 sessiond_trace_chunk_registry
,
2993 conn
->session
->sessiond_uuid
,
2994 conn
->session
->id_sessiond
.is_set
?
2995 conn
->session
->id_sessiond
.value
:
2999 char uuid_str
[LTTNG_UUID_STR_LEN
];
3001 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
3002 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
3007 reply_code
= LTTNG_ERR_NOMEM
;
3011 pthread_mutex_lock(&session
->lock
);
3012 if (close_command
.is_set
&&
3013 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
3015 * Clear command. It is a protocol error to ask for a
3016 * clear on a relay which does not allow it. Querying
3017 * the configuration allows figuring out whether
3018 * clearing is allowed before doing the clear.
3020 if (!opt_allow_clear
) {
3022 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3023 goto end_unlock_session
;
3026 if (session
->pending_closure_trace_chunk
&&
3027 session
->pending_closure_trace_chunk
!= chunk
) {
3028 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
3029 session
->session_name
);
3030 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3032 goto end_unlock_session
;
3035 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
3036 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
3037 if (close_command
.is_set
&&
3038 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
3039 !session
->has_rotated
) {
3040 /* New chunk stays in session output directory. */
3043 /* Use chunk name for new chunk. */
3046 /* Rename new chunk path. */
3047 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
3049 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3051 goto end_unlock_session
;
3053 session
->ongoing_rotation
= false;
3055 if ((!close_command
.is_set
||
3056 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
3057 !lttng_trace_chunk_get_name_overridden(chunk
)) {
3058 const char *old_path
;
3060 if (!session
->has_rotated
) {
3065 /* We need to move back the .tmp_old_chunk to its rightful place. */
3066 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
3067 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3069 goto end_unlock_session
;
3072 chunk_status
= lttng_trace_chunk_set_close_timestamp(
3073 chunk
, close_timestamp
);
3074 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3075 ERR("Failed to set trace chunk close timestamp");
3077 reply_code
= LTTNG_ERR_UNK
;
3078 goto end_unlock_session
;
3081 if (close_command
.is_set
) {
3082 chunk_status
= lttng_trace_chunk_set_close_command(
3083 chunk
, close_command
.value
);
3084 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3086 reply_code
= LTTNG_ERR_INVALID
;
3087 goto end_unlock_session
;
3090 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
3091 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
3092 ERR("Failed to get chunk name");
3094 reply_code
= LTTNG_ERR_UNK
;
3095 goto end_unlock_session
;
3097 if (!session
->has_rotated
&& !session
->snapshot
) {
3098 ret
= lttng_strncpy(closed_trace_chunk_path
,
3099 session
->output_path
,
3100 sizeof(closed_trace_chunk_path
));
3102 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3103 strlen(session
->output_path
),
3104 sizeof(closed_trace_chunk_path
));
3105 reply_code
= LTTNG_ERR_NOMEM
;
3107 goto end_unlock_session
;
3110 if (session
->snapshot
) {
3111 ret
= snprintf(closed_trace_chunk_path
,
3112 sizeof(closed_trace_chunk_path
),
3113 "%s/%s", session
->output_path
,
3116 ret
= snprintf(closed_trace_chunk_path
,
3117 sizeof(closed_trace_chunk_path
),
3118 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3120 session
->output_path
, chunk_name
);
3122 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3123 ERR("Failed to format closed trace chunk resulting path");
3124 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3126 goto end_unlock_session
;
3129 if (close_command
.is_set
&&
3130 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3131 session
->has_rotated
= true;
3133 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3134 path_length
= strlen(closed_trace_chunk_path
) + 1;
3135 if (path_length
> UINT32_MAX
) {
3136 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3138 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3139 goto end_unlock_session
;
3142 if (session
->current_trace_chunk
== chunk
) {
3144 * After a trace chunk close command, no new streams
3145 * referencing the chunk may be created. Hence, on the
3146 * event that no new trace chunk have been created for
3147 * the session, the reference to the current trace chunk
3148 * is released in order to allow it to be reclaimed when
3149 * the last stream releases its reference to it.
3151 lttng_trace_chunk_put(session
->current_trace_chunk
);
3152 session
->current_trace_chunk
= NULL
;
3154 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3155 session
->pending_closure_trace_chunk
= NULL
;
3157 pthread_mutex_unlock(&session
->lock
);
3160 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3161 reply
.path_length
= htobe32((uint32_t) path_length
);
3162 buf_ret
= lttng_dynamic_buffer_append(
3163 &reply_payload
, &reply
, sizeof(reply
));
3165 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3169 if (reply_code
== LTTNG_OK
) {
3170 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3171 closed_trace_chunk_path
, path_length
);
3173 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3178 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3182 if (send_ret
< reply_payload
.size
) {
3183 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3184 reply_payload
.size
, send_ret
);
3189 lttng_trace_chunk_put(chunk
);
3190 lttng_dynamic_buffer_reset(&reply_payload
);
3195 * relay_trace_chunk_exists: check if a trace chunk exists
3197 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3198 struct relay_connection
*conn
,
3199 const struct lttng_buffer_view
*payload
)
3203 struct relay_session
*session
= conn
->session
;
3204 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3205 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3206 struct lttng_buffer_view header_view
;
3210 if (!session
|| !conn
->version_check_done
) {
3211 ERR("Trying to check for the existance of a trace chunk before version check");
3216 if (session
->major
== 2 && session
->minor
< 11) {
3217 ERR("Chunk exists command is unsupported before 2.11");
3222 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3223 if (!lttng_buffer_view_is_valid(&header_view
)) {
3224 ERR("Failed to receive payload of chunk exists command");
3229 /* Convert to host endianness. */
3230 msg
= (typeof(msg
)) header_view
.data
;
3231 chunk_id
= be64toh(msg
->chunk_id
);
3233 ret
= sessiond_trace_chunk_registry_chunk_exists(
3234 sessiond_trace_chunk_registry
,
3235 conn
->session
->sessiond_uuid
,
3237 chunk_id
, &chunk_exists
);
3239 * If ret is not 0, send the reply and report the error to the caller.
3240 * It is a protocol (or internal) error and the session/connection
3241 * should be torn down.
3243 reply
= (typeof(reply
)){
3244 .generic
.ret_code
= htobe32((uint32_t)
3245 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3246 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
3248 send_ret
= conn
->sock
->ops
->sendmsg(
3249 conn
->sock
, &reply
, sizeof(reply
), 0);
3250 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3251 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3260 * relay_get_configuration: query whether feature is available
3262 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3263 struct relay_connection
*conn
,
3264 const struct lttng_buffer_view
*payload
)
3268 struct lttcomm_relayd_get_configuration
*msg
;
3269 struct lttcomm_relayd_get_configuration_reply reply
= {};
3270 struct lttng_buffer_view header_view
;
3271 uint64_t query_flags
= 0;
3272 uint64_t result_flags
= 0;
3274 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3275 if (!lttng_buffer_view_is_valid(&header_view
)) {
3276 ERR("Failed to receive payload of chunk close command");
3281 /* Convert to host endianness. */
3282 msg
= (typeof(msg
)) header_view
.data
;
3283 query_flags
= be64toh(msg
->query_flags
);
3286 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3289 if (opt_allow_clear
) {
3290 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3294 reply
= (typeof(reply
)){
3295 .generic
.ret_code
= htobe32((uint32_t)
3296 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3297 .relayd_configuration_flags
= htobe64(result_flags
),
3299 send_ret
= conn
->sock
->ops
->sendmsg(
3300 conn
->sock
, &reply
, sizeof(reply
), 0);
3301 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3302 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3310 #define DBG_CMD(cmd_name, conn) \
3311 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3313 static int relay_process_control_command(struct relay_connection
*conn
,
3314 const struct lttcomm_relayd_hdr
*header
,
3315 const struct lttng_buffer_view
*payload
)
3319 switch (header
->cmd
) {
3320 case RELAYD_CREATE_SESSION
:
3321 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3322 ret
= relay_create_session(header
, conn
, payload
);
3324 case RELAYD_ADD_STREAM
:
3325 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3326 ret
= relay_add_stream(header
, conn
, payload
);
3328 case RELAYD_START_DATA
:
3329 DBG_CMD("RELAYD_START_DATA", conn
);
3330 ret
= relay_start(header
, conn
, payload
);
3332 case RELAYD_SEND_METADATA
:
3333 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3334 ret
= relay_recv_metadata(header
, conn
, payload
);
3336 case RELAYD_VERSION
:
3337 DBG_CMD("RELAYD_VERSION", conn
);
3338 ret
= relay_send_version(header
, conn
, payload
);
3340 case RELAYD_CLOSE_STREAM
:
3341 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3342 ret
= relay_close_stream(header
, conn
, payload
);
3344 case RELAYD_DATA_PENDING
:
3345 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3346 ret
= relay_data_pending(header
, conn
, payload
);
3348 case RELAYD_QUIESCENT_CONTROL
:
3349 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3350 ret
= relay_quiescent_control(header
, conn
, payload
);
3352 case RELAYD_BEGIN_DATA_PENDING
:
3353 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3354 ret
= relay_begin_data_pending(header
, conn
, payload
);
3356 case RELAYD_END_DATA_PENDING
:
3357 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3358 ret
= relay_end_data_pending(header
, conn
, payload
);
3360 case RELAYD_SEND_INDEX
:
3361 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3362 ret
= relay_recv_index(header
, conn
, payload
);
3364 case RELAYD_STREAMS_SENT
:
3365 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3366 ret
= relay_streams_sent(header
, conn
, payload
);
3368 case RELAYD_RESET_METADATA
:
3369 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3370 ret
= relay_reset_metadata(header
, conn
, payload
);
3372 case RELAYD_ROTATE_STREAMS
:
3373 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3374 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3376 case RELAYD_CREATE_TRACE_CHUNK
:
3377 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3378 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3380 case RELAYD_CLOSE_TRACE_CHUNK
:
3381 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3382 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3384 case RELAYD_TRACE_CHUNK_EXISTS
:
3385 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3386 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3388 case RELAYD_GET_CONFIGURATION
:
3389 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3390 ret
= relay_get_configuration(header
, conn
, payload
);
3392 case RELAYD_UPDATE_SYNC_INFO
:
3394 ERR("Received unknown command (%u)", header
->cmd
);
3395 relay_unknown_command(conn
);
3404 static enum relay_connection_status
relay_process_control_receive_payload(
3405 struct relay_connection
*conn
)
3408 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3409 struct lttng_dynamic_buffer
*reception_buffer
=
3410 &conn
->protocol
.ctrl
.reception_buffer
;
3411 struct ctrl_connection_state_receive_payload
*state
=
3412 &conn
->protocol
.ctrl
.state
.receive_payload
;
3413 struct lttng_buffer_view payload_view
;
3415 if (state
->left_to_receive
== 0) {
3416 /* Short-circuit for payload-less commands. */
3417 goto reception_complete
;
3420 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3421 reception_buffer
->data
+ state
->received
,
3422 state
->left_to_receive
, MSG_DONTWAIT
);
3424 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3425 PERROR("Unable to receive command payload on sock %d",
3427 status
= RELAY_CONNECTION_STATUS_ERROR
;
3430 } else if (ret
== 0) {
3431 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3432 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3437 assert(ret
<= state
->left_to_receive
);
3439 state
->left_to_receive
-= ret
;
3440 state
->received
+= ret
;
3442 if (state
->left_to_receive
> 0) {
3444 * Can't transition to the protocol's next state, wait to
3445 * receive the rest of the header.
3447 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3448 state
->received
, state
->left_to_receive
,
3454 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3455 conn
->sock
->fd
, state
->received
);
3457 * The payload required to process the command has been received.
3458 * A view to the reception buffer is forwarded to the various
3459 * commands and the state of the control is reset on success.
3461 * Commands are responsible for sending their reply to the peer.
3463 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3465 ret
= relay_process_control_command(conn
,
3466 &state
->header
, &payload_view
);
3468 status
= RELAY_CONNECTION_STATUS_ERROR
;
3472 ret
= connection_reset_protocol_state(conn
);
3474 status
= RELAY_CONNECTION_STATUS_ERROR
;
3480 static enum relay_connection_status
relay_process_control_receive_header(
3481 struct relay_connection
*conn
)
3484 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3485 struct lttcomm_relayd_hdr header
;
3486 struct lttng_dynamic_buffer
*reception_buffer
=
3487 &conn
->protocol
.ctrl
.reception_buffer
;
3488 struct ctrl_connection_state_receive_header
*state
=
3489 &conn
->protocol
.ctrl
.state
.receive_header
;
3491 assert(state
->left_to_receive
!= 0);
3493 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3494 reception_buffer
->data
+ state
->received
,
3495 state
->left_to_receive
, MSG_DONTWAIT
);
3497 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3498 PERROR("Unable to receive control command header on sock %d",
3500 status
= RELAY_CONNECTION_STATUS_ERROR
;
3503 } else if (ret
== 0) {
3504 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3505 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3510 assert(ret
<= state
->left_to_receive
);
3512 state
->left_to_receive
-= ret
;
3513 state
->received
+= ret
;
3515 if (state
->left_to_receive
> 0) {
3517 * Can't transition to the protocol's next state, wait to
3518 * receive the rest of the header.
3520 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3521 state
->received
, state
->left_to_receive
,
3526 /* Transition to next state: receiving the command's payload. */
3527 conn
->protocol
.ctrl
.state_id
=
3528 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3529 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3530 header
.circuit_id
= be64toh(header
.circuit_id
);
3531 header
.data_size
= be64toh(header
.data_size
);
3532 header
.cmd
= be32toh(header
.cmd
);
3533 header
.cmd_version
= be32toh(header
.cmd_version
);
3534 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3535 &header
, sizeof(header
));
3537 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3538 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3541 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3542 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3544 status
= RELAY_CONNECTION_STATUS_ERROR
;
3548 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3550 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3551 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3554 status
= RELAY_CONNECTION_STATUS_ERROR
;
3558 if (header
.data_size
== 0) {
3560 * Manually invoke the next state as the poll loop
3561 * will not wake-up to allow us to proceed further.
3563 status
= relay_process_control_receive_payload(conn
);
3570 * Process the commands received on the control socket
3572 static enum relay_connection_status
relay_process_control(
3573 struct relay_connection
*conn
)
3575 enum relay_connection_status status
;
3577 switch (conn
->protocol
.ctrl
.state_id
) {
3578 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3579 status
= relay_process_control_receive_header(conn
);
3581 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3582 status
= relay_process_control_receive_payload(conn
);
3585 ERR("Unknown control connection protocol state encountered.");
3592 static enum relay_connection_status
relay_process_data_receive_header(
3593 struct relay_connection
*conn
)
3596 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3597 struct data_connection_state_receive_header
*state
=
3598 &conn
->protocol
.data
.state
.receive_header
;
3599 struct lttcomm_relayd_data_hdr header
;
3600 struct relay_stream
*stream
;
3602 assert(state
->left_to_receive
!= 0);
3604 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3605 state
->header_reception_buffer
+ state
->received
,
3606 state
->left_to_receive
, MSG_DONTWAIT
);
3608 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3609 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3610 status
= RELAY_CONNECTION_STATUS_ERROR
;
3613 } else if (ret
== 0) {
3614 /* Orderly shutdown. Not necessary to print an error. */
3615 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3616 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3621 assert(ret
<= state
->left_to_receive
);
3623 state
->left_to_receive
-= ret
;
3624 state
->received
+= ret
;
3626 if (state
->left_to_receive
> 0) {
3628 * Can't transition to the protocol's next state, wait to
3629 * receive the rest of the header.
3631 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3632 state
->received
, state
->left_to_receive
,
3637 /* Transition to next state: receiving the payload. */
3638 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3640 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3641 header
.circuit_id
= be64toh(header
.circuit_id
);
3642 header
.stream_id
= be64toh(header
.stream_id
);
3643 header
.data_size
= be32toh(header
.data_size
);
3644 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3645 header
.padding_size
= be32toh(header
.padding_size
);
3646 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3648 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3650 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3651 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3653 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3654 conn
->sock
->fd
, header
.circuit_id
,
3655 header
.stream_id
, header
.data_size
,
3656 header
.net_seq_num
, header
.padding_size
);
3658 stream
= stream_get_by_id(header
.stream_id
);
3660 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3662 /* Protocol error. */
3663 status
= RELAY_CONNECTION_STATUS_ERROR
;
3667 pthread_mutex_lock(&stream
->lock
);
3668 /* Prepare stream for the reception of a new packet. */
3669 ret
= stream_init_packet(stream
, header
.data_size
,
3670 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3671 pthread_mutex_unlock(&stream
->lock
);
3673 ERR("Failed to rotate stream output file");
3674 status
= RELAY_CONNECTION_STATUS_ERROR
;
3675 goto end_stream_unlock
;
3684 static enum relay_connection_status
relay_process_data_receive_payload(
3685 struct relay_connection
*conn
)
3688 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3689 struct relay_stream
*stream
;
3690 struct data_connection_state_receive_payload
*state
=
3691 &conn
->protocol
.data
.state
.receive_payload
;
3692 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3693 char data_buffer
[chunk_size
];
3694 bool partial_recv
= false;
3695 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3696 uint64_t left_to_receive
= state
->left_to_receive
;
3697 struct relay_session
*session
;
3699 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3700 state
->header
.stream_id
, state
->header
.net_seq_num
,
3701 state
->received
, left_to_receive
);
3703 stream
= stream_get_by_id(state
->header
.stream_id
);
3705 /* Protocol error. */
3706 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3707 state
->header
.stream_id
);
3708 status
= RELAY_CONNECTION_STATUS_ERROR
;
3712 pthread_mutex_lock(&stream
->lock
);
3713 session
= stream
->trace
->session
;
3714 if (!conn
->session
) {
3715 ret
= connection_set_session(conn
, session
);
3717 status
= RELAY_CONNECTION_STATUS_ERROR
;
3718 goto end_stream_unlock
;
3723 * The size of the "chunk" received on any iteration is bounded by:
3724 * - the data left to receive,
3725 * - the data immediately available on the socket,
3726 * - the on-stack data buffer
3728 while (left_to_receive
> 0 && !partial_recv
) {
3729 size_t recv_size
= min(left_to_receive
, chunk_size
);
3730 struct lttng_buffer_view packet_chunk
;
3732 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3733 recv_size
, MSG_DONTWAIT
);
3735 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3736 PERROR("Socket %d error", conn
->sock
->fd
);
3737 status
= RELAY_CONNECTION_STATUS_ERROR
;
3739 goto end_stream_unlock
;
3740 } else if (ret
== 0) {
3741 /* No more data ready to be consumed on socket. */
3742 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3743 state
->header
.stream_id
);
3744 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3746 } else if (ret
< (int) recv_size
) {
3748 * All the data available on the socket has been
3751 partial_recv
= true;
3755 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3757 assert(packet_chunk
.data
);
3759 ret
= stream_write(stream
, &packet_chunk
, 0);
3761 ERR("Relay error writing data to file");
3762 status
= RELAY_CONNECTION_STATUS_ERROR
;
3763 goto end_stream_unlock
;
3766 left_to_receive
-= recv_size
;
3767 state
->received
+= recv_size
;
3768 state
->left_to_receive
= left_to_receive
;
3771 if (state
->left_to_receive
> 0) {
3773 * Did not receive all the data expected, wait for more data to
3774 * become available on the socket.
3776 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3777 state
->header
.stream_id
, state
->received
,
3778 state
->left_to_receive
);
3779 goto end_stream_unlock
;
3782 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3784 status
= RELAY_CONNECTION_STATUS_ERROR
;
3785 goto end_stream_unlock
;
3788 if (session_streams_have_index(session
)) {
3789 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3790 state
->rotate_index
, &index_flushed
,
3791 state
->header
.data_size
+ state
->header
.padding_size
);
3793 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3794 stream
->stream_handle
,
3795 state
->header
.net_seq_num
, ret
);
3796 status
= RELAY_CONNECTION_STATUS_ERROR
;
3797 goto end_stream_unlock
;
3801 if (stream
->prev_data_seq
== -1ULL) {
3805 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3806 state
->header
.padding_size
, state
->header
.net_seq_num
,
3809 status
= RELAY_CONNECTION_STATUS_ERROR
;
3810 goto end_stream_unlock
;
3814 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3815 * contents of *state which are aliased (union) to the same location as
3816 * the new state. Don't use it beyond this point.
3818 connection_reset_protocol_state(conn
);
3822 close_requested
= stream
->close_requested
;
3823 pthread_mutex_unlock(&stream
->lock
);
3824 if (close_requested
&& left_to_receive
== 0) {
3825 try_stream_close(stream
);
3829 pthread_mutex_lock(&session
->lock
);
3830 uatomic_set(&session
->new_streams
, 1);
3831 pthread_mutex_unlock(&session
->lock
);
3840 * relay_process_data: Process the data received on the data socket
3842 static enum relay_connection_status
relay_process_data(
3843 struct relay_connection
*conn
)
3845 enum relay_connection_status status
;
3847 switch (conn
->protocol
.data
.state_id
) {
3848 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3849 status
= relay_process_data_receive_header(conn
);
3851 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3852 status
= relay_process_data_receive_payload(conn
);
3855 ERR("Unexpected data connection communication state.");
3862 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3866 (void) lttng_poll_del(events
, pollfd
);
3868 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3869 fd_tracker_util_close_fd
, NULL
);
3871 ERR("Closing pollfd %d", pollfd
);
3875 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3876 int pollfd
, struct relay_connection
*conn
)
3878 const char *type_str
;
3880 switch (conn
->type
) {
3885 type_str
= "Control";
3887 case RELAY_VIEWER_COMMAND
:
3888 type_str
= "Viewer Command";
3890 case RELAY_VIEWER_NOTIFICATION
:
3891 type_str
= "Viewer Notification";
3894 type_str
= "Unknown";
3896 cleanup_connection_pollfd(events
, pollfd
);
3897 connection_put(conn
);
3898 DBG("%s connection closed with %d", type_str
, pollfd
);
3902 * This thread does the actual work
3904 static void *relay_thread_worker(void *data
)
3906 int ret
, err
= -1, last_seen_data_fd
= -1;
3908 struct lttng_poll_event events
;
3909 struct lttng_ht
*relay_connections_ht
;
3910 struct lttng_ht_iter iter
;
3911 struct relay_connection
*destroy_conn
= NULL
;
3913 DBG("[thread] Relay worker started");
3915 rcu_register_thread();
3917 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3919 if (testpoint(relayd_thread_worker
)) {
3920 goto error_testpoint
;
3923 health_code_update();
3925 /* table of connections indexed on socket */
3926 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3927 if (!relay_connections_ht
) {
3928 goto relay_connections_ht_error
;
3931 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3933 goto error_poll_create
;
3936 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3943 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3945 health_code_update();
3947 /* Infinite blocking call, waiting for transmission */
3948 DBG3("Relayd worker thread polling...");
3949 health_poll_entry();
3950 ret
= lttng_poll_wait(&events
, -1);
3954 * Restart interrupted system call.
3956 if (errno
== EINTR
) {
3965 * Process control. The control connection is
3966 * prioritized so we don't starve it with high
3967 * throughput tracing data on the data connection.
3969 for (i
= 0; i
< nb_fd
; i
++) {
3970 /* Fetch once the poll data */
3971 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3972 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3974 health_code_update();
3976 /* Thread quit pipe has been closed. Killing thread. */
3977 ret
= check_thread_quit_pipe(pollfd
, revents
);
3983 /* Inspect the relay conn pipe for new connection */
3984 if (pollfd
== relay_conn_pipe
[0]) {
3985 if (revents
& LPOLLIN
) {
3986 struct relay_connection
*conn
;
3988 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3992 ret
= lttng_poll_add(&events
,
3994 LPOLLIN
| LPOLLRDHUP
);
3996 ERR("Failed to add new connection file descriptor to poll set");
3999 connection_ht_add(relay_connections_ht
, conn
);
4000 DBG("Connection socket %d added", conn
->sock
->fd
);
4001 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4002 ERR("Relay connection pipe error");
4005 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
4009 struct relay_connection
*ctrl_conn
;
4011 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4012 /* If not found, there is a synchronization issue. */
4015 if (ctrl_conn
->type
== RELAY_DATA
) {
4016 if (revents
& LPOLLIN
) {
4018 * Flag the last seen data fd not deleted. It will be
4019 * used as the last seen fd if any fd gets deleted in
4022 last_notdel_data_fd
= pollfd
;
4024 goto put_ctrl_connection
;
4026 assert(ctrl_conn
->type
== RELAY_CONTROL
);
4028 if (revents
& LPOLLIN
) {
4029 enum relay_connection_status status
;
4031 status
= relay_process_control(ctrl_conn
);
4032 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4034 * On socket error flag the session as aborted to force
4035 * the cleanup of its stream otherwise it can leak
4036 * during the lifetime of the relayd.
4038 * This prevents situations in which streams can be
4039 * left opened because an index was received, the
4040 * control connection is closed, and the data
4041 * connection is closed (uncleanly) before the packet's
4044 * Since the control connection encountered an error,
4045 * it is okay to be conservative and close the
4046 * session right now as we can't rely on the protocol
4047 * being respected anymore.
4049 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4050 session_abort(ctrl_conn
->session
);
4053 /* Clear the connection on error or close. */
4054 relay_thread_close_connection(&events
,
4059 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4060 relay_thread_close_connection(&events
,
4062 if (last_seen_data_fd
== pollfd
) {
4063 last_seen_data_fd
= last_notdel_data_fd
;
4066 ERR("Unexpected poll events %u for control sock %d",
4068 connection_put(ctrl_conn
);
4071 put_ctrl_connection
:
4072 connection_put(ctrl_conn
);
4077 * The last loop handled a control request, go back to poll to make
4078 * sure we prioritise the control socket.
4084 if (last_seen_data_fd
>= 0) {
4085 for (i
= 0; i
< nb_fd
; i
++) {
4086 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4088 health_code_update();
4090 if (last_seen_data_fd
== pollfd
) {
4097 /* Process data connection. */
4098 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4099 /* Fetch the poll data. */
4100 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4101 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4102 struct relay_connection
*data_conn
;
4104 health_code_update();
4107 /* No activity for this FD (poll implementation). */
4111 /* Skip the command pipe. It's handled in the first loop. */
4112 if (pollfd
== relay_conn_pipe
[0]) {
4116 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4118 /* Skip it. Might be removed before. */
4121 if (data_conn
->type
== RELAY_CONTROL
) {
4122 goto put_data_connection
;
4124 assert(data_conn
->type
== RELAY_DATA
);
4126 if (revents
& LPOLLIN
) {
4127 enum relay_connection_status status
;
4129 status
= relay_process_data(data_conn
);
4130 /* Connection closed or error. */
4131 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4133 * On socket error flag the session as aborted to force
4134 * the cleanup of its stream otherwise it can leak
4135 * during the lifetime of the relayd.
4137 * This prevents situations in which streams can be
4138 * left opened because an index was received, the
4139 * control connection is closed, and the data
4140 * connection is closed (uncleanly) before the packet's
4143 * Since the data connection encountered an error,
4144 * it is okay to be conservative and close the
4145 * session right now as we can't rely on the protocol
4146 * being respected anymore.
4148 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4149 session_abort(data_conn
->session
);
4151 relay_thread_close_connection(&events
, pollfd
,
4154 * Every goto restart call sets the last seen fd where
4155 * here we don't really care since we gracefully
4156 * continue the loop after the connection is deleted.
4159 /* Keep last seen port. */
4160 last_seen_data_fd
= pollfd
;
4161 connection_put(data_conn
);
4164 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4165 relay_thread_close_connection(&events
, pollfd
,
4168 ERR("Unknown poll events %u for data sock %d",
4171 put_data_connection
:
4172 connection_put(data_conn
);
4174 last_seen_data_fd
= -1;
4177 /* Normal exit, no error */
4182 /* Cleanup remaining connection object. */
4184 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4187 health_code_update();
4189 session_abort(destroy_conn
->session
);
4192 * No need to grab another ref, because we own
4195 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4200 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4202 lttng_ht_destroy(relay_connections_ht
);
4203 relay_connections_ht_error
:
4204 /* Close relay conn pipes */
4205 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4208 DBG("Thread exited with error");
4210 DBG("Worker thread cleanup complete");
4214 ERR("Health error occurred in %s", __func__
);
4216 health_unregister(health_relayd
);
4217 rcu_unregister_thread();
4218 lttng_relay_stop_threads();
4223 * Create the relay command pipe to wake thread_manage_apps.
4224 * Closed in cleanup().
4226 static int create_relay_conn_pipe(void)
4228 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4229 "Relayd connection pipe", relay_conn_pipe
);
4232 static int stdio_open(void *data
, int *fds
)
4234 fds
[0] = fileno(stdout
);
4235 fds
[1] = fileno(stderr
);
4239 static int track_stdio(void)
4242 const char *names
[] = { "stdout", "stderr" };
4244 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4245 names
, 2, stdio_open
, NULL
);
4251 int main(int argc
, char **argv
)
4253 bool thread_is_rcu_registered
= false;
4254 int ret
= 0, retval
= 0;
4256 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4258 /* Parse environment variables */
4259 ret
= parse_env_options();
4267 * Command line arguments overwrite environment.
4270 if (set_options(argc
, argv
)) {
4275 if (set_signal_handler()) {
4280 relayd_config_log();
4282 if (opt_print_version
) {
4288 ret
= fclose(stdin
);
4290 PERROR("Failed to close stdin");
4294 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4296 /* Try to create directory if -o, --output is specified. */
4297 if (opt_output_path
) {
4298 if (*opt_output_path
!= '/') {
4299 ERR("Please specify an absolute path for -o, --output PATH");
4304 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4307 ERR("Unable to create %s", opt_output_path
);
4314 if (opt_daemon
|| opt_background
) {
4315 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4323 if (opt_working_directory
) {
4324 ret
= utils_change_working_directory(opt_working_directory
);
4326 /* All errors are already logged. */
4331 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4332 if (!sessiond_trace_chunk_registry
) {
4333 ERR("Failed to initialize session daemon trace chunk registry");
4339 * The RCU thread registration (and use, through the fd-tracker's
4340 * creation) is done after the daemonization to allow us to not
4341 * deal with liburcu's fork() management as the call RCU needs to
4344 rcu_register_thread();
4345 thread_is_rcu_registered
= true;
4347 output_path
= create_output_path("");
4349 ERR("Failed to get output path");
4353 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4354 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4357 ERR("Failed to format unlinked file directory path");
4361 the_fd_tracker
= fd_tracker_create(
4362 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4363 free(unlinked_file_directory_path
);
4364 if (!the_fd_tracker
) {
4369 ret
= track_stdio();
4375 /* Initialize thread health monitoring */
4376 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4377 if (!health_relayd
) {
4378 PERROR("health_app_create error");
4383 /* Create thread quit pipe */
4384 if (init_thread_quit_pipe()) {
4389 /* Setup the thread apps communication pipe. */
4390 if (create_relay_conn_pipe()) {
4395 /* Init relay command queue. */
4396 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4398 /* Initialize communication library */
4400 lttcomm_inet_init();
4402 /* tables of sessions indexed by session ID */
4403 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4409 /* tables of streams indexed by stream ID */
4410 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4411 if (!relay_streams_ht
) {
4416 /* tables of streams indexed by stream ID */
4417 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4418 if (!viewer_streams_ht
) {
4423 ret
= init_health_quit_pipe();
4429 /* Create thread to manage the client socket */
4430 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4431 thread_manage_health
, (void *) NULL
);
4434 PERROR("pthread_create health");
4439 /* Setup the dispatcher thread */
4440 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4441 relay_thread_dispatcher
, (void *) NULL
);
4444 PERROR("pthread_create dispatcher");
4446 goto exit_dispatcher_thread
;
4449 /* Setup the worker thread */
4450 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4451 relay_thread_worker
, NULL
);
4454 PERROR("pthread_create worker");
4456 goto exit_worker_thread
;
4459 /* Setup the listener thread */
4460 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4461 relay_thread_listener
, (void *) NULL
);
4464 PERROR("pthread_create listener");
4466 goto exit_listener_thread
;
4469 ret
= relayd_live_create(live_uri
);
4471 ERR("Starting live viewer threads");
4477 * This is where we start awaiting program completion (e.g. through
4478 * signal that asks threads to teardown).
4481 ret
= relayd_live_join();
4487 ret
= pthread_join(listener_thread
, &status
);
4490 PERROR("pthread_join listener_thread");
4494 exit_listener_thread
:
4495 ret
= pthread_join(worker_thread
, &status
);
4498 PERROR("pthread_join worker_thread");
4503 ret
= pthread_join(dispatcher_thread
, &status
);
4506 PERROR("pthread_join dispatcher_thread");
4509 exit_dispatcher_thread
:
4511 ret
= pthread_join(health_thread
, &status
);
4514 PERROR("pthread_join health_thread");
4519 * Wait for all pending call_rcu work to complete before tearing
4520 * down data structures. call_rcu worker may be trying to
4521 * perform lookups in those structures.
4526 /* Ensure all prior call_rcu are done. */
4529 if (thread_is_rcu_registered
) {
4530 rcu_unregister_thread();