2 * Copyright (C) 2012 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * SPDX-License-Identifier: GPL-2.0-only
21 #include <sys/mount.h>
22 #include <sys/resource.h>
23 #include <sys/socket.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
29 #include <urcu/futex.h>
30 #include <urcu/uatomic.h>
31 #include <urcu/rculist.h>
38 #include <lttng/lttng.h>
39 #include <common/common.h>
40 #include <common/compat/poll.h>
41 #include <common/compat/socket.h>
42 #include <common/compat/endian.h>
43 #include <common/compat/getenv.h>
44 #include <common/defaults.h>
45 #include <common/daemonize.h>
46 #include <common/futex.h>
47 #include <common/sessiond-comm/sessiond-comm.h>
48 #include <common/sessiond-comm/inet.h>
49 #include <common/sessiond-comm/relayd.h>
50 #include <common/uri.h>
51 #include <common/utils.h>
52 #include <common/align.h>
53 #include <common/config/session-config.h>
54 #include <common/dynamic-buffer.h>
55 #include <common/buffer-view.h>
56 #include <common/string-utils/format.h>
57 #include <common/fd-tracker/fd-tracker.h>
58 #include <common/fd-tracker/utils.h>
60 #include "backward-compatibility-group-by.h"
62 #include "connection.h"
63 #include "ctf-trace.h"
64 #include "health-relayd.h"
67 #include "lttng-relayd.h"
69 #include "sessiond-trace-chunks.h"
71 #include "tcp_keep_alive.h"
72 #include "testpoint.h"
73 #include "tracefile-array.h"
76 #include "viewer-stream.h"
78 static const char *help_msg
=
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
86 enum relay_connection_status
{
87 RELAY_CONNECTION_STATUS_OK
,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR
,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED
,
94 /* command line options */
95 char *opt_output_path
, *opt_working_directory
;
96 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
97 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
103 #define NR_LTTNG_RELAY_READY 3
104 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
106 /* Size of receive buffer. */
107 #define RECV_DATA_BUFFER_SIZE 65536
109 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
110 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
112 static struct lttng_uri
*control_uri
;
113 static struct lttng_uri
*data_uri
;
114 static struct lttng_uri
*live_uri
;
116 const char *progname
;
118 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
119 static int tracing_group_name_override
;
121 const char * const config_section_name
= "relayd";
124 * Quit pipe for all threads. This permits a single cancellation point
125 * for all threads when receiving an event on the pipe.
127 int thread_quit_pipe
[2] = { -1, -1 };
130 * This pipe is used to inform the worker thread that a command is queued and
131 * ready to be processed.
133 static int relay_conn_pipe
[2] = { -1, -1 };
135 /* Shared between threads */
136 static int dispatch_thread_exit
;
138 static pthread_t listener_thread
;
139 static pthread_t dispatcher_thread
;
140 static pthread_t worker_thread
;
141 static pthread_t health_thread
;
144 * last_relay_stream_id_lock protects last_relay_stream_id increment
145 * atomicity on 32-bit architectures.
147 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
148 static uint64_t last_relay_stream_id
;
151 * Relay command queue.
153 * The relay_thread_listener and relay_thread_dispatcher communicate with this
156 static struct relay_conn_queue relay_conn_queue
;
158 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
159 static unsigned int lttng_opt_fd_pool_size
= -1;
161 /* Global relay stream hash table. */
162 struct lttng_ht
*relay_streams_ht
;
164 /* Global relay viewer stream hash table. */
165 struct lttng_ht
*viewer_streams_ht
;
167 /* Global relay sessions hash table. */
168 struct lttng_ht
*sessions_ht
;
170 /* Relayd health monitoring */
171 struct health_app
*health_relayd
;
173 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
175 /* Global fd tracker. */
176 struct fd_tracker
*the_fd_tracker
;
178 static struct option long_options
[] = {
179 { "control-port", 1, 0, 'C', },
180 { "data-port", 1, 0, 'D', },
181 { "live-port", 1, 0, 'L', },
182 { "daemonize", 0, 0, 'd', },
183 { "background", 0, 0, 'b', },
184 { "group", 1, 0, 'g', },
185 { "fd-pool-size", 1, 0, '\0', },
186 { "help", 0, 0, 'h', },
187 { "output", 1, 0, 'o', },
188 { "verbose", 0, 0, 'v', },
189 { "config", 1, 0, 'f' },
190 { "version", 0, 0, 'V' },
191 { "working-directory", 1, 0, 'w', },
192 { "group-output-by-session", 0, 0, 's', },
193 { "group-output-by-host", 0, 0, 'p', },
194 { "disallow-clear", 0, 0, 'x' },
198 static const char *config_ignore_options
[] = { "help", "config", "version" };
200 static void print_version(void) {
201 fprintf(stdout
, "%s\n", VERSION
);
204 static void relayd_config_log(void)
206 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
207 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
208 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
209 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
210 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
212 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
213 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
218 * Take an option from the getopt output and set it in the right variable to be
221 * Return 0 on success else a negative value.
223 static int set_option(int opt
, const char *arg
, const char *optname
)
229 if (!strcmp(optname
, "fd-pool-size")) {
233 v
= strtoul(arg
, NULL
, 0);
234 if (errno
!= 0 || !isdigit((unsigned char) arg
[0])) {
235 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
240 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
244 lttng_opt_fd_pool_size
= (unsigned int) v
;
246 fprintf(stderr
, "unknown option %s", optname
);
248 fprintf(stderr
, " with arg %s\n", arg
);
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
255 "-C, --control-port");
257 ret
= uri_parse(arg
, &control_uri
);
259 ERR("Invalid control URI specified");
262 if (control_uri
->port
== 0) {
263 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
268 if (lttng_is_setuid_setgid()) {
269 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
272 ret
= uri_parse(arg
, &data_uri
);
274 ERR("Invalid data URI specified");
277 if (data_uri
->port
== 0) {
278 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
283 if (lttng_is_setuid_setgid()) {
284 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
287 ret
= uri_parse(arg
, &live_uri
);
289 ERR("Invalid live URI specified");
292 if (live_uri
->port
== 0) {
293 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
304 if (lttng_is_setuid_setgid()) {
305 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
308 tracing_group_name
= strdup(arg
);
309 if (tracing_group_name
== NULL
) {
314 tracing_group_name_override
= 1;
318 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
320 ERR("Cannot show --help for `lttng-relayd`");
325 opt_print_version
= 1;
328 if (lttng_is_setuid_setgid()) {
329 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
332 ret
= asprintf(&opt_output_path
, "%s", arg
);
335 PERROR("asprintf opt_output_path");
341 if (lttng_is_setuid_setgid()) {
342 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
343 "-w, --working-directory");
345 ret
= asprintf(&opt_working_directory
, "%s", arg
);
348 PERROR("asprintf opt_working_directory");
355 /* Verbose level can increase using multiple -v */
357 lttng_opt_verbose
= config_parse_value(arg
);
359 /* Only 3 level of verbosity (-vvv). */
360 if (lttng_opt_verbose
< 3) {
361 lttng_opt_verbose
+= 1;
366 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
367 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
370 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
373 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
374 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
377 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
384 /* Unknown option or other error.
385 * Error is printed by getopt, just return */
398 * config_entry_handler_cb used to handle options read from a config file.
399 * See config_entry_handler_cb comment in common/config/session-config.h for the
400 * return value conventions.
402 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
406 if (!entry
|| !entry
->name
|| !entry
->value
) {
411 /* Check if the option is to be ignored */
412 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
413 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
418 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
419 /* Ignore if entry name is not fully matched. */
420 if (strcmp(entry
->name
, long_options
[i
].name
)) {
425 * If the option takes no argument on the command line,
426 * we have to check if the value is "true". We support
427 * non-zero numeric values, true, on and yes.
429 if (!long_options
[i
].has_arg
) {
430 ret
= config_parse_value(entry
->value
);
433 WARN("Invalid configuration value \"%s\" for option %s",
434 entry
->value
, entry
->name
);
436 /* False, skip boolean config option. */
441 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
445 WARN("Unrecognized option \"%s\" in daemon configuration file.",
452 static int parse_env_options(void)
457 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
459 opt_working_directory
= strdup(value
);
460 if (!opt_working_directory
) {
461 ERR("Failed to allocate working directory string (\"%s\")",
469 static int set_fd_pool_size(void)
472 struct rlimit rlimit
;
474 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
476 PERROR("Failed to get file descriptor limit");
481 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
482 (uint64_t) rlimit
.rlim_cur
,
483 (uint64_t) rlimit
.rlim_max
);
484 if (lttng_opt_fd_pool_size
== -1) {
485 /* Use default value (soft limit - reserve). */
486 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
487 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
488 (uint64_t) rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
492 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
493 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
497 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
498 ERR("File descriptor pool size must be set to at least %d",
499 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
504 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
505 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%" PRIu64
").",
506 lttng_opt_fd_pool_size
, (uint64_t) rlimit
.rlim_cur
);
511 DBG("File descriptor pool size argument (%u) adjusted to %u to accommodates transient fd uses",
512 lttng_opt_fd_pool_size
,
513 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
514 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
519 static int set_options(int argc
, char **argv
)
521 int c
, ret
= 0, option_index
= 0, retval
= 0;
522 int orig_optopt
= optopt
, orig_optind
= optind
;
523 char *default_address
, *optstring
;
524 char *config_path
= NULL
;
526 optstring
= utils_generate_optstring(long_options
,
527 sizeof(long_options
) / sizeof(struct option
));
533 /* Check for the --config option */
535 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
536 &option_index
)) != -1) {
540 } else if (c
!= 'f') {
544 if (lttng_is_setuid_setgid()) {
545 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
549 config_path
= utils_expand_path(optarg
);
551 ERR("Failed to resolve path: %s", optarg
);
556 ret
= config_get_section_entries(config_path
, config_section_name
,
557 config_entry_handler
, NULL
);
560 ERR("Invalid configuration option at line %i", ret
);
566 /* Reset getopt's global state */
567 optopt
= orig_optopt
;
568 optind
= orig_optind
;
570 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
575 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
582 /* assign default values */
583 if (control_uri
== NULL
) {
584 ret
= asprintf(&default_address
,
585 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
586 DEFAULT_NETWORK_CONTROL_PORT
);
588 PERROR("asprintf default data address");
593 ret
= uri_parse(default_address
, &control_uri
);
594 free(default_address
);
596 ERR("Invalid control URI specified");
601 if (data_uri
== NULL
) {
602 ret
= asprintf(&default_address
,
603 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
604 DEFAULT_NETWORK_DATA_PORT
);
606 PERROR("asprintf default data address");
611 ret
= uri_parse(default_address
, &data_uri
);
612 free(default_address
);
614 ERR("Invalid data URI specified");
619 if (live_uri
== NULL
) {
620 ret
= asprintf(&default_address
,
621 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
622 DEFAULT_NETWORK_VIEWER_PORT
);
624 PERROR("asprintf default viewer control address");
629 ret
= uri_parse(default_address
, &live_uri
);
630 free(default_address
);
632 ERR("Invalid viewer control URI specified");
637 ret
= set_fd_pool_size();
643 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
644 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
646 if (opt_allow_clear
) {
647 /* Check if env variable exists. */
648 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
650 ret
= config_parse_value(value
);
652 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
656 opt_allow_clear
= !ret
;
666 static void print_global_objects(void)
668 print_viewer_streams();
669 print_relay_streams();
673 static int noop_close(void *data
, int *fds
)
678 static void untrack_stdio(void)
680 int fds
[] = { fileno(stdout
), fileno(stderr
) };
683 * noop_close is used since we don't really want to close
684 * the stdio output fds; we merely want to stop tracking them.
686 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
687 fds
, 2, noop_close
, NULL
);
693 static void relayd_cleanup(void)
695 print_global_objects();
699 if (viewer_streams_ht
)
700 lttng_ht_destroy(viewer_streams_ht
);
701 if (relay_streams_ht
)
702 lttng_ht_destroy(relay_streams_ht
);
704 lttng_ht_destroy(sessions_ht
);
706 free(opt_output_path
);
707 free(opt_working_directory
);
710 health_app_destroy(health_relayd
);
712 /* Close thread quit pipes */
713 if (health_quit_pipe
[0] != -1) {
714 (void) fd_tracker_util_pipe_close(
715 the_fd_tracker
, health_quit_pipe
);
717 if (thread_quit_pipe
[0] != -1) {
718 (void) fd_tracker_util_pipe_close(
719 the_fd_tracker
, thread_quit_pipe
);
721 if (sessiond_trace_chunk_registry
) {
722 sessiond_trace_chunk_registry_destroy(
723 sessiond_trace_chunk_registry
);
725 if (the_fd_tracker
) {
728 * fd_tracker_destroy() will log the contents of the fd-tracker
729 * if a leak is detected.
731 fd_tracker_destroy(the_fd_tracker
);
734 uri_free(control_uri
);
736 /* Live URI is freed in the live thread. */
738 if (tracing_group_name_override
) {
739 free((void *) tracing_group_name
);
744 * Write to writable pipe used to notify a thread.
746 static int notify_thread_pipe(int wpipe
)
750 ret
= lttng_write(wpipe
, "!", 1);
752 PERROR("write poll pipe");
760 static int notify_health_quit_pipe(int *pipe
)
764 ret
= lttng_write(pipe
[1], "4", 1);
766 PERROR("write relay health quit");
775 * Stop all relayd and relayd-live threads.
777 int lttng_relay_stop_threads(void)
781 /* Stopping all threads */
782 DBG("Terminating all threads");
783 if (notify_thread_pipe(thread_quit_pipe
[1])) {
784 ERR("write error on thread quit pipe");
788 if (notify_health_quit_pipe(health_quit_pipe
)) {
789 ERR("write error on health quit pipe");
792 /* Dispatch thread */
793 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
794 futex_nto1_wake(&relay_conn_queue
.futex
);
796 if (relayd_live_stop()) {
797 ERR("Error stopping live threads");
804 * Signal handler for the daemon
806 * Simply stop all worker threads, leaving main() return gracefully after
807 * joining all threads and calling cleanup().
809 static void sighandler(int sig
)
813 DBG("SIGINT caught");
814 if (lttng_relay_stop_threads()) {
815 ERR("Error stopping threads");
819 DBG("SIGTERM caught");
820 if (lttng_relay_stop_threads()) {
821 ERR("Error stopping threads");
825 CMM_STORE_SHARED(recv_child_signal
, 1);
833 * Setup signal handler for :
834 * SIGINT, SIGTERM, SIGPIPE
836 static int set_signal_handler(void)
842 if ((ret
= sigemptyset(&sigset
)) < 0) {
843 PERROR("sigemptyset");
850 sa
.sa_handler
= sighandler
;
851 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
856 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
861 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
866 sa
.sa_handler
= SIG_IGN
;
867 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
872 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
877 void lttng_relay_notify_ready(void)
879 /* Notify the parent of the fork() process that we are ready. */
880 if (opt_daemon
|| opt_background
) {
881 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
882 kill(child_ppid
, SIGUSR1
);
888 * Init thread quit pipe.
890 * Return -1 on error or 0 if all pipes are created.
892 static int init_thread_quit_pipe(void)
894 return fd_tracker_util_pipe_open_cloexec(
895 the_fd_tracker
, "Quit pipe", thread_quit_pipe
);
899 * Init health quit pipe.
901 * Return -1 on error or 0 if all pipes are created.
903 static int init_health_quit_pipe(void)
905 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
906 "Health quit pipe", health_quit_pipe
);
910 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
912 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
913 int size
, const char *name
)
917 if (events
== NULL
|| size
== 0) {
922 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
923 name
, events
, 1, LTTNG_CLOEXEC
);
925 PERROR("Failed to create \"%s\" poll file descriptor", name
);
930 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
942 * Check if the thread quit pipe was triggered.
944 * Return 1 if it was triggered else 0;
946 static int check_thread_quit_pipe(int fd
, uint32_t events
)
948 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
955 static int create_sock(void *data
, int *out_fd
)
958 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
960 ret
= lttcomm_create_sock(sock
);
970 static int close_sock(void *data
, int *in_fd
)
972 struct lttcomm_sock
*sock
= (lttcomm_sock
*) data
;
974 return sock
->ops
->close(sock
);
977 static int accept_sock(void *data
, int *out_fd
)
980 /* Socks is an array of in_sock, out_sock. */
981 struct lttcomm_sock
**socks
= (lttcomm_sock
**) data
;
982 struct lttcomm_sock
*in_sock
= socks
[0];
984 socks
[1] = in_sock
->ops
->accept(in_sock
);
989 *out_fd
= socks
[1]->fd
;
995 * Create and init socket from uri.
997 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
1001 struct lttcomm_sock
*sock
= NULL
;
1002 char uri_str
[PATH_MAX
];
1003 char *formated_name
= NULL
;
1005 sock
= lttcomm_alloc_sock_from_uri(uri
);
1007 ERR("Allocating socket");
1012 * Don't fail to create the socket if the name can't be built as it is
1013 * only used for debugging purposes.
1015 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
1016 uri_str
[sizeof(uri_str
) - 1] = '\0';
1018 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
1021 formated_name
= NULL
;
1025 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
1026 (const char **) (formated_name
? &formated_name
: NULL
),
1027 1, create_sock
, sock
);
1029 PERROR("Failed to open \"%s\" relay socket",
1030 formated_name
?: "Unknown");
1033 DBG("Listening on %s socket %d", name
, sock
->fd
);
1035 ret
= sock
->ops
->bind(sock
);
1037 PERROR("Failed to bind socket");
1041 ret
= sock
->ops
->listen(sock
, -1);
1047 free(formated_name
);
1052 lttcomm_destroy_sock(sock
);
1054 free(formated_name
);
1059 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
1063 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
1064 struct lttcomm_sock
*new_sock
= NULL
;
1066 ret
= fd_tracker_open_unsuspendable_fd(
1067 the_fd_tracker
, &out_fd
,
1068 (const char **) &name
,
1069 1, accept_sock
, &socks
);
1073 new_sock
= socks
[1];
1074 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
1080 * This thread manages the listening for new connections on the network
1082 static void *relay_thread_listener(void *data
)
1084 int i
, ret
, pollfd
, err
= -1;
1085 uint32_t revents
, nb_fd
;
1086 struct lttng_poll_event events
;
1087 struct lttcomm_sock
*control_sock
, *data_sock
;
1089 DBG("[thread] Relay listener started");
1091 rcu_register_thread();
1092 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
1094 health_code_update();
1096 control_sock
= relay_socket_create(control_uri
, "Control listener");
1097 if (!control_sock
) {
1098 goto error_sock_control
;
1101 data_sock
= relay_socket_create(data_uri
, "Data listener");
1103 goto error_sock_relay
;
1107 * Pass 3 as size here for the thread quit pipe, control and
1110 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
1112 goto error_create_poll
;
1115 /* Add the control socket */
1116 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1118 goto error_poll_add
;
1121 /* Add the data socket */
1122 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
1124 goto error_poll_add
;
1127 lttng_relay_notify_ready();
1129 if (testpoint(relayd_thread_listener
)) {
1130 goto error_testpoint
;
1134 health_code_update();
1136 DBG("Listener accepting connections");
1139 health_poll_entry();
1140 ret
= lttng_poll_wait(&events
, -1);
1144 * Restart interrupted system call.
1146 if (errno
== EINTR
) {
1154 DBG("Relay new connection received");
1155 for (i
= 0; i
< nb_fd
; i
++) {
1156 health_code_update();
1158 /* Fetch once the poll data */
1159 revents
= LTTNG_POLL_GETEV(&events
, i
);
1160 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1162 /* Thread quit pipe has been closed. Killing thread. */
1163 ret
= check_thread_quit_pipe(pollfd
, revents
);
1169 if (revents
& LPOLLIN
) {
1171 * A new connection is requested, therefore a
1172 * sessiond/consumerd connection is allocated in
1173 * this thread, enqueued to a global queue and
1174 * dequeued (and freed) in the worker thread.
1177 struct relay_connection
*new_conn
;
1178 struct lttcomm_sock
*newsock
= NULL
;
1179 enum connection_type type
;
1181 if (pollfd
== data_sock
->fd
) {
1183 newsock
= accept_relayd_sock(data_sock
,
1184 "Data socket to relayd");
1186 LTTNG_ASSERT(pollfd
== control_sock
->fd
);
1187 type
= RELAY_CONTROL
;
1188 newsock
= accept_relayd_sock(control_sock
,
1189 "Control socket to relayd");
1192 PERROR("accepting sock");
1196 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1199 PERROR("setsockopt inet");
1200 lttcomm_destroy_sock(newsock
);
1204 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1206 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1208 lttcomm_destroy_sock(newsock
);
1212 new_conn
= connection_create(newsock
, type
);
1214 lttcomm_destroy_sock(newsock
);
1218 /* Enqueue request for the dispatcher thread. */
1219 cds_wfcq_head_ptr_t head
;
1220 head
.h
= &relay_conn_queue
.head
;
1221 cds_wfcq_enqueue(head
, &relay_conn_queue
.tail
,
1225 * Wake the dispatch queue futex.
1226 * Implicit memory barrier with the
1227 * exchange in cds_wfcq_enqueue.
1229 futex_nto1_wake(&relay_conn_queue
.futex
);
1230 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1231 ERR("socket poll error");
1234 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1244 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1246 if (data_sock
->fd
>= 0) {
1247 int data_sock_fd
= data_sock
->fd
;
1249 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1250 &data_sock_fd
, 1, close_sock
,
1253 PERROR("Failed to close the data listener socket file descriptor");
1257 lttcomm_destroy_sock(data_sock
);
1259 if (control_sock
->fd
>= 0) {
1260 int control_sock_fd
= control_sock
->fd
;
1262 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1263 &control_sock_fd
, 1, close_sock
,
1266 PERROR("Failed to close the control listener socket file descriptor");
1268 control_sock
->fd
= -1;
1270 lttcomm_destroy_sock(control_sock
);
1274 ERR("Health error occurred in %s", __func__
);
1276 health_unregister(health_relayd
);
1277 rcu_unregister_thread();
1278 DBG("Relay listener thread cleanup complete");
1279 lttng_relay_stop_threads();
1284 * This thread manages the dispatching of the requests to worker threads
1286 static void *relay_thread_dispatcher(void *data
)
1290 struct cds_wfcq_node
*node
;
1291 struct relay_connection
*new_conn
= NULL
;
1293 DBG("[thread] Relay dispatcher started");
1295 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1297 if (testpoint(relayd_thread_dispatcher
)) {
1298 goto error_testpoint
;
1301 health_code_update();
1304 health_code_update();
1306 /* Atomically prepare the queue futex */
1307 futex_nto1_prepare(&relay_conn_queue
.futex
);
1309 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1314 health_code_update();
1316 /* Dequeue commands */
1317 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1318 &relay_conn_queue
.tail
);
1320 DBG("Woken up but nothing in the relay command queue");
1321 /* Continue thread execution */
1324 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1326 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1329 * Inform worker thread of the new request. This
1330 * call is blocking so we can be assured that
1331 * the data will be read at some point in time
1332 * or wait to the end of the world :)
1334 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1336 PERROR("write connection pipe");
1337 connection_put(new_conn
);
1340 } while (node
!= NULL
);
1342 /* Futex wait on queue. Blocking call on futex() */
1343 health_poll_entry();
1344 futex_nto1_wait(&relay_conn_queue
.futex
);
1348 /* Normal exit, no error */
1355 ERR("Health error occurred in %s", __func__
);
1357 health_unregister(health_relayd
);
1358 DBG("Dispatch thread dying");
1359 lttng_relay_stop_threads();
1363 static bool session_streams_have_index(const struct relay_session
*session
)
1365 return session
->minor
>= 4 && !session
->snapshot
;
1369 * Handle the RELAYD_CREATE_SESSION command.
1371 * On success, send back the session id or else return a negative value.
1373 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1374 struct relay_connection
*conn
,
1375 const struct lttng_buffer_view
*payload
)
1379 struct relay_session
*session
= NULL
;
1380 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1381 char session_name
[LTTNG_NAME_MAX
] = {};
1382 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1383 uint32_t live_timer
= 0;
1384 bool snapshot
= false;
1385 bool session_name_contains_creation_timestamp
= false;
1386 /* Left nil for peers < 2.11. */
1387 char base_path
[LTTNG_PATH_MAX
] = {};
1388 lttng_uuid sessiond_uuid
= {};
1389 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1390 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1391 LTTNG_OPTIONAL(time_t) creation_time
= {};
1392 struct lttng_dynamic_buffer reply_payload
;
1394 lttng_dynamic_buffer_init(&reply_payload
);
1396 if (conn
->minor
< 4) {
1397 /* From 2.1 to 2.3 */
1399 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1400 /* From 2.4 to 2.10 */
1401 ret
= cmd_create_session_2_4(payload
, session_name
,
1402 hostname
, &live_timer
, &snapshot
);
1404 bool has_current_chunk
;
1405 uint64_t current_chunk_id_value
;
1406 time_t creation_time_value
;
1407 uint64_t id_sessiond_value
;
1409 /* From 2.11 to ... */
1410 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1411 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1412 sessiond_uuid
, &has_current_chunk
,
1413 ¤t_chunk_id_value
, &creation_time_value
,
1414 &session_name_contains_creation_timestamp
);
1415 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1416 /* The nil UUID is reserved for pre-2.11 clients. */
1417 ERR("Illegal nil UUID announced by peer in create session command");
1421 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1422 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1423 if (has_current_chunk
) {
1424 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1425 current_chunk_id_value
);
1433 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1434 snapshot
, sessiond_uuid
,
1435 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1436 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1437 creation_time
.is_set
? &creation_time
.value
: NULL
,
1438 conn
->major
, conn
->minor
,
1439 session_name_contains_creation_timestamp
);
1444 LTTNG_ASSERT(!conn
->session
);
1445 conn
->session
= session
;
1446 DBG("Created session %" PRIu64
, session
->id
);
1448 reply
.generic
.session_id
= htobe64(session
->id
);
1452 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1454 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1457 if (conn
->minor
< 11) {
1458 /* From 2.1 to 2.10 */
1459 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1460 &reply
.generic
, sizeof(reply
.generic
));
1462 ERR("Failed to append \"create session\" command reply header to payload buffer");
1467 const uint32_t output_path_length
=
1468 session
? strlen(session
->output_path
) + 1 : 0;
1470 reply
.output_path_length
= htobe32(output_path_length
);
1471 ret
= lttng_dynamic_buffer_append(
1472 &reply_payload
, &reply
, sizeof(reply
));
1474 ERR("Failed to append \"create session\" command reply header to payload buffer");
1478 if (output_path_length
) {
1479 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1480 session
->output_path
,
1481 output_path_length
);
1483 ERR("Failed to append \"create session\" command reply path to payload buffer");
1489 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1490 reply_payload
.size
, 0);
1491 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1492 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1493 reply_payload
.size
, send_ret
);
1497 if (ret
< 0 && session
) {
1498 session_put(session
);
1500 lttng_dynamic_buffer_reset(&reply_payload
);
1505 * When we have received all the streams and the metadata for a channel,
1506 * we make them visible to the viewer threads.
1508 static void publish_connection_local_streams(struct relay_connection
*conn
)
1510 struct relay_stream
*stream
;
1511 struct relay_session
*session
= conn
->session
;
1514 * We publish all streams belonging to a session atomically wrt
1517 pthread_mutex_lock(&session
->lock
);
1519 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1521 stream_publish(stream
);
1526 * Inform the viewer that there are new streams in the session.
1528 if (session
->viewer_attached
) {
1529 uatomic_set(&session
->new_streams
, 1);
1531 pthread_mutex_unlock(&session
->lock
);
1534 static int conform_channel_path(char *channel_path
)
1538 if (strstr("../", channel_path
)) {
1539 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1545 if (*channel_path
== '/') {
1546 const size_t len
= strlen(channel_path
);
1549 * Channel paths from peers prior to 2.11 are expressed as an
1550 * absolute path that is, in reality, relative to the relay
1551 * daemon's output directory. Remove the leading slash so it
1552 * is correctly interpreted as a relative path later on.
1554 * len (and not len - 1) is used to copy the trailing NULL.
1556 bcopy(channel_path
+ 1, channel_path
, len
);
1563 * relay_add_stream: allocate a new stream for a session
1565 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1566 struct relay_connection
*conn
,
1567 const struct lttng_buffer_view
*payload
)
1571 struct relay_session
*session
= conn
->session
;
1572 struct relay_stream
*stream
= NULL
;
1573 struct lttcomm_relayd_status_stream reply
;
1574 struct ctf_trace
*trace
= NULL
;
1575 uint64_t stream_handle
= -1ULL;
1576 char *path_name
= NULL
, *channel_name
= NULL
;
1577 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1578 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1580 if (!session
|| !conn
->version_check_done
) {
1581 ERR("Trying to add a stream before version check");
1583 goto end_no_session
;
1586 if (session
->minor
== 1) {
1588 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1590 } else if (session
->minor
> 1 && session
->minor
< 11) {
1591 /* From 2.2 to 2.10 */
1592 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1593 &channel_name
, &tracefile_size
, &tracefile_count
);
1595 /* From 2.11 to ... */
1596 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1597 &channel_name
, &tracefile_size
, &tracefile_count
,
1598 &stream_chunk_id
.value
);
1599 stream_chunk_id
.is_set
= true;
1606 if (conform_channel_path(path_name
)) {
1611 * Backward compatibility for --group-output-by-session.
1612 * Prior to lttng 2.11, the complete path is passed by the stream.
1613 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1614 * >=2.11 the chunk is responsible for the output path. When dealing
1615 * with producer < 2.11 the chunk output_path is the root output path
1616 * and the stream carries the complete path (path_name).
1617 * To support --group-output-by-session with older producer (<2.11), we
1618 * need to craft the path based on the stream path.
1620 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1621 if (conn
->minor
< 4) {
1623 * From 2.1 to 2.3, the session_name is not passed on
1624 * the RELAYD_CREATE_SESSION command. The session name
1625 * is necessary to detect the presence of a base_path
1626 * inside the stream path. Without it we cannot perform
1627 * a valid group-output-by-session transformation.
1629 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1630 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1631 session
->id
, path_name
);
1632 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1633 char *group_by_session_path_name
;
1635 LTTNG_ASSERT(session
->session_name
[0] != '\0');
1637 group_by_session_path_name
=
1638 backward_compat_group_by_session(
1640 session
->session_name
,
1641 session
->creation_time
.value
);
1642 if (!group_by_session_path_name
) {
1643 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1648 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1649 path_name
, group_by_session_path_name
);
1652 path_name
= group_by_session_path_name
;
1656 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1661 /* This stream here has one reference on the trace. */
1662 pthread_mutex_lock(&last_relay_stream_id_lock
);
1663 stream_handle
= ++last_relay_stream_id
;
1664 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1666 /* We pass ownership of path_name and channel_name. */
1667 stream
= stream_create(trace
, stream_handle
, path_name
,
1668 channel_name
, tracefile_size
, tracefile_count
);
1670 channel_name
= NULL
;
1673 * Streams are the owners of their trace. Reference to trace is
1674 * kept within stream_create().
1676 ctf_trace_put(trace
);
1679 memset(&reply
, 0, sizeof(reply
));
1680 reply
.handle
= htobe64(stream_handle
);
1682 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1684 reply
.ret_code
= htobe32(LTTNG_OK
);
1687 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1688 sizeof(struct lttcomm_relayd_status_stream
), 0);
1689 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1690 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1702 * relay_close_stream: close a specific stream
1704 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1705 struct relay_connection
*conn
,
1706 const struct lttng_buffer_view
*payload
)
1710 struct relay_session
*session
= conn
->session
;
1711 struct lttcomm_relayd_close_stream stream_info
;
1712 struct lttcomm_relayd_generic_reply reply
;
1713 struct relay_stream
*stream
;
1715 DBG("Close stream received");
1717 if (!session
|| !conn
->version_check_done
) {
1718 ERR("Trying to close a stream before version check");
1720 goto end_no_session
;
1723 if (payload
->size
< sizeof(stream_info
)) {
1724 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1725 sizeof(stream_info
), payload
->size
);
1727 goto end_no_session
;
1729 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1730 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1731 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1733 stream
= stream_get_by_id(stream_info
.stream_id
);
1740 * Set last_net_seq_num before the close flag. Required by data
1743 pthread_mutex_lock(&stream
->lock
);
1744 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1745 pthread_mutex_unlock(&stream
->lock
);
1748 * This is one of the conditions which may trigger a stream close
1749 * with the others being:
1750 * 1) A close command is received for a stream
1751 * 2) The control connection owning the stream is closed
1752 * 3) We have received all of the stream's data _after_ a close
1755 try_stream_close(stream
);
1756 if (stream
->is_metadata
) {
1757 struct relay_viewer_stream
*vstream
;
1759 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1761 if (stream
->no_new_metadata_notified
) {
1763 * Since all the metadata has been sent to the
1764 * viewer and that we have a request to close
1765 * its stream, we can safely teardown the
1766 * corresponding metadata viewer stream.
1768 viewer_stream_put(vstream
);
1770 /* Put local reference. */
1771 viewer_stream_put(vstream
);
1778 memset(&reply
, 0, sizeof(reply
));
1780 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1782 reply
.ret_code
= htobe32(LTTNG_OK
);
1784 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1785 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1786 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1787 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1797 * relay_reset_metadata: reset a metadata stream
1800 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1801 struct relay_connection
*conn
,
1802 const struct lttng_buffer_view
*payload
)
1806 struct relay_session
*session
= conn
->session
;
1807 struct lttcomm_relayd_reset_metadata stream_info
;
1808 struct lttcomm_relayd_generic_reply reply
;
1809 struct relay_stream
*stream
;
1811 DBG("Reset metadata received");
1813 if (!session
|| !conn
->version_check_done
) {
1814 ERR("Trying to reset a metadata stream before version check");
1816 goto end_no_session
;
1819 if (payload
->size
< sizeof(stream_info
)) {
1820 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1821 sizeof(stream_info
), payload
->size
);
1823 goto end_no_session
;
1825 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1826 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1827 stream_info
.version
= be64toh(stream_info
.version
);
1829 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1831 /* Unsupported for live sessions for now. */
1832 if (session
->live_timer
!= 0) {
1837 stream
= stream_get_by_id(stream_info
.stream_id
);
1842 pthread_mutex_lock(&stream
->lock
);
1843 if (!stream
->is_metadata
) {
1848 ret
= stream_reset_file(stream
);
1850 ERR("Failed to reset metadata stream %" PRIu64
1851 ": stream_path = %s, channel = %s",
1852 stream
->stream_handle
, stream
->path_name
,
1853 stream
->channel_name
);
1857 pthread_mutex_unlock(&stream
->lock
);
1861 memset(&reply
, 0, sizeof(reply
));
1863 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1865 reply
.ret_code
= htobe32(LTTNG_OK
);
1867 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1868 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1869 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1870 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1880 * relay_unknown_command: send -1 if received unknown command
1882 static void relay_unknown_command(struct relay_connection
*conn
)
1884 struct lttcomm_relayd_generic_reply reply
;
1887 memset(&reply
, 0, sizeof(reply
));
1888 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1889 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1890 if (send_ret
< sizeof(reply
)) {
1891 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1896 * relay_start: send an acknowledgment to the client to tell if we are
1897 * ready to receive data. We are ready if a session is established.
1899 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1900 struct relay_connection
*conn
,
1901 const struct lttng_buffer_view
*payload
)
1905 struct lttcomm_relayd_generic_reply reply
;
1906 struct relay_session
*session
= conn
->session
;
1909 DBG("Trying to start the streaming without a session established");
1910 ret
= htobe32(LTTNG_ERR_UNK
);
1913 memset(&reply
, 0, sizeof(reply
));
1914 reply
.ret_code
= htobe32(LTTNG_OK
);
1915 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1917 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1918 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1927 * relay_recv_metadata: receive the metadata for the session.
1929 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1930 struct relay_connection
*conn
,
1931 const struct lttng_buffer_view
*payload
)
1934 struct relay_session
*session
= conn
->session
;
1935 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1936 struct relay_stream
*metadata_stream
;
1937 uint64_t metadata_payload_size
;
1938 struct lttng_buffer_view packet_view
;
1941 ERR("Metadata sent before version check");
1946 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1947 ERR("Incorrect data size");
1951 metadata_payload_size
= recv_hdr
->data_size
-
1952 sizeof(struct lttcomm_relayd_metadata_payload
);
1954 memcpy(&metadata_payload_header
, payload
->data
,
1955 sizeof(metadata_payload_header
));
1956 metadata_payload_header
.stream_id
= be64toh(
1957 metadata_payload_header
.stream_id
);
1958 metadata_payload_header
.padding_size
= be32toh(
1959 metadata_payload_header
.padding_size
);
1961 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1962 if (!metadata_stream
) {
1967 packet_view
= lttng_buffer_view_from_view(payload
,
1968 sizeof(metadata_payload_header
), metadata_payload_size
);
1969 if (!lttng_buffer_view_is_valid(&packet_view
)) {
1970 ERR("Invalid metadata packet length announced by header");
1975 pthread_mutex_lock(&metadata_stream
->lock
);
1976 ret
= stream_write(metadata_stream
, &packet_view
,
1977 metadata_payload_header
.padding_size
);
1978 pthread_mutex_unlock(&metadata_stream
->lock
);
1984 stream_put(metadata_stream
);
1990 * relay_send_version: send relayd version number
1992 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1993 struct relay_connection
*conn
,
1994 const struct lttng_buffer_view
*payload
)
1998 struct lttcomm_relayd_version reply
, msg
;
1999 bool compatible
= true;
2001 conn
->version_check_done
= true;
2003 /* Get version from the other side. */
2004 if (payload
->size
< sizeof(msg
)) {
2005 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2006 sizeof(msg
), payload
->size
);
2011 memcpy(&msg
, payload
->data
, sizeof(msg
));
2012 msg
.major
= be32toh(msg
.major
);
2013 msg
.minor
= be32toh(msg
.minor
);
2015 memset(&reply
, 0, sizeof(reply
));
2016 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2017 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2019 /* Major versions must be the same */
2020 if (reply
.major
!= msg
.major
) {
2021 DBG("Incompatible major versions (%u vs %u), deleting session",
2022 reply
.major
, msg
.major
);
2026 conn
->major
= reply
.major
;
2027 /* We adapt to the lowest compatible version */
2028 if (reply
.minor
<= msg
.minor
) {
2029 conn
->minor
= reply
.minor
;
2031 conn
->minor
= msg
.minor
;
2034 reply
.major
= htobe32(reply
.major
);
2035 reply
.minor
= htobe32(reply
.minor
);
2036 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2038 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2039 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2052 DBG("Version check done using protocol %u.%u", conn
->major
,
2060 * Check for data pending for a given stream id from the session daemon.
2062 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2063 struct relay_connection
*conn
,
2064 const struct lttng_buffer_view
*payload
)
2066 struct relay_session
*session
= conn
->session
;
2067 struct lttcomm_relayd_data_pending msg
;
2068 struct lttcomm_relayd_generic_reply reply
;
2069 struct relay_stream
*stream
;
2072 uint64_t stream_seq
;
2074 DBG("Data pending command received");
2076 if (!session
|| !conn
->version_check_done
) {
2077 ERR("Trying to check for data before version check");
2079 goto end_no_session
;
2082 if (payload
->size
< sizeof(msg
)) {
2083 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2084 sizeof(msg
), payload
->size
);
2086 goto end_no_session
;
2088 memcpy(&msg
, payload
->data
, sizeof(msg
));
2089 msg
.stream_id
= be64toh(msg
.stream_id
);
2090 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2092 stream
= stream_get_by_id(msg
.stream_id
);
2093 if (stream
== NULL
) {
2098 pthread_mutex_lock(&stream
->lock
);
2100 if (session_streams_have_index(session
)) {
2102 * Ensure that both the index and stream data have been
2103 * flushed up to the requested point.
2105 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2107 stream_seq
= stream
->prev_data_seq
;
2109 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2110 ", prev_index_seq %" PRIu64
2111 ", and last_seq %" PRIu64
, msg
.stream_id
,
2112 stream
->prev_data_seq
, stream
->prev_index_seq
,
2113 msg
.last_net_seq_num
);
2115 /* Avoid wrapping issue */
2116 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2117 /* Data has in fact been written and is NOT pending */
2120 /* Data still being streamed thus pending */
2124 stream
->data_pending_check_done
= true;
2125 pthread_mutex_unlock(&stream
->lock
);
2130 memset(&reply
, 0, sizeof(reply
));
2131 reply
.ret_code
= htobe32(ret
);
2132 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2133 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2134 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2144 * Wait for the control socket to reach a quiescent state.
2146 * Note that for now, when receiving this command from the session
2147 * daemon, this means that every subsequent commands or data received on
2148 * the control socket has been handled. So, this is why we simply return
2151 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2152 struct relay_connection
*conn
,
2153 const struct lttng_buffer_view
*payload
)
2157 struct relay_stream
*stream
;
2158 struct lttcomm_relayd_quiescent_control msg
;
2159 struct lttcomm_relayd_generic_reply reply
;
2161 DBG("Checking quiescent state on control socket");
2163 if (!conn
->session
|| !conn
->version_check_done
) {
2164 ERR("Trying to check for data before version check");
2166 goto end_no_session
;
2169 if (payload
->size
< sizeof(msg
)) {
2170 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2171 sizeof(msg
), payload
->size
);
2173 goto end_no_session
;
2175 memcpy(&msg
, payload
->data
, sizeof(msg
));
2176 msg
.stream_id
= be64toh(msg
.stream_id
);
2178 stream
= stream_get_by_id(msg
.stream_id
);
2182 pthread_mutex_lock(&stream
->lock
);
2183 stream
->data_pending_check_done
= true;
2184 pthread_mutex_unlock(&stream
->lock
);
2186 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2189 memset(&reply
, 0, sizeof(reply
));
2190 reply
.ret_code
= htobe32(LTTNG_OK
);
2191 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2192 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2193 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2205 * Initialize a data pending command. This means that a consumer is about
2206 * to ask for data pending for each stream it holds. Simply iterate over
2207 * all streams of a session and set the data_pending_check_done flag.
2209 * This command returns to the client a LTTNG_OK code.
2211 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2212 struct relay_connection
*conn
,
2213 const struct lttng_buffer_view
*payload
)
2217 struct lttng_ht_iter iter
;
2218 struct lttcomm_relayd_begin_data_pending msg
;
2219 struct lttcomm_relayd_generic_reply reply
;
2220 struct relay_stream
*stream
;
2222 LTTNG_ASSERT(recv_hdr
);
2225 DBG("Init streams for data pending");
2227 if (!conn
->session
|| !conn
->version_check_done
) {
2228 ERR("Trying to check for data before version check");
2230 goto end_no_session
;
2233 if (payload
->size
< sizeof(msg
)) {
2234 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2235 sizeof(msg
), payload
->size
);
2237 goto end_no_session
;
2239 memcpy(&msg
, payload
->data
, sizeof(msg
));
2240 msg
.session_id
= be64toh(msg
.session_id
);
2243 * Iterate over all streams to set the begin data pending flag.
2244 * For now, the streams are indexed by stream handle so we have
2245 * to iterate over all streams to find the one associated with
2246 * the right session_id.
2249 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2251 if (!stream_get(stream
)) {
2254 if (stream
->trace
->session
->id
== msg
.session_id
) {
2255 pthread_mutex_lock(&stream
->lock
);
2256 stream
->data_pending_check_done
= false;
2257 pthread_mutex_unlock(&stream
->lock
);
2258 DBG("Set begin data pending flag to stream %" PRIu64
,
2259 stream
->stream_handle
);
2265 memset(&reply
, 0, sizeof(reply
));
2266 /* All good, send back reply. */
2267 reply
.ret_code
= htobe32(LTTNG_OK
);
2269 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2270 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2271 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2283 * End data pending command. This will check, for a given session id, if
2284 * each stream associated with it has its data_pending_check_done flag
2285 * set. If not, this means that the client lost track of the stream but
2286 * the data is still being streamed on our side. In this case, we inform
2287 * the client that data is in flight.
2289 * Return to the client if there is data in flight or not with a ret_code.
2291 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2292 struct relay_connection
*conn
,
2293 const struct lttng_buffer_view
*payload
)
2297 struct lttng_ht_iter iter
;
2298 struct lttcomm_relayd_end_data_pending msg
;
2299 struct lttcomm_relayd_generic_reply reply
;
2300 struct relay_stream
*stream
;
2301 uint32_t is_data_inflight
= 0;
2303 DBG("End data pending command");
2305 if (!conn
->session
|| !conn
->version_check_done
) {
2306 ERR("Trying to check for data before version check");
2308 goto end_no_session
;
2311 if (payload
->size
< sizeof(msg
)) {
2312 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2313 sizeof(msg
), payload
->size
);
2315 goto end_no_session
;
2317 memcpy(&msg
, payload
->data
, sizeof(msg
));
2318 msg
.session_id
= be64toh(msg
.session_id
);
2321 * Iterate over all streams to see if the begin data pending
2325 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2327 if (!stream_get(stream
)) {
2330 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2334 pthread_mutex_lock(&stream
->lock
);
2335 if (!stream
->data_pending_check_done
) {
2336 uint64_t stream_seq
;
2338 if (session_streams_have_index(conn
->session
)) {
2340 * Ensure that both the index and stream data have been
2341 * flushed up to the requested point.
2343 stream_seq
= std::min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2345 stream_seq
= stream
->prev_data_seq
;
2347 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2348 is_data_inflight
= 1;
2349 DBG("Data is still in flight for stream %" PRIu64
,
2350 stream
->stream_handle
);
2351 pthread_mutex_unlock(&stream
->lock
);
2356 pthread_mutex_unlock(&stream
->lock
);
2361 memset(&reply
, 0, sizeof(reply
));
2362 /* All good, send back reply. */
2363 reply
.ret_code
= htobe32(is_data_inflight
);
2365 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2366 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2367 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2379 * Receive an index for a specific stream.
2381 * Return 0 on success else a negative value.
2383 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2384 struct relay_connection
*conn
,
2385 const struct lttng_buffer_view
*payload
)
2389 struct relay_session
*session
= conn
->session
;
2390 struct lttcomm_relayd_index index_info
;
2391 struct lttcomm_relayd_generic_reply reply
;
2392 struct relay_stream
*stream
;
2397 DBG("Relay receiving index");
2399 if (!session
|| !conn
->version_check_done
) {
2400 ERR("Trying to close a stream before version check");
2402 goto end_no_session
;
2405 msg_len
= lttcomm_relayd_index_len(
2406 lttng_to_index_major(conn
->major
, conn
->minor
),
2407 lttng_to_index_minor(conn
->major
, conn
->minor
));
2408 if (payload
->size
< msg_len
) {
2409 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2410 msg_len
, payload
->size
);
2412 goto end_no_session
;
2414 memcpy(&index_info
, payload
->data
, msg_len
);
2415 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2416 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2417 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2418 index_info
.content_size
= be64toh(index_info
.content_size
);
2419 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2420 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2421 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2422 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2424 if (conn
->minor
>= 8) {
2425 index_info
.stream_instance_id
=
2426 be64toh(index_info
.stream_instance_id
);
2427 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2429 index_info
.stream_instance_id
= -1ULL;
2430 index_info
.packet_seq_num
= -1ULL;
2433 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2435 ERR("stream_get_by_id not found");
2440 pthread_mutex_lock(&stream
->lock
);
2441 ret
= stream_add_index(stream
, &index_info
);
2442 pthread_mutex_unlock(&stream
->lock
);
2444 goto end_stream_put
;
2450 memset(&reply
, 0, sizeof(reply
));
2452 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2454 reply
.ret_code
= htobe32(LTTNG_OK
);
2456 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2457 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2458 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2467 * Receive the streams_sent message.
2469 * Return 0 on success else a negative value.
2471 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2472 struct relay_connection
*conn
,
2473 const struct lttng_buffer_view
*payload
)
2477 struct lttcomm_relayd_generic_reply reply
;
2481 DBG("Relay receiving streams_sent");
2483 if (!conn
->session
|| !conn
->version_check_done
) {
2484 ERR("Trying to close a stream before version check");
2486 goto end_no_session
;
2490 * Publish every pending stream in the connection recv list which are
2491 * now ready to be used by the viewer.
2493 publish_connection_local_streams(conn
);
2495 memset(&reply
, 0, sizeof(reply
));
2496 reply
.ret_code
= htobe32(LTTNG_OK
);
2497 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2498 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2499 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2512 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2513 * session rotation feature (not the tracefile rotation feature).
2515 static int relay_rotate_session_streams(
2516 const struct lttcomm_relayd_hdr
*recv_hdr
,
2517 struct relay_connection
*conn
,
2518 const struct lttng_buffer_view
*payload
)
2523 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2524 struct relay_session
*session
= conn
->session
;
2525 struct lttcomm_relayd_rotate_streams rotate_streams
;
2526 struct lttcomm_relayd_generic_reply reply
= {};
2527 struct relay_stream
*stream
= NULL
;
2528 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2529 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2530 struct lttng_buffer_view stream_positions
;
2531 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2532 const char *chunk_id_str
= "none";
2534 if (!session
|| !conn
->version_check_done
) {
2535 ERR("Trying to rotate a stream before version check");
2540 if (session
->major
== 2 && session
->minor
< 11) {
2541 ERR("Unsupported feature before 2.11");
2546 if (payload
->size
< header_len
) {
2547 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2548 header_len
, payload
->size
);
2553 memcpy(&rotate_streams
, payload
->data
, header_len
);
2555 /* Convert header to host endianness. */
2556 rotate_streams
= (typeof(rotate_streams
)) {
2557 .stream_count
= be32toh(rotate_streams
.stream_count
),
2558 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2559 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2560 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2564 if (rotate_streams
.new_chunk_id
.is_set
) {
2566 * Retrieve the trace chunk the stream must transition to. As
2567 * per the protocol, this chunk should have been created
2568 * before this command is received.
2570 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2571 sessiond_trace_chunk_registry
,
2572 session
->sessiond_uuid
, session
->id
,
2573 rotate_streams
.new_chunk_id
.value
);
2574 if (!next_trace_chunk
) {
2575 char uuid_str
[LTTNG_UUID_STR_LEN
];
2577 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2578 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2579 ", trace_chunk_id = %" PRIu64
,
2580 uuid_str
, session
->id
,
2581 rotate_streams
.new_chunk_id
.value
);
2582 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2587 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2588 rotate_streams
.new_chunk_id
.value
);
2589 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2590 chunk_id_str
= "formatting error";
2592 chunk_id_str
= chunk_id_buf
;
2596 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2597 rotate_streams
.stream_count
, session
->session_name
,
2600 stream_positions
= lttng_buffer_view_from_view(payload
,
2601 sizeof(rotate_streams
), -1);
2602 if (!stream_positions
.data
||
2603 stream_positions
.size
<
2604 (rotate_streams
.stream_count
*
2605 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2606 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2611 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2612 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2613 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2614 const struct lttcomm_relayd_stream_rotation_position pos
= {
2615 .stream_id
= be64toh(position_comm
->stream_id
),
2616 .rotate_at_seq_num
= be64toh(
2617 position_comm
->rotate_at_seq_num
),
2620 stream
= stream_get_by_id(pos
.stream_id
);
2622 reply_code
= LTTNG_ERR_INVALID
;
2627 pthread_mutex_lock(&stream
->lock
);
2628 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2629 pos
.rotate_at_seq_num
);
2630 pthread_mutex_unlock(&stream
->lock
);
2632 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2640 reply_code
= LTTNG_OK
;
2647 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2648 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2649 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2650 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2651 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2656 lttng_trace_chunk_put(next_trace_chunk
);
2663 * relay_create_trace_chunk: create a new trace chunk
2665 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2666 struct relay_connection
*conn
,
2667 const struct lttng_buffer_view
*payload
)
2671 struct relay_session
*session
= conn
->session
;
2672 struct lttcomm_relayd_create_trace_chunk
*msg
;
2673 struct lttcomm_relayd_generic_reply reply
= {};
2674 struct lttng_buffer_view header_view
;
2675 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2676 enum lttng_error_code reply_code
= LTTNG_OK
;
2677 enum lttng_trace_chunk_status chunk_status
;
2678 const char *new_path
;
2680 if (!session
|| !conn
->version_check_done
) {
2681 ERR("Trying to create a trace chunk before version check");
2686 if (session
->major
== 2 && session
->minor
< 11) {
2687 ERR("Chunk creation command is unsupported before 2.11");
2692 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2693 if (!lttng_buffer_view_is_valid(&header_view
)) {
2694 ERR("Failed to receive payload of chunk creation command");
2699 /* Convert to host endianness. */
2700 msg
= (typeof(msg
)) header_view
.data
;
2701 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2702 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2703 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2705 if (session
->current_trace_chunk
&&
2706 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2707 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2708 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2709 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2710 ERR("Failed to rename old chunk");
2712 reply_code
= LTTNG_ERR_UNK
;
2716 session
->ongoing_rotation
= true;
2717 if (!session
->current_trace_chunk
) {
2718 if (!session
->has_rotated
) {
2724 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2726 chunk
= lttng_trace_chunk_create(
2727 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2729 ERR("Failed to create trace chunk in trace chunk creation command");
2731 reply_code
= LTTNG_ERR_NOMEM
;
2734 lttng_trace_chunk_set_fd_tracker(chunk
, the_fd_tracker
);
2736 if (msg
->override_name_length
) {
2738 const struct lttng_buffer_view chunk_name_view
=
2739 lttng_buffer_view_from_view(payload
,
2741 msg
->override_name_length
);
2743 if (!lttng_buffer_view_is_valid(&chunk_name_view
)) {
2744 ERR("Invalid payload of chunk creation command (protocol error): buffer too short for expected name length");
2746 reply_code
= LTTNG_ERR_INVALID
;
2750 name
= chunk_name_view
.data
;
2751 if (name
[msg
->override_name_length
- 1]) {
2752 ERR("Invalid payload of chunk creation command (protocol error): name is not null-terminated");
2754 reply_code
= LTTNG_ERR_INVALID
;
2758 chunk_status
= lttng_trace_chunk_override_name(
2759 chunk
, chunk_name_view
.data
);
2760 switch (chunk_status
) {
2761 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2763 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2764 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2765 reply_code
= LTTNG_ERR_INVALID
;
2769 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2770 reply_code
= LTTNG_ERR_UNK
;
2776 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2777 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2778 reply_code
= LTTNG_ERR_UNK
;
2783 LTTNG_ASSERT(conn
->session
->output_directory
);
2784 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
,
2785 conn
->session
->output_directory
);
2786 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2787 reply_code
= LTTNG_ERR_UNK
;
2792 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2793 sessiond_trace_chunk_registry
,
2794 conn
->session
->sessiond_uuid
,
2797 if (!published_chunk
) {
2798 char uuid_str
[LTTNG_UUID_STR_LEN
];
2800 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2801 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2806 reply_code
= LTTNG_ERR_NOMEM
;
2810 pthread_mutex_lock(&conn
->session
->lock
);
2811 if (conn
->session
->pending_closure_trace_chunk
) {
2813 * Invalid; this means a second create_trace_chunk command was
2814 * received before a close_trace_chunk.
2816 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2817 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2819 goto end_unlock_session
;
2821 conn
->session
->pending_closure_trace_chunk
=
2822 conn
->session
->current_trace_chunk
;
2823 conn
->session
->current_trace_chunk
= published_chunk
;
2824 published_chunk
= NULL
;
2825 if (!conn
->session
->pending_closure_trace_chunk
) {
2826 session
->ongoing_rotation
= false;
2829 pthread_mutex_unlock(&conn
->session
->lock
);
2831 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2832 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2834 sizeof(struct lttcomm_relayd_generic_reply
),
2836 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2837 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2842 lttng_trace_chunk_put(chunk
);
2843 lttng_trace_chunk_put(published_chunk
);
2848 * relay_close_trace_chunk: close a trace chunk
2850 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2851 struct relay_connection
*conn
,
2852 const struct lttng_buffer_view
*payload
)
2854 int ret
= 0, buf_ret
;
2856 struct relay_session
*session
= conn
->session
;
2857 struct lttcomm_relayd_close_trace_chunk
*msg
;
2858 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2859 struct lttng_buffer_view header_view
;
2860 struct lttng_trace_chunk
*chunk
= NULL
;
2861 enum lttng_error_code reply_code
= LTTNG_OK
;
2862 enum lttng_trace_chunk_status chunk_status
;
2864 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2865 time_t close_timestamp
;
2866 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2867 size_t path_length
= 0;
2868 const char *chunk_name
= NULL
;
2869 struct lttng_dynamic_buffer reply_payload
;
2870 const char *new_path
;
2872 lttng_dynamic_buffer_init(&reply_payload
);
2874 if (!session
|| !conn
->version_check_done
) {
2875 ERR("Trying to close a trace chunk before version check");
2880 if (session
->major
== 2 && session
->minor
< 11) {
2881 ERR("Chunk close command is unsupported before 2.11");
2886 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2887 if (!lttng_buffer_view_is_valid(&header_view
)) {
2888 ERR("Failed to receive payload of chunk close command");
2893 /* Convert to host endianness. */
2894 msg
= (typeof(msg
)) header_view
.data
;
2895 chunk_id
= be64toh(msg
->chunk_id
);
2896 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2897 close_command
.value
= (lttng_trace_chunk_command_type
) be32toh(msg
->close_command
.value
);
2898 close_command
.is_set
= msg
->close_command
.is_set
;
2900 chunk
= sessiond_trace_chunk_registry_get_chunk(
2901 sessiond_trace_chunk_registry
,
2902 conn
->session
->sessiond_uuid
,
2906 char uuid_str
[LTTNG_UUID_STR_LEN
];
2908 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2909 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2914 reply_code
= LTTNG_ERR_NOMEM
;
2918 pthread_mutex_lock(&session
->lock
);
2919 if (close_command
.is_set
&&
2920 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
2922 * Clear command. It is a protocol error to ask for a
2923 * clear on a relay which does not allow it. Querying
2924 * the configuration allows figuring out whether
2925 * clearing is allowed before doing the clear.
2927 if (!opt_allow_clear
) {
2929 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2930 goto end_unlock_session
;
2933 if (session
->pending_closure_trace_chunk
&&
2934 session
->pending_closure_trace_chunk
!= chunk
) {
2935 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2936 session
->session_name
);
2937 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2939 goto end_unlock_session
;
2942 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
2943 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2944 if (close_command
.is_set
&&
2945 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
2946 !session
->has_rotated
) {
2947 /* New chunk stays in session output directory. */
2950 /* Use chunk name for new chunk. */
2953 /* Rename new chunk path. */
2954 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2956 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2958 goto end_unlock_session
;
2960 session
->ongoing_rotation
= false;
2962 if ((!close_command
.is_set
||
2963 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
2964 !lttng_trace_chunk_get_name_overridden(chunk
)) {
2965 const char *old_path
;
2967 if (!session
->has_rotated
) {
2972 /* We need to move back the .tmp_old_chunk to its rightful place. */
2973 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
2974 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2976 goto end_unlock_session
;
2979 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2980 chunk
, close_timestamp
);
2981 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2982 ERR("Failed to set trace chunk close timestamp");
2984 reply_code
= LTTNG_ERR_UNK
;
2985 goto end_unlock_session
;
2988 if (close_command
.is_set
) {
2989 chunk_status
= lttng_trace_chunk_set_close_command(
2990 chunk
, close_command
.value
);
2991 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2993 reply_code
= LTTNG_ERR_INVALID
;
2994 goto end_unlock_session
;
2997 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2998 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2999 ERR("Failed to get chunk name");
3001 reply_code
= LTTNG_ERR_UNK
;
3002 goto end_unlock_session
;
3004 if (!session
->has_rotated
&& !session
->snapshot
) {
3005 ret
= lttng_strncpy(closed_trace_chunk_path
,
3006 session
->output_path
,
3007 sizeof(closed_trace_chunk_path
));
3009 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
3010 strlen(session
->output_path
),
3011 sizeof(closed_trace_chunk_path
));
3012 reply_code
= LTTNG_ERR_NOMEM
;
3014 goto end_unlock_session
;
3017 if (session
->snapshot
) {
3018 ret
= snprintf(closed_trace_chunk_path
,
3019 sizeof(closed_trace_chunk_path
),
3020 "%s/%s", session
->output_path
,
3023 ret
= snprintf(closed_trace_chunk_path
,
3024 sizeof(closed_trace_chunk_path
),
3025 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
3027 session
->output_path
, chunk_name
);
3029 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
3030 ERR("Failed to format closed trace chunk resulting path");
3031 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
3033 goto end_unlock_session
;
3036 if (close_command
.is_set
&&
3037 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
3038 session
->has_rotated
= true;
3040 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
3041 path_length
= strlen(closed_trace_chunk_path
) + 1;
3042 if (path_length
> UINT32_MAX
) {
3043 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
3045 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
3046 goto end_unlock_session
;
3049 if (session
->current_trace_chunk
== chunk
) {
3051 * After a trace chunk close command, no new streams
3052 * referencing the chunk may be created. Hence, on the
3053 * event that no new trace chunk have been created for
3054 * the session, the reference to the current trace chunk
3055 * is released in order to allow it to be reclaimed when
3056 * the last stream releases its reference to it.
3058 lttng_trace_chunk_put(session
->current_trace_chunk
);
3059 session
->current_trace_chunk
= NULL
;
3061 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
3062 session
->pending_closure_trace_chunk
= NULL
;
3064 pthread_mutex_unlock(&session
->lock
);
3067 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
3068 reply
.path_length
= htobe32((uint32_t) path_length
);
3069 buf_ret
= lttng_dynamic_buffer_append(
3070 &reply_payload
, &reply
, sizeof(reply
));
3072 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
3076 if (reply_code
== LTTNG_OK
) {
3077 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
3078 closed_trace_chunk_path
, path_length
);
3080 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
3085 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
3089 if (send_ret
< reply_payload
.size
) {
3090 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
3091 reply_payload
.size
, send_ret
);
3096 lttng_trace_chunk_put(chunk
);
3097 lttng_dynamic_buffer_reset(&reply_payload
);
3102 * relay_trace_chunk_exists: check if a trace chunk exists
3104 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
3105 struct relay_connection
*conn
,
3106 const struct lttng_buffer_view
*payload
)
3110 struct relay_session
*session
= conn
->session
;
3111 struct lttcomm_relayd_trace_chunk_exists
*msg
;
3112 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
3113 struct lttng_buffer_view header_view
;
3117 if (!session
|| !conn
->version_check_done
) {
3118 ERR("Trying to check for the existance of a trace chunk before version check");
3123 if (session
->major
== 2 && session
->minor
< 11) {
3124 ERR("Chunk exists command is unsupported before 2.11");
3129 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3130 if (!lttng_buffer_view_is_valid(&header_view
)) {
3131 ERR("Failed to receive payload of chunk exists command");
3136 /* Convert to host endianness. */
3137 msg
= (typeof(msg
)) header_view
.data
;
3138 chunk_id
= be64toh(msg
->chunk_id
);
3140 ret
= sessiond_trace_chunk_registry_chunk_exists(
3141 sessiond_trace_chunk_registry
,
3142 conn
->session
->sessiond_uuid
,
3144 chunk_id
, &chunk_exists
);
3146 * If ret is not 0, send the reply and report the error to the caller.
3147 * It is a protocol (or internal) error and the session/connection
3148 * should be torn down.
3150 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3151 reply
.trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0;
3153 send_ret
= conn
->sock
->ops
->sendmsg(
3154 conn
->sock
, &reply
, sizeof(reply
), 0);
3155 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3156 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3165 * relay_get_configuration: query whether feature is available
3167 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3168 struct relay_connection
*conn
,
3169 const struct lttng_buffer_view
*payload
)
3173 struct lttcomm_relayd_get_configuration
*msg
;
3174 struct lttcomm_relayd_get_configuration_reply reply
= {};
3175 struct lttng_buffer_view header_view
;
3176 uint64_t query_flags
= 0;
3177 uint64_t result_flags
= 0;
3179 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3180 if (!lttng_buffer_view_is_valid(&header_view
)) {
3181 ERR("Failed to receive payload of chunk close command");
3186 /* Convert to host endianness. */
3187 msg
= (typeof(msg
)) header_view
.data
;
3188 query_flags
= be64toh(msg
->query_flags
);
3191 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3194 if (opt_allow_clear
) {
3195 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3199 reply
.generic
.ret_code
= htobe32((uint32_t) (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
));
3200 reply
.relayd_configuration_flags
= htobe64(result_flags
);
3202 send_ret
= conn
->sock
->ops
->sendmsg(
3203 conn
->sock
, &reply
, sizeof(reply
), 0);
3204 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3205 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3213 #define DBG_CMD(cmd_name, conn) \
3214 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3216 static int relay_process_control_command(struct relay_connection
*conn
,
3217 const struct lttcomm_relayd_hdr
*header
,
3218 const struct lttng_buffer_view
*payload
)
3222 switch (header
->cmd
) {
3223 case RELAYD_CREATE_SESSION
:
3224 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3225 ret
= relay_create_session(header
, conn
, payload
);
3227 case RELAYD_ADD_STREAM
:
3228 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3229 ret
= relay_add_stream(header
, conn
, payload
);
3231 case RELAYD_START_DATA
:
3232 DBG_CMD("RELAYD_START_DATA", conn
);
3233 ret
= relay_start(header
, conn
, payload
);
3235 case RELAYD_SEND_METADATA
:
3236 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3237 ret
= relay_recv_metadata(header
, conn
, payload
);
3239 case RELAYD_VERSION
:
3240 DBG_CMD("RELAYD_VERSION", conn
);
3241 ret
= relay_send_version(header
, conn
, payload
);
3243 case RELAYD_CLOSE_STREAM
:
3244 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3245 ret
= relay_close_stream(header
, conn
, payload
);
3247 case RELAYD_DATA_PENDING
:
3248 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3249 ret
= relay_data_pending(header
, conn
, payload
);
3251 case RELAYD_QUIESCENT_CONTROL
:
3252 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3253 ret
= relay_quiescent_control(header
, conn
, payload
);
3255 case RELAYD_BEGIN_DATA_PENDING
:
3256 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3257 ret
= relay_begin_data_pending(header
, conn
, payload
);
3259 case RELAYD_END_DATA_PENDING
:
3260 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3261 ret
= relay_end_data_pending(header
, conn
, payload
);
3263 case RELAYD_SEND_INDEX
:
3264 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3265 ret
= relay_recv_index(header
, conn
, payload
);
3267 case RELAYD_STREAMS_SENT
:
3268 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3269 ret
= relay_streams_sent(header
, conn
, payload
);
3271 case RELAYD_RESET_METADATA
:
3272 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3273 ret
= relay_reset_metadata(header
, conn
, payload
);
3275 case RELAYD_ROTATE_STREAMS
:
3276 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3277 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3279 case RELAYD_CREATE_TRACE_CHUNK
:
3280 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3281 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3283 case RELAYD_CLOSE_TRACE_CHUNK
:
3284 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3285 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3287 case RELAYD_TRACE_CHUNK_EXISTS
:
3288 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3289 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3291 case RELAYD_GET_CONFIGURATION
:
3292 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3293 ret
= relay_get_configuration(header
, conn
, payload
);
3295 case RELAYD_UPDATE_SYNC_INFO
:
3297 ERR("Received unknown command (%u)", header
->cmd
);
3298 relay_unknown_command(conn
);
3307 static enum relay_connection_status
relay_process_control_receive_payload(
3308 struct relay_connection
*conn
)
3311 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3312 struct lttng_dynamic_buffer
*reception_buffer
=
3313 &conn
->protocol
.ctrl
.reception_buffer
;
3314 struct ctrl_connection_state_receive_payload
*state
=
3315 &conn
->protocol
.ctrl
.state
.receive_payload
;
3316 struct lttng_buffer_view payload_view
;
3318 if (state
->left_to_receive
== 0) {
3319 /* Short-circuit for payload-less commands. */
3320 goto reception_complete
;
3323 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3324 reception_buffer
->data
+ state
->received
,
3325 state
->left_to_receive
, MSG_DONTWAIT
);
3327 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3328 PERROR("Unable to receive command payload on sock %d",
3330 status
= RELAY_CONNECTION_STATUS_ERROR
;
3333 } else if (ret
== 0) {
3334 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3335 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3339 LTTNG_ASSERT(ret
> 0);
3340 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3342 state
->left_to_receive
-= ret
;
3343 state
->received
+= ret
;
3345 if (state
->left_to_receive
> 0) {
3347 * Can't transition to the protocol's next state, wait to
3348 * receive the rest of the header.
3350 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3351 state
->received
, state
->left_to_receive
,
3357 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3358 conn
->sock
->fd
, state
->received
);
3360 * The payload required to process the command has been received.
3361 * A view to the reception buffer is forwarded to the various
3362 * commands and the state of the control is reset on success.
3364 * Commands are responsible for sending their reply to the peer.
3366 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3368 ret
= relay_process_control_command(conn
,
3369 &state
->header
, &payload_view
);
3371 status
= RELAY_CONNECTION_STATUS_ERROR
;
3375 ret
= connection_reset_protocol_state(conn
);
3377 status
= RELAY_CONNECTION_STATUS_ERROR
;
3383 static enum relay_connection_status
relay_process_control_receive_header(
3384 struct relay_connection
*conn
)
3387 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3388 struct lttcomm_relayd_hdr header
;
3389 struct lttng_dynamic_buffer
*reception_buffer
=
3390 &conn
->protocol
.ctrl
.reception_buffer
;
3391 struct ctrl_connection_state_receive_header
*state
=
3392 &conn
->protocol
.ctrl
.state
.receive_header
;
3394 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3396 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3397 reception_buffer
->data
+ state
->received
,
3398 state
->left_to_receive
, MSG_DONTWAIT
);
3400 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3401 PERROR("Unable to receive control command header on sock %d",
3403 status
= RELAY_CONNECTION_STATUS_ERROR
;
3406 } else if (ret
== 0) {
3407 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3408 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3412 LTTNG_ASSERT(ret
> 0);
3413 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3415 state
->left_to_receive
-= ret
;
3416 state
->received
+= ret
;
3418 if (state
->left_to_receive
> 0) {
3420 * Can't transition to the protocol's next state, wait to
3421 * receive the rest of the header.
3423 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3424 state
->received
, state
->left_to_receive
,
3429 /* Transition to next state: receiving the command's payload. */
3430 conn
->protocol
.ctrl
.state_id
=
3431 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3432 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3433 header
.circuit_id
= be64toh(header
.circuit_id
);
3434 header
.data_size
= be64toh(header
.data_size
);
3435 header
.cmd
= be32toh(header
.cmd
);
3436 header
.cmd_version
= be32toh(header
.cmd_version
);
3437 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3438 &header
, sizeof(header
));
3440 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3441 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3444 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3445 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3447 status
= RELAY_CONNECTION_STATUS_ERROR
;
3451 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3453 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3454 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3457 status
= RELAY_CONNECTION_STATUS_ERROR
;
3461 if (header
.data_size
== 0) {
3463 * Manually invoke the next state as the poll loop
3464 * will not wake-up to allow us to proceed further.
3466 status
= relay_process_control_receive_payload(conn
);
3473 * Process the commands received on the control socket
3475 static enum relay_connection_status
relay_process_control(
3476 struct relay_connection
*conn
)
3478 enum relay_connection_status status
;
3480 switch (conn
->protocol
.ctrl
.state_id
) {
3481 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3482 status
= relay_process_control_receive_header(conn
);
3484 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3485 status
= relay_process_control_receive_payload(conn
);
3488 ERR("Unknown control connection protocol state encountered.");
3495 static enum relay_connection_status
relay_process_data_receive_header(
3496 struct relay_connection
*conn
)
3499 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3500 struct data_connection_state_receive_header
*state
=
3501 &conn
->protocol
.data
.state
.receive_header
;
3502 struct lttcomm_relayd_data_hdr header
;
3503 struct relay_stream
*stream
;
3505 LTTNG_ASSERT(state
->left_to_receive
!= 0);
3507 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3508 state
->header_reception_buffer
+ state
->received
,
3509 state
->left_to_receive
, MSG_DONTWAIT
);
3511 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3512 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3513 status
= RELAY_CONNECTION_STATUS_ERROR
;
3516 } else if (ret
== 0) {
3517 /* Orderly shutdown. Not necessary to print an error. */
3518 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3519 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3523 LTTNG_ASSERT(ret
> 0);
3524 LTTNG_ASSERT(ret
<= state
->left_to_receive
);
3526 state
->left_to_receive
-= ret
;
3527 state
->received
+= ret
;
3529 if (state
->left_to_receive
> 0) {
3531 * Can't transition to the protocol's next state, wait to
3532 * receive the rest of the header.
3534 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3535 state
->received
, state
->left_to_receive
,
3540 /* Transition to next state: receiving the payload. */
3541 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3543 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3544 header
.circuit_id
= be64toh(header
.circuit_id
);
3545 header
.stream_id
= be64toh(header
.stream_id
);
3546 header
.data_size
= be32toh(header
.data_size
);
3547 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3548 header
.padding_size
= be32toh(header
.padding_size
);
3549 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3551 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3553 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3554 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3556 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3557 conn
->sock
->fd
, header
.circuit_id
,
3558 header
.stream_id
, header
.data_size
,
3559 header
.net_seq_num
, header
.padding_size
);
3561 stream
= stream_get_by_id(header
.stream_id
);
3563 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3565 /* Protocol error. */
3566 status
= RELAY_CONNECTION_STATUS_ERROR
;
3570 pthread_mutex_lock(&stream
->lock
);
3571 /* Prepare stream for the reception of a new packet. */
3572 ret
= stream_init_packet(stream
, header
.data_size
,
3573 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3574 pthread_mutex_unlock(&stream
->lock
);
3576 ERR("Failed to rotate stream output file");
3577 status
= RELAY_CONNECTION_STATUS_ERROR
;
3578 goto end_stream_unlock
;
3587 static enum relay_connection_status
relay_process_data_receive_payload(
3588 struct relay_connection
*conn
)
3591 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3592 struct relay_stream
*stream
;
3593 struct data_connection_state_receive_payload
*state
=
3594 &conn
->protocol
.data
.state
.receive_payload
;
3595 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3596 char data_buffer
[chunk_size
];
3597 bool partial_recv
= false;
3598 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3599 uint64_t left_to_receive
= state
->left_to_receive
;
3600 struct relay_session
*session
;
3602 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3603 state
->header
.stream_id
, state
->header
.net_seq_num
,
3604 state
->received
, left_to_receive
);
3606 stream
= stream_get_by_id(state
->header
.stream_id
);
3608 /* Protocol error. */
3609 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3610 state
->header
.stream_id
);
3611 status
= RELAY_CONNECTION_STATUS_ERROR
;
3615 pthread_mutex_lock(&stream
->lock
);
3616 session
= stream
->trace
->session
;
3617 if (!conn
->session
) {
3618 ret
= connection_set_session(conn
, session
);
3620 status
= RELAY_CONNECTION_STATUS_ERROR
;
3621 goto end_stream_unlock
;
3626 * The size of the "chunk" received on any iteration is bounded by:
3627 * - the data left to receive,
3628 * - the data immediately available on the socket,
3629 * - the on-stack data buffer
3631 while (left_to_receive
> 0 && !partial_recv
) {
3632 size_t recv_size
= std::min(left_to_receive
, chunk_size
);
3633 struct lttng_buffer_view packet_chunk
;
3635 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3636 recv_size
, MSG_DONTWAIT
);
3638 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3639 PERROR("Socket %d error", conn
->sock
->fd
);
3640 status
= RELAY_CONNECTION_STATUS_ERROR
;
3642 goto end_stream_unlock
;
3643 } else if (ret
== 0) {
3644 /* No more data ready to be consumed on socket. */
3645 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3646 state
->header
.stream_id
);
3647 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3649 } else if (ret
< (int) recv_size
) {
3651 * All the data available on the socket has been
3654 partial_recv
= true;
3658 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3660 LTTNG_ASSERT(packet_chunk
.data
);
3662 ret
= stream_write(stream
, &packet_chunk
, 0);
3664 ERR("Relay error writing data to file");
3665 status
= RELAY_CONNECTION_STATUS_ERROR
;
3666 goto end_stream_unlock
;
3669 left_to_receive
-= recv_size
;
3670 state
->received
+= recv_size
;
3671 state
->left_to_receive
= left_to_receive
;
3674 if (state
->left_to_receive
> 0) {
3676 * Did not receive all the data expected, wait for more data to
3677 * become available on the socket.
3679 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3680 state
->header
.stream_id
, state
->received
,
3681 state
->left_to_receive
);
3682 goto end_stream_unlock
;
3685 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3687 status
= RELAY_CONNECTION_STATUS_ERROR
;
3688 goto end_stream_unlock
;
3691 if (session_streams_have_index(session
)) {
3692 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3693 state
->rotate_index
, &index_flushed
,
3694 state
->header
.data_size
+ state
->header
.padding_size
);
3696 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3697 stream
->stream_handle
,
3698 state
->header
.net_seq_num
, ret
);
3699 status
= RELAY_CONNECTION_STATUS_ERROR
;
3700 goto end_stream_unlock
;
3704 if (stream
->prev_data_seq
== -1ULL) {
3708 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3709 state
->header
.padding_size
, state
->header
.net_seq_num
,
3712 status
= RELAY_CONNECTION_STATUS_ERROR
;
3713 goto end_stream_unlock
;
3717 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3718 * contents of *state which are aliased (union) to the same location as
3719 * the new state. Don't use it beyond this point.
3721 connection_reset_protocol_state(conn
);
3725 close_requested
= stream
->close_requested
;
3726 pthread_mutex_unlock(&stream
->lock
);
3727 if (close_requested
&& left_to_receive
== 0) {
3728 try_stream_close(stream
);
3732 pthread_mutex_lock(&session
->lock
);
3733 uatomic_set(&session
->new_streams
, 1);
3734 pthread_mutex_unlock(&session
->lock
);
3743 * relay_process_data: Process the data received on the data socket
3745 static enum relay_connection_status
relay_process_data(
3746 struct relay_connection
*conn
)
3748 enum relay_connection_status status
;
3750 switch (conn
->protocol
.data
.state_id
) {
3751 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3752 status
= relay_process_data_receive_header(conn
);
3754 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3755 status
= relay_process_data_receive_payload(conn
);
3758 ERR("Unexpected data connection communication state.");
3765 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3769 (void) lttng_poll_del(events
, pollfd
);
3771 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3772 fd_tracker_util_close_fd
, NULL
);
3774 ERR("Closing pollfd %d", pollfd
);
3778 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3779 int pollfd
, struct relay_connection
*conn
)
3781 const char *type_str
;
3783 switch (conn
->type
) {
3788 type_str
= "Control";
3790 case RELAY_VIEWER_COMMAND
:
3791 type_str
= "Viewer Command";
3793 case RELAY_VIEWER_NOTIFICATION
:
3794 type_str
= "Viewer Notification";
3797 type_str
= "Unknown";
3799 cleanup_connection_pollfd(events
, pollfd
);
3800 connection_put(conn
);
3801 DBG("%s connection closed with %d", type_str
, pollfd
);
3805 * This thread does the actual work
3807 static void *relay_thread_worker(void *data
)
3809 int ret
, err
= -1, last_seen_data_fd
= -1;
3811 struct lttng_poll_event events
;
3812 struct lttng_ht
*relay_connections_ht
;
3813 struct lttng_ht_iter iter
;
3814 struct relay_connection
*destroy_conn
= NULL
;
3816 DBG("[thread] Relay worker started");
3818 rcu_register_thread();
3820 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3822 if (testpoint(relayd_thread_worker
)) {
3823 goto error_testpoint
;
3826 health_code_update();
3828 /* table of connections indexed on socket */
3829 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3830 if (!relay_connections_ht
) {
3831 goto relay_connections_ht_error
;
3834 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3836 goto error_poll_create
;
3839 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3846 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3848 health_code_update();
3850 /* Infinite blocking call, waiting for transmission */
3851 DBG3("Relayd worker thread polling...");
3852 health_poll_entry();
3853 ret
= lttng_poll_wait(&events
, -1);
3857 * Restart interrupted system call.
3859 if (errno
== EINTR
) {
3868 * Process control. The control connection is
3869 * prioritized so we don't starve it with high
3870 * throughput tracing data on the data connection.
3872 for (i
= 0; i
< nb_fd
; i
++) {
3873 /* Fetch once the poll data */
3874 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3875 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3877 health_code_update();
3879 /* Thread quit pipe has been closed. Killing thread. */
3880 ret
= check_thread_quit_pipe(pollfd
, revents
);
3886 /* Inspect the relay conn pipe for new connection */
3887 if (pollfd
== relay_conn_pipe
[0]) {
3888 if (revents
& LPOLLIN
) {
3889 struct relay_connection
*conn
;
3891 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3895 ret
= lttng_poll_add(&events
,
3897 LPOLLIN
| LPOLLRDHUP
);
3899 ERR("Failed to add new connection file descriptor to poll set");
3902 connection_ht_add(relay_connections_ht
, conn
);
3903 DBG("Connection socket %d added", conn
->sock
->fd
);
3904 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3905 ERR("Relay connection pipe error");
3908 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3912 struct relay_connection
*ctrl_conn
;
3914 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3915 /* If not found, there is a synchronization issue. */
3916 LTTNG_ASSERT(ctrl_conn
);
3918 if (ctrl_conn
->type
== RELAY_DATA
) {
3919 if (revents
& LPOLLIN
) {
3921 * Flag the last seen data fd not deleted. It will be
3922 * used as the last seen fd if any fd gets deleted in
3925 last_notdel_data_fd
= pollfd
;
3927 goto put_ctrl_connection
;
3929 LTTNG_ASSERT(ctrl_conn
->type
== RELAY_CONTROL
);
3931 if (revents
& LPOLLIN
) {
3932 enum relay_connection_status status
;
3934 status
= relay_process_control(ctrl_conn
);
3935 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3937 * On socket error flag the session as aborted to force
3938 * the cleanup of its stream otherwise it can leak
3939 * during the lifetime of the relayd.
3941 * This prevents situations in which streams can be
3942 * left opened because an index was received, the
3943 * control connection is closed, and the data
3944 * connection is closed (uncleanly) before the packet's
3947 * Since the control connection encountered an error,
3948 * it is okay to be conservative and close the
3949 * session right now as we can't rely on the protocol
3950 * being respected anymore.
3952 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3953 session_abort(ctrl_conn
->session
);
3956 /* Clear the connection on error or close. */
3957 relay_thread_close_connection(&events
,
3962 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3963 relay_thread_close_connection(&events
,
3965 if (last_seen_data_fd
== pollfd
) {
3966 last_seen_data_fd
= last_notdel_data_fd
;
3969 ERR("Unexpected poll events %u for control sock %d",
3971 connection_put(ctrl_conn
);
3974 put_ctrl_connection
:
3975 connection_put(ctrl_conn
);
3980 * The last loop handled a control request, go back to poll to make
3981 * sure we prioritise the control socket.
3987 if (last_seen_data_fd
>= 0) {
3988 for (i
= 0; i
< nb_fd
; i
++) {
3989 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3991 health_code_update();
3993 if (last_seen_data_fd
== pollfd
) {
4000 /* Process data connection. */
4001 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
4002 /* Fetch the poll data. */
4003 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
4004 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
4005 struct relay_connection
*data_conn
;
4007 health_code_update();
4010 /* No activity for this FD (poll implementation). */
4014 /* Skip the command pipe. It's handled in the first loop. */
4015 if (pollfd
== relay_conn_pipe
[0]) {
4019 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
4021 /* Skip it. Might be removed before. */
4024 if (data_conn
->type
== RELAY_CONTROL
) {
4025 goto put_data_connection
;
4027 LTTNG_ASSERT(data_conn
->type
== RELAY_DATA
);
4029 if (revents
& LPOLLIN
) {
4030 enum relay_connection_status status
;
4032 status
= relay_process_data(data_conn
);
4033 /* Connection closed or error. */
4034 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4036 * On socket error flag the session as aborted to force
4037 * the cleanup of its stream otherwise it can leak
4038 * during the lifetime of the relayd.
4040 * This prevents situations in which streams can be
4041 * left opened because an index was received, the
4042 * control connection is closed, and the data
4043 * connection is closed (uncleanly) before the packet's
4046 * Since the data connection encountered an error,
4047 * it is okay to be conservative and close the
4048 * session right now as we can't rely on the protocol
4049 * being respected anymore.
4051 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4052 session_abort(data_conn
->session
);
4054 relay_thread_close_connection(&events
, pollfd
,
4057 * Every goto restart call sets the last seen fd where
4058 * here we don't really care since we gracefully
4059 * continue the loop after the connection is deleted.
4062 /* Keep last seen port. */
4063 last_seen_data_fd
= pollfd
;
4064 connection_put(data_conn
);
4067 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4068 relay_thread_close_connection(&events
, pollfd
,
4071 ERR("Unknown poll events %u for data sock %d",
4074 put_data_connection
:
4075 connection_put(data_conn
);
4077 last_seen_data_fd
= -1;
4080 /* Normal exit, no error */
4085 /* Cleanup remaining connection object. */
4087 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4090 health_code_update();
4092 session_abort(destroy_conn
->session
);
4095 * No need to grab another ref, because we own
4098 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4103 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4105 lttng_ht_destroy(relay_connections_ht
);
4106 relay_connections_ht_error
:
4107 /* Close relay conn pipes */
4108 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4111 DBG("Thread exited with error");
4113 DBG("Worker thread cleanup complete");
4117 ERR("Health error occurred in %s", __func__
);
4119 health_unregister(health_relayd
);
4120 rcu_unregister_thread();
4121 lttng_relay_stop_threads();
4126 * Create the relay command pipe to wake thread_manage_apps.
4127 * Closed in cleanup().
4129 static int create_relay_conn_pipe(void)
4131 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4132 "Relayd connection pipe", relay_conn_pipe
);
4135 static int stdio_open(void *data
, int *fds
)
4137 fds
[0] = fileno(stdout
);
4138 fds
[1] = fileno(stderr
);
4142 static int track_stdio(void)
4145 const char *names
[] = { "stdout", "stderr" };
4147 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4148 names
, 2, stdio_open
, NULL
);
4154 int main(int argc
, char **argv
)
4156 bool thread_is_rcu_registered
= false;
4157 int ret
= 0, retval
= 0;
4159 char *unlinked_file_directory_path
= NULL
, *output_path
= NULL
;
4161 /* Parse environment variables */
4162 ret
= parse_env_options();
4170 * Command line arguments overwrite environment.
4173 if (set_options(argc
, argv
)) {
4178 if (set_signal_handler()) {
4183 relayd_config_log();
4185 if (opt_print_version
) {
4191 ret
= fclose(stdin
);
4193 PERROR("Failed to close stdin");
4197 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4199 /* Try to create directory if -o, --output is specified. */
4200 if (opt_output_path
) {
4201 if (*opt_output_path
!= '/') {
4202 ERR("Please specify an absolute path for -o, --output PATH");
4207 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4210 ERR("Unable to create %s", opt_output_path
);
4217 if (opt_daemon
|| opt_background
) {
4218 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4226 if (opt_working_directory
) {
4227 ret
= utils_change_working_directory(opt_working_directory
);
4229 /* All errors are already logged. */
4234 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4235 if (!sessiond_trace_chunk_registry
) {
4236 ERR("Failed to initialize session daemon trace chunk registry");
4242 * The RCU thread registration (and use, through the fd-tracker's
4243 * creation) is done after the daemonization to allow us to not
4244 * deal with liburcu's fork() management as the call RCU needs to
4247 rcu_register_thread();
4248 thread_is_rcu_registered
= true;
4250 output_path
= create_output_path("");
4252 ERR("Failed to get output path");
4256 ret
= asprintf(&unlinked_file_directory_path
, "%s/%s", output_path
,
4257 DEFAULT_UNLINKED_FILES_DIRECTORY
);
4260 ERR("Failed to format unlinked file directory path");
4264 the_fd_tracker
= fd_tracker_create(
4265 unlinked_file_directory_path
, lttng_opt_fd_pool_size
);
4266 free(unlinked_file_directory_path
);
4267 if (!the_fd_tracker
) {
4272 ret
= track_stdio();
4278 /* Initialize thread health monitoring */
4279 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4280 if (!health_relayd
) {
4281 PERROR("health_app_create error");
4286 /* Create thread quit pipe */
4287 if (init_thread_quit_pipe()) {
4292 /* Setup the thread apps communication pipe. */
4293 if (create_relay_conn_pipe()) {
4298 /* Init relay command queue. */
4299 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4301 /* Initialize communication library */
4303 lttcomm_inet_init();
4305 /* tables of sessions indexed by session ID */
4306 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4312 /* tables of streams indexed by stream ID */
4313 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4314 if (!relay_streams_ht
) {
4319 /* tables of streams indexed by stream ID */
4320 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4321 if (!viewer_streams_ht
) {
4326 ret
= init_health_quit_pipe();
4332 /* Create thread to manage the client socket */
4333 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4334 thread_manage_health
, (void *) NULL
);
4337 PERROR("pthread_create health");
4342 /* Setup the dispatcher thread */
4343 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4344 relay_thread_dispatcher
, (void *) NULL
);
4347 PERROR("pthread_create dispatcher");
4349 goto exit_dispatcher_thread
;
4352 /* Setup the worker thread */
4353 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4354 relay_thread_worker
, NULL
);
4357 PERROR("pthread_create worker");
4359 goto exit_worker_thread
;
4362 /* Setup the listener thread */
4363 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4364 relay_thread_listener
, (void *) NULL
);
4367 PERROR("pthread_create listener");
4369 goto exit_listener_thread
;
4372 ret
= relayd_live_create(live_uri
);
4374 ERR("Starting live viewer threads");
4380 * This is where we start awaiting program completion (e.g. through
4381 * signal that asks threads to teardown).
4384 ret
= relayd_live_join();
4390 ret
= pthread_join(listener_thread
, &status
);
4393 PERROR("pthread_join listener_thread");
4397 exit_listener_thread
:
4398 ret
= pthread_join(worker_thread
, &status
);
4401 PERROR("pthread_join worker_thread");
4406 ret
= pthread_join(dispatcher_thread
, &status
);
4409 PERROR("pthread_join dispatcher_thread");
4412 exit_dispatcher_thread
:
4414 ret
= pthread_join(health_thread
, &status
);
4417 PERROR("pthread_join health_thread");
4422 * Wait for all pending call_rcu work to complete before tearing
4423 * down data structures. call_rcu worker may be trying to
4424 * perform lookups in those structures.
4429 /* Ensure all prior call_rcu are done. */
4432 if (thread_is_rcu_registered
) {
4433 rcu_unregister_thread();