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/align.h>
52 #include <common/config/session-config.h>
53 #include <common/dynamic-buffer.h>
54 #include <common/buffer-view.h>
55 #include <common/string-utils/format.h>
56 #include <common/fd-tracker/fd-tracker.h>
57 #include <common/fd-tracker/utils.h>
59 #include "backward-compatibility-group-by.h"
61 #include "connection.h"
62 #include "ctf-trace.h"
63 #include "health-relayd.h"
66 #include "lttng-relayd.h"
68 #include "sessiond-trace-chunks.h"
70 #include "tcp_keep_alive.h"
71 #include "testpoint.h"
72 #include "tracefile-array.h"
75 #include "viewer-stream.h"
77 static const char *help_msg
=
78 #ifdef LTTNG_EMBED_HELP
79 #include <lttng-relayd.8.h>
85 enum relay_connection_status
{
86 RELAY_CONNECTION_STATUS_OK
,
87 /* An error occurred while processing an event on the connection. */
88 RELAY_CONNECTION_STATUS_ERROR
,
89 /* Connection closed/shutdown cleanly. */
90 RELAY_CONNECTION_STATUS_CLOSED
,
93 /* command line options */
94 char *opt_output_path
, *opt_working_directory
;
95 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
96 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
99 * We need to wait for listener and live listener threads, as well as
100 * health check thread, before being ready to signal readiness.
102 #define NR_LTTNG_RELAY_READY 3
103 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
105 /* Size of receive buffer. */
106 #define RECV_DATA_BUFFER_SIZE 65536
108 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
109 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
111 static struct lttng_uri
*control_uri
;
112 static struct lttng_uri
*data_uri
;
113 static struct lttng_uri
*live_uri
;
115 const char *progname
;
117 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
118 static int tracing_group_name_override
;
120 const char * const config_section_name
= "relayd";
123 * Quit pipe for all threads. This permits a single cancellation point
124 * for all threads when receiving an event on the pipe.
126 int thread_quit_pipe
[2] = { -1, -1 };
129 * This pipe is used to inform the worker thread that a command is queued and
130 * ready to be processed.
132 static int relay_conn_pipe
[2] = { -1, -1 };
134 /* Shared between threads */
135 static int dispatch_thread_exit
;
137 static pthread_t listener_thread
;
138 static pthread_t dispatcher_thread
;
139 static pthread_t worker_thread
;
140 static pthread_t health_thread
;
143 * last_relay_stream_id_lock protects last_relay_stream_id increment
144 * atomicity on 32-bit architectures.
146 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
147 static uint64_t last_relay_stream_id
;
150 * Relay command queue.
152 * The relay_thread_listener and relay_thread_dispatcher communicate with this
155 static struct relay_conn_queue relay_conn_queue
;
157 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
158 static unsigned int lttng_opt_fd_pool_size
= -1;
160 /* Global relay stream hash table. */
161 struct lttng_ht
*relay_streams_ht
;
163 /* Global relay viewer stream hash table. */
164 struct lttng_ht
*viewer_streams_ht
;
166 /* Global relay sessions hash table. */
167 struct lttng_ht
*sessions_ht
;
169 /* Relayd health monitoring */
170 struct health_app
*health_relayd
;
172 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
174 /* Global fd tracker. */
175 struct fd_tracker
*the_fd_tracker
;
177 static struct option long_options
[] = {
178 { "control-port", 1, 0, 'C', },
179 { "data-port", 1, 0, 'D', },
180 { "live-port", 1, 0, 'L', },
181 { "daemonize", 0, 0, 'd', },
182 { "background", 0, 0, 'b', },
183 { "group", 1, 0, 'g', },
184 { "fd-pool-size", 1, 0, '\0', },
185 { "help", 0, 0, 'h', },
186 { "output", 1, 0, 'o', },
187 { "verbose", 0, 0, 'v', },
188 { "config", 1, 0, 'f' },
189 { "version", 0, 0, 'V' },
190 { "working-directory", 1, 0, 'w', },
191 { "group-output-by-session", 0, 0, 's', },
192 { "group-output-by-host", 0, 0, 'p', },
193 { "disallow-clear", 0, 0, 'x' },
197 static const char *config_ignore_options
[] = { "help", "config", "version" };
199 static void print_version(void) {
200 fprintf(stdout
, "%s\n", VERSION
);
203 static void relayd_config_log(void)
205 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
206 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
207 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
208 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
209 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
211 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
212 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
217 * Take an option from the getopt output and set it in the right variable to be
220 * Return 0 on success else a negative value.
222 static int set_option(int opt
, const char *arg
, const char *optname
)
228 if (!strcmp(optname
, "fd-pool-size")) {
232 v
= strtoul(arg
, NULL
, 0);
233 if (errno
!= 0 || !isdigit(arg
[0])) {
234 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
239 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
243 lttng_opt_fd_pool_size
= (unsigned int) v
;
245 fprintf(stderr
, "unknown option %s", optname
);
247 fprintf(stderr
, " with arg %s\n", arg
);
252 if (lttng_is_setuid_setgid()) {
253 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
254 "-C, --control-port");
256 ret
= uri_parse(arg
, &control_uri
);
258 ERR("Invalid control URI specified");
261 if (control_uri
->port
== 0) {
262 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
267 if (lttng_is_setuid_setgid()) {
268 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
271 ret
= uri_parse(arg
, &data_uri
);
273 ERR("Invalid data URI specified");
276 if (data_uri
->port
== 0) {
277 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 ret
= uri_parse(arg
, &live_uri
);
288 ERR("Invalid live URI specified");
291 if (live_uri
->port
== 0) {
292 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
307 tracing_group_name
= strdup(arg
);
308 if (tracing_group_name
== NULL
) {
313 tracing_group_name_override
= 1;
317 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
319 ERR("Cannot show --help for `lttng-relayd`");
324 opt_print_version
= 1;
327 if (lttng_is_setuid_setgid()) {
328 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
331 ret
= asprintf(&opt_output_path
, "%s", arg
);
334 PERROR("asprintf opt_output_path");
340 if (lttng_is_setuid_setgid()) {
341 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
342 "-w, --working-directory");
344 ret
= asprintf(&opt_working_directory
, "%s", arg
);
347 PERROR("asprintf opt_working_directory");
354 /* Verbose level can increase using multiple -v */
356 lttng_opt_verbose
= config_parse_value(arg
);
358 /* Only 3 level of verbosity (-vvv). */
359 if (lttng_opt_verbose
< 3) {
360 lttng_opt_verbose
+= 1;
365 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
366 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
369 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
372 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
373 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
376 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
383 /* Unknown option or other error.
384 * Error is printed by getopt, just return */
397 * config_entry_handler_cb used to handle options read from a config file.
398 * See config_entry_handler_cb comment in common/config/session-config.h for the
399 * return value conventions.
401 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
405 if (!entry
|| !entry
->name
|| !entry
->value
) {
410 /* Check if the option is to be ignored */
411 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
412 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
417 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
418 /* Ignore if entry name is not fully matched. */
419 if (strcmp(entry
->name
, long_options
[i
].name
)) {
424 * If the option takes no argument on the command line,
425 * we have to check if the value is "true". We support
426 * non-zero numeric values, true, on and yes.
428 if (!long_options
[i
].has_arg
) {
429 ret
= config_parse_value(entry
->value
);
432 WARN("Invalid configuration value \"%s\" for option %s",
433 entry
->value
, entry
->name
);
435 /* False, skip boolean config option. */
440 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
444 WARN("Unrecognized option \"%s\" in daemon configuration file.",
451 static int parse_env_options(void)
456 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
458 opt_working_directory
= strdup(value
);
459 if (!opt_working_directory
) {
460 ERR("Failed to allocate working directory string (\"%s\")",
468 static int set_fd_pool_size(void)
471 struct rlimit rlimit
;
473 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
475 PERROR("Failed to get file descriptor limit");
480 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
481 (uint64_t) rlimit
.rlim_cur
,
482 (uint64_t) rlimit
.rlim_max
);
483 if (lttng_opt_fd_pool_size
== -1) {
484 /* Use default value (soft limit - reserve). */
485 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
486 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
487 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
491 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
492 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
496 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
497 ERR("File descriptor pool size must be set to at least %d",
498 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
503 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
504 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
505 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
510 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
511 lttng_opt_fd_pool_size
,
512 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
513 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
518 static int set_options(int argc
, char **argv
)
520 int c
, ret
= 0, option_index
= 0, retval
= 0;
521 int orig_optopt
= optopt
, orig_optind
= optind
;
522 char *default_address
, *optstring
;
523 const char *config_path
= NULL
;
525 optstring
= utils_generate_optstring(long_options
,
526 sizeof(long_options
) / sizeof(struct option
));
532 /* Check for the --config option */
534 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
535 &option_index
)) != -1) {
539 } else if (c
!= 'f') {
543 if (lttng_is_setuid_setgid()) {
544 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
547 config_path
= utils_expand_path(optarg
);
549 ERR("Failed to resolve path: %s", optarg
);
554 ret
= config_get_section_entries(config_path
, config_section_name
,
555 config_entry_handler
, NULL
);
558 ERR("Invalid configuration option at line %i", ret
);
564 /* Reset getopt's global state */
565 optopt
= orig_optopt
;
566 optind
= orig_optind
;
568 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
573 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
580 /* assign default values */
581 if (control_uri
== NULL
) {
582 ret
= asprintf(&default_address
,
583 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
584 DEFAULT_NETWORK_CONTROL_PORT
);
586 PERROR("asprintf default data address");
591 ret
= uri_parse(default_address
, &control_uri
);
592 free(default_address
);
594 ERR("Invalid control URI specified");
599 if (data_uri
== NULL
) {
600 ret
= asprintf(&default_address
,
601 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
602 DEFAULT_NETWORK_DATA_PORT
);
604 PERROR("asprintf default data address");
609 ret
= uri_parse(default_address
, &data_uri
);
610 free(default_address
);
612 ERR("Invalid data URI specified");
617 if (live_uri
== NULL
) {
618 ret
= asprintf(&default_address
,
619 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
620 DEFAULT_NETWORK_VIEWER_PORT
);
622 PERROR("asprintf default viewer control address");
627 ret
= uri_parse(default_address
, &live_uri
);
628 free(default_address
);
630 ERR("Invalid viewer control URI specified");
635 ret
= set_fd_pool_size();
641 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
642 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
644 if (opt_allow_clear
) {
645 /* Check if env variable exists. */
646 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
648 ret
= config_parse_value(value
);
650 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
654 opt_allow_clear
= !ret
;
663 static void print_global_objects(void)
665 print_viewer_streams();
666 print_relay_streams();
670 static int noop_close(void *data
, int *fds
)
675 static void untrack_stdio(void)
677 int fds
[] = { fileno(stdout
), fileno(stderr
) };
680 * noop_close is used since we don't really want to close
681 * the stdio output fds; we merely want to stop tracking them.
683 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
684 fds
, 2, noop_close
, NULL
);
690 static void relayd_cleanup(void)
692 print_global_objects();
696 if (viewer_streams_ht
)
697 lttng_ht_destroy(viewer_streams_ht
);
698 if (relay_streams_ht
)
699 lttng_ht_destroy(relay_streams_ht
);
701 lttng_ht_destroy(sessions_ht
);
703 free(opt_output_path
);
704 free(opt_working_directory
);
707 health_app_destroy(health_relayd
);
709 /* Close thread quit pipes */
710 if (health_quit_pipe
[0] != -1) {
711 (void) fd_tracker_util_pipe_close(
712 the_fd_tracker
, health_quit_pipe
);
714 if (thread_quit_pipe
[0] != -1) {
715 (void) fd_tracker_util_pipe_close(
716 the_fd_tracker
, thread_quit_pipe
);
718 if (sessiond_trace_chunk_registry
) {
719 sessiond_trace_chunk_registry_destroy(
720 sessiond_trace_chunk_registry
);
722 if (the_fd_tracker
) {
725 * fd_tracker_destroy() will log the contents of the fd-tracker
726 * if a leak is detected.
728 fd_tracker_destroy(the_fd_tracker
);
731 uri_free(control_uri
);
733 /* Live URI is freed in the live thread. */
735 if (tracing_group_name_override
) {
736 free((void *) tracing_group_name
);
741 * Write to writable pipe used to notify a thread.
743 static int notify_thread_pipe(int wpipe
)
747 ret
= lttng_write(wpipe
, "!", 1);
749 PERROR("write poll pipe");
757 static int notify_health_quit_pipe(int *pipe
)
761 ret
= lttng_write(pipe
[1], "4", 1);
763 PERROR("write relay health quit");
772 * Stop all relayd and relayd-live threads.
774 int lttng_relay_stop_threads(void)
778 /* Stopping all threads */
779 DBG("Terminating all threads");
780 if (notify_thread_pipe(thread_quit_pipe
[1])) {
781 ERR("write error on thread quit pipe");
785 if (notify_health_quit_pipe(health_quit_pipe
)) {
786 ERR("write error on health quit pipe");
789 /* Dispatch thread */
790 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
791 futex_nto1_wake(&relay_conn_queue
.futex
);
793 if (relayd_live_stop()) {
794 ERR("Error stopping live threads");
801 * Signal handler for the daemon
803 * Simply stop all worker threads, leaving main() return gracefully after
804 * joining all threads and calling cleanup().
806 static void sighandler(int sig
)
810 DBG("SIGINT caught");
811 if (lttng_relay_stop_threads()) {
812 ERR("Error stopping threads");
816 DBG("SIGTERM caught");
817 if (lttng_relay_stop_threads()) {
818 ERR("Error stopping threads");
822 CMM_STORE_SHARED(recv_child_signal
, 1);
830 * Setup signal handler for :
831 * SIGINT, SIGTERM, SIGPIPE
833 static int set_signal_handler(void)
839 if ((ret
= sigemptyset(&sigset
)) < 0) {
840 PERROR("sigemptyset");
847 sa
.sa_handler
= sighandler
;
848 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
853 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
858 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
863 sa
.sa_handler
= SIG_IGN
;
864 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
869 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
874 void lttng_relay_notify_ready(void)
876 /* Notify the parent of the fork() process that we are ready. */
877 if (opt_daemon
|| opt_background
) {
878 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
879 kill(child_ppid
, SIGUSR1
);
885 * Init thread quit pipe.
887 * Return -1 on error or 0 if all pipes are created.
889 static int init_thread_quit_pipe(void)
891 return fd_tracker_util_pipe_open_cloexec(
892 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
896 * Init health quit pipe.
898 * Return -1 on error or 0 if all pipes are created.
900 static int init_health_quit_pipe(void)
902 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
903 "Health quit pipe", health_quit_pipe
);
907 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
909 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
910 int size
, const char *name
)
914 if (events
== NULL
|| size
== 0) {
919 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
920 name
, events
, 1, LTTNG_CLOEXEC
);
923 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
935 * Check if the thread quit pipe was triggered.
937 * Return 1 if it was triggered else 0;
939 static int check_thread_quit_pipe(int fd
, uint32_t events
)
941 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
948 static int create_sock(void *data
, int *out_fd
)
951 struct lttcomm_sock
*sock
= data
;
953 ret
= lttcomm_create_sock(sock
);
963 static int close_sock(void *data
, int *in_fd
)
965 struct lttcomm_sock
*sock
= data
;
967 return sock
->ops
->close(sock
);
970 static int accept_sock(void *data
, int *out_fd
)
973 /* Socks is an array of in_sock, out_sock. */
974 struct lttcomm_sock
**socks
= data
;
975 struct lttcomm_sock
*in_sock
= socks
[0];
977 socks
[1] = in_sock
->ops
->accept(in_sock
);
982 *out_fd
= socks
[1]->fd
;
988 * Create and init socket from uri.
990 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
994 struct lttcomm_sock
*sock
= NULL
;
995 char uri_str
[PATH_MAX
];
996 char *formated_name
= NULL
;
998 sock
= lttcomm_alloc_sock_from_uri(uri
);
1000 ERR("Allocating socket");
1005 * Don't fail to create the socket if the name can't be built as it is
1006 * only used for debugging purposes.
1008 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1009 uri_str
[sizeof(uri_str
) - 1] = '\0';
1011 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1014 formated_name
= NULL
;
1018 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1019 (const char **) (formated_name
? &formated_name
: NULL
),
1020 1, create_sock
, sock
);
1021 free(formated_name
);
1022 DBG("Listening on %s socket %d", name
, sock
->fd
);
1024 ret
= sock
->ops
->bind(sock
);
1026 PERROR("Failed to bind socket");
1030 ret
= sock
->ops
->listen(sock
, -1);
1040 lttcomm_destroy_sock(sock
);
1046 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1050 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1051 struct lttcomm_sock
*new_sock
= NULL
;
1053 ret
= fd_tracker_open_unsuspendable_fd(
1054 the_fd_tracker
, &out_fd
,
1055 (const char **) &name
,
1056 1, accept_sock
, &socks
);
1060 new_sock
= socks
[1];
1061 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1067 * This thread manages the listening for new connections on the network
1069 static void *relay_thread_listener(void *data
)
1071 int i
, ret
, pollfd
, err
= -1;
1072 uint32_t revents
, nb_fd
;
1073 struct lttng_poll_event events
;
1074 struct lttcomm_sock
*control_sock
, *data_sock
;
1076 DBG("[thread] Relay listener started");
1078 rcu_register_thread();
1079 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1081 health_code_update();
1083 control_sock
= relay_socket_create(control_uri
, "Control listener");
1084 if (!control_sock
) {
1085 goto error_sock_control
;
1088 data_sock
= relay_socket_create(data_uri
, "Data listener");
1090 goto error_sock_relay
;
1094 * Pass 3 as size here for the thread quit pipe, control and
1097 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1099 goto error_create_poll
;
1102 /* Add the control socket */
1103 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1105 goto error_poll_add
;
1108 /* Add the data socket */
1109 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1111 goto error_poll_add
;
1114 lttng_relay_notify_ready();
1116 if (testpoint(relayd_thread_listener
)) {
1117 goto error_testpoint
;
1121 health_code_update();
1123 DBG("Listener accepting connections");
1126 health_poll_entry();
1127 ret
= lttng_poll_wait(&events
, -1);
1131 * Restart interrupted system call.
1133 if (errno
== EINTR
) {
1141 DBG("Relay new connection received");
1142 for (i
= 0; i
< nb_fd
; i
++) {
1143 health_code_update();
1145 /* Fetch once the poll data */
1146 revents
= LTTNG_POLL_GETEV(&events
, i
);
1147 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1149 /* Thread quit pipe has been closed. Killing thread. */
1150 ret
= check_thread_quit_pipe(pollfd
, revents
);
1156 if (revents
& LPOLLIN
) {
1158 * A new connection is requested, therefore a
1159 * sessiond/consumerd connection is allocated in
1160 * this thread, enqueued to a global queue and
1161 * dequeued (and freed) in the worker thread.
1164 struct relay_connection
*new_conn
;
1165 struct lttcomm_sock
*newsock
= NULL
;
1166 enum connection_type type
;
1168 if (pollfd
== data_sock
->fd
) {
1170 newsock
= accept_relayd_sock(data_sock
,
1171 "Data socket to relayd");
1173 assert(pollfd
== control_sock
->fd
);
1174 type
= RELAY_CONTROL
;
1175 newsock
= accept_relayd_sock(control_sock
,
1176 "Control socket to relayd");
1179 PERROR("accepting sock");
1183 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1186 PERROR("setsockopt inet");
1187 lttcomm_destroy_sock(newsock
);
1191 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1193 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1195 lttcomm_destroy_sock(newsock
);
1199 new_conn
= connection_create(newsock
, type
);
1201 lttcomm_destroy_sock(newsock
);
1205 /* Enqueue request for the dispatcher thread. */
1206 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1210 * Wake the dispatch queue futex.
1211 * Implicit memory barrier with the
1212 * exchange in cds_wfcq_enqueue.
1214 futex_nto1_wake(&relay_conn_queue
.futex
);
1215 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1216 ERR("socket poll error");
1219 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1229 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1231 if (data_sock
->fd
>= 0) {
1232 int data_sock_fd
= data_sock
->fd
;
1234 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1235 &data_sock_fd
, 1, close_sock
,
1238 PERROR("Failed to close the data listener socket file descriptor");
1242 lttcomm_destroy_sock(data_sock
);
1244 if (control_sock
->fd
>= 0) {
1245 int control_sock_fd
= control_sock
->fd
;
1247 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1248 &control_sock_fd
, 1, close_sock
,
1251 PERROR("Failed to close the control listener socket file descriptor");
1253 control_sock
->fd
= -1;
1255 lttcomm_destroy_sock(control_sock
);
1259 ERR("Health error occurred in %s", __func__
);
1261 health_unregister(health_relayd
);
1262 rcu_unregister_thread();
1263 DBG("Relay listener thread cleanup complete");
1264 lttng_relay_stop_threads();
1269 * This thread manages the dispatching of the requests to worker threads
1271 static void *relay_thread_dispatcher(void *data
)
1275 struct cds_wfcq_node
*node
;
1276 struct relay_connection
*new_conn
= NULL
;
1278 DBG("[thread] Relay dispatcher started");
1280 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1282 if (testpoint(relayd_thread_dispatcher
)) {
1283 goto error_testpoint
;
1286 health_code_update();
1289 health_code_update();
1291 /* Atomically prepare the queue futex */
1292 futex_nto1_prepare(&relay_conn_queue
.futex
);
1294 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1299 health_code_update();
1301 /* Dequeue commands */
1302 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1303 &relay_conn_queue
.tail
);
1305 DBG("Woken up but nothing in the relay command queue");
1306 /* Continue thread execution */
1309 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1311 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1314 * Inform worker thread of the new request. This
1315 * call is blocking so we can be assured that
1316 * the data will be read at some point in time
1317 * or wait to the end of the world :)
1319 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1321 PERROR("write connection pipe");
1322 connection_put(new_conn
);
1325 } while (node
!= NULL
);
1327 /* Futex wait on queue. Blocking call on futex() */
1328 health_poll_entry();
1329 futex_nto1_wait(&relay_conn_queue
.futex
);
1333 /* Normal exit, no error */
1340 ERR("Health error occurred in %s", __func__
);
1342 health_unregister(health_relayd
);
1343 DBG("Dispatch thread dying");
1344 lttng_relay_stop_threads();
1348 static bool session_streams_have_index(const struct relay_session
*session
)
1350 return session
->minor
>= 4 && !session
->snapshot
;
1354 * Handle the RELAYD_CREATE_SESSION command.
1356 * On success, send back the session id or else return a negative value.
1358 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1359 struct relay_connection
*conn
,
1360 const struct lttng_buffer_view
*payload
)
1364 struct relay_session
*session
= NULL
;
1365 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1366 char session_name
[LTTNG_NAME_MAX
] = {};
1367 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1368 uint32_t live_timer
= 0;
1369 bool snapshot
= false;
1370 bool session_name_contains_creation_timestamp
= false;
1371 /* Left nil for peers < 2.11. */
1372 char base_path
[LTTNG_PATH_MAX
] = {};
1373 lttng_uuid sessiond_uuid
= {};
1374 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1375 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1376 LTTNG_OPTIONAL(time_t) creation_time
= {};
1377 struct lttng_dynamic_buffer reply_payload
;
1379 lttng_dynamic_buffer_init(&reply_payload
);
1381 if (conn
->minor
< 4) {
1382 /* From 2.1 to 2.3 */
1384 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1385 /* From 2.4 to 2.10 */
1386 ret
= cmd_create_session_2_4(payload
, session_name
,
1387 hostname
, &live_timer
, &snapshot
);
1389 bool has_current_chunk
;
1390 uint64_t current_chunk_id_value
;
1391 time_t creation_time_value
;
1392 uint64_t id_sessiond_value
;
1394 /* From 2.11 to ... */
1395 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1396 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1397 sessiond_uuid
, &has_current_chunk
,
1398 ¤t_chunk_id_value
, &creation_time_value
,
1399 &session_name_contains_creation_timestamp
);
1400 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1401 /* The nil UUID is reserved for pre-2.11 clients. */
1402 ERR("Illegal nil UUID announced by peer in create session command");
1406 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1407 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1408 if (has_current_chunk
) {
1409 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1410 current_chunk_id_value
);
1418 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1419 snapshot
, sessiond_uuid
,
1420 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1421 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1422 creation_time
.is_set
? &creation_time
.value
: NULL
,
1423 conn
->major
, conn
->minor
,
1424 session_name_contains_creation_timestamp
);
1429 assert(!conn
->session
);
1430 conn
->session
= session
;
1431 DBG("Created session %" PRIu64
, session
->id
);
1433 reply
.generic
.session_id
= htobe64(session
->id
);
1437 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1439 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1442 if (conn
->minor
< 11) {
1443 /* From 2.1 to 2.10 */
1444 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1445 &reply
.generic
, sizeof(reply
.generic
));
1447 ERR("Failed to append \"create session\" command reply header to payload buffer");
1452 const uint32_t output_path_length
=
1453 session
? strlen(session
->output_path
) + 1 : 0;
1455 reply
.output_path_length
= htobe32(output_path_length
);
1456 ret
= lttng_dynamic_buffer_append(
1457 &reply_payload
, &reply
, sizeof(reply
));
1459 ERR("Failed to append \"create session\" command reply header to payload buffer");
1463 if (output_path_length
) {
1464 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1465 session
->output_path
,
1466 output_path_length
);
1468 ERR("Failed to append \"create session\" command reply path to payload buffer");
1474 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1475 reply_payload
.size
, 0);
1476 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1477 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1478 reply_payload
.size
, send_ret
);
1482 if (ret
< 0 && session
) {
1483 session_put(session
);
1485 lttng_dynamic_buffer_reset(&reply_payload
);
1490 * When we have received all the streams and the metadata for a channel,
1491 * we make them visible to the viewer threads.
1493 static void publish_connection_local_streams(struct relay_connection
*conn
)
1495 struct relay_stream
*stream
;
1496 struct relay_session
*session
= conn
->session
;
1499 * We publish all streams belonging to a session atomically wrt
1502 pthread_mutex_lock(&session
->lock
);
1504 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1506 stream_publish(stream
);
1511 * Inform the viewer that there are new streams in the session.
1513 if (session
->viewer_attached
) {
1514 uatomic_set(&session
->new_streams
, 1);
1516 pthread_mutex_unlock(&session
->lock
);
1519 static int conform_channel_path(char *channel_path
)
1523 if (strstr("../", channel_path
)) {
1524 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1530 if (*channel_path
== '/') {
1531 const size_t len
= strlen(channel_path
);
1534 * Channel paths from peers prior to 2.11 are expressed as an
1535 * absolute path that is, in reality, relative to the relay
1536 * daemon's output directory. Remove the leading slash so it
1537 * is correctly interpreted as a relative path later on.
1539 * len (and not len - 1) is used to copy the trailing NULL.
1541 bcopy(channel_path
+ 1, channel_path
, len
);
1548 * relay_add_stream: allocate a new stream for a session
1550 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1551 struct relay_connection
*conn
,
1552 const struct lttng_buffer_view
*payload
)
1556 struct relay_session
*session
= conn
->session
;
1557 struct relay_stream
*stream
= NULL
;
1558 struct lttcomm_relayd_status_stream reply
;
1559 struct ctf_trace
*trace
= NULL
;
1560 uint64_t stream_handle
= -1ULL;
1561 char *path_name
= NULL
, *channel_name
= NULL
;
1562 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1563 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1565 if (!session
|| !conn
->version_check_done
) {
1566 ERR("Trying to add a stream before version check");
1568 goto end_no_session
;
1571 if (session
->minor
== 1) {
1573 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1575 } else if (session
->minor
> 1 && session
->minor
< 11) {
1576 /* From 2.2 to 2.10 */
1577 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1578 &channel_name
, &tracefile_size
, &tracefile_count
);
1580 /* From 2.11 to ... */
1581 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1582 &channel_name
, &tracefile_size
, &tracefile_count
,
1583 &stream_chunk_id
.value
);
1584 stream_chunk_id
.is_set
= true;
1591 if (conform_channel_path(path_name
)) {
1596 * Backward compatibility for --group-output-by-session.
1597 * Prior to lttng 2.11, the complete path is passed by the stream.
1598 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1599 * >=2.11 the chunk is responsible for the output path. When dealing
1600 * with producer < 2.11 the chunk output_path is the root output path
1601 * and the stream carries the complete path (path_name).
1602 * To support --group-output-by-session with older producer (<2.11), we
1603 * need to craft the path based on the stream path.
1605 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1606 if (conn
->minor
< 4) {
1608 * From 2.1 to 2.3, the session_name is not passed on
1609 * the RELAYD_CREATE_SESSION command. The session name
1610 * is necessary to detect the presence of a base_path
1611 * inside the stream path. Without it we cannot perform
1612 * a valid group-output-by-session transformation.
1614 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1615 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1616 session
->id
, path_name
);
1617 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1618 char *group_by_session_path_name
;
1620 assert(session
->session_name
[0] != '\0');
1622 group_by_session_path_name
=
1623 backward_compat_group_by_session(
1625 session
->session_name
);
1626 if (!group_by_session_path_name
) {
1627 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1632 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1633 path_name
, group_by_session_path_name
);
1636 path_name
= group_by_session_path_name
;
1640 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1645 /* This stream here has one reference on the trace. */
1646 pthread_mutex_lock(&last_relay_stream_id_lock
);
1647 stream_handle
= ++last_relay_stream_id
;
1648 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1650 /* We pass ownership of path_name and channel_name. */
1651 stream
= stream_create(trace
, stream_handle
, path_name
,
1652 channel_name
, tracefile_size
, tracefile_count
);
1654 channel_name
= NULL
;
1657 * Streams are the owners of their trace. Reference to trace is
1658 * kept within stream_create().
1660 ctf_trace_put(trace
);
1663 memset(&reply
, 0, sizeof(reply
));
1664 reply
.handle
= htobe64(stream_handle
);
1666 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1668 reply
.ret_code
= htobe32(LTTNG_OK
);
1671 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1672 sizeof(struct lttcomm_relayd_status_stream
), 0);
1673 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1674 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1686 * relay_close_stream: close a specific stream
1688 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1689 struct relay_connection
*conn
,
1690 const struct lttng_buffer_view
*payload
)
1694 struct relay_session
*session
= conn
->session
;
1695 struct lttcomm_relayd_close_stream stream_info
;
1696 struct lttcomm_relayd_generic_reply reply
;
1697 struct relay_stream
*stream
;
1699 DBG("Close stream received");
1701 if (!session
|| !conn
->version_check_done
) {
1702 ERR("Trying to close a stream before version check");
1704 goto end_no_session
;
1707 if (payload
->size
< sizeof(stream_info
)) {
1708 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1709 sizeof(stream_info
), payload
->size
);
1711 goto end_no_session
;
1713 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1714 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1715 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1717 stream
= stream_get_by_id(stream_info
.stream_id
);
1724 * Set last_net_seq_num before the close flag. Required by data
1727 pthread_mutex_lock(&stream
->lock
);
1728 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1729 pthread_mutex_unlock(&stream
->lock
);
1732 * This is one of the conditions which may trigger a stream close
1733 * with the others being:
1734 * 1) A close command is received for a stream
1735 * 2) The control connection owning the stream is closed
1736 * 3) We have received all of the stream's data _after_ a close
1739 try_stream_close(stream
);
1740 if (stream
->is_metadata
) {
1741 struct relay_viewer_stream
*vstream
;
1743 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1745 if (stream
->no_new_metadata_notified
) {
1747 * Since all the metadata has been sent to the
1748 * viewer and that we have a request to close
1749 * its stream, we can safely teardown the
1750 * corresponding metadata viewer stream.
1752 viewer_stream_put(vstream
);
1754 /* Put local reference. */
1755 viewer_stream_put(vstream
);
1762 memset(&reply
, 0, sizeof(reply
));
1764 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1766 reply
.ret_code
= htobe32(LTTNG_OK
);
1768 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1769 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1770 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1771 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1781 * relay_reset_metadata: reset a metadata stream
1784 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1785 struct relay_connection
*conn
,
1786 const struct lttng_buffer_view
*payload
)
1790 struct relay_session
*session
= conn
->session
;
1791 struct lttcomm_relayd_reset_metadata stream_info
;
1792 struct lttcomm_relayd_generic_reply reply
;
1793 struct relay_stream
*stream
;
1795 DBG("Reset metadata received");
1797 if (!session
|| !conn
->version_check_done
) {
1798 ERR("Trying to reset a metadata stream before version check");
1800 goto end_no_session
;
1803 if (payload
->size
< sizeof(stream_info
)) {
1804 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1805 sizeof(stream_info
), payload
->size
);
1807 goto end_no_session
;
1809 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1810 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1811 stream_info
.version
= be64toh(stream_info
.version
);
1813 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1815 /* Unsupported for live sessions for now. */
1816 if (session
->live_timer
!= 0) {
1821 stream
= stream_get_by_id(stream_info
.stream_id
);
1826 pthread_mutex_lock(&stream
->lock
);
1827 if (!stream
->is_metadata
) {
1832 ret
= stream_reset_file(stream
);
1834 ERR("Failed to reset metadata stream %" PRIu64
1835 ": stream_path = %s, channel = %s",
1836 stream
->stream_handle
, stream
->path_name
,
1837 stream
->channel_name
);
1841 pthread_mutex_unlock(&stream
->lock
);
1845 memset(&reply
, 0, sizeof(reply
));
1847 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1849 reply
.ret_code
= htobe32(LTTNG_OK
);
1851 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1852 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1853 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1854 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1864 * relay_unknown_command: send -1 if received unknown command
1866 static void relay_unknown_command(struct relay_connection
*conn
)
1868 struct lttcomm_relayd_generic_reply reply
;
1871 memset(&reply
, 0, sizeof(reply
));
1872 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1873 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1874 if (send_ret
< sizeof(reply
)) {
1875 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1880 * relay_start: send an acknowledgment to the client to tell if we are
1881 * ready to receive data. We are ready if a session is established.
1883 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1884 struct relay_connection
*conn
,
1885 const struct lttng_buffer_view
*payload
)
1889 struct lttcomm_relayd_generic_reply reply
;
1890 struct relay_session
*session
= conn
->session
;
1893 DBG("Trying to start the streaming without a session established");
1894 ret
= htobe32(LTTNG_ERR_UNK
);
1897 memset(&reply
, 0, sizeof(reply
));
1898 reply
.ret_code
= htobe32(LTTNG_OK
);
1899 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1901 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1902 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1911 * relay_recv_metadata: receive the metadata for the session.
1913 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1914 struct relay_connection
*conn
,
1915 const struct lttng_buffer_view
*payload
)
1918 struct relay_session
*session
= conn
->session
;
1919 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1920 struct relay_stream
*metadata_stream
;
1921 uint64_t metadata_payload_size
;
1922 struct lttng_buffer_view packet_view
;
1925 ERR("Metadata sent before version check");
1930 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1931 ERR("Incorrect data size");
1935 metadata_payload_size
= recv_hdr
->data_size
-
1936 sizeof(struct lttcomm_relayd_metadata_payload
);
1938 memcpy(&metadata_payload_header
, payload
->data
,
1939 sizeof(metadata_payload_header
));
1940 metadata_payload_header
.stream_id
= be64toh(
1941 metadata_payload_header
.stream_id
);
1942 metadata_payload_header
.padding_size
= be32toh(
1943 metadata_payload_header
.padding_size
);
1945 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1946 if (!metadata_stream
) {
1951 packet_view
= lttng_buffer_view_from_view(payload
,
1952 sizeof(metadata_payload_header
), metadata_payload_size
);
1953 if (!packet_view
.data
) {
1954 ERR("Invalid metadata packet length announced by header");
1959 pthread_mutex_lock(&metadata_stream
->lock
);
1960 ret
= stream_write(metadata_stream
, &packet_view
,
1961 metadata_payload_header
.padding_size
);
1962 pthread_mutex_unlock(&metadata_stream
->lock
);
1968 stream_put(metadata_stream
);
1974 * relay_send_version: send relayd version number
1976 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1977 struct relay_connection
*conn
,
1978 const struct lttng_buffer_view
*payload
)
1982 struct lttcomm_relayd_version reply
, msg
;
1983 bool compatible
= true;
1985 conn
->version_check_done
= true;
1987 /* Get version from the other side. */
1988 if (payload
->size
< sizeof(msg
)) {
1989 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1990 sizeof(msg
), payload
->size
);
1995 memcpy(&msg
, payload
->data
, sizeof(msg
));
1996 msg
.major
= be32toh(msg
.major
);
1997 msg
.minor
= be32toh(msg
.minor
);
1999 memset(&reply
, 0, sizeof(reply
));
2000 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2001 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2003 /* Major versions must be the same */
2004 if (reply
.major
!= msg
.major
) {
2005 DBG("Incompatible major versions (%u vs %u), deleting session",
2006 reply
.major
, msg
.major
);
2010 conn
->major
= reply
.major
;
2011 /* We adapt to the lowest compatible version */
2012 if (reply
.minor
<= msg
.minor
) {
2013 conn
->minor
= reply
.minor
;
2015 conn
->minor
= msg
.minor
;
2018 reply
.major
= htobe32(reply
.major
);
2019 reply
.minor
= htobe32(reply
.minor
);
2020 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2022 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2023 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2036 DBG("Version check done using protocol %u.%u", conn
->major
,
2044 * Check for data pending for a given stream id from the session daemon.
2046 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2047 struct relay_connection
*conn
,
2048 const struct lttng_buffer_view
*payload
)
2050 struct relay_session
*session
= conn
->session
;
2051 struct lttcomm_relayd_data_pending msg
;
2052 struct lttcomm_relayd_generic_reply reply
;
2053 struct relay_stream
*stream
;
2056 uint64_t stream_seq
;
2058 DBG("Data pending command received");
2060 if (!session
|| !conn
->version_check_done
) {
2061 ERR("Trying to check for data before version check");
2063 goto end_no_session
;
2066 if (payload
->size
< sizeof(msg
)) {
2067 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2068 sizeof(msg
), payload
->size
);
2070 goto end_no_session
;
2072 memcpy(&msg
, payload
->data
, sizeof(msg
));
2073 msg
.stream_id
= be64toh(msg
.stream_id
);
2074 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2076 stream
= stream_get_by_id(msg
.stream_id
);
2077 if (stream
== NULL
) {
2082 pthread_mutex_lock(&stream
->lock
);
2084 if (session_streams_have_index(session
)) {
2086 * Ensure that both the index and stream data have been
2087 * flushed up to the requested point.
2089 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2091 stream_seq
= stream
->prev_data_seq
;
2093 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2094 ", prev_index_seq %" PRIu64
2095 ", and last_seq %" PRIu64
, msg
.stream_id
,
2096 stream
->prev_data_seq
, stream
->prev_index_seq
,
2097 msg
.last_net_seq_num
);
2099 /* Avoid wrapping issue */
2100 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2101 /* Data has in fact been written and is NOT pending */
2104 /* Data still being streamed thus pending */
2108 stream
->data_pending_check_done
= true;
2109 pthread_mutex_unlock(&stream
->lock
);
2114 memset(&reply
, 0, sizeof(reply
));
2115 reply
.ret_code
= htobe32(ret
);
2116 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2117 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2118 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2128 * Wait for the control socket to reach a quiescent state.
2130 * Note that for now, when receiving this command from the session
2131 * daemon, this means that every subsequent commands or data received on
2132 * the control socket has been handled. So, this is why we simply return
2135 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2136 struct relay_connection
*conn
,
2137 const struct lttng_buffer_view
*payload
)
2141 struct relay_stream
*stream
;
2142 struct lttcomm_relayd_quiescent_control msg
;
2143 struct lttcomm_relayd_generic_reply reply
;
2145 DBG("Checking quiescent state on control socket");
2147 if (!conn
->session
|| !conn
->version_check_done
) {
2148 ERR("Trying to check for data before version check");
2150 goto end_no_session
;
2153 if (payload
->size
< sizeof(msg
)) {
2154 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2155 sizeof(msg
), payload
->size
);
2157 goto end_no_session
;
2159 memcpy(&msg
, payload
->data
, sizeof(msg
));
2160 msg
.stream_id
= be64toh(msg
.stream_id
);
2162 stream
= stream_get_by_id(msg
.stream_id
);
2166 pthread_mutex_lock(&stream
->lock
);
2167 stream
->data_pending_check_done
= true;
2168 pthread_mutex_unlock(&stream
->lock
);
2170 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2173 memset(&reply
, 0, sizeof(reply
));
2174 reply
.ret_code
= htobe32(LTTNG_OK
);
2175 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2176 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2177 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2189 * Initialize a data pending command. This means that a consumer is about
2190 * to ask for data pending for each stream it holds. Simply iterate over
2191 * all streams of a session and set the data_pending_check_done flag.
2193 * This command returns to the client a LTTNG_OK code.
2195 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2196 struct relay_connection
*conn
,
2197 const struct lttng_buffer_view
*payload
)
2201 struct lttng_ht_iter iter
;
2202 struct lttcomm_relayd_begin_data_pending msg
;
2203 struct lttcomm_relayd_generic_reply reply
;
2204 struct relay_stream
*stream
;
2209 DBG("Init streams for data pending");
2211 if (!conn
->session
|| !conn
->version_check_done
) {
2212 ERR("Trying to check for data before version check");
2214 goto end_no_session
;
2217 if (payload
->size
< sizeof(msg
)) {
2218 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2219 sizeof(msg
), payload
->size
);
2221 goto end_no_session
;
2223 memcpy(&msg
, payload
->data
, sizeof(msg
));
2224 msg
.session_id
= be64toh(msg
.session_id
);
2227 * Iterate over all streams to set the begin data pending flag.
2228 * For now, the streams are indexed by stream handle so we have
2229 * to iterate over all streams to find the one associated with
2230 * the right session_id.
2233 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2235 if (!stream_get(stream
)) {
2238 if (stream
->trace
->session
->id
== msg
.session_id
) {
2239 pthread_mutex_lock(&stream
->lock
);
2240 stream
->data_pending_check_done
= false;
2241 pthread_mutex_unlock(&stream
->lock
);
2242 DBG("Set begin data pending flag to stream %" PRIu64
,
2243 stream
->stream_handle
);
2249 memset(&reply
, 0, sizeof(reply
));
2250 /* All good, send back reply. */
2251 reply
.ret_code
= htobe32(LTTNG_OK
);
2253 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2254 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2255 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2267 * End data pending command. This will check, for a given session id, if
2268 * each stream associated with it has its data_pending_check_done flag
2269 * set. If not, this means that the client lost track of the stream but
2270 * the data is still being streamed on our side. In this case, we inform
2271 * the client that data is in flight.
2273 * Return to the client if there is data in flight or not with a ret_code.
2275 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2276 struct relay_connection
*conn
,
2277 const struct lttng_buffer_view
*payload
)
2281 struct lttng_ht_iter iter
;
2282 struct lttcomm_relayd_end_data_pending msg
;
2283 struct lttcomm_relayd_generic_reply reply
;
2284 struct relay_stream
*stream
;
2285 uint32_t is_data_inflight
= 0;
2287 DBG("End data pending command");
2289 if (!conn
->session
|| !conn
->version_check_done
) {
2290 ERR("Trying to check for data before version check");
2292 goto end_no_session
;
2295 if (payload
->size
< sizeof(msg
)) {
2296 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2297 sizeof(msg
), payload
->size
);
2299 goto end_no_session
;
2301 memcpy(&msg
, payload
->data
, sizeof(msg
));
2302 msg
.session_id
= be64toh(msg
.session_id
);
2305 * Iterate over all streams to see if the begin data pending
2309 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2311 if (!stream_get(stream
)) {
2314 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2318 pthread_mutex_lock(&stream
->lock
);
2319 if (!stream
->data_pending_check_done
) {
2320 uint64_t stream_seq
;
2322 if (session_streams_have_index(conn
->session
)) {
2324 * Ensure that both the index and stream data have been
2325 * flushed up to the requested point.
2327 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2329 stream_seq
= stream
->prev_data_seq
;
2331 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2332 is_data_inflight
= 1;
2333 DBG("Data is still in flight for stream %" PRIu64
,
2334 stream
->stream_handle
);
2335 pthread_mutex_unlock(&stream
->lock
);
2340 pthread_mutex_unlock(&stream
->lock
);
2345 memset(&reply
, 0, sizeof(reply
));
2346 /* All good, send back reply. */
2347 reply
.ret_code
= htobe32(is_data_inflight
);
2349 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2350 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2351 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2363 * Receive an index for a specific stream.
2365 * Return 0 on success else a negative value.
2367 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2368 struct relay_connection
*conn
,
2369 const struct lttng_buffer_view
*payload
)
2373 struct relay_session
*session
= conn
->session
;
2374 struct lttcomm_relayd_index index_info
;
2375 struct lttcomm_relayd_generic_reply reply
;
2376 struct relay_stream
*stream
;
2381 DBG("Relay receiving index");
2383 if (!session
|| !conn
->version_check_done
) {
2384 ERR("Trying to close a stream before version check");
2386 goto end_no_session
;
2389 msg_len
= lttcomm_relayd_index_len(
2390 lttng_to_index_major(conn
->major
, conn
->minor
),
2391 lttng_to_index_minor(conn
->major
, conn
->minor
));
2392 if (payload
->size
< msg_len
) {
2393 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2394 msg_len
, payload
->size
);
2396 goto end_no_session
;
2398 memcpy(&index_info
, payload
->data
, msg_len
);
2399 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2400 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2401 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2402 index_info
.content_size
= be64toh(index_info
.content_size
);
2403 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2404 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2405 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2406 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2408 if (conn
->minor
>= 8) {
2409 index_info
.stream_instance_id
=
2410 be64toh(index_info
.stream_instance_id
);
2411 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2413 index_info
.stream_instance_id
= -1ULL;
2414 index_info
.packet_seq_num
= -1ULL;
2417 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2419 ERR("stream_get_by_id not found");
2424 pthread_mutex_lock(&stream
->lock
);
2425 ret
= stream_add_index(stream
, &index_info
);
2426 pthread_mutex_unlock(&stream
->lock
);
2428 goto end_stream_put
;
2434 memset(&reply
, 0, sizeof(reply
));
2436 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2438 reply
.ret_code
= htobe32(LTTNG_OK
);
2440 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2441 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2442 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2451 * Receive the streams_sent message.
2453 * Return 0 on success else a negative value.
2455 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2456 struct relay_connection
*conn
,
2457 const struct lttng_buffer_view
*payload
)
2461 struct lttcomm_relayd_generic_reply reply
;
2465 DBG("Relay receiving streams_sent");
2467 if (!conn
->session
|| !conn
->version_check_done
) {
2468 ERR("Trying to close a stream before version check");
2470 goto end_no_session
;
2474 * Publish every pending stream in the connection recv list which are
2475 * now ready to be used by the viewer.
2477 publish_connection_local_streams(conn
);
2479 memset(&reply
, 0, sizeof(reply
));
2480 reply
.ret_code
= htobe32(LTTNG_OK
);
2481 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2482 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2483 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2496 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2497 * session rotation feature (not the tracefile rotation feature).
2499 static int relay_rotate_session_streams(
2500 const struct lttcomm_relayd_hdr
*recv_hdr
,
2501 struct relay_connection
*conn
,
2502 const struct lttng_buffer_view
*payload
)
2507 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2508 struct relay_session
*session
= conn
->session
;
2509 struct lttcomm_relayd_rotate_streams rotate_streams
;
2510 struct lttcomm_relayd_generic_reply reply
= {};
2511 struct relay_stream
*stream
= NULL
;
2512 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2513 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2514 struct lttng_buffer_view stream_positions
;
2515 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2516 const char *chunk_id_str
= "none";
2518 if (!session
|| !conn
->version_check_done
) {
2519 ERR("Trying to rotate a stream before version check");
2524 if (session
->major
== 2 && session
->minor
< 11) {
2525 ERR("Unsupported feature before 2.11");
2530 if (payload
->size
< header_len
) {
2531 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2532 header_len
, payload
->size
);
2537 memcpy(&rotate_streams
, payload
->data
, header_len
);
2539 /* Convert header to host endianness. */
2540 rotate_streams
= (typeof(rotate_streams
)) {
2541 .stream_count
= be32toh(rotate_streams
.stream_count
),
2542 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2543 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2544 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2548 if (rotate_streams
.new_chunk_id
.is_set
) {
2550 * Retrieve the trace chunk the stream must transition to. As
2551 * per the protocol, this chunk should have been created
2552 * before this command is received.
2554 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2555 sessiond_trace_chunk_registry
,
2556 session
->sessiond_uuid
, session
->id
,
2557 rotate_streams
.new_chunk_id
.value
);
2558 if (!next_trace_chunk
) {
2559 char uuid_str
[LTTNG_UUID_STR_LEN
];
2561 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2562 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2563 ", trace_chunk_id = %" PRIu64
,
2564 uuid_str
, session
->id
,
2565 rotate_streams
.new_chunk_id
.value
);
2566 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2571 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2572 rotate_streams
.new_chunk_id
.value
);
2573 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2574 chunk_id_str
= "formatting error";
2576 chunk_id_str
= chunk_id_buf
;
2580 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2581 rotate_streams
.stream_count
, session
->session_name
,
2584 stream_positions
= lttng_buffer_view_from_view(payload
,
2585 sizeof(rotate_streams
), -1);
2586 if (!stream_positions
.data
||
2587 stream_positions
.size
<
2588 (rotate_streams
.stream_count
*
2589 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2590 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2595 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2596 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2597 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2598 const struct lttcomm_relayd_stream_rotation_position pos
= {
2599 .stream_id
= be64toh(position_comm
->stream_id
),
2600 .rotate_at_seq_num
= be64toh(
2601 position_comm
->rotate_at_seq_num
),
2604 stream
= stream_get_by_id(pos
.stream_id
);
2606 reply_code
= LTTNG_ERR_INVALID
;
2611 pthread_mutex_lock(&stream
->lock
);
2612 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2613 pos
.rotate_at_seq_num
);
2614 pthread_mutex_unlock(&stream
->lock
);
2616 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2624 reply_code
= LTTNG_OK
;
2631 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2632 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2633 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2634 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2635 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2640 lttng_trace_chunk_put(next_trace_chunk
);
2647 * relay_create_trace_chunk: create a new trace chunk
2649 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2650 struct relay_connection
*conn
,
2651 const struct lttng_buffer_view
*payload
)
2655 struct relay_session
*session
= conn
->session
;
2656 struct lttcomm_relayd_create_trace_chunk
*msg
;
2657 struct lttcomm_relayd_generic_reply reply
= {};
2658 struct lttng_buffer_view header_view
;
2659 struct lttng_buffer_view chunk_name_view
;
2660 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2661 enum lttng_error_code reply_code
= LTTNG_OK
;
2662 enum lttng_trace_chunk_status chunk_status
;
2663 const char *new_path
;
2665 if (!session
|| !conn
->version_check_done
) {
2666 ERR("Trying to create a trace chunk before version check");
2671 if (session
->major
== 2 && session
->minor
< 11) {
2672 ERR("Chunk creation command is unsupported before 2.11");
2677 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2678 if (!header_view
.data
) {
2679 ERR("Failed to receive payload of chunk creation command");
2684 /* Convert to host endianness. */
2685 msg
= (typeof(msg
)) header_view
.data
;
2686 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2687 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2688 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2690 if (session
->current_trace_chunk
&&
2691 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2692 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2693 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2694 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2695 ERR("Failed to rename old chunk");
2697 reply_code
= LTTNG_ERR_UNK
;
2701 session
->ongoing_rotation
= true;
2702 if (!session
->current_trace_chunk
) {
2703 if (!session
->has_rotated
) {
2709 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2711 chunk
= lttng_trace_chunk_create(
2712 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2714 ERR("Failed to create trace chunk in trace chunk creation command");
2716 reply_code
= LTTNG_ERR_NOMEM
;
2719 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2721 if (msg
->override_name_length
) {
2724 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2726 msg
->override_name_length
);
2727 name
= chunk_name_view
.data
;
2728 if (!name
|| name
[msg
->override_name_length
- 1]) {
2729 ERR("Failed to receive payload of chunk creation command");
2731 reply_code
= LTTNG_ERR_INVALID
;
2735 chunk_status
= lttng_trace_chunk_override_name(
2736 chunk
, chunk_name_view
.data
);
2737 switch (chunk_status
) {
2738 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2740 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2741 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2742 reply_code
= LTTNG_ERR_INVALID
;
2746 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2747 reply_code
= LTTNG_ERR_UNK
;
2753 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2754 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2755 reply_code
= LTTNG_ERR_UNK
;
2760 assert(conn
->session
->output_directory
);
2761 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2762 conn
->session
->output_directory
);
2763 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2764 reply_code
= LTTNG_ERR_UNK
;
2769 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2770 sessiond_trace_chunk_registry
,
2771 conn
->session
->sessiond_uuid
,
2774 if (!published_chunk
) {
2775 char uuid_str
[LTTNG_UUID_STR_LEN
];
2777 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2778 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2783 reply_code
= LTTNG_ERR_NOMEM
;
2787 pthread_mutex_lock(&conn
->session
->lock
);
2788 if (conn
->session
->pending_closure_trace_chunk
) {
2790 * Invalid; this means a second create_trace_chunk command was
2791 * received before a close_trace_chunk.
2793 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2794 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2796 goto end_unlock_session
;
2798 conn
->session
->pending_closure_trace_chunk
=
2799 conn
->session
->current_trace_chunk
;
2800 conn
->session
->current_trace_chunk
= published_chunk
;
2801 published_chunk
= NULL
;
2802 if (!conn
->session
->pending_closure_trace_chunk
) {
2803 session
->ongoing_rotation
= false;
2806 pthread_mutex_unlock(&conn
->session
->lock
);
2808 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2809 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2811 sizeof(struct lttcomm_relayd_generic_reply
),
2813 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2814 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2819 lttng_trace_chunk_put(chunk
);
2820 lttng_trace_chunk_put(published_chunk
);
2825 * relay_close_trace_chunk: close a trace chunk
2827 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2828 struct relay_connection
*conn
,
2829 const struct lttng_buffer_view
*payload
)
2831 int ret
= 0, buf_ret
;
2833 struct relay_session
*session
= conn
->session
;
2834 struct lttcomm_relayd_close_trace_chunk
*msg
;
2835 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2836 struct lttng_buffer_view header_view
;
2837 struct lttng_trace_chunk
*chunk
= NULL
;
2838 enum lttng_error_code reply_code
= LTTNG_OK
;
2839 enum lttng_trace_chunk_status chunk_status
;
2841 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2842 time_t close_timestamp
;
2843 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2844 size_t path_length
= 0;
2845 const char *chunk_name
= NULL
;
2846 struct lttng_dynamic_buffer reply_payload
;
2847 const char *new_path
;
2849 lttng_dynamic_buffer_init(&reply_payload
);
2851 if (!session
|| !conn
->version_check_done
) {
2852 ERR("Trying to close a trace chunk before version check");
2857 if (session
->major
== 2 && session
->minor
< 11) {
2858 ERR("Chunk close command is unsupported before 2.11");
2863 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2864 if (!header_view
.data
) {
2865 ERR("Failed to receive payload of chunk close command");
2870 /* Convert to host endianness. */
2871 msg
= (typeof(msg
)) header_view
.data
;
2872 chunk_id
= be64toh(msg
->chunk_id
);
2873 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2874 close_command
= (typeof(close_command
)){
2875 .value
= be32toh(msg
->close_command
.value
),
2876 .is_set
= msg
->close_command
.is_set
,
2879 chunk
= sessiond_trace_chunk_registry_get_chunk(
2880 sessiond_trace_chunk_registry
,
2881 conn
->session
->sessiond_uuid
,
2885 char uuid_str
[LTTNG_UUID_STR_LEN
];
2887 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2888 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2893 reply_code
= LTTNG_ERR_NOMEM
;
2897 pthread_mutex_lock(&session
->lock
);
2898 if (close_command
.is_set
&&
2899 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
2901 * Clear command. It is a protocol error to ask for a
2902 * clear on a relay which does not allow it. Querying
2903 * the configuration allows figuring out whether
2904 * clearing is allowed before doing the clear.
2906 if (!opt_allow_clear
) {
2908 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2909 goto end_unlock_session
;
2912 if (session
->pending_closure_trace_chunk
&&
2913 session
->pending_closure_trace_chunk
!= chunk
) {
2914 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2915 session
->session_name
);
2916 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2918 goto end_unlock_session
;
2921 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
2922 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2923 if (close_command
.is_set
&&
2924 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
2925 !session
->has_rotated
) {
2926 /* New chunk stays in session output directory. */
2929 /* Use chunk name for new chunk. */
2932 /* Rename new chunk path. */
2933 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2935 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2937 goto end_unlock_session
;
2939 session
->ongoing_rotation
= false;
2941 if ((!close_command
.is_set
||
2942 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
2943 !lttng_trace_chunk_get_name_overridden(chunk
)) {
2944 const char *old_path
;
2946 if (!session
->has_rotated
) {
2951 /* We need to move back the .tmp_old_chunk to its rightful place. */
2952 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
2953 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2955 goto end_unlock_session
;
2958 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2959 chunk
, close_timestamp
);
2960 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2961 ERR("Failed to set trace chunk close timestamp");
2963 reply_code
= LTTNG_ERR_UNK
;
2964 goto end_unlock_session
;
2967 if (close_command
.is_set
) {
2968 chunk_status
= lttng_trace_chunk_set_close_command(
2969 chunk
, close_command
.value
);
2970 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2972 reply_code
= LTTNG_ERR_INVALID
;
2973 goto end_unlock_session
;
2976 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2977 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2978 ERR("Failed to get chunk name");
2980 reply_code
= LTTNG_ERR_UNK
;
2981 goto end_unlock_session
;
2983 if (!session
->has_rotated
&& !session
->snapshot
) {
2984 ret
= lttng_strncpy(closed_trace_chunk_path
,
2985 session
->output_path
,
2986 sizeof(closed_trace_chunk_path
));
2988 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2989 strlen(session
->output_path
),
2990 sizeof(closed_trace_chunk_path
));
2991 reply_code
= LTTNG_ERR_NOMEM
;
2993 goto end_unlock_session
;
2996 if (session
->snapshot
) {
2997 ret
= snprintf(closed_trace_chunk_path
,
2998 sizeof(closed_trace_chunk_path
),
2999 "%s/%s", session
->output_path
,
3002 ret
= snprintf(closed_trace_chunk_path
,
3003 sizeof(closed_trace_chunk_path
),
3004 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3006 session
->output_path
, chunk_name
);
3008 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3009 ERR("Failed to format closed trace chunk resulting path");
3010 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3012 goto end_unlock_session
;
3015 if (close_command
.is_set
&&
3016 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3017 session
->has_rotated
= true;
3019 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3020 path_length
= strlen(closed_trace_chunk_path
) + 1;
3021 if (path_length
> UINT32_MAX
) {
3022 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3024 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3025 goto end_unlock_session
;
3028 if (session
->current_trace_chunk
== chunk
) {
3030 * After a trace chunk close command, no new streams
3031 * referencing the chunk may be created. Hence, on the
3032 * event that no new trace chunk have been created for
3033 * the session, the reference to the current trace chunk
3034 * is released in order to allow it to be reclaimed when
3035 * the last stream releases its reference to it.
3037 lttng_trace_chunk_put(session
->current_trace_chunk
);
3038 session
->current_trace_chunk
= NULL
;
3040 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3041 session
->pending_closure_trace_chunk
= NULL
;
3043 pthread_mutex_unlock(&session
->lock
);
3046 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3047 reply
.path_length
= htobe32((uint32_t) path_length
);
3048 buf_ret
= lttng_dynamic_buffer_append(
3049 &reply_payload
, &reply
, sizeof(reply
));
3051 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3055 if (reply_code
== LTTNG_OK
) {
3056 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3057 closed_trace_chunk_path
, path_length
);
3059 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3064 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3068 if (send_ret
< reply_payload
.size
) {
3069 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3070 reply_payload
.size
, send_ret
);
3075 lttng_trace_chunk_put(chunk
);
3076 lttng_dynamic_buffer_reset(&reply_payload
);
3081 * relay_trace_chunk_exists: check if a trace chunk exists
3083 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3084 struct relay_connection
*conn
,
3085 const struct lttng_buffer_view
*payload
)
3089 struct relay_session
*session
= conn
->session
;
3090 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3091 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3092 struct lttng_buffer_view header_view
;
3096 if (!session
|| !conn
->version_check_done
) {
3097 ERR("Trying to close a trace chunk before version check");
3102 if (session
->major
== 2 && session
->minor
< 11) {
3103 ERR("Chunk close command is unsupported before 2.11");
3108 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3109 if (!header_view
.data
) {
3110 ERR("Failed to receive payload of chunk close command");
3115 /* Convert to host endianness. */
3116 msg
= (typeof(msg
)) header_view
.data
;
3117 chunk_id
= be64toh(msg
->chunk_id
);
3119 ret
= sessiond_trace_chunk_registry_chunk_exists(
3120 sessiond_trace_chunk_registry
,
3121 conn
->session
->sessiond_uuid
,
3123 chunk_id
, &chunk_exists
);
3125 * If ret is not 0, send the reply and report the error to the caller.
3126 * It is a protocol (or internal) error and the session/connection
3127 * should be torn down.
3129 reply
= (typeof(reply
)){
3130 .generic
.ret_code
= htobe32((uint32_t)
3131 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3132 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
3134 send_ret
= conn
->sock
->ops
->sendmsg(
3135 conn
->sock
, &reply
, sizeof(reply
), 0);
3136 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3137 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3146 * relay_get_configuration: query whether feature is available
3148 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3149 struct relay_connection
*conn
,
3150 const struct lttng_buffer_view
*payload
)
3154 struct lttcomm_relayd_get_configuration
*msg
;
3155 struct lttcomm_relayd_get_configuration_reply reply
= {};
3156 struct lttng_buffer_view header_view
;
3157 uint64_t query_flags
= 0;
3158 uint64_t result_flags
= 0;
3160 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3161 if (!header_view
.data
) {
3162 ERR("Failed to receive payload of chunk close command");
3167 /* Convert to host endianness. */
3168 msg
= (typeof(msg
)) header_view
.data
;
3169 query_flags
= be64toh(msg
->query_flags
);
3172 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3175 if (opt_allow_clear
) {
3176 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3180 reply
= (typeof(reply
)){
3181 .generic
.ret_code
= htobe32((uint32_t)
3182 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3183 .relayd_configuration_flags
= htobe64(result_flags
),
3185 send_ret
= conn
->sock
->ops
->sendmsg(
3186 conn
->sock
, &reply
, sizeof(reply
), 0);
3187 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3188 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3196 #define DBG_CMD(cmd_name, conn) \
3197 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3199 static int relay_process_control_command(struct relay_connection
*conn
,
3200 const struct lttcomm_relayd_hdr
*header
,
3201 const struct lttng_buffer_view
*payload
)
3205 switch (header
->cmd
) {
3206 case RELAYD_CREATE_SESSION
:
3207 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3208 ret
= relay_create_session(header
, conn
, payload
);
3210 case RELAYD_ADD_STREAM
:
3211 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3212 ret
= relay_add_stream(header
, conn
, payload
);
3214 case RELAYD_START_DATA
:
3215 DBG_CMD("RELAYD_START_DATA", conn
);
3216 ret
= relay_start(header
, conn
, payload
);
3218 case RELAYD_SEND_METADATA
:
3219 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3220 ret
= relay_recv_metadata(header
, conn
, payload
);
3222 case RELAYD_VERSION
:
3223 DBG_CMD("RELAYD_VERSION", conn
);
3224 ret
= relay_send_version(header
, conn
, payload
);
3226 case RELAYD_CLOSE_STREAM
:
3227 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3228 ret
= relay_close_stream(header
, conn
, payload
);
3230 case RELAYD_DATA_PENDING
:
3231 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3232 ret
= relay_data_pending(header
, conn
, payload
);
3234 case RELAYD_QUIESCENT_CONTROL
:
3235 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3236 ret
= relay_quiescent_control(header
, conn
, payload
);
3238 case RELAYD_BEGIN_DATA_PENDING
:
3239 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3240 ret
= relay_begin_data_pending(header
, conn
, payload
);
3242 case RELAYD_END_DATA_PENDING
:
3243 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3244 ret
= relay_end_data_pending(header
, conn
, payload
);
3246 case RELAYD_SEND_INDEX
:
3247 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3248 ret
= relay_recv_index(header
, conn
, payload
);
3250 case RELAYD_STREAMS_SENT
:
3251 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3252 ret
= relay_streams_sent(header
, conn
, payload
);
3254 case RELAYD_RESET_METADATA
:
3255 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3256 ret
= relay_reset_metadata(header
, conn
, payload
);
3258 case RELAYD_ROTATE_STREAMS
:
3259 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3260 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3262 case RELAYD_CREATE_TRACE_CHUNK
:
3263 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3264 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3266 case RELAYD_CLOSE_TRACE_CHUNK
:
3267 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3268 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3270 case RELAYD_TRACE_CHUNK_EXISTS
:
3271 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3272 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3274 case RELAYD_GET_CONFIGURATION
:
3275 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3276 ret
= relay_get_configuration(header
, conn
, payload
);
3278 case RELAYD_UPDATE_SYNC_INFO
:
3280 ERR("Received unknown command (%u)", header
->cmd
);
3281 relay_unknown_command(conn
);
3290 static enum relay_connection_status
relay_process_control_receive_payload(
3291 struct relay_connection
*conn
)
3294 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3295 struct lttng_dynamic_buffer
*reception_buffer
=
3296 &conn
->protocol
.ctrl
.reception_buffer
;
3297 struct ctrl_connection_state_receive_payload
*state
=
3298 &conn
->protocol
.ctrl
.state
.receive_payload
;
3299 struct lttng_buffer_view payload_view
;
3301 if (state
->left_to_receive
== 0) {
3302 /* Short-circuit for payload-less commands. */
3303 goto reception_complete
;
3306 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3307 reception_buffer
->data
+ state
->received
,
3308 state
->left_to_receive
, MSG_DONTWAIT
);
3310 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3311 PERROR("Unable to receive command payload on sock %d",
3313 status
= RELAY_CONNECTION_STATUS_ERROR
;
3316 } else if (ret
== 0) {
3317 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3318 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3323 assert(ret
<= state
->left_to_receive
);
3325 state
->left_to_receive
-= ret
;
3326 state
->received
+= ret
;
3328 if (state
->left_to_receive
> 0) {
3330 * Can't transition to the protocol's next state, wait to
3331 * receive the rest of the header.
3333 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3334 state
->received
, state
->left_to_receive
,
3340 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3341 conn
->sock
->fd
, state
->received
);
3343 * The payload required to process the command has been received.
3344 * A view to the reception buffer is forwarded to the various
3345 * commands and the state of the control is reset on success.
3347 * Commands are responsible for sending their reply to the peer.
3349 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3351 ret
= relay_process_control_command(conn
,
3352 &state
->header
, &payload_view
);
3354 status
= RELAY_CONNECTION_STATUS_ERROR
;
3358 ret
= connection_reset_protocol_state(conn
);
3360 status
= RELAY_CONNECTION_STATUS_ERROR
;
3366 static enum relay_connection_status
relay_process_control_receive_header(
3367 struct relay_connection
*conn
)
3370 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3371 struct lttcomm_relayd_hdr header
;
3372 struct lttng_dynamic_buffer
*reception_buffer
=
3373 &conn
->protocol
.ctrl
.reception_buffer
;
3374 struct ctrl_connection_state_receive_header
*state
=
3375 &conn
->protocol
.ctrl
.state
.receive_header
;
3377 assert(state
->left_to_receive
!= 0);
3379 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3380 reception_buffer
->data
+ state
->received
,
3381 state
->left_to_receive
, MSG_DONTWAIT
);
3383 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3384 PERROR("Unable to receive control command header on sock %d",
3386 status
= RELAY_CONNECTION_STATUS_ERROR
;
3389 } else if (ret
== 0) {
3390 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3391 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3396 assert(ret
<= state
->left_to_receive
);
3398 state
->left_to_receive
-= ret
;
3399 state
->received
+= ret
;
3401 if (state
->left_to_receive
> 0) {
3403 * Can't transition to the protocol's next state, wait to
3404 * receive the rest of the header.
3406 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3407 state
->received
, state
->left_to_receive
,
3412 /* Transition to next state: receiving the command's payload. */
3413 conn
->protocol
.ctrl
.state_id
=
3414 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3415 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3416 header
.circuit_id
= be64toh(header
.circuit_id
);
3417 header
.data_size
= be64toh(header
.data_size
);
3418 header
.cmd
= be32toh(header
.cmd
);
3419 header
.cmd_version
= be32toh(header
.cmd_version
);
3420 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3421 &header
, sizeof(header
));
3423 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3424 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3427 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3428 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3430 status
= RELAY_CONNECTION_STATUS_ERROR
;
3434 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3436 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3437 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3440 status
= RELAY_CONNECTION_STATUS_ERROR
;
3444 if (header
.data_size
== 0) {
3446 * Manually invoke the next state as the poll loop
3447 * will not wake-up to allow us to proceed further.
3449 status
= relay_process_control_receive_payload(conn
);
3456 * Process the commands received on the control socket
3458 static enum relay_connection_status
relay_process_control(
3459 struct relay_connection
*conn
)
3461 enum relay_connection_status status
;
3463 switch (conn
->protocol
.ctrl
.state_id
) {
3464 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3465 status
= relay_process_control_receive_header(conn
);
3467 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3468 status
= relay_process_control_receive_payload(conn
);
3471 ERR("Unknown control connection protocol state encountered.");
3478 static enum relay_connection_status
relay_process_data_receive_header(
3479 struct relay_connection
*conn
)
3482 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3483 struct data_connection_state_receive_header
*state
=
3484 &conn
->protocol
.data
.state
.receive_header
;
3485 struct lttcomm_relayd_data_hdr header
;
3486 struct relay_stream
*stream
;
3488 assert(state
->left_to_receive
!= 0);
3490 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3491 state
->header_reception_buffer
+ state
->received
,
3492 state
->left_to_receive
, MSG_DONTWAIT
);
3494 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3495 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3496 status
= RELAY_CONNECTION_STATUS_ERROR
;
3499 } else if (ret
== 0) {
3500 /* Orderly shutdown. Not necessary to print an error. */
3501 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3502 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3507 assert(ret
<= state
->left_to_receive
);
3509 state
->left_to_receive
-= ret
;
3510 state
->received
+= ret
;
3512 if (state
->left_to_receive
> 0) {
3514 * Can't transition to the protocol's next state, wait to
3515 * receive the rest of the header.
3517 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3518 state
->received
, state
->left_to_receive
,
3523 /* Transition to next state: receiving the payload. */
3524 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3526 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3527 header
.circuit_id
= be64toh(header
.circuit_id
);
3528 header
.stream_id
= be64toh(header
.stream_id
);
3529 header
.data_size
= be32toh(header
.data_size
);
3530 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3531 header
.padding_size
= be32toh(header
.padding_size
);
3532 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3534 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3536 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3537 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3539 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3540 conn
->sock
->fd
, header
.circuit_id
,
3541 header
.stream_id
, header
.data_size
,
3542 header
.net_seq_num
, header
.padding_size
);
3544 stream
= stream_get_by_id(header
.stream_id
);
3546 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3548 /* Protocol error. */
3549 status
= RELAY_CONNECTION_STATUS_ERROR
;
3553 pthread_mutex_lock(&stream
->lock
);
3554 /* Prepare stream for the reception of a new packet. */
3555 ret
= stream_init_packet(stream
, header
.data_size
,
3556 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3557 pthread_mutex_unlock(&stream
->lock
);
3559 ERR("Failed to rotate stream output file");
3560 status
= RELAY_CONNECTION_STATUS_ERROR
;
3561 goto end_stream_unlock
;
3570 static enum relay_connection_status
relay_process_data_receive_payload(
3571 struct relay_connection
*conn
)
3574 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3575 struct relay_stream
*stream
;
3576 struct data_connection_state_receive_payload
*state
=
3577 &conn
->protocol
.data
.state
.receive_payload
;
3578 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3579 char data_buffer
[chunk_size
];
3580 bool partial_recv
= false;
3581 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3582 uint64_t left_to_receive
= state
->left_to_receive
;
3583 struct relay_session
*session
;
3585 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3586 state
->header
.stream_id
, state
->header
.net_seq_num
,
3587 state
->received
, left_to_receive
);
3589 stream
= stream_get_by_id(state
->header
.stream_id
);
3591 /* Protocol error. */
3592 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3593 state
->header
.stream_id
);
3594 status
= RELAY_CONNECTION_STATUS_ERROR
;
3598 pthread_mutex_lock(&stream
->lock
);
3599 session
= stream
->trace
->session
;
3600 if (!conn
->session
) {
3601 ret
= connection_set_session(conn
, session
);
3603 status
= RELAY_CONNECTION_STATUS_ERROR
;
3604 goto end_stream_unlock
;
3609 * The size of the "chunk" received on any iteration is bounded by:
3610 * - the data left to receive,
3611 * - the data immediately available on the socket,
3612 * - the on-stack data buffer
3614 while (left_to_receive
> 0 && !partial_recv
) {
3615 size_t recv_size
= min(left_to_receive
, chunk_size
);
3616 struct lttng_buffer_view packet_chunk
;
3618 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3619 recv_size
, MSG_DONTWAIT
);
3621 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3622 PERROR("Socket %d error", conn
->sock
->fd
);
3623 status
= RELAY_CONNECTION_STATUS_ERROR
;
3625 goto end_stream_unlock
;
3626 } else if (ret
== 0) {
3627 /* No more data ready to be consumed on socket. */
3628 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3629 state
->header
.stream_id
);
3630 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3632 } else if (ret
< (int) recv_size
) {
3634 * All the data available on the socket has been
3637 partial_recv
= true;
3641 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3643 assert(packet_chunk
.data
);
3645 ret
= stream_write(stream
, &packet_chunk
, 0);
3647 ERR("Relay error writing data to file");
3648 status
= RELAY_CONNECTION_STATUS_ERROR
;
3649 goto end_stream_unlock
;
3652 left_to_receive
-= recv_size
;
3653 state
->received
+= recv_size
;
3654 state
->left_to_receive
= left_to_receive
;
3657 if (state
->left_to_receive
> 0) {
3659 * Did not receive all the data expected, wait for more data to
3660 * become available on the socket.
3662 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3663 state
->header
.stream_id
, state
->received
,
3664 state
->left_to_receive
);
3665 goto end_stream_unlock
;
3668 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3670 status
= RELAY_CONNECTION_STATUS_ERROR
;
3671 goto end_stream_unlock
;
3674 if (session_streams_have_index(session
)) {
3675 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3676 state
->rotate_index
, &index_flushed
,
3677 state
->header
.data_size
+ state
->header
.padding_size
);
3679 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3680 stream
->stream_handle
,
3681 state
->header
.net_seq_num
, ret
);
3682 status
= RELAY_CONNECTION_STATUS_ERROR
;
3683 goto end_stream_unlock
;
3687 if (stream
->prev_data_seq
== -1ULL) {
3691 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3692 state
->header
.padding_size
, state
->header
.net_seq_num
,
3695 status
= RELAY_CONNECTION_STATUS_ERROR
;
3696 goto end_stream_unlock
;
3700 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3701 * contents of *state which are aliased (union) to the same location as
3702 * the new state. Don't use it beyond this point.
3704 connection_reset_protocol_state(conn
);
3708 close_requested
= stream
->close_requested
;
3709 pthread_mutex_unlock(&stream
->lock
);
3710 if (close_requested
&& left_to_receive
== 0) {
3711 try_stream_close(stream
);
3715 pthread_mutex_lock(&session
->lock
);
3716 uatomic_set(&session
->new_streams
, 1);
3717 pthread_mutex_unlock(&session
->lock
);
3726 * relay_process_data: Process the data received on the data socket
3728 static enum relay_connection_status
relay_process_data(
3729 struct relay_connection
*conn
)
3731 enum relay_connection_status status
;
3733 switch (conn
->protocol
.data
.state_id
) {
3734 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3735 status
= relay_process_data_receive_header(conn
);
3737 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3738 status
= relay_process_data_receive_payload(conn
);
3741 ERR("Unexpected data connection communication state.");
3748 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3752 (void) lttng_poll_del(events
, pollfd
);
3754 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3755 fd_tracker_util_close_fd
, NULL
);
3757 ERR("Closing pollfd %d", pollfd
);
3761 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3762 int pollfd
, struct relay_connection
*conn
)
3764 const char *type_str
;
3766 switch (conn
->type
) {
3771 type_str
= "Control";
3773 case RELAY_VIEWER_COMMAND
:
3774 type_str
= "Viewer Command";
3776 case RELAY_VIEWER_NOTIFICATION
:
3777 type_str
= "Viewer Notification";
3780 type_str
= "Unknown";
3782 cleanup_connection_pollfd(events
, pollfd
);
3783 connection_put(conn
);
3784 DBG("%s connection closed with %d", type_str
, pollfd
);
3788 * This thread does the actual work
3790 static void *relay_thread_worker(void *data
)
3792 int ret
, err
= -1, last_seen_data_fd
= -1;
3794 struct lttng_poll_event events
;
3795 struct lttng_ht
*relay_connections_ht
;
3796 struct lttng_ht_iter iter
;
3797 struct relay_connection
*destroy_conn
= NULL
;
3799 DBG("[thread] Relay worker started");
3801 rcu_register_thread();
3803 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3805 if (testpoint(relayd_thread_worker
)) {
3806 goto error_testpoint
;
3809 health_code_update();
3811 /* table of connections indexed on socket */
3812 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3813 if (!relay_connections_ht
) {
3814 goto relay_connections_ht_error
;
3817 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3819 goto error_poll_create
;
3822 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3829 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3831 health_code_update();
3833 /* Infinite blocking call, waiting for transmission */
3834 DBG3("Relayd worker thread polling...");
3835 health_poll_entry();
3836 ret
= lttng_poll_wait(&events
, -1);
3840 * Restart interrupted system call.
3842 if (errno
== EINTR
) {
3851 * Process control. The control connection is
3852 * prioritized so we don't starve it with high
3853 * throughput tracing data on the data connection.
3855 for (i
= 0; i
< nb_fd
; i
++) {
3856 /* Fetch once the poll data */
3857 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3858 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3860 health_code_update();
3862 /* Thread quit pipe has been closed. Killing thread. */
3863 ret
= check_thread_quit_pipe(pollfd
, revents
);
3869 /* Inspect the relay conn pipe for new connection */
3870 if (pollfd
== relay_conn_pipe
[0]) {
3871 if (revents
& LPOLLIN
) {
3872 struct relay_connection
*conn
;
3874 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3878 ret
= lttng_poll_add(&events
,
3880 LPOLLIN
| LPOLLRDHUP
);
3882 ERR("Failed to add new connection file descriptor to poll set");
3885 connection_ht_add(relay_connections_ht
, conn
);
3886 DBG("Connection socket %d added", conn
->sock
->fd
);
3887 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3888 ERR("Relay connection pipe error");
3891 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3895 struct relay_connection
*ctrl_conn
;
3897 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3898 /* If not found, there is a synchronization issue. */
3901 if (ctrl_conn
->type
== RELAY_DATA
) {
3902 if (revents
& LPOLLIN
) {
3904 * Flag the last seen data fd not deleted. It will be
3905 * used as the last seen fd if any fd gets deleted in
3908 last_notdel_data_fd
= pollfd
;
3910 goto put_ctrl_connection
;
3912 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3914 if (revents
& LPOLLIN
) {
3915 enum relay_connection_status status
;
3917 status
= relay_process_control(ctrl_conn
);
3918 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3920 * On socket error flag the session as aborted to force
3921 * the cleanup of its stream otherwise it can leak
3922 * during the lifetime of the relayd.
3924 * This prevents situations in which streams can be
3925 * left opened because an index was received, the
3926 * control connection is closed, and the data
3927 * connection is closed (uncleanly) before the packet's
3930 * Since the control connection encountered an error,
3931 * it is okay to be conservative and close the
3932 * session right now as we can't rely on the protocol
3933 * being respected anymore.
3935 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3936 session_abort(ctrl_conn
->session
);
3939 /* Clear the connection on error or close. */
3940 relay_thread_close_connection(&events
,
3945 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3946 relay_thread_close_connection(&events
,
3948 if (last_seen_data_fd
== pollfd
) {
3949 last_seen_data_fd
= last_notdel_data_fd
;
3952 ERR("Unexpected poll events %u for control sock %d",
3954 connection_put(ctrl_conn
);
3957 put_ctrl_connection
:
3958 connection_put(ctrl_conn
);
3963 * The last loop handled a control request, go back to poll to make
3964 * sure we prioritise the control socket.
3970 if (last_seen_data_fd
>= 0) {
3971 for (i
= 0; i
< nb_fd
; i
++) {
3972 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3974 health_code_update();
3976 if (last_seen_data_fd
== pollfd
) {
3983 /* Process data connection. */
3984 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3985 /* Fetch the poll data. */
3986 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3987 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3988 struct relay_connection
*data_conn
;
3990 health_code_update();
3993 /* No activity for this FD (poll implementation). */
3997 /* Skip the command pipe. It's handled in the first loop. */
3998 if (pollfd
== relay_conn_pipe
[0]) {
4002 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4004 /* Skip it. Might be removed before. */
4007 if (data_conn
->type
== RELAY_CONTROL
) {
4008 goto put_data_connection
;
4010 assert(data_conn
->type
== RELAY_DATA
);
4012 if (revents
& LPOLLIN
) {
4013 enum relay_connection_status status
;
4015 status
= relay_process_data(data_conn
);
4016 /* Connection closed or error. */
4017 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4019 * On socket error flag the session as aborted to force
4020 * the cleanup of its stream otherwise it can leak
4021 * during the lifetime of the relayd.
4023 * This prevents situations in which streams can be
4024 * left opened because an index was received, the
4025 * control connection is closed, and the data
4026 * connection is closed (uncleanly) before the packet's
4029 * Since the data connection encountered an error,
4030 * it is okay to be conservative and close the
4031 * session right now as we can't rely on the protocol
4032 * being respected anymore.
4034 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4035 session_abort(data_conn
->session
);
4037 relay_thread_close_connection(&events
, pollfd
,
4040 * Every goto restart call sets the last seen fd where
4041 * here we don't really care since we gracefully
4042 * continue the loop after the connection is deleted.
4045 /* Keep last seen port. */
4046 last_seen_data_fd
= pollfd
;
4047 connection_put(data_conn
);
4050 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4051 relay_thread_close_connection(&events
, pollfd
,
4054 ERR("Unknown poll events %u for data sock %d",
4057 put_data_connection
:
4058 connection_put(data_conn
);
4060 last_seen_data_fd
= -1;
4063 /* Normal exit, no error */
4068 /* Cleanup remaining connection object. */
4070 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4073 health_code_update();
4075 session_abort(destroy_conn
->session
);
4078 * No need to grab another ref, because we own
4081 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4086 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4088 lttng_ht_destroy(relay_connections_ht
);
4089 relay_connections_ht_error
:
4090 /* Close relay conn pipes */
4091 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4094 DBG("Thread exited with error");
4096 DBG("Worker thread cleanup complete");
4100 ERR("Health error occurred in %s", __func__
);
4102 health_unregister(health_relayd
);
4103 rcu_unregister_thread();
4104 lttng_relay_stop_threads();
4109 * Create the relay command pipe to wake thread_manage_apps.
4110 * Closed in cleanup().
4112 static int create_relay_conn_pipe(void)
4114 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4115 "Relayd connection pipe", relay_conn_pipe
);
4118 static int stdio_open(void *data
, int *fds
)
4120 fds
[0] = fileno(stdout
);
4121 fds
[1] = fileno(stderr
);
4125 static int track_stdio(void)
4128 const char *names
[] = { "stdout", "stderr" };
4130 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4131 names
, 2, stdio_open
, NULL
);
4137 int main(int argc
, char **argv
)
4139 bool thread_is_rcu_registered
= false;
4140 int ret
= 0, retval
= 0;
4142 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4144 /* Parse environment variables */
4145 ret
= parse_env_options();
4153 * Command line arguments overwrite environment.
4156 if (set_options(argc
, argv
)) {
4161 if (set_signal_handler()) {
4166 relayd_config_log();
4168 if (opt_print_version
) {
4174 ret
= fclose(stdin
);
4176 PERROR("Failed to close stdin");
4180 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4182 /* Try to create directory if -o, --output is specified. */
4183 if (opt_output_path
) {
4184 if (*opt_output_path
!= '/') {
4185 ERR("Please specify an absolute path for -o, --output PATH");
4190 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4193 ERR("Unable to create %s", opt_output_path
);
4200 if (opt_daemon
|| opt_background
) {
4201 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4209 if (opt_working_directory
) {
4210 ret
= utils_change_working_directory(opt_working_directory
);
4212 /* All errors are already logged. */
4217 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4218 if (!sessiond_trace_chunk_registry
) {
4219 ERR("Failed to initialize session daemon trace chunk registry");
4225 * The RCU thread registration (and use, through the fd-tracker's
4226 * creation) is done after the daemonization to allow us to not
4227 * deal with liburcu's fork() management as the call RCU needs to
4230 rcu_register_thread();
4231 thread_is_rcu_registered
= true;
4233 output_path
= create_output_path("");
4235 ERR("Failed to get output path");
4239 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4240 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4243 ERR("Failed to format unlinked file directory path");
4247 the_fd_tracker
= fd_tracker_create(
4248 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4249 free(unlinked_file_directory_path
);
4250 if (!the_fd_tracker
) {
4255 ret
= track_stdio();
4261 /* Initialize thread health monitoring */
4262 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4263 if (!health_relayd
) {
4264 PERROR("health_app_create error");
4269 /* Create thread quit pipe */
4270 if (init_thread_quit_pipe()) {
4275 /* Setup the thread apps communication pipe. */
4276 if (create_relay_conn_pipe()) {
4281 /* Init relay command queue. */
4282 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4284 /* Initialize communication library */
4286 lttcomm_inet_init();
4288 /* tables of sessions indexed by session ID */
4289 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4295 /* tables of streams indexed by stream ID */
4296 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4297 if (!relay_streams_ht
) {
4302 /* tables of streams indexed by stream ID */
4303 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4304 if (!viewer_streams_ht
) {
4309 ret
= init_health_quit_pipe();
4315 /* Create thread to manage the client socket */
4316 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4317 thread_manage_health
, (void *) NULL
);
4320 PERROR("pthread_create health");
4325 /* Setup the dispatcher thread */
4326 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4327 relay_thread_dispatcher
, (void *) NULL
);
4330 PERROR("pthread_create dispatcher");
4332 goto exit_dispatcher_thread
;
4335 /* Setup the worker thread */
4336 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4337 relay_thread_worker
, NULL
);
4340 PERROR("pthread_create worker");
4342 goto exit_worker_thread
;
4345 /* Setup the listener thread */
4346 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4347 relay_thread_listener
, (void *) NULL
);
4350 PERROR("pthread_create listener");
4352 goto exit_listener_thread
;
4355 ret
= relayd_live_create(live_uri
);
4357 ERR("Starting live viewer threads");
4363 * This is where we start awaiting program completion (e.g. through
4364 * signal that asks threads to teardown).
4367 ret
= relayd_live_join();
4373 ret
= pthread_join(listener_thread
, &status
);
4376 PERROR("pthread_join listener_thread");
4380 exit_listener_thread
:
4381 ret
= pthread_join(worker_thread
, &status
);
4384 PERROR("pthread_join worker_thread");
4389 ret
= pthread_join(dispatcher_thread
, &status
);
4392 PERROR("pthread_join dispatcher_thread");
4395 exit_dispatcher_thread
:
4397 ret
= pthread_join(health_thread
, &status
);
4400 PERROR("pthread_join health_thread");
4405 * Wait for all pending call_rcu work to complete before tearing
4406 * down data structures. call_rcu worker may be trying to
4407 * perform lookups in those structures.
4412 /* Ensure all prior call_rcu are done. */
4415 if (thread_is_rcu_registered
) {
4416 rcu_unregister_thread();