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
);
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
= data_sock
->ops
->close(data_sock
);
1047 lttcomm_destroy_sock(data_sock
);
1049 if (control_sock
->fd
>= 0) {
1050 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
1051 &control_sock
->fd
, 1, close_sock
,
1057 lttcomm_destroy_sock(control_sock
);
1061 ERR("Health error occurred in %s", __func__
);
1063 health_unregister(health_relayd
);
1064 DBG("Relay listener thread cleanup complete");
1065 lttng_relay_stop_threads();
1070 * This thread manages the dispatching of the requests to worker threads
1072 static void *relay_thread_dispatcher(void *data
)
1076 struct cds_wfcq_node
*node
;
1077 struct relay_connection
*new_conn
= NULL
;
1079 DBG("[thread] Relay dispatcher started");
1081 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1083 if (testpoint(relayd_thread_dispatcher
)) {
1084 goto error_testpoint
;
1087 health_code_update();
1090 health_code_update();
1092 /* Atomically prepare the queue futex */
1093 futex_nto1_prepare(&relay_conn_queue
.futex
);
1095 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1100 health_code_update();
1102 /* Dequeue commands */
1103 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1104 &relay_conn_queue
.tail
);
1106 DBG("Woken up but nothing in the relay command queue");
1107 /* Continue thread execution */
1110 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1112 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1115 * Inform worker thread of the new request. This
1116 * call is blocking so we can be assured that
1117 * the data will be read at some point in time
1118 * or wait to the end of the world :)
1120 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1122 PERROR("write connection pipe");
1123 connection_put(new_conn
);
1126 } while (node
!= NULL
);
1128 /* Futex wait on queue. Blocking call on futex() */
1129 health_poll_entry();
1130 futex_nto1_wait(&relay_conn_queue
.futex
);
1134 /* Normal exit, no error */
1141 ERR("Health error occurred in %s", __func__
);
1143 health_unregister(health_relayd
);
1144 DBG("Dispatch thread dying");
1145 lttng_relay_stop_threads();
1150 * Set index data from the control port to a given index object.
1152 static int set_index_control_data(struct relay_index
*index
,
1153 struct lttcomm_relayd_index
*data
,
1154 struct relay_connection
*conn
)
1156 struct ctf_packet_index index_data
;
1159 * The index on disk is encoded in big endian.
1161 index_data
.packet_size
= htobe64(data
->packet_size
);
1162 index_data
.content_size
= htobe64(data
->content_size
);
1163 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1164 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1165 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1166 index_data
.stream_id
= htobe64(data
->stream_id
);
1168 if (conn
->minor
>= 8) {
1169 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1170 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1173 return relay_index_set_data(index
, &index_data
);
1177 * Handle the RELAYD_CREATE_SESSION command.
1179 * On success, send back the session id or else return a negative value.
1181 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1182 struct relay_connection
*conn
,
1183 const struct lttng_buffer_view
*payload
)
1187 struct relay_session
*session
;
1188 struct lttcomm_relayd_status_session reply
;
1189 char session_name
[LTTNG_NAME_MAX
];
1190 char hostname
[LTTNG_HOST_NAME_MAX
];
1191 uint32_t live_timer
= 0;
1192 bool snapshot
= false;
1194 memset(session_name
, 0, LTTNG_NAME_MAX
);
1195 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1197 memset(&reply
, 0, sizeof(reply
));
1199 if (conn
->minor
< 4) {
1200 /* From 2.1 to 2.3 */
1202 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1203 /* From 2.4 to 2.10 */
1204 ret
= cmd_create_session_2_4(payload
, session_name
,
1205 hostname
, &live_timer
, &snapshot
);
1207 /* From 2.11 to ... */
1208 ret
= cmd_create_session_2_11(payload
, session_name
,
1209 hostname
, &live_timer
, &snapshot
);
1216 session
= session_create(session_name
, hostname
, live_timer
,
1217 snapshot
, conn
->major
, conn
->minor
);
1222 assert(!conn
->session
);
1223 conn
->session
= session
;
1224 DBG("Created session %" PRIu64
, session
->id
);
1226 reply
.session_id
= htobe64(session
->id
);
1230 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1232 reply
.ret_code
= htobe32(LTTNG_OK
);
1235 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1236 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1237 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1246 * When we have received all the streams and the metadata for a channel,
1247 * we make them visible to the viewer threads.
1249 static void publish_connection_local_streams(struct relay_connection
*conn
)
1251 struct relay_stream
*stream
;
1252 struct relay_session
*session
= conn
->session
;
1255 * We publish all streams belonging to a session atomically wrt
1258 pthread_mutex_lock(&session
->lock
);
1260 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1262 stream_publish(stream
);
1267 * Inform the viewer that there are new streams in the session.
1269 if (session
->viewer_attached
) {
1270 uatomic_set(&session
->new_streams
, 1);
1272 pthread_mutex_unlock(&session
->lock
);
1276 * relay_add_stream: allocate a new stream for a session
1278 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1279 struct relay_connection
*conn
,
1280 const struct lttng_buffer_view
*payload
)
1284 struct relay_session
*session
= conn
->session
;
1285 struct relay_stream
*stream
= NULL
;
1286 struct lttcomm_relayd_status_stream reply
;
1287 struct ctf_trace
*trace
= NULL
;
1288 uint64_t stream_handle
= -1ULL;
1289 char *path_name
= NULL
, *channel_name
= NULL
;
1290 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1291 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1293 if (!session
|| !conn
->version_check_done
) {
1294 ERR("Trying to add a stream before version check");
1296 goto end_no_session
;
1299 if (session
->minor
== 1) {
1301 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1303 } else if (session
->minor
> 1 && session
->minor
< 11) {
1304 /* From 2.2 to 2.10 */
1305 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1306 &channel_name
, &tracefile_size
, &tracefile_count
);
1308 /* From 2.11 to ... */
1309 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1310 &channel_name
, &tracefile_size
, &tracefile_count
,
1311 &stream_chunk_id
.value
);
1312 stream_chunk_id
.is_set
= true;
1319 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1323 /* This stream here has one reference on the trace. */
1325 pthread_mutex_lock(&last_relay_stream_id_lock
);
1326 stream_handle
= ++last_relay_stream_id
;
1327 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1329 /* We pass ownership of path_name and channel_name. */
1330 stream
= stream_create(trace
, stream_handle
, path_name
,
1331 channel_name
, tracefile_size
, tracefile_count
,
1334 channel_name
= NULL
;
1337 * Streams are the owners of their trace. Reference to trace is
1338 * kept within stream_create().
1340 ctf_trace_put(trace
);
1343 memset(&reply
, 0, sizeof(reply
));
1344 reply
.handle
= htobe64(stream_handle
);
1346 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1348 reply
.ret_code
= htobe32(LTTNG_OK
);
1351 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1352 sizeof(struct lttcomm_relayd_status_stream
), 0);
1353 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1354 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1366 * relay_close_stream: close a specific stream
1368 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1369 struct relay_connection
*conn
,
1370 const struct lttng_buffer_view
*payload
)
1374 struct relay_session
*session
= conn
->session
;
1375 struct lttcomm_relayd_close_stream stream_info
;
1376 struct lttcomm_relayd_generic_reply reply
;
1377 struct relay_stream
*stream
;
1379 DBG("Close stream received");
1381 if (!session
|| !conn
->version_check_done
) {
1382 ERR("Trying to close a stream before version check");
1384 goto end_no_session
;
1387 if (payload
->size
< sizeof(stream_info
)) {
1388 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1389 sizeof(stream_info
), payload
->size
);
1391 goto end_no_session
;
1393 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1394 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1395 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1397 stream
= stream_get_by_id(stream_info
.stream_id
);
1404 * Set last_net_seq_num before the close flag. Required by data
1407 pthread_mutex_lock(&stream
->lock
);
1408 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1409 pthread_mutex_unlock(&stream
->lock
);
1412 * This is one of the conditions which may trigger a stream close
1413 * with the others being:
1414 * 1) A close command is received for a stream
1415 * 2) The control connection owning the stream is closed
1416 * 3) We have received all of the stream's data _after_ a close
1419 try_stream_close(stream
);
1420 if (stream
->is_metadata
) {
1421 struct relay_viewer_stream
*vstream
;
1423 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1425 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1427 * Since all the metadata has been sent to the
1428 * viewer and that we have a request to close
1429 * its stream, we can safely teardown the
1430 * corresponding metadata viewer stream.
1432 viewer_stream_put(vstream
);
1434 /* Put local reference. */
1435 viewer_stream_put(vstream
);
1442 memset(&reply
, 0, sizeof(reply
));
1444 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1446 reply
.ret_code
= htobe32(LTTNG_OK
);
1448 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1449 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1450 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1451 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1461 * relay_reset_metadata: reset a metadata stream
1464 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1465 struct relay_connection
*conn
,
1466 const struct lttng_buffer_view
*payload
)
1470 struct relay_session
*session
= conn
->session
;
1471 struct lttcomm_relayd_reset_metadata stream_info
;
1472 struct lttcomm_relayd_generic_reply reply
;
1473 struct relay_stream
*stream
;
1475 DBG("Reset metadata received");
1477 if (!session
|| !conn
->version_check_done
) {
1478 ERR("Trying to reset a metadata stream before version check");
1480 goto end_no_session
;
1483 if (payload
->size
< sizeof(stream_info
)) {
1484 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1485 sizeof(stream_info
), payload
->size
);
1487 goto end_no_session
;
1489 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1490 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1491 stream_info
.version
= be64toh(stream_info
.version
);
1493 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1495 /* Unsupported for live sessions for now. */
1496 if (session
->live_timer
!= 0) {
1501 stream
= stream_get_by_id(stream_info
.stream_id
);
1506 pthread_mutex_lock(&stream
->lock
);
1507 if (!stream
->is_metadata
) {
1512 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1513 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1514 &stream
->stream_fd
->fd
);
1516 ERR("Failed to rotate metadata file %s of channel %s",
1517 stream
->path_name
, stream
->channel_name
);
1522 pthread_mutex_unlock(&stream
->lock
);
1526 memset(&reply
, 0, sizeof(reply
));
1528 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1530 reply
.ret_code
= htobe32(LTTNG_OK
);
1532 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1533 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1534 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1535 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1545 * relay_unknown_command: send -1 if received unknown command
1547 static void relay_unknown_command(struct relay_connection
*conn
)
1549 struct lttcomm_relayd_generic_reply reply
;
1552 memset(&reply
, 0, sizeof(reply
));
1553 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1554 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1555 if (send_ret
< sizeof(reply
)) {
1556 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1561 * relay_start: send an acknowledgment to the client to tell if we are
1562 * ready to receive data. We are ready if a session is established.
1564 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1565 struct relay_connection
*conn
,
1566 const struct lttng_buffer_view
*payload
)
1570 struct lttcomm_relayd_generic_reply reply
;
1571 struct relay_session
*session
= conn
->session
;
1574 DBG("Trying to start the streaming without a session established");
1575 ret
= htobe32(LTTNG_ERR_UNK
);
1578 memset(&reply
, 0, sizeof(reply
));
1579 reply
.ret_code
= htobe32(LTTNG_OK
);
1580 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1582 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1583 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1592 * Append padding to the file pointed by the file descriptor fd.
1594 static int write_padding_to_file(int fd
, uint32_t size
)
1603 zeros
= zmalloc(size
);
1604 if (zeros
== NULL
) {
1605 PERROR("zmalloc zeros for padding");
1610 ret
= lttng_write(fd
, zeros
, size
);
1612 PERROR("write padding to file");
1622 * Close the current index file if it is open, and create a new one.
1624 * Return 0 on success, -1 on error.
1627 int create_rotate_index_file(struct relay_stream
*stream
)
1630 uint32_t major
, minor
;
1632 /* Put ref on previous index_file. */
1633 if (stream
->index_file
) {
1634 lttng_index_file_put(stream
->index_file
);
1635 stream
->index_file
= NULL
;
1637 major
= stream
->trace
->session
->major
;
1638 minor
= stream
->trace
->session
->minor
;
1639 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
1640 stream
->channel_name
,
1641 -1, -1, stream
->tracefile_size
,
1642 tracefile_array_get_file_index_head(stream
->tfa
),
1643 lttng_to_index_major(major
, minor
),
1644 lttng_to_index_minor(major
, minor
));
1645 if (!stream
->index_file
) {
1657 int do_rotate_stream(struct relay_stream
*stream
)
1661 /* Perform the stream rotation. */
1662 ret
= utils_rotate_stream_file(stream
->path_name
,
1663 stream
->channel_name
, stream
->tracefile_size
,
1664 stream
->tracefile_count
, -1,
1665 -1, stream
->stream_fd
->fd
,
1666 NULL
, &stream
->stream_fd
->fd
);
1668 ERR("Rotating stream output file");
1671 stream
->tracefile_size_current
= 0;
1673 /* Rotate also the index if the stream is not a metadata stream. */
1674 if (!stream
->is_metadata
) {
1675 ret
= create_rotate_index_file(stream
);
1677 ERR("Failed to rotate index file");
1682 stream
->rotate_at_seq_num
= -1ULL;
1683 stream
->pos_after_last_complete_data_index
= 0;
1690 * If too much data has been written in a tracefile before we received the
1691 * rotation command, we have to move the excess data to the new tracefile and
1692 * perform the rotation. This can happen because the control and data
1693 * connections are separate, the indexes as well as the commands arrive from
1694 * the control connection and we have no control over the order so we could be
1695 * in a situation where too much data has been received on the data connection
1696 * before the rotation command on the control connection arrives. We don't need
1697 * to update the index because its order is guaranteed with the rotation
1701 int rotate_truncate_stream(struct relay_stream
*stream
)
1705 uint64_t diff
, pos
= 0;
1706 char buf
[FILE_COPY_BUFFER_SIZE
];
1708 assert(!stream
->is_metadata
);
1710 assert(stream
->tracefile_size_current
>
1711 stream
->pos_after_last_complete_data_index
);
1712 diff
= stream
->tracefile_size_current
-
1713 stream
->pos_after_last_complete_data_index
;
1715 /* Create the new tracefile. */
1716 new_fd
= utils_create_stream_file(stream
->path_name
,
1717 stream
->channel_name
,
1718 stream
->tracefile_size
, stream
->tracefile_count
,
1719 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1721 ERR("Failed to create new stream file at path %s for channel %s",
1722 stream
->path_name
, stream
->channel_name
);
1728 * Rewind the current tracefile to the position at which the rotation
1729 * should have occured.
1731 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1732 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1733 if (lseek_ret
< 0) {
1734 PERROR("seek truncate stream");
1739 /* Move data from the old file to the new file. */
1740 while (pos
< diff
) {
1741 uint64_t count
, bytes_left
;
1744 bytes_left
= diff
- pos
;
1745 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1746 assert(count
<= SIZE_MAX
);
1748 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1749 if (io_ret
< (ssize_t
) count
) {
1750 char error_string
[256];
1752 snprintf(error_string
, sizeof(error_string
),
1753 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1754 count
, stream
->stream_fd
->fd
, io_ret
);
1756 PERROR("%s", error_string
);
1758 ERR("%s", error_string
);
1764 io_ret
= lttng_write(new_fd
, buf
, count
);
1765 if (io_ret
< (ssize_t
) count
) {
1766 char error_string
[256];
1768 snprintf(error_string
, sizeof(error_string
),
1769 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1770 count
, new_fd
, io_ret
);
1772 PERROR("%s", error_string
);
1774 ERR("%s", error_string
);
1783 /* Truncate the file to get rid of the excess data. */
1784 ret
= ftruncate(stream
->stream_fd
->fd
,
1785 stream
->pos_after_last_complete_data_index
);
1787 PERROR("ftruncate");
1791 ret
= close(stream
->stream_fd
->fd
);
1793 PERROR("Closing tracefile");
1797 ret
= create_rotate_index_file(stream
);
1799 ERR("Rotate stream index file");
1804 * Update the offset and FD of all the eventual indexes created by the
1805 * data connection before the rotation command arrived.
1807 ret
= relay_index_switch_all_files(stream
);
1809 ERR("Failed to rotate index file");
1813 stream
->stream_fd
->fd
= new_fd
;
1814 stream
->tracefile_size_current
= diff
;
1815 stream
->pos_after_last_complete_data_index
= 0;
1816 stream
->rotate_at_seq_num
= -1ULL;
1825 * Check if a stream should perform a rotation (for session rotation).
1826 * Must be called with the stream lock held.
1828 * Return 0 on success, a negative value on error.
1831 int try_rotate_stream(struct relay_stream
*stream
)
1835 /* No rotation expected. */
1836 if (stream
->rotate_at_seq_num
== -1ULL) {
1840 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1841 stream
->prev_seq
== -1ULL) {
1842 DBG("Stream %" PRIu64
" no yet ready for rotation",
1843 stream
->stream_handle
);
1845 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1846 DBG("Rotation after too much data has been written in tracefile "
1847 "for stream %" PRIu64
", need to truncate before "
1848 "rotating", stream
->stream_handle
);
1849 ret
= rotate_truncate_stream(stream
);
1851 ERR("Failed to truncate stream");
1855 /* stream->prev_seq == stream->rotate_at_seq_num */
1856 DBG("Stream %" PRIu64
" ready for rotation",
1857 stream
->stream_handle
);
1858 ret
= do_rotate_stream(stream
);
1866 * relay_recv_metadata: receive the metadata for the session.
1868 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1869 struct relay_connection
*conn
,
1870 const struct lttng_buffer_view
*payload
)
1874 struct relay_session
*session
= conn
->session
;
1875 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1876 struct relay_stream
*metadata_stream
;
1877 uint64_t metadata_payload_size
;
1880 ERR("Metadata sent before version check");
1885 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1886 ERR("Incorrect data size");
1890 metadata_payload_size
= recv_hdr
->data_size
-
1891 sizeof(struct lttcomm_relayd_metadata_payload
);
1893 memcpy(&metadata_payload_header
, payload
->data
,
1894 sizeof(metadata_payload_header
));
1895 metadata_payload_header
.stream_id
= be64toh(
1896 metadata_payload_header
.stream_id
);
1897 metadata_payload_header
.padding_size
= be32toh(
1898 metadata_payload_header
.padding_size
);
1900 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1901 if (!metadata_stream
) {
1906 pthread_mutex_lock(&metadata_stream
->lock
);
1908 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1909 payload
->data
+ sizeof(metadata_payload_header
),
1910 metadata_payload_size
);
1911 if (size_ret
< metadata_payload_size
) {
1912 ERR("Relay error writing metadata on file");
1917 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1918 metadata_payload_header
.padding_size
);
1919 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1924 metadata_stream
->metadata_received
+=
1925 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1926 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1927 metadata_stream
->metadata_received
);
1929 ret
= try_rotate_stream(metadata_stream
);
1935 pthread_mutex_unlock(&metadata_stream
->lock
);
1936 stream_put(metadata_stream
);
1942 * relay_send_version: send relayd version number
1944 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1945 struct relay_connection
*conn
,
1946 const struct lttng_buffer_view
*payload
)
1950 struct lttcomm_relayd_version reply
, msg
;
1951 bool compatible
= true;
1953 conn
->version_check_done
= true;
1955 /* Get version from the other side. */
1956 if (payload
->size
< sizeof(msg
)) {
1957 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1958 sizeof(msg
), payload
->size
);
1963 memcpy(&msg
, payload
->data
, sizeof(msg
));
1964 msg
.major
= be32toh(msg
.major
);
1965 msg
.minor
= be32toh(msg
.minor
);
1967 memset(&reply
, 0, sizeof(reply
));
1968 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1969 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1971 /* Major versions must be the same */
1972 if (reply
.major
!= msg
.major
) {
1973 DBG("Incompatible major versions (%u vs %u), deleting session",
1974 reply
.major
, msg
.major
);
1978 conn
->major
= reply
.major
;
1979 /* We adapt to the lowest compatible version */
1980 if (reply
.minor
<= msg
.minor
) {
1981 conn
->minor
= reply
.minor
;
1983 conn
->minor
= msg
.minor
;
1986 reply
.major
= htobe32(reply
.major
);
1987 reply
.minor
= htobe32(reply
.minor
);
1988 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1990 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1991 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2004 DBG("Version check done using protocol %u.%u", conn
->major
,
2012 * Check for data pending for a given stream id from the session daemon.
2014 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2015 struct relay_connection
*conn
,
2016 const struct lttng_buffer_view
*payload
)
2018 struct relay_session
*session
= conn
->session
;
2019 struct lttcomm_relayd_data_pending msg
;
2020 struct lttcomm_relayd_generic_reply reply
;
2021 struct relay_stream
*stream
;
2025 DBG("Data pending command received");
2027 if (!session
|| !conn
->version_check_done
) {
2028 ERR("Trying to check for data before version check");
2030 goto end_no_session
;
2033 if (payload
->size
< sizeof(msg
)) {
2034 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2035 sizeof(msg
), payload
->size
);
2037 goto end_no_session
;
2039 memcpy(&msg
, payload
->data
, sizeof(msg
));
2040 msg
.stream_id
= be64toh(msg
.stream_id
);
2041 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2043 stream
= stream_get_by_id(msg
.stream_id
);
2044 if (stream
== NULL
) {
2049 pthread_mutex_lock(&stream
->lock
);
2051 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2052 " and last_seq %" PRIu64
, msg
.stream_id
,
2053 stream
->prev_seq
, msg
.last_net_seq_num
);
2055 /* Avoid wrapping issue */
2056 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2057 /* Data has in fact been written and is NOT pending */
2060 /* Data still being streamed thus pending */
2064 stream
->data_pending_check_done
= true;
2065 pthread_mutex_unlock(&stream
->lock
);
2070 memset(&reply
, 0, sizeof(reply
));
2071 reply
.ret_code
= htobe32(ret
);
2072 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2073 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2074 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2084 * Wait for the control socket to reach a quiescent state.
2086 * Note that for now, when receiving this command from the session
2087 * daemon, this means that every subsequent commands or data received on
2088 * the control socket has been handled. So, this is why we simply return
2091 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2092 struct relay_connection
*conn
,
2093 const struct lttng_buffer_view
*payload
)
2097 struct relay_stream
*stream
;
2098 struct lttcomm_relayd_quiescent_control msg
;
2099 struct lttcomm_relayd_generic_reply reply
;
2101 DBG("Checking quiescent state on control socket");
2103 if (!conn
->session
|| !conn
->version_check_done
) {
2104 ERR("Trying to check for data before version check");
2106 goto end_no_session
;
2109 if (payload
->size
< sizeof(msg
)) {
2110 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2111 sizeof(msg
), payload
->size
);
2113 goto end_no_session
;
2115 memcpy(&msg
, payload
->data
, sizeof(msg
));
2116 msg
.stream_id
= be64toh(msg
.stream_id
);
2118 stream
= stream_get_by_id(msg
.stream_id
);
2122 pthread_mutex_lock(&stream
->lock
);
2123 stream
->data_pending_check_done
= true;
2124 pthread_mutex_unlock(&stream
->lock
);
2126 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2129 memset(&reply
, 0, sizeof(reply
));
2130 reply
.ret_code
= htobe32(LTTNG_OK
);
2131 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2132 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2133 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2145 * Initialize a data pending command. This means that a consumer is about
2146 * to ask for data pending for each stream it holds. Simply iterate over
2147 * all streams of a session and set the data_pending_check_done flag.
2149 * This command returns to the client a LTTNG_OK code.
2151 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2152 struct relay_connection
*conn
,
2153 const struct lttng_buffer_view
*payload
)
2157 struct lttng_ht_iter iter
;
2158 struct lttcomm_relayd_begin_data_pending msg
;
2159 struct lttcomm_relayd_generic_reply reply
;
2160 struct relay_stream
*stream
;
2165 DBG("Init streams for data pending");
2167 if (!conn
->session
|| !conn
->version_check_done
) {
2168 ERR("Trying to check for data before version check");
2170 goto end_no_session
;
2173 if (payload
->size
< sizeof(msg
)) {
2174 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2175 sizeof(msg
), payload
->size
);
2177 goto end_no_session
;
2179 memcpy(&msg
, payload
->data
, sizeof(msg
));
2180 msg
.session_id
= be64toh(msg
.session_id
);
2183 * Iterate over all streams to set the begin data pending flag.
2184 * For now, the streams are indexed by stream handle so we have
2185 * to iterate over all streams to find the one associated with
2186 * the right session_id.
2189 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2191 if (!stream_get(stream
)) {
2194 if (stream
->trace
->session
->id
== msg
.session_id
) {
2195 pthread_mutex_lock(&stream
->lock
);
2196 stream
->data_pending_check_done
= false;
2197 pthread_mutex_unlock(&stream
->lock
);
2198 DBG("Set begin data pending flag to stream %" PRIu64
,
2199 stream
->stream_handle
);
2205 memset(&reply
, 0, sizeof(reply
));
2206 /* All good, send back reply. */
2207 reply
.ret_code
= htobe32(LTTNG_OK
);
2209 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2210 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2211 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2223 * End data pending command. This will check, for a given session id, if
2224 * each stream associated with it has its data_pending_check_done flag
2225 * set. If not, this means that the client lost track of the stream but
2226 * the data is still being streamed on our side. In this case, we inform
2227 * the client that data is in flight.
2229 * Return to the client if there is data in flight or not with a ret_code.
2231 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2232 struct relay_connection
*conn
,
2233 const struct lttng_buffer_view
*payload
)
2237 struct lttng_ht_iter iter
;
2238 struct lttcomm_relayd_end_data_pending msg
;
2239 struct lttcomm_relayd_generic_reply reply
;
2240 struct relay_stream
*stream
;
2241 uint32_t is_data_inflight
= 0;
2243 DBG("End data pending command");
2245 if (!conn
->session
|| !conn
->version_check_done
) {
2246 ERR("Trying to check for data before version check");
2248 goto end_no_session
;
2251 if (payload
->size
< sizeof(msg
)) {
2252 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2253 sizeof(msg
), payload
->size
);
2255 goto end_no_session
;
2257 memcpy(&msg
, payload
->data
, sizeof(msg
));
2258 msg
.session_id
= be64toh(msg
.session_id
);
2261 * Iterate over all streams to see if the begin data pending
2265 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2267 if (!stream_get(stream
)) {
2270 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2274 pthread_mutex_lock(&stream
->lock
);
2275 if (!stream
->data_pending_check_done
) {
2276 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2277 is_data_inflight
= 1;
2278 DBG("Data is still in flight for stream %" PRIu64
,
2279 stream
->stream_handle
);
2280 pthread_mutex_unlock(&stream
->lock
);
2285 pthread_mutex_unlock(&stream
->lock
);
2290 memset(&reply
, 0, sizeof(reply
));
2291 /* All good, send back reply. */
2292 reply
.ret_code
= htobe32(is_data_inflight
);
2294 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2295 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2296 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2308 * Receive an index for a specific stream.
2310 * Return 0 on success else a negative value.
2312 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2313 struct relay_connection
*conn
,
2314 const struct lttng_buffer_view
*payload
)
2318 struct relay_session
*session
= conn
->session
;
2319 struct lttcomm_relayd_index index_info
;
2320 struct relay_index
*index
;
2321 struct lttcomm_relayd_generic_reply reply
;
2322 struct relay_stream
*stream
;
2327 DBG("Relay receiving index");
2329 if (!session
|| !conn
->version_check_done
) {
2330 ERR("Trying to close a stream before version check");
2332 goto end_no_session
;
2335 msg_len
= lttcomm_relayd_index_len(
2336 lttng_to_index_major(conn
->major
, conn
->minor
),
2337 lttng_to_index_minor(conn
->major
, conn
->minor
));
2338 if (payload
->size
< msg_len
) {
2339 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2340 msg_len
, payload
->size
);
2342 goto end_no_session
;
2344 memcpy(&index_info
, payload
->data
, msg_len
);
2345 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2346 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2347 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2348 index_info
.content_size
= be64toh(index_info
.content_size
);
2349 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2350 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2351 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2352 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2354 if (conn
->minor
>= 8) {
2355 index_info
.stream_instance_id
=
2356 be64toh(index_info
.stream_instance_id
);
2357 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2360 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2362 ERR("stream_get_by_id not found");
2366 pthread_mutex_lock(&stream
->lock
);
2368 /* Live beacon handling */
2369 if (index_info
.packet_size
== 0) {
2370 DBG("Received live beacon for stream %" PRIu64
,
2371 stream
->stream_handle
);
2374 * Only flag a stream inactive when it has already
2375 * received data and no indexes are in flight.
2377 if (stream
->index_received_seqcount
> 0
2378 && stream
->indexes_in_flight
== 0) {
2379 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2382 goto end_stream_put
;
2384 stream
->beacon_ts_end
= -1ULL;
2387 if (stream
->ctf_stream_id
== -1ULL) {
2388 stream
->ctf_stream_id
= index_info
.stream_id
;
2390 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2393 ERR("relay_index_get_by_id_or_create index NULL");
2394 goto end_stream_put
;
2396 if (set_index_control_data(index
, &index_info
, conn
)) {
2397 ERR("set_index_control_data error");
2398 relay_index_put(index
);
2400 goto end_stream_put
;
2402 ret
= relay_index_try_flush(index
);
2404 tracefile_array_commit_seq(stream
->tfa
);
2405 stream
->index_received_seqcount
++;
2406 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2407 } else if (ret
> 0) {
2411 ERR("relay_index_try_flush error %d", ret
);
2412 relay_index_put(index
);
2417 pthread_mutex_unlock(&stream
->lock
);
2422 memset(&reply
, 0, sizeof(reply
));
2424 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2426 reply
.ret_code
= htobe32(LTTNG_OK
);
2428 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2429 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2430 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2439 * Receive the streams_sent message.
2441 * Return 0 on success else a negative value.
2443 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2444 struct relay_connection
*conn
,
2445 const struct lttng_buffer_view
*payload
)
2449 struct lttcomm_relayd_generic_reply reply
;
2453 DBG("Relay receiving streams_sent");
2455 if (!conn
->session
|| !conn
->version_check_done
) {
2456 ERR("Trying to close a stream before version check");
2458 goto end_no_session
;
2462 * Publish every pending stream in the connection recv list which are
2463 * now ready to be used by the viewer.
2465 publish_connection_local_streams(conn
);
2467 memset(&reply
, 0, sizeof(reply
));
2468 reply
.ret_code
= htobe32(LTTNG_OK
);
2469 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2470 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2471 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2484 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2485 * rotation feature (not the tracefile rotation feature).
2487 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2488 struct relay_connection
*conn
,
2489 const struct lttng_buffer_view
*payload
)
2493 struct relay_session
*session
= conn
->session
;
2494 struct lttcomm_relayd_rotate_stream stream_info
;
2495 struct lttcomm_relayd_generic_reply reply
;
2496 struct relay_stream
*stream
;
2499 struct lttng_buffer_view new_path_view
;
2501 DBG("Rotate stream received");
2503 if (!session
|| !conn
->version_check_done
) {
2504 ERR("Trying to rotate a stream before version check");
2509 if (session
->major
== 2 && session
->minor
< 11) {
2510 ERR("Unsupported feature before 2.11");
2515 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2517 if (payload
->size
< header_len
) {
2518 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2519 header_len
, payload
->size
);
2524 memcpy(&stream_info
, payload
->data
, header_len
);
2526 /* Convert to host */
2527 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2528 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2529 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2530 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2532 path_len
= stream_info
.pathname_length
;
2533 if (payload
->size
< header_len
+ path_len
) {
2534 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2535 header_len
+ path_len
, payload
->size
);
2540 /* Ensure it fits in local filename length. */
2541 if (path_len
>= LTTNG_PATH_MAX
) {
2542 ret
= -ENAMETOOLONG
;
2543 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2544 path_len
, LTTNG_PATH_MAX
);
2548 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2549 stream_info
.pathname_length
);
2551 stream
= stream_get_by_id(stream_info
.stream_id
);
2557 pthread_mutex_lock(&stream
->lock
);
2560 * Update the trace path (just the folder, the stream name does not
2563 free(stream
->path_name
);
2564 stream
->path_name
= create_output_path(new_path_view
.data
);
2565 if (!stream
->path_name
) {
2566 ERR("Failed to create a new output path");
2568 goto end_stream_unlock
;
2570 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2573 ERR("relay creating output directory");
2575 goto end_stream_unlock
;
2578 assert(stream
->current_chunk_id
.is_set
);
2579 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2581 if (stream
->is_metadata
) {
2583 * The metadata stream is sent only over the control connection
2584 * so we know we have all the data to perform the stream
2587 ret
= do_rotate_stream(stream
);
2589 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2590 ret
= try_rotate_stream(stream
);
2593 goto end_stream_unlock
;
2597 pthread_mutex_unlock(&stream
->lock
);
2600 memset(&reply
, 0, sizeof(reply
));
2602 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2604 reply
.ret_code
= htobe32(LTTNG_OK
);
2606 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2607 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2608 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2609 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2619 * relay_mkdir: Create a folder on the disk.
2621 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2622 struct relay_connection
*conn
,
2623 const struct lttng_buffer_view
*payload
)
2626 struct relay_session
*session
= conn
->session
;
2627 struct lttcomm_relayd_mkdir path_info_header
;
2628 struct lttcomm_relayd_generic_reply reply
;
2632 struct lttng_buffer_view path_view
;
2634 if (!session
|| !conn
->version_check_done
) {
2635 ERR("Trying to create a directory before version check");
2637 goto end_no_session
;
2640 if (session
->major
== 2 && session
->minor
< 11) {
2642 * This client is not supposed to use this command since
2643 * it predates its introduction.
2645 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2647 goto end_no_session
;
2650 header_len
= sizeof(path_info_header
);
2651 if (payload
->size
< header_len
) {
2652 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2653 header_len
, payload
->size
);
2655 goto end_no_session
;
2658 memcpy(&path_info_header
, payload
->data
, header_len
);
2660 path_info_header
.length
= be32toh(path_info_header
.length
);
2662 if (payload
->size
< header_len
+ path_info_header
.length
) {
2663 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2664 header_len
+ path_info_header
.length
, payload
->size
);
2666 goto end_no_session
;
2669 /* Ensure that it fits in local path length. */
2670 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2671 ret
= -ENAMETOOLONG
;
2672 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2673 path_info_header
.length
, LTTNG_PATH_MAX
);
2677 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2678 path_info_header
.length
);
2680 path
= create_output_path(path_view
.data
);
2682 ERR("Failed to create output path");
2687 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2689 ERR("relay creating output directory");
2696 memset(&reply
, 0, sizeof(reply
));
2698 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2700 reply
.ret_code
= htobe32(LTTNG_OK
);
2702 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2703 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2704 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2713 static int validate_rotate_rename_path_length(const char *path_type
,
2714 uint32_t path_length
)
2718 if (path_length
> LTTNG_PATH_MAX
) {
2719 ret
= -ENAMETOOLONG
;
2720 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2721 path_type
, path_length
, LTTNG_PATH_MAX
);
2722 } else if (path_length
== 0) {
2724 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2730 * relay_rotate_rename: rename the trace folder after a rotation is
2731 * completed. We are not closing any fd here, just moving the folder, so it
2732 * works even if data is still in-flight.
2734 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2735 struct relay_connection
*conn
,
2736 const struct lttng_buffer_view
*payload
)
2740 struct relay_session
*session
= conn
->session
;
2741 struct lttcomm_relayd_generic_reply reply
;
2742 struct lttcomm_relayd_rotate_rename header
;
2744 size_t received_paths_size
;
2745 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2746 struct lttng_buffer_view old_path_view
;
2747 struct lttng_buffer_view new_path_view
;
2749 if (!session
|| !conn
->version_check_done
) {
2750 ERR("Trying to rename a trace folder before version check");
2755 if (session
->major
== 2 && session
->minor
< 11) {
2756 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2761 header_len
= sizeof(header
);
2762 if (payload
->size
< header_len
) {
2763 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2764 header_len
, payload
->size
);
2769 memcpy(&header
, payload
->data
, header_len
);
2771 header
.old_path_length
= be32toh(header
.old_path_length
);
2772 header
.new_path_length
= be32toh(header
.new_path_length
);
2773 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2775 if (payload
->size
< header_len
+ received_paths_size
) {
2776 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2777 header_len
, payload
->size
);
2782 /* Ensure the paths don't exceed their allowed size. */
2783 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2787 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2792 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2793 header
.old_path_length
);
2794 new_path_view
= lttng_buffer_view_from_view(payload
,
2795 header_len
+ header
.old_path_length
,
2796 header
.new_path_length
);
2798 /* Validate that both paths received are NULL terminated. */
2799 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2800 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2804 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2805 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2810 complete_old_path
= create_output_path(old_path_view
.data
);
2811 if (!complete_old_path
) {
2812 ERR("Failed to build old output path in rotate_rename command");
2817 complete_new_path
= create_output_path(new_path_view
.data
);
2818 if (!complete_new_path
) {
2819 ERR("Failed to build new output path in rotate_rename command");
2824 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2827 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2833 * If a domain has not yet created its channel, the domain-specific
2834 * folder might not exist, but this is not an error.
2836 ret
= rename(complete_old_path
, complete_new_path
);
2837 if (ret
< 0 && errno
!= ENOENT
) {
2838 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2839 complete_old_path
, complete_new_path
);
2845 memset(&reply
, 0, sizeof(reply
));
2847 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2849 reply
.ret_code
= htobe32(LTTNG_OK
);
2851 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2853 if (send_ret
< sizeof(reply
)) {
2854 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2860 free(complete_old_path
);
2861 free(complete_new_path
);
2866 * Check if all the streams in the session have completed the last rotation.
2867 * The chunk_id value is used to distinguish the cases where a stream was
2868 * closed on the consumerd before the rotation started but it still active on
2869 * the relayd, and the case where a stream appeared on the consumerd/relayd
2870 * after the last rotation started (in that case, it is already writing in the
2871 * new chunk folder).
2874 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2875 struct relay_connection
*conn
,
2876 const struct lttng_buffer_view
*payload
)
2878 struct relay_session
*session
= conn
->session
;
2879 struct lttcomm_relayd_rotate_pending msg
;
2880 struct lttcomm_relayd_rotate_pending_reply reply
;
2881 struct lttng_ht_iter iter
;
2882 struct relay_stream
*stream
;
2886 bool rotate_pending
= false;
2888 DBG("Rotate pending command received");
2890 if (!session
|| !conn
->version_check_done
) {
2891 ERR("Trying to check for data before version check");
2896 if (session
->major
== 2 && session
->minor
< 11) {
2897 ERR("Unsupported feature before 2.11");
2902 if (payload
->size
< sizeof(msg
)) {
2903 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2904 sizeof(msg
), payload
->size
);
2909 memcpy(&msg
, payload
->data
, sizeof(msg
));
2911 chunk_id
= be64toh(msg
.chunk_id
);
2913 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2914 session
->session_name
, chunk_id
);
2917 * Iterate over all the streams in the session and check if they are
2918 * still waiting for data to perform their rotation.
2921 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2923 if (!stream_get(stream
)) {
2926 if (stream
->trace
->session
!= session
) {
2930 pthread_mutex_lock(&stream
->lock
);
2931 if (stream
->rotate_at_seq_num
!= -1ULL) {
2932 /* We have not yet performed the rotation. */
2933 rotate_pending
= true;
2934 DBG("Stream %" PRIu64
" is still rotating",
2935 stream
->stream_handle
);
2936 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
2938 * Stream closed on the consumer but still active on the
2941 rotate_pending
= true;
2942 DBG("Stream %" PRIu64
" did not exist on the consumer "
2943 "when the last rotation started, but is"
2944 "still waiting for data before getting"
2946 stream
->stream_handle
);
2948 pthread_mutex_unlock(&stream
->lock
);
2950 if (rotate_pending
) {
2957 memset(&reply
, 0, sizeof(reply
));
2958 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
2959 reply
.is_pending
= (uint8_t) !!rotate_pending
;
2960 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2962 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2963 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
2972 #define DBG_CMD(cmd_name, conn) \
2973 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2975 static int relay_process_control_command(struct relay_connection
*conn
,
2976 const struct lttcomm_relayd_hdr
*header
,
2977 const struct lttng_buffer_view
*payload
)
2981 switch (header
->cmd
) {
2982 case RELAYD_CREATE_SESSION
:
2983 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2984 ret
= relay_create_session(header
, conn
, payload
);
2986 case RELAYD_ADD_STREAM
:
2987 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2988 ret
= relay_add_stream(header
, conn
, payload
);
2990 case RELAYD_START_DATA
:
2991 DBG_CMD("RELAYD_START_DATA", conn
);
2992 ret
= relay_start(header
, conn
, payload
);
2994 case RELAYD_SEND_METADATA
:
2995 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2996 ret
= relay_recv_metadata(header
, conn
, payload
);
2998 case RELAYD_VERSION
:
2999 DBG_CMD("RELAYD_VERSION", conn
);
3000 ret
= relay_send_version(header
, conn
, payload
);
3002 case RELAYD_CLOSE_STREAM
:
3003 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3004 ret
= relay_close_stream(header
, conn
, payload
);
3006 case RELAYD_DATA_PENDING
:
3007 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3008 ret
= relay_data_pending(header
, conn
, payload
);
3010 case RELAYD_QUIESCENT_CONTROL
:
3011 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3012 ret
= relay_quiescent_control(header
, conn
, payload
);
3014 case RELAYD_BEGIN_DATA_PENDING
:
3015 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3016 ret
= relay_begin_data_pending(header
, conn
, payload
);
3018 case RELAYD_END_DATA_PENDING
:
3019 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3020 ret
= relay_end_data_pending(header
, conn
, payload
);
3022 case RELAYD_SEND_INDEX
:
3023 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3024 ret
= relay_recv_index(header
, conn
, payload
);
3026 case RELAYD_STREAMS_SENT
:
3027 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3028 ret
= relay_streams_sent(header
, conn
, payload
);
3030 case RELAYD_RESET_METADATA
:
3031 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3032 ret
= relay_reset_metadata(header
, conn
, payload
);
3034 case RELAYD_ROTATE_STREAM
:
3035 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3036 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3038 case RELAYD_ROTATE_RENAME
:
3039 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3040 ret
= relay_rotate_rename(header
, conn
, payload
);
3042 case RELAYD_ROTATE_PENDING
:
3043 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3044 ret
= relay_rotate_pending(header
, conn
, payload
);
3047 DBG_CMD("RELAYD_MKDIR", conn
);
3048 ret
= relay_mkdir(header
, conn
, payload
);
3050 case RELAYD_UPDATE_SYNC_INFO
:
3052 ERR("Received unknown command (%u)", header
->cmd
);
3053 relay_unknown_command(conn
);
3062 static enum relay_connection_status
relay_process_control_receive_payload(
3063 struct relay_connection
*conn
)
3066 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3067 struct lttng_dynamic_buffer
*reception_buffer
=
3068 &conn
->protocol
.ctrl
.reception_buffer
;
3069 struct ctrl_connection_state_receive_payload
*state
=
3070 &conn
->protocol
.ctrl
.state
.receive_payload
;
3071 struct lttng_buffer_view payload_view
;
3073 if (state
->left_to_receive
== 0) {
3074 /* Short-circuit for payload-less commands. */
3075 goto reception_complete
;
3078 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3079 reception_buffer
->data
+ state
->received
,
3080 state
->left_to_receive
, MSG_DONTWAIT
);
3082 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3083 PERROR("Unable to receive command payload on sock %d",
3085 status
= RELAY_CONNECTION_STATUS_ERROR
;
3088 } else if (ret
== 0) {
3089 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3090 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3095 assert(ret
<= state
->left_to_receive
);
3097 state
->left_to_receive
-= ret
;
3098 state
->received
+= ret
;
3100 if (state
->left_to_receive
> 0) {
3102 * Can't transition to the protocol's next state, wait to
3103 * receive the rest of the header.
3105 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3106 state
->received
, state
->left_to_receive
,
3112 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3113 conn
->sock
->fd
, state
->received
);
3115 * The payload required to process the command has been received.
3116 * A view to the reception buffer is forwarded to the various
3117 * commands and the state of the control is reset on success.
3119 * Commands are responsible for sending their reply to the peer.
3121 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3123 ret
= relay_process_control_command(conn
,
3124 &state
->header
, &payload_view
);
3126 status
= RELAY_CONNECTION_STATUS_ERROR
;
3130 ret
= connection_reset_protocol_state(conn
);
3132 status
= RELAY_CONNECTION_STATUS_ERROR
;
3138 static enum relay_connection_status
relay_process_control_receive_header(
3139 struct relay_connection
*conn
)
3142 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3143 struct lttcomm_relayd_hdr header
;
3144 struct lttng_dynamic_buffer
*reception_buffer
=
3145 &conn
->protocol
.ctrl
.reception_buffer
;
3146 struct ctrl_connection_state_receive_header
*state
=
3147 &conn
->protocol
.ctrl
.state
.receive_header
;
3149 assert(state
->left_to_receive
!= 0);
3151 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3152 reception_buffer
->data
+ state
->received
,
3153 state
->left_to_receive
, MSG_DONTWAIT
);
3155 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3156 PERROR("Unable to receive control command header on sock %d",
3158 status
= RELAY_CONNECTION_STATUS_ERROR
;
3161 } else if (ret
== 0) {
3162 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3163 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3168 assert(ret
<= state
->left_to_receive
);
3170 state
->left_to_receive
-= ret
;
3171 state
->received
+= ret
;
3173 if (state
->left_to_receive
> 0) {
3175 * Can't transition to the protocol's next state, wait to
3176 * receive the rest of the header.
3178 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3179 state
->received
, state
->left_to_receive
,
3184 /* Transition to next state: receiving the command's payload. */
3185 conn
->protocol
.ctrl
.state_id
=
3186 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3187 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3188 header
.circuit_id
= be64toh(header
.circuit_id
);
3189 header
.data_size
= be64toh(header
.data_size
);
3190 header
.cmd
= be32toh(header
.cmd
);
3191 header
.cmd_version
= be32toh(header
.cmd_version
);
3192 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3193 &header
, sizeof(header
));
3195 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3196 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3199 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3200 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3202 status
= RELAY_CONNECTION_STATUS_ERROR
;
3206 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3208 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3209 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3212 status
= RELAY_CONNECTION_STATUS_ERROR
;
3216 if (header
.data_size
== 0) {
3218 * Manually invoke the next state as the poll loop
3219 * will not wake-up to allow us to proceed further.
3221 status
= relay_process_control_receive_payload(conn
);
3228 * Process the commands received on the control socket
3230 static enum relay_connection_status
relay_process_control(
3231 struct relay_connection
*conn
)
3233 enum relay_connection_status status
;
3235 switch (conn
->protocol
.ctrl
.state_id
) {
3236 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3237 status
= relay_process_control_receive_header(conn
);
3239 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3240 status
= relay_process_control_receive_payload(conn
);
3243 ERR("Unknown control connection protocol state encountered.");
3251 * Handle index for a data stream.
3253 * Called with the stream lock held.
3255 * Return 0 on success else a negative value.
3257 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3258 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3261 uint64_t data_offset
;
3262 struct relay_index
*index
;
3264 /* Get data offset because we are about to update the index. */
3265 data_offset
= htobe64(stream
->tracefile_size_current
);
3267 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3268 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3271 * Lookup for an existing index for that stream id/sequence
3272 * number. If it exists, the control thread has already received the
3273 * data for it, thus we need to write it to disk.
3275 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3281 if (rotate_index
|| !stream
->index_file
) {
3282 ret
= create_rotate_index_file(stream
);
3284 ERR("Failed to rotate index");
3285 /* Put self-ref for this index due to error. */
3286 relay_index_put(index
);
3292 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3294 /* Put self-ref for this index due to error. */
3295 relay_index_put(index
);
3300 ret
= relay_index_try_flush(index
);
3302 tracefile_array_commit_seq(stream
->tfa
);
3303 stream
->index_received_seqcount
++;
3305 } else if (ret
> 0) {
3306 index
->total_size
= total_size
;
3310 /* Put self-ref for this index due to error. */
3311 relay_index_put(index
);
3319 static enum relay_connection_status
relay_process_data_receive_header(
3320 struct relay_connection
*conn
)
3323 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3324 struct data_connection_state_receive_header
*state
=
3325 &conn
->protocol
.data
.state
.receive_header
;
3326 struct lttcomm_relayd_data_hdr header
;
3327 struct relay_stream
*stream
;
3329 assert(state
->left_to_receive
!= 0);
3331 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3332 state
->header_reception_buffer
+ state
->received
,
3333 state
->left_to_receive
, MSG_DONTWAIT
);
3335 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3336 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3337 status
= RELAY_CONNECTION_STATUS_ERROR
;
3340 } else if (ret
== 0) {
3341 /* Orderly shutdown. Not necessary to print an error. */
3342 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3343 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3348 assert(ret
<= state
->left_to_receive
);
3350 state
->left_to_receive
-= ret
;
3351 state
->received
+= ret
;
3353 if (state
->left_to_receive
> 0) {
3355 * Can't transition to the protocol's next state, wait to
3356 * receive the rest of the header.
3358 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3359 state
->received
, state
->left_to_receive
,
3364 /* Transition to next state: receiving the payload. */
3365 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3367 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3368 header
.circuit_id
= be64toh(header
.circuit_id
);
3369 header
.stream_id
= be64toh(header
.stream_id
);
3370 header
.data_size
= be32toh(header
.data_size
);
3371 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3372 header
.padding_size
= be32toh(header
.padding_size
);
3373 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3375 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3377 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3378 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3380 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3381 conn
->sock
->fd
, header
.circuit_id
,
3382 header
.stream_id
, header
.data_size
,
3383 header
.net_seq_num
, header
.padding_size
);
3385 stream
= stream_get_by_id(header
.stream_id
);
3387 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3389 /* Protocol error. */
3390 status
= RELAY_CONNECTION_STATUS_ERROR
;
3394 pthread_mutex_lock(&stream
->lock
);
3396 /* Check if a rotation is needed. */
3397 if (stream
->tracefile_size
> 0 &&
3398 (stream
->tracefile_size_current
+ header
.data_size
) >
3399 stream
->tracefile_size
) {
3400 uint64_t old_id
, new_id
;
3402 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3403 tracefile_array_file_rotate(stream
->tfa
);
3405 /* new_id is updated by utils_rotate_stream_file. */
3408 ret
= utils_rotate_stream_file(stream
->path_name
,
3409 stream
->channel_name
, stream
->tracefile_size
,
3410 stream
->tracefile_count
, -1,
3411 -1, stream
->stream_fd
->fd
,
3412 &new_id
, &stream
->stream_fd
->fd
);
3414 ERR("Failed to rotate stream output file");
3415 status
= RELAY_CONNECTION_STATUS_ERROR
;
3416 goto end_stream_unlock
;
3420 * Reset current size because we just performed a stream
3423 stream
->tracefile_size_current
= 0;
3424 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3428 pthread_mutex_unlock(&stream
->lock
);
3434 static enum relay_connection_status
relay_process_data_receive_payload(
3435 struct relay_connection
*conn
)
3438 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3439 struct relay_stream
*stream
;
3440 struct data_connection_state_receive_payload
*state
=
3441 &conn
->protocol
.data
.state
.receive_payload
;
3442 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3443 char data_buffer
[chunk_size
];
3444 bool partial_recv
= false;
3445 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3446 uint64_t left_to_receive
= state
->left_to_receive
;
3447 struct relay_session
*session
;
3449 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3450 state
->header
.stream_id
, state
->header
.net_seq_num
,
3451 state
->received
, left_to_receive
);
3453 stream
= stream_get_by_id(state
->header
.stream_id
);
3455 /* Protocol error. */
3456 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3457 state
->header
.stream_id
);
3458 status
= RELAY_CONNECTION_STATUS_ERROR
;
3462 pthread_mutex_lock(&stream
->lock
);
3463 session
= stream
->trace
->session
;
3464 if (!conn
->session
) {
3465 ret
= connection_set_session(conn
, session
);
3467 status
= RELAY_CONNECTION_STATUS_ERROR
;
3468 goto end_stream_unlock
;
3473 * The size of the "chunk" received on any iteration is bounded by:
3474 * - the data left to receive,
3475 * - the data immediately available on the socket,
3476 * - the on-stack data buffer
3478 while (left_to_receive
> 0 && !partial_recv
) {
3480 size_t recv_size
= min(left_to_receive
, chunk_size
);
3482 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3483 recv_size
, MSG_DONTWAIT
);
3485 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3486 PERROR("Socket %d error", conn
->sock
->fd
);
3487 status
= RELAY_CONNECTION_STATUS_ERROR
;
3489 goto end_stream_unlock
;
3490 } else if (ret
== 0) {
3491 /* No more data ready to be consumed on socket. */
3492 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3493 state
->header
.stream_id
);
3494 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3496 } else if (ret
< (int) recv_size
) {
3498 * All the data available on the socket has been
3501 partial_recv
= true;
3506 /* Write data to stream output fd. */
3507 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3509 if (write_ret
< (ssize_t
) recv_size
) {
3510 ERR("Relay error writing data to file");
3511 status
= RELAY_CONNECTION_STATUS_ERROR
;
3512 goto end_stream_unlock
;
3515 left_to_receive
-= recv_size
;
3516 state
->received
+= recv_size
;
3517 state
->left_to_receive
= left_to_receive
;
3519 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3520 write_ret
, stream
->stream_handle
);
3523 if (state
->left_to_receive
> 0) {
3525 * Did not receive all the data expected, wait for more data to
3526 * become available on the socket.
3528 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3529 state
->header
.stream_id
, state
->received
,
3530 state
->left_to_receive
);
3531 goto end_stream_unlock
;
3534 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3535 state
->header
.padding_size
);
3536 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3537 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3538 stream
->stream_handle
,
3539 state
->header
.net_seq_num
, ret
);
3540 status
= RELAY_CONNECTION_STATUS_ERROR
;
3541 goto end_stream_unlock
;
3545 if (session
->minor
>= 4 && !session
->snapshot
) {
3546 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3547 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3549 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3550 stream
->stream_handle
,
3551 state
->header
.net_seq_num
, ret
);
3552 status
= RELAY_CONNECTION_STATUS_ERROR
;
3553 goto end_stream_unlock
;
3557 stream
->tracefile_size_current
+= state
->header
.data_size
+
3558 state
->header
.padding_size
;
3560 if (stream
->prev_seq
== -1ULL) {
3563 if (index_flushed
) {
3564 stream
->pos_after_last_complete_data_index
=
3565 stream
->tracefile_size_current
;
3568 stream
->prev_seq
= state
->header
.net_seq_num
;
3571 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3572 * contents of *state which are aliased (union) to the same location as
3573 * the new state. Don't use it beyond this point.
3575 connection_reset_protocol_state(conn
);
3578 ret
= try_rotate_stream(stream
);
3580 status
= RELAY_CONNECTION_STATUS_ERROR
;
3581 goto end_stream_unlock
;
3585 close_requested
= stream
->close_requested
;
3586 pthread_mutex_unlock(&stream
->lock
);
3587 if (close_requested
&& left_to_receive
== 0) {
3588 try_stream_close(stream
);
3592 pthread_mutex_lock(&session
->lock
);
3593 uatomic_set(&session
->new_streams
, 1);
3594 pthread_mutex_unlock(&session
->lock
);
3603 * relay_process_data: Process the data received on the data socket
3605 static enum relay_connection_status
relay_process_data(
3606 struct relay_connection
*conn
)
3608 enum relay_connection_status status
;
3610 switch (conn
->protocol
.data
.state_id
) {
3611 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3612 status
= relay_process_data_receive_header(conn
);
3614 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3615 status
= relay_process_data_receive_payload(conn
);
3618 ERR("Unexpected data connection communication state.");
3625 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3629 (void) lttng_poll_del(events
, pollfd
);
3631 ret
= close(pollfd
);
3633 ERR("Closing pollfd %d", pollfd
);
3637 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3638 int pollfd
, struct relay_connection
*conn
)
3640 const char *type_str
;
3642 switch (conn
->type
) {
3647 type_str
= "Control";
3649 case RELAY_VIEWER_COMMAND
:
3650 type_str
= "Viewer Command";
3652 case RELAY_VIEWER_NOTIFICATION
:
3653 type_str
= "Viewer Notification";
3656 type_str
= "Unknown";
3658 cleanup_connection_pollfd(events
, pollfd
);
3659 connection_put(conn
);
3660 DBG("%s connection closed with %d", type_str
, pollfd
);
3664 * This thread does the actual work
3666 static void *relay_thread_worker(void *data
)
3668 int ret
, err
= -1, last_seen_data_fd
= -1;
3670 struct lttng_poll_event events
;
3671 struct lttng_ht
*relay_connections_ht
;
3672 struct lttng_ht_iter iter
;
3673 struct relay_connection
*destroy_conn
= NULL
;
3675 DBG("[thread] Relay worker started");
3677 rcu_register_thread();
3679 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3681 if (testpoint(relayd_thread_worker
)) {
3682 goto error_testpoint
;
3685 health_code_update();
3687 /* table of connections indexed on socket */
3688 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3689 if (!relay_connections_ht
) {
3690 goto relay_connections_ht_error
;
3693 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3695 goto error_poll_create
;
3698 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3705 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3707 health_code_update();
3709 /* Infinite blocking call, waiting for transmission */
3710 DBG3("Relayd worker thread polling...");
3711 health_poll_entry();
3712 ret
= lttng_poll_wait(&events
, -1);
3716 * Restart interrupted system call.
3718 if (errno
== EINTR
) {
3727 * Process control. The control connection is
3728 * prioritized so we don't starve it with high
3729 * throughput tracing data on the data connection.
3731 for (i
= 0; i
< nb_fd
; i
++) {
3732 /* Fetch once the poll data */
3733 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3734 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3736 health_code_update();
3740 * No activity for this FD (poll
3746 /* Thread quit pipe has been closed. Killing thread. */
3747 ret
= check_thread_quit_pipe(pollfd
, revents
);
3753 /* Inspect the relay conn pipe for new connection */
3754 if (pollfd
== relay_conn_pipe
[0]) {
3755 if (revents
& LPOLLIN
) {
3756 struct relay_connection
*conn
;
3758 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3762 lttng_poll_add(&events
, conn
->sock
->fd
,
3763 LPOLLIN
| LPOLLRDHUP
);
3764 connection_ht_add(relay_connections_ht
, conn
);
3765 DBG("Connection socket %d added", conn
->sock
->fd
);
3766 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3767 ERR("Relay connection pipe error");
3770 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3774 struct relay_connection
*ctrl_conn
;
3776 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3777 /* If not found, there is a synchronization issue. */
3780 if (ctrl_conn
->type
== RELAY_DATA
) {
3781 if (revents
& LPOLLIN
) {
3783 * Flag the last seen data fd not deleted. It will be
3784 * used as the last seen fd if any fd gets deleted in
3787 last_notdel_data_fd
= pollfd
;
3789 goto put_ctrl_connection
;
3791 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3793 if (revents
& LPOLLIN
) {
3794 enum relay_connection_status status
;
3796 status
= relay_process_control(ctrl_conn
);
3797 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3799 * On socket error flag the session as aborted to force
3800 * the cleanup of its stream otherwise it can leak
3801 * during the lifetime of the relayd.
3803 * This prevents situations in which streams can be
3804 * left opened because an index was received, the
3805 * control connection is closed, and the data
3806 * connection is closed (uncleanly) before the packet's
3809 * Since the control connection encountered an error,
3810 * it is okay to be conservative and close the
3811 * session right now as we can't rely on the protocol
3812 * being respected anymore.
3814 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3815 session_abort(ctrl_conn
->session
);
3818 /* Clear the connection on error or close. */
3819 relay_thread_close_connection(&events
,
3824 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3825 relay_thread_close_connection(&events
,
3827 if (last_seen_data_fd
== pollfd
) {
3828 last_seen_data_fd
= last_notdel_data_fd
;
3831 ERR("Unexpected poll events %u for control sock %d",
3833 connection_put(ctrl_conn
);
3836 put_ctrl_connection
:
3837 connection_put(ctrl_conn
);
3842 * The last loop handled a control request, go back to poll to make
3843 * sure we prioritise the control socket.
3849 if (last_seen_data_fd
>= 0) {
3850 for (i
= 0; i
< nb_fd
; i
++) {
3851 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3853 health_code_update();
3855 if (last_seen_data_fd
== pollfd
) {
3862 /* Process data connection. */
3863 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3864 /* Fetch the poll data. */
3865 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3866 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3867 struct relay_connection
*data_conn
;
3869 health_code_update();
3872 /* No activity for this FD (poll implementation). */
3876 /* Skip the command pipe. It's handled in the first loop. */
3877 if (pollfd
== relay_conn_pipe
[0]) {
3881 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3883 /* Skip it. Might be removed before. */
3886 if (data_conn
->type
== RELAY_CONTROL
) {
3887 goto put_data_connection
;
3889 assert(data_conn
->type
== RELAY_DATA
);
3891 if (revents
& LPOLLIN
) {
3892 enum relay_connection_status status
;
3894 status
= relay_process_data(data_conn
);
3895 /* Connection closed or error. */
3896 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3898 * On socket error flag the session as aborted to force
3899 * the cleanup of its stream otherwise it can leak
3900 * during the lifetime of the relayd.
3902 * This prevents situations in which streams can be
3903 * left opened because an index was received, the
3904 * control connection is closed, and the data
3905 * connection is closed (uncleanly) before the packet's
3908 * Since the data connection encountered an error,
3909 * it is okay to be conservative and close the
3910 * session right now as we can't rely on the protocol
3911 * being respected anymore.
3913 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3914 session_abort(data_conn
->session
);
3916 relay_thread_close_connection(&events
, pollfd
,
3919 * Every goto restart call sets the last seen fd where
3920 * here we don't really care since we gracefully
3921 * continue the loop after the connection is deleted.
3924 /* Keep last seen port. */
3925 last_seen_data_fd
= pollfd
;
3926 connection_put(data_conn
);
3929 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3930 relay_thread_close_connection(&events
, pollfd
,
3933 ERR("Unknown poll events %u for data sock %d",
3936 put_data_connection
:
3937 connection_put(data_conn
);
3939 last_seen_data_fd
= -1;
3942 /* Normal exit, no error */
3947 /* Cleanup remaining connection object. */
3949 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3952 health_code_update();
3954 session_abort(destroy_conn
->session
);
3957 * No need to grab another ref, because we own
3960 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3965 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3967 lttng_ht_destroy(relay_connections_ht
);
3968 relay_connections_ht_error
:
3969 /* Close relay conn pipes */
3970 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3973 DBG("Thread exited with error");
3975 DBG("Worker thread cleanup complete");
3979 ERR("Health error occurred in %s", __func__
);
3981 health_unregister(health_relayd
);
3982 rcu_unregister_thread();
3983 lttng_relay_stop_threads();
3988 * Create the relay command pipe to wake thread_manage_apps.
3989 * Closed in cleanup().
3991 static int create_relay_conn_pipe(void)
3993 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3994 "Relayd connection pipe", relay_conn_pipe
);
3998 int stdio_open(void *data
, int *fds
)
4000 fds
[0] = fileno(stdout
);
4001 fds
[1] = fileno(stderr
);
4006 int noop_close(void *data
, int *fds
)
4012 int track_stdio(void)
4015 const char *names
[] = { "stdout", "stderr" };
4017 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
4018 names
, 2, stdio_open
, NULL
);
4022 void untrack_stdio(void)
4024 int fds
[] = { fileno(stdout
), fileno(stderr
) };
4027 * noop_close is used since we don't really want to close
4028 * the stdio output fds; we merely want to stop tracking them.
4030 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
4031 fds
, 2, noop_close
, NULL
);
4037 int main(int argc
, char **argv
)
4039 int ret
= 0, retval
= 0;
4042 /* Parse arguments */
4044 if (set_options(argc
, argv
)) {
4049 if (set_signal_handler()) {
4054 ret
= fclose(stdin
);
4056 PERROR("Failed to close stdin");
4059 /* Try to create directory if -o, --output is specified. */
4060 if (opt_output_path
) {
4061 if (*opt_output_path
!= '/') {
4062 ERR("Please specify an absolute path for -o, --output PATH");
4067 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4070 ERR("Unable to create %s", opt_output_path
);
4077 if (opt_daemon
|| opt_background
) {
4078 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4087 * The RCU thread registration (and use, through the fd-tracker's
4088 * creation) is done after the daemonization to allow us to not
4089 * deal with liburcu's fork() management as the call RCU needs to
4092 rcu_register_thread();
4094 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
4095 if (!the_fd_tracker
) {
4100 ret
= track_stdio();
4106 /* Initialize thread health monitoring */
4107 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4108 if (!health_relayd
) {
4109 PERROR("health_app_create error");
4111 goto exit_health_app_create
;
4114 /* Create thread quit pipe */
4115 if (init_thread_quit_pipe()) {
4117 goto exit_init_data
;
4120 /* Setup the thread apps communication pipe. */
4121 if (create_relay_conn_pipe()) {
4123 goto exit_init_data
;
4126 /* Init relay command queue. */
4127 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4129 /* Initialize communication library */
4131 lttcomm_inet_init();
4133 /* tables of sessions indexed by session ID */
4134 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4137 goto exit_init_data
;
4140 /* tables of streams indexed by stream ID */
4141 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4142 if (!relay_streams_ht
) {
4144 goto exit_init_data
;
4147 /* tables of streams indexed by stream ID */
4148 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4149 if (!viewer_streams_ht
) {
4151 goto exit_init_data
;
4154 ret
= init_health_quit_pipe();
4157 goto exit_health_quit_pipe
;
4160 /* Create thread to manage the client socket */
4161 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4162 thread_manage_health
, (void *) NULL
);
4165 PERROR("pthread_create health");
4167 goto exit_health_thread
;
4170 /* Setup the dispatcher thread */
4171 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4172 relay_thread_dispatcher
, (void *) NULL
);
4175 PERROR("pthread_create dispatcher");
4177 goto exit_dispatcher_thread
;
4180 /* Setup the worker thread */
4181 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4182 relay_thread_worker
, NULL
);
4185 PERROR("pthread_create worker");
4187 goto exit_worker_thread
;
4190 /* Setup the listener thread */
4191 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4192 relay_thread_listener
, (void *) NULL
);
4195 PERROR("pthread_create listener");
4197 goto exit_listener_thread
;
4200 ret
= relayd_live_create(live_uri
);
4202 ERR("Starting live viewer threads");
4208 * This is where we start awaiting program completion (e.g. through
4209 * signal that asks threads to teardown).
4212 ret
= relayd_live_join();
4218 ret
= pthread_join(listener_thread
, &status
);
4221 PERROR("pthread_join listener_thread");
4225 exit_listener_thread
:
4226 ret
= pthread_join(worker_thread
, &status
);
4229 PERROR("pthread_join worker_thread");
4234 ret
= pthread_join(dispatcher_thread
, &status
);
4237 PERROR("pthread_join dispatcher_thread");
4240 exit_dispatcher_thread
:
4242 ret
= pthread_join(health_thread
, &status
);
4245 PERROR("pthread_join health_thread");
4250 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4251 exit_health_quit_pipe
:
4254 health_app_destroy(health_relayd
);
4255 exit_health_app_create
:
4258 * Wait for all pending call_rcu work to complete before tearing
4259 * down data structures. call_rcu worker may be trying to
4260 * perform lookups in those structures.
4265 /* Ensure all prior call_rcu are done. */
4270 * fd_tracker_destroy() will log the contents of the fd-tracker
4271 * if a leak is detected.
4273 fd_tracker_destroy(the_fd_tracker
);
4274 rcu_unregister_thread();