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 <urcu/rculist.h>
66 #include "ctf-trace.h"
69 #include "lttng-relayd.h"
71 #include "health-relayd.h"
72 #include "testpoint.h"
73 #include "viewer-stream.h"
76 #include "connection.h"
77 #include "tracefile-array.h"
78 #include "tcp_keep_alive.h"
80 static const char *help_msg
=
81 #ifdef LTTNG_EMBED_HELP
82 #include <lttng-relayd.8.h>
88 enum relay_connection_status
{
89 RELAY_CONNECTION_STATUS_OK
,
90 /* An error occured while processing an event on the connection. */
91 RELAY_CONNECTION_STATUS_ERROR
,
92 /* Connection closed/shutdown cleanly. */
93 RELAY_CONNECTION_STATUS_CLOSED
,
96 /* command line options */
97 char *opt_output_path
;
98 static int opt_daemon
, opt_background
;
101 * We need to wait for listener and live listener threads, as well as
102 * health check thread, before being ready to signal readiness.
104 #define NR_LTTNG_RELAY_READY 3
105 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
107 /* Size of receive buffer. */
108 #define RECV_DATA_BUFFER_SIZE 65536
109 #define FILE_COPY_BUFFER_SIZE 65536
111 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
112 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
114 static struct lttng_uri
*control_uri
;
115 static struct lttng_uri
*data_uri
;
116 static struct lttng_uri
*live_uri
;
118 const char *progname
;
120 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
121 static int tracing_group_name_override
;
123 const char * const config_section_name
= "relayd";
126 * Quit pipe for all threads. This permits a single cancellation point
127 * for all threads when receiving an event on the pipe.
129 int thread_quit_pipe
[2] = { -1, -1 };
132 * This pipe is used to inform the worker thread that a command is queued and
133 * ready to be processed.
135 static int relay_conn_pipe
[2] = { -1, -1 };
137 /* Shared between threads */
138 static int dispatch_thread_exit
;
140 static pthread_t listener_thread
;
141 static pthread_t dispatcher_thread
;
142 static pthread_t worker_thread
;
143 static pthread_t health_thread
;
146 * last_relay_stream_id_lock protects last_relay_stream_id increment
147 * atomicity on 32-bit architectures.
149 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
150 static uint64_t last_relay_stream_id
;
153 * Relay command queue.
155 * The relay_thread_listener and relay_thread_dispatcher communicate with this
158 static struct relay_conn_queue relay_conn_queue
;
160 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
161 static unsigned int lttng_opt_fd_cap
;
163 /* Global relay stream hash table. */
164 struct lttng_ht
*relay_streams_ht
;
166 /* Global relay viewer stream hash table. */
167 struct lttng_ht
*viewer_streams_ht
;
169 /* Global relay sessions hash table. */
170 struct lttng_ht
*sessions_ht
;
172 /* Relayd health monitoring */
173 struct health_app
*health_relayd
;
175 /* Global fd tracker. */
176 struct fd_tracker
*the_fd_tracker
;
178 static struct option long_options
[] = {
179 { "control-port", 1, 0, 'C', },
180 { "data-port", 1, 0, 'D', },
181 { "live-port", 1, 0, 'L', },
182 { "daemonize", 0, 0, 'd', },
183 { "background", 0, 0, 'b', },
184 { "group", 1, 0, 'g', },
185 { "fd-cap", 1, 0, '\0', },
186 { "help", 0, 0, 'h', },
187 { "output", 1, 0, 'o', },
188 { "verbose", 0, 0, 'v', },
189 { "config", 1, 0, 'f' },
190 { "version", 0, 0, 'V' },
194 static const char *config_ignore_options
[] = { "help", "config", "version" };
197 * Take an option from the getopt output and set it in the right variable to be
200 * Return 0 on success else a negative value.
202 static int set_option(int opt
, const char *arg
, const char *optname
)
208 if (!strcmp(optname
, "fd-cap")) {
212 v
= strtoul(arg
, NULL
, 0);
213 if (errno
!= 0 || !isdigit(arg
[0])) {
214 ERR("Wrong value in --fd-cap parameter: %s", arg
);
218 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
219 ERR("File descriptor cap must be set to at least %d",
220 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
223 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
227 lttng_opt_fd_cap
= (unsigned int) v
;
228 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
231 fprintf(stderr
, "unknown option %s", optname
);
233 fprintf(stderr
, " with arg %s\n", arg
);
238 if (lttng_is_setuid_setgid()) {
239 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
240 "-C, --control-port");
242 ret
= uri_parse(arg
, &control_uri
);
244 ERR("Invalid control URI specified");
247 if (control_uri
->port
== 0) {
248 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
257 ret
= uri_parse(arg
, &data_uri
);
259 ERR("Invalid data URI specified");
262 if (data_uri
->port
== 0) {
263 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
268 if (lttng_is_setuid_setgid()) {
269 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
272 ret
= uri_parse(arg
, &live_uri
);
274 ERR("Invalid live URI specified");
277 if (live_uri
->port
== 0) {
278 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
289 if (lttng_is_setuid_setgid()) {
290 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
293 tracing_group_name
= strdup(arg
);
294 if (tracing_group_name
== NULL
) {
299 tracing_group_name_override
= 1;
303 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
305 ERR("Cannot show --help for `lttng-relayd`");
310 fprintf(stdout
, "%s\n", VERSION
);
313 if (lttng_is_setuid_setgid()) {
314 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
317 ret
= asprintf(&opt_output_path
, "%s", arg
);
320 PERROR("asprintf opt_output_path");
326 /* Verbose level can increase using multiple -v */
328 lttng_opt_verbose
= config_parse_value(arg
);
330 /* Only 3 level of verbosity (-vvv). */
331 if (lttng_opt_verbose
< 3) {
332 lttng_opt_verbose
+= 1;
337 /* Unknown option or other error.
338 * Error is printed by getopt, just return */
351 * config_entry_handler_cb used to handle options read from a config file.
352 * See config_entry_handler_cb comment in common/config/session-config.h for the
353 * return value conventions.
355 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
359 if (!entry
|| !entry
->name
|| !entry
->value
) {
364 /* Check if the option is to be ignored */
365 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
366 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
371 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
372 /* Ignore if entry name is not fully matched. */
373 if (strcmp(entry
->name
, long_options
[i
].name
)) {
378 * If the option takes no argument on the command line,
379 * we have to check if the value is "true". We support
380 * non-zero numeric values, true, on and yes.
382 if (!long_options
[i
].has_arg
) {
383 ret
= config_parse_value(entry
->value
);
386 WARN("Invalid configuration value \"%s\" for option %s",
387 entry
->value
, entry
->name
);
389 /* False, skip boolean config option. */
394 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
398 WARN("Unrecognized option \"%s\" in daemon configuration file.",
405 static int set_options(int argc
, char **argv
)
407 int c
, ret
= 0, option_index
= 0, retval
= 0;
408 int orig_optopt
= optopt
, orig_optind
= optind
;
409 char *default_address
, *optstring
;
410 const char *config_path
= NULL
;
412 optstring
= utils_generate_optstring(long_options
,
413 sizeof(long_options
) / sizeof(struct option
));
419 /* Check for the --config option */
421 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
422 &option_index
)) != -1) {
426 } else if (c
!= 'f') {
430 if (lttng_is_setuid_setgid()) {
431 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
434 config_path
= utils_expand_path(optarg
);
436 ERR("Failed to resolve path: %s", optarg
);
441 ret
= config_get_section_entries(config_path
, config_section_name
,
442 config_entry_handler
, NULL
);
445 ERR("Invalid configuration option at line %i", ret
);
451 /* Reset getopt's global state */
452 optopt
= orig_optopt
;
453 optind
= orig_optind
;
455 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
460 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
467 /* assign default values */
468 if (control_uri
== NULL
) {
469 ret
= asprintf(&default_address
,
470 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
471 DEFAULT_NETWORK_CONTROL_PORT
);
473 PERROR("asprintf default data address");
478 ret
= uri_parse(default_address
, &control_uri
);
479 free(default_address
);
481 ERR("Invalid control URI specified");
486 if (data_uri
== NULL
) {
487 ret
= asprintf(&default_address
,
488 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
489 DEFAULT_NETWORK_DATA_PORT
);
491 PERROR("asprintf default data address");
496 ret
= uri_parse(default_address
, &data_uri
);
497 free(default_address
);
499 ERR("Invalid data URI specified");
504 if (live_uri
== NULL
) {
505 ret
= asprintf(&default_address
,
506 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
507 DEFAULT_NETWORK_VIEWER_PORT
);
509 PERROR("asprintf default viewer control address");
514 ret
= uri_parse(default_address
, &live_uri
);
515 free(default_address
);
517 ERR("Invalid viewer control URI specified");
522 if (lttng_opt_fd_cap
== 0) {
524 struct rlimit rlimit
;
526 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
528 PERROR("Failed to get file descriptor limit");
532 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
540 static void print_global_objects(void)
542 print_viewer_streams();
543 print_relay_streams();
550 static void relayd_cleanup(void)
552 print_global_objects();
556 if (viewer_streams_ht
)
557 lttng_ht_destroy(viewer_streams_ht
);
558 if (relay_streams_ht
)
559 lttng_ht_destroy(relay_streams_ht
);
561 lttng_ht_destroy(sessions_ht
);
563 /* free the dynamically allocated opt_output_path */
564 free(opt_output_path
);
566 /* Close thread quit pipes */
567 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
569 uri_free(control_uri
);
571 /* Live URI is freed in the live thread. */
573 if (tracing_group_name_override
) {
574 free((void *) tracing_group_name
);
576 fd_tracker_log(the_fd_tracker
);
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 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
737 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
741 if (events
== NULL
|| size
== 0) {
746 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
752 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
764 * Check if the thread quit pipe was triggered.
766 * Return 1 if it was triggered else 0;
768 static int check_thread_quit_pipe(int fd
, uint32_t events
)
770 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
778 * Create and init socket from uri.
780 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
783 struct lttcomm_sock
*sock
= NULL
;
785 sock
= lttcomm_alloc_sock_from_uri(uri
);
787 ERR("Allocating socket");
791 ret
= lttcomm_create_sock(sock
);
795 DBG("Listening on sock %d", sock
->fd
);
797 ret
= sock
->ops
->bind(sock
);
799 PERROR("Failed to bind socket");
803 ret
= sock
->ops
->listen(sock
, -1);
813 lttcomm_destroy_sock(sock
);
819 * This thread manages the listening for new connections on the network
821 static void *relay_thread_listener(void *data
)
823 int i
, ret
, pollfd
, err
= -1;
824 uint32_t revents
, nb_fd
;
825 struct lttng_poll_event events
;
826 struct lttcomm_sock
*control_sock
, *data_sock
;
828 DBG("[thread] Relay listener started");
830 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
832 health_code_update();
834 control_sock
= relay_socket_create(control_uri
);
836 goto error_sock_control
;
839 data_sock
= relay_socket_create(data_uri
);
841 goto error_sock_relay
;
845 * Pass 3 as size here for the thread quit pipe, control and
848 ret
= create_thread_poll_set(&events
, 3);
850 goto error_create_poll
;
853 /* Add the control socket */
854 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
859 /* Add the data socket */
860 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
865 lttng_relay_notify_ready();
867 if (testpoint(relayd_thread_listener
)) {
868 goto error_testpoint
;
872 health_code_update();
874 DBG("Listener accepting connections");
878 ret
= lttng_poll_wait(&events
, -1);
882 * Restart interrupted system call.
884 if (errno
== EINTR
) {
892 DBG("Relay new connection received");
893 for (i
= 0; i
< nb_fd
; i
++) {
894 health_code_update();
896 /* Fetch once the poll data */
897 revents
= LTTNG_POLL_GETEV(&events
, i
);
898 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
902 * No activity for this FD (poll
908 /* Thread quit pipe has been closed. Killing thread. */
909 ret
= check_thread_quit_pipe(pollfd
, revents
);
915 if (revents
& LPOLLIN
) {
917 * A new connection is requested, therefore a
918 * sessiond/consumerd connection is allocated in
919 * this thread, enqueued to a global queue and
920 * dequeued (and freed) in the worker thread.
923 struct relay_connection
*new_conn
;
924 struct lttcomm_sock
*newsock
;
925 enum connection_type type
;
927 if (pollfd
== data_sock
->fd
) {
929 newsock
= data_sock
->ops
->accept(data_sock
);
930 DBG("Relay data connection accepted, socket %d",
933 assert(pollfd
== control_sock
->fd
);
934 type
= RELAY_CONTROL
;
935 newsock
= control_sock
->ops
->accept(control_sock
);
936 DBG("Relay control connection accepted, socket %d",
940 PERROR("accepting sock");
944 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
947 PERROR("setsockopt inet");
948 lttcomm_destroy_sock(newsock
);
952 ret
= socket_apply_keep_alive_config(newsock
->fd
);
954 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
956 lttcomm_destroy_sock(newsock
);
960 new_conn
= connection_create(newsock
, type
);
962 lttcomm_destroy_sock(newsock
);
966 /* Enqueue request for the dispatcher thread. */
967 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
971 * Wake the dispatch queue futex.
972 * Implicit memory barrier with the
973 * exchange in cds_wfcq_enqueue.
975 futex_nto1_wake(&relay_conn_queue
.futex
);
976 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
977 ERR("socket poll error");
980 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
990 lttng_poll_clean(&events
);
992 if (data_sock
->fd
>= 0) {
993 ret
= data_sock
->ops
->close(data_sock
);
998 lttcomm_destroy_sock(data_sock
);
1000 if (control_sock
->fd
>= 0) {
1001 ret
= control_sock
->ops
->close(control_sock
);
1006 lttcomm_destroy_sock(control_sock
);
1010 ERR("Health error occurred in %s", __func__
);
1012 health_unregister(health_relayd
);
1013 DBG("Relay listener thread cleanup complete");
1014 lttng_relay_stop_threads();
1019 * This thread manages the dispatching of the requests to worker threads
1021 static void *relay_thread_dispatcher(void *data
)
1025 struct cds_wfcq_node
*node
;
1026 struct relay_connection
*new_conn
= NULL
;
1028 DBG("[thread] Relay dispatcher started");
1030 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1032 if (testpoint(relayd_thread_dispatcher
)) {
1033 goto error_testpoint
;
1036 health_code_update();
1039 health_code_update();
1041 /* Atomically prepare the queue futex */
1042 futex_nto1_prepare(&relay_conn_queue
.futex
);
1044 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1049 health_code_update();
1051 /* Dequeue commands */
1052 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1053 &relay_conn_queue
.tail
);
1055 DBG("Woken up but nothing in the relay command queue");
1056 /* Continue thread execution */
1059 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1061 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1064 * Inform worker thread of the new request. This
1065 * call is blocking so we can be assured that
1066 * the data will be read at some point in time
1067 * or wait to the end of the world :)
1069 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1071 PERROR("write connection pipe");
1072 connection_put(new_conn
);
1075 } while (node
!= NULL
);
1077 /* Futex wait on queue. Blocking call on futex() */
1078 health_poll_entry();
1079 futex_nto1_wait(&relay_conn_queue
.futex
);
1083 /* Normal exit, no error */
1090 ERR("Health error occurred in %s", __func__
);
1092 health_unregister(health_relayd
);
1093 DBG("Dispatch thread dying");
1094 lttng_relay_stop_threads();
1099 * Set index data from the control port to a given index object.
1101 static int set_index_control_data(struct relay_index
*index
,
1102 struct lttcomm_relayd_index
*data
,
1103 struct relay_connection
*conn
)
1105 struct ctf_packet_index index_data
;
1108 * The index on disk is encoded in big endian.
1110 index_data
.packet_size
= htobe64(data
->packet_size
);
1111 index_data
.content_size
= htobe64(data
->content_size
);
1112 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1113 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1114 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1115 index_data
.stream_id
= htobe64(data
->stream_id
);
1117 if (conn
->minor
>= 8) {
1118 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1119 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1122 return relay_index_set_data(index
, &index_data
);
1126 * Handle the RELAYD_CREATE_SESSION command.
1128 * On success, send back the session id or else return a negative value.
1130 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1131 struct relay_connection
*conn
,
1132 const struct lttng_buffer_view
*payload
)
1136 struct relay_session
*session
;
1137 struct lttcomm_relayd_status_session reply
;
1138 char session_name
[LTTNG_NAME_MAX
];
1139 char hostname
[LTTNG_HOST_NAME_MAX
];
1140 uint32_t live_timer
= 0;
1141 bool snapshot
= false;
1143 memset(session_name
, 0, LTTNG_NAME_MAX
);
1144 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1146 memset(&reply
, 0, sizeof(reply
));
1148 if (conn
->minor
< 4) {
1149 /* From 2.1 to 2.3 */
1151 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1152 /* From 2.4 to 2.10 */
1153 ret
= cmd_create_session_2_4(payload
, session_name
,
1154 hostname
, &live_timer
, &snapshot
);
1156 /* From 2.11 to ... */
1157 ret
= cmd_create_session_2_11(payload
, session_name
,
1158 hostname
, &live_timer
, &snapshot
);
1165 session
= session_create(session_name
, hostname
, live_timer
,
1166 snapshot
, conn
->major
, conn
->minor
);
1171 assert(!conn
->session
);
1172 conn
->session
= session
;
1173 DBG("Created session %" PRIu64
, session
->id
);
1175 reply
.session_id
= htobe64(session
->id
);
1179 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1181 reply
.ret_code
= htobe32(LTTNG_OK
);
1184 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1185 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1186 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1195 * When we have received all the streams and the metadata for a channel,
1196 * we make them visible to the viewer threads.
1198 static void publish_connection_local_streams(struct relay_connection
*conn
)
1200 struct relay_stream
*stream
;
1201 struct relay_session
*session
= conn
->session
;
1204 * We publish all streams belonging to a session atomically wrt
1207 pthread_mutex_lock(&session
->lock
);
1209 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1211 stream_publish(stream
);
1216 * Inform the viewer that there are new streams in the session.
1218 if (session
->viewer_attached
) {
1219 uatomic_set(&session
->new_streams
, 1);
1221 pthread_mutex_unlock(&session
->lock
);
1225 * relay_add_stream: allocate a new stream for a session
1227 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1228 struct relay_connection
*conn
,
1229 const struct lttng_buffer_view
*payload
)
1233 struct relay_session
*session
= conn
->session
;
1234 struct relay_stream
*stream
= NULL
;
1235 struct lttcomm_relayd_status_stream reply
;
1236 struct ctf_trace
*trace
= NULL
;
1237 uint64_t stream_handle
= -1ULL;
1238 char *path_name
= NULL
, *channel_name
= NULL
;
1239 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1240 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1242 if (!session
|| !conn
->version_check_done
) {
1243 ERR("Trying to add a stream before version check");
1245 goto end_no_session
;
1248 if (session
->minor
== 1) {
1250 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1252 } else if (session
->minor
> 1 && session
->minor
< 11) {
1253 /* From 2.2 to 2.10 */
1254 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1255 &channel_name
, &tracefile_size
, &tracefile_count
);
1257 /* From 2.11 to ... */
1258 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1259 &channel_name
, &tracefile_size
, &tracefile_count
,
1260 &stream_chunk_id
.value
);
1261 stream_chunk_id
.is_set
= true;
1268 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1272 /* This stream here has one reference on the trace. */
1274 pthread_mutex_lock(&last_relay_stream_id_lock
);
1275 stream_handle
= ++last_relay_stream_id
;
1276 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1278 /* We pass ownership of path_name and channel_name. */
1279 stream
= stream_create(trace
, stream_handle
, path_name
,
1280 channel_name
, tracefile_size
, tracefile_count
,
1283 channel_name
= NULL
;
1286 * Streams are the owners of their trace. Reference to trace is
1287 * kept within stream_create().
1289 ctf_trace_put(trace
);
1292 memset(&reply
, 0, sizeof(reply
));
1293 reply
.handle
= htobe64(stream_handle
);
1295 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1297 reply
.ret_code
= htobe32(LTTNG_OK
);
1300 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1301 sizeof(struct lttcomm_relayd_status_stream
), 0);
1302 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1303 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1315 * relay_close_stream: close a specific stream
1317 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1318 struct relay_connection
*conn
,
1319 const struct lttng_buffer_view
*payload
)
1323 struct relay_session
*session
= conn
->session
;
1324 struct lttcomm_relayd_close_stream stream_info
;
1325 struct lttcomm_relayd_generic_reply reply
;
1326 struct relay_stream
*stream
;
1328 DBG("Close stream received");
1330 if (!session
|| !conn
->version_check_done
) {
1331 ERR("Trying to close a stream before version check");
1333 goto end_no_session
;
1336 if (payload
->size
< sizeof(stream_info
)) {
1337 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1338 sizeof(stream_info
), payload
->size
);
1340 goto end_no_session
;
1342 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1343 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1344 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1346 stream
= stream_get_by_id(stream_info
.stream_id
);
1353 * Set last_net_seq_num before the close flag. Required by data
1356 pthread_mutex_lock(&stream
->lock
);
1357 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1358 pthread_mutex_unlock(&stream
->lock
);
1361 * This is one of the conditions which may trigger a stream close
1362 * with the others being:
1363 * 1) A close command is received for a stream
1364 * 2) The control connection owning the stream is closed
1365 * 3) We have received all of the stream's data _after_ a close
1368 try_stream_close(stream
);
1369 if (stream
->is_metadata
) {
1370 struct relay_viewer_stream
*vstream
;
1372 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1374 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1376 * Since all the metadata has been sent to the
1377 * viewer and that we have a request to close
1378 * its stream, we can safely teardown the
1379 * corresponding metadata viewer stream.
1381 viewer_stream_put(vstream
);
1383 /* Put local reference. */
1384 viewer_stream_put(vstream
);
1391 memset(&reply
, 0, sizeof(reply
));
1393 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1395 reply
.ret_code
= htobe32(LTTNG_OK
);
1397 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1398 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1399 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1400 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1410 * relay_reset_metadata: reset a metadata stream
1413 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1414 struct relay_connection
*conn
,
1415 const struct lttng_buffer_view
*payload
)
1419 struct relay_session
*session
= conn
->session
;
1420 struct lttcomm_relayd_reset_metadata stream_info
;
1421 struct lttcomm_relayd_generic_reply reply
;
1422 struct relay_stream
*stream
;
1424 DBG("Reset metadata received");
1426 if (!session
|| !conn
->version_check_done
) {
1427 ERR("Trying to reset a metadata stream before version check");
1429 goto end_no_session
;
1432 if (payload
->size
< sizeof(stream_info
)) {
1433 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1434 sizeof(stream_info
), payload
->size
);
1436 goto end_no_session
;
1438 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1439 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1440 stream_info
.version
= be64toh(stream_info
.version
);
1442 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1444 /* Unsupported for live sessions for now. */
1445 if (session
->live_timer
!= 0) {
1450 stream
= stream_get_by_id(stream_info
.stream_id
);
1455 pthread_mutex_lock(&stream
->lock
);
1456 if (!stream
->is_metadata
) {
1461 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1462 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1463 &stream
->stream_fd
->fd
);
1465 ERR("Failed to rotate metadata file %s of channel %s",
1466 stream
->path_name
, stream
->channel_name
);
1471 pthread_mutex_unlock(&stream
->lock
);
1475 memset(&reply
, 0, sizeof(reply
));
1477 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1479 reply
.ret_code
= htobe32(LTTNG_OK
);
1481 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1482 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1483 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1484 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1494 * relay_unknown_command: send -1 if received unknown command
1496 static void relay_unknown_command(struct relay_connection
*conn
)
1498 struct lttcomm_relayd_generic_reply reply
;
1501 memset(&reply
, 0, sizeof(reply
));
1502 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1503 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1504 if (send_ret
< sizeof(reply
)) {
1505 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1510 * relay_start: send an acknowledgment to the client to tell if we are
1511 * ready to receive data. We are ready if a session is established.
1513 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1514 struct relay_connection
*conn
,
1515 const struct lttng_buffer_view
*payload
)
1519 struct lttcomm_relayd_generic_reply reply
;
1520 struct relay_session
*session
= conn
->session
;
1523 DBG("Trying to start the streaming without a session established");
1524 ret
= htobe32(LTTNG_ERR_UNK
);
1527 memset(&reply
, 0, sizeof(reply
));
1528 reply
.ret_code
= htobe32(LTTNG_OK
);
1529 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1531 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1532 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1541 * Append padding to the file pointed by the file descriptor fd.
1543 static int write_padding_to_file(int fd
, uint32_t size
)
1552 zeros
= zmalloc(size
);
1553 if (zeros
== NULL
) {
1554 PERROR("zmalloc zeros for padding");
1559 ret
= lttng_write(fd
, zeros
, size
);
1561 PERROR("write padding to file");
1571 * Close the current index file if it is open, and create a new one.
1573 * Return 0 on success, -1 on error.
1576 int create_rotate_index_file(struct relay_stream
*stream
)
1579 uint32_t major
, minor
;
1581 /* Put ref on previous index_file. */
1582 if (stream
->index_file
) {
1583 lttng_index_file_put(stream
->index_file
);
1584 stream
->index_file
= NULL
;
1586 major
= stream
->trace
->session
->major
;
1587 minor
= stream
->trace
->session
->minor
;
1588 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
1589 stream
->channel_name
,
1590 -1, -1, stream
->tracefile_size
,
1591 tracefile_array_get_file_index_head(stream
->tfa
),
1592 lttng_to_index_major(major
, minor
),
1593 lttng_to_index_minor(major
, minor
));
1594 if (!stream
->index_file
) {
1606 int do_rotate_stream(struct relay_stream
*stream
)
1610 /* Perform the stream rotation. */
1611 ret
= utils_rotate_stream_file(stream
->path_name
,
1612 stream
->channel_name
, stream
->tracefile_size
,
1613 stream
->tracefile_count
, -1,
1614 -1, stream
->stream_fd
->fd
,
1615 NULL
, &stream
->stream_fd
->fd
);
1617 ERR("Rotating stream output file");
1620 stream
->tracefile_size_current
= 0;
1622 /* Rotate also the index if the stream is not a metadata stream. */
1623 if (!stream
->is_metadata
) {
1624 ret
= create_rotate_index_file(stream
);
1626 ERR("Failed to rotate index file");
1631 stream
->rotate_at_seq_num
= -1ULL;
1632 stream
->pos_after_last_complete_data_index
= 0;
1639 * If too much data has been written in a tracefile before we received the
1640 * rotation command, we have to move the excess data to the new tracefile and
1641 * perform the rotation. This can happen because the control and data
1642 * connections are separate, the indexes as well as the commands arrive from
1643 * the control connection and we have no control over the order so we could be
1644 * in a situation where too much data has been received on the data connection
1645 * before the rotation command on the control connection arrives. We don't need
1646 * to update the index because its order is guaranteed with the rotation
1650 int rotate_truncate_stream(struct relay_stream
*stream
)
1654 uint64_t diff
, pos
= 0;
1655 char buf
[FILE_COPY_BUFFER_SIZE
];
1657 assert(!stream
->is_metadata
);
1659 assert(stream
->tracefile_size_current
>
1660 stream
->pos_after_last_complete_data_index
);
1661 diff
= stream
->tracefile_size_current
-
1662 stream
->pos_after_last_complete_data_index
;
1664 /* Create the new tracefile. */
1665 new_fd
= utils_create_stream_file(stream
->path_name
,
1666 stream
->channel_name
,
1667 stream
->tracefile_size
, stream
->tracefile_count
,
1668 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1670 ERR("Failed to create new stream file at path %s for channel %s",
1671 stream
->path_name
, stream
->channel_name
);
1677 * Rewind the current tracefile to the position at which the rotation
1678 * should have occured.
1680 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1681 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1682 if (lseek_ret
< 0) {
1683 PERROR("seek truncate stream");
1688 /* Move data from the old file to the new file. */
1689 while (pos
< diff
) {
1690 uint64_t count
, bytes_left
;
1693 bytes_left
= diff
- pos
;
1694 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1695 assert(count
<= SIZE_MAX
);
1697 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1698 if (io_ret
< (ssize_t
) count
) {
1699 char error_string
[256];
1701 snprintf(error_string
, sizeof(error_string
),
1702 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1703 count
, stream
->stream_fd
->fd
, io_ret
);
1705 PERROR("%s", error_string
);
1707 ERR("%s", error_string
);
1713 io_ret
= lttng_write(new_fd
, buf
, count
);
1714 if (io_ret
< (ssize_t
) count
) {
1715 char error_string
[256];
1717 snprintf(error_string
, sizeof(error_string
),
1718 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1719 count
, new_fd
, io_ret
);
1721 PERROR("%s", error_string
);
1723 ERR("%s", error_string
);
1732 /* Truncate the file to get rid of the excess data. */
1733 ret
= ftruncate(stream
->stream_fd
->fd
,
1734 stream
->pos_after_last_complete_data_index
);
1736 PERROR("ftruncate");
1740 ret
= close(stream
->stream_fd
->fd
);
1742 PERROR("Closing tracefile");
1746 ret
= create_rotate_index_file(stream
);
1748 ERR("Rotate stream index file");
1753 * Update the offset and FD of all the eventual indexes created by the
1754 * data connection before the rotation command arrived.
1756 ret
= relay_index_switch_all_files(stream
);
1758 ERR("Failed to rotate index file");
1762 stream
->stream_fd
->fd
= new_fd
;
1763 stream
->tracefile_size_current
= diff
;
1764 stream
->pos_after_last_complete_data_index
= 0;
1765 stream
->rotate_at_seq_num
= -1ULL;
1774 * Check if a stream should perform a rotation (for session rotation).
1775 * Must be called with the stream lock held.
1777 * Return 0 on success, a negative value on error.
1780 int try_rotate_stream(struct relay_stream
*stream
)
1784 /* No rotation expected. */
1785 if (stream
->rotate_at_seq_num
== -1ULL) {
1789 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1790 stream
->prev_seq
== -1ULL) {
1791 DBG("Stream %" PRIu64
" no yet ready for rotation",
1792 stream
->stream_handle
);
1794 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1795 DBG("Rotation after too much data has been written in tracefile "
1796 "for stream %" PRIu64
", need to truncate before "
1797 "rotating", stream
->stream_handle
);
1798 ret
= rotate_truncate_stream(stream
);
1800 ERR("Failed to truncate stream");
1804 /* stream->prev_seq == stream->rotate_at_seq_num */
1805 DBG("Stream %" PRIu64
" ready for rotation",
1806 stream
->stream_handle
);
1807 ret
= do_rotate_stream(stream
);
1815 * relay_recv_metadata: receive the metadata for the session.
1817 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1818 struct relay_connection
*conn
,
1819 const struct lttng_buffer_view
*payload
)
1823 struct relay_session
*session
= conn
->session
;
1824 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1825 struct relay_stream
*metadata_stream
;
1826 uint64_t metadata_payload_size
;
1829 ERR("Metadata sent before version check");
1834 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1835 ERR("Incorrect data size");
1839 metadata_payload_size
= recv_hdr
->data_size
-
1840 sizeof(struct lttcomm_relayd_metadata_payload
);
1842 memcpy(&metadata_payload_header
, payload
->data
,
1843 sizeof(metadata_payload_header
));
1844 metadata_payload_header
.stream_id
= be64toh(
1845 metadata_payload_header
.stream_id
);
1846 metadata_payload_header
.padding_size
= be32toh(
1847 metadata_payload_header
.padding_size
);
1849 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1850 if (!metadata_stream
) {
1855 pthread_mutex_lock(&metadata_stream
->lock
);
1857 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1858 payload
->data
+ sizeof(metadata_payload_header
),
1859 metadata_payload_size
);
1860 if (size_ret
< metadata_payload_size
) {
1861 ERR("Relay error writing metadata on file");
1866 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1867 metadata_payload_header
.padding_size
);
1868 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1873 metadata_stream
->metadata_received
+=
1874 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1875 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1876 metadata_stream
->metadata_received
);
1878 ret
= try_rotate_stream(metadata_stream
);
1884 pthread_mutex_unlock(&metadata_stream
->lock
);
1885 stream_put(metadata_stream
);
1891 * relay_send_version: send relayd version number
1893 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1894 struct relay_connection
*conn
,
1895 const struct lttng_buffer_view
*payload
)
1899 struct lttcomm_relayd_version reply
, msg
;
1900 bool compatible
= true;
1902 conn
->version_check_done
= true;
1904 /* Get version from the other side. */
1905 if (payload
->size
< sizeof(msg
)) {
1906 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1907 sizeof(msg
), payload
->size
);
1912 memcpy(&msg
, payload
->data
, sizeof(msg
));
1913 msg
.major
= be32toh(msg
.major
);
1914 msg
.minor
= be32toh(msg
.minor
);
1916 memset(&reply
, 0, sizeof(reply
));
1917 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1918 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1920 /* Major versions must be the same */
1921 if (reply
.major
!= msg
.major
) {
1922 DBG("Incompatible major versions (%u vs %u), deleting session",
1923 reply
.major
, msg
.major
);
1927 conn
->major
= reply
.major
;
1928 /* We adapt to the lowest compatible version */
1929 if (reply
.minor
<= msg
.minor
) {
1930 conn
->minor
= reply
.minor
;
1932 conn
->minor
= msg
.minor
;
1935 reply
.major
= htobe32(reply
.major
);
1936 reply
.minor
= htobe32(reply
.minor
);
1937 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1939 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1940 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1953 DBG("Version check done using protocol %u.%u", conn
->major
,
1961 * Check for data pending for a given stream id from the session daemon.
1963 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1964 struct relay_connection
*conn
,
1965 const struct lttng_buffer_view
*payload
)
1967 struct relay_session
*session
= conn
->session
;
1968 struct lttcomm_relayd_data_pending msg
;
1969 struct lttcomm_relayd_generic_reply reply
;
1970 struct relay_stream
*stream
;
1974 DBG("Data pending command received");
1976 if (!session
|| !conn
->version_check_done
) {
1977 ERR("Trying to check for data before version check");
1979 goto end_no_session
;
1982 if (payload
->size
< sizeof(msg
)) {
1983 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1984 sizeof(msg
), payload
->size
);
1986 goto end_no_session
;
1988 memcpy(&msg
, payload
->data
, sizeof(msg
));
1989 msg
.stream_id
= be64toh(msg
.stream_id
);
1990 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1992 stream
= stream_get_by_id(msg
.stream_id
);
1993 if (stream
== NULL
) {
1998 pthread_mutex_lock(&stream
->lock
);
2000 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2001 " and last_seq %" PRIu64
, msg
.stream_id
,
2002 stream
->prev_seq
, msg
.last_net_seq_num
);
2004 /* Avoid wrapping issue */
2005 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2006 /* Data has in fact been written and is NOT pending */
2009 /* Data still being streamed thus pending */
2013 stream
->data_pending_check_done
= true;
2014 pthread_mutex_unlock(&stream
->lock
);
2019 memset(&reply
, 0, sizeof(reply
));
2020 reply
.ret_code
= htobe32(ret
);
2021 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2022 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2023 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2033 * Wait for the control socket to reach a quiescent state.
2035 * Note that for now, when receiving this command from the session
2036 * daemon, this means that every subsequent commands or data received on
2037 * the control socket has been handled. So, this is why we simply return
2040 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2041 struct relay_connection
*conn
,
2042 const struct lttng_buffer_view
*payload
)
2046 struct relay_stream
*stream
;
2047 struct lttcomm_relayd_quiescent_control msg
;
2048 struct lttcomm_relayd_generic_reply reply
;
2050 DBG("Checking quiescent state on control socket");
2052 if (!conn
->session
|| !conn
->version_check_done
) {
2053 ERR("Trying to check for data before version check");
2055 goto end_no_session
;
2058 if (payload
->size
< sizeof(msg
)) {
2059 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2060 sizeof(msg
), payload
->size
);
2062 goto end_no_session
;
2064 memcpy(&msg
, payload
->data
, sizeof(msg
));
2065 msg
.stream_id
= be64toh(msg
.stream_id
);
2067 stream
= stream_get_by_id(msg
.stream_id
);
2071 pthread_mutex_lock(&stream
->lock
);
2072 stream
->data_pending_check_done
= true;
2073 pthread_mutex_unlock(&stream
->lock
);
2075 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2078 memset(&reply
, 0, sizeof(reply
));
2079 reply
.ret_code
= htobe32(LTTNG_OK
);
2080 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2081 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2082 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2094 * Initialize a data pending command. This means that a consumer is about
2095 * to ask for data pending for each stream it holds. Simply iterate over
2096 * all streams of a session and set the data_pending_check_done flag.
2098 * This command returns to the client a LTTNG_OK code.
2100 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2101 struct relay_connection
*conn
,
2102 const struct lttng_buffer_view
*payload
)
2106 struct lttng_ht_iter iter
;
2107 struct lttcomm_relayd_begin_data_pending msg
;
2108 struct lttcomm_relayd_generic_reply reply
;
2109 struct relay_stream
*stream
;
2114 DBG("Init streams for data pending");
2116 if (!conn
->session
|| !conn
->version_check_done
) {
2117 ERR("Trying to check for data before version check");
2119 goto end_no_session
;
2122 if (payload
->size
< sizeof(msg
)) {
2123 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2124 sizeof(msg
), payload
->size
);
2126 goto end_no_session
;
2128 memcpy(&msg
, payload
->data
, sizeof(msg
));
2129 msg
.session_id
= be64toh(msg
.session_id
);
2132 * Iterate over all streams to set the begin data pending flag.
2133 * For now, the streams are indexed by stream handle so we have
2134 * to iterate over all streams to find the one associated with
2135 * the right session_id.
2138 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2140 if (!stream_get(stream
)) {
2143 if (stream
->trace
->session
->id
== msg
.session_id
) {
2144 pthread_mutex_lock(&stream
->lock
);
2145 stream
->data_pending_check_done
= false;
2146 pthread_mutex_unlock(&stream
->lock
);
2147 DBG("Set begin data pending flag to stream %" PRIu64
,
2148 stream
->stream_handle
);
2154 memset(&reply
, 0, sizeof(reply
));
2155 /* All good, send back reply. */
2156 reply
.ret_code
= htobe32(LTTNG_OK
);
2158 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2159 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2160 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2172 * End data pending command. This will check, for a given session id, if
2173 * each stream associated with it has its data_pending_check_done flag
2174 * set. If not, this means that the client lost track of the stream but
2175 * the data is still being streamed on our side. In this case, we inform
2176 * the client that data is in flight.
2178 * Return to the client if there is data in flight or not with a ret_code.
2180 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2181 struct relay_connection
*conn
,
2182 const struct lttng_buffer_view
*payload
)
2186 struct lttng_ht_iter iter
;
2187 struct lttcomm_relayd_end_data_pending msg
;
2188 struct lttcomm_relayd_generic_reply reply
;
2189 struct relay_stream
*stream
;
2190 uint32_t is_data_inflight
= 0;
2192 DBG("End data pending command");
2194 if (!conn
->session
|| !conn
->version_check_done
) {
2195 ERR("Trying to check for data before version check");
2197 goto end_no_session
;
2200 if (payload
->size
< sizeof(msg
)) {
2201 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2202 sizeof(msg
), payload
->size
);
2204 goto end_no_session
;
2206 memcpy(&msg
, payload
->data
, sizeof(msg
));
2207 msg
.session_id
= be64toh(msg
.session_id
);
2210 * Iterate over all streams to see if the begin data pending
2214 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2216 if (!stream_get(stream
)) {
2219 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2223 pthread_mutex_lock(&stream
->lock
);
2224 if (!stream
->data_pending_check_done
) {
2225 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2226 is_data_inflight
= 1;
2227 DBG("Data is still in flight for stream %" PRIu64
,
2228 stream
->stream_handle
);
2229 pthread_mutex_unlock(&stream
->lock
);
2234 pthread_mutex_unlock(&stream
->lock
);
2239 memset(&reply
, 0, sizeof(reply
));
2240 /* All good, send back reply. */
2241 reply
.ret_code
= htobe32(is_data_inflight
);
2243 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2244 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2245 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2257 * Receive an index for a specific stream.
2259 * Return 0 on success else a negative value.
2261 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2262 struct relay_connection
*conn
,
2263 const struct lttng_buffer_view
*payload
)
2267 struct relay_session
*session
= conn
->session
;
2268 struct lttcomm_relayd_index index_info
;
2269 struct relay_index
*index
;
2270 struct lttcomm_relayd_generic_reply reply
;
2271 struct relay_stream
*stream
;
2276 DBG("Relay receiving index");
2278 if (!session
|| !conn
->version_check_done
) {
2279 ERR("Trying to close a stream before version check");
2281 goto end_no_session
;
2284 msg_len
= lttcomm_relayd_index_len(
2285 lttng_to_index_major(conn
->major
, conn
->minor
),
2286 lttng_to_index_minor(conn
->major
, conn
->minor
));
2287 if (payload
->size
< msg_len
) {
2288 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2289 msg_len
, payload
->size
);
2291 goto end_no_session
;
2293 memcpy(&index_info
, payload
->data
, msg_len
);
2294 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2295 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2296 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2297 index_info
.content_size
= be64toh(index_info
.content_size
);
2298 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2299 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2300 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2301 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2303 if (conn
->minor
>= 8) {
2304 index_info
.stream_instance_id
=
2305 be64toh(index_info
.stream_instance_id
);
2306 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2309 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2311 ERR("stream_get_by_id not found");
2315 pthread_mutex_lock(&stream
->lock
);
2317 /* Live beacon handling */
2318 if (index_info
.packet_size
== 0) {
2319 DBG("Received live beacon for stream %" PRIu64
,
2320 stream
->stream_handle
);
2323 * Only flag a stream inactive when it has already
2324 * received data and no indexes are in flight.
2326 if (stream
->index_received_seqcount
> 0
2327 && stream
->indexes_in_flight
== 0) {
2328 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2331 goto end_stream_put
;
2333 stream
->beacon_ts_end
= -1ULL;
2336 if (stream
->ctf_stream_id
== -1ULL) {
2337 stream
->ctf_stream_id
= index_info
.stream_id
;
2339 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2342 ERR("relay_index_get_by_id_or_create index NULL");
2343 goto end_stream_put
;
2345 if (set_index_control_data(index
, &index_info
, conn
)) {
2346 ERR("set_index_control_data error");
2347 relay_index_put(index
);
2349 goto end_stream_put
;
2351 ret
= relay_index_try_flush(index
);
2353 tracefile_array_commit_seq(stream
->tfa
);
2354 stream
->index_received_seqcount
++;
2355 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2356 } else if (ret
> 0) {
2360 ERR("relay_index_try_flush error %d", ret
);
2361 relay_index_put(index
);
2366 pthread_mutex_unlock(&stream
->lock
);
2371 memset(&reply
, 0, sizeof(reply
));
2373 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2375 reply
.ret_code
= htobe32(LTTNG_OK
);
2377 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2378 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2379 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2388 * Receive the streams_sent message.
2390 * Return 0 on success else a negative value.
2392 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2393 struct relay_connection
*conn
,
2394 const struct lttng_buffer_view
*payload
)
2398 struct lttcomm_relayd_generic_reply reply
;
2402 DBG("Relay receiving streams_sent");
2404 if (!conn
->session
|| !conn
->version_check_done
) {
2405 ERR("Trying to close a stream before version check");
2407 goto end_no_session
;
2411 * Publish every pending stream in the connection recv list which are
2412 * now ready to be used by the viewer.
2414 publish_connection_local_streams(conn
);
2416 memset(&reply
, 0, sizeof(reply
));
2417 reply
.ret_code
= htobe32(LTTNG_OK
);
2418 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2419 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2420 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2433 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2434 * rotation feature (not the tracefile rotation feature).
2436 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2437 struct relay_connection
*conn
,
2438 const struct lttng_buffer_view
*payload
)
2442 struct relay_session
*session
= conn
->session
;
2443 struct lttcomm_relayd_rotate_stream stream_info
;
2444 struct lttcomm_relayd_generic_reply reply
;
2445 struct relay_stream
*stream
;
2448 struct lttng_buffer_view new_path_view
;
2450 DBG("Rotate stream received");
2452 if (!session
|| !conn
->version_check_done
) {
2453 ERR("Trying to rotate a stream before version check");
2458 if (session
->major
== 2 && session
->minor
< 11) {
2459 ERR("Unsupported feature before 2.11");
2464 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2466 if (payload
->size
< header_len
) {
2467 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2468 header_len
, payload
->size
);
2473 memcpy(&stream_info
, payload
->data
, header_len
);
2475 /* Convert to host */
2476 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2477 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2478 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2479 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2481 path_len
= stream_info
.pathname_length
;
2482 if (payload
->size
< header_len
+ path_len
) {
2483 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2484 header_len
+ path_len
, payload
->size
);
2489 /* Ensure it fits in local filename length. */
2490 if (path_len
>= LTTNG_PATH_MAX
) {
2491 ret
= -ENAMETOOLONG
;
2492 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2493 path_len
, LTTNG_PATH_MAX
);
2497 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2498 stream_info
.pathname_length
);
2500 stream
= stream_get_by_id(stream_info
.stream_id
);
2506 pthread_mutex_lock(&stream
->lock
);
2509 * Update the trace path (just the folder, the stream name does not
2512 free(stream
->path_name
);
2513 stream
->path_name
= create_output_path(new_path_view
.data
);
2514 if (!stream
->path_name
) {
2515 ERR("Failed to create a new output path");
2517 goto end_stream_unlock
;
2519 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2522 ERR("relay creating output directory");
2524 goto end_stream_unlock
;
2527 assert(stream
->current_chunk_id
.is_set
);
2528 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2530 if (stream
->is_metadata
) {
2532 * The metadata stream is sent only over the control connection
2533 * so we know we have all the data to perform the stream
2536 ret
= do_rotate_stream(stream
);
2538 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2539 ret
= try_rotate_stream(stream
);
2542 goto end_stream_unlock
;
2546 pthread_mutex_unlock(&stream
->lock
);
2549 memset(&reply
, 0, sizeof(reply
));
2551 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2553 reply
.ret_code
= htobe32(LTTNG_OK
);
2555 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2556 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2557 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2558 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2568 * relay_mkdir: Create a folder on the disk.
2570 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2571 struct relay_connection
*conn
,
2572 const struct lttng_buffer_view
*payload
)
2575 struct relay_session
*session
= conn
->session
;
2576 struct lttcomm_relayd_mkdir path_info_header
;
2577 struct lttcomm_relayd_generic_reply reply
;
2581 struct lttng_buffer_view path_view
;
2583 if (!session
|| !conn
->version_check_done
) {
2584 ERR("Trying to create a directory before version check");
2586 goto end_no_session
;
2589 if (session
->major
== 2 && session
->minor
< 11) {
2591 * This client is not supposed to use this command since
2592 * it predates its introduction.
2594 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2596 goto end_no_session
;
2599 header_len
= sizeof(path_info_header
);
2600 if (payload
->size
< header_len
) {
2601 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2602 header_len
, payload
->size
);
2604 goto end_no_session
;
2607 memcpy(&path_info_header
, payload
->data
, header_len
);
2609 path_info_header
.length
= be32toh(path_info_header
.length
);
2611 if (payload
->size
< header_len
+ path_info_header
.length
) {
2612 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2613 header_len
+ path_info_header
.length
, payload
->size
);
2615 goto end_no_session
;
2618 /* Ensure that it fits in local path length. */
2619 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2620 ret
= -ENAMETOOLONG
;
2621 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2622 path_info_header
.length
, LTTNG_PATH_MAX
);
2626 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2627 path_info_header
.length
);
2629 path
= create_output_path(path_view
.data
);
2631 ERR("Failed to create output path");
2636 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2638 ERR("relay creating output directory");
2645 memset(&reply
, 0, sizeof(reply
));
2647 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2649 reply
.ret_code
= htobe32(LTTNG_OK
);
2651 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2652 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2653 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2662 static int validate_rotate_rename_path_length(const char *path_type
,
2663 uint32_t path_length
)
2667 if (path_length
> LTTNG_PATH_MAX
) {
2668 ret
= -ENAMETOOLONG
;
2669 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2670 path_type
, path_length
, LTTNG_PATH_MAX
);
2671 } else if (path_length
== 0) {
2673 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2679 * relay_rotate_rename: rename the trace folder after a rotation is
2680 * completed. We are not closing any fd here, just moving the folder, so it
2681 * works even if data is still in-flight.
2683 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2684 struct relay_connection
*conn
,
2685 const struct lttng_buffer_view
*payload
)
2689 struct relay_session
*session
= conn
->session
;
2690 struct lttcomm_relayd_generic_reply reply
;
2691 struct lttcomm_relayd_rotate_rename header
;
2693 size_t received_paths_size
;
2694 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2695 struct lttng_buffer_view old_path_view
;
2696 struct lttng_buffer_view new_path_view
;
2698 if (!session
|| !conn
->version_check_done
) {
2699 ERR("Trying to rename a trace folder before version check");
2704 if (session
->major
== 2 && session
->minor
< 11) {
2705 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2710 header_len
= sizeof(header
);
2711 if (payload
->size
< header_len
) {
2712 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2713 header_len
, payload
->size
);
2718 memcpy(&header
, payload
->data
, header_len
);
2720 header
.old_path_length
= be32toh(header
.old_path_length
);
2721 header
.new_path_length
= be32toh(header
.new_path_length
);
2722 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2724 if (payload
->size
< header_len
+ received_paths_size
) {
2725 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2726 header_len
, payload
->size
);
2731 /* Ensure the paths don't exceed their allowed size. */
2732 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2736 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2741 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2742 header
.old_path_length
);
2743 new_path_view
= lttng_buffer_view_from_view(payload
,
2744 header_len
+ header
.old_path_length
,
2745 header
.new_path_length
);
2747 /* Validate that both paths received are NULL terminated. */
2748 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2749 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2753 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2754 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2759 complete_old_path
= create_output_path(old_path_view
.data
);
2760 if (!complete_old_path
) {
2761 ERR("Failed to build old output path in rotate_rename command");
2766 complete_new_path
= create_output_path(new_path_view
.data
);
2767 if (!complete_new_path
) {
2768 ERR("Failed to build new output path in rotate_rename command");
2773 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2776 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2782 * If a domain has not yet created its channel, the domain-specific
2783 * folder might not exist, but this is not an error.
2785 ret
= rename(complete_old_path
, complete_new_path
);
2786 if (ret
< 0 && errno
!= ENOENT
) {
2787 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2788 complete_old_path
, complete_new_path
);
2794 memset(&reply
, 0, sizeof(reply
));
2796 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2798 reply
.ret_code
= htobe32(LTTNG_OK
);
2800 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2802 if (send_ret
< sizeof(reply
)) {
2803 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2809 free(complete_old_path
);
2810 free(complete_new_path
);
2815 * Check if all the streams in the session have completed the last rotation.
2816 * The chunk_id value is used to distinguish the cases where a stream was
2817 * closed on the consumerd before the rotation started but it still active on
2818 * the relayd, and the case where a stream appeared on the consumerd/relayd
2819 * after the last rotation started (in that case, it is already writing in the
2820 * new chunk folder).
2823 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2824 struct relay_connection
*conn
,
2825 const struct lttng_buffer_view
*payload
)
2827 struct relay_session
*session
= conn
->session
;
2828 struct lttcomm_relayd_rotate_pending msg
;
2829 struct lttcomm_relayd_rotate_pending_reply reply
;
2830 struct lttng_ht_iter iter
;
2831 struct relay_stream
*stream
;
2835 bool rotate_pending
= false;
2837 DBG("Rotate pending command received");
2839 if (!session
|| !conn
->version_check_done
) {
2840 ERR("Trying to check for data before version check");
2845 if (session
->major
== 2 && session
->minor
< 11) {
2846 ERR("Unsupported feature before 2.11");
2851 if (payload
->size
< sizeof(msg
)) {
2852 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2853 sizeof(msg
), payload
->size
);
2858 memcpy(&msg
, payload
->data
, sizeof(msg
));
2860 chunk_id
= be64toh(msg
.chunk_id
);
2862 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2863 session
->session_name
, chunk_id
);
2866 * Iterate over all the streams in the session and check if they are
2867 * still waiting for data to perform their rotation.
2870 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2872 if (!stream_get(stream
)) {
2875 if (stream
->trace
->session
!= session
) {
2879 pthread_mutex_lock(&stream
->lock
);
2880 if (stream
->rotate_at_seq_num
!= -1ULL) {
2881 /* We have not yet performed the rotation. */
2882 rotate_pending
= true;
2883 DBG("Stream %" PRIu64
" is still rotating",
2884 stream
->stream_handle
);
2885 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
2887 * Stream closed on the consumer but still active on the
2890 rotate_pending
= true;
2891 DBG("Stream %" PRIu64
" did not exist on the consumer "
2892 "when the last rotation started, but is"
2893 "still waiting for data before getting"
2895 stream
->stream_handle
);
2897 pthread_mutex_unlock(&stream
->lock
);
2899 if (rotate_pending
) {
2906 memset(&reply
, 0, sizeof(reply
));
2907 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
2908 reply
.is_pending
= (uint8_t) !!rotate_pending
;
2909 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2911 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2912 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
2921 #define DBG_CMD(cmd_name, conn) \
2922 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2924 static int relay_process_control_command(struct relay_connection
*conn
,
2925 const struct lttcomm_relayd_hdr
*header
,
2926 const struct lttng_buffer_view
*payload
)
2930 switch (header
->cmd
) {
2931 case RELAYD_CREATE_SESSION
:
2932 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2933 ret
= relay_create_session(header
, conn
, payload
);
2935 case RELAYD_ADD_STREAM
:
2936 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2937 ret
= relay_add_stream(header
, conn
, payload
);
2939 case RELAYD_START_DATA
:
2940 DBG_CMD("RELAYD_START_DATA", conn
);
2941 ret
= relay_start(header
, conn
, payload
);
2943 case RELAYD_SEND_METADATA
:
2944 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2945 ret
= relay_recv_metadata(header
, conn
, payload
);
2947 case RELAYD_VERSION
:
2948 DBG_CMD("RELAYD_VERSION", conn
);
2949 ret
= relay_send_version(header
, conn
, payload
);
2951 case RELAYD_CLOSE_STREAM
:
2952 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2953 ret
= relay_close_stream(header
, conn
, payload
);
2955 case RELAYD_DATA_PENDING
:
2956 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2957 ret
= relay_data_pending(header
, conn
, payload
);
2959 case RELAYD_QUIESCENT_CONTROL
:
2960 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2961 ret
= relay_quiescent_control(header
, conn
, payload
);
2963 case RELAYD_BEGIN_DATA_PENDING
:
2964 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2965 ret
= relay_begin_data_pending(header
, conn
, payload
);
2967 case RELAYD_END_DATA_PENDING
:
2968 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2969 ret
= relay_end_data_pending(header
, conn
, payload
);
2971 case RELAYD_SEND_INDEX
:
2972 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2973 ret
= relay_recv_index(header
, conn
, payload
);
2975 case RELAYD_STREAMS_SENT
:
2976 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2977 ret
= relay_streams_sent(header
, conn
, payload
);
2979 case RELAYD_RESET_METADATA
:
2980 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2981 ret
= relay_reset_metadata(header
, conn
, payload
);
2983 case RELAYD_ROTATE_STREAM
:
2984 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
2985 ret
= relay_rotate_session_stream(header
, conn
, payload
);
2987 case RELAYD_ROTATE_RENAME
:
2988 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
2989 ret
= relay_rotate_rename(header
, conn
, payload
);
2991 case RELAYD_ROTATE_PENDING
:
2992 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
2993 ret
= relay_rotate_pending(header
, conn
, payload
);
2996 DBG_CMD("RELAYD_MKDIR", conn
);
2997 ret
= relay_mkdir(header
, conn
, payload
);
2999 case RELAYD_UPDATE_SYNC_INFO
:
3001 ERR("Received unknown command (%u)", header
->cmd
);
3002 relay_unknown_command(conn
);
3011 static enum relay_connection_status
relay_process_control_receive_payload(
3012 struct relay_connection
*conn
)
3015 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3016 struct lttng_dynamic_buffer
*reception_buffer
=
3017 &conn
->protocol
.ctrl
.reception_buffer
;
3018 struct ctrl_connection_state_receive_payload
*state
=
3019 &conn
->protocol
.ctrl
.state
.receive_payload
;
3020 struct lttng_buffer_view payload_view
;
3022 if (state
->left_to_receive
== 0) {
3023 /* Short-circuit for payload-less commands. */
3024 goto reception_complete
;
3027 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3028 reception_buffer
->data
+ state
->received
,
3029 state
->left_to_receive
, MSG_DONTWAIT
);
3031 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3032 PERROR("Unable to receive command payload on sock %d",
3034 status
= RELAY_CONNECTION_STATUS_ERROR
;
3037 } else if (ret
== 0) {
3038 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3039 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3044 assert(ret
<= state
->left_to_receive
);
3046 state
->left_to_receive
-= ret
;
3047 state
->received
+= ret
;
3049 if (state
->left_to_receive
> 0) {
3051 * Can't transition to the protocol's next state, wait to
3052 * receive the rest of the header.
3054 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3055 state
->received
, state
->left_to_receive
,
3061 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3062 conn
->sock
->fd
, state
->received
);
3064 * The payload required to process the command has been received.
3065 * A view to the reception buffer is forwarded to the various
3066 * commands and the state of the control is reset on success.
3068 * Commands are responsible for sending their reply to the peer.
3070 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3072 ret
= relay_process_control_command(conn
,
3073 &state
->header
, &payload_view
);
3075 status
= RELAY_CONNECTION_STATUS_ERROR
;
3079 ret
= connection_reset_protocol_state(conn
);
3081 status
= RELAY_CONNECTION_STATUS_ERROR
;
3087 static enum relay_connection_status
relay_process_control_receive_header(
3088 struct relay_connection
*conn
)
3091 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3092 struct lttcomm_relayd_hdr header
;
3093 struct lttng_dynamic_buffer
*reception_buffer
=
3094 &conn
->protocol
.ctrl
.reception_buffer
;
3095 struct ctrl_connection_state_receive_header
*state
=
3096 &conn
->protocol
.ctrl
.state
.receive_header
;
3098 assert(state
->left_to_receive
!= 0);
3100 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3101 reception_buffer
->data
+ state
->received
,
3102 state
->left_to_receive
, MSG_DONTWAIT
);
3104 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3105 PERROR("Unable to receive control command header on sock %d",
3107 status
= RELAY_CONNECTION_STATUS_ERROR
;
3110 } else if (ret
== 0) {
3111 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3112 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3117 assert(ret
<= state
->left_to_receive
);
3119 state
->left_to_receive
-= ret
;
3120 state
->received
+= ret
;
3122 if (state
->left_to_receive
> 0) {
3124 * Can't transition to the protocol's next state, wait to
3125 * receive the rest of the header.
3127 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3128 state
->received
, state
->left_to_receive
,
3133 /* Transition to next state: receiving the command's payload. */
3134 conn
->protocol
.ctrl
.state_id
=
3135 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3136 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3137 header
.circuit_id
= be64toh(header
.circuit_id
);
3138 header
.data_size
= be64toh(header
.data_size
);
3139 header
.cmd
= be32toh(header
.cmd
);
3140 header
.cmd_version
= be32toh(header
.cmd_version
);
3141 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3142 &header
, sizeof(header
));
3144 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3145 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3148 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3149 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3151 status
= RELAY_CONNECTION_STATUS_ERROR
;
3155 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3157 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3158 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3161 status
= RELAY_CONNECTION_STATUS_ERROR
;
3165 if (header
.data_size
== 0) {
3167 * Manually invoke the next state as the poll loop
3168 * will not wake-up to allow us to proceed further.
3170 status
= relay_process_control_receive_payload(conn
);
3177 * Process the commands received on the control socket
3179 static enum relay_connection_status
relay_process_control(
3180 struct relay_connection
*conn
)
3182 enum relay_connection_status status
;
3184 switch (conn
->protocol
.ctrl
.state_id
) {
3185 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3186 status
= relay_process_control_receive_header(conn
);
3188 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3189 status
= relay_process_control_receive_payload(conn
);
3192 ERR("Unknown control connection protocol state encountered.");
3200 * Handle index for a data stream.
3202 * Called with the stream lock held.
3204 * Return 0 on success else a negative value.
3206 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3207 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3210 uint64_t data_offset
;
3211 struct relay_index
*index
;
3213 /* Get data offset because we are about to update the index. */
3214 data_offset
= htobe64(stream
->tracefile_size_current
);
3216 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3217 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3220 * Lookup for an existing index for that stream id/sequence
3221 * number. If it exists, the control thread has already received the
3222 * data for it, thus we need to write it to disk.
3224 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3230 if (rotate_index
|| !stream
->index_file
) {
3231 ret
= create_rotate_index_file(stream
);
3233 ERR("Failed to rotate index");
3234 /* Put self-ref for this index due to error. */
3235 relay_index_put(index
);
3241 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3243 /* Put self-ref for this index due to error. */
3244 relay_index_put(index
);
3249 ret
= relay_index_try_flush(index
);
3251 tracefile_array_commit_seq(stream
->tfa
);
3252 stream
->index_received_seqcount
++;
3254 } else if (ret
> 0) {
3255 index
->total_size
= total_size
;
3259 /* Put self-ref for this index due to error. */
3260 relay_index_put(index
);
3268 static enum relay_connection_status
relay_process_data_receive_header(
3269 struct relay_connection
*conn
)
3272 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3273 struct data_connection_state_receive_header
*state
=
3274 &conn
->protocol
.data
.state
.receive_header
;
3275 struct lttcomm_relayd_data_hdr header
;
3276 struct relay_stream
*stream
;
3278 assert(state
->left_to_receive
!= 0);
3280 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3281 state
->header_reception_buffer
+ state
->received
,
3282 state
->left_to_receive
, MSG_DONTWAIT
);
3284 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3285 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3286 status
= RELAY_CONNECTION_STATUS_ERROR
;
3289 } else if (ret
== 0) {
3290 /* Orderly shutdown. Not necessary to print an error. */
3291 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3292 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3297 assert(ret
<= state
->left_to_receive
);
3299 state
->left_to_receive
-= ret
;
3300 state
->received
+= ret
;
3302 if (state
->left_to_receive
> 0) {
3304 * Can't transition to the protocol's next state, wait to
3305 * receive the rest of the header.
3307 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3308 state
->received
, state
->left_to_receive
,
3313 /* Transition to next state: receiving the payload. */
3314 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3316 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3317 header
.circuit_id
= be64toh(header
.circuit_id
);
3318 header
.stream_id
= be64toh(header
.stream_id
);
3319 header
.data_size
= be32toh(header
.data_size
);
3320 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3321 header
.padding_size
= be32toh(header
.padding_size
);
3322 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3324 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3326 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3327 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3329 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3330 conn
->sock
->fd
, header
.circuit_id
,
3331 header
.stream_id
, header
.data_size
,
3332 header
.net_seq_num
, header
.padding_size
);
3334 stream
= stream_get_by_id(header
.stream_id
);
3336 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3338 /* Protocol error. */
3339 status
= RELAY_CONNECTION_STATUS_ERROR
;
3343 pthread_mutex_lock(&stream
->lock
);
3345 /* Check if a rotation is needed. */
3346 if (stream
->tracefile_size
> 0 &&
3347 (stream
->tracefile_size_current
+ header
.data_size
) >
3348 stream
->tracefile_size
) {
3349 uint64_t old_id
, new_id
;
3351 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3352 tracefile_array_file_rotate(stream
->tfa
);
3354 /* new_id is updated by utils_rotate_stream_file. */
3357 ret
= utils_rotate_stream_file(stream
->path_name
,
3358 stream
->channel_name
, stream
->tracefile_size
,
3359 stream
->tracefile_count
, -1,
3360 -1, stream
->stream_fd
->fd
,
3361 &new_id
, &stream
->stream_fd
->fd
);
3363 ERR("Failed to rotate stream output file");
3364 status
= RELAY_CONNECTION_STATUS_ERROR
;
3365 goto end_stream_unlock
;
3369 * Reset current size because we just performed a stream
3372 stream
->tracefile_size_current
= 0;
3373 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3377 pthread_mutex_unlock(&stream
->lock
);
3383 static enum relay_connection_status
relay_process_data_receive_payload(
3384 struct relay_connection
*conn
)
3387 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3388 struct relay_stream
*stream
;
3389 struct data_connection_state_receive_payload
*state
=
3390 &conn
->protocol
.data
.state
.receive_payload
;
3391 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3392 char data_buffer
[chunk_size
];
3393 bool partial_recv
= false;
3394 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3395 uint64_t left_to_receive
= state
->left_to_receive
;
3396 struct relay_session
*session
;
3398 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3399 state
->header
.stream_id
, state
->header
.net_seq_num
,
3400 state
->received
, left_to_receive
);
3402 stream
= stream_get_by_id(state
->header
.stream_id
);
3404 /* Protocol error. */
3405 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3406 state
->header
.stream_id
);
3407 status
= RELAY_CONNECTION_STATUS_ERROR
;
3411 pthread_mutex_lock(&stream
->lock
);
3412 session
= stream
->trace
->session
;
3413 if (!conn
->session
) {
3414 ret
= connection_set_session(conn
, session
);
3416 status
= RELAY_CONNECTION_STATUS_ERROR
;
3417 goto end_stream_unlock
;
3422 * The size of the "chunk" received on any iteration is bounded by:
3423 * - the data left to receive,
3424 * - the data immediately available on the socket,
3425 * - the on-stack data buffer
3427 while (left_to_receive
> 0 && !partial_recv
) {
3429 size_t recv_size
= min(left_to_receive
, chunk_size
);
3431 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3432 recv_size
, MSG_DONTWAIT
);
3434 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3435 PERROR("Socket %d error", conn
->sock
->fd
);
3436 status
= RELAY_CONNECTION_STATUS_ERROR
;
3438 goto end_stream_unlock
;
3439 } else if (ret
== 0) {
3440 /* No more data ready to be consumed on socket. */
3441 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3442 state
->header
.stream_id
);
3443 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3445 } else if (ret
< (int) recv_size
) {
3447 * All the data available on the socket has been
3450 partial_recv
= true;
3455 /* Write data to stream output fd. */
3456 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3458 if (write_ret
< (ssize_t
) recv_size
) {
3459 ERR("Relay error writing data to file");
3460 status
= RELAY_CONNECTION_STATUS_ERROR
;
3461 goto end_stream_unlock
;
3464 left_to_receive
-= recv_size
;
3465 state
->received
+= recv_size
;
3466 state
->left_to_receive
= left_to_receive
;
3468 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3469 write_ret
, stream
->stream_handle
);
3472 if (state
->left_to_receive
> 0) {
3474 * Did not receive all the data expected, wait for more data to
3475 * become available on the socket.
3477 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3478 state
->header
.stream_id
, state
->received
,
3479 state
->left_to_receive
);
3480 goto end_stream_unlock
;
3483 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3484 state
->header
.padding_size
);
3485 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3486 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3487 stream
->stream_handle
,
3488 state
->header
.net_seq_num
, ret
);
3489 status
= RELAY_CONNECTION_STATUS_ERROR
;
3490 goto end_stream_unlock
;
3494 if (session
->minor
>= 4 && !session
->snapshot
) {
3495 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3496 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3498 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3499 stream
->stream_handle
,
3500 state
->header
.net_seq_num
, ret
);
3501 status
= RELAY_CONNECTION_STATUS_ERROR
;
3502 goto end_stream_unlock
;
3506 stream
->tracefile_size_current
+= state
->header
.data_size
+
3507 state
->header
.padding_size
;
3509 if (stream
->prev_seq
== -1ULL) {
3512 if (index_flushed
) {
3513 stream
->pos_after_last_complete_data_index
=
3514 stream
->tracefile_size_current
;
3517 stream
->prev_seq
= state
->header
.net_seq_num
;
3520 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3521 * contents of *state which are aliased (union) to the same location as
3522 * the new state. Don't use it beyond this point.
3524 connection_reset_protocol_state(conn
);
3527 ret
= try_rotate_stream(stream
);
3529 status
= RELAY_CONNECTION_STATUS_ERROR
;
3530 goto end_stream_unlock
;
3534 close_requested
= stream
->close_requested
;
3535 pthread_mutex_unlock(&stream
->lock
);
3536 if (close_requested
&& left_to_receive
== 0) {
3537 try_stream_close(stream
);
3541 pthread_mutex_lock(&session
->lock
);
3542 uatomic_set(&session
->new_streams
, 1);
3543 pthread_mutex_unlock(&session
->lock
);
3552 * relay_process_data: Process the data received on the data socket
3554 static enum relay_connection_status
relay_process_data(
3555 struct relay_connection
*conn
)
3557 enum relay_connection_status status
;
3559 switch (conn
->protocol
.data
.state_id
) {
3560 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3561 status
= relay_process_data_receive_header(conn
);
3563 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3564 status
= relay_process_data_receive_payload(conn
);
3567 ERR("Unexpected data connection communication state.");
3574 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3578 (void) lttng_poll_del(events
, pollfd
);
3580 ret
= close(pollfd
);
3582 ERR("Closing pollfd %d", pollfd
);
3586 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3587 int pollfd
, struct relay_connection
*conn
)
3589 const char *type_str
;
3591 switch (conn
->type
) {
3596 type_str
= "Control";
3598 case RELAY_VIEWER_COMMAND
:
3599 type_str
= "Viewer Command";
3601 case RELAY_VIEWER_NOTIFICATION
:
3602 type_str
= "Viewer Notification";
3605 type_str
= "Unknown";
3607 cleanup_connection_pollfd(events
, pollfd
);
3608 connection_put(conn
);
3609 DBG("%s connection closed with %d", type_str
, pollfd
);
3613 * This thread does the actual work
3615 static void *relay_thread_worker(void *data
)
3617 int ret
, err
= -1, last_seen_data_fd
= -1;
3619 struct lttng_poll_event events
;
3620 struct lttng_ht
*relay_connections_ht
;
3621 struct lttng_ht_iter iter
;
3622 struct relay_connection
*destroy_conn
= NULL
;
3624 DBG("[thread] Relay worker started");
3626 rcu_register_thread();
3628 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3630 if (testpoint(relayd_thread_worker
)) {
3631 goto error_testpoint
;
3634 health_code_update();
3636 /* table of connections indexed on socket */
3637 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3638 if (!relay_connections_ht
) {
3639 goto relay_connections_ht_error
;
3642 ret
= create_thread_poll_set(&events
, 2);
3644 goto error_poll_create
;
3647 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3654 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3656 health_code_update();
3658 /* Infinite blocking call, waiting for transmission */
3659 DBG3("Relayd worker thread polling...");
3660 health_poll_entry();
3661 ret
= lttng_poll_wait(&events
, -1);
3665 * Restart interrupted system call.
3667 if (errno
== EINTR
) {
3676 * Process control. The control connection is
3677 * prioritized so we don't starve it with high
3678 * throughput tracing data on the data connection.
3680 for (i
= 0; i
< nb_fd
; i
++) {
3681 /* Fetch once the poll data */
3682 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3683 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3685 health_code_update();
3689 * No activity for this FD (poll
3695 /* Thread quit pipe has been closed. Killing thread. */
3696 ret
= check_thread_quit_pipe(pollfd
, revents
);
3702 /* Inspect the relay conn pipe for new connection */
3703 if (pollfd
== relay_conn_pipe
[0]) {
3704 if (revents
& LPOLLIN
) {
3705 struct relay_connection
*conn
;
3707 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3711 lttng_poll_add(&events
, conn
->sock
->fd
,
3712 LPOLLIN
| LPOLLRDHUP
);
3713 connection_ht_add(relay_connections_ht
, conn
);
3714 DBG("Connection socket %d added", conn
->sock
->fd
);
3715 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3716 ERR("Relay connection pipe error");
3719 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3723 struct relay_connection
*ctrl_conn
;
3725 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3726 /* If not found, there is a synchronization issue. */
3729 if (ctrl_conn
->type
== RELAY_DATA
) {
3730 if (revents
& LPOLLIN
) {
3732 * Flag the last seen data fd not deleted. It will be
3733 * used as the last seen fd if any fd gets deleted in
3736 last_notdel_data_fd
= pollfd
;
3738 goto put_ctrl_connection
;
3740 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3742 if (revents
& LPOLLIN
) {
3743 enum relay_connection_status status
;
3745 status
= relay_process_control(ctrl_conn
);
3746 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3748 * On socket error flag the session as aborted to force
3749 * the cleanup of its stream otherwise it can leak
3750 * during the lifetime of the relayd.
3752 * This prevents situations in which streams can be
3753 * left opened because an index was received, the
3754 * control connection is closed, and the data
3755 * connection is closed (uncleanly) before the packet's
3758 * Since the control connection encountered an error,
3759 * it is okay to be conservative and close the
3760 * session right now as we can't rely on the protocol
3761 * being respected anymore.
3763 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3764 session_abort(ctrl_conn
->session
);
3767 /* Clear the connection on error or close. */
3768 relay_thread_close_connection(&events
,
3773 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3774 relay_thread_close_connection(&events
,
3776 if (last_seen_data_fd
== pollfd
) {
3777 last_seen_data_fd
= last_notdel_data_fd
;
3780 ERR("Unexpected poll events %u for control sock %d",
3782 connection_put(ctrl_conn
);
3785 put_ctrl_connection
:
3786 connection_put(ctrl_conn
);
3791 * The last loop handled a control request, go back to poll to make
3792 * sure we prioritise the control socket.
3798 if (last_seen_data_fd
>= 0) {
3799 for (i
= 0; i
< nb_fd
; i
++) {
3800 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3802 health_code_update();
3804 if (last_seen_data_fd
== pollfd
) {
3811 /* Process data connection. */
3812 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3813 /* Fetch the poll data. */
3814 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3815 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3816 struct relay_connection
*data_conn
;
3818 health_code_update();
3821 /* No activity for this FD (poll implementation). */
3825 /* Skip the command pipe. It's handled in the first loop. */
3826 if (pollfd
== relay_conn_pipe
[0]) {
3830 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3832 /* Skip it. Might be removed before. */
3835 if (data_conn
->type
== RELAY_CONTROL
) {
3836 goto put_data_connection
;
3838 assert(data_conn
->type
== RELAY_DATA
);
3840 if (revents
& LPOLLIN
) {
3841 enum relay_connection_status status
;
3843 status
= relay_process_data(data_conn
);
3844 /* Connection closed or error. */
3845 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3847 * On socket error flag the session as aborted to force
3848 * the cleanup of its stream otherwise it can leak
3849 * during the lifetime of the relayd.
3851 * This prevents situations in which streams can be
3852 * left opened because an index was received, the
3853 * control connection is closed, and the data
3854 * connection is closed (uncleanly) before the packet's
3857 * Since the data connection encountered an error,
3858 * it is okay to be conservative and close the
3859 * session right now as we can't rely on the protocol
3860 * being respected anymore.
3862 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3863 session_abort(data_conn
->session
);
3865 relay_thread_close_connection(&events
, pollfd
,
3868 * Every goto restart call sets the last seen fd where
3869 * here we don't really care since we gracefully
3870 * continue the loop after the connection is deleted.
3873 /* Keep last seen port. */
3874 last_seen_data_fd
= pollfd
;
3875 connection_put(data_conn
);
3878 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3879 relay_thread_close_connection(&events
, pollfd
,
3882 ERR("Unknown poll events %u for data sock %d",
3885 put_data_connection
:
3886 connection_put(data_conn
);
3888 last_seen_data_fd
= -1;
3891 /* Normal exit, no error */
3896 /* Cleanup remaining connection object. */
3898 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3901 health_code_update();
3903 session_abort(destroy_conn
->session
);
3906 * No need to grab another ref, because we own
3909 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3914 lttng_poll_clean(&events
);
3916 lttng_ht_destroy(relay_connections_ht
);
3917 relay_connections_ht_error
:
3918 /* Close relay conn pipes */
3919 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3922 DBG("Thread exited with error");
3924 DBG("Worker thread cleanup complete");
3928 ERR("Health error occurred in %s", __func__
);
3930 health_unregister(health_relayd
);
3931 rcu_unregister_thread();
3932 lttng_relay_stop_threads();
3937 * Create the relay command pipe to wake thread_manage_apps.
3938 * Closed in cleanup().
3940 static int create_relay_conn_pipe(void)
3942 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3943 "Relayd connection pipe", relay_conn_pipe
);
3949 int main(int argc
, char **argv
)
3951 int ret
= 0, retval
= 0;
3954 /* Parse arguments */
3956 if (set_options(argc
, argv
)) {
3961 if (set_signal_handler()) {
3966 ret
= fclose(stdin
);
3968 PERROR("Failed to close stdin");
3971 /* Try to create directory if -o, --output is specified. */
3972 if (opt_output_path
) {
3973 if (*opt_output_path
!= '/') {
3974 ERR("Please specify an absolute path for -o, --output PATH");
3979 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3982 ERR("Unable to create %s", opt_output_path
);
3989 if (opt_daemon
|| opt_background
) {
3990 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3999 * The RCU thread registration (and use, through the fd-tracker's
4000 * creation) is done after the daemonization to allow us to not
4001 * deal with liburcu's fork() management as the call RCU needs to
4004 rcu_register_thread();
4006 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
4007 if (!the_fd_tracker
) {
4012 /* Initialize thread health monitoring */
4013 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4014 if (!health_relayd
) {
4015 PERROR("health_app_create error");
4017 goto exit_health_app_create
;
4020 /* Create thread quit pipe */
4021 if (init_thread_quit_pipe()) {
4023 goto exit_init_data
;
4026 /* Setup the thread apps communication pipe. */
4027 if (create_relay_conn_pipe()) {
4029 goto exit_init_data
;
4032 /* Init relay command queue. */
4033 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4035 /* Initialize communication library */
4037 lttcomm_inet_init();
4039 /* tables of sessions indexed by session ID */
4040 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4043 goto exit_init_data
;
4046 /* tables of streams indexed by stream ID */
4047 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4048 if (!relay_streams_ht
) {
4050 goto exit_init_data
;
4053 /* tables of streams indexed by stream ID */
4054 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4055 if (!viewer_streams_ht
) {
4057 goto exit_init_data
;
4060 ret
= utils_create_pipe(health_quit_pipe
);
4063 goto exit_health_quit_pipe
;
4066 /* Create thread to manage the client socket */
4067 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4068 thread_manage_health
, (void *) NULL
);
4071 PERROR("pthread_create health");
4073 goto exit_health_thread
;
4076 /* Setup the dispatcher thread */
4077 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4078 relay_thread_dispatcher
, (void *) NULL
);
4081 PERROR("pthread_create dispatcher");
4083 goto exit_dispatcher_thread
;
4086 /* Setup the worker thread */
4087 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4088 relay_thread_worker
, NULL
);
4091 PERROR("pthread_create worker");
4093 goto exit_worker_thread
;
4096 /* Setup the listener thread */
4097 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4098 relay_thread_listener
, (void *) NULL
);
4101 PERROR("pthread_create listener");
4103 goto exit_listener_thread
;
4106 ret
= relayd_live_create(live_uri
);
4108 ERR("Starting live viewer threads");
4114 * This is where we start awaiting program completion (e.g. through
4115 * signal that asks threads to teardown).
4118 ret
= relayd_live_join();
4124 ret
= pthread_join(listener_thread
, &status
);
4127 PERROR("pthread_join listener_thread");
4131 exit_listener_thread
:
4132 ret
= pthread_join(worker_thread
, &status
);
4135 PERROR("pthread_join worker_thread");
4140 ret
= pthread_join(dispatcher_thread
, &status
);
4143 PERROR("pthread_join dispatcher_thread");
4146 exit_dispatcher_thread
:
4148 ret
= pthread_join(health_thread
, &status
);
4151 PERROR("pthread_join health_thread");
4156 utils_close_pipe(health_quit_pipe
);
4157 exit_health_quit_pipe
:
4160 health_app_destroy(health_relayd
);
4161 exit_health_app_create
:
4164 * Wait for all pending call_rcu work to complete before tearing
4165 * down data structures. call_rcu worker may be trying to
4166 * perform lookups in those structures.
4171 /* Ensure all prior call_rcu are done. */
4174 fd_tracker_destroy(the_fd_tracker
);
4175 rcu_unregister_thread();