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_cap
;
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-cap", 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-cap")) {
213 v
= strtoul(arg
, NULL
, 0);
214 if (errno
!= 0 || !isdigit(arg
[0])) {
215 ERR("Wrong value in --fd-cap parameter: %s", arg
);
219 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
220 ERR("File descriptor cap must be set to at least %d",
221 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
224 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
228 lttng_opt_fd_cap
= (unsigned int) v
;
229 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
232 fprintf(stderr
, "unknown option %s", optname
);
234 fprintf(stderr
, " with arg %s\n", arg
);
239 if (lttng_is_setuid_setgid()) {
240 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
241 "-C, --control-port");
243 ret
= uri_parse(arg
, &control_uri
);
245 ERR("Invalid control URI specified");
248 if (control_uri
->port
== 0) {
249 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
254 if (lttng_is_setuid_setgid()) {
255 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
258 ret
= uri_parse(arg
, &data_uri
);
260 ERR("Invalid data URI specified");
263 if (data_uri
->port
== 0) {
264 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
269 if (lttng_is_setuid_setgid()) {
270 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
273 ret
= uri_parse(arg
, &live_uri
);
275 ERR("Invalid live URI specified");
278 if (live_uri
->port
== 0) {
279 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
290 if (lttng_is_setuid_setgid()) {
291 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
294 tracing_group_name
= strdup(arg
);
295 if (tracing_group_name
== NULL
) {
300 tracing_group_name_override
= 1;
304 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
306 ERR("Cannot show --help for `lttng-relayd`");
311 fprintf(stdout
, "%s\n", VERSION
);
314 if (lttng_is_setuid_setgid()) {
315 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
318 ret
= asprintf(&opt_output_path
, "%s", arg
);
321 PERROR("asprintf opt_output_path");
327 /* Verbose level can increase using multiple -v */
329 lttng_opt_verbose
= config_parse_value(arg
);
331 /* Only 3 level of verbosity (-vvv). */
332 if (lttng_opt_verbose
< 3) {
333 lttng_opt_verbose
+= 1;
338 /* Unknown option or other error.
339 * Error is printed by getopt, just return */
352 * config_entry_handler_cb used to handle options read from a config file.
353 * See config_entry_handler_cb comment in common/config/session-config.h for the
354 * return value conventions.
356 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
360 if (!entry
|| !entry
->name
|| !entry
->value
) {
365 /* Check if the option is to be ignored */
366 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
367 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
372 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
373 /* Ignore if entry name is not fully matched. */
374 if (strcmp(entry
->name
, long_options
[i
].name
)) {
379 * If the option takes no argument on the command line,
380 * we have to check if the value is "true". We support
381 * non-zero numeric values, true, on and yes.
383 if (!long_options
[i
].has_arg
) {
384 ret
= config_parse_value(entry
->value
);
387 WARN("Invalid configuration value \"%s\" for option %s",
388 entry
->value
, entry
->name
);
390 /* False, skip boolean config option. */
395 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
399 WARN("Unrecognized option \"%s\" in daemon configuration file.",
406 static int set_options(int argc
, char **argv
)
408 int c
, ret
= 0, option_index
= 0, retval
= 0;
409 int orig_optopt
= optopt
, orig_optind
= optind
;
410 char *default_address
, *optstring
;
411 const char *config_path
= NULL
;
413 optstring
= utils_generate_optstring(long_options
,
414 sizeof(long_options
) / sizeof(struct option
));
420 /* Check for the --config option */
422 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
423 &option_index
)) != -1) {
427 } else if (c
!= 'f') {
431 if (lttng_is_setuid_setgid()) {
432 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
435 config_path
= utils_expand_path(optarg
);
437 ERR("Failed to resolve path: %s", optarg
);
442 ret
= config_get_section_entries(config_path
, config_section_name
,
443 config_entry_handler
, NULL
);
446 ERR("Invalid configuration option at line %i", ret
);
452 /* Reset getopt's global state */
453 optopt
= orig_optopt
;
454 optind
= orig_optind
;
456 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
461 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
468 /* assign default values */
469 if (control_uri
== NULL
) {
470 ret
= asprintf(&default_address
,
471 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
472 DEFAULT_NETWORK_CONTROL_PORT
);
474 PERROR("asprintf default data address");
479 ret
= uri_parse(default_address
, &control_uri
);
480 free(default_address
);
482 ERR("Invalid control URI specified");
487 if (data_uri
== NULL
) {
488 ret
= asprintf(&default_address
,
489 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
490 DEFAULT_NETWORK_DATA_PORT
);
492 PERROR("asprintf default data address");
497 ret
= uri_parse(default_address
, &data_uri
);
498 free(default_address
);
500 ERR("Invalid data URI specified");
505 if (live_uri
== NULL
) {
506 ret
= asprintf(&default_address
,
507 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
508 DEFAULT_NETWORK_VIEWER_PORT
);
510 PERROR("asprintf default viewer control address");
515 ret
= uri_parse(default_address
, &live_uri
);
516 free(default_address
);
518 ERR("Invalid viewer control URI specified");
523 if (lttng_opt_fd_cap
== 0) {
525 struct rlimit rlimit
;
527 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
529 PERROR("Failed to get file descriptor limit");
533 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
541 static void print_global_objects(void)
543 print_viewer_streams();
544 print_relay_streams();
551 static void relayd_cleanup(void)
553 print_global_objects();
557 if (viewer_streams_ht
)
558 lttng_ht_destroy(viewer_streams_ht
);
559 if (relay_streams_ht
)
560 lttng_ht_destroy(relay_streams_ht
);
562 lttng_ht_destroy(sessions_ht
);
564 /* free the dynamically allocated opt_output_path */
565 free(opt_output_path
);
567 /* Close thread quit pipes */
568 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
570 uri_free(control_uri
);
572 /* Live URI is freed in the live thread. */
574 if (tracing_group_name_override
) {
575 free((void *) tracing_group_name
);
580 * Write to writable pipe used to notify a thread.
582 static int notify_thread_pipe(int wpipe
)
586 ret
= lttng_write(wpipe
, "!", 1);
588 PERROR("write poll pipe");
596 static int notify_health_quit_pipe(int *pipe
)
600 ret
= lttng_write(pipe
[1], "4", 1);
602 PERROR("write relay health quit");
611 * Stop all relayd and relayd-live threads.
613 int lttng_relay_stop_threads(void)
617 /* Stopping all threads */
618 DBG("Terminating all threads");
619 if (notify_thread_pipe(thread_quit_pipe
[1])) {
620 ERR("write error on thread quit pipe");
624 if (notify_health_quit_pipe(health_quit_pipe
)) {
625 ERR("write error on health quit pipe");
628 /* Dispatch thread */
629 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
630 futex_nto1_wake(&relay_conn_queue
.futex
);
632 if (relayd_live_stop()) {
633 ERR("Error stopping live threads");
640 * Signal handler for the daemon
642 * Simply stop all worker threads, leaving main() return gracefully after
643 * joining all threads and calling cleanup().
645 static void sighandler(int sig
)
649 DBG("SIGINT caught");
650 if (lttng_relay_stop_threads()) {
651 ERR("Error stopping threads");
655 DBG("SIGTERM caught");
656 if (lttng_relay_stop_threads()) {
657 ERR("Error stopping threads");
661 CMM_STORE_SHARED(recv_child_signal
, 1);
669 * Setup signal handler for :
670 * SIGINT, SIGTERM, SIGPIPE
672 static int set_signal_handler(void)
678 if ((ret
= sigemptyset(&sigset
)) < 0) {
679 PERROR("sigemptyset");
686 sa
.sa_handler
= sighandler
;
687 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
692 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
697 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
702 sa
.sa_handler
= SIG_IGN
;
703 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
708 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
713 void lttng_relay_notify_ready(void)
715 /* Notify the parent of the fork() process that we are ready. */
716 if (opt_daemon
|| opt_background
) {
717 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
718 kill(child_ppid
, SIGUSR1
);
724 * Init thread quit pipe.
726 * Return -1 on error or 0 if all pipes are created.
728 static int init_thread_quit_pipe(void)
730 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
731 "Quit pipe", thread_quit_pipe
);
735 * Init health quit pipe.
737 * Return -1 on error or 0 if all pipes are created.
739 static int init_health_quit_pipe(void)
741 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
742 "Health quit pipe", health_quit_pipe
);
746 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
748 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
749 int size
, const char *name
)
753 if (events
== NULL
|| size
== 0) {
758 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
759 name
, events
, 1, LTTNG_CLOEXEC
);
762 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
774 * Check if the thread quit pipe was triggered.
776 * Return 1 if it was triggered else 0;
778 static int check_thread_quit_pipe(int fd
, uint32_t events
)
780 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
787 static int create_sock(void *data
, int *out_fd
)
790 struct lttcomm_sock
*sock
= data
;
792 ret
= lttcomm_create_sock(sock
);
802 static int close_sock(void *data
, int *in_fd
)
804 struct lttcomm_sock
*sock
= data
;
806 return sock
->ops
->close(sock
);
809 static int accept_sock(void *data
, int *out_fd
)
812 /* Socks is an array of in_sock, out_sock. */
813 struct lttcomm_sock
**socks
= data
;
814 struct lttcomm_sock
*in_sock
= socks
[0];
816 socks
[1] = in_sock
->ops
->accept(in_sock
);
821 *out_fd
= socks
[1]->fd
;
827 * Create and init socket from uri.
829 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
833 struct lttcomm_sock
*sock
= NULL
;
834 char uri_str
[PATH_MAX
];
835 char *formated_name
= NULL
;
837 sock
= lttcomm_alloc_sock_from_uri(uri
);
839 ERR("Allocating socket");
844 * Don't fail to create the socket if the name can't be built as it is
845 * only used for debugging purposes.
847 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
848 uri_str
[sizeof(uri_str
) - 1] = '\0';
850 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
853 formated_name
= NULL
;
857 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
858 (const char **) (formated_name
? &formated_name
: NULL
),
859 1, create_sock
, sock
);
861 DBG("Listening on %s socket %d", name
, sock
->fd
);
863 ret
= sock
->ops
->bind(sock
);
865 PERROR("Failed to bind socket");
869 ret
= sock
->ops
->listen(sock
, -1);
879 lttcomm_destroy_sock(sock
);
885 struct lttcomm_sock
*accept_relayd_sock(struct lttcomm_sock
*listening_sock
,
889 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
890 struct lttcomm_sock
*new_sock
= NULL
;
892 ret
= fd_tracker_open_unsuspendable_fd(
893 the_fd_tracker
, &out_fd
,
894 (const char **) &name
,
895 1, accept_sock
, &socks
);
900 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
906 * This thread manages the listening for new connections on the network
908 static void *relay_thread_listener(void *data
)
910 int i
, ret
, pollfd
, err
= -1;
911 uint32_t revents
, nb_fd
;
912 struct lttng_poll_event events
;
913 struct lttcomm_sock
*control_sock
, *data_sock
;
915 DBG("[thread] Relay listener started");
917 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
919 health_code_update();
921 control_sock
= relay_socket_create(control_uri
, "Control listener");
923 goto error_sock_control
;
926 data_sock
= relay_socket_create(data_uri
, "Data listener");
928 goto error_sock_relay
;
932 * Pass 3 as size here for the thread quit pipe, control and
935 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
937 goto error_create_poll
;
940 /* Add the control socket */
941 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
946 /* Add the data socket */
947 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
952 lttng_relay_notify_ready();
954 if (testpoint(relayd_thread_listener
)) {
955 goto error_testpoint
;
959 health_code_update();
961 DBG("Listener accepting connections");
965 ret
= lttng_poll_wait(&events
, -1);
969 * Restart interrupted system call.
971 if (errno
== EINTR
) {
979 DBG("Relay new connection received");
980 for (i
= 0; i
< nb_fd
; i
++) {
981 health_code_update();
983 /* Fetch once the poll data */
984 revents
= LTTNG_POLL_GETEV(&events
, i
);
985 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
989 * No activity for this FD (poll
995 /* Thread quit pipe has been closed. Killing thread. */
996 ret
= check_thread_quit_pipe(pollfd
, revents
);
1002 if (revents
& LPOLLIN
) {
1004 * A new connection is requested, therefore a
1005 * sessiond/consumerd connection is allocated in
1006 * this thread, enqueued to a global queue and
1007 * dequeued (and freed) in the worker thread.
1010 struct relay_connection
*new_conn
;
1011 struct lttcomm_sock
*newsock
= NULL
;
1012 enum connection_type type
;
1014 if (pollfd
== data_sock
->fd
) {
1016 newsock
= accept_relayd_sock(data_sock
,
1017 "Data socket to relayd");
1019 assert(pollfd
== control_sock
->fd
);
1020 type
= RELAY_CONTROL
;
1021 newsock
= control_sock
->ops
->accept(control_sock
);
1022 DBG("Relay control connection accepted, socket %d",
1026 PERROR("accepting sock");
1030 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1033 PERROR("setsockopt inet");
1034 lttcomm_destroy_sock(newsock
);
1038 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1040 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1042 lttcomm_destroy_sock(newsock
);
1046 new_conn
= connection_create(newsock
, type
);
1048 lttcomm_destroy_sock(newsock
);
1052 /* Enqueue request for the dispatcher thread. */
1053 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1057 * Wake the dispatch queue futex.
1058 * Implicit memory barrier with the
1059 * exchange in cds_wfcq_enqueue.
1061 futex_nto1_wake(&relay_conn_queue
.futex
);
1062 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1063 ERR("socket poll error");
1066 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1076 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1078 if (data_sock
->fd
>= 0) {
1079 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1080 &data_sock
->fd
, 1, close_sock
,
1086 lttcomm_destroy_sock(data_sock
);
1088 if (control_sock
->fd
>= 0) {
1089 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1090 &control_sock
->fd
, 1, close_sock
,
1096 lttcomm_destroy_sock(control_sock
);
1100 ERR("Health error occurred in %s", __func__
);
1102 health_unregister(health_relayd
);
1103 DBG("Relay listener thread cleanup complete");
1104 lttng_relay_stop_threads();
1109 * This thread manages the dispatching of the requests to worker threads
1111 static void *relay_thread_dispatcher(void *data
)
1115 struct cds_wfcq_node
*node
;
1116 struct relay_connection
*new_conn
= NULL
;
1118 DBG("[thread] Relay dispatcher started");
1120 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1122 if (testpoint(relayd_thread_dispatcher
)) {
1123 goto error_testpoint
;
1126 health_code_update();
1129 health_code_update();
1131 /* Atomically prepare the queue futex */
1132 futex_nto1_prepare(&relay_conn_queue
.futex
);
1134 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1139 health_code_update();
1141 /* Dequeue commands */
1142 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1143 &relay_conn_queue
.tail
);
1145 DBG("Woken up but nothing in the relay command queue");
1146 /* Continue thread execution */
1149 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1151 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1154 * Inform worker thread of the new request. This
1155 * call is blocking so we can be assured that
1156 * the data will be read at some point in time
1157 * or wait to the end of the world :)
1159 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1161 PERROR("write connection pipe");
1162 connection_put(new_conn
);
1165 } while (node
!= NULL
);
1167 /* Futex wait on queue. Blocking call on futex() */
1168 health_poll_entry();
1169 futex_nto1_wait(&relay_conn_queue
.futex
);
1173 /* Normal exit, no error */
1180 ERR("Health error occurred in %s", __func__
);
1182 health_unregister(health_relayd
);
1183 DBG("Dispatch thread dying");
1184 lttng_relay_stop_threads();
1189 * Set index data from the control port to a given index object.
1191 static int set_index_control_data(struct relay_index
*index
,
1192 struct lttcomm_relayd_index
*data
,
1193 struct relay_connection
*conn
)
1195 struct ctf_packet_index index_data
;
1198 * The index on disk is encoded in big endian.
1200 index_data
.packet_size
= htobe64(data
->packet_size
);
1201 index_data
.content_size
= htobe64(data
->content_size
);
1202 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1203 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1204 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1205 index_data
.stream_id
= htobe64(data
->stream_id
);
1207 if (conn
->minor
>= 8) {
1208 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1209 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1212 return relay_index_set_data(index
, &index_data
);
1216 * Handle the RELAYD_CREATE_SESSION command.
1218 * On success, send back the session id or else return a negative value.
1220 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1221 struct relay_connection
*conn
,
1222 const struct lttng_buffer_view
*payload
)
1226 struct relay_session
*session
;
1227 struct lttcomm_relayd_status_session reply
;
1228 char session_name
[LTTNG_NAME_MAX
];
1229 char hostname
[LTTNG_HOST_NAME_MAX
];
1230 uint32_t live_timer
= 0;
1231 bool snapshot
= false;
1233 memset(session_name
, 0, LTTNG_NAME_MAX
);
1234 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1236 memset(&reply
, 0, sizeof(reply
));
1238 if (conn
->minor
< 4) {
1239 /* From 2.1 to 2.3 */
1241 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1242 /* From 2.4 to 2.10 */
1243 ret
= cmd_create_session_2_4(payload
, session_name
,
1244 hostname
, &live_timer
, &snapshot
);
1246 /* From 2.11 to ... */
1247 ret
= cmd_create_session_2_11(payload
, session_name
,
1248 hostname
, &live_timer
, &snapshot
);
1255 session
= session_create(session_name
, hostname
, live_timer
,
1256 snapshot
, conn
->major
, conn
->minor
);
1261 assert(!conn
->session
);
1262 conn
->session
= session
;
1263 DBG("Created session %" PRIu64
, session
->id
);
1265 reply
.session_id
= htobe64(session
->id
);
1269 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1271 reply
.ret_code
= htobe32(LTTNG_OK
);
1274 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1275 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1276 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1285 * When we have received all the streams and the metadata for a channel,
1286 * we make them visible to the viewer threads.
1288 static void publish_connection_local_streams(struct relay_connection
*conn
)
1290 struct relay_stream
*stream
;
1291 struct relay_session
*session
= conn
->session
;
1294 * We publish all streams belonging to a session atomically wrt
1297 pthread_mutex_lock(&session
->lock
);
1299 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1301 stream_publish(stream
);
1306 * Inform the viewer that there are new streams in the session.
1308 if (session
->viewer_attached
) {
1309 uatomic_set(&session
->new_streams
, 1);
1311 pthread_mutex_unlock(&session
->lock
);
1315 * relay_add_stream: allocate a new stream for a session
1317 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1318 struct relay_connection
*conn
,
1319 const struct lttng_buffer_view
*payload
)
1323 struct relay_session
*session
= conn
->session
;
1324 struct relay_stream
*stream
= NULL
;
1325 struct lttcomm_relayd_status_stream reply
;
1326 struct ctf_trace
*trace
= NULL
;
1327 uint64_t stream_handle
= -1ULL;
1328 char *path_name
= NULL
, *channel_name
= NULL
;
1329 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1330 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1332 if (!session
|| !conn
->version_check_done
) {
1333 ERR("Trying to add a stream before version check");
1335 goto end_no_session
;
1338 if (session
->minor
== 1) {
1340 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1342 } else if (session
->minor
> 1 && session
->minor
< 11) {
1343 /* From 2.2 to 2.10 */
1344 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1345 &channel_name
, &tracefile_size
, &tracefile_count
);
1347 /* From 2.11 to ... */
1348 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1349 &channel_name
, &tracefile_size
, &tracefile_count
,
1350 &stream_chunk_id
.value
);
1351 stream_chunk_id
.is_set
= true;
1358 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1362 /* This stream here has one reference on the trace. */
1364 pthread_mutex_lock(&last_relay_stream_id_lock
);
1365 stream_handle
= ++last_relay_stream_id
;
1366 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1368 /* We pass ownership of path_name and channel_name. */
1369 stream
= stream_create(trace
, stream_handle
, path_name
,
1370 channel_name
, tracefile_size
, tracefile_count
,
1373 channel_name
= NULL
;
1376 * Streams are the owners of their trace. Reference to trace is
1377 * kept within stream_create().
1379 ctf_trace_put(trace
);
1382 memset(&reply
, 0, sizeof(reply
));
1383 reply
.handle
= htobe64(stream_handle
);
1385 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1387 reply
.ret_code
= htobe32(LTTNG_OK
);
1390 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1391 sizeof(struct lttcomm_relayd_status_stream
), 0);
1392 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1393 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1405 * relay_close_stream: close a specific stream
1407 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1408 struct relay_connection
*conn
,
1409 const struct lttng_buffer_view
*payload
)
1413 struct relay_session
*session
= conn
->session
;
1414 struct lttcomm_relayd_close_stream stream_info
;
1415 struct lttcomm_relayd_generic_reply reply
;
1416 struct relay_stream
*stream
;
1418 DBG("Close stream received");
1420 if (!session
|| !conn
->version_check_done
) {
1421 ERR("Trying to close a stream before version check");
1423 goto end_no_session
;
1426 if (payload
->size
< sizeof(stream_info
)) {
1427 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1428 sizeof(stream_info
), payload
->size
);
1430 goto end_no_session
;
1432 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1433 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1434 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1436 stream
= stream_get_by_id(stream_info
.stream_id
);
1443 * Set last_net_seq_num before the close flag. Required by data
1446 pthread_mutex_lock(&stream
->lock
);
1447 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1448 pthread_mutex_unlock(&stream
->lock
);
1451 * This is one of the conditions which may trigger a stream close
1452 * with the others being:
1453 * 1) A close command is received for a stream
1454 * 2) The control connection owning the stream is closed
1455 * 3) We have received all of the stream's data _after_ a close
1458 try_stream_close(stream
);
1459 if (stream
->is_metadata
) {
1460 struct relay_viewer_stream
*vstream
;
1462 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1464 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1466 * Since all the metadata has been sent to the
1467 * viewer and that we have a request to close
1468 * its stream, we can safely teardown the
1469 * corresponding metadata viewer stream.
1471 viewer_stream_put(vstream
);
1473 /* Put local reference. */
1474 viewer_stream_put(vstream
);
1481 memset(&reply
, 0, sizeof(reply
));
1483 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1485 reply
.ret_code
= htobe32(LTTNG_OK
);
1487 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1488 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1489 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1490 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1500 * relay_reset_metadata: reset a metadata stream
1503 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1504 struct relay_connection
*conn
,
1505 const struct lttng_buffer_view
*payload
)
1509 struct relay_session
*session
= conn
->session
;
1510 struct lttcomm_relayd_reset_metadata stream_info
;
1511 struct lttcomm_relayd_generic_reply reply
;
1512 struct relay_stream
*stream
;
1514 DBG("Reset metadata received");
1516 if (!session
|| !conn
->version_check_done
) {
1517 ERR("Trying to reset a metadata stream before version check");
1519 goto end_no_session
;
1522 if (payload
->size
< sizeof(stream_info
)) {
1523 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1524 sizeof(stream_info
), payload
->size
);
1526 goto end_no_session
;
1528 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1529 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1530 stream_info
.version
= be64toh(stream_info
.version
);
1532 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1534 /* Unsupported for live sessions for now. */
1535 if (session
->live_timer
!= 0) {
1540 stream
= stream_get_by_id(stream_info
.stream_id
);
1545 pthread_mutex_lock(&stream
->lock
);
1546 if (!stream
->is_metadata
) {
1551 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1552 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1553 &stream
->stream_fd
->fd
);
1555 ERR("Failed to rotate metadata file %s of channel %s",
1556 stream
->path_name
, stream
->channel_name
);
1561 pthread_mutex_unlock(&stream
->lock
);
1565 memset(&reply
, 0, sizeof(reply
));
1567 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1569 reply
.ret_code
= htobe32(LTTNG_OK
);
1571 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1572 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1573 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1574 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1584 * relay_unknown_command: send -1 if received unknown command
1586 static void relay_unknown_command(struct relay_connection
*conn
)
1588 struct lttcomm_relayd_generic_reply reply
;
1591 memset(&reply
, 0, sizeof(reply
));
1592 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1593 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1594 if (send_ret
< sizeof(reply
)) {
1595 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1600 * relay_start: send an acknowledgment to the client to tell if we are
1601 * ready to receive data. We are ready if a session is established.
1603 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1604 struct relay_connection
*conn
,
1605 const struct lttng_buffer_view
*payload
)
1609 struct lttcomm_relayd_generic_reply reply
;
1610 struct relay_session
*session
= conn
->session
;
1613 DBG("Trying to start the streaming without a session established");
1614 ret
= htobe32(LTTNG_ERR_UNK
);
1617 memset(&reply
, 0, sizeof(reply
));
1618 reply
.ret_code
= htobe32(LTTNG_OK
);
1619 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1621 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1622 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1631 * Append padding to the file pointed by the file descriptor fd.
1633 static int write_padding_to_file(int fd
, uint32_t size
)
1642 zeros
= zmalloc(size
);
1643 if (zeros
== NULL
) {
1644 PERROR("zmalloc zeros for padding");
1649 ret
= lttng_write(fd
, zeros
, size
);
1651 PERROR("write padding to file");
1661 * Close the current index file if it is open, and create a new one.
1663 * Return 0 on success, -1 on error.
1666 int create_rotate_index_file(struct relay_stream
*stream
)
1669 uint32_t major
, minor
;
1671 /* Put ref on previous index_file. */
1672 if (stream
->index_file
) {
1673 lttng_index_file_put(stream
->index_file
);
1674 stream
->index_file
= NULL
;
1676 major
= stream
->trace
->session
->major
;
1677 minor
= stream
->trace
->session
->minor
;
1678 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
1679 stream
->channel_name
,
1680 -1, -1, stream
->tracefile_size
,
1681 tracefile_array_get_file_index_head(stream
->tfa
),
1682 lttng_to_index_major(major
, minor
),
1683 lttng_to_index_minor(major
, minor
));
1684 if (!stream
->index_file
) {
1696 int do_rotate_stream(struct relay_stream
*stream
)
1700 /* Perform the stream rotation. */
1701 ret
= utils_rotate_stream_file(stream
->path_name
,
1702 stream
->channel_name
, stream
->tracefile_size
,
1703 stream
->tracefile_count
, -1,
1704 -1, stream
->stream_fd
->fd
,
1705 NULL
, &stream
->stream_fd
->fd
);
1707 ERR("Rotating stream output file");
1710 stream
->tracefile_size_current
= 0;
1712 /* Rotate also the index if the stream is not a metadata stream. */
1713 if (!stream
->is_metadata
) {
1714 ret
= create_rotate_index_file(stream
);
1716 ERR("Failed to rotate index file");
1721 stream
->rotate_at_seq_num
= -1ULL;
1722 stream
->pos_after_last_complete_data_index
= 0;
1729 * If too much data has been written in a tracefile before we received the
1730 * rotation command, we have to move the excess data to the new tracefile and
1731 * perform the rotation. This can happen because the control and data
1732 * connections are separate, the indexes as well as the commands arrive from
1733 * the control connection and we have no control over the order so we could be
1734 * in a situation where too much data has been received on the data connection
1735 * before the rotation command on the control connection arrives. We don't need
1736 * to update the index because its order is guaranteed with the rotation
1740 int rotate_truncate_stream(struct relay_stream
*stream
)
1744 uint64_t diff
, pos
= 0;
1745 char buf
[FILE_COPY_BUFFER_SIZE
];
1747 assert(!stream
->is_metadata
);
1749 assert(stream
->tracefile_size_current
>
1750 stream
->pos_after_last_complete_data_index
);
1751 diff
= stream
->tracefile_size_current
-
1752 stream
->pos_after_last_complete_data_index
;
1754 /* Create the new tracefile. */
1755 new_fd
= utils_create_stream_file(stream
->path_name
,
1756 stream
->channel_name
,
1757 stream
->tracefile_size
, stream
->tracefile_count
,
1758 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1760 ERR("Failed to create new stream file at path %s for channel %s",
1761 stream
->path_name
, stream
->channel_name
);
1767 * Rewind the current tracefile to the position at which the rotation
1768 * should have occured.
1770 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1771 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1772 if (lseek_ret
< 0) {
1773 PERROR("seek truncate stream");
1778 /* Move data from the old file to the new file. */
1779 while (pos
< diff
) {
1780 uint64_t count
, bytes_left
;
1783 bytes_left
= diff
- pos
;
1784 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1785 assert(count
<= SIZE_MAX
);
1787 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1788 if (io_ret
< (ssize_t
) count
) {
1789 char error_string
[256];
1791 snprintf(error_string
, sizeof(error_string
),
1792 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1793 count
, stream
->stream_fd
->fd
, io_ret
);
1795 PERROR("%s", error_string
);
1797 ERR("%s", error_string
);
1803 io_ret
= lttng_write(new_fd
, buf
, count
);
1804 if (io_ret
< (ssize_t
) count
) {
1805 char error_string
[256];
1807 snprintf(error_string
, sizeof(error_string
),
1808 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1809 count
, new_fd
, io_ret
);
1811 PERROR("%s", error_string
);
1813 ERR("%s", error_string
);
1822 /* Truncate the file to get rid of the excess data. */
1823 ret
= ftruncate(stream
->stream_fd
->fd
,
1824 stream
->pos_after_last_complete_data_index
);
1826 PERROR("ftruncate");
1830 ret
= close(stream
->stream_fd
->fd
);
1832 PERROR("Closing tracefile");
1836 ret
= create_rotate_index_file(stream
);
1838 ERR("Rotate stream index file");
1843 * Update the offset and FD of all the eventual indexes created by the
1844 * data connection before the rotation command arrived.
1846 ret
= relay_index_switch_all_files(stream
);
1848 ERR("Failed to rotate index file");
1852 stream
->stream_fd
->fd
= new_fd
;
1853 stream
->tracefile_size_current
= diff
;
1854 stream
->pos_after_last_complete_data_index
= 0;
1855 stream
->rotate_at_seq_num
= -1ULL;
1864 * Check if a stream should perform a rotation (for session rotation).
1865 * Must be called with the stream lock held.
1867 * Return 0 on success, a negative value on error.
1870 int try_rotate_stream(struct relay_stream
*stream
)
1874 /* No rotation expected. */
1875 if (stream
->rotate_at_seq_num
== -1ULL) {
1879 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1880 stream
->prev_seq
== -1ULL) {
1881 DBG("Stream %" PRIu64
" no yet ready for rotation",
1882 stream
->stream_handle
);
1884 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1885 DBG("Rotation after too much data has been written in tracefile "
1886 "for stream %" PRIu64
", need to truncate before "
1887 "rotating", stream
->stream_handle
);
1888 ret
= rotate_truncate_stream(stream
);
1890 ERR("Failed to truncate stream");
1894 /* stream->prev_seq == stream->rotate_at_seq_num */
1895 DBG("Stream %" PRIu64
" ready for rotation",
1896 stream
->stream_handle
);
1897 ret
= do_rotate_stream(stream
);
1905 * relay_recv_metadata: receive the metadata for the session.
1907 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1908 struct relay_connection
*conn
,
1909 const struct lttng_buffer_view
*payload
)
1913 struct relay_session
*session
= conn
->session
;
1914 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1915 struct relay_stream
*metadata_stream
;
1916 uint64_t metadata_payload_size
;
1919 ERR("Metadata sent before version check");
1924 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1925 ERR("Incorrect data size");
1929 metadata_payload_size
= recv_hdr
->data_size
-
1930 sizeof(struct lttcomm_relayd_metadata_payload
);
1932 memcpy(&metadata_payload_header
, payload
->data
,
1933 sizeof(metadata_payload_header
));
1934 metadata_payload_header
.stream_id
= be64toh(
1935 metadata_payload_header
.stream_id
);
1936 metadata_payload_header
.padding_size
= be32toh(
1937 metadata_payload_header
.padding_size
);
1939 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1940 if (!metadata_stream
) {
1945 pthread_mutex_lock(&metadata_stream
->lock
);
1947 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1948 payload
->data
+ sizeof(metadata_payload_header
),
1949 metadata_payload_size
);
1950 if (size_ret
< metadata_payload_size
) {
1951 ERR("Relay error writing metadata on file");
1956 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1957 metadata_payload_header
.padding_size
);
1958 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1963 metadata_stream
->metadata_received
+=
1964 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1965 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1966 metadata_stream
->metadata_received
);
1968 ret
= try_rotate_stream(metadata_stream
);
1974 pthread_mutex_unlock(&metadata_stream
->lock
);
1975 stream_put(metadata_stream
);
1981 * relay_send_version: send relayd version number
1983 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1984 struct relay_connection
*conn
,
1985 const struct lttng_buffer_view
*payload
)
1989 struct lttcomm_relayd_version reply
, msg
;
1990 bool compatible
= true;
1992 conn
->version_check_done
= true;
1994 /* Get version from the other side. */
1995 if (payload
->size
< sizeof(msg
)) {
1996 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1997 sizeof(msg
), payload
->size
);
2002 memcpy(&msg
, payload
->data
, sizeof(msg
));
2003 msg
.major
= be32toh(msg
.major
);
2004 msg
.minor
= be32toh(msg
.minor
);
2006 memset(&reply
, 0, sizeof(reply
));
2007 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
2008 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
2010 /* Major versions must be the same */
2011 if (reply
.major
!= msg
.major
) {
2012 DBG("Incompatible major versions (%u vs %u), deleting session",
2013 reply
.major
, msg
.major
);
2017 conn
->major
= reply
.major
;
2018 /* We adapt to the lowest compatible version */
2019 if (reply
.minor
<= msg
.minor
) {
2020 conn
->minor
= reply
.minor
;
2022 conn
->minor
= msg
.minor
;
2025 reply
.major
= htobe32(reply
.major
);
2026 reply
.minor
= htobe32(reply
.minor
);
2027 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2029 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2030 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2043 DBG("Version check done using protocol %u.%u", conn
->major
,
2051 * Check for data pending for a given stream id from the session daemon.
2053 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2054 struct relay_connection
*conn
,
2055 const struct lttng_buffer_view
*payload
)
2057 struct relay_session
*session
= conn
->session
;
2058 struct lttcomm_relayd_data_pending msg
;
2059 struct lttcomm_relayd_generic_reply reply
;
2060 struct relay_stream
*stream
;
2064 DBG("Data pending command received");
2066 if (!session
|| !conn
->version_check_done
) {
2067 ERR("Trying to check for data before version check");
2069 goto end_no_session
;
2072 if (payload
->size
< sizeof(msg
)) {
2073 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2074 sizeof(msg
), payload
->size
);
2076 goto end_no_session
;
2078 memcpy(&msg
, payload
->data
, sizeof(msg
));
2079 msg
.stream_id
= be64toh(msg
.stream_id
);
2080 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2082 stream
= stream_get_by_id(msg
.stream_id
);
2083 if (stream
== NULL
) {
2088 pthread_mutex_lock(&stream
->lock
);
2090 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2091 " and last_seq %" PRIu64
, msg
.stream_id
,
2092 stream
->prev_seq
, msg
.last_net_seq_num
);
2094 /* Avoid wrapping issue */
2095 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2096 /* Data has in fact been written and is NOT pending */
2099 /* Data still being streamed thus pending */
2103 stream
->data_pending_check_done
= true;
2104 pthread_mutex_unlock(&stream
->lock
);
2109 memset(&reply
, 0, sizeof(reply
));
2110 reply
.ret_code
= htobe32(ret
);
2111 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2112 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2113 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2123 * Wait for the control socket to reach a quiescent state.
2125 * Note that for now, when receiving this command from the session
2126 * daemon, this means that every subsequent commands or data received on
2127 * the control socket has been handled. So, this is why we simply return
2130 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2131 struct relay_connection
*conn
,
2132 const struct lttng_buffer_view
*payload
)
2136 struct relay_stream
*stream
;
2137 struct lttcomm_relayd_quiescent_control msg
;
2138 struct lttcomm_relayd_generic_reply reply
;
2140 DBG("Checking quiescent state on control socket");
2142 if (!conn
->session
|| !conn
->version_check_done
) {
2143 ERR("Trying to check for data before version check");
2145 goto end_no_session
;
2148 if (payload
->size
< sizeof(msg
)) {
2149 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2150 sizeof(msg
), payload
->size
);
2152 goto end_no_session
;
2154 memcpy(&msg
, payload
->data
, sizeof(msg
));
2155 msg
.stream_id
= be64toh(msg
.stream_id
);
2157 stream
= stream_get_by_id(msg
.stream_id
);
2161 pthread_mutex_lock(&stream
->lock
);
2162 stream
->data_pending_check_done
= true;
2163 pthread_mutex_unlock(&stream
->lock
);
2165 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2168 memset(&reply
, 0, sizeof(reply
));
2169 reply
.ret_code
= htobe32(LTTNG_OK
);
2170 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2171 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2172 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2184 * Initialize a data pending command. This means that a consumer is about
2185 * to ask for data pending for each stream it holds. Simply iterate over
2186 * all streams of a session and set the data_pending_check_done flag.
2188 * This command returns to the client a LTTNG_OK code.
2190 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2191 struct relay_connection
*conn
,
2192 const struct lttng_buffer_view
*payload
)
2196 struct lttng_ht_iter iter
;
2197 struct lttcomm_relayd_begin_data_pending msg
;
2198 struct lttcomm_relayd_generic_reply reply
;
2199 struct relay_stream
*stream
;
2204 DBG("Init streams for data pending");
2206 if (!conn
->session
|| !conn
->version_check_done
) {
2207 ERR("Trying to check for data before version check");
2209 goto end_no_session
;
2212 if (payload
->size
< sizeof(msg
)) {
2213 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2214 sizeof(msg
), payload
->size
);
2216 goto end_no_session
;
2218 memcpy(&msg
, payload
->data
, sizeof(msg
));
2219 msg
.session_id
= be64toh(msg
.session_id
);
2222 * Iterate over all streams to set the begin data pending flag.
2223 * For now, the streams are indexed by stream handle so we have
2224 * to iterate over all streams to find the one associated with
2225 * the right session_id.
2228 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2230 if (!stream_get(stream
)) {
2233 if (stream
->trace
->session
->id
== msg
.session_id
) {
2234 pthread_mutex_lock(&stream
->lock
);
2235 stream
->data_pending_check_done
= false;
2236 pthread_mutex_unlock(&stream
->lock
);
2237 DBG("Set begin data pending flag to stream %" PRIu64
,
2238 stream
->stream_handle
);
2244 memset(&reply
, 0, sizeof(reply
));
2245 /* All good, send back reply. */
2246 reply
.ret_code
= htobe32(LTTNG_OK
);
2248 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2249 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2250 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2262 * End data pending command. This will check, for a given session id, if
2263 * each stream associated with it has its data_pending_check_done flag
2264 * set. If not, this means that the client lost track of the stream but
2265 * the data is still being streamed on our side. In this case, we inform
2266 * the client that data is in flight.
2268 * Return to the client if there is data in flight or not with a ret_code.
2270 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2271 struct relay_connection
*conn
,
2272 const struct lttng_buffer_view
*payload
)
2276 struct lttng_ht_iter iter
;
2277 struct lttcomm_relayd_end_data_pending msg
;
2278 struct lttcomm_relayd_generic_reply reply
;
2279 struct relay_stream
*stream
;
2280 uint32_t is_data_inflight
= 0;
2282 DBG("End data pending command");
2284 if (!conn
->session
|| !conn
->version_check_done
) {
2285 ERR("Trying to check for data before version check");
2287 goto end_no_session
;
2290 if (payload
->size
< sizeof(msg
)) {
2291 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2292 sizeof(msg
), payload
->size
);
2294 goto end_no_session
;
2296 memcpy(&msg
, payload
->data
, sizeof(msg
));
2297 msg
.session_id
= be64toh(msg
.session_id
);
2300 * Iterate over all streams to see if the begin data pending
2304 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2306 if (!stream_get(stream
)) {
2309 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2313 pthread_mutex_lock(&stream
->lock
);
2314 if (!stream
->data_pending_check_done
) {
2315 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2316 is_data_inflight
= 1;
2317 DBG("Data is still in flight for stream %" PRIu64
,
2318 stream
->stream_handle
);
2319 pthread_mutex_unlock(&stream
->lock
);
2324 pthread_mutex_unlock(&stream
->lock
);
2329 memset(&reply
, 0, sizeof(reply
));
2330 /* All good, send back reply. */
2331 reply
.ret_code
= htobe32(is_data_inflight
);
2333 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2334 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2335 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2347 * Receive an index for a specific stream.
2349 * Return 0 on success else a negative value.
2351 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2352 struct relay_connection
*conn
,
2353 const struct lttng_buffer_view
*payload
)
2357 struct relay_session
*session
= conn
->session
;
2358 struct lttcomm_relayd_index index_info
;
2359 struct relay_index
*index
;
2360 struct lttcomm_relayd_generic_reply reply
;
2361 struct relay_stream
*stream
;
2366 DBG("Relay receiving index");
2368 if (!session
|| !conn
->version_check_done
) {
2369 ERR("Trying to close a stream before version check");
2371 goto end_no_session
;
2374 msg_len
= lttcomm_relayd_index_len(
2375 lttng_to_index_major(conn
->major
, conn
->minor
),
2376 lttng_to_index_minor(conn
->major
, conn
->minor
));
2377 if (payload
->size
< msg_len
) {
2378 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2379 msg_len
, payload
->size
);
2381 goto end_no_session
;
2383 memcpy(&index_info
, payload
->data
, msg_len
);
2384 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2385 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2386 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2387 index_info
.content_size
= be64toh(index_info
.content_size
);
2388 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2389 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2390 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2391 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2393 if (conn
->minor
>= 8) {
2394 index_info
.stream_instance_id
=
2395 be64toh(index_info
.stream_instance_id
);
2396 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2399 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2401 ERR("stream_get_by_id not found");
2405 pthread_mutex_lock(&stream
->lock
);
2407 /* Live beacon handling */
2408 if (index_info
.packet_size
== 0) {
2409 DBG("Received live beacon for stream %" PRIu64
,
2410 stream
->stream_handle
);
2413 * Only flag a stream inactive when it has already
2414 * received data and no indexes are in flight.
2416 if (stream
->index_received_seqcount
> 0
2417 && stream
->indexes_in_flight
== 0) {
2418 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2421 goto end_stream_put
;
2423 stream
->beacon_ts_end
= -1ULL;
2426 if (stream
->ctf_stream_id
== -1ULL) {
2427 stream
->ctf_stream_id
= index_info
.stream_id
;
2429 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2432 ERR("relay_index_get_by_id_or_create index NULL");
2433 goto end_stream_put
;
2435 if (set_index_control_data(index
, &index_info
, conn
)) {
2436 ERR("set_index_control_data error");
2437 relay_index_put(index
);
2439 goto end_stream_put
;
2441 ret
= relay_index_try_flush(index
);
2443 tracefile_array_commit_seq(stream
->tfa
);
2444 stream
->index_received_seqcount
++;
2445 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2446 } else if (ret
> 0) {
2450 ERR("relay_index_try_flush error %d", ret
);
2451 relay_index_put(index
);
2456 pthread_mutex_unlock(&stream
->lock
);
2461 memset(&reply
, 0, sizeof(reply
));
2463 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2465 reply
.ret_code
= htobe32(LTTNG_OK
);
2467 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2468 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2469 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2478 * Receive the streams_sent message.
2480 * Return 0 on success else a negative value.
2482 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2483 struct relay_connection
*conn
,
2484 const struct lttng_buffer_view
*payload
)
2488 struct lttcomm_relayd_generic_reply reply
;
2492 DBG("Relay receiving streams_sent");
2494 if (!conn
->session
|| !conn
->version_check_done
) {
2495 ERR("Trying to close a stream before version check");
2497 goto end_no_session
;
2501 * Publish every pending stream in the connection recv list which are
2502 * now ready to be used by the viewer.
2504 publish_connection_local_streams(conn
);
2506 memset(&reply
, 0, sizeof(reply
));
2507 reply
.ret_code
= htobe32(LTTNG_OK
);
2508 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2509 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2510 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2523 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2524 * rotation feature (not the tracefile rotation feature).
2526 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2527 struct relay_connection
*conn
,
2528 const struct lttng_buffer_view
*payload
)
2532 struct relay_session
*session
= conn
->session
;
2533 struct lttcomm_relayd_rotate_stream stream_info
;
2534 struct lttcomm_relayd_generic_reply reply
;
2535 struct relay_stream
*stream
;
2538 struct lttng_buffer_view new_path_view
;
2540 DBG("Rotate stream received");
2542 if (!session
|| !conn
->version_check_done
) {
2543 ERR("Trying to rotate a stream before version check");
2548 if (session
->major
== 2 && session
->minor
< 11) {
2549 ERR("Unsupported feature before 2.11");
2554 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2556 if (payload
->size
< header_len
) {
2557 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2558 header_len
, payload
->size
);
2563 memcpy(&stream_info
, payload
->data
, header_len
);
2565 /* Convert to host */
2566 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2567 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2568 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2569 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2571 path_len
= stream_info
.pathname_length
;
2572 if (payload
->size
< header_len
+ path_len
) {
2573 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2574 header_len
+ path_len
, payload
->size
);
2579 /* Ensure it fits in local filename length. */
2580 if (path_len
>= LTTNG_PATH_MAX
) {
2581 ret
= -ENAMETOOLONG
;
2582 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2583 path_len
, LTTNG_PATH_MAX
);
2587 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2588 stream_info
.pathname_length
);
2590 stream
= stream_get_by_id(stream_info
.stream_id
);
2596 pthread_mutex_lock(&stream
->lock
);
2599 * Update the trace path (just the folder, the stream name does not
2602 free(stream
->path_name
);
2603 stream
->path_name
= create_output_path(new_path_view
.data
);
2604 if (!stream
->path_name
) {
2605 ERR("Failed to create a new output path");
2607 goto end_stream_unlock
;
2609 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2612 ERR("relay creating output directory");
2614 goto end_stream_unlock
;
2617 assert(stream
->current_chunk_id
.is_set
);
2618 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2620 if (stream
->is_metadata
) {
2622 * The metadata stream is sent only over the control connection
2623 * so we know we have all the data to perform the stream
2626 ret
= do_rotate_stream(stream
);
2628 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2629 ret
= try_rotate_stream(stream
);
2632 goto end_stream_unlock
;
2636 pthread_mutex_unlock(&stream
->lock
);
2639 memset(&reply
, 0, sizeof(reply
));
2641 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2643 reply
.ret_code
= htobe32(LTTNG_OK
);
2645 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2646 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2647 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2648 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2658 * relay_mkdir: Create a folder on the disk.
2660 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2661 struct relay_connection
*conn
,
2662 const struct lttng_buffer_view
*payload
)
2665 struct relay_session
*session
= conn
->session
;
2666 struct lttcomm_relayd_mkdir path_info_header
;
2667 struct lttcomm_relayd_generic_reply reply
;
2671 struct lttng_buffer_view path_view
;
2673 if (!session
|| !conn
->version_check_done
) {
2674 ERR("Trying to create a directory before version check");
2676 goto end_no_session
;
2679 if (session
->major
== 2 && session
->minor
< 11) {
2681 * This client is not supposed to use this command since
2682 * it predates its introduction.
2684 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2686 goto end_no_session
;
2689 header_len
= sizeof(path_info_header
);
2690 if (payload
->size
< header_len
) {
2691 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2692 header_len
, payload
->size
);
2694 goto end_no_session
;
2697 memcpy(&path_info_header
, payload
->data
, header_len
);
2699 path_info_header
.length
= be32toh(path_info_header
.length
);
2701 if (payload
->size
< header_len
+ path_info_header
.length
) {
2702 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2703 header_len
+ path_info_header
.length
, payload
->size
);
2705 goto end_no_session
;
2708 /* Ensure that it fits in local path length. */
2709 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2710 ret
= -ENAMETOOLONG
;
2711 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2712 path_info_header
.length
, LTTNG_PATH_MAX
);
2716 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2717 path_info_header
.length
);
2719 path
= create_output_path(path_view
.data
);
2721 ERR("Failed to create output path");
2726 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2728 ERR("relay creating output directory");
2735 memset(&reply
, 0, sizeof(reply
));
2737 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2739 reply
.ret_code
= htobe32(LTTNG_OK
);
2741 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2742 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2743 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2752 static int validate_rotate_rename_path_length(const char *path_type
,
2753 uint32_t path_length
)
2757 if (path_length
> LTTNG_PATH_MAX
) {
2758 ret
= -ENAMETOOLONG
;
2759 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2760 path_type
, path_length
, LTTNG_PATH_MAX
);
2761 } else if (path_length
== 0) {
2763 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2769 * relay_rotate_rename: rename the trace folder after a rotation is
2770 * completed. We are not closing any fd here, just moving the folder, so it
2771 * works even if data is still in-flight.
2773 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2774 struct relay_connection
*conn
,
2775 const struct lttng_buffer_view
*payload
)
2779 struct relay_session
*session
= conn
->session
;
2780 struct lttcomm_relayd_generic_reply reply
;
2781 struct lttcomm_relayd_rotate_rename header
;
2783 size_t received_paths_size
;
2784 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2785 struct lttng_buffer_view old_path_view
;
2786 struct lttng_buffer_view new_path_view
;
2788 if (!session
|| !conn
->version_check_done
) {
2789 ERR("Trying to rename a trace folder before version check");
2794 if (session
->major
== 2 && session
->minor
< 11) {
2795 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2800 header_len
= sizeof(header
);
2801 if (payload
->size
< header_len
) {
2802 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2803 header_len
, payload
->size
);
2808 memcpy(&header
, payload
->data
, header_len
);
2810 header
.old_path_length
= be32toh(header
.old_path_length
);
2811 header
.new_path_length
= be32toh(header
.new_path_length
);
2812 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2814 if (payload
->size
< header_len
+ received_paths_size
) {
2815 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2816 header_len
, payload
->size
);
2821 /* Ensure the paths don't exceed their allowed size. */
2822 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2826 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2831 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2832 header
.old_path_length
);
2833 new_path_view
= lttng_buffer_view_from_view(payload
,
2834 header_len
+ header
.old_path_length
,
2835 header
.new_path_length
);
2837 /* Validate that both paths received are NULL terminated. */
2838 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2839 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2843 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2844 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2849 complete_old_path
= create_output_path(old_path_view
.data
);
2850 if (!complete_old_path
) {
2851 ERR("Failed to build old output path in rotate_rename command");
2856 complete_new_path
= create_output_path(new_path_view
.data
);
2857 if (!complete_new_path
) {
2858 ERR("Failed to build new output path in rotate_rename command");
2863 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2866 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2872 * If a domain has not yet created its channel, the domain-specific
2873 * folder might not exist, but this is not an error.
2875 ret
= rename(complete_old_path
, complete_new_path
);
2876 if (ret
< 0 && errno
!= ENOENT
) {
2877 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2878 complete_old_path
, complete_new_path
);
2884 memset(&reply
, 0, sizeof(reply
));
2886 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2888 reply
.ret_code
= htobe32(LTTNG_OK
);
2890 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2892 if (send_ret
< sizeof(reply
)) {
2893 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2899 free(complete_old_path
);
2900 free(complete_new_path
);
2905 * Check if all the streams in the session have completed the last rotation.
2906 * The chunk_id value is used to distinguish the cases where a stream was
2907 * closed on the consumerd before the rotation started but it still active on
2908 * the relayd, and the case where a stream appeared on the consumerd/relayd
2909 * after the last rotation started (in that case, it is already writing in the
2910 * new chunk folder).
2913 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2914 struct relay_connection
*conn
,
2915 const struct lttng_buffer_view
*payload
)
2917 struct relay_session
*session
= conn
->session
;
2918 struct lttcomm_relayd_rotate_pending msg
;
2919 struct lttcomm_relayd_rotate_pending_reply reply
;
2920 struct lttng_ht_iter iter
;
2921 struct relay_stream
*stream
;
2925 bool rotate_pending
= false;
2927 DBG("Rotate pending command received");
2929 if (!session
|| !conn
->version_check_done
) {
2930 ERR("Trying to check for data before version check");
2935 if (session
->major
== 2 && session
->minor
< 11) {
2936 ERR("Unsupported feature before 2.11");
2941 if (payload
->size
< sizeof(msg
)) {
2942 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2943 sizeof(msg
), payload
->size
);
2948 memcpy(&msg
, payload
->data
, sizeof(msg
));
2950 chunk_id
= be64toh(msg
.chunk_id
);
2952 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2953 session
->session_name
, chunk_id
);
2956 * Iterate over all the streams in the session and check if they are
2957 * still waiting for data to perform their rotation.
2960 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2962 if (!stream_get(stream
)) {
2965 if (stream
->trace
->session
!= session
) {
2969 pthread_mutex_lock(&stream
->lock
);
2970 if (stream
->rotate_at_seq_num
!= -1ULL) {
2971 /* We have not yet performed the rotation. */
2972 rotate_pending
= true;
2973 DBG("Stream %" PRIu64
" is still rotating",
2974 stream
->stream_handle
);
2975 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
2977 * Stream closed on the consumer but still active on the
2980 rotate_pending
= true;
2981 DBG("Stream %" PRIu64
" did not exist on the consumer "
2982 "when the last rotation started, but is"
2983 "still waiting for data before getting"
2985 stream
->stream_handle
);
2987 pthread_mutex_unlock(&stream
->lock
);
2989 if (rotate_pending
) {
2996 memset(&reply
, 0, sizeof(reply
));
2997 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
2998 reply
.is_pending
= (uint8_t) !!rotate_pending
;
2999 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
3001 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3002 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
3011 #define DBG_CMD(cmd_name, conn) \
3012 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3014 static int relay_process_control_command(struct relay_connection
*conn
,
3015 const struct lttcomm_relayd_hdr
*header
,
3016 const struct lttng_buffer_view
*payload
)
3020 switch (header
->cmd
) {
3021 case RELAYD_CREATE_SESSION
:
3022 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3023 ret
= relay_create_session(header
, conn
, payload
);
3025 case RELAYD_ADD_STREAM
:
3026 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3027 ret
= relay_add_stream(header
, conn
, payload
);
3029 case RELAYD_START_DATA
:
3030 DBG_CMD("RELAYD_START_DATA", conn
);
3031 ret
= relay_start(header
, conn
, payload
);
3033 case RELAYD_SEND_METADATA
:
3034 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3035 ret
= relay_recv_metadata(header
, conn
, payload
);
3037 case RELAYD_VERSION
:
3038 DBG_CMD("RELAYD_VERSION", conn
);
3039 ret
= relay_send_version(header
, conn
, payload
);
3041 case RELAYD_CLOSE_STREAM
:
3042 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3043 ret
= relay_close_stream(header
, conn
, payload
);
3045 case RELAYD_DATA_PENDING
:
3046 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3047 ret
= relay_data_pending(header
, conn
, payload
);
3049 case RELAYD_QUIESCENT_CONTROL
:
3050 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3051 ret
= relay_quiescent_control(header
, conn
, payload
);
3053 case RELAYD_BEGIN_DATA_PENDING
:
3054 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3055 ret
= relay_begin_data_pending(header
, conn
, payload
);
3057 case RELAYD_END_DATA_PENDING
:
3058 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3059 ret
= relay_end_data_pending(header
, conn
, payload
);
3061 case RELAYD_SEND_INDEX
:
3062 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3063 ret
= relay_recv_index(header
, conn
, payload
);
3065 case RELAYD_STREAMS_SENT
:
3066 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3067 ret
= relay_streams_sent(header
, conn
, payload
);
3069 case RELAYD_RESET_METADATA
:
3070 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3071 ret
= relay_reset_metadata(header
, conn
, payload
);
3073 case RELAYD_ROTATE_STREAM
:
3074 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3075 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3077 case RELAYD_ROTATE_RENAME
:
3078 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3079 ret
= relay_rotate_rename(header
, conn
, payload
);
3081 case RELAYD_ROTATE_PENDING
:
3082 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3083 ret
= relay_rotate_pending(header
, conn
, payload
);
3086 DBG_CMD("RELAYD_MKDIR", conn
);
3087 ret
= relay_mkdir(header
, conn
, payload
);
3089 case RELAYD_UPDATE_SYNC_INFO
:
3091 ERR("Received unknown command (%u)", header
->cmd
);
3092 relay_unknown_command(conn
);
3101 static enum relay_connection_status
relay_process_control_receive_payload(
3102 struct relay_connection
*conn
)
3105 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3106 struct lttng_dynamic_buffer
*reception_buffer
=
3107 &conn
->protocol
.ctrl
.reception_buffer
;
3108 struct ctrl_connection_state_receive_payload
*state
=
3109 &conn
->protocol
.ctrl
.state
.receive_payload
;
3110 struct lttng_buffer_view payload_view
;
3112 if (state
->left_to_receive
== 0) {
3113 /* Short-circuit for payload-less commands. */
3114 goto reception_complete
;
3117 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3118 reception_buffer
->data
+ state
->received
,
3119 state
->left_to_receive
, MSG_DONTWAIT
);
3121 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3122 PERROR("Unable to receive command payload on sock %d",
3124 status
= RELAY_CONNECTION_STATUS_ERROR
;
3127 } else if (ret
== 0) {
3128 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3129 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3134 assert(ret
<= state
->left_to_receive
);
3136 state
->left_to_receive
-= ret
;
3137 state
->received
+= ret
;
3139 if (state
->left_to_receive
> 0) {
3141 * Can't transition to the protocol's next state, wait to
3142 * receive the rest of the header.
3144 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3145 state
->received
, state
->left_to_receive
,
3151 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3152 conn
->sock
->fd
, state
->received
);
3154 * The payload required to process the command has been received.
3155 * A view to the reception buffer is forwarded to the various
3156 * commands and the state of the control is reset on success.
3158 * Commands are responsible for sending their reply to the peer.
3160 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3162 ret
= relay_process_control_command(conn
,
3163 &state
->header
, &payload_view
);
3165 status
= RELAY_CONNECTION_STATUS_ERROR
;
3169 ret
= connection_reset_protocol_state(conn
);
3171 status
= RELAY_CONNECTION_STATUS_ERROR
;
3177 static enum relay_connection_status
relay_process_control_receive_header(
3178 struct relay_connection
*conn
)
3181 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3182 struct lttcomm_relayd_hdr header
;
3183 struct lttng_dynamic_buffer
*reception_buffer
=
3184 &conn
->protocol
.ctrl
.reception_buffer
;
3185 struct ctrl_connection_state_receive_header
*state
=
3186 &conn
->protocol
.ctrl
.state
.receive_header
;
3188 assert(state
->left_to_receive
!= 0);
3190 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3191 reception_buffer
->data
+ state
->received
,
3192 state
->left_to_receive
, MSG_DONTWAIT
);
3194 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3195 PERROR("Unable to receive control command header on sock %d",
3197 status
= RELAY_CONNECTION_STATUS_ERROR
;
3200 } else if (ret
== 0) {
3201 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3202 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3207 assert(ret
<= state
->left_to_receive
);
3209 state
->left_to_receive
-= ret
;
3210 state
->received
+= ret
;
3212 if (state
->left_to_receive
> 0) {
3214 * Can't transition to the protocol's next state, wait to
3215 * receive the rest of the header.
3217 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3218 state
->received
, state
->left_to_receive
,
3223 /* Transition to next state: receiving the command's payload. */
3224 conn
->protocol
.ctrl
.state_id
=
3225 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3226 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3227 header
.circuit_id
= be64toh(header
.circuit_id
);
3228 header
.data_size
= be64toh(header
.data_size
);
3229 header
.cmd
= be32toh(header
.cmd
);
3230 header
.cmd_version
= be32toh(header
.cmd_version
);
3231 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3232 &header
, sizeof(header
));
3234 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3235 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3238 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3239 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3241 status
= RELAY_CONNECTION_STATUS_ERROR
;
3245 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3247 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3248 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3251 status
= RELAY_CONNECTION_STATUS_ERROR
;
3255 if (header
.data_size
== 0) {
3257 * Manually invoke the next state as the poll loop
3258 * will not wake-up to allow us to proceed further.
3260 status
= relay_process_control_receive_payload(conn
);
3267 * Process the commands received on the control socket
3269 static enum relay_connection_status
relay_process_control(
3270 struct relay_connection
*conn
)
3272 enum relay_connection_status status
;
3274 switch (conn
->protocol
.ctrl
.state_id
) {
3275 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3276 status
= relay_process_control_receive_header(conn
);
3278 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3279 status
= relay_process_control_receive_payload(conn
);
3282 ERR("Unknown control connection protocol state encountered.");
3290 * Handle index for a data stream.
3292 * Called with the stream lock held.
3294 * Return 0 on success else a negative value.
3296 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3297 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3300 uint64_t data_offset
;
3301 struct relay_index
*index
;
3303 /* Get data offset because we are about to update the index. */
3304 data_offset
= htobe64(stream
->tracefile_size_current
);
3306 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3307 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3310 * Lookup for an existing index for that stream id/sequence
3311 * number. If it exists, the control thread has already received the
3312 * data for it, thus we need to write it to disk.
3314 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3320 if (rotate_index
|| !stream
->index_file
) {
3321 ret
= create_rotate_index_file(stream
);
3323 ERR("Failed to rotate index");
3324 /* Put self-ref for this index due to error. */
3325 relay_index_put(index
);
3331 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3333 /* Put self-ref for this index due to error. */
3334 relay_index_put(index
);
3339 ret
= relay_index_try_flush(index
);
3341 tracefile_array_commit_seq(stream
->tfa
);
3342 stream
->index_received_seqcount
++;
3344 } else if (ret
> 0) {
3345 index
->total_size
= total_size
;
3349 /* Put self-ref for this index due to error. */
3350 relay_index_put(index
);
3358 static enum relay_connection_status
relay_process_data_receive_header(
3359 struct relay_connection
*conn
)
3362 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3363 struct data_connection_state_receive_header
*state
=
3364 &conn
->protocol
.data
.state
.receive_header
;
3365 struct lttcomm_relayd_data_hdr header
;
3366 struct relay_stream
*stream
;
3368 assert(state
->left_to_receive
!= 0);
3370 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3371 state
->header_reception_buffer
+ state
->received
,
3372 state
->left_to_receive
, MSG_DONTWAIT
);
3374 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3375 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3376 status
= RELAY_CONNECTION_STATUS_ERROR
;
3379 } else if (ret
== 0) {
3380 /* Orderly shutdown. Not necessary to print an error. */
3381 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3382 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3387 assert(ret
<= state
->left_to_receive
);
3389 state
->left_to_receive
-= ret
;
3390 state
->received
+= ret
;
3392 if (state
->left_to_receive
> 0) {
3394 * Can't transition to the protocol's next state, wait to
3395 * receive the rest of the header.
3397 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3398 state
->received
, state
->left_to_receive
,
3403 /* Transition to next state: receiving the payload. */
3404 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3406 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3407 header
.circuit_id
= be64toh(header
.circuit_id
);
3408 header
.stream_id
= be64toh(header
.stream_id
);
3409 header
.data_size
= be32toh(header
.data_size
);
3410 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3411 header
.padding_size
= be32toh(header
.padding_size
);
3412 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3414 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3416 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3417 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3419 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3420 conn
->sock
->fd
, header
.circuit_id
,
3421 header
.stream_id
, header
.data_size
,
3422 header
.net_seq_num
, header
.padding_size
);
3424 stream
= stream_get_by_id(header
.stream_id
);
3426 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3428 /* Protocol error. */
3429 status
= RELAY_CONNECTION_STATUS_ERROR
;
3433 pthread_mutex_lock(&stream
->lock
);
3435 /* Check if a rotation is needed. */
3436 if (stream
->tracefile_size
> 0 &&
3437 (stream
->tracefile_size_current
+ header
.data_size
) >
3438 stream
->tracefile_size
) {
3439 uint64_t old_id
, new_id
;
3441 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3442 tracefile_array_file_rotate(stream
->tfa
);
3444 /* new_id is updated by utils_rotate_stream_file. */
3447 ret
= utils_rotate_stream_file(stream
->path_name
,
3448 stream
->channel_name
, stream
->tracefile_size
,
3449 stream
->tracefile_count
, -1,
3450 -1, stream
->stream_fd
->fd
,
3451 &new_id
, &stream
->stream_fd
->fd
);
3453 ERR("Failed to rotate stream output file");
3454 status
= RELAY_CONNECTION_STATUS_ERROR
;
3455 goto end_stream_unlock
;
3459 * Reset current size because we just performed a stream
3462 stream
->tracefile_size_current
= 0;
3463 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3467 pthread_mutex_unlock(&stream
->lock
);
3473 static enum relay_connection_status
relay_process_data_receive_payload(
3474 struct relay_connection
*conn
)
3477 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3478 struct relay_stream
*stream
;
3479 struct data_connection_state_receive_payload
*state
=
3480 &conn
->protocol
.data
.state
.receive_payload
;
3481 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3482 char data_buffer
[chunk_size
];
3483 bool partial_recv
= false;
3484 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3485 uint64_t left_to_receive
= state
->left_to_receive
;
3486 struct relay_session
*session
;
3488 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3489 state
->header
.stream_id
, state
->header
.net_seq_num
,
3490 state
->received
, left_to_receive
);
3492 stream
= stream_get_by_id(state
->header
.stream_id
);
3494 /* Protocol error. */
3495 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3496 state
->header
.stream_id
);
3497 status
= RELAY_CONNECTION_STATUS_ERROR
;
3501 pthread_mutex_lock(&stream
->lock
);
3502 session
= stream
->trace
->session
;
3503 if (!conn
->session
) {
3504 ret
= connection_set_session(conn
, session
);
3506 status
= RELAY_CONNECTION_STATUS_ERROR
;
3507 goto end_stream_unlock
;
3512 * The size of the "chunk" received on any iteration is bounded by:
3513 * - the data left to receive,
3514 * - the data immediately available on the socket,
3515 * - the on-stack data buffer
3517 while (left_to_receive
> 0 && !partial_recv
) {
3519 size_t recv_size
= min(left_to_receive
, chunk_size
);
3521 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3522 recv_size
, MSG_DONTWAIT
);
3524 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3525 PERROR("Socket %d error", conn
->sock
->fd
);
3526 status
= RELAY_CONNECTION_STATUS_ERROR
;
3528 goto end_stream_unlock
;
3529 } else if (ret
== 0) {
3530 /* No more data ready to be consumed on socket. */
3531 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3532 state
->header
.stream_id
);
3533 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3535 } else if (ret
< (int) recv_size
) {
3537 * All the data available on the socket has been
3540 partial_recv
= true;
3545 /* Write data to stream output fd. */
3546 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3548 if (write_ret
< (ssize_t
) recv_size
) {
3549 ERR("Relay error writing data to file");
3550 status
= RELAY_CONNECTION_STATUS_ERROR
;
3551 goto end_stream_unlock
;
3554 left_to_receive
-= recv_size
;
3555 state
->received
+= recv_size
;
3556 state
->left_to_receive
= left_to_receive
;
3558 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3559 write_ret
, stream
->stream_handle
);
3562 if (state
->left_to_receive
> 0) {
3564 * Did not receive all the data expected, wait for more data to
3565 * become available on the socket.
3567 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3568 state
->header
.stream_id
, state
->received
,
3569 state
->left_to_receive
);
3570 goto end_stream_unlock
;
3573 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3574 state
->header
.padding_size
);
3575 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3576 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3577 stream
->stream_handle
,
3578 state
->header
.net_seq_num
, ret
);
3579 status
= RELAY_CONNECTION_STATUS_ERROR
;
3580 goto end_stream_unlock
;
3584 if (session
->minor
>= 4 && !session
->snapshot
) {
3585 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3586 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3588 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3589 stream
->stream_handle
,
3590 state
->header
.net_seq_num
, ret
);
3591 status
= RELAY_CONNECTION_STATUS_ERROR
;
3592 goto end_stream_unlock
;
3596 stream
->tracefile_size_current
+= state
->header
.data_size
+
3597 state
->header
.padding_size
;
3599 if (stream
->prev_seq
== -1ULL) {
3602 if (index_flushed
) {
3603 stream
->pos_after_last_complete_data_index
=
3604 stream
->tracefile_size_current
;
3607 stream
->prev_seq
= state
->header
.net_seq_num
;
3610 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3611 * contents of *state which are aliased (union) to the same location as
3612 * the new state. Don't use it beyond this point.
3614 connection_reset_protocol_state(conn
);
3617 ret
= try_rotate_stream(stream
);
3619 status
= RELAY_CONNECTION_STATUS_ERROR
;
3620 goto end_stream_unlock
;
3624 close_requested
= stream
->close_requested
;
3625 pthread_mutex_unlock(&stream
->lock
);
3626 if (close_requested
&& left_to_receive
== 0) {
3627 try_stream_close(stream
);
3631 pthread_mutex_lock(&session
->lock
);
3632 uatomic_set(&session
->new_streams
, 1);
3633 pthread_mutex_unlock(&session
->lock
);
3642 * relay_process_data: Process the data received on the data socket
3644 static enum relay_connection_status
relay_process_data(
3645 struct relay_connection
*conn
)
3647 enum relay_connection_status status
;
3649 switch (conn
->protocol
.data
.state_id
) {
3650 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3651 status
= relay_process_data_receive_header(conn
);
3653 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3654 status
= relay_process_data_receive_payload(conn
);
3657 ERR("Unexpected data connection communication state.");
3664 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3668 (void) lttng_poll_del(events
, pollfd
);
3670 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
3671 fd_tracker_util_close_fd
, NULL
);
3673 ERR("Closing pollfd %d", pollfd
);
3677 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3678 int pollfd
, struct relay_connection
*conn
)
3680 const char *type_str
;
3682 switch (conn
->type
) {
3687 type_str
= "Control";
3689 case RELAY_VIEWER_COMMAND
:
3690 type_str
= "Viewer Command";
3692 case RELAY_VIEWER_NOTIFICATION
:
3693 type_str
= "Viewer Notification";
3696 type_str
= "Unknown";
3698 cleanup_connection_pollfd(events
, pollfd
);
3699 connection_put(conn
);
3700 DBG("%s connection closed with %d", type_str
, pollfd
);
3704 * This thread does the actual work
3706 static void *relay_thread_worker(void *data
)
3708 int ret
, err
= -1, last_seen_data_fd
= -1;
3710 struct lttng_poll_event events
;
3711 struct lttng_ht
*relay_connections_ht
;
3712 struct lttng_ht_iter iter
;
3713 struct relay_connection
*destroy_conn
= NULL
;
3715 DBG("[thread] Relay worker started");
3717 rcu_register_thread();
3719 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3721 if (testpoint(relayd_thread_worker
)) {
3722 goto error_testpoint
;
3725 health_code_update();
3727 /* table of connections indexed on socket */
3728 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3729 if (!relay_connections_ht
) {
3730 goto relay_connections_ht_error
;
3733 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3735 goto error_poll_create
;
3738 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3745 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3747 health_code_update();
3749 /* Infinite blocking call, waiting for transmission */
3750 DBG3("Relayd worker thread polling...");
3751 health_poll_entry();
3752 ret
= lttng_poll_wait(&events
, -1);
3756 * Restart interrupted system call.
3758 if (errno
== EINTR
) {
3767 * Process control. The control connection is
3768 * prioritized so we don't starve it with high
3769 * throughput tracing data on the data connection.
3771 for (i
= 0; i
< nb_fd
; i
++) {
3772 /* Fetch once the poll data */
3773 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3774 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3776 health_code_update();
3780 * No activity for this FD (poll
3786 /* Thread quit pipe has been closed. Killing thread. */
3787 ret
= check_thread_quit_pipe(pollfd
, revents
);
3793 /* Inspect the relay conn pipe for new connection */
3794 if (pollfd
== relay_conn_pipe
[0]) {
3795 if (revents
& LPOLLIN
) {
3796 struct relay_connection
*conn
;
3798 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3802 lttng_poll_add(&events
, conn
->sock
->fd
,
3803 LPOLLIN
| LPOLLRDHUP
);
3804 connection_ht_add(relay_connections_ht
, conn
);
3805 DBG("Connection socket %d added", conn
->sock
->fd
);
3806 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3807 ERR("Relay connection pipe error");
3810 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3814 struct relay_connection
*ctrl_conn
;
3816 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3817 /* If not found, there is a synchronization issue. */
3820 if (ctrl_conn
->type
== RELAY_DATA
) {
3821 if (revents
& LPOLLIN
) {
3823 * Flag the last seen data fd not deleted. It will be
3824 * used as the last seen fd if any fd gets deleted in
3827 last_notdel_data_fd
= pollfd
;
3829 goto put_ctrl_connection
;
3831 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3833 if (revents
& LPOLLIN
) {
3834 enum relay_connection_status status
;
3836 status
= relay_process_control(ctrl_conn
);
3837 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3839 * On socket error flag the session as aborted to force
3840 * the cleanup of its stream otherwise it can leak
3841 * during the lifetime of the relayd.
3843 * This prevents situations in which streams can be
3844 * left opened because an index was received, the
3845 * control connection is closed, and the data
3846 * connection is closed (uncleanly) before the packet's
3849 * Since the control connection encountered an error,
3850 * it is okay to be conservative and close the
3851 * session right now as we can't rely on the protocol
3852 * being respected anymore.
3854 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3855 session_abort(ctrl_conn
->session
);
3858 /* Clear the connection on error or close. */
3859 relay_thread_close_connection(&events
,
3864 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3865 relay_thread_close_connection(&events
,
3867 if (last_seen_data_fd
== pollfd
) {
3868 last_seen_data_fd
= last_notdel_data_fd
;
3871 ERR("Unexpected poll events %u for control sock %d",
3873 connection_put(ctrl_conn
);
3876 put_ctrl_connection
:
3877 connection_put(ctrl_conn
);
3882 * The last loop handled a control request, go back to poll to make
3883 * sure we prioritise the control socket.
3889 if (last_seen_data_fd
>= 0) {
3890 for (i
= 0; i
< nb_fd
; i
++) {
3891 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3893 health_code_update();
3895 if (last_seen_data_fd
== pollfd
) {
3902 /* Process data connection. */
3903 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3904 /* Fetch the poll data. */
3905 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3906 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3907 struct relay_connection
*data_conn
;
3909 health_code_update();
3912 /* No activity for this FD (poll implementation). */
3916 /* Skip the command pipe. It's handled in the first loop. */
3917 if (pollfd
== relay_conn_pipe
[0]) {
3921 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3923 /* Skip it. Might be removed before. */
3926 if (data_conn
->type
== RELAY_CONTROL
) {
3927 goto put_data_connection
;
3929 assert(data_conn
->type
== RELAY_DATA
);
3931 if (revents
& LPOLLIN
) {
3932 enum relay_connection_status status
;
3934 status
= relay_process_data(data_conn
);
3935 /* Connection closed or error. */
3936 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3938 * On socket error flag the session as aborted to force
3939 * the cleanup of its stream otherwise it can leak
3940 * during the lifetime of the relayd.
3942 * This prevents situations in which streams can be
3943 * left opened because an index was received, the
3944 * control connection is closed, and the data
3945 * connection is closed (uncleanly) before the packet's
3948 * Since the data connection encountered an error,
3949 * it is okay to be conservative and close the
3950 * session right now as we can't rely on the protocol
3951 * being respected anymore.
3953 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3954 session_abort(data_conn
->session
);
3956 relay_thread_close_connection(&events
, pollfd
,
3959 * Every goto restart call sets the last seen fd where
3960 * here we don't really care since we gracefully
3961 * continue the loop after the connection is deleted.
3964 /* Keep last seen port. */
3965 last_seen_data_fd
= pollfd
;
3966 connection_put(data_conn
);
3969 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3970 relay_thread_close_connection(&events
, pollfd
,
3973 ERR("Unknown poll events %u for data sock %d",
3976 put_data_connection
:
3977 connection_put(data_conn
);
3979 last_seen_data_fd
= -1;
3982 /* Normal exit, no error */
3987 /* Cleanup remaining connection object. */
3989 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3992 health_code_update();
3994 session_abort(destroy_conn
->session
);
3997 * No need to grab another ref, because we own
4000 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4005 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
4007 lttng_ht_destroy(relay_connections_ht
);
4008 relay_connections_ht_error
:
4009 /* Close relay conn pipes */
4010 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
4013 DBG("Thread exited with error");
4015 DBG("Worker thread cleanup complete");
4019 ERR("Health error occurred in %s", __func__
);
4021 health_unregister(health_relayd
);
4022 rcu_unregister_thread();
4023 lttng_relay_stop_threads();
4028 * Create the relay command pipe to wake thread_manage_apps.
4029 * Closed in cleanup().
4031 static int create_relay_conn_pipe(void)
4033 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
4034 "Relayd connection pipe", relay_conn_pipe
);
4038 int stdio_open(void *data
, int *fds
)
4040 fds
[0] = fileno(stdout
);
4041 fds
[1] = fileno(stderr
);
4046 int noop_close(void *data
, int *fds
)
4052 int track_stdio(void)
4055 const char *names
[] = { "stdout", "stderr" };
4057 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4058 names
, 2, stdio_open
, NULL
);
4062 void untrack_stdio(void)
4064 int fds
[] = { fileno(stdout
), fileno(stderr
) };
4067 * noop_close is used since we don't really want to close
4068 * the stdio output fds; we merely want to stop tracking them.
4070 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
4071 fds
, 2, noop_close
, NULL
);
4077 int main(int argc
, char **argv
)
4079 int ret
= 0, retval
= 0;
4082 /* Parse arguments */
4084 if (set_options(argc
, argv
)) {
4089 if (set_signal_handler()) {
4094 ret
= fclose(stdin
);
4096 PERROR("Failed to close stdin");
4099 /* Try to create directory if -o, --output is specified. */
4100 if (opt_output_path
) {
4101 if (*opt_output_path
!= '/') {
4102 ERR("Please specify an absolute path for -o, --output PATH");
4107 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4110 ERR("Unable to create %s", opt_output_path
);
4117 if (opt_daemon
|| opt_background
) {
4118 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4127 * The RCU thread registration (and use, through the fd-tracker's
4128 * creation) is done after the daemonization to allow us to not
4129 * deal with liburcu's fork() management as the call RCU needs to
4132 rcu_register_thread();
4134 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
4135 if (!the_fd_tracker
) {
4140 ret
= track_stdio();
4146 /* Initialize thread health monitoring */
4147 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4148 if (!health_relayd
) {
4149 PERROR("health_app_create error");
4151 goto exit_health_app_create
;
4154 /* Create thread quit pipe */
4155 if (init_thread_quit_pipe()) {
4157 goto exit_init_data
;
4160 /* Setup the thread apps communication pipe. */
4161 if (create_relay_conn_pipe()) {
4163 goto exit_init_data
;
4166 /* Init relay command queue. */
4167 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4169 /* Initialize communication library */
4171 lttcomm_inet_init();
4173 /* tables of sessions indexed by session ID */
4174 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4177 goto exit_init_data
;
4180 /* tables of streams indexed by stream ID */
4181 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4182 if (!relay_streams_ht
) {
4184 goto exit_init_data
;
4187 /* tables of streams indexed by stream ID */
4188 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4189 if (!viewer_streams_ht
) {
4191 goto exit_init_data
;
4194 ret
= init_health_quit_pipe();
4197 goto exit_health_quit_pipe
;
4200 /* Create thread to manage the client socket */
4201 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4202 thread_manage_health
, (void *) NULL
);
4205 PERROR("pthread_create health");
4207 goto exit_health_thread
;
4210 /* Setup the dispatcher thread */
4211 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4212 relay_thread_dispatcher
, (void *) NULL
);
4215 PERROR("pthread_create dispatcher");
4217 goto exit_dispatcher_thread
;
4220 /* Setup the worker thread */
4221 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4222 relay_thread_worker
, NULL
);
4225 PERROR("pthread_create worker");
4227 goto exit_worker_thread
;
4230 /* Setup the listener thread */
4231 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4232 relay_thread_listener
, (void *) NULL
);
4235 PERROR("pthread_create listener");
4237 goto exit_listener_thread
;
4240 ret
= relayd_live_create(live_uri
);
4242 ERR("Starting live viewer threads");
4248 * This is where we start awaiting program completion (e.g. through
4249 * signal that asks threads to teardown).
4252 ret
= relayd_live_join();
4258 ret
= pthread_join(listener_thread
, &status
);
4261 PERROR("pthread_join listener_thread");
4265 exit_listener_thread
:
4266 ret
= pthread_join(worker_thread
, &status
);
4269 PERROR("pthread_join worker_thread");
4274 ret
= pthread_join(dispatcher_thread
, &status
);
4277 PERROR("pthread_join dispatcher_thread");
4280 exit_dispatcher_thread
:
4282 ret
= pthread_join(health_thread
, &status
);
4285 PERROR("pthread_join health_thread");
4290 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4291 exit_health_quit_pipe
:
4294 health_app_destroy(health_relayd
);
4295 exit_health_app_create
:
4298 * Wait for all pending call_rcu work to complete before tearing
4299 * down data structures. call_rcu worker may be trying to
4300 * perform lookups in those structures.
4305 /* Ensure all prior call_rcu are done. */
4310 * fd_tracker_destroy() will log the contents of the fd-tracker
4311 * if a leak is detected.
4313 fd_tracker_destroy(the_fd_tracker
);
4314 rcu_unregister_thread();