2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
37 #include <sys/resource.h>
39 #include <urcu/futex.h>
40 #include <urcu/uatomic.h>
41 #include <urcu/rculist.h>
47 #include <lttng/lttng.h>
48 #include <common/common.h>
49 #include <common/compat/poll.h>
50 #include <common/compat/socket.h>
51 #include <common/compat/endian.h>
52 #include <common/compat/getenv.h>
53 #include <common/defaults.h>
54 #include <common/daemonize.h>
55 #include <common/futex.h>
56 #include <common/sessiond-comm/sessiond-comm.h>
57 #include <common/sessiond-comm/inet.h>
58 #include <common/sessiond-comm/relayd.h>
59 #include <common/uri.h>
60 #include <common/utils.h>
61 #include <common/align.h>
62 #include <common/config/session-config.h>
63 #include <common/dynamic-buffer.h>
64 #include <common/buffer-view.h>
65 #include <common/string-utils/format.h>
67 #include "backward-compatibility-group-by.h"
69 #include "connection.h"
70 #include "ctf-trace.h"
71 #include "health-relayd.h"
74 #include "lttng-relayd.h"
76 #include "sessiond-trace-chunks.h"
78 #include "tcp_keep_alive.h"
79 #include "testpoint.h"
80 #include "tracefile-array.h"
83 #include "viewer-stream.h"
85 static const char *help_msg
=
86 #ifdef LTTNG_EMBED_HELP
87 #include <lttng-relayd.8.h>
93 enum relay_connection_status
{
94 RELAY_CONNECTION_STATUS_OK
,
95 /* An error occurred while processing an event on the connection. */
96 RELAY_CONNECTION_STATUS_ERROR
,
97 /* Connection closed/shutdown cleanly. */
98 RELAY_CONNECTION_STATUS_CLOSED
,
101 /* command line options */
102 char *opt_output_path
, *opt_working_directory
;
103 static int opt_daemon
, opt_background
, opt_print_version
, opt_allow_clear
= 1;
104 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
107 * We need to wait for listener and live listener threads, as well as
108 * health check thread, before being ready to signal readiness.
110 #define NR_LTTNG_RELAY_READY 3
111 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
113 /* Size of receive buffer. */
114 #define RECV_DATA_BUFFER_SIZE 65536
116 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
117 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
119 static struct lttng_uri
*control_uri
;
120 static struct lttng_uri
*data_uri
;
121 static struct lttng_uri
*live_uri
;
123 const char *progname
;
125 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
126 static int tracing_group_name_override
;
128 const char * const config_section_name
= "relayd";
131 * Quit pipe for all threads. This permits a single cancellation point
132 * for all threads when receiving an event on the pipe.
134 int thread_quit_pipe
[2] = { -1, -1 };
137 * This pipe is used to inform the worker thread that a command is queued and
138 * ready to be processed.
140 static int relay_conn_pipe
[2] = { -1, -1 };
142 /* Shared between threads */
143 static int dispatch_thread_exit
;
145 static pthread_t listener_thread
;
146 static pthread_t dispatcher_thread
;
147 static pthread_t worker_thread
;
148 static pthread_t health_thread
;
151 * last_relay_stream_id_lock protects last_relay_stream_id increment
152 * atomicity on 32-bit architectures.
154 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
155 static uint64_t last_relay_stream_id
;
158 * Relay command queue.
160 * The relay_thread_listener and relay_thread_dispatcher communicate with this
163 static struct relay_conn_queue relay_conn_queue
;
165 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
166 static unsigned int lttng_opt_fd_cap
;
168 /* Global relay stream hash table. */
169 struct lttng_ht
*relay_streams_ht
;
171 /* Global relay viewer stream hash table. */
172 struct lttng_ht
*viewer_streams_ht
;
174 /* Global relay sessions hash table. */
175 struct lttng_ht
*sessions_ht
;
177 /* Relayd health monitoring */
178 struct health_app
*health_relayd
;
180 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
182 static struct option long_options
[] = {
183 { "control-port", 1, 0, 'C', },
184 { "data-port", 1, 0, 'D', },
185 { "live-port", 1, 0, 'L', },
186 { "daemonize", 0, 0, 'd', },
187 { "background", 0, 0, 'b', },
188 { "group", 1, 0, 'g', },
189 { "fd-cap", 1, 0, '\0', },
190 { "help", 0, 0, 'h', },
191 { "output", 1, 0, 'o', },
192 { "verbose", 0, 0, 'v', },
193 { "config", 1, 0, 'f' },
194 { "version", 0, 0, 'V' },
195 { "working-directory", 1, 0, 'w', },
196 { "group-output-by-session", 0, 0, 's', },
197 { "group-output-by-host", 0, 0, 'p', },
198 { "disallow-clear", 0, 0, 'x' },
202 static const char *config_ignore_options
[] = { "help", "config", "version" };
204 static void print_version(void) {
205 fprintf(stdout
, "%s\n", VERSION
);
208 static void relayd_config_log(void)
210 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
211 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
212 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
213 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
214 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
216 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
217 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
222 * Take an option from the getopt output and set it in the right variable to be
225 * Return 0 on success else a negative value.
227 static int set_option(int opt
, const char *arg
, const char *optname
)
233 if (!strcmp(optname
, "fd-cap")) {
237 v
= strtoul(arg
, NULL
, 0);
238 if (errno
!= 0 || !isdigit(arg
[0])) {
239 ERR("Wrong value in --fd-cap parameter: %s",
244 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
245 ERR("File descriptor cap must be set to at least %d",
246 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
249 ERR("File descriptor cap overflow in --fd-cap parameter: %s",
254 lttng_opt_fd_cap
= (unsigned int) v
;
255 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
257 fprintf(stderr
, "unknown option %s", optname
);
259 fprintf(stderr
, " with arg %s\n", arg
);
264 if (lttng_is_setuid_setgid()) {
265 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
266 "-C, --control-port");
268 ret
= uri_parse(arg
, &control_uri
);
270 ERR("Invalid control URI specified");
273 if (control_uri
->port
== 0) {
274 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
279 if (lttng_is_setuid_setgid()) {
280 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
283 ret
= uri_parse(arg
, &data_uri
);
285 ERR("Invalid data URI specified");
288 if (data_uri
->port
== 0) {
289 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
294 if (lttng_is_setuid_setgid()) {
295 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
298 ret
= uri_parse(arg
, &live_uri
);
300 ERR("Invalid live URI specified");
303 if (live_uri
->port
== 0) {
304 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
315 if (lttng_is_setuid_setgid()) {
316 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
319 tracing_group_name
= strdup(arg
);
320 if (tracing_group_name
== NULL
) {
325 tracing_group_name_override
= 1;
329 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
331 ERR("Cannot show --help for `lttng-relayd`");
336 opt_print_version
= 1;
339 if (lttng_is_setuid_setgid()) {
340 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
343 ret
= asprintf(&opt_output_path
, "%s", arg
);
346 PERROR("asprintf opt_output_path");
352 if (lttng_is_setuid_setgid()) {
353 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
354 "-w, --working-directory");
356 ret
= asprintf(&opt_working_directory
, "%s", arg
);
359 PERROR("asprintf opt_working_directory");
366 /* Verbose level can increase using multiple -v */
368 lttng_opt_verbose
= config_parse_value(arg
);
370 /* Only 3 level of verbosity (-vvv). */
371 if (lttng_opt_verbose
< 3) {
372 lttng_opt_verbose
+= 1;
377 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
378 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
381 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
384 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
385 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
388 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
395 /* Unknown option or other error.
396 * Error is printed by getopt, just return */
409 * config_entry_handler_cb used to handle options read from a config file.
410 * See config_entry_handler_cb comment in common/config/session-config.h for the
411 * return value conventions.
413 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
417 if (!entry
|| !entry
->name
|| !entry
->value
) {
422 /* Check if the option is to be ignored */
423 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
424 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
429 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
430 /* Ignore if entry name is not fully matched. */
431 if (strcmp(entry
->name
, long_options
[i
].name
)) {
436 * If the option takes no argument on the command line,
437 * we have to check if the value is "true". We support
438 * non-zero numeric values, true, on and yes.
440 if (!long_options
[i
].has_arg
) {
441 ret
= config_parse_value(entry
->value
);
444 WARN("Invalid configuration value \"%s\" for option %s",
445 entry
->value
, entry
->name
);
447 /* False, skip boolean config option. */
452 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
456 WARN("Unrecognized option \"%s\" in daemon configuration file.",
463 static int parse_env_options(void)
468 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
470 opt_working_directory
= strdup(value
);
471 if (!opt_working_directory
) {
472 ERR("Failed to allocate working directory string (\"%s\")",
480 static int set_options(int argc
, char **argv
)
482 int c
, ret
= 0, option_index
= 0, retval
= 0;
483 int orig_optopt
= optopt
, orig_optind
= optind
;
484 char *default_address
, *optstring
;
485 const char *config_path
= NULL
;
487 optstring
= utils_generate_optstring(long_options
,
488 sizeof(long_options
) / sizeof(struct option
));
494 /* Check for the --config option */
496 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
497 &option_index
)) != -1) {
501 } else if (c
!= 'f') {
505 if (lttng_is_setuid_setgid()) {
506 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
509 config_path
= utils_expand_path(optarg
);
511 ERR("Failed to resolve path: %s", optarg
);
516 ret
= config_get_section_entries(config_path
, config_section_name
,
517 config_entry_handler
, NULL
);
520 ERR("Invalid configuration option at line %i", ret
);
526 /* Reset getopt's global state */
527 optopt
= orig_optopt
;
528 optind
= orig_optind
;
530 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
535 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
542 /* assign default values */
543 if (control_uri
== NULL
) {
544 ret
= asprintf(&default_address
,
545 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
546 DEFAULT_NETWORK_CONTROL_PORT
);
548 PERROR("asprintf default data address");
553 ret
= uri_parse(default_address
, &control_uri
);
554 free(default_address
);
556 ERR("Invalid control URI specified");
561 if (data_uri
== NULL
) {
562 ret
= asprintf(&default_address
,
563 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
564 DEFAULT_NETWORK_DATA_PORT
);
566 PERROR("asprintf default data address");
571 ret
= uri_parse(default_address
, &data_uri
);
572 free(default_address
);
574 ERR("Invalid data URI specified");
579 if (live_uri
== NULL
) {
580 ret
= asprintf(&default_address
,
581 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
582 DEFAULT_NETWORK_VIEWER_PORT
);
584 PERROR("asprintf default viewer control address");
589 ret
= uri_parse(default_address
, &live_uri
);
590 free(default_address
);
592 ERR("Invalid viewer control URI specified");
597 if (lttng_opt_fd_cap
== 0) {
599 struct rlimit rlimit
;
601 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
603 PERROR("Failed to get file descriptor limit");
607 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
610 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
611 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
613 if (opt_allow_clear
) {
614 /* Check if env variable exists. */
615 const char *value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
617 ret
= config_parse_value(value
);
619 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
623 opt_allow_clear
= !ret
;
632 static void print_global_objects(void)
634 rcu_register_thread();
636 print_viewer_streams();
637 print_relay_streams();
640 rcu_unregister_thread();
646 static void relayd_cleanup(void)
648 print_global_objects();
652 if (viewer_streams_ht
)
653 lttng_ht_destroy(viewer_streams_ht
);
654 if (relay_streams_ht
)
655 lttng_ht_destroy(relay_streams_ht
);
657 lttng_ht_destroy(sessions_ht
);
659 free(opt_output_path
);
660 free(opt_working_directory
);
663 health_app_destroy(health_relayd
);
665 /* Close thread quit pipes */
666 utils_close_pipe(health_quit_pipe
);
667 utils_close_pipe(thread_quit_pipe
);
669 if (sessiond_trace_chunk_registry
) {
670 sessiond_trace_chunk_registry_destroy(
671 sessiond_trace_chunk_registry
);
674 uri_free(control_uri
);
676 /* Live URI is freed in the live thread. */
678 if (tracing_group_name_override
) {
679 free((void *) tracing_group_name
);
684 * Write to writable pipe used to notify a thread.
686 static int notify_thread_pipe(int wpipe
)
690 ret
= lttng_write(wpipe
, "!", 1);
692 PERROR("write poll pipe");
700 static int notify_health_quit_pipe(int *pipe
)
704 ret
= lttng_write(pipe
[1], "4", 1);
706 PERROR("write relay health quit");
715 * Stop all relayd and relayd-live threads.
717 int lttng_relay_stop_threads(void)
721 /* Stopping all threads */
722 DBG("Terminating all threads");
723 if (notify_thread_pipe(thread_quit_pipe
[1])) {
724 ERR("write error on thread quit pipe");
728 if (notify_health_quit_pipe(health_quit_pipe
)) {
729 ERR("write error on health quit pipe");
732 /* Dispatch thread */
733 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
734 futex_nto1_wake(&relay_conn_queue
.futex
);
736 if (relayd_live_stop()) {
737 ERR("Error stopping live threads");
744 * Signal handler for the daemon
746 * Simply stop all worker threads, leaving main() return gracefully after
747 * joining all threads and calling cleanup().
749 static void sighandler(int sig
)
753 DBG("SIGINT caught");
754 if (lttng_relay_stop_threads()) {
755 ERR("Error stopping threads");
759 DBG("SIGTERM caught");
760 if (lttng_relay_stop_threads()) {
761 ERR("Error stopping threads");
765 CMM_STORE_SHARED(recv_child_signal
, 1);
773 * Setup signal handler for :
774 * SIGINT, SIGTERM, SIGPIPE
776 static int set_signal_handler(void)
782 if ((ret
= sigemptyset(&sigset
)) < 0) {
783 PERROR("sigemptyset");
790 sa
.sa_handler
= sighandler
;
791 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
796 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
801 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
806 sa
.sa_handler
= SIG_IGN
;
807 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
812 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
817 void lttng_relay_notify_ready(void)
819 /* Notify the parent of the fork() process that we are ready. */
820 if (opt_daemon
|| opt_background
) {
821 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
822 kill(child_ppid
, SIGUSR1
);
828 * Init thread quit pipe.
830 * Return -1 on error or 0 if all pipes are created.
832 static int init_thread_quit_pipe(void)
836 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
842 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
844 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
848 if (events
== NULL
|| size
== 0) {
853 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
859 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
871 * Check if the thread quit pipe was triggered.
873 * Return 1 if it was triggered else 0;
875 static int check_thread_quit_pipe(int fd
, uint32_t events
)
877 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
885 * Create and init socket from uri.
887 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
890 struct lttcomm_sock
*sock
= NULL
;
892 sock
= lttcomm_alloc_sock_from_uri(uri
);
894 ERR("Allocating socket");
898 ret
= lttcomm_create_sock(sock
);
902 DBG("Listening on sock %d", sock
->fd
);
904 ret
= sock
->ops
->bind(sock
);
906 PERROR("Failed to bind socket");
910 ret
= sock
->ops
->listen(sock
, -1);
920 lttcomm_destroy_sock(sock
);
926 * This thread manages the listening for new connections on the network
928 static void *relay_thread_listener(void *data
)
930 int i
, ret
, pollfd
, err
= -1;
931 uint32_t revents
, nb_fd
;
932 struct lttng_poll_event events
;
933 struct lttcomm_sock
*control_sock
, *data_sock
;
935 DBG("[thread] Relay listener started");
937 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
939 health_code_update();
941 control_sock
= relay_socket_create(control_uri
);
943 goto error_sock_control
;
946 data_sock
= relay_socket_create(data_uri
);
948 goto error_sock_relay
;
952 * Pass 3 as size here for the thread quit pipe, control and
955 ret
= create_thread_poll_set(&events
, 3);
957 goto error_create_poll
;
960 /* Add the control socket */
961 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
966 /* Add the data socket */
967 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
972 lttng_relay_notify_ready();
974 if (testpoint(relayd_thread_listener
)) {
975 goto error_testpoint
;
979 health_code_update();
981 DBG("Listener accepting connections");
985 ret
= lttng_poll_wait(&events
, -1);
989 * Restart interrupted system call.
991 if (errno
== EINTR
) {
999 DBG("Relay new connection received");
1000 for (i
= 0; i
< nb_fd
; i
++) {
1001 health_code_update();
1003 /* Fetch once the poll data */
1004 revents
= LTTNG_POLL_GETEV(&events
, i
);
1005 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1007 /* Thread quit pipe has been closed. Killing thread. */
1008 ret
= check_thread_quit_pipe(pollfd
, revents
);
1014 if (revents
& LPOLLIN
) {
1016 * A new connection is requested, therefore a
1017 * sessiond/consumerd connection is allocated in
1018 * this thread, enqueued to a global queue and
1019 * dequeued (and freed) in the worker thread.
1022 struct relay_connection
*new_conn
;
1023 struct lttcomm_sock
*newsock
;
1024 enum connection_type type
;
1026 if (pollfd
== data_sock
->fd
) {
1028 newsock
= data_sock
->ops
->accept(data_sock
);
1029 DBG("Relay data connection accepted, socket %d",
1032 assert(pollfd
== control_sock
->fd
);
1033 type
= RELAY_CONTROL
;
1034 newsock
= control_sock
->ops
->accept(control_sock
);
1035 DBG("Relay control connection accepted, socket %d",
1039 PERROR("accepting sock");
1043 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1046 PERROR("setsockopt inet");
1047 lttcomm_destroy_sock(newsock
);
1051 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1053 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1055 lttcomm_destroy_sock(newsock
);
1059 new_conn
= connection_create(newsock
, type
);
1061 lttcomm_destroy_sock(newsock
);
1065 /* Enqueue request for the dispatcher thread. */
1066 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1070 * Wake the dispatch queue futex.
1071 * Implicit memory barrier with the
1072 * exchange in cds_wfcq_enqueue.
1074 futex_nto1_wake(&relay_conn_queue
.futex
);
1075 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1076 ERR("socket poll error");
1079 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1089 lttng_poll_clean(&events
);
1091 if (data_sock
->fd
>= 0) {
1092 ret
= data_sock
->ops
->close(data_sock
);
1097 lttcomm_destroy_sock(data_sock
);
1099 if (control_sock
->fd
>= 0) {
1100 ret
= control_sock
->ops
->close(control_sock
);
1105 lttcomm_destroy_sock(control_sock
);
1109 ERR("Health error occurred in %s", __func__
);
1111 health_unregister(health_relayd
);
1112 DBG("Relay listener thread cleanup complete");
1113 lttng_relay_stop_threads();
1118 * This thread manages the dispatching of the requests to worker threads
1120 static void *relay_thread_dispatcher(void *data
)
1124 struct cds_wfcq_node
*node
;
1125 struct relay_connection
*new_conn
= NULL
;
1127 DBG("[thread] Relay dispatcher started");
1129 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1131 if (testpoint(relayd_thread_dispatcher
)) {
1132 goto error_testpoint
;
1135 health_code_update();
1138 health_code_update();
1140 /* Atomically prepare the queue futex */
1141 futex_nto1_prepare(&relay_conn_queue
.futex
);
1143 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1148 health_code_update();
1150 /* Dequeue commands */
1151 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1152 &relay_conn_queue
.tail
);
1154 DBG("Woken up but nothing in the relay command queue");
1155 /* Continue thread execution */
1158 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1160 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1163 * Inform worker thread of the new request. This
1164 * call is blocking so we can be assured that
1165 * the data will be read at some point in time
1166 * or wait to the end of the world :)
1168 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1170 PERROR("write connection pipe");
1171 connection_put(new_conn
);
1174 } while (node
!= NULL
);
1176 /* Futex wait on queue. Blocking call on futex() */
1177 health_poll_entry();
1178 futex_nto1_wait(&relay_conn_queue
.futex
);
1182 /* Normal exit, no error */
1189 ERR("Health error occurred in %s", __func__
);
1191 health_unregister(health_relayd
);
1192 DBG("Dispatch thread dying");
1193 lttng_relay_stop_threads();
1197 static bool session_streams_have_index(const struct relay_session
*session
)
1199 return session
->minor
>= 4 && !session
->snapshot
;
1203 * Handle the RELAYD_CREATE_SESSION command.
1205 * On success, send back the session id or else return a negative value.
1207 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1208 struct relay_connection
*conn
,
1209 const struct lttng_buffer_view
*payload
)
1213 struct relay_session
*session
= NULL
;
1214 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1215 char session_name
[LTTNG_NAME_MAX
] = {};
1216 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1217 uint32_t live_timer
= 0;
1218 bool snapshot
= false;
1219 bool session_name_contains_creation_timestamp
= false;
1220 /* Left nil for peers < 2.11. */
1221 char base_path
[LTTNG_PATH_MAX
] = {};
1222 lttng_uuid sessiond_uuid
= {};
1223 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1224 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1225 LTTNG_OPTIONAL(time_t) creation_time
= {};
1226 struct lttng_dynamic_buffer reply_payload
;
1228 lttng_dynamic_buffer_init(&reply_payload
);
1230 if (conn
->minor
< 4) {
1231 /* From 2.1 to 2.3 */
1233 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1234 /* From 2.4 to 2.10 */
1235 ret
= cmd_create_session_2_4(payload
, session_name
,
1236 hostname
, &live_timer
, &snapshot
);
1238 bool has_current_chunk
;
1239 uint64_t current_chunk_id_value
;
1240 time_t creation_time_value
;
1241 uint64_t id_sessiond_value
;
1243 /* From 2.11 to ... */
1244 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1245 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1246 sessiond_uuid
, &has_current_chunk
,
1247 ¤t_chunk_id_value
, &creation_time_value
,
1248 &session_name_contains_creation_timestamp
);
1249 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1250 /* The nil UUID is reserved for pre-2.11 clients. */
1251 ERR("Illegal nil UUID announced by peer in create session command");
1255 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1256 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1257 if (has_current_chunk
) {
1258 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1259 current_chunk_id_value
);
1267 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1268 snapshot
, sessiond_uuid
,
1269 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1270 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1271 creation_time
.is_set
? &creation_time
.value
: NULL
,
1272 conn
->major
, conn
->minor
,
1273 session_name_contains_creation_timestamp
);
1278 assert(!conn
->session
);
1279 conn
->session
= session
;
1280 DBG("Created session %" PRIu64
, session
->id
);
1282 reply
.generic
.session_id
= htobe64(session
->id
);
1286 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1288 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1291 if (conn
->minor
< 11) {
1292 /* From 2.1 to 2.10 */
1293 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1294 &reply
.generic
, sizeof(reply
.generic
));
1296 ERR("Failed to append \"create session\" command reply header to payload buffer");
1301 const uint32_t output_path_length
=
1302 session
? strlen(session
->output_path
) + 1 : 0;
1304 reply
.output_path_length
= htobe32(output_path_length
);
1305 ret
= lttng_dynamic_buffer_append(
1306 &reply_payload
, &reply
, sizeof(reply
));
1308 ERR("Failed to append \"create session\" command reply header to payload buffer");
1312 if (output_path_length
) {
1313 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1314 session
->output_path
,
1315 output_path_length
);
1317 ERR("Failed to append \"create session\" command reply path to payload buffer");
1323 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1324 reply_payload
.size
, 0);
1325 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1326 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1327 reply_payload
.size
, send_ret
);
1331 if (ret
< 0 && session
) {
1332 session_put(session
);
1334 lttng_dynamic_buffer_reset(&reply_payload
);
1339 * When we have received all the streams and the metadata for a channel,
1340 * we make them visible to the viewer threads.
1342 static void publish_connection_local_streams(struct relay_connection
*conn
)
1344 struct relay_stream
*stream
;
1345 struct relay_session
*session
= conn
->session
;
1348 * We publish all streams belonging to a session atomically wrt
1351 pthread_mutex_lock(&session
->lock
);
1353 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1355 stream_publish(stream
);
1360 * Inform the viewer that there are new streams in the session.
1362 if (session
->viewer_attached
) {
1363 uatomic_set(&session
->new_streams
, 1);
1365 pthread_mutex_unlock(&session
->lock
);
1368 static int conform_channel_path(char *channel_path
)
1372 if (strstr("../", channel_path
)) {
1373 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1379 if (*channel_path
== '/') {
1380 const size_t len
= strlen(channel_path
);
1383 * Channel paths from peers prior to 2.11 are expressed as an
1384 * absolute path that is, in reality, relative to the relay
1385 * daemon's output directory. Remove the leading slash so it
1386 * is correctly interpreted as a relative path later on.
1388 * len (and not len - 1) is used to copy the trailing NULL.
1390 bcopy(channel_path
+ 1, channel_path
, len
);
1397 * relay_add_stream: allocate a new stream for a session
1399 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1400 struct relay_connection
*conn
,
1401 const struct lttng_buffer_view
*payload
)
1405 struct relay_session
*session
= conn
->session
;
1406 struct relay_stream
*stream
= NULL
;
1407 struct lttcomm_relayd_status_stream reply
;
1408 struct ctf_trace
*trace
= NULL
;
1409 uint64_t stream_handle
= -1ULL;
1410 char *path_name
= NULL
, *channel_name
= NULL
;
1411 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1412 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1414 if (!session
|| !conn
->version_check_done
) {
1415 ERR("Trying to add a stream before version check");
1417 goto end_no_session
;
1420 if (session
->minor
== 1) {
1422 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1424 } else if (session
->minor
> 1 && session
->minor
< 11) {
1425 /* From 2.2 to 2.10 */
1426 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1427 &channel_name
, &tracefile_size
, &tracefile_count
);
1429 /* From 2.11 to ... */
1430 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1431 &channel_name
, &tracefile_size
, &tracefile_count
,
1432 &stream_chunk_id
.value
);
1433 stream_chunk_id
.is_set
= true;
1440 if (conform_channel_path(path_name
)) {
1445 * Backward compatibility for --group-output-by-session.
1446 * Prior to lttng 2.11, the complete path is passed by the stream.
1447 * Starting at 2.11, lttng-relayd uses chunk. When dealing with producer
1448 * >=2.11 the chunk is responsible for the output path. When dealing
1449 * with producer < 2.11 the chunk output_path is the root output path
1450 * and the stream carries the complete path (path_name).
1451 * To support --group-output-by-session with older producer (<2.11), we
1452 * need to craft the path based on the stream path.
1454 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_SESSION
) {
1455 if (conn
->minor
< 4) {
1457 * From 2.1 to 2.3, the session_name is not passed on
1458 * the RELAYD_CREATE_SESSION command. The session name
1459 * is necessary to detect the presence of a base_path
1460 * inside the stream path. Without it we cannot perform
1461 * a valid group-output-by-session transformation.
1463 WARN("Unable to perform a --group-by-session transformation for session %" PRIu64
1464 " for stream with path \"%s\" as it is produced by a peer using a protocol older than v2.4",
1465 session
->id
, path_name
);
1466 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1467 char *group_by_session_path_name
;
1469 assert(session
->session_name
[0] != '\0');
1471 group_by_session_path_name
=
1472 backward_compat_group_by_session(
1474 session
->session_name
);
1475 if (!group_by_session_path_name
) {
1476 ERR("Failed to apply group by session to stream of session %" PRIu64
,
1481 DBG("Transformed session path from \"%s\" to \"%s\" to honor per-session name grouping",
1482 path_name
, group_by_session_path_name
);
1485 path_name
= group_by_session_path_name
;
1489 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1494 /* This stream here has one reference on the trace. */
1495 pthread_mutex_lock(&last_relay_stream_id_lock
);
1496 stream_handle
= ++last_relay_stream_id
;
1497 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1499 /* We pass ownership of path_name and channel_name. */
1500 stream
= stream_create(trace
, stream_handle
, path_name
,
1501 channel_name
, tracefile_size
, tracefile_count
);
1503 channel_name
= NULL
;
1506 * Streams are the owners of their trace. Reference to trace is
1507 * kept within stream_create().
1509 ctf_trace_put(trace
);
1512 memset(&reply
, 0, sizeof(reply
));
1513 reply
.handle
= htobe64(stream_handle
);
1515 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1517 reply
.ret_code
= htobe32(LTTNG_OK
);
1520 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1521 sizeof(struct lttcomm_relayd_status_stream
), 0);
1522 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1523 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1535 * relay_close_stream: close a specific stream
1537 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1538 struct relay_connection
*conn
,
1539 const struct lttng_buffer_view
*payload
)
1543 struct relay_session
*session
= conn
->session
;
1544 struct lttcomm_relayd_close_stream stream_info
;
1545 struct lttcomm_relayd_generic_reply reply
;
1546 struct relay_stream
*stream
;
1548 DBG("Close stream received");
1550 if (!session
|| !conn
->version_check_done
) {
1551 ERR("Trying to close a stream before version check");
1553 goto end_no_session
;
1556 if (payload
->size
< sizeof(stream_info
)) {
1557 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1558 sizeof(stream_info
), payload
->size
);
1560 goto end_no_session
;
1562 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1563 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1564 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1566 stream
= stream_get_by_id(stream_info
.stream_id
);
1573 * Set last_net_seq_num before the close flag. Required by data
1576 pthread_mutex_lock(&stream
->lock
);
1577 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1578 pthread_mutex_unlock(&stream
->lock
);
1581 * This is one of the conditions which may trigger a stream close
1582 * with the others being:
1583 * 1) A close command is received for a stream
1584 * 2) The control connection owning the stream is closed
1585 * 3) We have received all of the stream's data _after_ a close
1588 try_stream_close(stream
);
1589 if (stream
->is_metadata
) {
1590 struct relay_viewer_stream
*vstream
;
1592 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1594 if (stream
->no_new_metadata_notified
) {
1596 * Since all the metadata has been sent to the
1597 * viewer and that we have a request to close
1598 * its stream, we can safely teardown the
1599 * corresponding metadata viewer stream.
1601 viewer_stream_put(vstream
);
1603 /* Put local reference. */
1604 viewer_stream_put(vstream
);
1611 memset(&reply
, 0, sizeof(reply
));
1613 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1615 reply
.ret_code
= htobe32(LTTNG_OK
);
1617 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1618 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1619 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1620 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1630 * relay_reset_metadata: reset a metadata stream
1633 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1634 struct relay_connection
*conn
,
1635 const struct lttng_buffer_view
*payload
)
1639 struct relay_session
*session
= conn
->session
;
1640 struct lttcomm_relayd_reset_metadata stream_info
;
1641 struct lttcomm_relayd_generic_reply reply
;
1642 struct relay_stream
*stream
;
1644 DBG("Reset metadata received");
1646 if (!session
|| !conn
->version_check_done
) {
1647 ERR("Trying to reset a metadata stream before version check");
1649 goto end_no_session
;
1652 if (payload
->size
< sizeof(stream_info
)) {
1653 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1654 sizeof(stream_info
), payload
->size
);
1656 goto end_no_session
;
1658 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1659 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1660 stream_info
.version
= be64toh(stream_info
.version
);
1662 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1664 /* Unsupported for live sessions for now. */
1665 if (session
->live_timer
!= 0) {
1670 stream
= stream_get_by_id(stream_info
.stream_id
);
1675 pthread_mutex_lock(&stream
->lock
);
1676 if (!stream
->is_metadata
) {
1681 ret
= stream_reset_file(stream
);
1683 ERR("Failed to reset metadata stream %" PRIu64
1684 ": stream_path = %s, channel = %s",
1685 stream
->stream_handle
, stream
->path_name
,
1686 stream
->channel_name
);
1690 pthread_mutex_unlock(&stream
->lock
);
1694 memset(&reply
, 0, sizeof(reply
));
1696 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1698 reply
.ret_code
= htobe32(LTTNG_OK
);
1700 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1701 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1702 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1703 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1713 * relay_unknown_command: send -1 if received unknown command
1715 static void relay_unknown_command(struct relay_connection
*conn
)
1717 struct lttcomm_relayd_generic_reply reply
;
1720 memset(&reply
, 0, sizeof(reply
));
1721 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1722 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1723 if (send_ret
< sizeof(reply
)) {
1724 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1729 * relay_start: send an acknowledgment to the client to tell if we are
1730 * ready to receive data. We are ready if a session is established.
1732 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1733 struct relay_connection
*conn
,
1734 const struct lttng_buffer_view
*payload
)
1738 struct lttcomm_relayd_generic_reply reply
;
1739 struct relay_session
*session
= conn
->session
;
1742 DBG("Trying to start the streaming without a session established");
1743 ret
= htobe32(LTTNG_ERR_UNK
);
1746 memset(&reply
, 0, sizeof(reply
));
1747 reply
.ret_code
= htobe32(LTTNG_OK
);
1748 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1750 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1751 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1760 * relay_recv_metadata: receive the metadata for the session.
1762 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1763 struct relay_connection
*conn
,
1764 const struct lttng_buffer_view
*payload
)
1767 struct relay_session
*session
= conn
->session
;
1768 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1769 struct relay_stream
*metadata_stream
;
1770 uint64_t metadata_payload_size
;
1771 struct lttng_buffer_view packet_view
;
1774 ERR("Metadata sent before version check");
1779 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1780 ERR("Incorrect data size");
1784 metadata_payload_size
= recv_hdr
->data_size
-
1785 sizeof(struct lttcomm_relayd_metadata_payload
);
1787 memcpy(&metadata_payload_header
, payload
->data
,
1788 sizeof(metadata_payload_header
));
1789 metadata_payload_header
.stream_id
= be64toh(
1790 metadata_payload_header
.stream_id
);
1791 metadata_payload_header
.padding_size
= be32toh(
1792 metadata_payload_header
.padding_size
);
1794 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1795 if (!metadata_stream
) {
1800 packet_view
= lttng_buffer_view_from_view(payload
,
1801 sizeof(metadata_payload_header
), metadata_payload_size
);
1802 if (!packet_view
.data
) {
1803 ERR("Invalid metadata packet length announced by header");
1808 pthread_mutex_lock(&metadata_stream
->lock
);
1809 ret
= stream_write(metadata_stream
, &packet_view
,
1810 metadata_payload_header
.padding_size
);
1811 pthread_mutex_unlock(&metadata_stream
->lock
);
1817 stream_put(metadata_stream
);
1823 * relay_send_version: send relayd version number
1825 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1826 struct relay_connection
*conn
,
1827 const struct lttng_buffer_view
*payload
)
1831 struct lttcomm_relayd_version reply
, msg
;
1832 bool compatible
= true;
1834 conn
->version_check_done
= true;
1836 /* Get version from the other side. */
1837 if (payload
->size
< sizeof(msg
)) {
1838 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1839 sizeof(msg
), payload
->size
);
1844 memcpy(&msg
, payload
->data
, sizeof(msg
));
1845 msg
.major
= be32toh(msg
.major
);
1846 msg
.minor
= be32toh(msg
.minor
);
1848 memset(&reply
, 0, sizeof(reply
));
1849 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1850 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1852 /* Major versions must be the same */
1853 if (reply
.major
!= msg
.major
) {
1854 DBG("Incompatible major versions (%u vs %u), deleting session",
1855 reply
.major
, msg
.major
);
1859 conn
->major
= reply
.major
;
1860 /* We adapt to the lowest compatible version */
1861 if (reply
.minor
<= msg
.minor
) {
1862 conn
->minor
= reply
.minor
;
1864 conn
->minor
= msg
.minor
;
1867 reply
.major
= htobe32(reply
.major
);
1868 reply
.minor
= htobe32(reply
.minor
);
1869 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1871 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1872 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1885 DBG("Version check done using protocol %u.%u", conn
->major
,
1893 * Check for data pending for a given stream id from the session daemon.
1895 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1896 struct relay_connection
*conn
,
1897 const struct lttng_buffer_view
*payload
)
1899 struct relay_session
*session
= conn
->session
;
1900 struct lttcomm_relayd_data_pending msg
;
1901 struct lttcomm_relayd_generic_reply reply
;
1902 struct relay_stream
*stream
;
1905 uint64_t stream_seq
;
1907 DBG("Data pending command received");
1909 if (!session
|| !conn
->version_check_done
) {
1910 ERR("Trying to check for data before version check");
1912 goto end_no_session
;
1915 if (payload
->size
< sizeof(msg
)) {
1916 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1917 sizeof(msg
), payload
->size
);
1919 goto end_no_session
;
1921 memcpy(&msg
, payload
->data
, sizeof(msg
));
1922 msg
.stream_id
= be64toh(msg
.stream_id
);
1923 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1925 stream
= stream_get_by_id(msg
.stream_id
);
1926 if (stream
== NULL
) {
1931 pthread_mutex_lock(&stream
->lock
);
1933 if (session_streams_have_index(session
)) {
1935 * Ensure that both the index and stream data have been
1936 * flushed up to the requested point.
1938 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
1940 stream_seq
= stream
->prev_data_seq
;
1942 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
1943 ", prev_index_seq %" PRIu64
1944 ", and last_seq %" PRIu64
, msg
.stream_id
,
1945 stream
->prev_data_seq
, stream
->prev_index_seq
,
1946 msg
.last_net_seq_num
);
1948 /* Avoid wrapping issue */
1949 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
1950 /* Data has in fact been written and is NOT pending */
1953 /* Data still being streamed thus pending */
1957 stream
->data_pending_check_done
= true;
1958 pthread_mutex_unlock(&stream
->lock
);
1963 memset(&reply
, 0, sizeof(reply
));
1964 reply
.ret_code
= htobe32(ret
);
1965 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1966 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1967 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1977 * Wait for the control socket to reach a quiescent state.
1979 * Note that for now, when receiving this command from the session
1980 * daemon, this means that every subsequent commands or data received on
1981 * the control socket has been handled. So, this is why we simply return
1984 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1985 struct relay_connection
*conn
,
1986 const struct lttng_buffer_view
*payload
)
1990 struct relay_stream
*stream
;
1991 struct lttcomm_relayd_quiescent_control msg
;
1992 struct lttcomm_relayd_generic_reply reply
;
1994 DBG("Checking quiescent state on control socket");
1996 if (!conn
->session
|| !conn
->version_check_done
) {
1997 ERR("Trying to check for data before version check");
1999 goto end_no_session
;
2002 if (payload
->size
< sizeof(msg
)) {
2003 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2004 sizeof(msg
), payload
->size
);
2006 goto end_no_session
;
2008 memcpy(&msg
, payload
->data
, sizeof(msg
));
2009 msg
.stream_id
= be64toh(msg
.stream_id
);
2011 stream
= stream_get_by_id(msg
.stream_id
);
2015 pthread_mutex_lock(&stream
->lock
);
2016 stream
->data_pending_check_done
= true;
2017 pthread_mutex_unlock(&stream
->lock
);
2019 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2022 memset(&reply
, 0, sizeof(reply
));
2023 reply
.ret_code
= htobe32(LTTNG_OK
);
2024 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2025 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2026 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2038 * Initialize a data pending command. This means that a consumer is about
2039 * to ask for data pending for each stream it holds. Simply iterate over
2040 * all streams of a session and set the data_pending_check_done flag.
2042 * This command returns to the client a LTTNG_OK code.
2044 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2045 struct relay_connection
*conn
,
2046 const struct lttng_buffer_view
*payload
)
2050 struct lttng_ht_iter iter
;
2051 struct lttcomm_relayd_begin_data_pending msg
;
2052 struct lttcomm_relayd_generic_reply reply
;
2053 struct relay_stream
*stream
;
2058 DBG("Init streams for data pending");
2060 if (!conn
->session
|| !conn
->version_check_done
) {
2061 ERR("Trying to check for data before version check");
2063 goto end_no_session
;
2066 if (payload
->size
< sizeof(msg
)) {
2067 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2068 sizeof(msg
), payload
->size
);
2070 goto end_no_session
;
2072 memcpy(&msg
, payload
->data
, sizeof(msg
));
2073 msg
.session_id
= be64toh(msg
.session_id
);
2076 * Iterate over all streams to set the begin data pending flag.
2077 * For now, the streams are indexed by stream handle so we have
2078 * to iterate over all streams to find the one associated with
2079 * the right session_id.
2082 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2084 if (!stream_get(stream
)) {
2087 if (stream
->trace
->session
->id
== msg
.session_id
) {
2088 pthread_mutex_lock(&stream
->lock
);
2089 stream
->data_pending_check_done
= false;
2090 pthread_mutex_unlock(&stream
->lock
);
2091 DBG("Set begin data pending flag to stream %" PRIu64
,
2092 stream
->stream_handle
);
2098 memset(&reply
, 0, sizeof(reply
));
2099 /* All good, send back reply. */
2100 reply
.ret_code
= htobe32(LTTNG_OK
);
2102 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2103 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2104 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2116 * End data pending command. This will check, for a given session id, if
2117 * each stream associated with it has its data_pending_check_done flag
2118 * set. If not, this means that the client lost track of the stream but
2119 * the data is still being streamed on our side. In this case, we inform
2120 * the client that data is in flight.
2122 * Return to the client if there is data in flight or not with a ret_code.
2124 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2125 struct relay_connection
*conn
,
2126 const struct lttng_buffer_view
*payload
)
2130 struct lttng_ht_iter iter
;
2131 struct lttcomm_relayd_end_data_pending msg
;
2132 struct lttcomm_relayd_generic_reply reply
;
2133 struct relay_stream
*stream
;
2134 uint32_t is_data_inflight
= 0;
2136 DBG("End data pending command");
2138 if (!conn
->session
|| !conn
->version_check_done
) {
2139 ERR("Trying to check for data before version check");
2141 goto end_no_session
;
2144 if (payload
->size
< sizeof(msg
)) {
2145 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2146 sizeof(msg
), payload
->size
);
2148 goto end_no_session
;
2150 memcpy(&msg
, payload
->data
, sizeof(msg
));
2151 msg
.session_id
= be64toh(msg
.session_id
);
2154 * Iterate over all streams to see if the begin data pending
2158 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2160 if (!stream_get(stream
)) {
2163 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2167 pthread_mutex_lock(&stream
->lock
);
2168 if (!stream
->data_pending_check_done
) {
2169 uint64_t stream_seq
;
2171 if (session_streams_have_index(conn
->session
)) {
2173 * Ensure that both the index and stream data have been
2174 * flushed up to the requested point.
2176 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2178 stream_seq
= stream
->prev_data_seq
;
2180 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2181 is_data_inflight
= 1;
2182 DBG("Data is still in flight for stream %" PRIu64
,
2183 stream
->stream_handle
);
2184 pthread_mutex_unlock(&stream
->lock
);
2189 pthread_mutex_unlock(&stream
->lock
);
2194 memset(&reply
, 0, sizeof(reply
));
2195 /* All good, send back reply. */
2196 reply
.ret_code
= htobe32(is_data_inflight
);
2198 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2199 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2200 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2212 * Receive an index for a specific stream.
2214 * Return 0 on success else a negative value.
2216 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2217 struct relay_connection
*conn
,
2218 const struct lttng_buffer_view
*payload
)
2222 struct relay_session
*session
= conn
->session
;
2223 struct lttcomm_relayd_index index_info
;
2224 struct lttcomm_relayd_generic_reply reply
;
2225 struct relay_stream
*stream
;
2230 DBG("Relay receiving index");
2232 if (!session
|| !conn
->version_check_done
) {
2233 ERR("Trying to close a stream before version check");
2235 goto end_no_session
;
2238 msg_len
= lttcomm_relayd_index_len(
2239 lttng_to_index_major(conn
->major
, conn
->minor
),
2240 lttng_to_index_minor(conn
->major
, conn
->minor
));
2241 if (payload
->size
< msg_len
) {
2242 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2243 msg_len
, payload
->size
);
2245 goto end_no_session
;
2247 memcpy(&index_info
, payload
->data
, msg_len
);
2248 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2249 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2250 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2251 index_info
.content_size
= be64toh(index_info
.content_size
);
2252 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2253 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2254 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2255 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2257 if (conn
->minor
>= 8) {
2258 index_info
.stream_instance_id
=
2259 be64toh(index_info
.stream_instance_id
);
2260 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2262 index_info
.stream_instance_id
= -1ULL;
2263 index_info
.packet_seq_num
= -1ULL;
2266 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2268 ERR("stream_get_by_id not found");
2273 pthread_mutex_lock(&stream
->lock
);
2274 ret
= stream_add_index(stream
, &index_info
);
2275 pthread_mutex_unlock(&stream
->lock
);
2277 goto end_stream_put
;
2283 memset(&reply
, 0, sizeof(reply
));
2285 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2287 reply
.ret_code
= htobe32(LTTNG_OK
);
2289 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2290 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2291 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2300 * Receive the streams_sent message.
2302 * Return 0 on success else a negative value.
2304 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2305 struct relay_connection
*conn
,
2306 const struct lttng_buffer_view
*payload
)
2310 struct lttcomm_relayd_generic_reply reply
;
2314 DBG("Relay receiving streams_sent");
2316 if (!conn
->session
|| !conn
->version_check_done
) {
2317 ERR("Trying to close a stream before version check");
2319 goto end_no_session
;
2323 * Publish every pending stream in the connection recv list which are
2324 * now ready to be used by the viewer.
2326 publish_connection_local_streams(conn
);
2328 memset(&reply
, 0, sizeof(reply
));
2329 reply
.ret_code
= htobe32(LTTNG_OK
);
2330 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2331 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2332 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2345 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2346 * session rotation feature (not the tracefile rotation feature).
2348 static int relay_rotate_session_streams(
2349 const struct lttcomm_relayd_hdr
*recv_hdr
,
2350 struct relay_connection
*conn
,
2351 const struct lttng_buffer_view
*payload
)
2356 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2357 struct relay_session
*session
= conn
->session
;
2358 struct lttcomm_relayd_rotate_streams rotate_streams
;
2359 struct lttcomm_relayd_generic_reply reply
= {};
2360 struct relay_stream
*stream
= NULL
;
2361 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2362 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2363 struct lttng_buffer_view stream_positions
;
2364 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2365 const char *chunk_id_str
= "none";
2367 if (!session
|| !conn
->version_check_done
) {
2368 ERR("Trying to rotate a stream before version check");
2373 if (session
->major
== 2 && session
->minor
< 11) {
2374 ERR("Unsupported feature before 2.11");
2379 if (payload
->size
< header_len
) {
2380 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2381 header_len
, payload
->size
);
2386 memcpy(&rotate_streams
, payload
->data
, header_len
);
2388 /* Convert header to host endianness. */
2389 rotate_streams
= (typeof(rotate_streams
)) {
2390 .stream_count
= be32toh(rotate_streams
.stream_count
),
2391 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2392 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2393 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2397 if (rotate_streams
.new_chunk_id
.is_set
) {
2399 * Retrieve the trace chunk the stream must transition to. As
2400 * per the protocol, this chunk should have been created
2401 * before this command is received.
2403 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2404 sessiond_trace_chunk_registry
,
2405 session
->sessiond_uuid
, session
->id
,
2406 rotate_streams
.new_chunk_id
.value
);
2407 if (!next_trace_chunk
) {
2408 char uuid_str
[LTTNG_UUID_STR_LEN
];
2410 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2411 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2412 ", trace_chunk_id = %" PRIu64
,
2413 uuid_str
, session
->id
,
2414 rotate_streams
.new_chunk_id
.value
);
2415 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2420 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2421 rotate_streams
.new_chunk_id
.value
);
2422 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2423 chunk_id_str
= "formatting error";
2425 chunk_id_str
= chunk_id_buf
;
2429 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2430 rotate_streams
.stream_count
, session
->session_name
,
2433 stream_positions
= lttng_buffer_view_from_view(payload
,
2434 sizeof(rotate_streams
), -1);
2435 if (!stream_positions
.data
||
2436 stream_positions
.size
<
2437 (rotate_streams
.stream_count
*
2438 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2439 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2444 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2445 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2446 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2447 const struct lttcomm_relayd_stream_rotation_position pos
= {
2448 .stream_id
= be64toh(position_comm
->stream_id
),
2449 .rotate_at_seq_num
= be64toh(
2450 position_comm
->rotate_at_seq_num
),
2453 stream
= stream_get_by_id(pos
.stream_id
);
2455 reply_code
= LTTNG_ERR_INVALID
;
2460 pthread_mutex_lock(&stream
->lock
);
2461 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2462 pos
.rotate_at_seq_num
);
2463 pthread_mutex_unlock(&stream
->lock
);
2465 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2473 reply_code
= LTTNG_OK
;
2480 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2481 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2482 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2483 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2484 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2489 lttng_trace_chunk_put(next_trace_chunk
);
2496 * relay_create_trace_chunk: create a new trace chunk
2498 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2499 struct relay_connection
*conn
,
2500 const struct lttng_buffer_view
*payload
)
2504 struct relay_session
*session
= conn
->session
;
2505 struct lttcomm_relayd_create_trace_chunk
*msg
;
2506 struct lttcomm_relayd_generic_reply reply
= {};
2507 struct lttng_buffer_view header_view
;
2508 struct lttng_buffer_view chunk_name_view
;
2509 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2510 enum lttng_error_code reply_code
= LTTNG_OK
;
2511 enum lttng_trace_chunk_status chunk_status
;
2512 struct lttng_directory_handle
*session_output
= NULL
;
2513 const char *new_path
;
2515 if (!session
|| !conn
->version_check_done
) {
2516 ERR("Trying to create a trace chunk before version check");
2521 if (session
->major
== 2 && session
->minor
< 11) {
2522 ERR("Chunk creation command is unsupported before 2.11");
2527 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2528 if (!header_view
.data
) {
2529 ERR("Failed to receive payload of chunk creation command");
2534 /* Convert to host endianness. */
2535 msg
= (typeof(msg
)) header_view
.data
;
2536 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2537 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2538 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2540 if (session
->current_trace_chunk
&&
2541 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2542 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2543 DEFAULT_CHUNK_TMP_OLD_DIRECTORY
);
2544 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2545 ERR("Failed to rename old chunk");
2547 reply_code
= LTTNG_ERR_UNK
;
2551 session
->ongoing_rotation
= true;
2552 if (!session
->current_trace_chunk
) {
2553 if (!session
->has_rotated
) {
2559 new_path
= DEFAULT_CHUNK_TMP_NEW_DIRECTORY
;
2561 chunk
= lttng_trace_chunk_create(
2562 msg
->chunk_id
, msg
->creation_timestamp
, new_path
);
2564 ERR("Failed to create trace chunk in trace chunk creation command");
2566 reply_code
= LTTNG_ERR_NOMEM
;
2570 if (msg
->override_name_length
) {
2573 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2575 msg
->override_name_length
);
2576 name
= chunk_name_view
.data
;
2577 if (!name
|| name
[msg
->override_name_length
- 1]) {
2578 ERR("Failed to receive payload of chunk creation command");
2580 reply_code
= LTTNG_ERR_INVALID
;
2584 chunk_status
= lttng_trace_chunk_override_name(
2585 chunk
, chunk_name_view
.data
);
2586 switch (chunk_status
) {
2587 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2589 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2590 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2591 reply_code
= LTTNG_ERR_INVALID
;
2595 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2596 reply_code
= LTTNG_ERR_UNK
;
2602 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2603 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2604 reply_code
= LTTNG_ERR_UNK
;
2609 session_output
= session_create_output_directory_handle(
2611 if (!session_output
) {
2612 reply_code
= LTTNG_ERR_CREATE_DIR_FAIL
;
2615 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, session_output
);
2616 lttng_directory_handle_put(session_output
);
2617 session_output
= NULL
;
2618 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2619 reply_code
= LTTNG_ERR_UNK
;
2624 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2625 sessiond_trace_chunk_registry
,
2626 conn
->session
->sessiond_uuid
,
2629 if (!published_chunk
) {
2630 char uuid_str
[LTTNG_UUID_STR_LEN
];
2632 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2633 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2638 reply_code
= LTTNG_ERR_NOMEM
;
2642 pthread_mutex_lock(&conn
->session
->lock
);
2643 if (conn
->session
->pending_closure_trace_chunk
) {
2645 * Invalid; this means a second create_trace_chunk command was
2646 * received before a close_trace_chunk.
2648 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2649 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2651 goto end_unlock_session
;
2653 conn
->session
->pending_closure_trace_chunk
=
2654 conn
->session
->current_trace_chunk
;
2655 conn
->session
->current_trace_chunk
= published_chunk
;
2656 published_chunk
= NULL
;
2657 if (!conn
->session
->pending_closure_trace_chunk
) {
2658 session
->ongoing_rotation
= false;
2661 pthread_mutex_unlock(&conn
->session
->lock
);
2663 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2664 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2666 sizeof(struct lttcomm_relayd_generic_reply
),
2668 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2669 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2674 lttng_trace_chunk_put(chunk
);
2675 lttng_trace_chunk_put(published_chunk
);
2676 lttng_directory_handle_put(session_output
);
2681 * relay_close_trace_chunk: close a trace chunk
2683 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2684 struct relay_connection
*conn
,
2685 const struct lttng_buffer_view
*payload
)
2687 int ret
= 0, buf_ret
;
2689 struct relay_session
*session
= conn
->session
;
2690 struct lttcomm_relayd_close_trace_chunk
*msg
;
2691 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2692 struct lttng_buffer_view header_view
;
2693 struct lttng_trace_chunk
*chunk
= NULL
;
2694 enum lttng_error_code reply_code
= LTTNG_OK
;
2695 enum lttng_trace_chunk_status chunk_status
;
2697 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2698 time_t close_timestamp
;
2699 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2700 size_t path_length
= 0;
2701 const char *chunk_name
= NULL
;
2702 struct lttng_dynamic_buffer reply_payload
;
2703 const char *new_path
;
2705 lttng_dynamic_buffer_init(&reply_payload
);
2707 if (!session
|| !conn
->version_check_done
) {
2708 ERR("Trying to close a trace chunk before version check");
2713 if (session
->major
== 2 && session
->minor
< 11) {
2714 ERR("Chunk close command is unsupported before 2.11");
2719 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2720 if (!header_view
.data
) {
2721 ERR("Failed to receive payload of chunk close command");
2726 /* Convert to host endianness. */
2727 msg
= (typeof(msg
)) header_view
.data
;
2728 chunk_id
= be64toh(msg
->chunk_id
);
2729 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2730 close_command
= (typeof(close_command
)){
2731 .value
= be32toh(msg
->close_command
.value
),
2732 .is_set
= msg
->close_command
.is_set
,
2735 chunk
= sessiond_trace_chunk_registry_get_chunk(
2736 sessiond_trace_chunk_registry
,
2737 conn
->session
->sessiond_uuid
,
2741 char uuid_str
[LTTNG_UUID_STR_LEN
];
2743 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2744 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2749 reply_code
= LTTNG_ERR_NOMEM
;
2753 pthread_mutex_lock(&session
->lock
);
2754 if (close_command
.is_set
&&
2755 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
) {
2757 * Clear command. It is a protocol error to ask for a
2758 * clear on a relay which does not allow it. Querying
2759 * the configuration allows figuring out whether
2760 * clearing is allowed before doing the clear.
2762 if (!opt_allow_clear
) {
2764 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2765 goto end_unlock_session
;
2768 if (session
->pending_closure_trace_chunk
&&
2769 session
->pending_closure_trace_chunk
!= chunk
) {
2770 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2771 session
->session_name
);
2772 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2774 goto end_unlock_session
;
2777 if (session
->current_trace_chunk
&& session
->current_trace_chunk
!= chunk
&&
2778 !lttng_trace_chunk_get_name_overridden(session
->current_trace_chunk
)) {
2779 if (close_command
.is_set
&&
2780 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_DELETE
&&
2781 !session
->has_rotated
) {
2782 /* New chunk stays in session output directory. */
2785 /* Use chunk name for new chunk. */
2788 /* Rename new chunk path. */
2789 chunk_status
= lttng_trace_chunk_rename_path(session
->current_trace_chunk
,
2791 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2795 session
->ongoing_rotation
= false;
2797 if ((!close_command
.is_set
||
2798 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_NO_OPERATION
) &&
2799 !lttng_trace_chunk_get_name_overridden(chunk
)) {
2800 const char *old_path
;
2802 if (!session
->has_rotated
) {
2807 /* We need to move back the .tmp_old_chunk to its rightful place. */
2808 chunk_status
= lttng_trace_chunk_rename_path(chunk
, old_path
);
2809 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2814 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2815 chunk
, close_timestamp
);
2816 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2817 ERR("Failed to set trace chunk close timestamp");
2819 reply_code
= LTTNG_ERR_UNK
;
2820 goto end_unlock_session
;
2823 if (close_command
.is_set
) {
2824 chunk_status
= lttng_trace_chunk_set_close_command(
2825 chunk
, close_command
.value
);
2826 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2828 reply_code
= LTTNG_ERR_INVALID
;
2829 goto end_unlock_session
;
2832 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2833 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2834 ERR("Failed to get chunk name");
2836 reply_code
= LTTNG_ERR_UNK
;
2837 goto end_unlock_session
;
2839 if (!session
->has_rotated
&& !session
->snapshot
) {
2840 ret
= lttng_strncpy(closed_trace_chunk_path
,
2841 session
->output_path
,
2842 sizeof(closed_trace_chunk_path
));
2844 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2845 strlen(session
->output_path
),
2846 sizeof(closed_trace_chunk_path
));
2847 reply_code
= LTTNG_ERR_NOMEM
;
2849 goto end_unlock_session
;
2852 if (session
->snapshot
) {
2853 ret
= snprintf(closed_trace_chunk_path
,
2854 sizeof(closed_trace_chunk_path
),
2855 "%s/%s", session
->output_path
,
2858 ret
= snprintf(closed_trace_chunk_path
,
2859 sizeof(closed_trace_chunk_path
),
2860 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2862 session
->output_path
, chunk_name
);
2864 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
2865 ERR("Failed to format closed trace chunk resulting path");
2866 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
2868 goto end_unlock_session
;
2871 if (close_command
.is_set
&&
2872 close_command
.value
== LTTNG_TRACE_CHUNK_COMMAND_TYPE_MOVE_TO_COMPLETED
) {
2873 session
->has_rotated
= true;
2875 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
2876 path_length
= strlen(closed_trace_chunk_path
) + 1;
2877 if (path_length
> UINT32_MAX
) {
2878 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2880 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2881 goto end_unlock_session
;
2884 if (session
->current_trace_chunk
== chunk
) {
2886 * After a trace chunk close command, no new streams
2887 * referencing the chunk may be created. Hence, on the
2888 * event that no new trace chunk have been created for
2889 * the session, the reference to the current trace chunk
2890 * is released in order to allow it to be reclaimed when
2891 * the last stream releases its reference to it.
2893 lttng_trace_chunk_put(session
->current_trace_chunk
);
2894 session
->current_trace_chunk
= NULL
;
2896 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
2897 session
->pending_closure_trace_chunk
= NULL
;
2899 pthread_mutex_unlock(&session
->lock
);
2902 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
2903 reply
.path_length
= htobe32((uint32_t) path_length
);
2904 buf_ret
= lttng_dynamic_buffer_append(
2905 &reply_payload
, &reply
, sizeof(reply
));
2907 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2911 if (reply_code
== LTTNG_OK
) {
2912 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
2913 closed_trace_chunk_path
, path_length
);
2915 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2920 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2924 if (send_ret
< reply_payload
.size
) {
2925 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2926 reply_payload
.size
, send_ret
);
2931 lttng_trace_chunk_put(chunk
);
2932 lttng_dynamic_buffer_reset(&reply_payload
);
2937 * relay_trace_chunk_exists: check if a trace chunk exists
2939 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
2940 struct relay_connection
*conn
,
2941 const struct lttng_buffer_view
*payload
)
2945 struct relay_session
*session
= conn
->session
;
2946 struct lttcomm_relayd_trace_chunk_exists
*msg
;
2947 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
2948 struct lttng_buffer_view header_view
;
2952 if (!session
|| !conn
->version_check_done
) {
2953 ERR("Trying to close a trace chunk before version check");
2958 if (session
->major
== 2 && session
->minor
< 11) {
2959 ERR("Chunk close command is unsupported before 2.11");
2964 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2965 if (!header_view
.data
) {
2966 ERR("Failed to receive payload of chunk close command");
2971 /* Convert to host endianness. */
2972 msg
= (typeof(msg
)) header_view
.data
;
2973 chunk_id
= be64toh(msg
->chunk_id
);
2975 ret
= sessiond_trace_chunk_registry_chunk_exists(
2976 sessiond_trace_chunk_registry
,
2977 conn
->session
->sessiond_uuid
,
2979 chunk_id
, &chunk_exists
);
2981 * If ret is not 0, send the reply and report the error to the caller.
2982 * It is a protocol (or internal) error and the session/connection
2983 * should be torn down.
2985 reply
= (typeof(reply
)){
2986 .generic
.ret_code
= htobe32((uint32_t)
2987 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
2988 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
2990 send_ret
= conn
->sock
->ops
->sendmsg(
2991 conn
->sock
, &reply
, sizeof(reply
), 0);
2992 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2993 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
3002 * relay_get_configuration: query whether feature is available
3004 static int relay_get_configuration(const struct lttcomm_relayd_hdr
*recv_hdr
,
3005 struct relay_connection
*conn
,
3006 const struct lttng_buffer_view
*payload
)
3010 struct lttcomm_relayd_get_configuration
*msg
;
3011 struct lttcomm_relayd_get_configuration_reply reply
= {};
3012 struct lttng_buffer_view header_view
;
3013 uint64_t query_flags
= 0;
3014 uint64_t result_flags
= 0;
3016 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
3017 if (!header_view
.data
) {
3018 ERR("Failed to receive payload of chunk close command");
3023 /* Convert to host endianness. */
3024 msg
= (typeof(msg
)) header_view
.data
;
3025 query_flags
= be64toh(msg
->query_flags
);
3028 ret
= LTTNG_ERR_INVALID_PROTOCOL
;
3031 if (opt_allow_clear
) {
3032 result_flags
|= LTTCOMM_RELAYD_CONFIGURATION_FLAG_CLEAR_ALLOWED
;
3036 reply
= (typeof(reply
)){
3037 .generic
.ret_code
= htobe32((uint32_t)
3038 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
3039 .relayd_configuration_flags
= htobe64(result_flags
),
3041 send_ret
= conn
->sock
->ops
->sendmsg(
3042 conn
->sock
, &reply
, sizeof(reply
), 0);
3043 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3044 ERR("Failed to send \"get configuration\" command reply (ret = %zd)",
3052 #define DBG_CMD(cmd_name, conn) \
3053 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3055 static int relay_process_control_command(struct relay_connection
*conn
,
3056 const struct lttcomm_relayd_hdr
*header
,
3057 const struct lttng_buffer_view
*payload
)
3061 switch (header
->cmd
) {
3062 case RELAYD_CREATE_SESSION
:
3063 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3064 ret
= relay_create_session(header
, conn
, payload
);
3066 case RELAYD_ADD_STREAM
:
3067 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3068 ret
= relay_add_stream(header
, conn
, payload
);
3070 case RELAYD_START_DATA
:
3071 DBG_CMD("RELAYD_START_DATA", conn
);
3072 ret
= relay_start(header
, conn
, payload
);
3074 case RELAYD_SEND_METADATA
:
3075 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3076 ret
= relay_recv_metadata(header
, conn
, payload
);
3078 case RELAYD_VERSION
:
3079 DBG_CMD("RELAYD_VERSION", conn
);
3080 ret
= relay_send_version(header
, conn
, payload
);
3082 case RELAYD_CLOSE_STREAM
:
3083 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3084 ret
= relay_close_stream(header
, conn
, payload
);
3086 case RELAYD_DATA_PENDING
:
3087 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3088 ret
= relay_data_pending(header
, conn
, payload
);
3090 case RELAYD_QUIESCENT_CONTROL
:
3091 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3092 ret
= relay_quiescent_control(header
, conn
, payload
);
3094 case RELAYD_BEGIN_DATA_PENDING
:
3095 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3096 ret
= relay_begin_data_pending(header
, conn
, payload
);
3098 case RELAYD_END_DATA_PENDING
:
3099 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3100 ret
= relay_end_data_pending(header
, conn
, payload
);
3102 case RELAYD_SEND_INDEX
:
3103 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3104 ret
= relay_recv_index(header
, conn
, payload
);
3106 case RELAYD_STREAMS_SENT
:
3107 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3108 ret
= relay_streams_sent(header
, conn
, payload
);
3110 case RELAYD_RESET_METADATA
:
3111 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3112 ret
= relay_reset_metadata(header
, conn
, payload
);
3114 case RELAYD_ROTATE_STREAMS
:
3115 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
3116 ret
= relay_rotate_session_streams(header
, conn
, payload
);
3118 case RELAYD_CREATE_TRACE_CHUNK
:
3119 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
3120 ret
= relay_create_trace_chunk(header
, conn
, payload
);
3122 case RELAYD_CLOSE_TRACE_CHUNK
:
3123 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
3124 ret
= relay_close_trace_chunk(header
, conn
, payload
);
3126 case RELAYD_TRACE_CHUNK_EXISTS
:
3127 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
3128 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
3130 case RELAYD_GET_CONFIGURATION
:
3131 DBG_CMD("RELAYD_GET_CONFIGURATION", conn
);
3132 ret
= relay_get_configuration(header
, conn
, payload
);
3134 case RELAYD_UPDATE_SYNC_INFO
:
3136 ERR("Received unknown command (%u)", header
->cmd
);
3137 relay_unknown_command(conn
);
3146 static enum relay_connection_status
relay_process_control_receive_payload(
3147 struct relay_connection
*conn
)
3150 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3151 struct lttng_dynamic_buffer
*reception_buffer
=
3152 &conn
->protocol
.ctrl
.reception_buffer
;
3153 struct ctrl_connection_state_receive_payload
*state
=
3154 &conn
->protocol
.ctrl
.state
.receive_payload
;
3155 struct lttng_buffer_view payload_view
;
3157 if (state
->left_to_receive
== 0) {
3158 /* Short-circuit for payload-less commands. */
3159 goto reception_complete
;
3162 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3163 reception_buffer
->data
+ state
->received
,
3164 state
->left_to_receive
, MSG_DONTWAIT
);
3166 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3167 PERROR("Unable to receive command payload on sock %d",
3169 status
= RELAY_CONNECTION_STATUS_ERROR
;
3172 } else if (ret
== 0) {
3173 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3174 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3179 assert(ret
<= state
->left_to_receive
);
3181 state
->left_to_receive
-= ret
;
3182 state
->received
+= ret
;
3184 if (state
->left_to_receive
> 0) {
3186 * Can't transition to the protocol's next state, wait to
3187 * receive the rest of the header.
3189 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3190 state
->received
, state
->left_to_receive
,
3196 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3197 conn
->sock
->fd
, state
->received
);
3199 * The payload required to process the command has been received.
3200 * A view to the reception buffer is forwarded to the various
3201 * commands and the state of the control is reset on success.
3203 * Commands are responsible for sending their reply to the peer.
3205 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3207 ret
= relay_process_control_command(conn
,
3208 &state
->header
, &payload_view
);
3210 status
= RELAY_CONNECTION_STATUS_ERROR
;
3214 ret
= connection_reset_protocol_state(conn
);
3216 status
= RELAY_CONNECTION_STATUS_ERROR
;
3222 static enum relay_connection_status
relay_process_control_receive_header(
3223 struct relay_connection
*conn
)
3226 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3227 struct lttcomm_relayd_hdr header
;
3228 struct lttng_dynamic_buffer
*reception_buffer
=
3229 &conn
->protocol
.ctrl
.reception_buffer
;
3230 struct ctrl_connection_state_receive_header
*state
=
3231 &conn
->protocol
.ctrl
.state
.receive_header
;
3233 assert(state
->left_to_receive
!= 0);
3235 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3236 reception_buffer
->data
+ state
->received
,
3237 state
->left_to_receive
, MSG_DONTWAIT
);
3239 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3240 PERROR("Unable to receive control command header on sock %d",
3242 status
= RELAY_CONNECTION_STATUS_ERROR
;
3245 } else if (ret
== 0) {
3246 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3247 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3252 assert(ret
<= state
->left_to_receive
);
3254 state
->left_to_receive
-= ret
;
3255 state
->received
+= ret
;
3257 if (state
->left_to_receive
> 0) {
3259 * Can't transition to the protocol's next state, wait to
3260 * receive the rest of the header.
3262 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3263 state
->received
, state
->left_to_receive
,
3268 /* Transition to next state: receiving the command's payload. */
3269 conn
->protocol
.ctrl
.state_id
=
3270 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3271 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3272 header
.circuit_id
= be64toh(header
.circuit_id
);
3273 header
.data_size
= be64toh(header
.data_size
);
3274 header
.cmd
= be32toh(header
.cmd
);
3275 header
.cmd_version
= be32toh(header
.cmd_version
);
3276 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3277 &header
, sizeof(header
));
3279 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3280 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3283 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3284 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3286 status
= RELAY_CONNECTION_STATUS_ERROR
;
3290 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3292 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3293 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3296 status
= RELAY_CONNECTION_STATUS_ERROR
;
3300 if (header
.data_size
== 0) {
3302 * Manually invoke the next state as the poll loop
3303 * will not wake-up to allow us to proceed further.
3305 status
= relay_process_control_receive_payload(conn
);
3312 * Process the commands received on the control socket
3314 static enum relay_connection_status
relay_process_control(
3315 struct relay_connection
*conn
)
3317 enum relay_connection_status status
;
3319 switch (conn
->protocol
.ctrl
.state_id
) {
3320 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3321 status
= relay_process_control_receive_header(conn
);
3323 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3324 status
= relay_process_control_receive_payload(conn
);
3327 ERR("Unknown control connection protocol state encountered.");
3334 static enum relay_connection_status
relay_process_data_receive_header(
3335 struct relay_connection
*conn
)
3338 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3339 struct data_connection_state_receive_header
*state
=
3340 &conn
->protocol
.data
.state
.receive_header
;
3341 struct lttcomm_relayd_data_hdr header
;
3342 struct relay_stream
*stream
;
3344 assert(state
->left_to_receive
!= 0);
3346 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3347 state
->header_reception_buffer
+ state
->received
,
3348 state
->left_to_receive
, MSG_DONTWAIT
);
3350 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3351 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3352 status
= RELAY_CONNECTION_STATUS_ERROR
;
3355 } else if (ret
== 0) {
3356 /* Orderly shutdown. Not necessary to print an error. */
3357 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3358 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3363 assert(ret
<= state
->left_to_receive
);
3365 state
->left_to_receive
-= ret
;
3366 state
->received
+= ret
;
3368 if (state
->left_to_receive
> 0) {
3370 * Can't transition to the protocol's next state, wait to
3371 * receive the rest of the header.
3373 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3374 state
->received
, state
->left_to_receive
,
3379 /* Transition to next state: receiving the payload. */
3380 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3382 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3383 header
.circuit_id
= be64toh(header
.circuit_id
);
3384 header
.stream_id
= be64toh(header
.stream_id
);
3385 header
.data_size
= be32toh(header
.data_size
);
3386 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3387 header
.padding_size
= be32toh(header
.padding_size
);
3388 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3390 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3392 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3393 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3395 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3396 conn
->sock
->fd
, header
.circuit_id
,
3397 header
.stream_id
, header
.data_size
,
3398 header
.net_seq_num
, header
.padding_size
);
3400 stream
= stream_get_by_id(header
.stream_id
);
3402 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3404 /* Protocol error. */
3405 status
= RELAY_CONNECTION_STATUS_ERROR
;
3409 pthread_mutex_lock(&stream
->lock
);
3410 /* Prepare stream for the reception of a new packet. */
3411 ret
= stream_init_packet(stream
, header
.data_size
,
3412 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3413 pthread_mutex_unlock(&stream
->lock
);
3415 ERR("Failed to rotate stream output file");
3416 status
= RELAY_CONNECTION_STATUS_ERROR
;
3417 goto end_stream_unlock
;
3426 static enum relay_connection_status
relay_process_data_receive_payload(
3427 struct relay_connection
*conn
)
3430 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3431 struct relay_stream
*stream
;
3432 struct data_connection_state_receive_payload
*state
=
3433 &conn
->protocol
.data
.state
.receive_payload
;
3434 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3435 char data_buffer
[chunk_size
];
3436 bool partial_recv
= false;
3437 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3438 uint64_t left_to_receive
= state
->left_to_receive
;
3439 struct relay_session
*session
;
3441 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3442 state
->header
.stream_id
, state
->header
.net_seq_num
,
3443 state
->received
, left_to_receive
);
3445 stream
= stream_get_by_id(state
->header
.stream_id
);
3447 /* Protocol error. */
3448 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3449 state
->header
.stream_id
);
3450 status
= RELAY_CONNECTION_STATUS_ERROR
;
3454 pthread_mutex_lock(&stream
->lock
);
3455 session
= stream
->trace
->session
;
3456 if (!conn
->session
) {
3457 ret
= connection_set_session(conn
, session
);
3459 status
= RELAY_CONNECTION_STATUS_ERROR
;
3460 goto end_stream_unlock
;
3465 * The size of the "chunk" received on any iteration is bounded by:
3466 * - the data left to receive,
3467 * - the data immediately available on the socket,
3468 * - the on-stack data buffer
3470 while (left_to_receive
> 0 && !partial_recv
) {
3471 size_t recv_size
= min(left_to_receive
, chunk_size
);
3472 struct lttng_buffer_view packet_chunk
;
3474 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3475 recv_size
, MSG_DONTWAIT
);
3477 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3478 PERROR("Socket %d error", conn
->sock
->fd
);
3479 status
= RELAY_CONNECTION_STATUS_ERROR
;
3481 goto end_stream_unlock
;
3482 } else if (ret
== 0) {
3483 /* No more data ready to be consumed on socket. */
3484 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3485 state
->header
.stream_id
);
3486 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3488 } else if (ret
< (int) recv_size
) {
3490 * All the data available on the socket has been
3493 partial_recv
= true;
3497 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3499 assert(packet_chunk
.data
);
3501 ret
= stream_write(stream
, &packet_chunk
, 0);
3503 ERR("Relay error writing data to file");
3504 status
= RELAY_CONNECTION_STATUS_ERROR
;
3505 goto end_stream_unlock
;
3508 left_to_receive
-= recv_size
;
3509 state
->received
+= recv_size
;
3510 state
->left_to_receive
= left_to_receive
;
3513 if (state
->left_to_receive
> 0) {
3515 * Did not receive all the data expected, wait for more data to
3516 * become available on the socket.
3518 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3519 state
->header
.stream_id
, state
->received
,
3520 state
->left_to_receive
);
3521 goto end_stream_unlock
;
3524 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3526 status
= RELAY_CONNECTION_STATUS_ERROR
;
3527 goto end_stream_unlock
;
3530 if (session_streams_have_index(session
)) {
3531 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3532 state
->rotate_index
, &index_flushed
,
3533 state
->header
.data_size
+ state
->header
.padding_size
);
3535 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3536 stream
->stream_handle
,
3537 state
->header
.net_seq_num
, ret
);
3538 status
= RELAY_CONNECTION_STATUS_ERROR
;
3539 goto end_stream_unlock
;
3543 if (stream
->prev_data_seq
== -1ULL) {
3547 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3548 state
->header
.padding_size
, state
->header
.net_seq_num
,
3551 status
= RELAY_CONNECTION_STATUS_ERROR
;
3552 goto end_stream_unlock
;
3556 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3557 * contents of *state which are aliased (union) to the same location as
3558 * the new state. Don't use it beyond this point.
3560 connection_reset_protocol_state(conn
);
3564 close_requested
= stream
->close_requested
;
3565 pthread_mutex_unlock(&stream
->lock
);
3566 if (close_requested
&& left_to_receive
== 0) {
3567 try_stream_close(stream
);
3571 pthread_mutex_lock(&session
->lock
);
3572 uatomic_set(&session
->new_streams
, 1);
3573 pthread_mutex_unlock(&session
->lock
);
3582 * relay_process_data: Process the data received on the data socket
3584 static enum relay_connection_status
relay_process_data(
3585 struct relay_connection
*conn
)
3587 enum relay_connection_status status
;
3589 switch (conn
->protocol
.data
.state_id
) {
3590 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3591 status
= relay_process_data_receive_header(conn
);
3593 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3594 status
= relay_process_data_receive_payload(conn
);
3597 ERR("Unexpected data connection communication state.");
3604 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3608 (void) lttng_poll_del(events
, pollfd
);
3610 ret
= close(pollfd
);
3612 ERR("Closing pollfd %d", pollfd
);
3616 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3617 int pollfd
, struct relay_connection
*conn
)
3619 const char *type_str
;
3621 switch (conn
->type
) {
3626 type_str
= "Control";
3628 case RELAY_VIEWER_COMMAND
:
3629 type_str
= "Viewer Command";
3631 case RELAY_VIEWER_NOTIFICATION
:
3632 type_str
= "Viewer Notification";
3635 type_str
= "Unknown";
3637 cleanup_connection_pollfd(events
, pollfd
);
3638 connection_put(conn
);
3639 DBG("%s connection closed with %d", type_str
, pollfd
);
3643 * This thread does the actual work
3645 static void *relay_thread_worker(void *data
)
3647 int ret
, err
= -1, last_seen_data_fd
= -1;
3649 struct lttng_poll_event events
;
3650 struct lttng_ht
*relay_connections_ht
;
3651 struct lttng_ht_iter iter
;
3652 struct relay_connection
*destroy_conn
= NULL
;
3654 DBG("[thread] Relay worker started");
3656 rcu_register_thread();
3658 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3660 if (testpoint(relayd_thread_worker
)) {
3661 goto error_testpoint
;
3664 health_code_update();
3666 /* table of connections indexed on socket */
3667 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3668 if (!relay_connections_ht
) {
3669 goto relay_connections_ht_error
;
3672 ret
= create_thread_poll_set(&events
, 2);
3674 goto error_poll_create
;
3677 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3684 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3686 health_code_update();
3688 /* Infinite blocking call, waiting for transmission */
3689 DBG3("Relayd worker thread polling...");
3690 health_poll_entry();
3691 ret
= lttng_poll_wait(&events
, -1);
3695 * Restart interrupted system call.
3697 if (errno
== EINTR
) {
3706 * Process control. The control connection is
3707 * prioritized so we don't starve it with high
3708 * throughput tracing data on the data connection.
3710 for (i
= 0; i
< nb_fd
; i
++) {
3711 /* Fetch once the poll data */
3712 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3713 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3715 health_code_update();
3717 /* Thread quit pipe has been closed. Killing thread. */
3718 ret
= check_thread_quit_pipe(pollfd
, revents
);
3724 /* Inspect the relay conn pipe for new connection */
3725 if (pollfd
== relay_conn_pipe
[0]) {
3726 if (revents
& LPOLLIN
) {
3727 struct relay_connection
*conn
;
3729 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3733 ret
= lttng_poll_add(&events
,
3735 LPOLLIN
| LPOLLRDHUP
);
3737 ERR("Failed to add new connection file descriptor to poll set");
3740 connection_ht_add(relay_connections_ht
, conn
);
3741 DBG("Connection socket %d added", conn
->sock
->fd
);
3742 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3743 ERR("Relay connection pipe error");
3746 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3750 struct relay_connection
*ctrl_conn
;
3752 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3753 /* If not found, there is a synchronization issue. */
3756 if (ctrl_conn
->type
== RELAY_DATA
) {
3757 if (revents
& LPOLLIN
) {
3759 * Flag the last seen data fd not deleted. It will be
3760 * used as the last seen fd if any fd gets deleted in
3763 last_notdel_data_fd
= pollfd
;
3765 goto put_ctrl_connection
;
3767 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3769 if (revents
& LPOLLIN
) {
3770 enum relay_connection_status status
;
3772 status
= relay_process_control(ctrl_conn
);
3773 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3775 * On socket error flag the session as aborted to force
3776 * the cleanup of its stream otherwise it can leak
3777 * during the lifetime of the relayd.
3779 * This prevents situations in which streams can be
3780 * left opened because an index was received, the
3781 * control connection is closed, and the data
3782 * connection is closed (uncleanly) before the packet's
3785 * Since the control connection encountered an error,
3786 * it is okay to be conservative and close the
3787 * session right now as we can't rely on the protocol
3788 * being respected anymore.
3790 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3791 session_abort(ctrl_conn
->session
);
3794 /* Clear the connection on error or close. */
3795 relay_thread_close_connection(&events
,
3800 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3801 relay_thread_close_connection(&events
,
3803 if (last_seen_data_fd
== pollfd
) {
3804 last_seen_data_fd
= last_notdel_data_fd
;
3807 ERR("Unexpected poll events %u for control sock %d",
3809 connection_put(ctrl_conn
);
3812 put_ctrl_connection
:
3813 connection_put(ctrl_conn
);
3818 * The last loop handled a control request, go back to poll to make
3819 * sure we prioritise the control socket.
3825 if (last_seen_data_fd
>= 0) {
3826 for (i
= 0; i
< nb_fd
; i
++) {
3827 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3829 health_code_update();
3831 if (last_seen_data_fd
== pollfd
) {
3838 /* Process data connection. */
3839 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3840 /* Fetch the poll data. */
3841 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3842 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3843 struct relay_connection
*data_conn
;
3845 health_code_update();
3848 /* No activity for this FD (poll implementation). */
3852 /* Skip the command pipe. It's handled in the first loop. */
3853 if (pollfd
== relay_conn_pipe
[0]) {
3857 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3859 /* Skip it. Might be removed before. */
3862 if (data_conn
->type
== RELAY_CONTROL
) {
3863 goto put_data_connection
;
3865 assert(data_conn
->type
== RELAY_DATA
);
3867 if (revents
& LPOLLIN
) {
3868 enum relay_connection_status status
;
3870 status
= relay_process_data(data_conn
);
3871 /* Connection closed or error. */
3872 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3874 * On socket error flag the session as aborted to force
3875 * the cleanup of its stream otherwise it can leak
3876 * during the lifetime of the relayd.
3878 * This prevents situations in which streams can be
3879 * left opened because an index was received, the
3880 * control connection is closed, and the data
3881 * connection is closed (uncleanly) before the packet's
3884 * Since the data connection encountered an error,
3885 * it is okay to be conservative and close the
3886 * session right now as we can't rely on the protocol
3887 * being respected anymore.
3889 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3890 session_abort(data_conn
->session
);
3892 relay_thread_close_connection(&events
, pollfd
,
3895 * Every goto restart call sets the last seen fd where
3896 * here we don't really care since we gracefully
3897 * continue the loop after the connection is deleted.
3900 /* Keep last seen port. */
3901 last_seen_data_fd
= pollfd
;
3902 connection_put(data_conn
);
3905 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3906 relay_thread_close_connection(&events
, pollfd
,
3909 ERR("Unknown poll events %u for data sock %d",
3912 put_data_connection
:
3913 connection_put(data_conn
);
3915 last_seen_data_fd
= -1;
3918 /* Normal exit, no error */
3923 /* Cleanup remaining connection object. */
3925 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3928 health_code_update();
3930 session_abort(destroy_conn
->session
);
3933 * No need to grab another ref, because we own
3936 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3941 lttng_poll_clean(&events
);
3943 lttng_ht_destroy(relay_connections_ht
);
3944 relay_connections_ht_error
:
3945 /* Close relay conn pipes */
3946 utils_close_pipe(relay_conn_pipe
);
3948 DBG("Thread exited with error");
3950 DBG("Worker thread cleanup complete");
3954 ERR("Health error occurred in %s", __func__
);
3956 health_unregister(health_relayd
);
3957 rcu_unregister_thread();
3958 lttng_relay_stop_threads();
3963 * Create the relay command pipe to wake thread_manage_apps.
3964 * Closed in cleanup().
3966 static int create_relay_conn_pipe(void)
3970 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3978 int main(int argc
, char **argv
)
3980 int ret
= 0, retval
= 0;
3983 /* Parse environment variables */
3984 ret
= parse_env_options();
3992 * Command line arguments overwrite environment.
3995 if (set_options(argc
, argv
)) {
4000 if (set_signal_handler()) {
4005 relayd_config_log();
4007 if (opt_print_version
) {
4013 ret
= fclose(stdin
);
4015 PERROR("Failed to close stdin");
4019 DBG("Clear command %s", opt_allow_clear
? "allowed" : "disallowed");
4021 /* Try to create directory if -o, --output is specified. */
4022 if (opt_output_path
) {
4023 if (*opt_output_path
!= '/') {
4024 ERR("Please specify an absolute path for -o, --output PATH");
4029 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4032 ERR("Unable to create %s", opt_output_path
);
4039 if (opt_daemon
|| opt_background
) {
4042 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4050 * We are in the child. Make sure all other file
4051 * descriptors are closed, in case we are called with
4052 * more opened file descriptors than the standard ones.
4054 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
4059 if (opt_working_directory
) {
4060 ret
= utils_change_working_directory(opt_working_directory
);
4062 /* All errors are already logged. */
4067 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
4068 if (!sessiond_trace_chunk_registry
) {
4069 ERR("Failed to initialize session daemon trace chunk registry");
4074 /* Initialize thread health monitoring */
4075 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4076 if (!health_relayd
) {
4077 PERROR("health_app_create error");
4082 /* Create thread quit pipe */
4083 if (init_thread_quit_pipe()) {
4088 /* Setup the thread apps communication pipe. */
4089 if (create_relay_conn_pipe()) {
4094 /* Init relay command queue. */
4095 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4097 /* Initialize communication library */
4099 lttcomm_inet_init();
4101 /* tables of sessions indexed by session ID */
4102 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4108 /* tables of streams indexed by stream ID */
4109 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4110 if (!relay_streams_ht
) {
4115 /* tables of streams indexed by stream ID */
4116 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4117 if (!viewer_streams_ht
) {
4122 ret
= utils_create_pipe(health_quit_pipe
);
4128 /* Create thread to manage the client socket */
4129 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4130 thread_manage_health
, (void *) NULL
);
4133 PERROR("pthread_create health");
4138 /* Setup the dispatcher thread */
4139 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4140 relay_thread_dispatcher
, (void *) NULL
);
4143 PERROR("pthread_create dispatcher");
4145 goto exit_dispatcher_thread
;
4148 /* Setup the worker thread */
4149 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4150 relay_thread_worker
, NULL
);
4153 PERROR("pthread_create worker");
4155 goto exit_worker_thread
;
4158 /* Setup the listener thread */
4159 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4160 relay_thread_listener
, (void *) NULL
);
4163 PERROR("pthread_create listener");
4165 goto exit_listener_thread
;
4168 ret
= relayd_live_create(live_uri
);
4170 ERR("Starting live viewer threads");
4176 * This is where we start awaiting program completion (e.g. through
4177 * signal that asks threads to teardown).
4180 ret
= relayd_live_join();
4186 ret
= pthread_join(listener_thread
, &status
);
4189 PERROR("pthread_join listener_thread");
4193 exit_listener_thread
:
4194 ret
= pthread_join(worker_thread
, &status
);
4197 PERROR("pthread_join worker_thread");
4202 ret
= pthread_join(dispatcher_thread
, &status
);
4205 PERROR("pthread_join dispatcher_thread");
4208 exit_dispatcher_thread
:
4210 ret
= pthread_join(health_thread
, &status
);
4213 PERROR("pthread_join health_thread");
4218 * Wait for all pending call_rcu work to complete before tearing
4219 * down data structures. call_rcu worker may be trying to
4220 * perform lookups in those structures.
4225 /* Ensure all prior call_rcu are done. */