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
);
810 * Create and init socket from uri.
812 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
,
816 struct lttcomm_sock
*sock
= NULL
;
817 char uri_str
[PATH_MAX
];
818 char *formated_name
= NULL
;
820 sock
= lttcomm_alloc_sock_from_uri(uri
);
822 ERR("Allocating socket");
827 * Don't fail to create the socket if the name can't be built as it is
828 * only used for debugging purposes.
830 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
831 uri_str
[sizeof(uri_str
) - 1] = '\0';
833 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
836 formated_name
= NULL
;
840 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
841 (const char **) (formated_name
? &formated_name
: NULL
),
842 1, create_sock
, sock
);
844 DBG("Listening on %s socket %d", name
, sock
->fd
);
846 ret
= sock
->ops
->bind(sock
);
848 PERROR("Failed to bind socket");
852 ret
= sock
->ops
->listen(sock
, -1);
862 lttcomm_destroy_sock(sock
);
868 * This thread manages the listening for new connections on the network
870 static void *relay_thread_listener(void *data
)
872 int i
, ret
, pollfd
, err
= -1;
873 uint32_t revents
, nb_fd
;
874 struct lttng_poll_event events
;
875 struct lttcomm_sock
*control_sock
, *data_sock
;
877 DBG("[thread] Relay listener started");
879 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
881 health_code_update();
883 control_sock
= relay_socket_create(control_uri
, "Control listener");
885 goto error_sock_control
;
888 data_sock
= relay_socket_create(data_uri
, "Data listener");
890 goto error_sock_relay
;
894 * Pass 3 as size here for the thread quit pipe, control and
897 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
899 goto error_create_poll
;
902 /* Add the control socket */
903 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
908 /* Add the data socket */
909 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
914 lttng_relay_notify_ready();
916 if (testpoint(relayd_thread_listener
)) {
917 goto error_testpoint
;
921 health_code_update();
923 DBG("Listener accepting connections");
927 ret
= lttng_poll_wait(&events
, -1);
931 * Restart interrupted system call.
933 if (errno
== EINTR
) {
941 DBG("Relay new connection received");
942 for (i
= 0; i
< nb_fd
; i
++) {
943 health_code_update();
945 /* Fetch once the poll data */
946 revents
= LTTNG_POLL_GETEV(&events
, i
);
947 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
951 * No activity for this FD (poll
957 /* Thread quit pipe has been closed. Killing thread. */
958 ret
= check_thread_quit_pipe(pollfd
, revents
);
964 if (revents
& LPOLLIN
) {
966 * A new connection is requested, therefore a
967 * sessiond/consumerd connection is allocated in
968 * this thread, enqueued to a global queue and
969 * dequeued (and freed) in the worker thread.
972 struct relay_connection
*new_conn
;
973 struct lttcomm_sock
*newsock
;
974 enum connection_type type
;
976 if (pollfd
== data_sock
->fd
) {
978 newsock
= data_sock
->ops
->accept(data_sock
);
979 DBG("Relay data connection accepted, socket %d",
982 assert(pollfd
== control_sock
->fd
);
983 type
= RELAY_CONTROL
;
984 newsock
= control_sock
->ops
->accept(control_sock
);
985 DBG("Relay control connection accepted, socket %d",
989 PERROR("accepting sock");
993 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
996 PERROR("setsockopt inet");
997 lttcomm_destroy_sock(newsock
);
1001 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1003 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1005 lttcomm_destroy_sock(newsock
);
1009 new_conn
= connection_create(newsock
, type
);
1011 lttcomm_destroy_sock(newsock
);
1015 /* Enqueue request for the dispatcher thread. */
1016 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1020 * Wake the dispatch queue futex.
1021 * Implicit memory barrier with the
1022 * exchange in cds_wfcq_enqueue.
1024 futex_nto1_wake(&relay_conn_queue
.futex
);
1025 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1026 ERR("socket poll error");
1029 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1039 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1041 if (data_sock
->fd
>= 0) {
1042 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1043 &data_sock
->fd
, 1, close_sock
,
1049 lttcomm_destroy_sock(data_sock
);
1051 if (control_sock
->fd
>= 0) {
1052 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1053 &control_sock
->fd
, 1, close_sock
,
1059 lttcomm_destroy_sock(control_sock
);
1063 ERR("Health error occurred in %s", __func__
);
1065 health_unregister(health_relayd
);
1066 DBG("Relay listener thread cleanup complete");
1067 lttng_relay_stop_threads();
1072 * This thread manages the dispatching of the requests to worker threads
1074 static void *relay_thread_dispatcher(void *data
)
1078 struct cds_wfcq_node
*node
;
1079 struct relay_connection
*new_conn
= NULL
;
1081 DBG("[thread] Relay dispatcher started");
1083 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1085 if (testpoint(relayd_thread_dispatcher
)) {
1086 goto error_testpoint
;
1089 health_code_update();
1092 health_code_update();
1094 /* Atomically prepare the queue futex */
1095 futex_nto1_prepare(&relay_conn_queue
.futex
);
1097 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1102 health_code_update();
1104 /* Dequeue commands */
1105 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1106 &relay_conn_queue
.tail
);
1108 DBG("Woken up but nothing in the relay command queue");
1109 /* Continue thread execution */
1112 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1114 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1117 * Inform worker thread of the new request. This
1118 * call is blocking so we can be assured that
1119 * the data will be read at some point in time
1120 * or wait to the end of the world :)
1122 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1124 PERROR("write connection pipe");
1125 connection_put(new_conn
);
1128 } while (node
!= NULL
);
1130 /* Futex wait on queue. Blocking call on futex() */
1131 health_poll_entry();
1132 futex_nto1_wait(&relay_conn_queue
.futex
);
1136 /* Normal exit, no error */
1143 ERR("Health error occurred in %s", __func__
);
1145 health_unregister(health_relayd
);
1146 DBG("Dispatch thread dying");
1147 lttng_relay_stop_threads();
1152 * Set index data from the control port to a given index object.
1154 static int set_index_control_data(struct relay_index
*index
,
1155 struct lttcomm_relayd_index
*data
,
1156 struct relay_connection
*conn
)
1158 struct ctf_packet_index index_data
;
1161 * The index on disk is encoded in big endian.
1163 index_data
.packet_size
= htobe64(data
->packet_size
);
1164 index_data
.content_size
= htobe64(data
->content_size
);
1165 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1166 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1167 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1168 index_data
.stream_id
= htobe64(data
->stream_id
);
1170 if (conn
->minor
>= 8) {
1171 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1172 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1175 return relay_index_set_data(index
, &index_data
);
1179 * Handle the RELAYD_CREATE_SESSION command.
1181 * On success, send back the session id or else return a negative value.
1183 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1184 struct relay_connection
*conn
,
1185 const struct lttng_buffer_view
*payload
)
1189 struct relay_session
*session
;
1190 struct lttcomm_relayd_status_session reply
;
1191 char session_name
[LTTNG_NAME_MAX
];
1192 char hostname
[LTTNG_HOST_NAME_MAX
];
1193 uint32_t live_timer
= 0;
1194 bool snapshot
= false;
1196 memset(session_name
, 0, LTTNG_NAME_MAX
);
1197 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1199 memset(&reply
, 0, sizeof(reply
));
1201 if (conn
->minor
< 4) {
1202 /* From 2.1 to 2.3 */
1204 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1205 /* From 2.4 to 2.10 */
1206 ret
= cmd_create_session_2_4(payload
, session_name
,
1207 hostname
, &live_timer
, &snapshot
);
1209 /* From 2.11 to ... */
1210 ret
= cmd_create_session_2_11(payload
, session_name
,
1211 hostname
, &live_timer
, &snapshot
);
1218 session
= session_create(session_name
, hostname
, live_timer
,
1219 snapshot
, conn
->major
, conn
->minor
);
1224 assert(!conn
->session
);
1225 conn
->session
= session
;
1226 DBG("Created session %" PRIu64
, session
->id
);
1228 reply
.session_id
= htobe64(session
->id
);
1232 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1234 reply
.ret_code
= htobe32(LTTNG_OK
);
1237 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1238 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1239 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1248 * When we have received all the streams and the metadata for a channel,
1249 * we make them visible to the viewer threads.
1251 static void publish_connection_local_streams(struct relay_connection
*conn
)
1253 struct relay_stream
*stream
;
1254 struct relay_session
*session
= conn
->session
;
1257 * We publish all streams belonging to a session atomically wrt
1260 pthread_mutex_lock(&session
->lock
);
1262 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1264 stream_publish(stream
);
1269 * Inform the viewer that there are new streams in the session.
1271 if (session
->viewer_attached
) {
1272 uatomic_set(&session
->new_streams
, 1);
1274 pthread_mutex_unlock(&session
->lock
);
1278 * relay_add_stream: allocate a new stream for a session
1280 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1281 struct relay_connection
*conn
,
1282 const struct lttng_buffer_view
*payload
)
1286 struct relay_session
*session
= conn
->session
;
1287 struct relay_stream
*stream
= NULL
;
1288 struct lttcomm_relayd_status_stream reply
;
1289 struct ctf_trace
*trace
= NULL
;
1290 uint64_t stream_handle
= -1ULL;
1291 char *path_name
= NULL
, *channel_name
= NULL
;
1292 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1293 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1295 if (!session
|| !conn
->version_check_done
) {
1296 ERR("Trying to add a stream before version check");
1298 goto end_no_session
;
1301 if (session
->minor
== 1) {
1303 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1305 } else if (session
->minor
> 1 && session
->minor
< 11) {
1306 /* From 2.2 to 2.10 */
1307 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1308 &channel_name
, &tracefile_size
, &tracefile_count
);
1310 /* From 2.11 to ... */
1311 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1312 &channel_name
, &tracefile_size
, &tracefile_count
,
1313 &stream_chunk_id
.value
);
1314 stream_chunk_id
.is_set
= true;
1321 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1325 /* This stream here has one reference on the trace. */
1327 pthread_mutex_lock(&last_relay_stream_id_lock
);
1328 stream_handle
= ++last_relay_stream_id
;
1329 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1331 /* We pass ownership of path_name and channel_name. */
1332 stream
= stream_create(trace
, stream_handle
, path_name
,
1333 channel_name
, tracefile_size
, tracefile_count
,
1336 channel_name
= NULL
;
1339 * Streams are the owners of their trace. Reference to trace is
1340 * kept within stream_create().
1342 ctf_trace_put(trace
);
1345 memset(&reply
, 0, sizeof(reply
));
1346 reply
.handle
= htobe64(stream_handle
);
1348 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1350 reply
.ret_code
= htobe32(LTTNG_OK
);
1353 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1354 sizeof(struct lttcomm_relayd_status_stream
), 0);
1355 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1356 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1368 * relay_close_stream: close a specific stream
1370 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1371 struct relay_connection
*conn
,
1372 const struct lttng_buffer_view
*payload
)
1376 struct relay_session
*session
= conn
->session
;
1377 struct lttcomm_relayd_close_stream stream_info
;
1378 struct lttcomm_relayd_generic_reply reply
;
1379 struct relay_stream
*stream
;
1381 DBG("Close stream received");
1383 if (!session
|| !conn
->version_check_done
) {
1384 ERR("Trying to close a stream before version check");
1386 goto end_no_session
;
1389 if (payload
->size
< sizeof(stream_info
)) {
1390 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1391 sizeof(stream_info
), payload
->size
);
1393 goto end_no_session
;
1395 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1396 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1397 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1399 stream
= stream_get_by_id(stream_info
.stream_id
);
1406 * Set last_net_seq_num before the close flag. Required by data
1409 pthread_mutex_lock(&stream
->lock
);
1410 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1411 pthread_mutex_unlock(&stream
->lock
);
1414 * This is one of the conditions which may trigger a stream close
1415 * with the others being:
1416 * 1) A close command is received for a stream
1417 * 2) The control connection owning the stream is closed
1418 * 3) We have received all of the stream's data _after_ a close
1421 try_stream_close(stream
);
1422 if (stream
->is_metadata
) {
1423 struct relay_viewer_stream
*vstream
;
1425 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1427 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1429 * Since all the metadata has been sent to the
1430 * viewer and that we have a request to close
1431 * its stream, we can safely teardown the
1432 * corresponding metadata viewer stream.
1434 viewer_stream_put(vstream
);
1436 /* Put local reference. */
1437 viewer_stream_put(vstream
);
1444 memset(&reply
, 0, sizeof(reply
));
1446 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1448 reply
.ret_code
= htobe32(LTTNG_OK
);
1450 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1451 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1452 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1453 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1463 * relay_reset_metadata: reset a metadata stream
1466 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1467 struct relay_connection
*conn
,
1468 const struct lttng_buffer_view
*payload
)
1472 struct relay_session
*session
= conn
->session
;
1473 struct lttcomm_relayd_reset_metadata stream_info
;
1474 struct lttcomm_relayd_generic_reply reply
;
1475 struct relay_stream
*stream
;
1477 DBG("Reset metadata received");
1479 if (!session
|| !conn
->version_check_done
) {
1480 ERR("Trying to reset a metadata stream before version check");
1482 goto end_no_session
;
1485 if (payload
->size
< sizeof(stream_info
)) {
1486 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1487 sizeof(stream_info
), payload
->size
);
1489 goto end_no_session
;
1491 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1492 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1493 stream_info
.version
= be64toh(stream_info
.version
);
1495 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1497 /* Unsupported for live sessions for now. */
1498 if (session
->live_timer
!= 0) {
1503 stream
= stream_get_by_id(stream_info
.stream_id
);
1508 pthread_mutex_lock(&stream
->lock
);
1509 if (!stream
->is_metadata
) {
1514 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1515 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1516 &stream
->stream_fd
->fd
);
1518 ERR("Failed to rotate metadata file %s of channel %s",
1519 stream
->path_name
, stream
->channel_name
);
1524 pthread_mutex_unlock(&stream
->lock
);
1528 memset(&reply
, 0, sizeof(reply
));
1530 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1532 reply
.ret_code
= htobe32(LTTNG_OK
);
1534 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1535 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1536 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1537 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1547 * relay_unknown_command: send -1 if received unknown command
1549 static void relay_unknown_command(struct relay_connection
*conn
)
1551 struct lttcomm_relayd_generic_reply reply
;
1554 memset(&reply
, 0, sizeof(reply
));
1555 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1556 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1557 if (send_ret
< sizeof(reply
)) {
1558 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1563 * relay_start: send an acknowledgment to the client to tell if we are
1564 * ready to receive data. We are ready if a session is established.
1566 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1567 struct relay_connection
*conn
,
1568 const struct lttng_buffer_view
*payload
)
1572 struct lttcomm_relayd_generic_reply reply
;
1573 struct relay_session
*session
= conn
->session
;
1576 DBG("Trying to start the streaming without a session established");
1577 ret
= htobe32(LTTNG_ERR_UNK
);
1580 memset(&reply
, 0, sizeof(reply
));
1581 reply
.ret_code
= htobe32(LTTNG_OK
);
1582 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1584 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1585 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1594 * Append padding to the file pointed by the file descriptor fd.
1596 static int write_padding_to_file(int fd
, uint32_t size
)
1605 zeros
= zmalloc(size
);
1606 if (zeros
== NULL
) {
1607 PERROR("zmalloc zeros for padding");
1612 ret
= lttng_write(fd
, zeros
, size
);
1614 PERROR("write padding to file");
1624 * Close the current index file if it is open, and create a new one.
1626 * Return 0 on success, -1 on error.
1629 int create_rotate_index_file(struct relay_stream
*stream
)
1632 uint32_t major
, minor
;
1634 /* Put ref on previous index_file. */
1635 if (stream
->index_file
) {
1636 lttng_index_file_put(stream
->index_file
);
1637 stream
->index_file
= NULL
;
1639 major
= stream
->trace
->session
->major
;
1640 minor
= stream
->trace
->session
->minor
;
1641 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
1642 stream
->channel_name
,
1643 -1, -1, stream
->tracefile_size
,
1644 tracefile_array_get_file_index_head(stream
->tfa
),
1645 lttng_to_index_major(major
, minor
),
1646 lttng_to_index_minor(major
, minor
));
1647 if (!stream
->index_file
) {
1659 int do_rotate_stream(struct relay_stream
*stream
)
1663 /* Perform the stream rotation. */
1664 ret
= utils_rotate_stream_file(stream
->path_name
,
1665 stream
->channel_name
, stream
->tracefile_size
,
1666 stream
->tracefile_count
, -1,
1667 -1, stream
->stream_fd
->fd
,
1668 NULL
, &stream
->stream_fd
->fd
);
1670 ERR("Rotating stream output file");
1673 stream
->tracefile_size_current
= 0;
1675 /* Rotate also the index if the stream is not a metadata stream. */
1676 if (!stream
->is_metadata
) {
1677 ret
= create_rotate_index_file(stream
);
1679 ERR("Failed to rotate index file");
1684 stream
->rotate_at_seq_num
= -1ULL;
1685 stream
->pos_after_last_complete_data_index
= 0;
1692 * If too much data has been written in a tracefile before we received the
1693 * rotation command, we have to move the excess data to the new tracefile and
1694 * perform the rotation. This can happen because the control and data
1695 * connections are separate, the indexes as well as the commands arrive from
1696 * the control connection and we have no control over the order so we could be
1697 * in a situation where too much data has been received on the data connection
1698 * before the rotation command on the control connection arrives. We don't need
1699 * to update the index because its order is guaranteed with the rotation
1703 int rotate_truncate_stream(struct relay_stream
*stream
)
1707 uint64_t diff
, pos
= 0;
1708 char buf
[FILE_COPY_BUFFER_SIZE
];
1710 assert(!stream
->is_metadata
);
1712 assert(stream
->tracefile_size_current
>
1713 stream
->pos_after_last_complete_data_index
);
1714 diff
= stream
->tracefile_size_current
-
1715 stream
->pos_after_last_complete_data_index
;
1717 /* Create the new tracefile. */
1718 new_fd
= utils_create_stream_file(stream
->path_name
,
1719 stream
->channel_name
,
1720 stream
->tracefile_size
, stream
->tracefile_count
,
1721 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1723 ERR("Failed to create new stream file at path %s for channel %s",
1724 stream
->path_name
, stream
->channel_name
);
1730 * Rewind the current tracefile to the position at which the rotation
1731 * should have occured.
1733 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1734 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1735 if (lseek_ret
< 0) {
1736 PERROR("seek truncate stream");
1741 /* Move data from the old file to the new file. */
1742 while (pos
< diff
) {
1743 uint64_t count
, bytes_left
;
1746 bytes_left
= diff
- pos
;
1747 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1748 assert(count
<= SIZE_MAX
);
1750 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1751 if (io_ret
< (ssize_t
) count
) {
1752 char error_string
[256];
1754 snprintf(error_string
, sizeof(error_string
),
1755 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1756 count
, stream
->stream_fd
->fd
, io_ret
);
1758 PERROR("%s", error_string
);
1760 ERR("%s", error_string
);
1766 io_ret
= lttng_write(new_fd
, buf
, count
);
1767 if (io_ret
< (ssize_t
) count
) {
1768 char error_string
[256];
1770 snprintf(error_string
, sizeof(error_string
),
1771 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1772 count
, new_fd
, io_ret
);
1774 PERROR("%s", error_string
);
1776 ERR("%s", error_string
);
1785 /* Truncate the file to get rid of the excess data. */
1786 ret
= ftruncate(stream
->stream_fd
->fd
,
1787 stream
->pos_after_last_complete_data_index
);
1789 PERROR("ftruncate");
1793 ret
= close(stream
->stream_fd
->fd
);
1795 PERROR("Closing tracefile");
1799 ret
= create_rotate_index_file(stream
);
1801 ERR("Rotate stream index file");
1806 * Update the offset and FD of all the eventual indexes created by the
1807 * data connection before the rotation command arrived.
1809 ret
= relay_index_switch_all_files(stream
);
1811 ERR("Failed to rotate index file");
1815 stream
->stream_fd
->fd
= new_fd
;
1816 stream
->tracefile_size_current
= diff
;
1817 stream
->pos_after_last_complete_data_index
= 0;
1818 stream
->rotate_at_seq_num
= -1ULL;
1827 * Check if a stream should perform a rotation (for session rotation).
1828 * Must be called with the stream lock held.
1830 * Return 0 on success, a negative value on error.
1833 int try_rotate_stream(struct relay_stream
*stream
)
1837 /* No rotation expected. */
1838 if (stream
->rotate_at_seq_num
== -1ULL) {
1842 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1843 stream
->prev_seq
== -1ULL) {
1844 DBG("Stream %" PRIu64
" no yet ready for rotation",
1845 stream
->stream_handle
);
1847 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1848 DBG("Rotation after too much data has been written in tracefile "
1849 "for stream %" PRIu64
", need to truncate before "
1850 "rotating", stream
->stream_handle
);
1851 ret
= rotate_truncate_stream(stream
);
1853 ERR("Failed to truncate stream");
1857 /* stream->prev_seq == stream->rotate_at_seq_num */
1858 DBG("Stream %" PRIu64
" ready for rotation",
1859 stream
->stream_handle
);
1860 ret
= do_rotate_stream(stream
);
1868 * relay_recv_metadata: receive the metadata for the session.
1870 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1871 struct relay_connection
*conn
,
1872 const struct lttng_buffer_view
*payload
)
1876 struct relay_session
*session
= conn
->session
;
1877 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1878 struct relay_stream
*metadata_stream
;
1879 uint64_t metadata_payload_size
;
1882 ERR("Metadata sent before version check");
1887 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1888 ERR("Incorrect data size");
1892 metadata_payload_size
= recv_hdr
->data_size
-
1893 sizeof(struct lttcomm_relayd_metadata_payload
);
1895 memcpy(&metadata_payload_header
, payload
->data
,
1896 sizeof(metadata_payload_header
));
1897 metadata_payload_header
.stream_id
= be64toh(
1898 metadata_payload_header
.stream_id
);
1899 metadata_payload_header
.padding_size
= be32toh(
1900 metadata_payload_header
.padding_size
);
1902 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1903 if (!metadata_stream
) {
1908 pthread_mutex_lock(&metadata_stream
->lock
);
1910 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1911 payload
->data
+ sizeof(metadata_payload_header
),
1912 metadata_payload_size
);
1913 if (size_ret
< metadata_payload_size
) {
1914 ERR("Relay error writing metadata on file");
1919 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1920 metadata_payload_header
.padding_size
);
1921 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1926 metadata_stream
->metadata_received
+=
1927 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1928 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1929 metadata_stream
->metadata_received
);
1931 ret
= try_rotate_stream(metadata_stream
);
1937 pthread_mutex_unlock(&metadata_stream
->lock
);
1938 stream_put(metadata_stream
);
1944 * relay_send_version: send relayd version number
1946 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1947 struct relay_connection
*conn
,
1948 const struct lttng_buffer_view
*payload
)
1952 struct lttcomm_relayd_version reply
, msg
;
1953 bool compatible
= true;
1955 conn
->version_check_done
= true;
1957 /* Get version from the other side. */
1958 if (payload
->size
< sizeof(msg
)) {
1959 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1960 sizeof(msg
), payload
->size
);
1965 memcpy(&msg
, payload
->data
, sizeof(msg
));
1966 msg
.major
= be32toh(msg
.major
);
1967 msg
.minor
= be32toh(msg
.minor
);
1969 memset(&reply
, 0, sizeof(reply
));
1970 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1971 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1973 /* Major versions must be the same */
1974 if (reply
.major
!= msg
.major
) {
1975 DBG("Incompatible major versions (%u vs %u), deleting session",
1976 reply
.major
, msg
.major
);
1980 conn
->major
= reply
.major
;
1981 /* We adapt to the lowest compatible version */
1982 if (reply
.minor
<= msg
.minor
) {
1983 conn
->minor
= reply
.minor
;
1985 conn
->minor
= msg
.minor
;
1988 reply
.major
= htobe32(reply
.major
);
1989 reply
.minor
= htobe32(reply
.minor
);
1990 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1992 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1993 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2006 DBG("Version check done using protocol %u.%u", conn
->major
,
2014 * Check for data pending for a given stream id from the session daemon.
2016 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2017 struct relay_connection
*conn
,
2018 const struct lttng_buffer_view
*payload
)
2020 struct relay_session
*session
= conn
->session
;
2021 struct lttcomm_relayd_data_pending msg
;
2022 struct lttcomm_relayd_generic_reply reply
;
2023 struct relay_stream
*stream
;
2027 DBG("Data pending command received");
2029 if (!session
|| !conn
->version_check_done
) {
2030 ERR("Trying to check for data before version check");
2032 goto end_no_session
;
2035 if (payload
->size
< sizeof(msg
)) {
2036 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2037 sizeof(msg
), payload
->size
);
2039 goto end_no_session
;
2041 memcpy(&msg
, payload
->data
, sizeof(msg
));
2042 msg
.stream_id
= be64toh(msg
.stream_id
);
2043 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2045 stream
= stream_get_by_id(msg
.stream_id
);
2046 if (stream
== NULL
) {
2051 pthread_mutex_lock(&stream
->lock
);
2053 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2054 " and last_seq %" PRIu64
, msg
.stream_id
,
2055 stream
->prev_seq
, msg
.last_net_seq_num
);
2057 /* Avoid wrapping issue */
2058 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2059 /* Data has in fact been written and is NOT pending */
2062 /* Data still being streamed thus pending */
2066 stream
->data_pending_check_done
= true;
2067 pthread_mutex_unlock(&stream
->lock
);
2072 memset(&reply
, 0, sizeof(reply
));
2073 reply
.ret_code
= htobe32(ret
);
2074 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2075 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2076 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2086 * Wait for the control socket to reach a quiescent state.
2088 * Note that for now, when receiving this command from the session
2089 * daemon, this means that every subsequent commands or data received on
2090 * the control socket has been handled. So, this is why we simply return
2093 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2094 struct relay_connection
*conn
,
2095 const struct lttng_buffer_view
*payload
)
2099 struct relay_stream
*stream
;
2100 struct lttcomm_relayd_quiescent_control msg
;
2101 struct lttcomm_relayd_generic_reply reply
;
2103 DBG("Checking quiescent state on control socket");
2105 if (!conn
->session
|| !conn
->version_check_done
) {
2106 ERR("Trying to check for data before version check");
2108 goto end_no_session
;
2111 if (payload
->size
< sizeof(msg
)) {
2112 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2113 sizeof(msg
), payload
->size
);
2115 goto end_no_session
;
2117 memcpy(&msg
, payload
->data
, sizeof(msg
));
2118 msg
.stream_id
= be64toh(msg
.stream_id
);
2120 stream
= stream_get_by_id(msg
.stream_id
);
2124 pthread_mutex_lock(&stream
->lock
);
2125 stream
->data_pending_check_done
= true;
2126 pthread_mutex_unlock(&stream
->lock
);
2128 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2131 memset(&reply
, 0, sizeof(reply
));
2132 reply
.ret_code
= htobe32(LTTNG_OK
);
2133 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2134 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2135 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2147 * Initialize a data pending command. This means that a consumer is about
2148 * to ask for data pending for each stream it holds. Simply iterate over
2149 * all streams of a session and set the data_pending_check_done flag.
2151 * This command returns to the client a LTTNG_OK code.
2153 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2154 struct relay_connection
*conn
,
2155 const struct lttng_buffer_view
*payload
)
2159 struct lttng_ht_iter iter
;
2160 struct lttcomm_relayd_begin_data_pending msg
;
2161 struct lttcomm_relayd_generic_reply reply
;
2162 struct relay_stream
*stream
;
2167 DBG("Init streams for data pending");
2169 if (!conn
->session
|| !conn
->version_check_done
) {
2170 ERR("Trying to check for data before version check");
2172 goto end_no_session
;
2175 if (payload
->size
< sizeof(msg
)) {
2176 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2177 sizeof(msg
), payload
->size
);
2179 goto end_no_session
;
2181 memcpy(&msg
, payload
->data
, sizeof(msg
));
2182 msg
.session_id
= be64toh(msg
.session_id
);
2185 * Iterate over all streams to set the begin data pending flag.
2186 * For now, the streams are indexed by stream handle so we have
2187 * to iterate over all streams to find the one associated with
2188 * the right session_id.
2191 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2193 if (!stream_get(stream
)) {
2196 if (stream
->trace
->session
->id
== msg
.session_id
) {
2197 pthread_mutex_lock(&stream
->lock
);
2198 stream
->data_pending_check_done
= false;
2199 pthread_mutex_unlock(&stream
->lock
);
2200 DBG("Set begin data pending flag to stream %" PRIu64
,
2201 stream
->stream_handle
);
2207 memset(&reply
, 0, sizeof(reply
));
2208 /* All good, send back reply. */
2209 reply
.ret_code
= htobe32(LTTNG_OK
);
2211 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2212 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2213 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2225 * End data pending command. This will check, for a given session id, if
2226 * each stream associated with it has its data_pending_check_done flag
2227 * set. If not, this means that the client lost track of the stream but
2228 * the data is still being streamed on our side. In this case, we inform
2229 * the client that data is in flight.
2231 * Return to the client if there is data in flight or not with a ret_code.
2233 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2234 struct relay_connection
*conn
,
2235 const struct lttng_buffer_view
*payload
)
2239 struct lttng_ht_iter iter
;
2240 struct lttcomm_relayd_end_data_pending msg
;
2241 struct lttcomm_relayd_generic_reply reply
;
2242 struct relay_stream
*stream
;
2243 uint32_t is_data_inflight
= 0;
2245 DBG("End data pending command");
2247 if (!conn
->session
|| !conn
->version_check_done
) {
2248 ERR("Trying to check for data before version check");
2250 goto end_no_session
;
2253 if (payload
->size
< sizeof(msg
)) {
2254 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2255 sizeof(msg
), payload
->size
);
2257 goto end_no_session
;
2259 memcpy(&msg
, payload
->data
, sizeof(msg
));
2260 msg
.session_id
= be64toh(msg
.session_id
);
2263 * Iterate over all streams to see if the begin data pending
2267 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2269 if (!stream_get(stream
)) {
2272 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2276 pthread_mutex_lock(&stream
->lock
);
2277 if (!stream
->data_pending_check_done
) {
2278 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2279 is_data_inflight
= 1;
2280 DBG("Data is still in flight for stream %" PRIu64
,
2281 stream
->stream_handle
);
2282 pthread_mutex_unlock(&stream
->lock
);
2287 pthread_mutex_unlock(&stream
->lock
);
2292 memset(&reply
, 0, sizeof(reply
));
2293 /* All good, send back reply. */
2294 reply
.ret_code
= htobe32(is_data_inflight
);
2296 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2297 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2298 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2310 * Receive an index for a specific stream.
2312 * Return 0 on success else a negative value.
2314 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2315 struct relay_connection
*conn
,
2316 const struct lttng_buffer_view
*payload
)
2320 struct relay_session
*session
= conn
->session
;
2321 struct lttcomm_relayd_index index_info
;
2322 struct relay_index
*index
;
2323 struct lttcomm_relayd_generic_reply reply
;
2324 struct relay_stream
*stream
;
2329 DBG("Relay receiving index");
2331 if (!session
|| !conn
->version_check_done
) {
2332 ERR("Trying to close a stream before version check");
2334 goto end_no_session
;
2337 msg_len
= lttcomm_relayd_index_len(
2338 lttng_to_index_major(conn
->major
, conn
->minor
),
2339 lttng_to_index_minor(conn
->major
, conn
->minor
));
2340 if (payload
->size
< msg_len
) {
2341 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2342 msg_len
, payload
->size
);
2344 goto end_no_session
;
2346 memcpy(&index_info
, payload
->data
, msg_len
);
2347 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2348 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2349 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2350 index_info
.content_size
= be64toh(index_info
.content_size
);
2351 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2352 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2353 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2354 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2356 if (conn
->minor
>= 8) {
2357 index_info
.stream_instance_id
=
2358 be64toh(index_info
.stream_instance_id
);
2359 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2362 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2364 ERR("stream_get_by_id not found");
2368 pthread_mutex_lock(&stream
->lock
);
2370 /* Live beacon handling */
2371 if (index_info
.packet_size
== 0) {
2372 DBG("Received live beacon for stream %" PRIu64
,
2373 stream
->stream_handle
);
2376 * Only flag a stream inactive when it has already
2377 * received data and no indexes are in flight.
2379 if (stream
->index_received_seqcount
> 0
2380 && stream
->indexes_in_flight
== 0) {
2381 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2384 goto end_stream_put
;
2386 stream
->beacon_ts_end
= -1ULL;
2389 if (stream
->ctf_stream_id
== -1ULL) {
2390 stream
->ctf_stream_id
= index_info
.stream_id
;
2392 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2395 ERR("relay_index_get_by_id_or_create index NULL");
2396 goto end_stream_put
;
2398 if (set_index_control_data(index
, &index_info
, conn
)) {
2399 ERR("set_index_control_data error");
2400 relay_index_put(index
);
2402 goto end_stream_put
;
2404 ret
= relay_index_try_flush(index
);
2406 tracefile_array_commit_seq(stream
->tfa
);
2407 stream
->index_received_seqcount
++;
2408 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2409 } else if (ret
> 0) {
2413 ERR("relay_index_try_flush error %d", ret
);
2414 relay_index_put(index
);
2419 pthread_mutex_unlock(&stream
->lock
);
2424 memset(&reply
, 0, sizeof(reply
));
2426 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2428 reply
.ret_code
= htobe32(LTTNG_OK
);
2430 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2431 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2432 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2441 * Receive the streams_sent message.
2443 * Return 0 on success else a negative value.
2445 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2446 struct relay_connection
*conn
,
2447 const struct lttng_buffer_view
*payload
)
2451 struct lttcomm_relayd_generic_reply reply
;
2455 DBG("Relay receiving streams_sent");
2457 if (!conn
->session
|| !conn
->version_check_done
) {
2458 ERR("Trying to close a stream before version check");
2460 goto end_no_session
;
2464 * Publish every pending stream in the connection recv list which are
2465 * now ready to be used by the viewer.
2467 publish_connection_local_streams(conn
);
2469 memset(&reply
, 0, sizeof(reply
));
2470 reply
.ret_code
= htobe32(LTTNG_OK
);
2471 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2472 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2473 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2486 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2487 * rotation feature (not the tracefile rotation feature).
2489 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2490 struct relay_connection
*conn
,
2491 const struct lttng_buffer_view
*payload
)
2495 struct relay_session
*session
= conn
->session
;
2496 struct lttcomm_relayd_rotate_stream stream_info
;
2497 struct lttcomm_relayd_generic_reply reply
;
2498 struct relay_stream
*stream
;
2501 struct lttng_buffer_view new_path_view
;
2503 DBG("Rotate stream received");
2505 if (!session
|| !conn
->version_check_done
) {
2506 ERR("Trying to rotate a stream before version check");
2511 if (session
->major
== 2 && session
->minor
< 11) {
2512 ERR("Unsupported feature before 2.11");
2517 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2519 if (payload
->size
< header_len
) {
2520 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2521 header_len
, payload
->size
);
2526 memcpy(&stream_info
, payload
->data
, header_len
);
2528 /* Convert to host */
2529 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2530 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2531 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2532 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2534 path_len
= stream_info
.pathname_length
;
2535 if (payload
->size
< header_len
+ path_len
) {
2536 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2537 header_len
+ path_len
, payload
->size
);
2542 /* Ensure it fits in local filename length. */
2543 if (path_len
>= LTTNG_PATH_MAX
) {
2544 ret
= -ENAMETOOLONG
;
2545 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2546 path_len
, LTTNG_PATH_MAX
);
2550 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2551 stream_info
.pathname_length
);
2553 stream
= stream_get_by_id(stream_info
.stream_id
);
2559 pthread_mutex_lock(&stream
->lock
);
2562 * Update the trace path (just the folder, the stream name does not
2565 free(stream
->path_name
);
2566 stream
->path_name
= create_output_path(new_path_view
.data
);
2567 if (!stream
->path_name
) {
2568 ERR("Failed to create a new output path");
2570 goto end_stream_unlock
;
2572 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2575 ERR("relay creating output directory");
2577 goto end_stream_unlock
;
2580 assert(stream
->current_chunk_id
.is_set
);
2581 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2583 if (stream
->is_metadata
) {
2585 * The metadata stream is sent only over the control connection
2586 * so we know we have all the data to perform the stream
2589 ret
= do_rotate_stream(stream
);
2591 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2592 ret
= try_rotate_stream(stream
);
2595 goto end_stream_unlock
;
2599 pthread_mutex_unlock(&stream
->lock
);
2602 memset(&reply
, 0, sizeof(reply
));
2604 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2606 reply
.ret_code
= htobe32(LTTNG_OK
);
2608 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2609 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2610 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2611 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2621 * relay_mkdir: Create a folder on the disk.
2623 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2624 struct relay_connection
*conn
,
2625 const struct lttng_buffer_view
*payload
)
2628 struct relay_session
*session
= conn
->session
;
2629 struct lttcomm_relayd_mkdir path_info_header
;
2630 struct lttcomm_relayd_generic_reply reply
;
2634 struct lttng_buffer_view path_view
;
2636 if (!session
|| !conn
->version_check_done
) {
2637 ERR("Trying to create a directory before version check");
2639 goto end_no_session
;
2642 if (session
->major
== 2 && session
->minor
< 11) {
2644 * This client is not supposed to use this command since
2645 * it predates its introduction.
2647 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2649 goto end_no_session
;
2652 header_len
= sizeof(path_info_header
);
2653 if (payload
->size
< header_len
) {
2654 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2655 header_len
, payload
->size
);
2657 goto end_no_session
;
2660 memcpy(&path_info_header
, payload
->data
, header_len
);
2662 path_info_header
.length
= be32toh(path_info_header
.length
);
2664 if (payload
->size
< header_len
+ path_info_header
.length
) {
2665 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2666 header_len
+ path_info_header
.length
, payload
->size
);
2668 goto end_no_session
;
2671 /* Ensure that it fits in local path length. */
2672 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2673 ret
= -ENAMETOOLONG
;
2674 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2675 path_info_header
.length
, LTTNG_PATH_MAX
);
2679 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2680 path_info_header
.length
);
2682 path
= create_output_path(path_view
.data
);
2684 ERR("Failed to create output path");
2689 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2691 ERR("relay creating output directory");
2698 memset(&reply
, 0, sizeof(reply
));
2700 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2702 reply
.ret_code
= htobe32(LTTNG_OK
);
2704 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2705 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2706 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2715 static int validate_rotate_rename_path_length(const char *path_type
,
2716 uint32_t path_length
)
2720 if (path_length
> LTTNG_PATH_MAX
) {
2721 ret
= -ENAMETOOLONG
;
2722 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2723 path_type
, path_length
, LTTNG_PATH_MAX
);
2724 } else if (path_length
== 0) {
2726 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2732 * relay_rotate_rename: rename the trace folder after a rotation is
2733 * completed. We are not closing any fd here, just moving the folder, so it
2734 * works even if data is still in-flight.
2736 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2737 struct relay_connection
*conn
,
2738 const struct lttng_buffer_view
*payload
)
2742 struct relay_session
*session
= conn
->session
;
2743 struct lttcomm_relayd_generic_reply reply
;
2744 struct lttcomm_relayd_rotate_rename header
;
2746 size_t received_paths_size
;
2747 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2748 struct lttng_buffer_view old_path_view
;
2749 struct lttng_buffer_view new_path_view
;
2751 if (!session
|| !conn
->version_check_done
) {
2752 ERR("Trying to rename a trace folder before version check");
2757 if (session
->major
== 2 && session
->minor
< 11) {
2758 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2763 header_len
= sizeof(header
);
2764 if (payload
->size
< header_len
) {
2765 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2766 header_len
, payload
->size
);
2771 memcpy(&header
, payload
->data
, header_len
);
2773 header
.old_path_length
= be32toh(header
.old_path_length
);
2774 header
.new_path_length
= be32toh(header
.new_path_length
);
2775 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2777 if (payload
->size
< header_len
+ received_paths_size
) {
2778 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2779 header_len
, payload
->size
);
2784 /* Ensure the paths don't exceed their allowed size. */
2785 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2789 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2794 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2795 header
.old_path_length
);
2796 new_path_view
= lttng_buffer_view_from_view(payload
,
2797 header_len
+ header
.old_path_length
,
2798 header
.new_path_length
);
2800 /* Validate that both paths received are NULL terminated. */
2801 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2802 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2806 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2807 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2812 complete_old_path
= create_output_path(old_path_view
.data
);
2813 if (!complete_old_path
) {
2814 ERR("Failed to build old output path in rotate_rename command");
2819 complete_new_path
= create_output_path(new_path_view
.data
);
2820 if (!complete_new_path
) {
2821 ERR("Failed to build new output path in rotate_rename command");
2826 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2829 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2835 * If a domain has not yet created its channel, the domain-specific
2836 * folder might not exist, but this is not an error.
2838 ret
= rename(complete_old_path
, complete_new_path
);
2839 if (ret
< 0 && errno
!= ENOENT
) {
2840 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2841 complete_old_path
, complete_new_path
);
2847 memset(&reply
, 0, sizeof(reply
));
2849 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2851 reply
.ret_code
= htobe32(LTTNG_OK
);
2853 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2855 if (send_ret
< sizeof(reply
)) {
2856 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2862 free(complete_old_path
);
2863 free(complete_new_path
);
2868 * Check if all the streams in the session have completed the last rotation.
2869 * The chunk_id value is used to distinguish the cases where a stream was
2870 * closed on the consumerd before the rotation started but it still active on
2871 * the relayd, and the case where a stream appeared on the consumerd/relayd
2872 * after the last rotation started (in that case, it is already writing in the
2873 * new chunk folder).
2876 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2877 struct relay_connection
*conn
,
2878 const struct lttng_buffer_view
*payload
)
2880 struct relay_session
*session
= conn
->session
;
2881 struct lttcomm_relayd_rotate_pending msg
;
2882 struct lttcomm_relayd_rotate_pending_reply reply
;
2883 struct lttng_ht_iter iter
;
2884 struct relay_stream
*stream
;
2888 bool rotate_pending
= false;
2890 DBG("Rotate pending command received");
2892 if (!session
|| !conn
->version_check_done
) {
2893 ERR("Trying to check for data before version check");
2898 if (session
->major
== 2 && session
->minor
< 11) {
2899 ERR("Unsupported feature before 2.11");
2904 if (payload
->size
< sizeof(msg
)) {
2905 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2906 sizeof(msg
), payload
->size
);
2911 memcpy(&msg
, payload
->data
, sizeof(msg
));
2913 chunk_id
= be64toh(msg
.chunk_id
);
2915 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2916 session
->session_name
, chunk_id
);
2919 * Iterate over all the streams in the session and check if they are
2920 * still waiting for data to perform their rotation.
2923 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2925 if (!stream_get(stream
)) {
2928 if (stream
->trace
->session
!= session
) {
2932 pthread_mutex_lock(&stream
->lock
);
2933 if (stream
->rotate_at_seq_num
!= -1ULL) {
2934 /* We have not yet performed the rotation. */
2935 rotate_pending
= true;
2936 DBG("Stream %" PRIu64
" is still rotating",
2937 stream
->stream_handle
);
2938 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
2940 * Stream closed on the consumer but still active on the
2943 rotate_pending
= true;
2944 DBG("Stream %" PRIu64
" did not exist on the consumer "
2945 "when the last rotation started, but is"
2946 "still waiting for data before getting"
2948 stream
->stream_handle
);
2950 pthread_mutex_unlock(&stream
->lock
);
2952 if (rotate_pending
) {
2959 memset(&reply
, 0, sizeof(reply
));
2960 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
2961 reply
.is_pending
= (uint8_t) !!rotate_pending
;
2962 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2964 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2965 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
2974 #define DBG_CMD(cmd_name, conn) \
2975 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2977 static int relay_process_control_command(struct relay_connection
*conn
,
2978 const struct lttcomm_relayd_hdr
*header
,
2979 const struct lttng_buffer_view
*payload
)
2983 switch (header
->cmd
) {
2984 case RELAYD_CREATE_SESSION
:
2985 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2986 ret
= relay_create_session(header
, conn
, payload
);
2988 case RELAYD_ADD_STREAM
:
2989 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2990 ret
= relay_add_stream(header
, conn
, payload
);
2992 case RELAYD_START_DATA
:
2993 DBG_CMD("RELAYD_START_DATA", conn
);
2994 ret
= relay_start(header
, conn
, payload
);
2996 case RELAYD_SEND_METADATA
:
2997 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2998 ret
= relay_recv_metadata(header
, conn
, payload
);
3000 case RELAYD_VERSION
:
3001 DBG_CMD("RELAYD_VERSION", conn
);
3002 ret
= relay_send_version(header
, conn
, payload
);
3004 case RELAYD_CLOSE_STREAM
:
3005 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3006 ret
= relay_close_stream(header
, conn
, payload
);
3008 case RELAYD_DATA_PENDING
:
3009 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3010 ret
= relay_data_pending(header
, conn
, payload
);
3012 case RELAYD_QUIESCENT_CONTROL
:
3013 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3014 ret
= relay_quiescent_control(header
, conn
, payload
);
3016 case RELAYD_BEGIN_DATA_PENDING
:
3017 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3018 ret
= relay_begin_data_pending(header
, conn
, payload
);
3020 case RELAYD_END_DATA_PENDING
:
3021 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3022 ret
= relay_end_data_pending(header
, conn
, payload
);
3024 case RELAYD_SEND_INDEX
:
3025 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3026 ret
= relay_recv_index(header
, conn
, payload
);
3028 case RELAYD_STREAMS_SENT
:
3029 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3030 ret
= relay_streams_sent(header
, conn
, payload
);
3032 case RELAYD_RESET_METADATA
:
3033 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3034 ret
= relay_reset_metadata(header
, conn
, payload
);
3036 case RELAYD_ROTATE_STREAM
:
3037 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3038 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3040 case RELAYD_ROTATE_RENAME
:
3041 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3042 ret
= relay_rotate_rename(header
, conn
, payload
);
3044 case RELAYD_ROTATE_PENDING
:
3045 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3046 ret
= relay_rotate_pending(header
, conn
, payload
);
3049 DBG_CMD("RELAYD_MKDIR", conn
);
3050 ret
= relay_mkdir(header
, conn
, payload
);
3052 case RELAYD_UPDATE_SYNC_INFO
:
3054 ERR("Received unknown command (%u)", header
->cmd
);
3055 relay_unknown_command(conn
);
3064 static enum relay_connection_status
relay_process_control_receive_payload(
3065 struct relay_connection
*conn
)
3068 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3069 struct lttng_dynamic_buffer
*reception_buffer
=
3070 &conn
->protocol
.ctrl
.reception_buffer
;
3071 struct ctrl_connection_state_receive_payload
*state
=
3072 &conn
->protocol
.ctrl
.state
.receive_payload
;
3073 struct lttng_buffer_view payload_view
;
3075 if (state
->left_to_receive
== 0) {
3076 /* Short-circuit for payload-less commands. */
3077 goto reception_complete
;
3080 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3081 reception_buffer
->data
+ state
->received
,
3082 state
->left_to_receive
, MSG_DONTWAIT
);
3084 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3085 PERROR("Unable to receive command payload on sock %d",
3087 status
= RELAY_CONNECTION_STATUS_ERROR
;
3090 } else if (ret
== 0) {
3091 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3092 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3097 assert(ret
<= state
->left_to_receive
);
3099 state
->left_to_receive
-= ret
;
3100 state
->received
+= ret
;
3102 if (state
->left_to_receive
> 0) {
3104 * Can't transition to the protocol's next state, wait to
3105 * receive the rest of the header.
3107 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3108 state
->received
, state
->left_to_receive
,
3114 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3115 conn
->sock
->fd
, state
->received
);
3117 * The payload required to process the command has been received.
3118 * A view to the reception buffer is forwarded to the various
3119 * commands and the state of the control is reset on success.
3121 * Commands are responsible for sending their reply to the peer.
3123 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3125 ret
= relay_process_control_command(conn
,
3126 &state
->header
, &payload_view
);
3128 status
= RELAY_CONNECTION_STATUS_ERROR
;
3132 ret
= connection_reset_protocol_state(conn
);
3134 status
= RELAY_CONNECTION_STATUS_ERROR
;
3140 static enum relay_connection_status
relay_process_control_receive_header(
3141 struct relay_connection
*conn
)
3144 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3145 struct lttcomm_relayd_hdr header
;
3146 struct lttng_dynamic_buffer
*reception_buffer
=
3147 &conn
->protocol
.ctrl
.reception_buffer
;
3148 struct ctrl_connection_state_receive_header
*state
=
3149 &conn
->protocol
.ctrl
.state
.receive_header
;
3151 assert(state
->left_to_receive
!= 0);
3153 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3154 reception_buffer
->data
+ state
->received
,
3155 state
->left_to_receive
, MSG_DONTWAIT
);
3157 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3158 PERROR("Unable to receive control command header on sock %d",
3160 status
= RELAY_CONNECTION_STATUS_ERROR
;
3163 } else if (ret
== 0) {
3164 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3165 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3170 assert(ret
<= state
->left_to_receive
);
3172 state
->left_to_receive
-= ret
;
3173 state
->received
+= ret
;
3175 if (state
->left_to_receive
> 0) {
3177 * Can't transition to the protocol's next state, wait to
3178 * receive the rest of the header.
3180 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3181 state
->received
, state
->left_to_receive
,
3186 /* Transition to next state: receiving the command's payload. */
3187 conn
->protocol
.ctrl
.state_id
=
3188 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3189 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3190 header
.circuit_id
= be64toh(header
.circuit_id
);
3191 header
.data_size
= be64toh(header
.data_size
);
3192 header
.cmd
= be32toh(header
.cmd
);
3193 header
.cmd_version
= be32toh(header
.cmd_version
);
3194 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3195 &header
, sizeof(header
));
3197 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3198 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3201 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3202 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3204 status
= RELAY_CONNECTION_STATUS_ERROR
;
3208 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3210 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3211 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3214 status
= RELAY_CONNECTION_STATUS_ERROR
;
3218 if (header
.data_size
== 0) {
3220 * Manually invoke the next state as the poll loop
3221 * will not wake-up to allow us to proceed further.
3223 status
= relay_process_control_receive_payload(conn
);
3230 * Process the commands received on the control socket
3232 static enum relay_connection_status
relay_process_control(
3233 struct relay_connection
*conn
)
3235 enum relay_connection_status status
;
3237 switch (conn
->protocol
.ctrl
.state_id
) {
3238 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3239 status
= relay_process_control_receive_header(conn
);
3241 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3242 status
= relay_process_control_receive_payload(conn
);
3245 ERR("Unknown control connection protocol state encountered.");
3253 * Handle index for a data stream.
3255 * Called with the stream lock held.
3257 * Return 0 on success else a negative value.
3259 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3260 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3263 uint64_t data_offset
;
3264 struct relay_index
*index
;
3266 /* Get data offset because we are about to update the index. */
3267 data_offset
= htobe64(stream
->tracefile_size_current
);
3269 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3270 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3273 * Lookup for an existing index for that stream id/sequence
3274 * number. If it exists, the control thread has already received the
3275 * data for it, thus we need to write it to disk.
3277 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3283 if (rotate_index
|| !stream
->index_file
) {
3284 ret
= create_rotate_index_file(stream
);
3286 ERR("Failed to rotate index");
3287 /* Put self-ref for this index due to error. */
3288 relay_index_put(index
);
3294 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3296 /* Put self-ref for this index due to error. */
3297 relay_index_put(index
);
3302 ret
= relay_index_try_flush(index
);
3304 tracefile_array_commit_seq(stream
->tfa
);
3305 stream
->index_received_seqcount
++;
3307 } else if (ret
> 0) {
3308 index
->total_size
= total_size
;
3312 /* Put self-ref for this index due to error. */
3313 relay_index_put(index
);
3321 static enum relay_connection_status
relay_process_data_receive_header(
3322 struct relay_connection
*conn
)
3325 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3326 struct data_connection_state_receive_header
*state
=
3327 &conn
->protocol
.data
.state
.receive_header
;
3328 struct lttcomm_relayd_data_hdr header
;
3329 struct relay_stream
*stream
;
3331 assert(state
->left_to_receive
!= 0);
3333 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3334 state
->header_reception_buffer
+ state
->received
,
3335 state
->left_to_receive
, MSG_DONTWAIT
);
3337 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3338 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3339 status
= RELAY_CONNECTION_STATUS_ERROR
;
3342 } else if (ret
== 0) {
3343 /* Orderly shutdown. Not necessary to print an error. */
3344 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3345 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3350 assert(ret
<= state
->left_to_receive
);
3352 state
->left_to_receive
-= ret
;
3353 state
->received
+= ret
;
3355 if (state
->left_to_receive
> 0) {
3357 * Can't transition to the protocol's next state, wait to
3358 * receive the rest of the header.
3360 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3361 state
->received
, state
->left_to_receive
,
3366 /* Transition to next state: receiving the payload. */
3367 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3369 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3370 header
.circuit_id
= be64toh(header
.circuit_id
);
3371 header
.stream_id
= be64toh(header
.stream_id
);
3372 header
.data_size
= be32toh(header
.data_size
);
3373 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3374 header
.padding_size
= be32toh(header
.padding_size
);
3375 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3377 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3379 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3380 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3382 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3383 conn
->sock
->fd
, header
.circuit_id
,
3384 header
.stream_id
, header
.data_size
,
3385 header
.net_seq_num
, header
.padding_size
);
3387 stream
= stream_get_by_id(header
.stream_id
);
3389 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3391 /* Protocol error. */
3392 status
= RELAY_CONNECTION_STATUS_ERROR
;
3396 pthread_mutex_lock(&stream
->lock
);
3398 /* Check if a rotation is needed. */
3399 if (stream
->tracefile_size
> 0 &&
3400 (stream
->tracefile_size_current
+ header
.data_size
) >
3401 stream
->tracefile_size
) {
3402 uint64_t old_id
, new_id
;
3404 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3405 tracefile_array_file_rotate(stream
->tfa
);
3407 /* new_id is updated by utils_rotate_stream_file. */
3410 ret
= utils_rotate_stream_file(stream
->path_name
,
3411 stream
->channel_name
, stream
->tracefile_size
,
3412 stream
->tracefile_count
, -1,
3413 -1, stream
->stream_fd
->fd
,
3414 &new_id
, &stream
->stream_fd
->fd
);
3416 ERR("Failed to rotate stream output file");
3417 status
= RELAY_CONNECTION_STATUS_ERROR
;
3418 goto end_stream_unlock
;
3422 * Reset current size because we just performed a stream
3425 stream
->tracefile_size_current
= 0;
3426 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3430 pthread_mutex_unlock(&stream
->lock
);
3436 static enum relay_connection_status
relay_process_data_receive_payload(
3437 struct relay_connection
*conn
)
3440 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3441 struct relay_stream
*stream
;
3442 struct data_connection_state_receive_payload
*state
=
3443 &conn
->protocol
.data
.state
.receive_payload
;
3444 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3445 char data_buffer
[chunk_size
];
3446 bool partial_recv
= false;
3447 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3448 uint64_t left_to_receive
= state
->left_to_receive
;
3449 struct relay_session
*session
;
3451 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3452 state
->header
.stream_id
, state
->header
.net_seq_num
,
3453 state
->received
, left_to_receive
);
3455 stream
= stream_get_by_id(state
->header
.stream_id
);
3457 /* Protocol error. */
3458 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3459 state
->header
.stream_id
);
3460 status
= RELAY_CONNECTION_STATUS_ERROR
;
3464 pthread_mutex_lock(&stream
->lock
);
3465 session
= stream
->trace
->session
;
3466 if (!conn
->session
) {
3467 ret
= connection_set_session(conn
, session
);
3469 status
= RELAY_CONNECTION_STATUS_ERROR
;
3470 goto end_stream_unlock
;
3475 * The size of the "chunk" received on any iteration is bounded by:
3476 * - the data left to receive,
3477 * - the data immediately available on the socket,
3478 * - the on-stack data buffer
3480 while (left_to_receive
> 0 && !partial_recv
) {
3482 size_t recv_size
= min(left_to_receive
, chunk_size
);
3484 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3485 recv_size
, MSG_DONTWAIT
);
3487 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3488 PERROR("Socket %d error", conn
->sock
->fd
);
3489 status
= RELAY_CONNECTION_STATUS_ERROR
;
3491 goto end_stream_unlock
;
3492 } else if (ret
== 0) {
3493 /* No more data ready to be consumed on socket. */
3494 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3495 state
->header
.stream_id
);
3496 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3498 } else if (ret
< (int) recv_size
) {
3500 * All the data available on the socket has been
3503 partial_recv
= true;
3508 /* Write data to stream output fd. */
3509 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3511 if (write_ret
< (ssize_t
) recv_size
) {
3512 ERR("Relay error writing data to file");
3513 status
= RELAY_CONNECTION_STATUS_ERROR
;
3514 goto end_stream_unlock
;
3517 left_to_receive
-= recv_size
;
3518 state
->received
+= recv_size
;
3519 state
->left_to_receive
= left_to_receive
;
3521 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3522 write_ret
, stream
->stream_handle
);
3525 if (state
->left_to_receive
> 0) {
3527 * Did not receive all the data expected, wait for more data to
3528 * become available on the socket.
3530 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3531 state
->header
.stream_id
, state
->received
,
3532 state
->left_to_receive
);
3533 goto end_stream_unlock
;
3536 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3537 state
->header
.padding_size
);
3538 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3539 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3540 stream
->stream_handle
,
3541 state
->header
.net_seq_num
, ret
);
3542 status
= RELAY_CONNECTION_STATUS_ERROR
;
3543 goto end_stream_unlock
;
3547 if (session
->minor
>= 4 && !session
->snapshot
) {
3548 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3549 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3551 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3552 stream
->stream_handle
,
3553 state
->header
.net_seq_num
, ret
);
3554 status
= RELAY_CONNECTION_STATUS_ERROR
;
3555 goto end_stream_unlock
;
3559 stream
->tracefile_size_current
+= state
->header
.data_size
+
3560 state
->header
.padding_size
;
3562 if (stream
->prev_seq
== -1ULL) {
3565 if (index_flushed
) {
3566 stream
->pos_after_last_complete_data_index
=
3567 stream
->tracefile_size_current
;
3570 stream
->prev_seq
= state
->header
.net_seq_num
;
3573 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3574 * contents of *state which are aliased (union) to the same location as
3575 * the new state. Don't use it beyond this point.
3577 connection_reset_protocol_state(conn
);
3580 ret
= try_rotate_stream(stream
);
3582 status
= RELAY_CONNECTION_STATUS_ERROR
;
3583 goto end_stream_unlock
;
3587 close_requested
= stream
->close_requested
;
3588 pthread_mutex_unlock(&stream
->lock
);
3589 if (close_requested
&& left_to_receive
== 0) {
3590 try_stream_close(stream
);
3594 pthread_mutex_lock(&session
->lock
);
3595 uatomic_set(&session
->new_streams
, 1);
3596 pthread_mutex_unlock(&session
->lock
);
3605 * relay_process_data: Process the data received on the data socket
3607 static enum relay_connection_status
relay_process_data(
3608 struct relay_connection
*conn
)
3610 enum relay_connection_status status
;
3612 switch (conn
->protocol
.data
.state_id
) {
3613 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3614 status
= relay_process_data_receive_header(conn
);
3616 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3617 status
= relay_process_data_receive_payload(conn
);
3620 ERR("Unexpected data connection communication state.");
3627 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3631 (void) lttng_poll_del(events
, pollfd
);
3633 ret
= close(pollfd
);
3635 ERR("Closing pollfd %d", pollfd
);
3639 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3640 int pollfd
, struct relay_connection
*conn
)
3642 const char *type_str
;
3644 switch (conn
->type
) {
3649 type_str
= "Control";
3651 case RELAY_VIEWER_COMMAND
:
3652 type_str
= "Viewer Command";
3654 case RELAY_VIEWER_NOTIFICATION
:
3655 type_str
= "Viewer Notification";
3658 type_str
= "Unknown";
3660 cleanup_connection_pollfd(events
, pollfd
);
3661 connection_put(conn
);
3662 DBG("%s connection closed with %d", type_str
, pollfd
);
3666 * This thread does the actual work
3668 static void *relay_thread_worker(void *data
)
3670 int ret
, err
= -1, last_seen_data_fd
= -1;
3672 struct lttng_poll_event events
;
3673 struct lttng_ht
*relay_connections_ht
;
3674 struct lttng_ht_iter iter
;
3675 struct relay_connection
*destroy_conn
= NULL
;
3677 DBG("[thread] Relay worker started");
3679 rcu_register_thread();
3681 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3683 if (testpoint(relayd_thread_worker
)) {
3684 goto error_testpoint
;
3687 health_code_update();
3689 /* table of connections indexed on socket */
3690 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3691 if (!relay_connections_ht
) {
3692 goto relay_connections_ht_error
;
3695 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3697 goto error_poll_create
;
3700 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3707 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3709 health_code_update();
3711 /* Infinite blocking call, waiting for transmission */
3712 DBG3("Relayd worker thread polling...");
3713 health_poll_entry();
3714 ret
= lttng_poll_wait(&events
, -1);
3718 * Restart interrupted system call.
3720 if (errno
== EINTR
) {
3729 * Process control. The control connection is
3730 * prioritized so we don't starve it with high
3731 * throughput tracing data on the data connection.
3733 for (i
= 0; i
< nb_fd
; i
++) {
3734 /* Fetch once the poll data */
3735 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3736 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3738 health_code_update();
3742 * No activity for this FD (poll
3748 /* Thread quit pipe has been closed. Killing thread. */
3749 ret
= check_thread_quit_pipe(pollfd
, revents
);
3755 /* Inspect the relay conn pipe for new connection */
3756 if (pollfd
== relay_conn_pipe
[0]) {
3757 if (revents
& LPOLLIN
) {
3758 struct relay_connection
*conn
;
3760 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3764 lttng_poll_add(&events
, conn
->sock
->fd
,
3765 LPOLLIN
| LPOLLRDHUP
);
3766 connection_ht_add(relay_connections_ht
, conn
);
3767 DBG("Connection socket %d added", conn
->sock
->fd
);
3768 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3769 ERR("Relay connection pipe error");
3772 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3776 struct relay_connection
*ctrl_conn
;
3778 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3779 /* If not found, there is a synchronization issue. */
3782 if (ctrl_conn
->type
== RELAY_DATA
) {
3783 if (revents
& LPOLLIN
) {
3785 * Flag the last seen data fd not deleted. It will be
3786 * used as the last seen fd if any fd gets deleted in
3789 last_notdel_data_fd
= pollfd
;
3791 goto put_ctrl_connection
;
3793 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3795 if (revents
& LPOLLIN
) {
3796 enum relay_connection_status status
;
3798 status
= relay_process_control(ctrl_conn
);
3799 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3801 * On socket error flag the session as aborted to force
3802 * the cleanup of its stream otherwise it can leak
3803 * during the lifetime of the relayd.
3805 * This prevents situations in which streams can be
3806 * left opened because an index was received, the
3807 * control connection is closed, and the data
3808 * connection is closed (uncleanly) before the packet's
3811 * Since the control connection encountered an error,
3812 * it is okay to be conservative and close the
3813 * session right now as we can't rely on the protocol
3814 * being respected anymore.
3816 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3817 session_abort(ctrl_conn
->session
);
3820 /* Clear the connection on error or close. */
3821 relay_thread_close_connection(&events
,
3826 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3827 relay_thread_close_connection(&events
,
3829 if (last_seen_data_fd
== pollfd
) {
3830 last_seen_data_fd
= last_notdel_data_fd
;
3833 ERR("Unexpected poll events %u for control sock %d",
3835 connection_put(ctrl_conn
);
3838 put_ctrl_connection
:
3839 connection_put(ctrl_conn
);
3844 * The last loop handled a control request, go back to poll to make
3845 * sure we prioritise the control socket.
3851 if (last_seen_data_fd
>= 0) {
3852 for (i
= 0; i
< nb_fd
; i
++) {
3853 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3855 health_code_update();
3857 if (last_seen_data_fd
== pollfd
) {
3864 /* Process data connection. */
3865 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3866 /* Fetch the poll data. */
3867 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3868 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3869 struct relay_connection
*data_conn
;
3871 health_code_update();
3874 /* No activity for this FD (poll implementation). */
3878 /* Skip the command pipe. It's handled in the first loop. */
3879 if (pollfd
== relay_conn_pipe
[0]) {
3883 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3885 /* Skip it. Might be removed before. */
3888 if (data_conn
->type
== RELAY_CONTROL
) {
3889 goto put_data_connection
;
3891 assert(data_conn
->type
== RELAY_DATA
);
3893 if (revents
& LPOLLIN
) {
3894 enum relay_connection_status status
;
3896 status
= relay_process_data(data_conn
);
3897 /* Connection closed or error. */
3898 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3900 * On socket error flag the session as aborted to force
3901 * the cleanup of its stream otherwise it can leak
3902 * during the lifetime of the relayd.
3904 * This prevents situations in which streams can be
3905 * left opened because an index was received, the
3906 * control connection is closed, and the data
3907 * connection is closed (uncleanly) before the packet's
3910 * Since the data connection encountered an error,
3911 * it is okay to be conservative and close the
3912 * session right now as we can't rely on the protocol
3913 * being respected anymore.
3915 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3916 session_abort(data_conn
->session
);
3918 relay_thread_close_connection(&events
, pollfd
,
3921 * Every goto restart call sets the last seen fd where
3922 * here we don't really care since we gracefully
3923 * continue the loop after the connection is deleted.
3926 /* Keep last seen port. */
3927 last_seen_data_fd
= pollfd
;
3928 connection_put(data_conn
);
3931 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3932 relay_thread_close_connection(&events
, pollfd
,
3935 ERR("Unknown poll events %u for data sock %d",
3938 put_data_connection
:
3939 connection_put(data_conn
);
3941 last_seen_data_fd
= -1;
3944 /* Normal exit, no error */
3949 /* Cleanup remaining connection object. */
3951 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3954 health_code_update();
3956 session_abort(destroy_conn
->session
);
3959 * No need to grab another ref, because we own
3962 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3967 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3969 lttng_ht_destroy(relay_connections_ht
);
3970 relay_connections_ht_error
:
3971 /* Close relay conn pipes */
3972 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3975 DBG("Thread exited with error");
3977 DBG("Worker thread cleanup complete");
3981 ERR("Health error occurred in %s", __func__
);
3983 health_unregister(health_relayd
);
3984 rcu_unregister_thread();
3985 lttng_relay_stop_threads();
3990 * Create the relay command pipe to wake thread_manage_apps.
3991 * Closed in cleanup().
3993 static int create_relay_conn_pipe(void)
3995 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3996 "Relayd connection pipe", relay_conn_pipe
);
4000 int stdio_open(void *data
, int *fds
)
4002 fds
[0] = fileno(stdout
);
4003 fds
[1] = fileno(stderr
);
4008 int noop_close(void *data
, int *fds
)
4014 int track_stdio(void)
4017 const char *names
[] = { "stdout", "stderr" };
4019 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4020 names
, 2, stdio_open
, NULL
);
4024 void untrack_stdio(void)
4026 int fds
[] = { fileno(stdout
), fileno(stderr
) };
4029 * noop_close is used since we don't really want to close
4030 * the stdio output fds; we merely want to stop tracking them.
4032 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
4033 fds
, 2, noop_close
, NULL
);
4039 int main(int argc
, char **argv
)
4041 int ret
= 0, retval
= 0;
4044 /* Parse arguments */
4046 if (set_options(argc
, argv
)) {
4051 if (set_signal_handler()) {
4056 ret
= fclose(stdin
);
4058 PERROR("Failed to close stdin");
4061 /* Try to create directory if -o, --output is specified. */
4062 if (opt_output_path
) {
4063 if (*opt_output_path
!= '/') {
4064 ERR("Please specify an absolute path for -o, --output PATH");
4069 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4072 ERR("Unable to create %s", opt_output_path
);
4079 if (opt_daemon
|| opt_background
) {
4080 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4089 * The RCU thread registration (and use, through the fd-tracker's
4090 * creation) is done after the daemonization to allow us to not
4091 * deal with liburcu's fork() management as the call RCU needs to
4094 rcu_register_thread();
4096 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
4097 if (!the_fd_tracker
) {
4102 ret
= track_stdio();
4108 /* Initialize thread health monitoring */
4109 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4110 if (!health_relayd
) {
4111 PERROR("health_app_create error");
4113 goto exit_health_app_create
;
4116 /* Create thread quit pipe */
4117 if (init_thread_quit_pipe()) {
4119 goto exit_init_data
;
4122 /* Setup the thread apps communication pipe. */
4123 if (create_relay_conn_pipe()) {
4125 goto exit_init_data
;
4128 /* Init relay command queue. */
4129 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4131 /* Initialize communication library */
4133 lttcomm_inet_init();
4135 /* tables of sessions indexed by session ID */
4136 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4139 goto exit_init_data
;
4142 /* tables of streams indexed by stream ID */
4143 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4144 if (!relay_streams_ht
) {
4146 goto exit_init_data
;
4149 /* tables of streams indexed by stream ID */
4150 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4151 if (!viewer_streams_ht
) {
4153 goto exit_init_data
;
4156 ret
= init_health_quit_pipe();
4159 goto exit_health_quit_pipe
;
4162 /* Create thread to manage the client socket */
4163 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4164 thread_manage_health
, (void *) NULL
);
4167 PERROR("pthread_create health");
4169 goto exit_health_thread
;
4172 /* Setup the dispatcher thread */
4173 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4174 relay_thread_dispatcher
, (void *) NULL
);
4177 PERROR("pthread_create dispatcher");
4179 goto exit_dispatcher_thread
;
4182 /* Setup the worker thread */
4183 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4184 relay_thread_worker
, NULL
);
4187 PERROR("pthread_create worker");
4189 goto exit_worker_thread
;
4192 /* Setup the listener thread */
4193 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4194 relay_thread_listener
, (void *) NULL
);
4197 PERROR("pthread_create listener");
4199 goto exit_listener_thread
;
4202 ret
= relayd_live_create(live_uri
);
4204 ERR("Starting live viewer threads");
4210 * This is where we start awaiting program completion (e.g. through
4211 * signal that asks threads to teardown).
4214 ret
= relayd_live_join();
4220 ret
= pthread_join(listener_thread
, &status
);
4223 PERROR("pthread_join listener_thread");
4227 exit_listener_thread
:
4228 ret
= pthread_join(worker_thread
, &status
);
4231 PERROR("pthread_join worker_thread");
4236 ret
= pthread_join(dispatcher_thread
, &status
);
4239 PERROR("pthread_join dispatcher_thread");
4242 exit_dispatcher_thread
:
4244 ret
= pthread_join(health_thread
, &status
);
4247 PERROR("pthread_join health_thread");
4252 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4253 exit_health_quit_pipe
:
4256 health_app_destroy(health_relayd
);
4257 exit_health_app_create
:
4260 * Wait for all pending call_rcu work to complete before tearing
4261 * down data structures. call_rcu worker may be trying to
4262 * perform lookups in those structures.
4267 /* Ensure all prior call_rcu are done. */
4272 * fd_tracker_destroy() will log the contents of the fd-tracker
4273 * if a leak is detected.
4275 fd_tracker_destroy(the_fd_tracker
);
4276 rcu_unregister_thread();