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 %lu (soft) and %lu (hard)",
413 rlimit
.rlim_cur
, 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 (%lu). The process' file number limit must be set to at least %i.",
418 rlimit
.rlim_cur
, DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
422 lttng_opt_fd_pool_size
= rlimit
.rlim_cur
-
423 DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
427 if (lttng_opt_fd_pool_size
< DEFAULT_RELAYD_MIN_FD_POOL_SIZE
) {
428 ERR("File descriptor pool size must be set to at least %d",
429 DEFAULT_RELAYD_MIN_FD_POOL_SIZE
);
434 if (lttng_opt_fd_pool_size
> rlimit
.rlim_cur
) {
435 ERR("File descriptor pool size argument (%u) exceeds the process' soft limit (%lu).",
436 lttng_opt_fd_pool_size
, rlimit
.rlim_cur
);
442 DBG("File descriptor pool size argument (%u) adjusted to %u to accomodate transient fd uses",
443 lttng_opt_fd_pool_size
,
444 lttng_opt_fd_pool_size
- DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
);
445 lttng_opt_fd_pool_size
-= DEFAULT_RELAYD_FD_POOL_SIZE_RESERVE
;
450 static int set_options(int argc
, char **argv
)
452 int c
, ret
= 0, option_index
= 0, retval
= 0;
453 int orig_optopt
= optopt
, orig_optind
= optind
;
454 char *default_address
, *optstring
;
455 const char *config_path
= NULL
;
457 optstring
= utils_generate_optstring(long_options
,
458 sizeof(long_options
) / sizeof(struct option
));
464 /* Check for the --config option */
466 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
467 &option_index
)) != -1) {
471 } else if (c
!= 'f') {
475 if (lttng_is_setuid_setgid()) {
476 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
479 config_path
= utils_expand_path(optarg
);
481 ERR("Failed to resolve path: %s", optarg
);
486 ret
= config_get_section_entries(config_path
, config_section_name
,
487 config_entry_handler
, NULL
);
490 ERR("Invalid configuration option at line %i", ret
);
496 /* Reset getopt's global state */
497 optopt
= orig_optopt
;
498 optind
= orig_optind
;
500 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
505 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
512 /* assign default values */
513 if (control_uri
== NULL
) {
514 ret
= asprintf(&default_address
,
515 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
516 DEFAULT_NETWORK_CONTROL_PORT
);
518 PERROR("asprintf default data address");
523 ret
= uri_parse(default_address
, &control_uri
);
524 free(default_address
);
526 ERR("Invalid control URI specified");
531 if (data_uri
== NULL
) {
532 ret
= asprintf(&default_address
,
533 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
534 DEFAULT_NETWORK_DATA_PORT
);
536 PERROR("asprintf default data address");
541 ret
= uri_parse(default_address
, &data_uri
);
542 free(default_address
);
544 ERR("Invalid data URI specified");
549 if (live_uri
== NULL
) {
550 ret
= asprintf(&default_address
,
551 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
552 DEFAULT_NETWORK_VIEWER_PORT
);
554 PERROR("asprintf default viewer control address");
559 ret
= uri_parse(default_address
, &live_uri
);
560 free(default_address
);
562 ERR("Invalid viewer control URI specified");
567 ret
= set_fd_pool_size();
578 static void print_global_objects(void)
580 print_viewer_streams();
581 print_relay_streams();
588 static void relayd_cleanup(void)
590 print_global_objects();
594 if (viewer_streams_ht
)
595 lttng_ht_destroy(viewer_streams_ht
);
596 if (relay_streams_ht
)
597 lttng_ht_destroy(relay_streams_ht
);
599 lttng_ht_destroy(sessions_ht
);
601 /* free the dynamically allocated opt_output_path */
602 free(opt_output_path
);
604 /* Close thread quit pipes */
605 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
607 uri_free(control_uri
);
609 /* Live URI is freed in the live thread. */
611 if (tracing_group_name_override
) {
612 free((void *) tracing_group_name
);
617 * Write to writable pipe used to notify a thread.
619 static int notify_thread_pipe(int wpipe
)
623 ret
= lttng_write(wpipe
, "!", 1);
625 PERROR("write poll pipe");
633 static int notify_health_quit_pipe(int *pipe
)
637 ret
= lttng_write(pipe
[1], "4", 1);
639 PERROR("write relay health quit");
648 * Stop all relayd and relayd-live threads.
650 int lttng_relay_stop_threads(void)
654 /* Stopping all threads */
655 DBG("Terminating all threads");
656 if (notify_thread_pipe(thread_quit_pipe
[1])) {
657 ERR("write error on thread quit pipe");
661 if (notify_health_quit_pipe(health_quit_pipe
)) {
662 ERR("write error on health quit pipe");
665 /* Dispatch thread */
666 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
667 futex_nto1_wake(&relay_conn_queue
.futex
);
669 if (relayd_live_stop()) {
670 ERR("Error stopping live threads");
677 * Signal handler for the daemon
679 * Simply stop all worker threads, leaving main() return gracefully after
680 * joining all threads and calling cleanup().
682 static void sighandler(int sig
)
686 DBG("SIGINT caught");
687 if (lttng_relay_stop_threads()) {
688 ERR("Error stopping threads");
692 DBG("SIGTERM caught");
693 if (lttng_relay_stop_threads()) {
694 ERR("Error stopping threads");
698 CMM_STORE_SHARED(recv_child_signal
, 1);
706 * Setup signal handler for :
707 * SIGINT, SIGTERM, SIGPIPE
709 static int set_signal_handler(void)
715 if ((ret
= sigemptyset(&sigset
)) < 0) {
716 PERROR("sigemptyset");
723 sa
.sa_handler
= sighandler
;
724 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
729 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
734 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
739 sa
.sa_handler
= SIG_IGN
;
740 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
745 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
750 void lttng_relay_notify_ready(void)
752 /* Notify the parent of the fork() process that we are ready. */
753 if (opt_daemon
|| opt_background
) {
754 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
755 kill(child_ppid
, SIGUSR1
);
761 * Init thread quit pipe.
763 * Return -1 on error or 0 if all pipes are created.
765 static int init_thread_quit_pipe(void)
767 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
768 "Quit pipe", thread_quit_pipe
);
772 * Init health quit pipe.
774 * Return -1 on error or 0 if all pipes are created.
776 static int init_health_quit_pipe(void)
778 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
779 "Health quit pipe", health_quit_pipe
);
783 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
785 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
786 int size
, const char *name
)
790 if (events
== NULL
|| size
== 0) {
795 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
796 name
, events
, 1, LTTNG_CLOEXEC
);
799 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
811 * Check if the thread quit pipe was triggered.
813 * Return 1 if it was triggered else 0;
815 static int check_thread_quit_pipe(int fd
, uint32_t events
)
817 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
824 static int create_sock(void *data
, int *out_fd
)
827 struct lttcomm_sock
*sock
= data
;
829 ret
= lttcomm_create_sock(sock
);
839 static int close_sock(void *data
, int *in_fd
)
841 struct lttcomm_sock
*sock
= data
;
843 return sock
->ops
->close(sock
);
846 static int accept_sock(void *data
, int *out_fd
)
849 /* Socks is an array of in_sock, out_sock. */
850 struct lttcomm_sock
**socks
= data
;
851 struct lttcomm_sock
*in_sock
= socks
[0];
853 socks
[1] = in_sock
->ops
->accept(in_sock
);
858 *out_fd
= socks
[1]->fd
;
864 * Create and init socket from uri.
866 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
870 struct lttcomm_sock
*sock
= NULL
;
871 char uri_str
[PATH_MAX
];
872 char *formated_name
= NULL
;
874 sock
= lttcomm_alloc_sock_from_uri(uri
);
876 ERR("Allocating socket");
881 * Don't fail to create the socket if the name can't be built as it is
882 * only used for debugging purposes.
884 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
885 uri_str
[sizeof(uri_str
) - 1] = '\0';
887 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
890 formated_name
= NULL
;
894 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
895 (const char **) (formated_name
? &formated_name
: NULL
),
896 1, create_sock
, sock
);
898 DBG("Listening on %s socket %d", name
, sock
->fd
);
900 ret
= sock
->ops
->bind(sock
);
902 PERROR("Failed to bind socket");
906 ret
= sock
->ops
->listen(sock
, -1);
916 lttcomm_destroy_sock(sock
);
922 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
926 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
927 struct lttcomm_sock
*new_sock
= NULL
;
929 ret
= fd_tracker_open_unsuspendable_fd(
930 the_fd_tracker
, &out_fd
,
931 (const char **) &name
,
932 1, accept_sock
, &socks
);
937 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
943 * This thread manages the listening for new connections on the network
945 static void *relay_thread_listener(void *data
)
947 int i
, ret
, pollfd
, err
= -1;
948 uint32_t revents
, nb_fd
;
949 struct lttng_poll_event events
;
950 struct lttcomm_sock
*control_sock
, *data_sock
;
952 DBG("[thread] Relay listener started");
954 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
956 health_code_update();
958 control_sock
= relay_socket_create(control_uri
, "Control listener");
960 goto error_sock_control
;
963 data_sock
= relay_socket_create(data_uri
, "Data listener");
965 goto error_sock_relay
;
969 * Pass 3 as size here for the thread quit pipe, control and
972 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
974 goto error_create_poll
;
977 /* Add the control socket */
978 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
983 /* Add the data socket */
984 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
989 lttng_relay_notify_ready();
991 if (testpoint(relayd_thread_listener
)) {
992 goto error_testpoint
;
996 health_code_update();
998 DBG("Listener accepting connections");
1001 health_poll_entry();
1002 ret
= lttng_poll_wait(&events
, -1);
1006 * Restart interrupted system call.
1008 if (errno
== EINTR
) {
1016 DBG("Relay new connection received");
1017 for (i
= 0; i
< nb_fd
; i
++) {
1018 health_code_update();
1020 /* Fetch once the poll data */
1021 revents
= LTTNG_POLL_GETEV(&events
, i
);
1022 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
1026 * No activity for this FD (poll
1032 /* Thread quit pipe has been closed. Killing thread. */
1033 ret
= check_thread_quit_pipe(pollfd
, revents
);
1039 if (revents
& LPOLLIN
) {
1041 * A new connection is requested, therefore a
1042 * sessiond/consumerd connection is allocated in
1043 * this thread, enqueued to a global queue and
1044 * dequeued (and freed) in the worker thread.
1047 struct relay_connection
*new_conn
;
1048 struct lttcomm_sock
*newsock
= NULL
;
1049 enum connection_type type
;
1051 if (pollfd
== data_sock
->fd
) {
1053 newsock
= accept_relayd_sock(data_sock
,
1054 "Data socket to relayd");
1056 assert(pollfd
== control_sock
->fd
);
1057 type
= RELAY_CONTROL
;
1058 newsock
= accept_relayd_sock(control_sock
,
1059 "Control socket to relayd");
1062 PERROR("accepting sock");
1066 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1069 PERROR("setsockopt inet");
1070 lttcomm_destroy_sock(newsock
);
1074 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1076 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1078 lttcomm_destroy_sock(newsock
);
1082 new_conn
= connection_create(newsock
, type
);
1084 lttcomm_destroy_sock(newsock
);
1088 /* Enqueue request for the dispatcher thread. */
1089 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1093 * Wake the dispatch queue futex.
1094 * Implicit memory barrier with the
1095 * exchange in cds_wfcq_enqueue.
1097 futex_nto1_wake(&relay_conn_queue
.futex
);
1098 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1099 ERR("socket poll error");
1102 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1112 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1114 if (data_sock
->fd
>= 0) {
1115 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1116 &data_sock
->fd
, 1, close_sock
,
1122 lttcomm_destroy_sock(data_sock
);
1124 if (control_sock
->fd
>= 0) {
1125 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1126 &control_sock
->fd
, 1, close_sock
,
1132 lttcomm_destroy_sock(control_sock
);
1136 ERR("Health error occurred in %s", __func__
);
1138 health_unregister(health_relayd
);
1139 DBG("Relay listener thread cleanup complete");
1140 lttng_relay_stop_threads();
1145 * This thread manages the dispatching of the requests to worker threads
1147 static void *relay_thread_dispatcher(void *data
)
1151 struct cds_wfcq_node
*node
;
1152 struct relay_connection
*new_conn
= NULL
;
1154 DBG("[thread] Relay dispatcher started");
1156 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1158 if (testpoint(relayd_thread_dispatcher
)) {
1159 goto error_testpoint
;
1162 health_code_update();
1165 health_code_update();
1167 /* Atomically prepare the queue futex */
1168 futex_nto1_prepare(&relay_conn_queue
.futex
);
1170 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1175 health_code_update();
1177 /* Dequeue commands */
1178 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1179 &relay_conn_queue
.tail
);
1181 DBG("Woken up but nothing in the relay command queue");
1182 /* Continue thread execution */
1185 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1187 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1190 * Inform worker thread of the new request. This
1191 * call is blocking so we can be assured that
1192 * the data will be read at some point in time
1193 * or wait to the end of the world :)
1195 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1197 PERROR("write connection pipe");
1198 connection_put(new_conn
);
1201 } while (node
!= NULL
);
1203 /* Futex wait on queue. Blocking call on futex() */
1204 health_poll_entry();
1205 futex_nto1_wait(&relay_conn_queue
.futex
);
1209 /* Normal exit, no error */
1216 ERR("Health error occurred in %s", __func__
);
1218 health_unregister(health_relayd
);
1219 DBG("Dispatch thread dying");
1220 lttng_relay_stop_threads();
1225 * Set index data from the control port to a given index object.
1227 static int set_index_control_data(struct relay_index
*index
,
1228 struct lttcomm_relayd_index
*data
,
1229 struct relay_connection
*conn
)
1231 struct ctf_packet_index index_data
;
1234 * The index on disk is encoded in big endian.
1236 index_data
.packet_size
= htobe64(data
->packet_size
);
1237 index_data
.content_size
= htobe64(data
->content_size
);
1238 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1239 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1240 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1241 index_data
.stream_id
= htobe64(data
->stream_id
);
1243 if (conn
->minor
>= 8) {
1244 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1245 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1248 return relay_index_set_data(index
, &index_data
);
1252 * Handle the RELAYD_CREATE_SESSION command.
1254 * On success, send back the session id or else return a negative value.
1256 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1257 struct relay_connection
*conn
,
1258 const struct lttng_buffer_view
*payload
)
1262 struct relay_session
*session
;
1263 struct lttcomm_relayd_status_session reply
;
1264 char session_name
[LTTNG_NAME_MAX
];
1265 char hostname
[LTTNG_HOST_NAME_MAX
];
1266 uint32_t live_timer
= 0;
1267 bool snapshot
= false;
1269 memset(session_name
, 0, LTTNG_NAME_MAX
);
1270 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1272 memset(&reply
, 0, sizeof(reply
));
1274 if (conn
->minor
< 4) {
1275 /* From 2.1 to 2.3 */
1277 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1278 /* From 2.4 to 2.10 */
1279 ret
= cmd_create_session_2_4(payload
, session_name
,
1280 hostname
, &live_timer
, &snapshot
);
1282 /* From 2.11 to ... */
1283 ret
= cmd_create_session_2_11(payload
, session_name
,
1284 hostname
, &live_timer
, &snapshot
);
1291 session
= session_create(session_name
, hostname
, live_timer
,
1292 snapshot
, conn
->major
, conn
->minor
);
1297 assert(!conn
->session
);
1298 conn
->session
= session
;
1299 DBG("Created session %" PRIu64
, session
->id
);
1301 reply
.session_id
= htobe64(session
->id
);
1305 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1307 reply
.ret_code
= htobe32(LTTNG_OK
);
1310 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1311 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1312 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1321 * When we have received all the streams and the metadata for a channel,
1322 * we make them visible to the viewer threads.
1324 static void publish_connection_local_streams(struct relay_connection
*conn
)
1326 struct relay_stream
*stream
;
1327 struct relay_session
*session
= conn
->session
;
1330 * We publish all streams belonging to a session atomically wrt
1333 pthread_mutex_lock(&session
->lock
);
1335 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1337 stream_publish(stream
);
1342 * Inform the viewer that there are new streams in the session.
1344 if (session
->viewer_attached
) {
1345 uatomic_set(&session
->new_streams
, 1);
1347 pthread_mutex_unlock(&session
->lock
);
1351 * relay_add_stream: allocate a new stream for a session
1353 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1354 struct relay_connection
*conn
,
1355 const struct lttng_buffer_view
*payload
)
1359 struct relay_session
*session
= conn
->session
;
1360 struct relay_stream
*stream
= NULL
;
1361 struct lttcomm_relayd_status_stream reply
;
1362 struct ctf_trace
*trace
= NULL
;
1363 uint64_t stream_handle
= -1ULL;
1364 char *path_name
= NULL
, *channel_name
= NULL
;
1365 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1366 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1368 if (!session
|| !conn
->version_check_done
) {
1369 ERR("Trying to add a stream before version check");
1371 goto end_no_session
;
1374 if (session
->minor
== 1) {
1376 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1378 } else if (session
->minor
> 1 && session
->minor
< 11) {
1379 /* From 2.2 to 2.10 */
1380 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1381 &channel_name
, &tracefile_size
, &tracefile_count
);
1383 /* From 2.11 to ... */
1384 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1385 &channel_name
, &tracefile_size
, &tracefile_count
,
1386 &stream_chunk_id
.value
);
1387 stream_chunk_id
.is_set
= true;
1394 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1398 /* This stream here has one reference on the trace. */
1400 pthread_mutex_lock(&last_relay_stream_id_lock
);
1401 stream_handle
= ++last_relay_stream_id
;
1402 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1404 /* We pass ownership of path_name and channel_name. */
1405 stream
= stream_create(trace
, stream_handle
, path_name
,
1406 channel_name
, tracefile_size
, tracefile_count
,
1409 channel_name
= NULL
;
1412 * Streams are the owners of their trace. Reference to trace is
1413 * kept within stream_create().
1415 ctf_trace_put(trace
);
1418 memset(&reply
, 0, sizeof(reply
));
1419 reply
.handle
= htobe64(stream_handle
);
1421 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1423 reply
.ret_code
= htobe32(LTTNG_OK
);
1426 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1427 sizeof(struct lttcomm_relayd_status_stream
), 0);
1428 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1429 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1441 * relay_close_stream: close a specific stream
1443 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1444 struct relay_connection
*conn
,
1445 const struct lttng_buffer_view
*payload
)
1449 struct relay_session
*session
= conn
->session
;
1450 struct lttcomm_relayd_close_stream stream_info
;
1451 struct lttcomm_relayd_generic_reply reply
;
1452 struct relay_stream
*stream
;
1454 DBG("Close stream received");
1456 if (!session
|| !conn
->version_check_done
) {
1457 ERR("Trying to close a stream before version check");
1459 goto end_no_session
;
1462 if (payload
->size
< sizeof(stream_info
)) {
1463 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1464 sizeof(stream_info
), payload
->size
);
1466 goto end_no_session
;
1468 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1469 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1470 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1472 stream
= stream_get_by_id(stream_info
.stream_id
);
1479 * Set last_net_seq_num before the close flag. Required by data
1482 pthread_mutex_lock(&stream
->lock
);
1483 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1484 pthread_mutex_unlock(&stream
->lock
);
1487 * This is one of the conditions which may trigger a stream close
1488 * with the others being:
1489 * 1) A close command is received for a stream
1490 * 2) The control connection owning the stream is closed
1491 * 3) We have received all of the stream's data _after_ a close
1494 try_stream_close(stream
);
1495 if (stream
->is_metadata
) {
1496 struct relay_viewer_stream
*vstream
;
1498 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1500 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1502 * Since all the metadata has been sent to the
1503 * viewer and that we have a request to close
1504 * its stream, we can safely teardown the
1505 * corresponding metadata viewer stream.
1507 viewer_stream_put(vstream
);
1509 /* Put local reference. */
1510 viewer_stream_put(vstream
);
1517 memset(&reply
, 0, sizeof(reply
));
1519 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1521 reply
.ret_code
= htobe32(LTTNG_OK
);
1523 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1524 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1525 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1526 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1536 * relay_reset_metadata: reset a metadata stream
1539 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1540 struct relay_connection
*conn
,
1541 const struct lttng_buffer_view
*payload
)
1545 struct relay_session
*session
= conn
->session
;
1546 struct lttcomm_relayd_reset_metadata stream_info
;
1547 struct lttcomm_relayd_generic_reply reply
;
1548 struct relay_stream
*stream
;
1550 DBG("Reset metadata received");
1552 if (!session
|| !conn
->version_check_done
) {
1553 ERR("Trying to reset a metadata stream before version check");
1555 goto end_no_session
;
1558 if (payload
->size
< sizeof(stream_info
)) {
1559 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1560 sizeof(stream_info
), payload
->size
);
1562 goto end_no_session
;
1564 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1565 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1566 stream_info
.version
= be64toh(stream_info
.version
);
1568 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1570 /* Unsupported for live sessions for now. */
1571 if (session
->live_timer
!= 0) {
1576 stream
= stream_get_by_id(stream_info
.stream_id
);
1581 pthread_mutex_lock(&stream
->lock
);
1582 if (!stream
->is_metadata
) {
1587 ret
= stream_fd_rotate(stream
->stream_fd
,
1588 stream
->path_name
, stream
->channel_name
, 0, 0, NULL
);
1590 ERR("Failed to rotate metadata file %s of channel %s",
1591 stream
->path_name
, stream
->channel_name
);
1596 pthread_mutex_unlock(&stream
->lock
);
1600 memset(&reply
, 0, sizeof(reply
));
1602 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1604 reply
.ret_code
= htobe32(LTTNG_OK
);
1606 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1607 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1608 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1609 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1619 * relay_unknown_command: send -1 if received unknown command
1621 static void relay_unknown_command(struct relay_connection
*conn
)
1623 struct lttcomm_relayd_generic_reply reply
;
1626 memset(&reply
, 0, sizeof(reply
));
1627 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1628 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1629 if (send_ret
< sizeof(reply
)) {
1630 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1635 * relay_start: send an acknowledgment to the client to tell if we are
1636 * ready to receive data. We are ready if a session is established.
1638 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1639 struct relay_connection
*conn
,
1640 const struct lttng_buffer_view
*payload
)
1644 struct lttcomm_relayd_generic_reply reply
;
1645 struct relay_session
*session
= conn
->session
;
1648 DBG("Trying to start the streaming without a session established");
1649 ret
= htobe32(LTTNG_ERR_UNK
);
1652 memset(&reply
, 0, sizeof(reply
));
1653 reply
.ret_code
= htobe32(LTTNG_OK
);
1654 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1656 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1657 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1666 * Append padding to the file pointed by the file descriptor fd.
1668 static int write_padding_to_file(int fd
, uint32_t size
)
1677 zeros
= zmalloc(size
);
1678 if (zeros
== NULL
) {
1679 PERROR("zmalloc zeros for padding");
1684 ret
= lttng_write(fd
, zeros
, size
);
1686 PERROR("write padding to file");
1696 * Close the current index file if it is open, and create a new one.
1698 * Return 0 on success, -1 on error.
1701 int create_rotate_index_file(struct relay_stream
*stream
)
1704 uint32_t major
, minor
;
1706 /* Put ref on previous index_file. */
1707 if (stream
->index_file
) {
1708 relay_index_file_put(stream
->index_file
);
1709 stream
->index_file
= NULL
;
1711 major
= stream
->trace
->session
->major
;
1712 minor
= stream
->trace
->session
->minor
;
1713 stream
->index_file
= relay_index_file_create(stream
->path_name
,
1714 stream
->channel_name
,
1715 stream
->tracefile_size
,
1716 tracefile_array_get_file_index_head(stream
->tfa
),
1717 lttng_to_index_major(major
, minor
),
1718 lttng_to_index_minor(major
, minor
));
1719 if (!stream
->index_file
) {
1731 int do_rotate_stream(struct relay_stream
*stream
)
1735 /* Perform the stream rotation. */
1736 ret
= stream_fd_rotate(stream
->stream_fd
, stream
->path_name
,
1737 stream
->channel_name
, stream
->tracefile_size
,
1738 stream
->tracefile_count
, NULL
);
1740 ERR("Rotating stream output file");
1743 stream
->tracefile_size_current
= 0;
1745 /* Rotate also the index if the stream is not a metadata stream. */
1746 if (!stream
->is_metadata
) {
1747 ret
= create_rotate_index_file(stream
);
1749 ERR("Failed to rotate index file");
1754 stream
->rotate_at_seq_num
= -1ULL;
1755 stream
->pos_after_last_complete_data_index
= 0;
1762 * If too much data has been written in a tracefile before we received the
1763 * rotation command, we have to move the excess data to the new tracefile and
1764 * perform the rotation. This can happen because the control and data
1765 * connections are separate, the indexes as well as the commands arrive from
1766 * the control connection and we have no control over the order so we could be
1767 * in a situation where too much data has been received on the data connection
1768 * before the rotation command on the control connection arrives. We don't need
1769 * to update the index because its order is guaranteed with the rotation
1773 int rotate_truncate_stream(struct relay_stream
*stream
)
1775 int ret
, old_fd
= -1, new_fd
= -1;
1777 uint64_t diff
, pos
= 0;
1778 char buf
[FILE_COPY_BUFFER_SIZE
];
1779 struct stream_fd
*new_stream_fd
= NULL
;
1781 assert(!stream
->is_metadata
);
1783 assert(stream
->tracefile_size_current
>
1784 stream
->pos_after_last_complete_data_index
);
1785 diff
= stream
->tracefile_size_current
-
1786 stream
->pos_after_last_complete_data_index
;
1788 /* Create the new tracefile. */
1789 new_stream_fd
= stream_fd_create(stream
->path_name
, stream
->channel_name
,
1790 stream
->tracefile_size
, stream
->tracefile_count
, NULL
);
1791 if (new_stream_fd
< 0) {
1792 ERR("Failed to create new stream file at path %s for channel %s",
1793 stream
->path_name
, stream
->channel_name
);
1798 old_fd
= stream_fd_get_fd(stream
->stream_fd
);
1804 new_fd
= stream_fd_get_fd(new_stream_fd
);
1811 * Rewind the current tracefile to the position at which the rotation
1812 * should have occured.
1814 lseek_ret
= lseek(old_fd
, stream
->pos_after_last_complete_data_index
,
1816 if (lseek_ret
< 0) {
1817 PERROR("seek truncate stream");
1822 /* Move data from the old file to the new file. */
1823 while (pos
< diff
) {
1824 uint64_t count
, bytes_left
;
1827 bytes_left
= diff
- pos
;
1828 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1829 assert(count
<= SIZE_MAX
);
1831 io_ret
= lttng_read(old_fd
, buf
, count
);
1832 if (io_ret
< (ssize_t
) count
) {
1833 char error_string
[256];
1835 snprintf(error_string
, sizeof(error_string
),
1836 "Failed to read %" PRIu64
" bytes from in rotate_truncate_stream(), returned %zi",
1839 PERROR("%s", error_string
);
1841 ERR("%s", error_string
);
1847 io_ret
= lttng_write(new_fd
, buf
, count
);
1848 if (io_ret
< (ssize_t
) count
) {
1849 char error_string
[256];
1851 snprintf(error_string
, sizeof(error_string
),
1852 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1853 count
, new_fd
, io_ret
);
1855 PERROR("%s", error_string
);
1857 ERR("%s", error_string
);
1866 stream_fd_put_fd(new_stream_fd
);
1869 /* Truncate the file to get rid of the excess data. */
1870 ret
= ftruncate(old_fd
, stream
->pos_after_last_complete_data_index
);
1872 PERROR("ftruncate");
1876 stream_fd_put_fd(stream
->stream_fd
);
1880 * Swap the old stream_fd with the new, releasing the stream's
1883 stream_fd_put(stream
->stream_fd
);
1884 stream
->stream_fd
= new_stream_fd
;
1886 ret
= create_rotate_index_file(stream
);
1888 ERR("Rotate stream index file");
1893 * Update the offset and FD of all the eventual indexes created by the
1894 * data connection before the rotation command arrived.
1896 ret
= relay_index_switch_all_files(stream
);
1898 ERR("Failed to rotate index file");
1902 stream
->tracefile_size_current
= diff
;
1903 stream
->pos_after_last_complete_data_index
= 0;
1904 stream
->rotate_at_seq_num
= -1ULL;
1910 stream_fd_put_fd(stream
->stream_fd
);
1913 stream_fd_put_fd(new_stream_fd
);
1920 * Check if a stream should perform a rotation (for session rotation).
1921 * Must be called with the stream lock held.
1923 * Return 0 on success, a negative value on error.
1926 int try_rotate_stream(struct relay_stream
*stream
)
1930 /* No rotation expected. */
1931 if (stream
->rotate_at_seq_num
== -1ULL) {
1935 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1936 stream
->prev_seq
== -1ULL) {
1937 DBG("Stream %" PRIu64
" no yet ready for rotation",
1938 stream
->stream_handle
);
1940 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1941 DBG("Rotation after too much data has been written in tracefile "
1942 "for stream %" PRIu64
", need to truncate before "
1943 "rotating", stream
->stream_handle
);
1944 ret
= rotate_truncate_stream(stream
);
1946 ERR("Failed to truncate stream");
1950 /* stream->prev_seq == stream->rotate_at_seq_num */
1951 DBG("Stream %" PRIu64
" ready for rotation",
1952 stream
->stream_handle
);
1953 ret
= do_rotate_stream(stream
);
1961 * relay_recv_metadata: receive the metadata for the session.
1963 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1964 struct relay_connection
*conn
,
1965 const struct lttng_buffer_view
*payload
)
1969 struct relay_session
*session
= conn
->session
;
1970 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1971 struct relay_stream
*metadata_stream
;
1972 uint64_t metadata_payload_size
;
1973 int metadata_fd
= -1;
1976 ERR("Metadata sent before version check");
1981 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1982 ERR("Incorrect data size");
1986 metadata_payload_size
= recv_hdr
->data_size
-
1987 sizeof(struct lttcomm_relayd_metadata_payload
);
1989 memcpy(&metadata_payload_header
, payload
->data
,
1990 sizeof(metadata_payload_header
));
1991 metadata_payload_header
.stream_id
= be64toh(
1992 metadata_payload_header
.stream_id
);
1993 metadata_payload_header
.padding_size
= be32toh(
1994 metadata_payload_header
.padding_size
);
1996 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1997 if (!metadata_stream
) {
2002 pthread_mutex_lock(&metadata_stream
->lock
);
2004 metadata_fd
= stream_fd_get_fd(metadata_stream
->stream_fd
);
2005 if (metadata_fd
< 0) {
2008 size_ret
= lttng_write(metadata_fd
,
2009 payload
->data
+ sizeof(metadata_payload_header
),
2010 metadata_payload_size
);
2011 if (size_ret
< metadata_payload_size
) {
2012 ERR("Relay error writing metadata on file");
2017 size_ret
= write_padding_to_file(metadata_fd
,
2018 metadata_payload_header
.padding_size
);
2019 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
2024 metadata_stream
->metadata_received
+=
2025 metadata_payload_size
+ metadata_payload_header
.padding_size
;
2026 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
2027 metadata_stream
->metadata_received
);
2029 ret
= try_rotate_stream(metadata_stream
);
2035 stream_fd_put_fd(metadata_stream
->stream_fd
);
2037 pthread_mutex_unlock(&metadata_stream
->lock
);
2038 stream_put(metadata_stream
);
2044 * relay_send_version: send relayd version number
2046 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
2047 struct relay_connection
*conn
,
2048 const struct lttng_buffer_view
*payload
)
2052 struct lttcomm_relayd_version reply
, msg
;
2053 bool compatible
= true;
2055 conn
->version_check_done
= true;
2057 /* Get version from the other side. */
2058 if (payload
->size
< sizeof(msg
)) {
2059 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
2060 sizeof(msg
), payload
->size
);
2065 memcpy(&msg
, payload
->data
, sizeof(msg
));
2066 msg
.major
= be32toh(msg
.major
);
2067 msg
.minor
= be32toh(msg
.minor
);
2069 memset(&reply
, 0, sizeof(reply
));
2070 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2071 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2073 /* Major versions must be the same */
2074 if (reply
.major
!= msg
.major
) {
2075 DBG("Incompatible major versions (%u vs %u), deleting session",
2076 reply
.major
, msg
.major
);
2080 conn
->major
= reply
.major
;
2081 /* We adapt to the lowest compatible version */
2082 if (reply
.minor
<= msg
.minor
) {
2083 conn
->minor
= reply
.minor
;
2085 conn
->minor
= msg
.minor
;
2088 reply
.major
= htobe32(reply
.major
);
2089 reply
.minor
= htobe32(reply
.minor
);
2090 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2092 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2093 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2106 DBG("Version check done using protocol %u.%u", conn
->major
,
2114 * Check for data pending for a given stream id from the session daemon.
2116 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2117 struct relay_connection
*conn
,
2118 const struct lttng_buffer_view
*payload
)
2120 struct relay_session
*session
= conn
->session
;
2121 struct lttcomm_relayd_data_pending msg
;
2122 struct lttcomm_relayd_generic_reply reply
;
2123 struct relay_stream
*stream
;
2127 DBG("Data pending command received");
2129 if (!session
|| !conn
->version_check_done
) {
2130 ERR("Trying to check for data before version check");
2132 goto end_no_session
;
2135 if (payload
->size
< sizeof(msg
)) {
2136 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2137 sizeof(msg
), payload
->size
);
2139 goto end_no_session
;
2141 memcpy(&msg
, payload
->data
, sizeof(msg
));
2142 msg
.stream_id
= be64toh(msg
.stream_id
);
2143 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2145 stream
= stream_get_by_id(msg
.stream_id
);
2146 if (stream
== NULL
) {
2151 pthread_mutex_lock(&stream
->lock
);
2153 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2154 " and last_seq %" PRIu64
, msg
.stream_id
,
2155 stream
->prev_seq
, msg
.last_net_seq_num
);
2157 /* Avoid wrapping issue */
2158 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2159 /* Data has in fact been written and is NOT pending */
2162 /* Data still being streamed thus pending */
2166 stream
->data_pending_check_done
= true;
2167 pthread_mutex_unlock(&stream
->lock
);
2172 memset(&reply
, 0, sizeof(reply
));
2173 reply
.ret_code
= htobe32(ret
);
2174 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2175 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2176 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2186 * Wait for the control socket to reach a quiescent state.
2188 * Note that for now, when receiving this command from the session
2189 * daemon, this means that every subsequent commands or data received on
2190 * the control socket has been handled. So, this is why we simply return
2193 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2194 struct relay_connection
*conn
,
2195 const struct lttng_buffer_view
*payload
)
2199 struct relay_stream
*stream
;
2200 struct lttcomm_relayd_quiescent_control msg
;
2201 struct lttcomm_relayd_generic_reply reply
;
2203 DBG("Checking quiescent state on control socket");
2205 if (!conn
->session
|| !conn
->version_check_done
) {
2206 ERR("Trying to check for data before version check");
2208 goto end_no_session
;
2211 if (payload
->size
< sizeof(msg
)) {
2212 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2213 sizeof(msg
), payload
->size
);
2215 goto end_no_session
;
2217 memcpy(&msg
, payload
->data
, sizeof(msg
));
2218 msg
.stream_id
= be64toh(msg
.stream_id
);
2220 stream
= stream_get_by_id(msg
.stream_id
);
2224 pthread_mutex_lock(&stream
->lock
);
2225 stream
->data_pending_check_done
= true;
2226 pthread_mutex_unlock(&stream
->lock
);
2228 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2231 memset(&reply
, 0, sizeof(reply
));
2232 reply
.ret_code
= htobe32(LTTNG_OK
);
2233 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2234 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2235 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2247 * Initialize a data pending command. This means that a consumer is about
2248 * to ask for data pending for each stream it holds. Simply iterate over
2249 * all streams of a session and set the data_pending_check_done flag.
2251 * This command returns to the client a LTTNG_OK code.
2253 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2254 struct relay_connection
*conn
,
2255 const struct lttng_buffer_view
*payload
)
2259 struct lttng_ht_iter iter
;
2260 struct lttcomm_relayd_begin_data_pending msg
;
2261 struct lttcomm_relayd_generic_reply reply
;
2262 struct relay_stream
*stream
;
2267 DBG("Init streams for data pending");
2269 if (!conn
->session
|| !conn
->version_check_done
) {
2270 ERR("Trying to check for data before version check");
2272 goto end_no_session
;
2275 if (payload
->size
< sizeof(msg
)) {
2276 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2277 sizeof(msg
), payload
->size
);
2279 goto end_no_session
;
2281 memcpy(&msg
, payload
->data
, sizeof(msg
));
2282 msg
.session_id
= be64toh(msg
.session_id
);
2285 * Iterate over all streams to set the begin data pending flag.
2286 * For now, the streams are indexed by stream handle so we have
2287 * to iterate over all streams to find the one associated with
2288 * the right session_id.
2291 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2293 if (!stream_get(stream
)) {
2296 if (stream
->trace
->session
->id
== msg
.session_id
) {
2297 pthread_mutex_lock(&stream
->lock
);
2298 stream
->data_pending_check_done
= false;
2299 pthread_mutex_unlock(&stream
->lock
);
2300 DBG("Set begin data pending flag to stream %" PRIu64
,
2301 stream
->stream_handle
);
2307 memset(&reply
, 0, sizeof(reply
));
2308 /* All good, send back reply. */
2309 reply
.ret_code
= htobe32(LTTNG_OK
);
2311 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2312 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2313 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2325 * End data pending command. This will check, for a given session id, if
2326 * each stream associated with it has its data_pending_check_done flag
2327 * set. If not, this means that the client lost track of the stream but
2328 * the data is still being streamed on our side. In this case, we inform
2329 * the client that data is in flight.
2331 * Return to the client if there is data in flight or not with a ret_code.
2333 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2334 struct relay_connection
*conn
,
2335 const struct lttng_buffer_view
*payload
)
2339 struct lttng_ht_iter iter
;
2340 struct lttcomm_relayd_end_data_pending msg
;
2341 struct lttcomm_relayd_generic_reply reply
;
2342 struct relay_stream
*stream
;
2343 uint32_t is_data_inflight
= 0;
2345 DBG("End data pending command");
2347 if (!conn
->session
|| !conn
->version_check_done
) {
2348 ERR("Trying to check for data before version check");
2350 goto end_no_session
;
2353 if (payload
->size
< sizeof(msg
)) {
2354 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2355 sizeof(msg
), payload
->size
);
2357 goto end_no_session
;
2359 memcpy(&msg
, payload
->data
, sizeof(msg
));
2360 msg
.session_id
= be64toh(msg
.session_id
);
2363 * Iterate over all streams to see if the begin data pending
2367 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2369 if (!stream_get(stream
)) {
2372 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2376 pthread_mutex_lock(&stream
->lock
);
2377 if (!stream
->data_pending_check_done
) {
2378 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2379 is_data_inflight
= 1;
2380 DBG("Data is still in flight for stream %" PRIu64
,
2381 stream
->stream_handle
);
2382 pthread_mutex_unlock(&stream
->lock
);
2387 pthread_mutex_unlock(&stream
->lock
);
2392 memset(&reply
, 0, sizeof(reply
));
2393 /* All good, send back reply. */
2394 reply
.ret_code
= htobe32(is_data_inflight
);
2396 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2397 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2398 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2410 * Receive an index for a specific stream.
2412 * Return 0 on success else a negative value.
2414 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2415 struct relay_connection
*conn
,
2416 const struct lttng_buffer_view
*payload
)
2420 struct relay_session
*session
= conn
->session
;
2421 struct lttcomm_relayd_index index_info
;
2422 struct relay_index
*index
;
2423 struct lttcomm_relayd_generic_reply reply
;
2424 struct relay_stream
*stream
;
2429 DBG("Relay receiving index");
2431 if (!session
|| !conn
->version_check_done
) {
2432 ERR("Trying to close a stream before version check");
2434 goto end_no_session
;
2437 msg_len
= lttcomm_relayd_index_len(
2438 lttng_to_index_major(conn
->major
, conn
->minor
),
2439 lttng_to_index_minor(conn
->major
, conn
->minor
));
2440 if (payload
->size
< msg_len
) {
2441 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2442 msg_len
, payload
->size
);
2444 goto end_no_session
;
2446 memcpy(&index_info
, payload
->data
, msg_len
);
2447 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2448 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2449 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2450 index_info
.content_size
= be64toh(index_info
.content_size
);
2451 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2452 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2453 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2454 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2456 if (conn
->minor
>= 8) {
2457 index_info
.stream_instance_id
=
2458 be64toh(index_info
.stream_instance_id
);
2459 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2462 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2464 ERR("stream_get_by_id not found");
2468 pthread_mutex_lock(&stream
->lock
);
2470 /* Live beacon handling */
2471 if (index_info
.packet_size
== 0) {
2472 DBG("Received live beacon for stream %" PRIu64
,
2473 stream
->stream_handle
);
2476 * Only flag a stream inactive when it has already
2477 * received data and no indexes are in flight.
2479 if (stream
->index_received_seqcount
> 0
2480 && stream
->indexes_in_flight
== 0) {
2481 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2484 goto end_stream_put
;
2486 stream
->beacon_ts_end
= -1ULL;
2489 if (stream
->ctf_stream_id
== -1ULL) {
2490 stream
->ctf_stream_id
= index_info
.stream_id
;
2492 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2495 ERR("relay_index_get_by_id_or_create index NULL");
2496 goto end_stream_put
;
2498 if (set_index_control_data(index
, &index_info
, conn
)) {
2499 ERR("set_index_control_data error");
2500 relay_index_put(index
);
2502 goto end_stream_put
;
2504 ret
= relay_index_try_flush(index
);
2506 tracefile_array_commit_seq(stream
->tfa
);
2507 stream
->index_received_seqcount
++;
2508 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2509 } else if (ret
> 0) {
2513 ERR("relay_index_try_flush error %d", ret
);
2514 relay_index_put(index
);
2519 pthread_mutex_unlock(&stream
->lock
);
2524 memset(&reply
, 0, sizeof(reply
));
2526 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2528 reply
.ret_code
= htobe32(LTTNG_OK
);
2530 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2531 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2532 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2541 * Receive the streams_sent message.
2543 * Return 0 on success else a negative value.
2545 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2546 struct relay_connection
*conn
,
2547 const struct lttng_buffer_view
*payload
)
2551 struct lttcomm_relayd_generic_reply reply
;
2555 DBG("Relay receiving streams_sent");
2557 if (!conn
->session
|| !conn
->version_check_done
) {
2558 ERR("Trying to close a stream before version check");
2560 goto end_no_session
;
2564 * Publish every pending stream in the connection recv list which are
2565 * now ready to be used by the viewer.
2567 publish_connection_local_streams(conn
);
2569 memset(&reply
, 0, sizeof(reply
));
2570 reply
.ret_code
= htobe32(LTTNG_OK
);
2571 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2572 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2573 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2586 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2587 * rotation feature (not the tracefile rotation feature).
2589 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2590 struct relay_connection
*conn
,
2591 const struct lttng_buffer_view
*payload
)
2595 struct relay_session
*session
= conn
->session
;
2596 struct lttcomm_relayd_rotate_stream stream_info
;
2597 struct lttcomm_relayd_generic_reply reply
;
2598 struct relay_stream
*stream
;
2601 struct lttng_buffer_view new_path_view
;
2603 DBG("Rotate stream received");
2605 if (!session
|| !conn
->version_check_done
) {
2606 ERR("Trying to rotate a stream before version check");
2611 if (session
->major
== 2 && session
->minor
< 11) {
2612 ERR("Unsupported feature before 2.11");
2617 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2619 if (payload
->size
< header_len
) {
2620 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2621 header_len
, payload
->size
);
2626 memcpy(&stream_info
, payload
->data
, header_len
);
2628 /* Convert to host */
2629 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2630 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2631 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2632 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2634 path_len
= stream_info
.pathname_length
;
2635 if (payload
->size
< header_len
+ path_len
) {
2636 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2637 header_len
+ path_len
, payload
->size
);
2642 /* Ensure it fits in local filename length. */
2643 if (path_len
>= LTTNG_PATH_MAX
) {
2644 ret
= -ENAMETOOLONG
;
2645 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2646 path_len
, LTTNG_PATH_MAX
);
2650 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2651 stream_info
.pathname_length
);
2653 stream
= stream_get_by_id(stream_info
.stream_id
);
2659 pthread_mutex_lock(&stream
->lock
);
2662 * Update the trace path (just the folder, the stream name does not
2665 free(stream
->path_name
);
2666 stream
->path_name
= create_output_path(new_path_view
.data
);
2667 if (!stream
->path_name
) {
2668 ERR("Failed to create a new output path");
2670 goto end_stream_unlock
;
2672 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2675 ERR("relay creating output directory");
2677 goto end_stream_unlock
;
2680 assert(stream
->current_chunk_id
.is_set
);
2681 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2683 if (stream
->is_metadata
) {
2685 * The metadata stream is sent only over the control connection
2686 * so we know we have all the data to perform the stream
2689 ret
= do_rotate_stream(stream
);
2691 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2692 ret
= try_rotate_stream(stream
);
2695 goto end_stream_unlock
;
2699 pthread_mutex_unlock(&stream
->lock
);
2702 memset(&reply
, 0, sizeof(reply
));
2704 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2706 reply
.ret_code
= htobe32(LTTNG_OK
);
2708 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2709 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2710 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2711 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2721 * relay_mkdir: Create a folder on the disk.
2723 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2724 struct relay_connection
*conn
,
2725 const struct lttng_buffer_view
*payload
)
2728 struct relay_session
*session
= conn
->session
;
2729 struct lttcomm_relayd_mkdir path_info_header
;
2730 struct lttcomm_relayd_generic_reply reply
;
2734 struct lttng_buffer_view path_view
;
2736 if (!session
|| !conn
->version_check_done
) {
2737 ERR("Trying to create a directory before version check");
2739 goto end_no_session
;
2742 if (session
->major
== 2 && session
->minor
< 11) {
2744 * This client is not supposed to use this command since
2745 * it predates its introduction.
2747 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2749 goto end_no_session
;
2752 header_len
= sizeof(path_info_header
);
2753 if (payload
->size
< header_len
) {
2754 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2755 header_len
, payload
->size
);
2757 goto end_no_session
;
2760 memcpy(&path_info_header
, payload
->data
, header_len
);
2762 path_info_header
.length
= be32toh(path_info_header
.length
);
2764 if (payload
->size
< header_len
+ path_info_header
.length
) {
2765 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2766 header_len
+ path_info_header
.length
, payload
->size
);
2768 goto end_no_session
;
2771 /* Ensure that it fits in local path length. */
2772 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2773 ret
= -ENAMETOOLONG
;
2774 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2775 path_info_header
.length
, LTTNG_PATH_MAX
);
2779 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2780 path_info_header
.length
);
2782 path
= create_output_path(path_view
.data
);
2784 ERR("Failed to create output path");
2789 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2791 ERR("relay creating output directory");
2798 memset(&reply
, 0, sizeof(reply
));
2800 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2802 reply
.ret_code
= htobe32(LTTNG_OK
);
2804 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2805 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2806 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2815 static int validate_rotate_rename_path_length(const char *path_type
,
2816 uint32_t path_length
)
2820 if (path_length
> LTTNG_PATH_MAX
) {
2821 ret
= -ENAMETOOLONG
;
2822 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2823 path_type
, path_length
, LTTNG_PATH_MAX
);
2824 } else if (path_length
== 0) {
2826 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2832 * relay_rotate_rename: rename the trace folder after a rotation is
2833 * completed. We are not closing any fd here, just moving the folder, so it
2834 * works even if data is still in-flight.
2836 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2837 struct relay_connection
*conn
,
2838 const struct lttng_buffer_view
*payload
)
2842 struct relay_session
*session
= conn
->session
;
2843 struct lttcomm_relayd_generic_reply reply
;
2844 struct lttcomm_relayd_rotate_rename header
;
2846 size_t received_paths_size
;
2847 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2848 struct lttng_buffer_view old_path_view
;
2849 struct lttng_buffer_view new_path_view
;
2851 if (!session
|| !conn
->version_check_done
) {
2852 ERR("Trying to rename a trace folder before version check");
2857 if (session
->major
== 2 && session
->minor
< 11) {
2858 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2863 header_len
= sizeof(header
);
2864 if (payload
->size
< header_len
) {
2865 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2866 header_len
, payload
->size
);
2871 memcpy(&header
, payload
->data
, header_len
);
2873 header
.old_path_length
= be32toh(header
.old_path_length
);
2874 header
.new_path_length
= be32toh(header
.new_path_length
);
2875 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2877 if (payload
->size
< header_len
+ received_paths_size
) {
2878 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2879 header_len
, payload
->size
);
2884 /* Ensure the paths don't exceed their allowed size. */
2885 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2889 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2894 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2895 header
.old_path_length
);
2896 new_path_view
= lttng_buffer_view_from_view(payload
,
2897 header_len
+ header
.old_path_length
,
2898 header
.new_path_length
);
2900 /* Validate that both paths received are NULL terminated. */
2901 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2902 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2906 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2907 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2912 complete_old_path
= create_output_path(old_path_view
.data
);
2913 if (!complete_old_path
) {
2914 ERR("Failed to build old output path in rotate_rename command");
2919 complete_new_path
= create_output_path(new_path_view
.data
);
2920 if (!complete_new_path
) {
2921 ERR("Failed to build new output path in rotate_rename command");
2926 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2929 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2935 * If a domain has not yet created its channel, the domain-specific
2936 * folder might not exist, but this is not an error.
2938 ret
= rename(complete_old_path
, complete_new_path
);
2939 if (ret
< 0 && errno
!= ENOENT
) {
2940 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2941 complete_old_path
, complete_new_path
);
2947 memset(&reply
, 0, sizeof(reply
));
2949 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2951 reply
.ret_code
= htobe32(LTTNG_OK
);
2953 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2955 if (send_ret
< sizeof(reply
)) {
2956 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2962 free(complete_old_path
);
2963 free(complete_new_path
);
2968 * Check if all the streams in the session have completed the last rotation.
2969 * The chunk_id value is used to distinguish the cases where a stream was
2970 * closed on the consumerd before the rotation started but it still active on
2971 * the relayd, and the case where a stream appeared on the consumerd/relayd
2972 * after the last rotation started (in that case, it is already writing in the
2973 * new chunk folder).
2976 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2977 struct relay_connection
*conn
,
2978 const struct lttng_buffer_view
*payload
)
2980 struct relay_session
*session
= conn
->session
;
2981 struct lttcomm_relayd_rotate_pending msg
;
2982 struct lttcomm_relayd_rotate_pending_reply reply
;
2983 struct lttng_ht_iter iter
;
2984 struct relay_stream
*stream
;
2988 bool rotate_pending
= false;
2990 DBG("Rotate pending command received");
2992 if (!session
|| !conn
->version_check_done
) {
2993 ERR("Trying to check for data before version check");
2998 if (session
->major
== 2 && session
->minor
< 11) {
2999 ERR("Unsupported feature before 2.11");
3004 if (payload
->size
< sizeof(msg
)) {
3005 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
3006 sizeof(msg
), payload
->size
);
3011 memcpy(&msg
, payload
->data
, sizeof(msg
));
3013 chunk_id
= be64toh(msg
.chunk_id
);
3015 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
3016 session
->session_name
, chunk_id
);
3019 * Iterate over all the streams in the session and check if they are
3020 * still waiting for data to perform their rotation.
3023 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
3025 if (!stream_get(stream
)) {
3028 if (stream
->trace
->session
!= session
) {
3032 pthread_mutex_lock(&stream
->lock
);
3033 if (stream
->rotate_at_seq_num
!= -1ULL) {
3034 /* We have not yet performed the rotation. */
3035 rotate_pending
= true;
3036 DBG("Stream %" PRIu64
" is still rotating",
3037 stream
->stream_handle
);
3038 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
3040 * Stream closed on the consumer but still active on the
3043 rotate_pending
= true;
3044 DBG("Stream %" PRIu64
" did not exist on the consumer "
3045 "when the last rotation started, but is"
3046 "still waiting for data before getting"
3048 stream
->stream_handle
);
3050 pthread_mutex_unlock(&stream
->lock
);
3052 if (rotate_pending
) {
3059 memset(&reply
, 0, sizeof(reply
));
3060 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
3061 reply
.is_pending
= (uint8_t) !!rotate_pending
;
3062 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
3064 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3065 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
3074 #define DBG_CMD(cmd_name, conn) \
3075 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3077 static int relay_process_control_command(struct relay_connection
*conn
,
3078 const struct lttcomm_relayd_hdr
*header
,
3079 const struct lttng_buffer_view
*payload
)
3083 switch (header
->cmd
) {
3084 case RELAYD_CREATE_SESSION
:
3085 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3086 ret
= relay_create_session(header
, conn
, payload
);
3088 case RELAYD_ADD_STREAM
:
3089 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3090 ret
= relay_add_stream(header
, conn
, payload
);
3092 case RELAYD_START_DATA
:
3093 DBG_CMD("RELAYD_START_DATA", conn
);
3094 ret
= relay_start(header
, conn
, payload
);
3096 case RELAYD_SEND_METADATA
:
3097 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3098 ret
= relay_recv_metadata(header
, conn
, payload
);
3100 case RELAYD_VERSION
:
3101 DBG_CMD("RELAYD_VERSION", conn
);
3102 ret
= relay_send_version(header
, conn
, payload
);
3104 case RELAYD_CLOSE_STREAM
:
3105 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3106 ret
= relay_close_stream(header
, conn
, payload
);
3108 case RELAYD_DATA_PENDING
:
3109 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3110 ret
= relay_data_pending(header
, conn
, payload
);
3112 case RELAYD_QUIESCENT_CONTROL
:
3113 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3114 ret
= relay_quiescent_control(header
, conn
, payload
);
3116 case RELAYD_BEGIN_DATA_PENDING
:
3117 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3118 ret
= relay_begin_data_pending(header
, conn
, payload
);
3120 case RELAYD_END_DATA_PENDING
:
3121 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3122 ret
= relay_end_data_pending(header
, conn
, payload
);
3124 case RELAYD_SEND_INDEX
:
3125 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3126 ret
= relay_recv_index(header
, conn
, payload
);
3128 case RELAYD_STREAMS_SENT
:
3129 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3130 ret
= relay_streams_sent(header
, conn
, payload
);
3132 case RELAYD_RESET_METADATA
:
3133 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3134 ret
= relay_reset_metadata(header
, conn
, payload
);
3136 case RELAYD_ROTATE_STREAM
:
3137 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3138 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3140 case RELAYD_ROTATE_RENAME
:
3141 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3142 ret
= relay_rotate_rename(header
, conn
, payload
);
3144 case RELAYD_ROTATE_PENDING
:
3145 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3146 ret
= relay_rotate_pending(header
, conn
, payload
);
3149 DBG_CMD("RELAYD_MKDIR", conn
);
3150 ret
= relay_mkdir(header
, conn
, payload
);
3152 case RELAYD_UPDATE_SYNC_INFO
:
3154 ERR("Received unknown command (%u)", header
->cmd
);
3155 relay_unknown_command(conn
);
3164 static enum relay_connection_status
relay_process_control_receive_payload(
3165 struct relay_connection
*conn
)
3168 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3169 struct lttng_dynamic_buffer
*reception_buffer
=
3170 &conn
->protocol
.ctrl
.reception_buffer
;
3171 struct ctrl_connection_state_receive_payload
*state
=
3172 &conn
->protocol
.ctrl
.state
.receive_payload
;
3173 struct lttng_buffer_view payload_view
;
3175 if (state
->left_to_receive
== 0) {
3176 /* Short-circuit for payload-less commands. */
3177 goto reception_complete
;
3180 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3181 reception_buffer
->data
+ state
->received
,
3182 state
->left_to_receive
, MSG_DONTWAIT
);
3184 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3185 PERROR("Unable to receive command payload on sock %d",
3187 status
= RELAY_CONNECTION_STATUS_ERROR
;
3190 } else if (ret
== 0) {
3191 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3192 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3197 assert(ret
<= state
->left_to_receive
);
3199 state
->left_to_receive
-= ret
;
3200 state
->received
+= ret
;
3202 if (state
->left_to_receive
> 0) {
3204 * Can't transition to the protocol's next state, wait to
3205 * receive the rest of the header.
3207 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3208 state
->received
, state
->left_to_receive
,
3214 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3215 conn
->sock
->fd
, state
->received
);
3217 * The payload required to process the command has been received.
3218 * A view to the reception buffer is forwarded to the various
3219 * commands and the state of the control is reset on success.
3221 * Commands are responsible for sending their reply to the peer.
3223 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3225 ret
= relay_process_control_command(conn
,
3226 &state
->header
, &payload_view
);
3228 status
= RELAY_CONNECTION_STATUS_ERROR
;
3232 ret
= connection_reset_protocol_state(conn
);
3234 status
= RELAY_CONNECTION_STATUS_ERROR
;
3240 static enum relay_connection_status
relay_process_control_receive_header(
3241 struct relay_connection
*conn
)
3244 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3245 struct lttcomm_relayd_hdr header
;
3246 struct lttng_dynamic_buffer
*reception_buffer
=
3247 &conn
->protocol
.ctrl
.reception_buffer
;
3248 struct ctrl_connection_state_receive_header
*state
=
3249 &conn
->protocol
.ctrl
.state
.receive_header
;
3251 assert(state
->left_to_receive
!= 0);
3253 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3254 reception_buffer
->data
+ state
->received
,
3255 state
->left_to_receive
, MSG_DONTWAIT
);
3257 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3258 PERROR("Unable to receive control command header on sock %d",
3260 status
= RELAY_CONNECTION_STATUS_ERROR
;
3263 } else if (ret
== 0) {
3264 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3265 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3270 assert(ret
<= state
->left_to_receive
);
3272 state
->left_to_receive
-= ret
;
3273 state
->received
+= ret
;
3275 if (state
->left_to_receive
> 0) {
3277 * Can't transition to the protocol's next state, wait to
3278 * receive the rest of the header.
3280 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3281 state
->received
, state
->left_to_receive
,
3286 /* Transition to next state: receiving the command's payload. */
3287 conn
->protocol
.ctrl
.state_id
=
3288 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3289 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3290 header
.circuit_id
= be64toh(header
.circuit_id
);
3291 header
.data_size
= be64toh(header
.data_size
);
3292 header
.cmd
= be32toh(header
.cmd
);
3293 header
.cmd_version
= be32toh(header
.cmd_version
);
3294 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3295 &header
, sizeof(header
));
3297 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3298 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3301 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3302 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3304 status
= RELAY_CONNECTION_STATUS_ERROR
;
3308 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3310 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3311 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3314 status
= RELAY_CONNECTION_STATUS_ERROR
;
3318 if (header
.data_size
== 0) {
3320 * Manually invoke the next state as the poll loop
3321 * will not wake-up to allow us to proceed further.
3323 status
= relay_process_control_receive_payload(conn
);
3330 * Process the commands received on the control socket
3332 static enum relay_connection_status
relay_process_control(
3333 struct relay_connection
*conn
)
3335 enum relay_connection_status status
;
3337 switch (conn
->protocol
.ctrl
.state_id
) {
3338 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3339 status
= relay_process_control_receive_header(conn
);
3341 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3342 status
= relay_process_control_receive_payload(conn
);
3345 ERR("Unknown control connection protocol state encountered.");
3353 * Handle index for a data stream.
3355 * Called with the stream lock held.
3357 * Return 0 on success else a negative value.
3359 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3360 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3363 uint64_t data_offset
;
3364 struct relay_index
*index
;
3366 /* Get data offset because we are about to update the index. */
3367 data_offset
= htobe64(stream
->tracefile_size_current
);
3369 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3370 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3373 * Lookup for an existing index for that stream id/sequence
3374 * number. If it exists, the control thread has already received the
3375 * data for it, thus we need to write it to disk.
3377 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3383 if (rotate_index
|| !stream
->index_file
) {
3384 ret
= create_rotate_index_file(stream
);
3386 ERR("Failed to rotate index");
3387 /* Put self-ref for this index due to error. */
3388 relay_index_put(index
);
3394 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3396 /* Put self-ref for this index due to error. */
3397 relay_index_put(index
);
3402 ret
= relay_index_try_flush(index
);
3404 tracefile_array_commit_seq(stream
->tfa
);
3405 stream
->index_received_seqcount
++;
3407 } else if (ret
> 0) {
3408 index
->total_size
= total_size
;
3412 /* Put self-ref for this index due to error. */
3413 relay_index_put(index
);
3421 static enum relay_connection_status
relay_process_data_receive_header(
3422 struct relay_connection
*conn
)
3425 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3426 struct data_connection_state_receive_header
*state
=
3427 &conn
->protocol
.data
.state
.receive_header
;
3428 struct lttcomm_relayd_data_hdr header
;
3429 struct relay_stream
*stream
;
3431 assert(state
->left_to_receive
!= 0);
3433 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3434 state
->header_reception_buffer
+ state
->received
,
3435 state
->left_to_receive
, MSG_DONTWAIT
);
3437 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3438 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3439 status
= RELAY_CONNECTION_STATUS_ERROR
;
3442 } else if (ret
== 0) {
3443 /* Orderly shutdown. Not necessary to print an error. */
3444 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3445 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3450 assert(ret
<= state
->left_to_receive
);
3452 state
->left_to_receive
-= ret
;
3453 state
->received
+= ret
;
3455 if (state
->left_to_receive
> 0) {
3457 * Can't transition to the protocol's next state, wait to
3458 * receive the rest of the header.
3460 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3461 state
->received
, state
->left_to_receive
,
3466 /* Transition to next state: receiving the payload. */
3467 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3469 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3470 header
.circuit_id
= be64toh(header
.circuit_id
);
3471 header
.stream_id
= be64toh(header
.stream_id
);
3472 header
.data_size
= be32toh(header
.data_size
);
3473 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3474 header
.padding_size
= be32toh(header
.padding_size
);
3475 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3477 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3479 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3480 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3482 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3483 conn
->sock
->fd
, header
.circuit_id
,
3484 header
.stream_id
, header
.data_size
,
3485 header
.net_seq_num
, header
.padding_size
);
3487 stream
= stream_get_by_id(header
.stream_id
);
3489 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3491 /* Protocol error. */
3492 status
= RELAY_CONNECTION_STATUS_ERROR
;
3496 pthread_mutex_lock(&stream
->lock
);
3498 /* Check if a rotation is needed. */
3499 if (stream
->tracefile_size
> 0 &&
3500 (stream
->tracefile_size_current
+ header
.data_size
) >
3501 stream
->tracefile_size
) {
3502 uint64_t old_id
, new_id
;
3504 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3505 tracefile_array_file_rotate(stream
->tfa
);
3507 /* new_id is updated by utils_rotate_stream_file. */
3510 ret
= stream_fd_rotate(stream
->stream_fd
, stream
->path_name
,
3511 stream
->channel_name
, stream
->tracefile_size
,
3512 stream
->tracefile_count
, &new_id
);
3514 ERR("Failed to rotate stream output file");
3515 status
= RELAY_CONNECTION_STATUS_ERROR
;
3516 goto end_stream_unlock
;
3520 * Reset current size because we just performed a stream
3523 stream
->tracefile_size_current
= 0;
3524 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3528 pthread_mutex_unlock(&stream
->lock
);
3534 static enum relay_connection_status
relay_process_data_receive_payload(
3535 struct relay_connection
*conn
)
3538 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3539 struct relay_stream
*stream
;
3540 struct data_connection_state_receive_payload
*state
=
3541 &conn
->protocol
.data
.state
.receive_payload
;
3542 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3543 char data_buffer
[chunk_size
];
3544 bool partial_recv
= false;
3545 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3546 uint64_t left_to_receive
= state
->left_to_receive
;
3547 struct relay_session
*session
;
3550 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3551 state
->header
.stream_id
, state
->header
.net_seq_num
,
3552 state
->received
, left_to_receive
);
3554 stream
= stream_get_by_id(state
->header
.stream_id
);
3556 /* Protocol error. */
3557 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3558 state
->header
.stream_id
);
3559 status
= RELAY_CONNECTION_STATUS_ERROR
;
3563 pthread_mutex_lock(&stream
->lock
);
3564 session
= stream
->trace
->session
;
3565 if (!conn
->session
) {
3566 ret
= connection_set_session(conn
, session
);
3568 status
= RELAY_CONNECTION_STATUS_ERROR
;
3569 goto end_stream_unlock
;
3573 stream_fd
= stream_fd_get_fd(stream
->stream_fd
);
3574 if (stream_fd
< 0) {
3575 status
= RELAY_CONNECTION_STATUS_ERROR
;
3576 goto end_stream_unlock
;
3580 * The size of the "chunk" received on any iteration is bounded by:
3581 * - the data left to receive,
3582 * - the data immediately available on the socket,
3583 * - the on-stack data buffer
3585 while (left_to_receive
> 0 && !partial_recv
) {
3587 size_t recv_size
= min(left_to_receive
, chunk_size
);
3589 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3590 recv_size
, MSG_DONTWAIT
);
3592 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3593 PERROR("Socket %d error", conn
->sock
->fd
);
3594 status
= RELAY_CONNECTION_STATUS_ERROR
;
3597 } else if (ret
== 0) {
3598 /* No more data ready to be consumed on socket. */
3599 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3600 state
->header
.stream_id
);
3601 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3603 } else if (ret
< (int) recv_size
) {
3605 * All the data available on the socket has been
3608 partial_recv
= true;
3613 /* Write data to stream output fd. */
3614 write_ret
= lttng_write(stream_fd
, data_buffer
,
3616 if (write_ret
< (ssize_t
) recv_size
) {
3617 ERR("Relay error writing data to file");
3618 status
= RELAY_CONNECTION_STATUS_ERROR
;
3622 left_to_receive
-= recv_size
;
3623 state
->received
+= recv_size
;
3624 state
->left_to_receive
= left_to_receive
;
3626 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3627 write_ret
, stream
->stream_handle
);
3630 if (state
->left_to_receive
> 0) {
3632 * Did not receive all the data expected, wait for more data to
3633 * become available on the socket.
3635 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3636 state
->header
.stream_id
, state
->received
,
3637 state
->left_to_receive
);
3641 ret
= write_padding_to_file(stream_fd
,
3642 state
->header
.padding_size
);
3643 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3644 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3645 stream
->stream_handle
,
3646 state
->header
.net_seq_num
, ret
);
3647 status
= RELAY_CONNECTION_STATUS_ERROR
;
3652 if (session
->minor
>= 4 && !session
->snapshot
) {
3653 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3654 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3656 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3657 stream
->stream_handle
,
3658 state
->header
.net_seq_num
, ret
);
3659 status
= RELAY_CONNECTION_STATUS_ERROR
;
3664 stream
->tracefile_size_current
+= state
->header
.data_size
+
3665 state
->header
.padding_size
;
3667 if (stream
->prev_seq
== -1ULL) {
3670 if (index_flushed
) {
3671 stream
->pos_after_last_complete_data_index
=
3672 stream
->tracefile_size_current
;
3675 stream
->prev_seq
= state
->header
.net_seq_num
;
3678 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3679 * contents of *state which are aliased (union) to the same location as
3680 * the new state. Don't use it beyond this point.
3682 connection_reset_protocol_state(conn
);
3685 ret
= try_rotate_stream(stream
);
3687 status
= RELAY_CONNECTION_STATUS_ERROR
;
3691 (void) stream_fd_put_fd(stream
->stream_fd
);
3693 close_requested
= stream
->close_requested
;
3694 pthread_mutex_unlock(&stream
->lock
);
3695 if (close_requested
&& left_to_receive
== 0) {
3696 try_stream_close(stream
);
3700 pthread_mutex_lock(&session
->lock
);
3701 uatomic_set(&session
->new_streams
, 1);
3702 pthread_mutex_unlock(&session
->lock
);
3711 * relay_process_data: Process the data received on the data socket
3713 static enum relay_connection_status
relay_process_data(
3714 struct relay_connection
*conn
)
3716 enum relay_connection_status status
;
3718 switch (conn
->protocol
.data
.state_id
) {
3719 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3720 status
= relay_process_data_receive_header(conn
);
3722 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3723 status
= relay_process_data_receive_payload(conn
);
3726 ERR("Unexpected data connection communication state.");
3733 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3737 (void) lttng_poll_del(events
, pollfd
);
3739 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3740 fd_tracker_util_close_fd
, NULL
);
3742 ERR("Closing pollfd %d", pollfd
);
3746 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3747 int pollfd
, struct relay_connection
*conn
)
3749 const char *type_str
;
3751 switch (conn
->type
) {
3756 type_str
= "Control";
3758 case RELAY_VIEWER_COMMAND
:
3759 type_str
= "Viewer Command";
3761 case RELAY_VIEWER_NOTIFICATION
:
3762 type_str
= "Viewer Notification";
3765 type_str
= "Unknown";
3767 cleanup_connection_pollfd(events
, pollfd
);
3768 connection_put(conn
);
3769 DBG("%s connection closed with %d", type_str
, pollfd
);
3773 * This thread does the actual work
3775 static void *relay_thread_worker(void *data
)
3777 int ret
, err
= -1, last_seen_data_fd
= -1;
3779 struct lttng_poll_event events
;
3780 struct lttng_ht
*relay_connections_ht
;
3781 struct lttng_ht_iter iter
;
3782 struct relay_connection
*destroy_conn
= NULL
;
3784 DBG("[thread] Relay worker started");
3786 rcu_register_thread();
3788 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3790 if (testpoint(relayd_thread_worker
)) {
3791 goto error_testpoint
;
3794 health_code_update();
3796 /* table of connections indexed on socket */
3797 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3798 if (!relay_connections_ht
) {
3799 goto relay_connections_ht_error
;
3802 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3804 goto error_poll_create
;
3807 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3814 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3816 health_code_update();
3818 /* Infinite blocking call, waiting for transmission */
3819 DBG3("Relayd worker thread polling...");
3820 health_poll_entry();
3821 ret
= lttng_poll_wait(&events
, -1);
3825 * Restart interrupted system call.
3827 if (errno
== EINTR
) {
3836 * Process control. The control connection is
3837 * prioritized so we don't starve it with high
3838 * throughput tracing data on the data connection.
3840 for (i
= 0; i
< nb_fd
; i
++) {
3841 /* Fetch once the poll data */
3842 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3843 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3845 health_code_update();
3849 * No activity for this FD (poll
3855 /* Thread quit pipe has been closed. Killing thread. */
3856 ret
= check_thread_quit_pipe(pollfd
, revents
);
3862 /* Inspect the relay conn pipe for new connection */
3863 if (pollfd
== relay_conn_pipe
[0]) {
3864 if (revents
& LPOLLIN
) {
3865 struct relay_connection
*conn
;
3867 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3871 lttng_poll_add(&events
, conn
->sock
->fd
,
3872 LPOLLIN
| LPOLLRDHUP
);
3873 connection_ht_add(relay_connections_ht
, conn
);
3874 DBG("Connection socket %d added", conn
->sock
->fd
);
3875 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3876 ERR("Relay connection pipe error");
3879 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3883 struct relay_connection
*ctrl_conn
;
3885 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3886 /* If not found, there is a synchronization issue. */
3889 if (ctrl_conn
->type
== RELAY_DATA
) {
3890 if (revents
& LPOLLIN
) {
3892 * Flag the last seen data fd not deleted. It will be
3893 * used as the last seen fd if any fd gets deleted in
3896 last_notdel_data_fd
= pollfd
;
3898 goto put_ctrl_connection
;
3900 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3902 if (revents
& LPOLLIN
) {
3903 enum relay_connection_status status
;
3905 status
= relay_process_control(ctrl_conn
);
3906 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3908 * On socket error flag the session as aborted to force
3909 * the cleanup of its stream otherwise it can leak
3910 * during the lifetime of the relayd.
3912 * This prevents situations in which streams can be
3913 * left opened because an index was received, the
3914 * control connection is closed, and the data
3915 * connection is closed (uncleanly) before the packet's
3918 * Since the control connection encountered an error,
3919 * it is okay to be conservative and close the
3920 * session right now as we can't rely on the protocol
3921 * being respected anymore.
3923 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3924 session_abort(ctrl_conn
->session
);
3927 /* Clear the connection on error or close. */
3928 relay_thread_close_connection(&events
,
3933 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3934 relay_thread_close_connection(&events
,
3936 if (last_seen_data_fd
== pollfd
) {
3937 last_seen_data_fd
= last_notdel_data_fd
;
3940 ERR("Unexpected poll events %u for control sock %d",
3942 connection_put(ctrl_conn
);
3945 put_ctrl_connection
:
3946 connection_put(ctrl_conn
);
3951 * The last loop handled a control request, go back to poll to make
3952 * sure we prioritise the control socket.
3958 if (last_seen_data_fd
>= 0) {
3959 for (i
= 0; i
< nb_fd
; i
++) {
3960 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3962 health_code_update();
3964 if (last_seen_data_fd
== pollfd
) {
3971 /* Process data connection. */
3972 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3973 /* Fetch the poll data. */
3974 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3975 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3976 struct relay_connection
*data_conn
;
3978 health_code_update();
3981 /* No activity for this FD (poll implementation). */
3985 /* Skip the command pipe. It's handled in the first loop. */
3986 if (pollfd
== relay_conn_pipe
[0]) {
3990 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3992 /* Skip it. Might be removed before. */
3995 if (data_conn
->type
== RELAY_CONTROL
) {
3996 goto put_data_connection
;
3998 assert(data_conn
->type
== RELAY_DATA
);
4000 if (revents
& LPOLLIN
) {
4001 enum relay_connection_status status
;
4003 status
= relay_process_data(data_conn
);
4004 /* Connection closed or error. */
4005 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
4007 * On socket error flag the session as aborted to force
4008 * the cleanup of its stream otherwise it can leak
4009 * during the lifetime of the relayd.
4011 * This prevents situations in which streams can be
4012 * left opened because an index was received, the
4013 * control connection is closed, and the data
4014 * connection is closed (uncleanly) before the packet's
4017 * Since the data connection encountered an error,
4018 * it is okay to be conservative and close the
4019 * session right now as we can't rely on the protocol
4020 * being respected anymore.
4022 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4023 session_abort(data_conn
->session
);
4025 relay_thread_close_connection(&events
, pollfd
,
4028 * Every goto restart call sets the last seen fd where
4029 * here we don't really care since we gracefully
4030 * continue the loop after the connection is deleted.
4033 /* Keep last seen port. */
4034 last_seen_data_fd
= pollfd
;
4035 connection_put(data_conn
);
4038 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4039 relay_thread_close_connection(&events
, pollfd
,
4042 ERR("Unknown poll events %u for data sock %d",
4045 put_data_connection
:
4046 connection_put(data_conn
);
4048 last_seen_data_fd
= -1;
4051 /* Normal exit, no error */
4056 /* Cleanup remaining connection object. */
4058 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4061 health_code_update();
4063 session_abort(destroy_conn
->session
);
4066 * No need to grab another ref, because we own
4069 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4074 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4076 lttng_ht_destroy(relay_connections_ht
);
4077 relay_connections_ht_error
:
4078 /* Close relay conn pipes */
4079 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4082 DBG("Thread exited with error");
4084 DBG("Worker thread cleanup complete");
4088 ERR("Health error occurred in %s", __func__
);
4090 health_unregister(health_relayd
);
4091 rcu_unregister_thread();
4092 lttng_relay_stop_threads();
4097 * Create the relay command pipe to wake thread_manage_apps.
4098 * Closed in cleanup().
4100 static int create_relay_conn_pipe(void)
4102 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4103 "Relayd connection pipe", relay_conn_pipe
);
4107 int stdio_open(void *data
, int *fds
)
4109 fds
[0] = fileno(stdout
);
4110 fds
[1] = fileno(stderr
);
4115 int noop_close(void *data
, int *fds
)
4121 int track_stdio(void)
4124 const char *names
[] = { "stdout", "stderr" };
4126 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4127 names
, 2, stdio_open
, NULL
);
4131 void untrack_stdio(void)
4133 int fds
[] = { fileno(stdout
), fileno(stderr
) };
4136 * noop_close is used since we don't really want to close
4137 * the stdio output fds; we merely want to stop tracking them.
4139 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
4140 fds
, 2, noop_close
, NULL
);
4146 int main(int argc
, char **argv
)
4148 int ret
= 0, retval
= 0;
4151 /* Parse arguments */
4153 if (set_options(argc
, argv
)) {
4158 if (set_signal_handler()) {
4163 ret
= fclose(stdin
);
4165 PERROR("Failed to close stdin");
4168 /* Try to create directory if -o, --output is specified. */
4169 if (opt_output_path
) {
4170 if (*opt_output_path
!= '/') {
4171 ERR("Please specify an absolute path for -o, --output PATH");
4176 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4179 ERR("Unable to create %s", opt_output_path
);
4186 if (opt_daemon
|| opt_background
) {
4187 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4196 * The RCU thread registration (and use, through the fd-tracker's
4197 * creation) is done after the daemonization to allow us to not
4198 * deal with liburcu's fork() management as the call RCU needs to
4201 rcu_register_thread();
4203 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_pool_size
);
4204 if (!the_fd_tracker
) {
4209 ret
= track_stdio();
4215 /* Initialize thread health monitoring */
4216 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4217 if (!health_relayd
) {
4218 PERROR("health_app_create error");
4220 goto exit_health_app_create
;
4223 /* Create thread quit pipe */
4224 if (init_thread_quit_pipe()) {
4226 goto exit_init_data
;
4229 /* Setup the thread apps communication pipe. */
4230 if (create_relay_conn_pipe()) {
4232 goto exit_init_data
;
4235 /* Init relay command queue. */
4236 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4238 /* Initialize communication library */
4240 lttcomm_inet_init();
4242 /* tables of sessions indexed by session ID */
4243 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4246 goto exit_init_data
;
4249 /* tables of streams indexed by stream ID */
4250 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4251 if (!relay_streams_ht
) {
4253 goto exit_init_data
;
4256 /* tables of streams indexed by stream ID */
4257 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4258 if (!viewer_streams_ht
) {
4260 goto exit_init_data
;
4263 ret
= init_health_quit_pipe();
4266 goto exit_health_quit_pipe
;
4269 /* Create thread to manage the client socket */
4270 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4271 thread_manage_health
, (void *) NULL
);
4274 PERROR("pthread_create health");
4276 goto exit_health_thread
;
4279 /* Setup the dispatcher thread */
4280 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4281 relay_thread_dispatcher
, (void *) NULL
);
4284 PERROR("pthread_create dispatcher");
4286 goto exit_dispatcher_thread
;
4289 /* Setup the worker thread */
4290 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4291 relay_thread_worker
, NULL
);
4294 PERROR("pthread_create worker");
4296 goto exit_worker_thread
;
4299 /* Setup the listener thread */
4300 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4301 relay_thread_listener
, (void *) NULL
);
4304 PERROR("pthread_create listener");
4306 goto exit_listener_thread
;
4309 ret
= relayd_live_create(live_uri
);
4311 ERR("Starting live viewer threads");
4317 * This is where we start awaiting program completion (e.g. through
4318 * signal that asks threads to teardown).
4321 ret
= relayd_live_join();
4327 ret
= pthread_join(listener_thread
, &status
);
4330 PERROR("pthread_join listener_thread");
4334 exit_listener_thread
:
4335 ret
= pthread_join(worker_thread
, &status
);
4338 PERROR("pthread_join worker_thread");
4343 ret
= pthread_join(dispatcher_thread
, &status
);
4346 PERROR("pthread_join dispatcher_thread");
4349 exit_dispatcher_thread
:
4351 ret
= pthread_join(health_thread
, &status
);
4354 PERROR("pthread_join health_thread");
4359 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4360 exit_health_quit_pipe
:
4363 health_app_destroy(health_relayd
);
4364 exit_health_app_create
:
4367 * Wait for all pending call_rcu work to complete before tearing
4368 * down data structures. call_rcu worker may be trying to
4369 * perform lookups in those structures.
4374 /* Ensure all prior call_rcu are done. */
4379 * fd_tracker_destroy() will log the contents of the fd-tracker
4380 * if a leak is detected.
4382 fd_tracker_destroy(the_fd_tracker
);
4383 rcu_unregister_thread();