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>
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/align.h>
60 #include <common/config/session-config.h>
61 #include <common/dynamic-buffer.h>
62 #include <common/buffer-view.h>
63 #include <common/fd-tracker/utils.h>
64 #include <urcu/rculist.h>
67 #include "ctf-trace.h"
70 #include "lttng-relayd.h"
72 #include "health-relayd.h"
73 #include "testpoint.h"
74 #include "viewer-stream.h"
77 #include "connection.h"
78 #include "tracefile-array.h"
79 #include "tcp_keep_alive.h"
81 static const char *help_msg
=
82 #ifdef LTTNG_EMBED_HELP
83 #include <lttng-relayd.8.h>
89 enum relay_connection_status
{
90 RELAY_CONNECTION_STATUS_OK
,
91 /* An error occured while processing an event on the connection. */
92 RELAY_CONNECTION_STATUS_ERROR
,
93 /* Connection closed/shutdown cleanly. */
94 RELAY_CONNECTION_STATUS_CLOSED
,
97 /* command line options */
98 char *opt_output_path
;
99 static int opt_daemon
, opt_background
;
102 * We need to wait for listener and live listener threads, as well as
103 * health check thread, before being ready to signal readiness.
105 #define NR_LTTNG_RELAY_READY 3
106 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
108 /* Size of receive buffer. */
109 #define RECV_DATA_BUFFER_SIZE 65536
110 #define FILE_COPY_BUFFER_SIZE 65536
112 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
113 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
115 static struct lttng_uri
*control_uri
;
116 static struct lttng_uri
*data_uri
;
117 static struct lttng_uri
*live_uri
;
119 const char *progname
;
121 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
122 static int tracing_group_name_override
;
124 const char * const config_section_name
= "relayd";
127 * Quit pipe for all threads. This permits a single cancellation point
128 * for all threads when receiving an event on the pipe.
130 int thread_quit_pipe
[2] = { -1, -1 };
133 * This pipe is used to inform the worker thread that a command is queued and
134 * ready to be processed.
136 static int relay_conn_pipe
[2] = { -1, -1 };
138 /* Shared between threads */
139 static int dispatch_thread_exit
;
141 static pthread_t listener_thread
;
142 static pthread_t dispatcher_thread
;
143 static pthread_t worker_thread
;
144 static pthread_t health_thread
;
147 * last_relay_stream_id_lock protects last_relay_stream_id increment
148 * atomicity on 32-bit architectures.
150 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
151 static uint64_t last_relay_stream_id
;
154 * Relay command queue.
156 * The relay_thread_listener and relay_thread_dispatcher communicate with this
159 static struct relay_conn_queue relay_conn_queue
;
161 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
162 static unsigned int lttng_opt_fd_pool_size
= -1;
164 /* Global relay stream hash table. */
165 struct lttng_ht
*relay_streams_ht
;
167 /* Global relay viewer stream hash table. */
168 struct lttng_ht
*viewer_streams_ht
;
170 /* Global relay sessions hash table. */
171 struct lttng_ht
*sessions_ht
;
173 /* Relayd health monitoring */
174 struct health_app
*health_relayd
;
176 /* Global fd tracker. */
177 struct fd_tracker
*the_fd_tracker
;
179 static struct option long_options
[] = {
180 { "control-port", 1, 0, 'C', },
181 { "data-port", 1, 0, 'D', },
182 { "live-port", 1, 0, 'L', },
183 { "daemonize", 0, 0, 'd', },
184 { "background", 0, 0, 'b', },
185 { "group", 1, 0, 'g', },
186 { "fd-pool-size", 1, 0, '\0', },
187 { "help", 0, 0, 'h', },
188 { "output", 1, 0, 'o', },
189 { "verbose", 0, 0, 'v', },
190 { "config", 1, 0, 'f' },
191 { "version", 0, 0, 'V' },
195 static const char *config_ignore_options
[] = { "help", "config", "version" };
198 * Take an option from the getopt output and set it in the right variable to be
201 * Return 0 on success else a negative value.
203 static int set_option(int opt
, const char *arg
, const char *optname
)
209 if (!strcmp(optname
, "fd-pool-size")) {
213 v
= strtoul(arg
, NULL
, 0);
214 if (errno
!= 0 || !isdigit(arg
[0])) {
215 ERR("Wrong value in --fd-pool-size parameter: %s", arg
);
220 ERR("File descriptor cap overflow in --fd-pool-size parameter: %s", arg
);
224 lttng_opt_fd_pool_size
= (unsigned int) v
;
226 fprintf(stderr
, "unknown option %s", optname
);
228 fprintf(stderr
, " with arg %s\n", arg
);
233 if (lttng_is_setuid_setgid()) {
234 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
235 "-C, --control-port");
237 ret
= uri_parse(arg
, &control_uri
);
239 ERR("Invalid control URI specified");
242 if (control_uri
->port
== 0) {
243 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
248 if (lttng_is_setuid_setgid()) {
249 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
252 ret
= uri_parse(arg
, &data_uri
);
254 ERR("Invalid data URI specified");
257 if (data_uri
->port
== 0) {
258 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
263 if (lttng_is_setuid_setgid()) {
264 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
267 ret
= uri_parse(arg
, &live_uri
);
269 ERR("Invalid live URI specified");
272 if (live_uri
->port
== 0) {
273 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
288 tracing_group_name
= strdup(arg
);
289 if (tracing_group_name
== NULL
) {
294 tracing_group_name_override
= 1;
298 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
300 ERR("Cannot show --help for `lttng-relayd`");
305 fprintf(stdout
, "%s\n", VERSION
);
308 if (lttng_is_setuid_setgid()) {
309 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
312 ret
= asprintf(&opt_output_path
, "%s", arg
);
315 PERROR("asprintf opt_output_path");
321 /* Verbose level can increase using multiple -v */
323 lttng_opt_verbose
= config_parse_value(arg
);
325 /* Only 3 level of verbosity (-vvv). */
326 if (lttng_opt_verbose
< 3) {
327 lttng_opt_verbose
+= 1;
332 /* Unknown option or other error.
333 * Error is printed by getopt, just return */
346 * config_entry_handler_cb used to handle options read from a config file.
347 * See config_entry_handler_cb comment in common/config/session-config.h for the
348 * return value conventions.
350 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
354 if (!entry
|| !entry
->name
|| !entry
->value
) {
359 /* Check if the option is to be ignored */
360 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
361 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
366 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
367 /* Ignore if entry name is not fully matched. */
368 if (strcmp(entry
->name
, long_options
[i
].name
)) {
373 * If the option takes no argument on the command line,
374 * we have to check if the value is "true". We support
375 * non-zero numeric values, true, on and yes.
377 if (!long_options
[i
].has_arg
) {
378 ret
= config_parse_value(entry
->value
);
381 WARN("Invalid configuration value \"%s\" for option %s",
382 entry
->value
, entry
->name
);
384 /* False, skip boolean config option. */
389 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
393 WARN("Unrecognized option \"%s\" in daemon configuration file.",
400 static int set_fd_pool_size(void)
403 struct rlimit rlimit
;
405 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
407 PERROR("Failed to get file descriptor limit");
412 DBG("File descriptor count limits are %" PRIu64
" (soft) and %" PRIu64
" (hard)",
413 (uint64_t) rlimit
.rlim_cur
, (uint64_t) rlimit
.rlim_max
);
414 if (lttng_opt_fd_pool_size
== -1) {
415 /* Use default value (soft limit - reserve). */
416 if (rlimit
.rlim_cur
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
417 ERR("The process' file number limit is too low (%" PRIu64
"). The process' file number limit must be set to at least %i.",
418 (uint64_t) rlimit
.rlim_cur
,
419 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
423 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
424 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
428 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
429 ERR("File descriptor pool size must be set to at least %d",
430 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
435 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
436 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%lu).",
437 lttng_opt_fd_pool_size
, rlimit
.rlim_cur
);
443 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
444 lttng_opt_fd_pool_size
,
445 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
446 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
451 static int set_options(int argc
, char **argv
)
453 int c
, ret
= 0, option_index
= 0, retval
= 0;
454 int orig_optopt
= optopt
, orig_optind
= optind
;
455 char *default_address
, *optstring
;
456 const char *config_path
= NULL
;
458 optstring
= utils_generate_optstring(long_options
,
459 sizeof(long_options
) / sizeof(struct option
));
465 /* Check for the --config option */
467 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
468 &option_index
)) != -1) {
472 } else if (c
!= 'f') {
476 if (lttng_is_setuid_setgid()) {
477 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
480 config_path
= utils_expand_path(optarg
);
482 ERR("Failed to resolve path: %s", optarg
);
487 ret
= config_get_section_entries(config_path
, config_section_name
,
488 config_entry_handler
, NULL
);
491 ERR("Invalid configuration option at line %i", ret
);
497 /* Reset getopt's global state */
498 optopt
= orig_optopt
;
499 optind
= orig_optind
;
501 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
506 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
513 /* assign default values */
514 if (control_uri
== NULL
) {
515 ret
= asprintf(&default_address
,
516 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
517 DEFAULT_NETWORK_CONTROL_PORT
);
519 PERROR("asprintf default data address");
524 ret
= uri_parse(default_address
, &control_uri
);
525 free(default_address
);
527 ERR("Invalid control URI specified");
532 if (data_uri
== NULL
) {
533 ret
= asprintf(&default_address
,
534 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
535 DEFAULT_NETWORK_DATA_PORT
);
537 PERROR("asprintf default data address");
542 ret
= uri_parse(default_address
, &data_uri
);
543 free(default_address
);
545 ERR("Invalid data URI specified");
550 if (live_uri
== NULL
) {
551 ret
= asprintf(&default_address
,
552 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
553 DEFAULT_NETWORK_VIEWER_PORT
);
555 PERROR("asprintf default viewer control address");
560 ret
= uri_parse(default_address
, &live_uri
);
561 free(default_address
);
563 ERR("Invalid viewer control URI specified");
568 ret
= set_fd_pool_size();
579 static void print_global_objects(void)
581 print_viewer_streams();
582 print_relay_streams();
589 static void relayd_cleanup(void)
591 print_global_objects();
595 if (viewer_streams_ht
)
596 lttng_ht_destroy(viewer_streams_ht
);
597 if (relay_streams_ht
)
598 lttng_ht_destroy(relay_streams_ht
);
600 lttng_ht_destroy(sessions_ht
);
602 /* free the dynamically allocated opt_output_path */
603 free(opt_output_path
);
605 /* Close thread quit pipes */
606 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
608 uri_free(control_uri
);
610 /* Live URI is freed in the live thread. */
612 if (tracing_group_name_override
) {
613 free((void *) tracing_group_name
);
618 * Write to writable pipe used to notify a thread.
620 static int notify_thread_pipe(int wpipe
)
624 ret
= lttng_write(wpipe
, "!", 1);
626 PERROR("write poll pipe");
634 static int notify_health_quit_pipe(int *pipe
)
638 ret
= lttng_write(pipe
[1], "4", 1);
640 PERROR("write relay health quit");
649 * Stop all relayd and relayd-live threads.
651 int lttng_relay_stop_threads(void)
655 /* Stopping all threads */
656 DBG("Terminating all threads");
657 if (notify_thread_pipe(thread_quit_pipe
[1])) {
658 ERR("write error on thread quit pipe");
662 if (notify_health_quit_pipe(health_quit_pipe
)) {
663 ERR("write error on health quit pipe");
666 /* Dispatch thread */
667 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
668 futex_nto1_wake(&relay_conn_queue
.futex
);
670 if (relayd_live_stop()) {
671 ERR("Error stopping live threads");
678 * Signal handler for the daemon
680 * Simply stop all worker threads, leaving main() return gracefully after
681 * joining all threads and calling cleanup().
683 static void sighandler(int sig
)
687 DBG("SIGINT caught");
688 if (lttng_relay_stop_threads()) {
689 ERR("Error stopping threads");
693 DBG("SIGTERM caught");
694 if (lttng_relay_stop_threads()) {
695 ERR("Error stopping threads");
699 CMM_STORE_SHARED(recv_child_signal
, 1);
707 * Setup signal handler for :
708 * SIGINT, SIGTERM, SIGPIPE
710 static int set_signal_handler(void)
716 if ((ret
= sigemptyset(&sigset
)) < 0) {
717 PERROR("sigemptyset");
724 sa
.sa_handler
= sighandler
;
725 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
730 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
735 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
740 sa
.sa_handler
= SIG_IGN
;
741 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
746 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
751 void lttng_relay_notify_ready(void)
753 /* Notify the parent of the fork() process that we are ready. */
754 if (opt_daemon
|| opt_background
) {
755 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
756 kill(child_ppid
, SIGUSR1
);
762 * Init thread quit pipe.
764 * Return -1 on error or 0 if all pipes are created.
766 static int init_thread_quit_pipe(void)
768 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
769 "Quit pipe", thread_quit_pipe
);
773 * Init health quit pipe.
775 * Return -1 on error or 0 if all pipes are created.
777 static int init_health_quit_pipe(void)
779 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
780 "Health quit pipe", health_quit_pipe
);
784 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
786 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
787 int size
, const char *name
)
791 if (events
== NULL
|| size
== 0) {
796 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
797 name
, events
, 1, LTTNG_CLOEXEC
);
800 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
812 * Check if the thread quit pipe was triggered.
814 * Return 1 if it was triggered else 0;
816 static int check_thread_quit_pipe(int fd
, uint32_t events
)
818 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
825 static int create_sock(void *data
, int *out_fd
)
828 struct lttcomm_sock
*sock
= data
;
830 ret
= lttcomm_create_sock(sock
);
840 static int close_sock(void *data
, int *in_fd
)
842 struct lttcomm_sock
*sock
= data
;
844 return sock
->ops
->close(sock
);
847 static int accept_sock(void *data
, int *out_fd
)
850 /* Socks is an array of in_sock, out_sock. */
851 struct lttcomm_sock
**socks
= data
;
852 struct lttcomm_sock
*in_sock
= socks
[0];
854 socks
[1] = in_sock
->ops
->accept(in_sock
);
859 *out_fd
= socks
[1]->fd
;
865 * Create and init socket from uri.
867 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
871 struct lttcomm_sock
*sock
= NULL
;
872 char uri_str
[PATH_MAX
];
873 char *formated_name
= NULL
;
875 sock
= lttcomm_alloc_sock_from_uri(uri
);
877 ERR("Allocating socket");
882 * Don't fail to create the socket if the name can't be built as it is
883 * only used for debugging purposes.
885 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
886 uri_str
[sizeof(uri_str
) - 1] = '\0';
888 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
891 formated_name
= NULL
;
895 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
896 (const char **) (formated_name
? &formated_name
: NULL
),
897 1, create_sock
, sock
);
899 DBG("Listening on %s socket %d", name
, sock
->fd
);
901 ret
= sock
->ops
->bind(sock
);
903 PERROR("Failed to bind socket");
907 ret
= sock
->ops
->listen(sock
, -1);
917 lttcomm_destroy_sock(sock
);
923 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
927 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
928 struct lttcomm_sock
*new_sock
= NULL
;
930 ret
= fd_tracker_open_unsuspendable_fd(
931 the_fd_tracker
, &out_fd
,
932 (const char **) &name
,
933 1, accept_sock
, &socks
);
938 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
944 * This thread manages the listening for new connections on the network
946 static void *relay_thread_listener(void *data
)
948 int i
, ret
, pollfd
, err
= -1;
949 uint32_t revents
, nb_fd
;
950 struct lttng_poll_event events
;
951 struct lttcomm_sock
*control_sock
, *data_sock
;
953 DBG("[thread] Relay listener started");
955 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
957 health_code_update();
959 control_sock
= relay_socket_create(control_uri
, "Control listener");
961 goto error_sock_control
;
964 data_sock
= relay_socket_create(data_uri
, "Data listener");
966 goto error_sock_relay
;
970 * Pass 3 as size here for the thread quit pipe, control and
973 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
975 goto error_create_poll
;
978 /* Add the control socket */
979 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
984 /* Add the data socket */
985 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
990 lttng_relay_notify_ready();
992 if (testpoint(relayd_thread_listener
)) {
993 goto error_testpoint
;
997 health_code_update();
999 DBG("Listener accepting connections");
1002 health_poll_entry();
1003 ret
= lttng_poll_wait(&events
, -1);
1007 * Restart interrupted system call.
1009 if (errno
== EINTR
) {
1017 DBG("Relay new connection received");
1018 for (i
= 0; i
< nb_fd
; i
++) {
1019 health_code_update();
1021 /* Fetch once the poll data */
1022 revents
= LTTNG_POLL_GETEV(&events
, i
);
1023 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1027 * No activity for this FD (poll
1033 /* Thread quit pipe has been closed. Killing thread. */
1034 ret
= check_thread_quit_pipe(pollfd
, revents
);
1040 if (revents
& LPOLLIN
) {
1042 * A new connection is requested, therefore a
1043 * sessiond/consumerd connection is allocated in
1044 * this thread, enqueued to a global queue and
1045 * dequeued (and freed) in the worker thread.
1048 struct relay_connection
*new_conn
;
1049 struct lttcomm_sock
*newsock
= NULL
;
1050 enum connection_type type
;
1052 if (pollfd
== data_sock
->fd
) {
1054 newsock
= accept_relayd_sock(data_sock
,
1055 "Data socket to relayd");
1057 assert(pollfd
== control_sock
->fd
);
1058 type
= RELAY_CONTROL
;
1059 newsock
= accept_relayd_sock(control_sock
,
1060 "Control socket to relayd");
1063 PERROR("accepting sock");
1067 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1070 PERROR("setsockopt inet");
1071 lttcomm_destroy_sock(newsock
);
1075 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1077 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1079 lttcomm_destroy_sock(newsock
);
1083 new_conn
= connection_create(newsock
, type
);
1085 lttcomm_destroy_sock(newsock
);
1089 /* Enqueue request for the dispatcher thread. */
1090 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1094 * Wake the dispatch queue futex.
1095 * Implicit memory barrier with the
1096 * exchange in cds_wfcq_enqueue.
1098 futex_nto1_wake(&relay_conn_queue
.futex
);
1099 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1100 ERR("socket poll error");
1103 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1113 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1115 if (data_sock
->fd
>= 0) {
1116 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1117 &data_sock
->fd
, 1, close_sock
,
1123 lttcomm_destroy_sock(data_sock
);
1125 if (control_sock
->fd
>= 0) {
1126 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1127 &control_sock
->fd
, 1, close_sock
,
1133 lttcomm_destroy_sock(control_sock
);
1137 ERR("Health error occurred in %s", __func__
);
1139 health_unregister(health_relayd
);
1140 DBG("Relay listener thread cleanup complete");
1141 lttng_relay_stop_threads();
1146 * This thread manages the dispatching of the requests to worker threads
1148 static void *relay_thread_dispatcher(void *data
)
1152 struct cds_wfcq_node
*node
;
1153 struct relay_connection
*new_conn
= NULL
;
1155 DBG("[thread] Relay dispatcher started");
1157 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1159 if (testpoint(relayd_thread_dispatcher
)) {
1160 goto error_testpoint
;
1163 health_code_update();
1166 health_code_update();
1168 /* Atomically prepare the queue futex */
1169 futex_nto1_prepare(&relay_conn_queue
.futex
);
1171 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1176 health_code_update();
1178 /* Dequeue commands */
1179 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1180 &relay_conn_queue
.tail
);
1182 DBG("Woken up but nothing in the relay command queue");
1183 /* Continue thread execution */
1186 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1188 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1191 * Inform worker thread of the new request. This
1192 * call is blocking so we can be assured that
1193 * the data will be read at some point in time
1194 * or wait to the end of the world :)
1196 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1198 PERROR("write connection pipe");
1199 connection_put(new_conn
);
1202 } while (node
!= NULL
);
1204 /* Futex wait on queue. Blocking call on futex() */
1205 health_poll_entry();
1206 futex_nto1_wait(&relay_conn_queue
.futex
);
1210 /* Normal exit, no error */
1217 ERR("Health error occurred in %s", __func__
);
1219 health_unregister(health_relayd
);
1220 DBG("Dispatch thread dying");
1221 lttng_relay_stop_threads();
1226 * Set index data from the control port to a given index object.
1228 static int set_index_control_data(struct relay_index
*index
,
1229 struct lttcomm_relayd_index
*data
,
1230 struct relay_connection
*conn
)
1232 struct ctf_packet_index index_data
;
1235 * The index on disk is encoded in big endian.
1237 index_data
.packet_size
= htobe64(data
->packet_size
);
1238 index_data
.content_size
= htobe64(data
->content_size
);
1239 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1240 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1241 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1242 index_data
.stream_id
= htobe64(data
->stream_id
);
1244 if (conn
->minor
>= 8) {
1245 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1246 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1249 return relay_index_set_data(index
, &index_data
);
1253 * Handle the RELAYD_CREATE_SESSION command.
1255 * On success, send back the session id or else return a negative value.
1257 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1258 struct relay_connection
*conn
,
1259 const struct lttng_buffer_view
*payload
)
1263 struct relay_session
*session
;
1264 struct lttcomm_relayd_status_session reply
;
1265 char session_name
[LTTNG_NAME_MAX
];
1266 char hostname
[LTTNG_HOST_NAME_MAX
];
1267 uint32_t live_timer
= 0;
1268 bool snapshot
= false;
1270 memset(session_name
, 0, LTTNG_NAME_MAX
);
1271 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1273 memset(&reply
, 0, sizeof(reply
));
1275 if (conn
->minor
< 4) {
1276 /* From 2.1 to 2.3 */
1278 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1279 /* From 2.4 to 2.10 */
1280 ret
= cmd_create_session_2_4(payload
, session_name
,
1281 hostname
, &live_timer
, &snapshot
);
1283 /* From 2.11 to ... */
1284 ret
= cmd_create_session_2_11(payload
, session_name
,
1285 hostname
, &live_timer
, &snapshot
);
1292 session
= session_create(session_name
, hostname
, live_timer
,
1293 snapshot
, conn
->major
, conn
->minor
);
1298 assert(!conn
->session
);
1299 conn
->session
= session
;
1300 DBG("Created session %" PRIu64
, session
->id
);
1302 reply
.session_id
= htobe64(session
->id
);
1306 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1308 reply
.ret_code
= htobe32(LTTNG_OK
);
1311 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1312 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1313 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1322 * When we have received all the streams and the metadata for a channel,
1323 * we make them visible to the viewer threads.
1325 static void publish_connection_local_streams(struct relay_connection
*conn
)
1327 struct relay_stream
*stream
;
1328 struct relay_session
*session
= conn
->session
;
1331 * We publish all streams belonging to a session atomically wrt
1334 pthread_mutex_lock(&session
->lock
);
1336 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1338 stream_publish(stream
);
1343 * Inform the viewer that there are new streams in the session.
1345 if (session
->viewer_attached
) {
1346 uatomic_set(&session
->new_streams
, 1);
1348 pthread_mutex_unlock(&session
->lock
);
1352 * relay_add_stream: allocate a new stream for a session
1354 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1355 struct relay_connection
*conn
,
1356 const struct lttng_buffer_view
*payload
)
1360 struct relay_session
*session
= conn
->session
;
1361 struct relay_stream
*stream
= NULL
;
1362 struct lttcomm_relayd_status_stream reply
;
1363 struct ctf_trace
*trace
= NULL
;
1364 uint64_t stream_handle
= -1ULL;
1365 char *path_name
= NULL
, *channel_name
= NULL
;
1366 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1367 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1369 if (!session
|| !conn
->version_check_done
) {
1370 ERR("Trying to add a stream before version check");
1372 goto end_no_session
;
1375 if (session
->minor
== 1) {
1377 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1379 } else if (session
->minor
> 1 && session
->minor
< 11) {
1380 /* From 2.2 to 2.10 */
1381 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1382 &channel_name
, &tracefile_size
, &tracefile_count
);
1384 /* From 2.11 to ... */
1385 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1386 &channel_name
, &tracefile_size
, &tracefile_count
,
1387 &stream_chunk_id
.value
);
1388 stream_chunk_id
.is_set
= true;
1395 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1399 /* This stream here has one reference on the trace. */
1401 pthread_mutex_lock(&last_relay_stream_id_lock
);
1402 stream_handle
= ++last_relay_stream_id
;
1403 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1405 /* We pass ownership of path_name and channel_name. */
1406 stream
= stream_create(trace
, stream_handle
, path_name
,
1407 channel_name
, tracefile_size
, tracefile_count
,
1410 channel_name
= NULL
;
1413 * Streams are the owners of their trace. Reference to trace is
1414 * kept within stream_create().
1416 ctf_trace_put(trace
);
1419 memset(&reply
, 0, sizeof(reply
));
1420 reply
.handle
= htobe64(stream_handle
);
1422 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1424 reply
.ret_code
= htobe32(LTTNG_OK
);
1427 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1428 sizeof(struct lttcomm_relayd_status_stream
), 0);
1429 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1430 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1442 * relay_close_stream: close a specific stream
1444 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1445 struct relay_connection
*conn
,
1446 const struct lttng_buffer_view
*payload
)
1450 struct relay_session
*session
= conn
->session
;
1451 struct lttcomm_relayd_close_stream stream_info
;
1452 struct lttcomm_relayd_generic_reply reply
;
1453 struct relay_stream
*stream
;
1455 DBG("Close stream received");
1457 if (!session
|| !conn
->version_check_done
) {
1458 ERR("Trying to close a stream before version check");
1460 goto end_no_session
;
1463 if (payload
->size
< sizeof(stream_info
)) {
1464 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1465 sizeof(stream_info
), payload
->size
);
1467 goto end_no_session
;
1469 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1470 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1471 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1473 stream
= stream_get_by_id(stream_info
.stream_id
);
1480 * Set last_net_seq_num before the close flag. Required by data
1483 pthread_mutex_lock(&stream
->lock
);
1484 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1485 pthread_mutex_unlock(&stream
->lock
);
1488 * This is one of the conditions which may trigger a stream close
1489 * with the others being:
1490 * 1) A close command is received for a stream
1491 * 2) The control connection owning the stream is closed
1492 * 3) We have received all of the stream's data _after_ a close
1495 try_stream_close(stream
);
1496 if (stream
->is_metadata
) {
1497 struct relay_viewer_stream
*vstream
;
1499 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1501 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1503 * Since all the metadata has been sent to the
1504 * viewer and that we have a request to close
1505 * its stream, we can safely teardown the
1506 * corresponding metadata viewer stream.
1508 viewer_stream_put(vstream
);
1510 /* Put local reference. */
1511 viewer_stream_put(vstream
);
1518 memset(&reply
, 0, sizeof(reply
));
1520 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1522 reply
.ret_code
= htobe32(LTTNG_OK
);
1524 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1525 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1526 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1527 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1537 * relay_reset_metadata: reset a metadata stream
1540 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1541 struct relay_connection
*conn
,
1542 const struct lttng_buffer_view
*payload
)
1546 struct relay_session
*session
= conn
->session
;
1547 struct lttcomm_relayd_reset_metadata stream_info
;
1548 struct lttcomm_relayd_generic_reply reply
;
1549 struct relay_stream
*stream
;
1551 DBG("Reset metadata received");
1553 if (!session
|| !conn
->version_check_done
) {
1554 ERR("Trying to reset a metadata stream before version check");
1556 goto end_no_session
;
1559 if (payload
->size
< sizeof(stream_info
)) {
1560 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1561 sizeof(stream_info
), payload
->size
);
1563 goto end_no_session
;
1565 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1566 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1567 stream_info
.version
= be64toh(stream_info
.version
);
1569 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1571 /* Unsupported for live sessions for now. */
1572 if (session
->live_timer
!= 0) {
1577 stream
= stream_get_by_id(stream_info
.stream_id
);
1582 pthread_mutex_lock(&stream
->lock
);
1583 if (!stream
->is_metadata
) {
1588 ret
= stream_fd_rotate(stream
->stream_fd
,
1589 stream
->path_name
, stream
->channel_name
, 0, 0, NULL
);
1591 ERR("Failed to rotate metadata file %s of channel %s",
1592 stream
->path_name
, stream
->channel_name
);
1597 pthread_mutex_unlock(&stream
->lock
);
1601 memset(&reply
, 0, sizeof(reply
));
1603 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1605 reply
.ret_code
= htobe32(LTTNG_OK
);
1607 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1608 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1609 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1610 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1620 * relay_unknown_command: send -1 if received unknown command
1622 static void relay_unknown_command(struct relay_connection
*conn
)
1624 struct lttcomm_relayd_generic_reply reply
;
1627 memset(&reply
, 0, sizeof(reply
));
1628 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1629 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1630 if (send_ret
< sizeof(reply
)) {
1631 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1636 * relay_start: send an acknowledgment to the client to tell if we are
1637 * ready to receive data. We are ready if a session is established.
1639 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1640 struct relay_connection
*conn
,
1641 const struct lttng_buffer_view
*payload
)
1645 struct lttcomm_relayd_generic_reply reply
;
1646 struct relay_session
*session
= conn
->session
;
1649 DBG("Trying to start the streaming without a session established");
1650 ret
= htobe32(LTTNG_ERR_UNK
);
1653 memset(&reply
, 0, sizeof(reply
));
1654 reply
.ret_code
= htobe32(LTTNG_OK
);
1655 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1657 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1658 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1667 * Append padding to the file pointed by the file descriptor fd.
1669 static int write_padding_to_file(int fd
, uint32_t size
)
1678 zeros
= zmalloc(size
);
1679 if (zeros
== NULL
) {
1680 PERROR("zmalloc zeros for padding");
1685 ret
= lttng_write(fd
, zeros
, size
);
1687 PERROR("write padding to file");
1697 * Close the current index file if it is open, and create a new one.
1699 * Return 0 on success, -1 on error.
1702 int create_rotate_index_file(struct relay_stream
*stream
)
1705 uint32_t major
, minor
;
1707 /* Put ref on previous index_file. */
1708 if (stream
->index_file
) {
1709 relay_index_file_put(stream
->index_file
);
1710 stream
->index_file
= NULL
;
1712 major
= stream
->trace
->session
->major
;
1713 minor
= stream
->trace
->session
->minor
;
1714 stream
->index_file
= relay_index_file_create(stream
->path_name
,
1715 stream
->channel_name
,
1716 stream
->tracefile_size
,
1717 tracefile_array_get_file_index_head(stream
->tfa
),
1718 lttng_to_index_major(major
, minor
),
1719 lttng_to_index_minor(major
, minor
));
1720 if (!stream
->index_file
) {
1732 int do_rotate_stream(struct relay_stream
*stream
)
1736 /* Perform the stream rotation. */
1737 ret
= stream_fd_rotate(stream
->stream_fd
, stream
->path_name
,
1738 stream
->channel_name
, stream
->tracefile_size
,
1739 stream
->tracefile_count
, NULL
);
1741 ERR("Rotating stream output file");
1744 stream
->tracefile_size_current
= 0;
1746 /* Rotate also the index if the stream is not a metadata stream. */
1747 if (!stream
->is_metadata
) {
1748 ret
= create_rotate_index_file(stream
);
1750 ERR("Failed to rotate index file");
1755 stream
->rotate_at_seq_num
= -1ULL;
1756 stream
->pos_after_last_complete_data_index
= 0;
1763 * If too much data has been written in a tracefile before we received the
1764 * rotation command, we have to move the excess data to the new tracefile and
1765 * perform the rotation. This can happen because the control and data
1766 * connections are separate, the indexes as well as the commands arrive from
1767 * the control connection and we have no control over the order so we could be
1768 * in a situation where too much data has been received on the data connection
1769 * before the rotation command on the control connection arrives. We don't need
1770 * to update the index because its order is guaranteed with the rotation
1774 int rotate_truncate_stream(struct relay_stream
*stream
)
1776 int ret
, old_fd
= -1, new_fd
= -1;
1778 uint64_t diff
, pos
= 0;
1779 char buf
[FILE_COPY_BUFFER_SIZE
];
1780 struct stream_fd
*new_stream_fd
= NULL
;
1782 assert(!stream
->is_metadata
);
1784 assert(stream
->tracefile_size_current
>
1785 stream
->pos_after_last_complete_data_index
);
1786 diff
= stream
->tracefile_size_current
-
1787 stream
->pos_after_last_complete_data_index
;
1789 /* Create the new tracefile. */
1790 new_stream_fd
= stream_fd_create(stream
->path_name
, stream
->channel_name
,
1791 stream
->tracefile_size
, stream
->tracefile_count
, NULL
);
1792 if (new_stream_fd
< 0) {
1793 ERR("Failed to create new stream file at path %s for channel %s",
1794 stream
->path_name
, stream
->channel_name
);
1799 old_fd
= stream_fd_get_fd(stream
->stream_fd
);
1805 new_fd
= stream_fd_get_fd(new_stream_fd
);
1812 * Rewind the current tracefile to the position at which the rotation
1813 * should have occured.
1815 lseek_ret
= lseek(old_fd
, stream
->pos_after_last_complete_data_index
,
1817 if (lseek_ret
< 0) {
1818 PERROR("seek truncate stream");
1823 /* Move data from the old file to the new file. */
1824 while (pos
< diff
) {
1825 uint64_t count
, bytes_left
;
1828 bytes_left
= diff
- pos
;
1829 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1830 assert(count
<= SIZE_MAX
);
1832 io_ret
= lttng_read(old_fd
, buf
, count
);
1833 if (io_ret
< (ssize_t
) count
) {
1834 char error_string
[256];
1836 snprintf(error_string
, sizeof(error_string
),
1837 "Failed to read %" PRIu64
" bytes from in rotate_truncate_stream(), returned %zi",
1840 PERROR("%s", error_string
);
1842 ERR("%s", error_string
);
1848 io_ret
= lttng_write(new_fd
, buf
, count
);
1849 if (io_ret
< (ssize_t
) count
) {
1850 char error_string
[256];
1852 snprintf(error_string
, sizeof(error_string
),
1853 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1854 count
, new_fd
, io_ret
);
1856 PERROR("%s", error_string
);
1858 ERR("%s", error_string
);
1867 stream_fd_put_fd(new_stream_fd
);
1870 /* Truncate the file to get rid of the excess data. */
1871 ret
= ftruncate(old_fd
, stream
->pos_after_last_complete_data_index
);
1873 PERROR("ftruncate");
1877 stream_fd_put_fd(stream
->stream_fd
);
1881 * Swap the old stream_fd with the new, releasing the stream's
1884 stream_fd_put(stream
->stream_fd
);
1885 stream
->stream_fd
= new_stream_fd
;
1887 ret
= create_rotate_index_file(stream
);
1889 ERR("Rotate stream index file");
1894 * Update the offset and FD of all the eventual indexes created by the
1895 * data connection before the rotation command arrived.
1897 ret
= relay_index_switch_all_files(stream
);
1899 ERR("Failed to rotate index file");
1903 stream
->tracefile_size_current
= diff
;
1904 stream
->pos_after_last_complete_data_index
= 0;
1905 stream
->rotate_at_seq_num
= -1ULL;
1911 stream_fd_put_fd(stream
->stream_fd
);
1914 stream_fd_put_fd(new_stream_fd
);
1921 * Check if a stream should perform a rotation (for session rotation).
1922 * Must be called with the stream lock held.
1924 * Return 0 on success, a negative value on error.
1927 int try_rotate_stream(struct relay_stream
*stream
)
1931 /* No rotation expected. */
1932 if (stream
->rotate_at_seq_num
== -1ULL) {
1936 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1937 stream
->prev_seq
== -1ULL) {
1938 DBG("Stream %" PRIu64
" no yet ready for rotation",
1939 stream
->stream_handle
);
1941 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1942 DBG("Rotation after too much data has been written in tracefile "
1943 "for stream %" PRIu64
", need to truncate before "
1944 "rotating", stream
->stream_handle
);
1945 ret
= rotate_truncate_stream(stream
);
1947 ERR("Failed to truncate stream");
1951 /* stream->prev_seq == stream->rotate_at_seq_num */
1952 DBG("Stream %" PRIu64
" ready for rotation",
1953 stream
->stream_handle
);
1954 ret
= do_rotate_stream(stream
);
1962 * relay_recv_metadata: receive the metadata for the session.
1964 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1965 struct relay_connection
*conn
,
1966 const struct lttng_buffer_view
*payload
)
1970 struct relay_session
*session
= conn
->session
;
1971 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1972 struct relay_stream
*metadata_stream
;
1973 uint64_t metadata_payload_size
;
1974 int metadata_fd
= -1;
1977 ERR("Metadata sent before version check");
1982 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1983 ERR("Incorrect data size");
1987 metadata_payload_size
= recv_hdr
->data_size
-
1988 sizeof(struct lttcomm_relayd_metadata_payload
);
1990 memcpy(&metadata_payload_header
, payload
->data
,
1991 sizeof(metadata_payload_header
));
1992 metadata_payload_header
.stream_id
= be64toh(
1993 metadata_payload_header
.stream_id
);
1994 metadata_payload_header
.padding_size
= be32toh(
1995 metadata_payload_header
.padding_size
);
1997 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1998 if (!metadata_stream
) {
2003 pthread_mutex_lock(&metadata_stream
->lock
);
2005 metadata_fd
= stream_fd_get_fd(metadata_stream
->stream_fd
);
2006 if (metadata_fd
< 0) {
2009 size_ret
= lttng_write(metadata_fd
,
2010 payload
->data
+ sizeof(metadata_payload_header
),
2011 metadata_payload_size
);
2012 if (size_ret
< metadata_payload_size
) {
2013 ERR("Relay error writing metadata on file");
2018 size_ret
= write_padding_to_file(metadata_fd
,
2019 metadata_payload_header
.padding_size
);
2020 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
2025 metadata_stream
->metadata_received
+=
2026 metadata_payload_size
+ metadata_payload_header
.padding_size
;
2027 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
2028 metadata_stream
->metadata_received
);
2030 ret
= try_rotate_stream(metadata_stream
);
2036 stream_fd_put_fd(metadata_stream
->stream_fd
);
2038 pthread_mutex_unlock(&metadata_stream
->lock
);
2039 stream_put(metadata_stream
);
2045 * relay_send_version: send relayd version number
2047 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
2048 struct relay_connection
*conn
,
2049 const struct lttng_buffer_view
*payload
)
2053 struct lttcomm_relayd_version reply
, msg
;
2054 bool compatible
= true;
2056 conn
->version_check_done
= true;
2058 /* Get version from the other side. */
2059 if (payload
->size
< sizeof(msg
)) {
2060 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2061 sizeof(msg
), payload
->size
);
2066 memcpy(&msg
, payload
->data
, sizeof(msg
));
2067 msg
.major
= be32toh(msg
.major
);
2068 msg
.minor
= be32toh(msg
.minor
);
2070 memset(&reply
, 0, sizeof(reply
));
2071 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2072 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2074 /* Major versions must be the same */
2075 if (reply
.major
!= msg
.major
) {
2076 DBG("Incompatible major versions (%u vs %u), deleting session",
2077 reply
.major
, msg
.major
);
2081 conn
->major
= reply
.major
;
2082 /* We adapt to the lowest compatible version */
2083 if (reply
.minor
<= msg
.minor
) {
2084 conn
->minor
= reply
.minor
;
2086 conn
->minor
= msg
.minor
;
2089 reply
.major
= htobe32(reply
.major
);
2090 reply
.minor
= htobe32(reply
.minor
);
2091 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2093 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2094 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2107 DBG("Version check done using protocol %u.%u", conn
->major
,
2115 * Check for data pending for a given stream id from the session daemon.
2117 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2118 struct relay_connection
*conn
,
2119 const struct lttng_buffer_view
*payload
)
2121 struct relay_session
*session
= conn
->session
;
2122 struct lttcomm_relayd_data_pending msg
;
2123 struct lttcomm_relayd_generic_reply reply
;
2124 struct relay_stream
*stream
;
2128 DBG("Data pending command received");
2130 if (!session
|| !conn
->version_check_done
) {
2131 ERR("Trying to check for data before version check");
2133 goto end_no_session
;
2136 if (payload
->size
< sizeof(msg
)) {
2137 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2138 sizeof(msg
), payload
->size
);
2140 goto end_no_session
;
2142 memcpy(&msg
, payload
->data
, sizeof(msg
));
2143 msg
.stream_id
= be64toh(msg
.stream_id
);
2144 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2146 stream
= stream_get_by_id(msg
.stream_id
);
2147 if (stream
== NULL
) {
2152 pthread_mutex_lock(&stream
->lock
);
2154 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2155 " and last_seq %" PRIu64
, msg
.stream_id
,
2156 stream
->prev_seq
, msg
.last_net_seq_num
);
2158 /* Avoid wrapping issue */
2159 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2160 /* Data has in fact been written and is NOT pending */
2163 /* Data still being streamed thus pending */
2167 stream
->data_pending_check_done
= true;
2168 pthread_mutex_unlock(&stream
->lock
);
2173 memset(&reply
, 0, sizeof(reply
));
2174 reply
.ret_code
= htobe32(ret
);
2175 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2176 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2177 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2187 * Wait for the control socket to reach a quiescent state.
2189 * Note that for now, when receiving this command from the session
2190 * daemon, this means that every subsequent commands or data received on
2191 * the control socket has been handled. So, this is why we simply return
2194 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2195 struct relay_connection
*conn
,
2196 const struct lttng_buffer_view
*payload
)
2200 struct relay_stream
*stream
;
2201 struct lttcomm_relayd_quiescent_control msg
;
2202 struct lttcomm_relayd_generic_reply reply
;
2204 DBG("Checking quiescent state on control socket");
2206 if (!conn
->session
|| !conn
->version_check_done
) {
2207 ERR("Trying to check for data before version check");
2209 goto end_no_session
;
2212 if (payload
->size
< sizeof(msg
)) {
2213 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2214 sizeof(msg
), payload
->size
);
2216 goto end_no_session
;
2218 memcpy(&msg
, payload
->data
, sizeof(msg
));
2219 msg
.stream_id
= be64toh(msg
.stream_id
);
2221 stream
= stream_get_by_id(msg
.stream_id
);
2225 pthread_mutex_lock(&stream
->lock
);
2226 stream
->data_pending_check_done
= true;
2227 pthread_mutex_unlock(&stream
->lock
);
2229 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2232 memset(&reply
, 0, sizeof(reply
));
2233 reply
.ret_code
= htobe32(LTTNG_OK
);
2234 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2235 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2236 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2248 * Initialize a data pending command. This means that a consumer is about
2249 * to ask for data pending for each stream it holds. Simply iterate over
2250 * all streams of a session and set the data_pending_check_done flag.
2252 * This command returns to the client a LTTNG_OK code.
2254 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2255 struct relay_connection
*conn
,
2256 const struct lttng_buffer_view
*payload
)
2260 struct lttng_ht_iter iter
;
2261 struct lttcomm_relayd_begin_data_pending msg
;
2262 struct lttcomm_relayd_generic_reply reply
;
2263 struct relay_stream
*stream
;
2268 DBG("Init streams for data pending");
2270 if (!conn
->session
|| !conn
->version_check_done
) {
2271 ERR("Trying to check for data before version check");
2273 goto end_no_session
;
2276 if (payload
->size
< sizeof(msg
)) {
2277 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2278 sizeof(msg
), payload
->size
);
2280 goto end_no_session
;
2282 memcpy(&msg
, payload
->data
, sizeof(msg
));
2283 msg
.session_id
= be64toh(msg
.session_id
);
2286 * Iterate over all streams to set the begin data pending flag.
2287 * For now, the streams are indexed by stream handle so we have
2288 * to iterate over all streams to find the one associated with
2289 * the right session_id.
2292 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2294 if (!stream_get(stream
)) {
2297 if (stream
->trace
->session
->id
== msg
.session_id
) {
2298 pthread_mutex_lock(&stream
->lock
);
2299 stream
->data_pending_check_done
= false;
2300 pthread_mutex_unlock(&stream
->lock
);
2301 DBG("Set begin data pending flag to stream %" PRIu64
,
2302 stream
->stream_handle
);
2308 memset(&reply
, 0, sizeof(reply
));
2309 /* All good, send back reply. */
2310 reply
.ret_code
= htobe32(LTTNG_OK
);
2312 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2313 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2314 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2326 * End data pending command. This will check, for a given session id, if
2327 * each stream associated with it has its data_pending_check_done flag
2328 * set. If not, this means that the client lost track of the stream but
2329 * the data is still being streamed on our side. In this case, we inform
2330 * the client that data is in flight.
2332 * Return to the client if there is data in flight or not with a ret_code.
2334 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2335 struct relay_connection
*conn
,
2336 const struct lttng_buffer_view
*payload
)
2340 struct lttng_ht_iter iter
;
2341 struct lttcomm_relayd_end_data_pending msg
;
2342 struct lttcomm_relayd_generic_reply reply
;
2343 struct relay_stream
*stream
;
2344 uint32_t is_data_inflight
= 0;
2346 DBG("End data pending command");
2348 if (!conn
->session
|| !conn
->version_check_done
) {
2349 ERR("Trying to check for data before version check");
2351 goto end_no_session
;
2354 if (payload
->size
< sizeof(msg
)) {
2355 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2356 sizeof(msg
), payload
->size
);
2358 goto end_no_session
;
2360 memcpy(&msg
, payload
->data
, sizeof(msg
));
2361 msg
.session_id
= be64toh(msg
.session_id
);
2364 * Iterate over all streams to see if the begin data pending
2368 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2370 if (!stream_get(stream
)) {
2373 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2377 pthread_mutex_lock(&stream
->lock
);
2378 if (!stream
->data_pending_check_done
) {
2379 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2380 is_data_inflight
= 1;
2381 DBG("Data is still in flight for stream %" PRIu64
,
2382 stream
->stream_handle
);
2383 pthread_mutex_unlock(&stream
->lock
);
2388 pthread_mutex_unlock(&stream
->lock
);
2393 memset(&reply
, 0, sizeof(reply
));
2394 /* All good, send back reply. */
2395 reply
.ret_code
= htobe32(is_data_inflight
);
2397 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2398 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2399 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2411 * Receive an index for a specific stream.
2413 * Return 0 on success else a negative value.
2415 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2416 struct relay_connection
*conn
,
2417 const struct lttng_buffer_view
*payload
)
2421 struct relay_session
*session
= conn
->session
;
2422 struct lttcomm_relayd_index index_info
;
2423 struct relay_index
*index
;
2424 struct lttcomm_relayd_generic_reply reply
;
2425 struct relay_stream
*stream
;
2430 DBG("Relay receiving index");
2432 if (!session
|| !conn
->version_check_done
) {
2433 ERR("Trying to close a stream before version check");
2435 goto end_no_session
;
2438 msg_len
= lttcomm_relayd_index_len(
2439 lttng_to_index_major(conn
->major
, conn
->minor
),
2440 lttng_to_index_minor(conn
->major
, conn
->minor
));
2441 if (payload
->size
< msg_len
) {
2442 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2443 msg_len
, payload
->size
);
2445 goto end_no_session
;
2447 memcpy(&index_info
, payload
->data
, msg_len
);
2448 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2449 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2450 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2451 index_info
.content_size
= be64toh(index_info
.content_size
);
2452 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2453 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2454 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2455 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2457 if (conn
->minor
>= 8) {
2458 index_info
.stream_instance_id
=
2459 be64toh(index_info
.stream_instance_id
);
2460 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2463 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2465 ERR("stream_get_by_id not found");
2469 pthread_mutex_lock(&stream
->lock
);
2471 /* Live beacon handling */
2472 if (index_info
.packet_size
== 0) {
2473 DBG("Received live beacon for stream %" PRIu64
,
2474 stream
->stream_handle
);
2477 * Only flag a stream inactive when it has already
2478 * received data and no indexes are in flight.
2480 if (stream
->index_received_seqcount
> 0
2481 && stream
->indexes_in_flight
== 0) {
2482 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2485 goto end_stream_put
;
2487 stream
->beacon_ts_end
= -1ULL;
2490 if (stream
->ctf_stream_id
== -1ULL) {
2491 stream
->ctf_stream_id
= index_info
.stream_id
;
2493 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2496 ERR("relay_index_get_by_id_or_create index NULL");
2497 goto end_stream_put
;
2499 if (set_index_control_data(index
, &index_info
, conn
)) {
2500 ERR("set_index_control_data error");
2501 relay_index_put(index
);
2503 goto end_stream_put
;
2505 ret
= relay_index_try_flush(index
);
2507 tracefile_array_commit_seq(stream
->tfa
);
2508 stream
->index_received_seqcount
++;
2509 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2510 } else if (ret
> 0) {
2514 ERR("relay_index_try_flush error %d", ret
);
2515 relay_index_put(index
);
2520 pthread_mutex_unlock(&stream
->lock
);
2525 memset(&reply
, 0, sizeof(reply
));
2527 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2529 reply
.ret_code
= htobe32(LTTNG_OK
);
2531 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2532 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2533 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2542 * Receive the streams_sent message.
2544 * Return 0 on success else a negative value.
2546 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2547 struct relay_connection
*conn
,
2548 const struct lttng_buffer_view
*payload
)
2552 struct lttcomm_relayd_generic_reply reply
;
2556 DBG("Relay receiving streams_sent");
2558 if (!conn
->session
|| !conn
->version_check_done
) {
2559 ERR("Trying to close a stream before version check");
2561 goto end_no_session
;
2565 * Publish every pending stream in the connection recv list which are
2566 * now ready to be used by the viewer.
2568 publish_connection_local_streams(conn
);
2570 memset(&reply
, 0, sizeof(reply
));
2571 reply
.ret_code
= htobe32(LTTNG_OK
);
2572 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2573 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2574 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2587 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2588 * rotation feature (not the tracefile rotation feature).
2590 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2591 struct relay_connection
*conn
,
2592 const struct lttng_buffer_view
*payload
)
2596 struct relay_session
*session
= conn
->session
;
2597 struct lttcomm_relayd_rotate_stream stream_info
;
2598 struct lttcomm_relayd_generic_reply reply
;
2599 struct relay_stream
*stream
;
2602 struct lttng_buffer_view new_path_view
;
2604 DBG("Rotate stream received");
2606 if (!session
|| !conn
->version_check_done
) {
2607 ERR("Trying to rotate a stream before version check");
2612 if (session
->major
== 2 && session
->minor
< 11) {
2613 ERR("Unsupported feature before 2.11");
2618 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2620 if (payload
->size
< header_len
) {
2621 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2622 header_len
, payload
->size
);
2627 memcpy(&stream_info
, payload
->data
, header_len
);
2629 /* Convert to host */
2630 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2631 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2632 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2633 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2635 path_len
= stream_info
.pathname_length
;
2636 if (payload
->size
< header_len
+ path_len
) {
2637 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2638 header_len
+ path_len
, payload
->size
);
2643 /* Ensure it fits in local filename length. */
2644 if (path_len
>= LTTNG_PATH_MAX
) {
2645 ret
= -ENAMETOOLONG
;
2646 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2647 path_len
, LTTNG_PATH_MAX
);
2651 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2652 stream_info
.pathname_length
);
2654 stream
= stream_get_by_id(stream_info
.stream_id
);
2660 pthread_mutex_lock(&stream
->lock
);
2663 * Update the trace path (just the folder, the stream name does not
2666 free(stream
->path_name
);
2667 stream
->path_name
= create_output_path(new_path_view
.data
);
2668 if (!stream
->path_name
) {
2669 ERR("Failed to create a new output path");
2671 goto end_stream_unlock
;
2673 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2676 ERR("relay creating output directory");
2678 goto end_stream_unlock
;
2681 assert(stream
->current_chunk_id
.is_set
);
2682 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2684 if (stream
->is_metadata
) {
2686 * The metadata stream is sent only over the control connection
2687 * so we know we have all the data to perform the stream
2690 ret
= do_rotate_stream(stream
);
2692 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2693 ret
= try_rotate_stream(stream
);
2696 goto end_stream_unlock
;
2700 pthread_mutex_unlock(&stream
->lock
);
2703 memset(&reply
, 0, sizeof(reply
));
2705 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2707 reply
.ret_code
= htobe32(LTTNG_OK
);
2709 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2710 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2711 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2712 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2722 * relay_mkdir: Create a folder on the disk.
2724 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2725 struct relay_connection
*conn
,
2726 const struct lttng_buffer_view
*payload
)
2729 struct relay_session
*session
= conn
->session
;
2730 struct lttcomm_relayd_mkdir path_info_header
;
2731 struct lttcomm_relayd_generic_reply reply
;
2735 struct lttng_buffer_view path_view
;
2737 if (!session
|| !conn
->version_check_done
) {
2738 ERR("Trying to create a directory before version check");
2740 goto end_no_session
;
2743 if (session
->major
== 2 && session
->minor
< 11) {
2745 * This client is not supposed to use this command since
2746 * it predates its introduction.
2748 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2750 goto end_no_session
;
2753 header_len
= sizeof(path_info_header
);
2754 if (payload
->size
< header_len
) {
2755 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2756 header_len
, payload
->size
);
2758 goto end_no_session
;
2761 memcpy(&path_info_header
, payload
->data
, header_len
);
2763 path_info_header
.length
= be32toh(path_info_header
.length
);
2765 if (payload
->size
< header_len
+ path_info_header
.length
) {
2766 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2767 header_len
+ path_info_header
.length
, payload
->size
);
2769 goto end_no_session
;
2772 /* Ensure that it fits in local path length. */
2773 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2774 ret
= -ENAMETOOLONG
;
2775 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2776 path_info_header
.length
, LTTNG_PATH_MAX
);
2780 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2781 path_info_header
.length
);
2783 path
= create_output_path(path_view
.data
);
2785 ERR("Failed to create output path");
2790 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2792 ERR("relay creating output directory");
2799 memset(&reply
, 0, sizeof(reply
));
2801 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2803 reply
.ret_code
= htobe32(LTTNG_OK
);
2805 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2806 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2807 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2816 static int validate_rotate_rename_path_length(const char *path_type
,
2817 uint32_t path_length
)
2821 if (path_length
> LTTNG_PATH_MAX
) {
2822 ret
= -ENAMETOOLONG
;
2823 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2824 path_type
, path_length
, LTTNG_PATH_MAX
);
2825 } else if (path_length
== 0) {
2827 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2833 * relay_rotate_rename: rename the trace folder after a rotation is
2834 * completed. We are not closing any fd here, just moving the folder, so it
2835 * works even if data is still in-flight.
2837 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2838 struct relay_connection
*conn
,
2839 const struct lttng_buffer_view
*payload
)
2843 struct relay_session
*session
= conn
->session
;
2844 struct lttcomm_relayd_generic_reply reply
;
2845 struct lttcomm_relayd_rotate_rename header
;
2847 size_t received_paths_size
;
2848 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2849 struct lttng_buffer_view old_path_view
;
2850 struct lttng_buffer_view new_path_view
;
2852 if (!session
|| !conn
->version_check_done
) {
2853 ERR("Trying to rename a trace folder before version check");
2858 if (session
->major
== 2 && session
->minor
< 11) {
2859 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2864 header_len
= sizeof(header
);
2865 if (payload
->size
< header_len
) {
2866 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2867 header_len
, payload
->size
);
2872 memcpy(&header
, payload
->data
, header_len
);
2874 header
.old_path_length
= be32toh(header
.old_path_length
);
2875 header
.new_path_length
= be32toh(header
.new_path_length
);
2876 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2878 if (payload
->size
< header_len
+ received_paths_size
) {
2879 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2880 header_len
, payload
->size
);
2885 /* Ensure the paths don't exceed their allowed size. */
2886 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2890 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2895 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2896 header
.old_path_length
);
2897 new_path_view
= lttng_buffer_view_from_view(payload
,
2898 header_len
+ header
.old_path_length
,
2899 header
.new_path_length
);
2901 /* Validate that both paths received are NULL terminated. */
2902 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2903 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2907 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2908 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2913 complete_old_path
= create_output_path(old_path_view
.data
);
2914 if (!complete_old_path
) {
2915 ERR("Failed to build old output path in rotate_rename command");
2920 complete_new_path
= create_output_path(new_path_view
.data
);
2921 if (!complete_new_path
) {
2922 ERR("Failed to build new output path in rotate_rename command");
2927 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2930 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2936 * If a domain has not yet created its channel, the domain-specific
2937 * folder might not exist, but this is not an error.
2939 ret
= rename(complete_old_path
, complete_new_path
);
2940 if (ret
< 0 && errno
!= ENOENT
) {
2941 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2942 complete_old_path
, complete_new_path
);
2948 memset(&reply
, 0, sizeof(reply
));
2950 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2952 reply
.ret_code
= htobe32(LTTNG_OK
);
2954 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2956 if (send_ret
< sizeof(reply
)) {
2957 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2963 free(complete_old_path
);
2964 free(complete_new_path
);
2969 * Check if all the streams in the session have completed the last rotation.
2970 * The chunk_id value is used to distinguish the cases where a stream was
2971 * closed on the consumerd before the rotation started but it still active on
2972 * the relayd, and the case where a stream appeared on the consumerd/relayd
2973 * after the last rotation started (in that case, it is already writing in the
2974 * new chunk folder).
2977 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2978 struct relay_connection
*conn
,
2979 const struct lttng_buffer_view
*payload
)
2981 struct relay_session
*session
= conn
->session
;
2982 struct lttcomm_relayd_rotate_pending msg
;
2983 struct lttcomm_relayd_rotate_pending_reply reply
;
2984 struct lttng_ht_iter iter
;
2985 struct relay_stream
*stream
;
2989 bool rotate_pending
= false;
2991 DBG("Rotate pending command received");
2993 if (!session
|| !conn
->version_check_done
) {
2994 ERR("Trying to check for data before version check");
2999 if (session
->major
== 2 && session
->minor
< 11) {
3000 ERR("Unsupported feature before 2.11");
3005 if (payload
->size
< sizeof(msg
)) {
3006 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
3007 sizeof(msg
), payload
->size
);
3012 memcpy(&msg
, payload
->data
, sizeof(msg
));
3014 chunk_id
= be64toh(msg
.chunk_id
);
3016 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
3017 session
->session_name
, chunk_id
);
3020 * Iterate over all the streams in the session and check if they are
3021 * still waiting for data to perform their rotation.
3024 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
3026 if (!stream_get(stream
)) {
3029 if (stream
->trace
->session
!= session
) {
3033 pthread_mutex_lock(&stream
->lock
);
3034 if (stream
->rotate_at_seq_num
!= -1ULL) {
3035 /* We have not yet performed the rotation. */
3036 rotate_pending
= true;
3037 DBG("Stream %" PRIu64
" is still rotating",
3038 stream
->stream_handle
);
3039 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
3041 * Stream closed on the consumer but still active on the
3044 rotate_pending
= true;
3045 DBG("Stream %" PRIu64
" did not exist on the consumer "
3046 "when the last rotation started, but is"
3047 "still waiting for data before getting"
3049 stream
->stream_handle
);
3051 pthread_mutex_unlock(&stream
->lock
);
3053 if (rotate_pending
) {
3060 memset(&reply
, 0, sizeof(reply
));
3061 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
3062 reply
.is_pending
= (uint8_t) !!rotate_pending
;
3063 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
3065 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3066 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
3075 #define DBG_CMD(cmd_name, conn) \
3076 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3078 static int relay_process_control_command(struct relay_connection
*conn
,
3079 const struct lttcomm_relayd_hdr
*header
,
3080 const struct lttng_buffer_view
*payload
)
3084 switch (header
->cmd
) {
3085 case RELAYD_CREATE_SESSION
:
3086 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3087 ret
= relay_create_session(header
, conn
, payload
);
3089 case RELAYD_ADD_STREAM
:
3090 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3091 ret
= relay_add_stream(header
, conn
, payload
);
3093 case RELAYD_START_DATA
:
3094 DBG_CMD("RELAYD_START_DATA", conn
);
3095 ret
= relay_start(header
, conn
, payload
);
3097 case RELAYD_SEND_METADATA
:
3098 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3099 ret
= relay_recv_metadata(header
, conn
, payload
);
3101 case RELAYD_VERSION
:
3102 DBG_CMD("RELAYD_VERSION", conn
);
3103 ret
= relay_send_version(header
, conn
, payload
);
3105 case RELAYD_CLOSE_STREAM
:
3106 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3107 ret
= relay_close_stream(header
, conn
, payload
);
3109 case RELAYD_DATA_PENDING
:
3110 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3111 ret
= relay_data_pending(header
, conn
, payload
);
3113 case RELAYD_QUIESCENT_CONTROL
:
3114 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3115 ret
= relay_quiescent_control(header
, conn
, payload
);
3117 case RELAYD_BEGIN_DATA_PENDING
:
3118 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3119 ret
= relay_begin_data_pending(header
, conn
, payload
);
3121 case RELAYD_END_DATA_PENDING
:
3122 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3123 ret
= relay_end_data_pending(header
, conn
, payload
);
3125 case RELAYD_SEND_INDEX
:
3126 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3127 ret
= relay_recv_index(header
, conn
, payload
);
3129 case RELAYD_STREAMS_SENT
:
3130 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3131 ret
= relay_streams_sent(header
, conn
, payload
);
3133 case RELAYD_RESET_METADATA
:
3134 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3135 ret
= relay_reset_metadata(header
, conn
, payload
);
3137 case RELAYD_ROTATE_STREAM
:
3138 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3139 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3141 case RELAYD_ROTATE_RENAME
:
3142 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3143 ret
= relay_rotate_rename(header
, conn
, payload
);
3145 case RELAYD_ROTATE_PENDING
:
3146 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3147 ret
= relay_rotate_pending(header
, conn
, payload
);
3150 DBG_CMD("RELAYD_MKDIR", conn
);
3151 ret
= relay_mkdir(header
, conn
, payload
);
3153 case RELAYD_UPDATE_SYNC_INFO
:
3155 ERR("Received unknown command (%u)", header
->cmd
);
3156 relay_unknown_command(conn
);
3165 static enum relay_connection_status
relay_process_control_receive_payload(
3166 struct relay_connection
*conn
)
3169 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3170 struct lttng_dynamic_buffer
*reception_buffer
=
3171 &conn
->protocol
.ctrl
.reception_buffer
;
3172 struct ctrl_connection_state_receive_payload
*state
=
3173 &conn
->protocol
.ctrl
.state
.receive_payload
;
3174 struct lttng_buffer_view payload_view
;
3176 if (state
->left_to_receive
== 0) {
3177 /* Short-circuit for payload-less commands. */
3178 goto reception_complete
;
3181 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3182 reception_buffer
->data
+ state
->received
,
3183 state
->left_to_receive
, MSG_DONTWAIT
);
3185 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3186 PERROR("Unable to receive command payload on sock %d",
3188 status
= RELAY_CONNECTION_STATUS_ERROR
;
3191 } else if (ret
== 0) {
3192 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3193 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3198 assert(ret
<= state
->left_to_receive
);
3200 state
->left_to_receive
-= ret
;
3201 state
->received
+= ret
;
3203 if (state
->left_to_receive
> 0) {
3205 * Can't transition to the protocol's next state, wait to
3206 * receive the rest of the header.
3208 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3209 state
->received
, state
->left_to_receive
,
3215 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3216 conn
->sock
->fd
, state
->received
);
3218 * The payload required to process the command has been received.
3219 * A view to the reception buffer is forwarded to the various
3220 * commands and the state of the control is reset on success.
3222 * Commands are responsible for sending their reply to the peer.
3224 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3226 ret
= relay_process_control_command(conn
,
3227 &state
->header
, &payload_view
);
3229 status
= RELAY_CONNECTION_STATUS_ERROR
;
3233 ret
= connection_reset_protocol_state(conn
);
3235 status
= RELAY_CONNECTION_STATUS_ERROR
;
3241 static enum relay_connection_status
relay_process_control_receive_header(
3242 struct relay_connection
*conn
)
3245 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3246 struct lttcomm_relayd_hdr header
;
3247 struct lttng_dynamic_buffer
*reception_buffer
=
3248 &conn
->protocol
.ctrl
.reception_buffer
;
3249 struct ctrl_connection_state_receive_header
*state
=
3250 &conn
->protocol
.ctrl
.state
.receive_header
;
3252 assert(state
->left_to_receive
!= 0);
3254 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3255 reception_buffer
->data
+ state
->received
,
3256 state
->left_to_receive
, MSG_DONTWAIT
);
3258 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3259 PERROR("Unable to receive control command header on sock %d",
3261 status
= RELAY_CONNECTION_STATUS_ERROR
;
3264 } else if (ret
== 0) {
3265 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3266 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3271 assert(ret
<= state
->left_to_receive
);
3273 state
->left_to_receive
-= ret
;
3274 state
->received
+= ret
;
3276 if (state
->left_to_receive
> 0) {
3278 * Can't transition to the protocol's next state, wait to
3279 * receive the rest of the header.
3281 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3282 state
->received
, state
->left_to_receive
,
3287 /* Transition to next state: receiving the command's payload. */
3288 conn
->protocol
.ctrl
.state_id
=
3289 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3290 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3291 header
.circuit_id
= be64toh(header
.circuit_id
);
3292 header
.data_size
= be64toh(header
.data_size
);
3293 header
.cmd
= be32toh(header
.cmd
);
3294 header
.cmd_version
= be32toh(header
.cmd_version
);
3295 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3296 &header
, sizeof(header
));
3298 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3299 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3302 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3303 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3305 status
= RELAY_CONNECTION_STATUS_ERROR
;
3309 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3311 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3312 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3315 status
= RELAY_CONNECTION_STATUS_ERROR
;
3319 if (header
.data_size
== 0) {
3321 * Manually invoke the next state as the poll loop
3322 * will not wake-up to allow us to proceed further.
3324 status
= relay_process_control_receive_payload(conn
);
3331 * Process the commands received on the control socket
3333 static enum relay_connection_status
relay_process_control(
3334 struct relay_connection
*conn
)
3336 enum relay_connection_status status
;
3338 switch (conn
->protocol
.ctrl
.state_id
) {
3339 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3340 status
= relay_process_control_receive_header(conn
);
3342 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3343 status
= relay_process_control_receive_payload(conn
);
3346 ERR("Unknown control connection protocol state encountered.");
3354 * Handle index for a data stream.
3356 * Called with the stream lock held.
3358 * Return 0 on success else a negative value.
3360 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3361 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3364 uint64_t data_offset
;
3365 struct relay_index
*index
;
3367 /* Get data offset because we are about to update the index. */
3368 data_offset
= htobe64(stream
->tracefile_size_current
);
3370 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3371 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3374 * Lookup for an existing index for that stream id/sequence
3375 * number. If it exists, the control thread has already received the
3376 * data for it, thus we need to write it to disk.
3378 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3384 if (rotate_index
|| !stream
->index_file
) {
3385 ret
= create_rotate_index_file(stream
);
3387 ERR("Failed to rotate index");
3388 /* Put self-ref for this index due to error. */
3389 relay_index_put(index
);
3395 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3397 /* Put self-ref for this index due to error. */
3398 relay_index_put(index
);
3403 ret
= relay_index_try_flush(index
);
3405 tracefile_array_commit_seq(stream
->tfa
);
3406 stream
->index_received_seqcount
++;
3408 } else if (ret
> 0) {
3409 index
->total_size
= total_size
;
3413 /* Put self-ref for this index due to error. */
3414 relay_index_put(index
);
3422 static enum relay_connection_status
relay_process_data_receive_header(
3423 struct relay_connection
*conn
)
3426 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3427 struct data_connection_state_receive_header
*state
=
3428 &conn
->protocol
.data
.state
.receive_header
;
3429 struct lttcomm_relayd_data_hdr header
;
3430 struct relay_stream
*stream
;
3432 assert(state
->left_to_receive
!= 0);
3434 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3435 state
->header_reception_buffer
+ state
->received
,
3436 state
->left_to_receive
, MSG_DONTWAIT
);
3438 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3439 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3440 status
= RELAY_CONNECTION_STATUS_ERROR
;
3443 } else if (ret
== 0) {
3444 /* Orderly shutdown. Not necessary to print an error. */
3445 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3446 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3451 assert(ret
<= state
->left_to_receive
);
3453 state
->left_to_receive
-= ret
;
3454 state
->received
+= ret
;
3456 if (state
->left_to_receive
> 0) {
3458 * Can't transition to the protocol's next state, wait to
3459 * receive the rest of the header.
3461 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3462 state
->received
, state
->left_to_receive
,
3467 /* Transition to next state: receiving the payload. */
3468 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3470 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3471 header
.circuit_id
= be64toh(header
.circuit_id
);
3472 header
.stream_id
= be64toh(header
.stream_id
);
3473 header
.data_size
= be32toh(header
.data_size
);
3474 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3475 header
.padding_size
= be32toh(header
.padding_size
);
3476 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3478 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3480 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3481 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3483 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3484 conn
->sock
->fd
, header
.circuit_id
,
3485 header
.stream_id
, header
.data_size
,
3486 header
.net_seq_num
, header
.padding_size
);
3488 stream
= stream_get_by_id(header
.stream_id
);
3490 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3492 /* Protocol error. */
3493 status
= RELAY_CONNECTION_STATUS_ERROR
;
3497 pthread_mutex_lock(&stream
->lock
);
3499 /* Check if a rotation is needed. */
3500 if (stream
->tracefile_size
> 0 &&
3501 (stream
->tracefile_size_current
+ header
.data_size
) >
3502 stream
->tracefile_size
) {
3503 uint64_t old_id
, new_id
;
3505 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3506 tracefile_array_file_rotate(stream
->tfa
);
3508 /* new_id is updated by utils_rotate_stream_file. */
3511 ret
= stream_fd_rotate(stream
->stream_fd
, stream
->path_name
,
3512 stream
->channel_name
, stream
->tracefile_size
,
3513 stream
->tracefile_count
, &new_id
);
3515 ERR("Failed to rotate stream output file");
3516 status
= RELAY_CONNECTION_STATUS_ERROR
;
3517 goto end_stream_unlock
;
3521 * Reset current size because we just performed a stream
3524 stream
->tracefile_size_current
= 0;
3525 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3529 pthread_mutex_unlock(&stream
->lock
);
3535 static enum relay_connection_status
relay_process_data_receive_payload(
3536 struct relay_connection
*conn
)
3539 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3540 struct relay_stream
*stream
;
3541 struct data_connection_state_receive_payload
*state
=
3542 &conn
->protocol
.data
.state
.receive_payload
;
3543 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3544 char data_buffer
[chunk_size
];
3545 bool partial_recv
= false;
3546 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3547 uint64_t left_to_receive
= state
->left_to_receive
;
3548 struct relay_session
*session
;
3551 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3552 state
->header
.stream_id
, state
->header
.net_seq_num
,
3553 state
->received
, left_to_receive
);
3555 stream
= stream_get_by_id(state
->header
.stream_id
);
3557 /* Protocol error. */
3558 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3559 state
->header
.stream_id
);
3560 status
= RELAY_CONNECTION_STATUS_ERROR
;
3564 pthread_mutex_lock(&stream
->lock
);
3565 session
= stream
->trace
->session
;
3566 if (!conn
->session
) {
3567 ret
= connection_set_session(conn
, session
);
3569 status
= RELAY_CONNECTION_STATUS_ERROR
;
3570 goto end_stream_unlock
;
3574 stream_fd
= stream_fd_get_fd(stream
->stream_fd
);
3575 if (stream_fd
< 0) {
3576 status
= RELAY_CONNECTION_STATUS_ERROR
;
3577 goto end_stream_unlock
;
3581 * The size of the "chunk" received on any iteration is bounded by:
3582 * - the data left to receive,
3583 * - the data immediately available on the socket,
3584 * - the on-stack data buffer
3586 while (left_to_receive
> 0 && !partial_recv
) {
3588 size_t recv_size
= min(left_to_receive
, chunk_size
);
3590 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3591 recv_size
, MSG_DONTWAIT
);
3593 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3594 PERROR("Socket %d error", conn
->sock
->fd
);
3595 status
= RELAY_CONNECTION_STATUS_ERROR
;
3598 } else if (ret
== 0) {
3599 /* No more data ready to be consumed on socket. */
3600 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3601 state
->header
.stream_id
);
3602 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3604 } else if (ret
< (int) recv_size
) {
3606 * All the data available on the socket has been
3609 partial_recv
= true;
3614 /* Write data to stream output fd. */
3615 write_ret
= lttng_write(stream_fd
, data_buffer
,
3617 if (write_ret
< (ssize_t
) recv_size
) {
3618 ERR("Relay error writing data to file");
3619 status
= RELAY_CONNECTION_STATUS_ERROR
;
3623 left_to_receive
-= recv_size
;
3624 state
->received
+= recv_size
;
3625 state
->left_to_receive
= left_to_receive
;
3627 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3628 write_ret
, stream
->stream_handle
);
3631 if (state
->left_to_receive
> 0) {
3633 * Did not receive all the data expected, wait for more data to
3634 * become available on the socket.
3636 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3637 state
->header
.stream_id
, state
->received
,
3638 state
->left_to_receive
);
3642 ret
= write_padding_to_file(stream_fd
,
3643 state
->header
.padding_size
);
3644 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3645 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3646 stream
->stream_handle
,
3647 state
->header
.net_seq_num
, ret
);
3648 status
= RELAY_CONNECTION_STATUS_ERROR
;
3653 if (session
->minor
>= 4 && !session
->snapshot
) {
3654 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3655 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3657 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3658 stream
->stream_handle
,
3659 state
->header
.net_seq_num
, ret
);
3660 status
= RELAY_CONNECTION_STATUS_ERROR
;
3665 stream
->tracefile_size_current
+= state
->header
.data_size
+
3666 state
->header
.padding_size
;
3668 if (stream
->prev_seq
== -1ULL) {
3671 if (index_flushed
) {
3672 stream
->pos_after_last_complete_data_index
=
3673 stream
->tracefile_size_current
;
3676 stream
->prev_seq
= state
->header
.net_seq_num
;
3679 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3680 * contents of *state which are aliased (union) to the same location as
3681 * the new state. Don't use it beyond this point.
3683 connection_reset_protocol_state(conn
);
3686 ret
= try_rotate_stream(stream
);
3688 status
= RELAY_CONNECTION_STATUS_ERROR
;
3692 (void) stream_fd_put_fd(stream
->stream_fd
);
3694 close_requested
= stream
->close_requested
;
3695 pthread_mutex_unlock(&stream
->lock
);
3696 if (close_requested
&& left_to_receive
== 0) {
3697 try_stream_close(stream
);
3701 pthread_mutex_lock(&session
->lock
);
3702 uatomic_set(&session
->new_streams
, 1);
3703 pthread_mutex_unlock(&session
->lock
);
3712 * relay_process_data: Process the data received on the data socket
3714 static enum relay_connection_status
relay_process_data(
3715 struct relay_connection
*conn
)
3717 enum relay_connection_status status
;
3719 switch (conn
->protocol
.data
.state_id
) {
3720 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3721 status
= relay_process_data_receive_header(conn
);
3723 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3724 status
= relay_process_data_receive_payload(conn
);
3727 ERR("Unexpected data connection communication state.");
3734 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3738 (void) lttng_poll_del(events
, pollfd
);
3740 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3741 fd_tracker_util_close_fd
, NULL
);
3743 ERR("Closing pollfd %d", pollfd
);
3747 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3748 int pollfd
, struct relay_connection
*conn
)
3750 const char *type_str
;
3752 switch (conn
->type
) {
3757 type_str
= "Control";
3759 case RELAY_VIEWER_COMMAND
:
3760 type_str
= "Viewer Command";
3762 case RELAY_VIEWER_NOTIFICATION
:
3763 type_str
= "Viewer Notification";
3766 type_str
= "Unknown";
3768 cleanup_connection_pollfd(events
, pollfd
);
3769 connection_put(conn
);
3770 DBG("%s connection closed with %d", type_str
, pollfd
);
3774 * This thread does the actual work
3776 static void *relay_thread_worker(void *data
)
3778 int ret
, err
= -1, last_seen_data_fd
= -1;
3780 struct lttng_poll_event events
;
3781 struct lttng_ht
*relay_connections_ht
;
3782 struct lttng_ht_iter iter
;
3783 struct relay_connection
*destroy_conn
= NULL
;
3785 DBG("[thread] Relay worker started");
3787 rcu_register_thread();
3789 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3791 if (testpoint(relayd_thread_worker
)) {
3792 goto error_testpoint
;
3795 health_code_update();
3797 /* table of connections indexed on socket */
3798 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3799 if (!relay_connections_ht
) {
3800 goto relay_connections_ht_error
;
3803 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3805 goto error_poll_create
;
3808 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3815 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3817 health_code_update();
3819 /* Infinite blocking call, waiting for transmission */
3820 DBG3("Relayd worker thread polling...");
3821 health_poll_entry();
3822 ret
= lttng_poll_wait(&events
, -1);
3826 * Restart interrupted system call.
3828 if (errno
== EINTR
) {
3837 * Process control. The control connection is
3838 * prioritized so we don't starve it with high
3839 * throughput tracing data on the data connection.
3841 for (i
= 0; i
< nb_fd
; i
++) {
3842 /* Fetch once the poll data */
3843 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3844 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3846 health_code_update();
3850 * No activity for this FD (poll
3856 /* Thread quit pipe has been closed. Killing thread. */
3857 ret
= check_thread_quit_pipe(pollfd
, revents
);
3863 /* Inspect the relay conn pipe for new connection */
3864 if (pollfd
== relay_conn_pipe
[0]) {
3865 if (revents
& LPOLLIN
) {
3866 struct relay_connection
*conn
;
3868 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3872 lttng_poll_add(&events
, conn
->sock
->fd
,
3873 LPOLLIN
| LPOLLRDHUP
);
3874 connection_ht_add(relay_connections_ht
, conn
);
3875 DBG("Connection socket %d added", conn
->sock
->fd
);
3876 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3877 ERR("Relay connection pipe error");
3880 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3884 struct relay_connection
*ctrl_conn
;
3886 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3887 /* If not found, there is a synchronization issue. */
3890 if (ctrl_conn
->type
== RELAY_DATA
) {
3891 if (revents
& LPOLLIN
) {
3893 * Flag the last seen data fd not deleted. It will be
3894 * used as the last seen fd if any fd gets deleted in
3897 last_notdel_data_fd
= pollfd
;
3899 goto put_ctrl_connection
;
3901 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3903 if (revents
& LPOLLIN
) {
3904 enum relay_connection_status status
;
3906 status
= relay_process_control(ctrl_conn
);
3907 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3909 * On socket error flag the session as aborted to force
3910 * the cleanup of its stream otherwise it can leak
3911 * during the lifetime of the relayd.
3913 * This prevents situations in which streams can be
3914 * left opened because an index was received, the
3915 * control connection is closed, and the data
3916 * connection is closed (uncleanly) before the packet's
3919 * Since the control connection encountered an error,
3920 * it is okay to be conservative and close the
3921 * session right now as we can't rely on the protocol
3922 * being respected anymore.
3924 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3925 session_abort(ctrl_conn
->session
);
3928 /* Clear the connection on error or close. */
3929 relay_thread_close_connection(&events
,
3934 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3935 relay_thread_close_connection(&events
,
3937 if (last_seen_data_fd
== pollfd
) {
3938 last_seen_data_fd
= last_notdel_data_fd
;
3941 ERR("Unexpected poll events %u for control sock %d",
3943 connection_put(ctrl_conn
);
3946 put_ctrl_connection
:
3947 connection_put(ctrl_conn
);
3952 * The last loop handled a control request, go back to poll to make
3953 * sure we prioritise the control socket.
3959 if (last_seen_data_fd
>= 0) {
3960 for (i
= 0; i
< nb_fd
; i
++) {
3961 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3963 health_code_update();
3965 if (last_seen_data_fd
== pollfd
) {
3972 /* Process data connection. */
3973 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3974 /* Fetch the poll data. */
3975 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3976 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3977 struct relay_connection
*data_conn
;
3979 health_code_update();
3982 /* No activity for this FD (poll implementation). */
3986 /* Skip the command pipe. It's handled in the first loop. */
3987 if (pollfd
== relay_conn_pipe
[0]) {
3991 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3993 /* Skip it. Might be removed before. */
3996 if (data_conn
->type
== RELAY_CONTROL
) {
3997 goto put_data_connection
;
3999 assert(data_conn
->type
== RELAY_DATA
);
4001 if (revents
& LPOLLIN
) {
4002 enum relay_connection_status status
;
4004 status
= relay_process_data(data_conn
);
4005 /* Connection closed or error. */
4006 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4008 * On socket error flag the session as aborted to force
4009 * the cleanup of its stream otherwise it can leak
4010 * during the lifetime of the relayd.
4012 * This prevents situations in which streams can be
4013 * left opened because an index was received, the
4014 * control connection is closed, and the data
4015 * connection is closed (uncleanly) before the packet's
4018 * Since the data connection encountered an error,
4019 * it is okay to be conservative and close the
4020 * session right now as we can't rely on the protocol
4021 * being respected anymore.
4023 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4024 session_abort(data_conn
->session
);
4026 relay_thread_close_connection(&events
, pollfd
,
4029 * Every goto restart call sets the last seen fd where
4030 * here we don't really care since we gracefully
4031 * continue the loop after the connection is deleted.
4034 /* Keep last seen port. */
4035 last_seen_data_fd
= pollfd
;
4036 connection_put(data_conn
);
4039 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4040 relay_thread_close_connection(&events
, pollfd
,
4043 ERR("Unknown poll events %u for data sock %d",
4046 put_data_connection
:
4047 connection_put(data_conn
);
4049 last_seen_data_fd
= -1;
4052 /* Normal exit, no error */
4057 /* Cleanup remaining connection object. */
4059 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4062 health_code_update();
4064 session_abort(destroy_conn
->session
);
4067 * No need to grab another ref, because we own
4070 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4075 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4077 lttng_ht_destroy(relay_connections_ht
);
4078 relay_connections_ht_error
:
4079 /* Close relay conn pipes */
4080 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4083 DBG("Thread exited with error");
4085 DBG("Worker thread cleanup complete");
4089 ERR("Health error occurred in %s", __func__
);
4091 health_unregister(health_relayd
);
4092 rcu_unregister_thread();
4093 lttng_relay_stop_threads();
4098 * Create the relay command pipe to wake thread_manage_apps.
4099 * Closed in cleanup().
4101 static int create_relay_conn_pipe(void)
4103 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4104 "Relayd connection pipe", relay_conn_pipe
);
4108 int stdio_open(void *data
, int *fds
)
4110 fds
[0] = fileno(stdout
);
4111 fds
[1] = fileno(stderr
);
4116 int noop_close(void *data
, int *fds
)
4122 int track_stdio(void)
4125 const char *names
[] = { "stdout", "stderr" };
4127 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4128 names
, 2, stdio_open
, NULL
);
4132 void untrack_stdio(void)
4134 int fds
[] = { fileno(stdout
), fileno(stderr
) };
4137 * noop_close is used since we don't really want to close
4138 * the stdio output fds; we merely want to stop tracking them.
4140 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
4141 fds
, 2, noop_close
, NULL
);
4147 int main(int argc
, char **argv
)
4149 int ret
= 0, retval
= 0;
4152 /* Parse arguments */
4154 if (set_options(argc
, argv
)) {
4159 if (set_signal_handler()) {
4164 ret
= fclose(stdin
);
4166 PERROR("Failed to close stdin");
4169 /* Try to create directory if -o, --output is specified. */
4170 if (opt_output_path
) {
4171 if (*opt_output_path
!= '/') {
4172 ERR("Please specify an absolute path for -o, --output PATH");
4177 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4180 ERR("Unable to create %s", opt_output_path
);
4187 if (opt_daemon
|| opt_background
) {
4188 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4197 * The RCU thread registration (and use, through the fd-tracker's
4198 * creation) is done after the daemonization to allow us to not
4199 * deal with liburcu's fork() management as the call RCU needs to
4202 rcu_register_thread();
4204 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_pool_size
);
4205 if (!the_fd_tracker
) {
4210 ret
= track_stdio();
4216 /* Initialize thread health monitoring */
4217 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4218 if (!health_relayd
) {
4219 PERROR("health_app_create error");
4221 goto exit_health_app_create
;
4224 /* Create thread quit pipe */
4225 if (init_thread_quit_pipe()) {
4227 goto exit_init_data
;
4230 /* Setup the thread apps communication pipe. */
4231 if (create_relay_conn_pipe()) {
4233 goto exit_init_data
;
4236 /* Init relay command queue. */
4237 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4239 /* Initialize communication library */
4241 lttcomm_inet_init();
4243 /* tables of sessions indexed by session ID */
4244 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4247 goto exit_init_data
;
4250 /* tables of streams indexed by stream ID */
4251 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4252 if (!relay_streams_ht
) {
4254 goto exit_init_data
;
4257 /* tables of streams indexed by stream ID */
4258 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4259 if (!viewer_streams_ht
) {
4261 goto exit_init_data
;
4264 ret
= init_health_quit_pipe();
4267 goto exit_health_quit_pipe
;
4270 /* Create thread to manage the client socket */
4271 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4272 thread_manage_health
, (void *) NULL
);
4275 PERROR("pthread_create health");
4277 goto exit_health_thread
;
4280 /* Setup the dispatcher thread */
4281 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4282 relay_thread_dispatcher
, (void *) NULL
);
4285 PERROR("pthread_create dispatcher");
4287 goto exit_dispatcher_thread
;
4290 /* Setup the worker thread */
4291 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4292 relay_thread_worker
, NULL
);
4295 PERROR("pthread_create worker");
4297 goto exit_worker_thread
;
4300 /* Setup the listener thread */
4301 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4302 relay_thread_listener
, (void *) NULL
);
4305 PERROR("pthread_create listener");
4307 goto exit_listener_thread
;
4310 ret
= relayd_live_create(live_uri
);
4312 ERR("Starting live viewer threads");
4318 * This is where we start awaiting program completion (e.g. through
4319 * signal that asks threads to teardown).
4322 ret
= relayd_live_join();
4328 ret
= pthread_join(listener_thread
, &status
);
4331 PERROR("pthread_join listener_thread");
4335 exit_listener_thread
:
4336 ret
= pthread_join(worker_thread
, &status
);
4339 PERROR("pthread_join worker_thread");
4344 ret
= pthread_join(dispatcher_thread
, &status
);
4347 PERROR("pthread_join dispatcher_thread");
4350 exit_dispatcher_thread
:
4352 ret
= pthread_join(health_thread
, &status
);
4355 PERROR("pthread_join health_thread");
4360 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4361 exit_health_quit_pipe
:
4364 health_app_destroy(health_relayd
);
4365 exit_health_app_create
:
4368 * Wait for all pending call_rcu work to complete before tearing
4369 * down data structures. call_rcu worker may be trying to
4370 * perform lookups in those structures.
4375 /* Ensure all prior call_rcu are done. */
4380 * fd_tracker_destroy() will log the contents of the fd-tracker
4381 * if a leak is detected.
4383 fd_tracker_destroy(the_fd_tracker
);
4384 rcu_unregister_thread();