2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
37 #include <sys/resource.h>
39 #include <urcu/futex.h>
40 #include <urcu/uatomic.h>
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/align.h>
60 #include <common/config/session-config.h>
61 #include <common/dynamic-buffer.h>
62 #include <common/buffer-view.h>
63 #include <common/fd-tracker/utils.h>
64 #include <urcu/rculist.h>
67 #include "ctf-trace.h"
70 #include "lttng-relayd.h"
72 #include "health-relayd.h"
73 #include "testpoint.h"
74 #include "viewer-stream.h"
77 #include "connection.h"
78 #include "tracefile-array.h"
79 #include "tcp_keep_alive.h"
81 static const char *help_msg
=
82 #ifdef LTTNG_EMBED_HELP
83 #include <lttng-relayd.8.h>
89 enum relay_connection_status
{
90 RELAY_CONNECTION_STATUS_OK
,
91 /* An error occured while processing an event on the connection. */
92 RELAY_CONNECTION_STATUS_ERROR
,
93 /* Connection closed/shutdown cleanly. */
94 RELAY_CONNECTION_STATUS_CLOSED
,
97 /* command line options */
98 char *opt_output_path
;
99 static int opt_daemon
, opt_background
;
102 * We need to wait for listener and live listener threads, as well as
103 * health check thread, before being ready to signal readiness.
105 #define NR_LTTNG_RELAY_READY 3
106 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
108 /* Size of receive buffer. */
109 #define RECV_DATA_BUFFER_SIZE 65536
110 #define FILE_COPY_BUFFER_SIZE 65536
112 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
113 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
115 static struct lttng_uri
*control_uri
;
116 static struct lttng_uri
*data_uri
;
117 static struct lttng_uri
*live_uri
;
119 const char *progname
;
121 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
122 static int tracing_group_name_override
;
124 const char * const config_section_name
= "relayd";
127 * Quit pipe for all threads. This permits a single cancellation point
128 * for all threads when receiving an event on the pipe.
130 int thread_quit_pipe
[2] = { -1, -1 };
133 * This pipe is used to inform the worker thread that a command is queued and
134 * ready to be processed.
136 static int relay_conn_pipe
[2] = { -1, -1 };
138 /* Shared between threads */
139 static int dispatch_thread_exit
;
141 static pthread_t listener_thread
;
142 static pthread_t dispatcher_thread
;
143 static pthread_t worker_thread
;
144 static pthread_t health_thread
;
147 * last_relay_stream_id_lock protects last_relay_stream_id increment
148 * atomicity on 32-bit architectures.
150 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
151 static uint64_t last_relay_stream_id
;
154 * Relay command queue.
156 * The relay_thread_listener and relay_thread_dispatcher communicate with this
159 static struct relay_conn_queue relay_conn_queue
;
161 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
162 static unsigned int lttng_opt_fd_cap
;
164 /* Global relay stream hash table. */
165 struct lttng_ht
*relay_streams_ht
;
167 /* Global relay viewer stream hash table. */
168 struct lttng_ht
*viewer_streams_ht
;
170 /* Global relay sessions hash table. */
171 struct lttng_ht
*sessions_ht
;
173 /* Relayd health monitoring */
174 struct health_app
*health_relayd
;
176 /* Global fd tracker. */
177 struct fd_tracker
*the_fd_tracker
;
179 static struct option long_options
[] = {
180 { "control-port", 1, 0, 'C', },
181 { "data-port", 1, 0, 'D', },
182 { "live-port", 1, 0, 'L', },
183 { "daemonize", 0, 0, 'd', },
184 { "background", 0, 0, 'b', },
185 { "group", 1, 0, 'g', },
186 { "fd-cap", 1, 0, '\0', },
187 { "help", 0, 0, 'h', },
188 { "output", 1, 0, 'o', },
189 { "verbose", 0, 0, 'v', },
190 { "config", 1, 0, 'f' },
191 { "version", 0, 0, 'V' },
195 static const char *config_ignore_options
[] = { "help", "config", "version" };
198 * Take an option from the getopt output and set it in the right variable to be
201 * Return 0 on success else a negative value.
203 static int set_option(int opt
, const char *arg
, const char *optname
)
209 if (!strcmp(optname
, "fd-cap")) {
213 v
= strtoul(arg
, NULL
, 0);
214 if (errno
!= 0 || !isdigit(arg
[0])) {
215 ERR("Wrong value in --fd-cap parameter: %s", arg
);
219 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
220 ERR("File descriptor cap must be set to at least %d",
221 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
224 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
228 lttng_opt_fd_cap
= (unsigned int) v
;
229 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
232 fprintf(stderr
, "unknown option %s", optname
);
234 fprintf(stderr
, " with arg %s\n", arg
);
239 if (lttng_is_setuid_setgid()) {
240 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
241 "-C, --control-port");
243 ret
= uri_parse(arg
, &control_uri
);
245 ERR("Invalid control URI specified");
248 if (control_uri
->port
== 0) {
249 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
254 if (lttng_is_setuid_setgid()) {
255 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
258 ret
= uri_parse(arg
, &data_uri
);
260 ERR("Invalid data URI specified");
263 if (data_uri
->port
== 0) {
264 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
269 if (lttng_is_setuid_setgid()) {
270 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
273 ret
= uri_parse(arg
, &live_uri
);
275 ERR("Invalid live URI specified");
278 if (live_uri
->port
== 0) {
279 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
290 if (lttng_is_setuid_setgid()) {
291 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
294 tracing_group_name
= strdup(arg
);
295 if (tracing_group_name
== NULL
) {
300 tracing_group_name_override
= 1;
304 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
306 ERR("Cannot show --help for `lttng-relayd`");
311 fprintf(stdout
, "%s\n", VERSION
);
314 if (lttng_is_setuid_setgid()) {
315 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
318 ret
= asprintf(&opt_output_path
, "%s", arg
);
321 PERROR("asprintf opt_output_path");
327 /* Verbose level can increase using multiple -v */
329 lttng_opt_verbose
= config_parse_value(arg
);
331 /* Only 3 level of verbosity (-vvv). */
332 if (lttng_opt_verbose
< 3) {
333 lttng_opt_verbose
+= 1;
338 /* Unknown option or other error.
339 * Error is printed by getopt, just return */
352 * config_entry_handler_cb used to handle options read from a config file.
353 * See config_entry_handler_cb comment in common/config/session-config.h for the
354 * return value conventions.
356 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
360 if (!entry
|| !entry
->name
|| !entry
->value
) {
365 /* Check if the option is to be ignored */
366 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
367 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
372 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
373 /* Ignore if entry name is not fully matched. */
374 if (strcmp(entry
->name
, long_options
[i
].name
)) {
379 * If the option takes no argument on the command line,
380 * we have to check if the value is "true". We support
381 * non-zero numeric values, true, on and yes.
383 if (!long_options
[i
].has_arg
) {
384 ret
= config_parse_value(entry
->value
);
387 WARN("Invalid configuration value \"%s\" for option %s",
388 entry
->value
, entry
->name
);
390 /* False, skip boolean config option. */
395 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
399 WARN("Unrecognized option \"%s\" in daemon configuration file.",
406 static int set_options(int argc
, char **argv
)
408 int c
, ret
= 0, option_index
= 0, retval
= 0;
409 int orig_optopt
= optopt
, orig_optind
= optind
;
410 char *default_address
, *optstring
;
411 const char *config_path
= NULL
;
413 optstring
= utils_generate_optstring(long_options
,
414 sizeof(long_options
) / sizeof(struct option
));
420 /* Check for the --config option */
422 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
423 &option_index
)) != -1) {
427 } else if (c
!= 'f') {
431 if (lttng_is_setuid_setgid()) {
432 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
435 config_path
= utils_expand_path(optarg
);
437 ERR("Failed to resolve path: %s", optarg
);
442 ret
= config_get_section_entries(config_path
, config_section_name
,
443 config_entry_handler
, NULL
);
446 ERR("Invalid configuration option at line %i", ret
);
452 /* Reset getopt's global state */
453 optopt
= orig_optopt
;
454 optind
= orig_optind
;
456 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
461 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
468 /* assign default values */
469 if (control_uri
== NULL
) {
470 ret
= asprintf(&default_address
,
471 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
472 DEFAULT_NETWORK_CONTROL_PORT
);
474 PERROR("asprintf default data address");
479 ret
= uri_parse(default_address
, &control_uri
);
480 free(default_address
);
482 ERR("Invalid control URI specified");
487 if (data_uri
== NULL
) {
488 ret
= asprintf(&default_address
,
489 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
490 DEFAULT_NETWORK_DATA_PORT
);
492 PERROR("asprintf default data address");
497 ret
= uri_parse(default_address
, &data_uri
);
498 free(default_address
);
500 ERR("Invalid data URI specified");
505 if (live_uri
== NULL
) {
506 ret
= asprintf(&default_address
,
507 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
508 DEFAULT_NETWORK_VIEWER_PORT
);
510 PERROR("asprintf default viewer control address");
515 ret
= uri_parse(default_address
, &live_uri
);
516 free(default_address
);
518 ERR("Invalid viewer control URI specified");
523 if (lttng_opt_fd_cap
== 0) {
525 struct rlimit rlimit
;
527 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
529 PERROR("Failed to get file descriptor limit");
533 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
541 static void print_global_objects(void)
543 print_viewer_streams();
544 print_relay_streams();
551 static void relayd_cleanup(void)
553 print_global_objects();
557 if (viewer_streams_ht
)
558 lttng_ht_destroy(viewer_streams_ht
);
559 if (relay_streams_ht
)
560 lttng_ht_destroy(relay_streams_ht
);
562 lttng_ht_destroy(sessions_ht
);
564 /* free the dynamically allocated opt_output_path */
565 free(opt_output_path
);
567 /* Close thread quit pipes */
568 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
570 uri_free(control_uri
);
572 /* Live URI is freed in the live thread. */
574 if (tracing_group_name_override
) {
575 free((void *) tracing_group_name
);
580 * Write to writable pipe used to notify a thread.
582 static int notify_thread_pipe(int wpipe
)
586 ret
= lttng_write(wpipe
, "!", 1);
588 PERROR("write poll pipe");
596 static int notify_health_quit_pipe(int *pipe
)
600 ret
= lttng_write(pipe
[1], "4", 1);
602 PERROR("write relay health quit");
611 * Stop all relayd and relayd-live threads.
613 int lttng_relay_stop_threads(void)
617 /* Stopping all threads */
618 DBG("Terminating all threads");
619 if (notify_thread_pipe(thread_quit_pipe
[1])) {
620 ERR("write error on thread quit pipe");
624 if (notify_health_quit_pipe(health_quit_pipe
)) {
625 ERR("write error on health quit pipe");
628 /* Dispatch thread */
629 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
630 futex_nto1_wake(&relay_conn_queue
.futex
);
632 if (relayd_live_stop()) {
633 ERR("Error stopping live threads");
640 * Signal handler for the daemon
642 * Simply stop all worker threads, leaving main() return gracefully after
643 * joining all threads and calling cleanup().
645 static void sighandler(int sig
)
649 DBG("SIGINT caught");
650 if (lttng_relay_stop_threads()) {
651 ERR("Error stopping threads");
655 DBG("SIGTERM caught");
656 if (lttng_relay_stop_threads()) {
657 ERR("Error stopping threads");
661 CMM_STORE_SHARED(recv_child_signal
, 1);
669 * Setup signal handler for :
670 * SIGINT, SIGTERM, SIGPIPE
672 static int set_signal_handler(void)
678 if ((ret
= sigemptyset(&sigset
)) < 0) {
679 PERROR("sigemptyset");
686 sa
.sa_handler
= sighandler
;
687 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
692 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
697 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
702 sa
.sa_handler
= SIG_IGN
;
703 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
708 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
713 void lttng_relay_notify_ready(void)
715 /* Notify the parent of the fork() process that we are ready. */
716 if (opt_daemon
|| opt_background
) {
717 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
718 kill(child_ppid
, SIGUSR1
);
724 * Init thread quit pipe.
726 * Return -1 on error or 0 if all pipes are created.
728 static int init_thread_quit_pipe(void)
730 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
731 "Quit pipe", thread_quit_pipe
);
735 * Init health quit pipe.
737 * Return -1 on error or 0 if all pipes are created.
739 static int init_health_quit_pipe(void)
741 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
742 "Health quit pipe", health_quit_pipe
);
746 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
748 static int create_named_thread_poll_set(struct lttng_poll_event
*events
,
749 int size
, const char *name
)
753 if (events
== NULL
|| size
== 0) {
758 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
759 name
, events
, 1, LTTNG_CLOEXEC
);
762 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
774 * Check if the thread quit pipe was triggered.
776 * Return 1 if it was triggered else 0;
778 static int check_thread_quit_pipe(int fd
, uint32_t events
)
780 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
788 * Create and init socket from uri.
790 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
793 struct lttcomm_sock
*sock
= NULL
;
795 sock
= lttcomm_alloc_sock_from_uri(uri
);
797 ERR("Allocating socket");
801 ret
= lttcomm_create_sock(sock
);
805 DBG("Listening on sock %d", sock
->fd
);
807 ret
= sock
->ops
->bind(sock
);
809 PERROR("Failed to bind socket");
813 ret
= sock
->ops
->listen(sock
, -1);
823 lttcomm_destroy_sock(sock
);
829 * This thread manages the listening for new connections on the network
831 static void *relay_thread_listener(void *data
)
833 int i
, ret
, pollfd
, err
= -1;
834 uint32_t revents
, nb_fd
;
835 struct lttng_poll_event events
;
836 struct lttcomm_sock
*control_sock
, *data_sock
;
838 DBG("[thread] Relay listener started");
840 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
842 health_code_update();
844 control_sock
= relay_socket_create(control_uri
);
846 goto error_sock_control
;
849 data_sock
= relay_socket_create(data_uri
);
851 goto error_sock_relay
;
855 * Pass 3 as size here for the thread quit pipe, control and
858 ret
= create_named_thread_poll_set(&events
, 3, "Listener thread epoll");
860 goto error_create_poll
;
863 /* Add the control socket */
864 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
869 /* Add the data socket */
870 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
875 lttng_relay_notify_ready();
877 if (testpoint(relayd_thread_listener
)) {
878 goto error_testpoint
;
882 health_code_update();
884 DBG("Listener accepting connections");
888 ret
= lttng_poll_wait(&events
, -1);
892 * Restart interrupted system call.
894 if (errno
== EINTR
) {
902 DBG("Relay new connection received");
903 for (i
= 0; i
< nb_fd
; i
++) {
904 health_code_update();
906 /* Fetch once the poll data */
907 revents
= LTTNG_POLL_GETEV(&events
, i
);
908 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
912 * No activity for this FD (poll
918 /* Thread quit pipe has been closed. Killing thread. */
919 ret
= check_thread_quit_pipe(pollfd
, revents
);
925 if (revents
& LPOLLIN
) {
927 * A new connection is requested, therefore a
928 * sessiond/consumerd connection is allocated in
929 * this thread, enqueued to a global queue and
930 * dequeued (and freed) in the worker thread.
933 struct relay_connection
*new_conn
;
934 struct lttcomm_sock
*newsock
;
935 enum connection_type type
;
937 if (pollfd
== data_sock
->fd
) {
939 newsock
= data_sock
->ops
->accept(data_sock
);
940 DBG("Relay data connection accepted, socket %d",
943 assert(pollfd
== control_sock
->fd
);
944 type
= RELAY_CONTROL
;
945 newsock
= control_sock
->ops
->accept(control_sock
);
946 DBG("Relay control connection accepted, socket %d",
950 PERROR("accepting sock");
954 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
957 PERROR("setsockopt inet");
958 lttcomm_destroy_sock(newsock
);
962 ret
= socket_apply_keep_alive_config(newsock
->fd
);
964 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
966 lttcomm_destroy_sock(newsock
);
970 new_conn
= connection_create(newsock
, type
);
972 lttcomm_destroy_sock(newsock
);
976 /* Enqueue request for the dispatcher thread. */
977 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
981 * Wake the dispatch queue futex.
982 * Implicit memory barrier with the
983 * exchange in cds_wfcq_enqueue.
985 futex_nto1_wake(&relay_conn_queue
.futex
);
986 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
987 ERR("socket poll error");
990 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1000 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
1002 if (data_sock
->fd
>= 0) {
1003 ret
= data_sock
->ops
->close(data_sock
);
1008 lttcomm_destroy_sock(data_sock
);
1010 if (control_sock
->fd
>= 0) {
1011 ret
= control_sock
->ops
->close(control_sock
);
1016 lttcomm_destroy_sock(control_sock
);
1020 ERR("Health error occurred in %s", __func__
);
1022 health_unregister(health_relayd
);
1023 DBG("Relay listener thread cleanup complete");
1024 lttng_relay_stop_threads();
1029 * This thread manages the dispatching of the requests to worker threads
1031 static void *relay_thread_dispatcher(void *data
)
1035 struct cds_wfcq_node
*node
;
1036 struct relay_connection
*new_conn
= NULL
;
1038 DBG("[thread] Relay dispatcher started");
1040 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1042 if (testpoint(relayd_thread_dispatcher
)) {
1043 goto error_testpoint
;
1046 health_code_update();
1049 health_code_update();
1051 /* Atomically prepare the queue futex */
1052 futex_nto1_prepare(&relay_conn_queue
.futex
);
1054 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1059 health_code_update();
1061 /* Dequeue commands */
1062 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1063 &relay_conn_queue
.tail
);
1065 DBG("Woken up but nothing in the relay command queue");
1066 /* Continue thread execution */
1069 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1071 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1074 * Inform worker thread of the new request. This
1075 * call is blocking so we can be assured that
1076 * the data will be read at some point in time
1077 * or wait to the end of the world :)
1079 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1081 PERROR("write connection pipe");
1082 connection_put(new_conn
);
1085 } while (node
!= NULL
);
1087 /* Futex wait on queue. Blocking call on futex() */
1088 health_poll_entry();
1089 futex_nto1_wait(&relay_conn_queue
.futex
);
1093 /* Normal exit, no error */
1100 ERR("Health error occurred in %s", __func__
);
1102 health_unregister(health_relayd
);
1103 DBG("Dispatch thread dying");
1104 lttng_relay_stop_threads();
1109 * Set index data from the control port to a given index object.
1111 static int set_index_control_data(struct relay_index
*index
,
1112 struct lttcomm_relayd_index
*data
,
1113 struct relay_connection
*conn
)
1115 struct ctf_packet_index index_data
;
1118 * The index on disk is encoded in big endian.
1120 index_data
.packet_size
= htobe64(data
->packet_size
);
1121 index_data
.content_size
= htobe64(data
->content_size
);
1122 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1123 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1124 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1125 index_data
.stream_id
= htobe64(data
->stream_id
);
1127 if (conn
->minor
>= 8) {
1128 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1129 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1132 return relay_index_set_data(index
, &index_data
);
1136 * Handle the RELAYD_CREATE_SESSION command.
1138 * On success, send back the session id or else return a negative value.
1140 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1141 struct relay_connection
*conn
,
1142 const struct lttng_buffer_view
*payload
)
1146 struct relay_session
*session
;
1147 struct lttcomm_relayd_status_session reply
;
1148 char session_name
[LTTNG_NAME_MAX
];
1149 char hostname
[LTTNG_HOST_NAME_MAX
];
1150 uint32_t live_timer
= 0;
1151 bool snapshot
= false;
1153 memset(session_name
, 0, LTTNG_NAME_MAX
);
1154 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1156 memset(&reply
, 0, sizeof(reply
));
1158 if (conn
->minor
< 4) {
1159 /* From 2.1 to 2.3 */
1161 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1162 /* From 2.4 to 2.10 */
1163 ret
= cmd_create_session_2_4(payload
, session_name
,
1164 hostname
, &live_timer
, &snapshot
);
1166 /* From 2.11 to ... */
1167 ret
= cmd_create_session_2_11(payload
, session_name
,
1168 hostname
, &live_timer
, &snapshot
);
1175 session
= session_create(session_name
, hostname
, live_timer
,
1176 snapshot
, conn
->major
, conn
->minor
);
1181 assert(!conn
->session
);
1182 conn
->session
= session
;
1183 DBG("Created session %" PRIu64
, session
->id
);
1185 reply
.session_id
= htobe64(session
->id
);
1189 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1191 reply
.ret_code
= htobe32(LTTNG_OK
);
1194 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1195 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1196 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1205 * When we have received all the streams and the metadata for a channel,
1206 * we make them visible to the viewer threads.
1208 static void publish_connection_local_streams(struct relay_connection
*conn
)
1210 struct relay_stream
*stream
;
1211 struct relay_session
*session
= conn
->session
;
1214 * We publish all streams belonging to a session atomically wrt
1217 pthread_mutex_lock(&session
->lock
);
1219 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1221 stream_publish(stream
);
1226 * Inform the viewer that there are new streams in the session.
1228 if (session
->viewer_attached
) {
1229 uatomic_set(&session
->new_streams
, 1);
1231 pthread_mutex_unlock(&session
->lock
);
1235 * relay_add_stream: allocate a new stream for a session
1237 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1238 struct relay_connection
*conn
,
1239 const struct lttng_buffer_view
*payload
)
1243 struct relay_session
*session
= conn
->session
;
1244 struct relay_stream
*stream
= NULL
;
1245 struct lttcomm_relayd_status_stream reply
;
1246 struct ctf_trace
*trace
= NULL
;
1247 uint64_t stream_handle
= -1ULL;
1248 char *path_name
= NULL
, *channel_name
= NULL
;
1249 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1250 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1252 if (!session
|| !conn
->version_check_done
) {
1253 ERR("Trying to add a stream before version check");
1255 goto end_no_session
;
1258 if (session
->minor
== 1) {
1260 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1262 } else if (session
->minor
> 1 && session
->minor
< 11) {
1263 /* From 2.2 to 2.10 */
1264 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1265 &channel_name
, &tracefile_size
, &tracefile_count
);
1267 /* From 2.11 to ... */
1268 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1269 &channel_name
, &tracefile_size
, &tracefile_count
,
1270 &stream_chunk_id
.value
);
1271 stream_chunk_id
.is_set
= true;
1278 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1282 /* This stream here has one reference on the trace. */
1284 pthread_mutex_lock(&last_relay_stream_id_lock
);
1285 stream_handle
= ++last_relay_stream_id
;
1286 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1288 /* We pass ownership of path_name and channel_name. */
1289 stream
= stream_create(trace
, stream_handle
, path_name
,
1290 channel_name
, tracefile_size
, tracefile_count
,
1293 channel_name
= NULL
;
1296 * Streams are the owners of their trace. Reference to trace is
1297 * kept within stream_create().
1299 ctf_trace_put(trace
);
1302 memset(&reply
, 0, sizeof(reply
));
1303 reply
.handle
= htobe64(stream_handle
);
1305 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1307 reply
.ret_code
= htobe32(LTTNG_OK
);
1310 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1311 sizeof(struct lttcomm_relayd_status_stream
), 0);
1312 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1313 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1325 * relay_close_stream: close a specific stream
1327 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1328 struct relay_connection
*conn
,
1329 const struct lttng_buffer_view
*payload
)
1333 struct relay_session
*session
= conn
->session
;
1334 struct lttcomm_relayd_close_stream stream_info
;
1335 struct lttcomm_relayd_generic_reply reply
;
1336 struct relay_stream
*stream
;
1338 DBG("Close stream received");
1340 if (!session
|| !conn
->version_check_done
) {
1341 ERR("Trying to close a stream before version check");
1343 goto end_no_session
;
1346 if (payload
->size
< sizeof(stream_info
)) {
1347 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1348 sizeof(stream_info
), payload
->size
);
1350 goto end_no_session
;
1352 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1353 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1354 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1356 stream
= stream_get_by_id(stream_info
.stream_id
);
1363 * Set last_net_seq_num before the close flag. Required by data
1366 pthread_mutex_lock(&stream
->lock
);
1367 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1368 pthread_mutex_unlock(&stream
->lock
);
1371 * This is one of the conditions which may trigger a stream close
1372 * with the others being:
1373 * 1) A close command is received for a stream
1374 * 2) The control connection owning the stream is closed
1375 * 3) We have received all of the stream's data _after_ a close
1378 try_stream_close(stream
);
1379 if (stream
->is_metadata
) {
1380 struct relay_viewer_stream
*vstream
;
1382 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1384 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1386 * Since all the metadata has been sent to the
1387 * viewer and that we have a request to close
1388 * its stream, we can safely teardown the
1389 * corresponding metadata viewer stream.
1391 viewer_stream_put(vstream
);
1393 /* Put local reference. */
1394 viewer_stream_put(vstream
);
1401 memset(&reply
, 0, sizeof(reply
));
1403 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1405 reply
.ret_code
= htobe32(LTTNG_OK
);
1407 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1408 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1409 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1410 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1420 * relay_reset_metadata: reset a metadata stream
1423 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1424 struct relay_connection
*conn
,
1425 const struct lttng_buffer_view
*payload
)
1429 struct relay_session
*session
= conn
->session
;
1430 struct lttcomm_relayd_reset_metadata stream_info
;
1431 struct lttcomm_relayd_generic_reply reply
;
1432 struct relay_stream
*stream
;
1434 DBG("Reset metadata received");
1436 if (!session
|| !conn
->version_check_done
) {
1437 ERR("Trying to reset a metadata stream before version check");
1439 goto end_no_session
;
1442 if (payload
->size
< sizeof(stream_info
)) {
1443 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1444 sizeof(stream_info
), payload
->size
);
1446 goto end_no_session
;
1448 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1449 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1450 stream_info
.version
= be64toh(stream_info
.version
);
1452 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1454 /* Unsupported for live sessions for now. */
1455 if (session
->live_timer
!= 0) {
1460 stream
= stream_get_by_id(stream_info
.stream_id
);
1465 pthread_mutex_lock(&stream
->lock
);
1466 if (!stream
->is_metadata
) {
1471 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1472 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1473 &stream
->stream_fd
->fd
);
1475 ERR("Failed to rotate metadata file %s of channel %s",
1476 stream
->path_name
, stream
->channel_name
);
1481 pthread_mutex_unlock(&stream
->lock
);
1485 memset(&reply
, 0, sizeof(reply
));
1487 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1489 reply
.ret_code
= htobe32(LTTNG_OK
);
1491 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1492 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1493 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1494 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1504 * relay_unknown_command: send -1 if received unknown command
1506 static void relay_unknown_command(struct relay_connection
*conn
)
1508 struct lttcomm_relayd_generic_reply reply
;
1511 memset(&reply
, 0, sizeof(reply
));
1512 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1513 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1514 if (send_ret
< sizeof(reply
)) {
1515 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1520 * relay_start: send an acknowledgment to the client to tell if we are
1521 * ready to receive data. We are ready if a session is established.
1523 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1524 struct relay_connection
*conn
,
1525 const struct lttng_buffer_view
*payload
)
1529 struct lttcomm_relayd_generic_reply reply
;
1530 struct relay_session
*session
= conn
->session
;
1533 DBG("Trying to start the streaming without a session established");
1534 ret
= htobe32(LTTNG_ERR_UNK
);
1537 memset(&reply
, 0, sizeof(reply
));
1538 reply
.ret_code
= htobe32(LTTNG_OK
);
1539 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1541 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1542 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1551 * Append padding to the file pointed by the file descriptor fd.
1553 static int write_padding_to_file(int fd
, uint32_t size
)
1562 zeros
= zmalloc(size
);
1563 if (zeros
== NULL
) {
1564 PERROR("zmalloc zeros for padding");
1569 ret
= lttng_write(fd
, zeros
, size
);
1571 PERROR("write padding to file");
1581 * Close the current index file if it is open, and create a new one.
1583 * Return 0 on success, -1 on error.
1586 int create_rotate_index_file(struct relay_stream
*stream
)
1589 uint32_t major
, minor
;
1591 /* Put ref on previous index_file. */
1592 if (stream
->index_file
) {
1593 lttng_index_file_put(stream
->index_file
);
1594 stream
->index_file
= NULL
;
1596 major
= stream
->trace
->session
->major
;
1597 minor
= stream
->trace
->session
->minor
;
1598 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
1599 stream
->channel_name
,
1600 -1, -1, stream
->tracefile_size
,
1601 tracefile_array_get_file_index_head(stream
->tfa
),
1602 lttng_to_index_major(major
, minor
),
1603 lttng_to_index_minor(major
, minor
));
1604 if (!stream
->index_file
) {
1616 int do_rotate_stream(struct relay_stream
*stream
)
1620 /* Perform the stream rotation. */
1621 ret
= utils_rotate_stream_file(stream
->path_name
,
1622 stream
->channel_name
, stream
->tracefile_size
,
1623 stream
->tracefile_count
, -1,
1624 -1, stream
->stream_fd
->fd
,
1625 NULL
, &stream
->stream_fd
->fd
);
1627 ERR("Rotating stream output file");
1630 stream
->tracefile_size_current
= 0;
1632 /* Rotate also the index if the stream is not a metadata stream. */
1633 if (!stream
->is_metadata
) {
1634 ret
= create_rotate_index_file(stream
);
1636 ERR("Failed to rotate index file");
1641 stream
->rotate_at_seq_num
= -1ULL;
1642 stream
->pos_after_last_complete_data_index
= 0;
1649 * If too much data has been written in a tracefile before we received the
1650 * rotation command, we have to move the excess data to the new tracefile and
1651 * perform the rotation. This can happen because the control and data
1652 * connections are separate, the indexes as well as the commands arrive from
1653 * the control connection and we have no control over the order so we could be
1654 * in a situation where too much data has been received on the data connection
1655 * before the rotation command on the control connection arrives. We don't need
1656 * to update the index because its order is guaranteed with the rotation
1660 int rotate_truncate_stream(struct relay_stream
*stream
)
1664 uint64_t diff
, pos
= 0;
1665 char buf
[FILE_COPY_BUFFER_SIZE
];
1667 assert(!stream
->is_metadata
);
1669 assert(stream
->tracefile_size_current
>
1670 stream
->pos_after_last_complete_data_index
);
1671 diff
= stream
->tracefile_size_current
-
1672 stream
->pos_after_last_complete_data_index
;
1674 /* Create the new tracefile. */
1675 new_fd
= utils_create_stream_file(stream
->path_name
,
1676 stream
->channel_name
,
1677 stream
->tracefile_size
, stream
->tracefile_count
,
1678 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1680 ERR("Failed to create new stream file at path %s for channel %s",
1681 stream
->path_name
, stream
->channel_name
);
1687 * Rewind the current tracefile to the position at which the rotation
1688 * should have occured.
1690 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1691 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1692 if (lseek_ret
< 0) {
1693 PERROR("seek truncate stream");
1698 /* Move data from the old file to the new file. */
1699 while (pos
< diff
) {
1700 uint64_t count
, bytes_left
;
1703 bytes_left
= diff
- pos
;
1704 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1705 assert(count
<= SIZE_MAX
);
1707 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1708 if (io_ret
< (ssize_t
) count
) {
1709 char error_string
[256];
1711 snprintf(error_string
, sizeof(error_string
),
1712 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1713 count
, stream
->stream_fd
->fd
, io_ret
);
1715 PERROR("%s", error_string
);
1717 ERR("%s", error_string
);
1723 io_ret
= lttng_write(new_fd
, buf
, count
);
1724 if (io_ret
< (ssize_t
) count
) {
1725 char error_string
[256];
1727 snprintf(error_string
, sizeof(error_string
),
1728 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1729 count
, new_fd
, io_ret
);
1731 PERROR("%s", error_string
);
1733 ERR("%s", error_string
);
1742 /* Truncate the file to get rid of the excess data. */
1743 ret
= ftruncate(stream
->stream_fd
->fd
,
1744 stream
->pos_after_last_complete_data_index
);
1746 PERROR("ftruncate");
1750 ret
= close(stream
->stream_fd
->fd
);
1752 PERROR("Closing tracefile");
1756 ret
= create_rotate_index_file(stream
);
1758 ERR("Rotate stream index file");
1763 * Update the offset and FD of all the eventual indexes created by the
1764 * data connection before the rotation command arrived.
1766 ret
= relay_index_switch_all_files(stream
);
1768 ERR("Failed to rotate index file");
1772 stream
->stream_fd
->fd
= new_fd
;
1773 stream
->tracefile_size_current
= diff
;
1774 stream
->pos_after_last_complete_data_index
= 0;
1775 stream
->rotate_at_seq_num
= -1ULL;
1784 * Check if a stream should perform a rotation (for session rotation).
1785 * Must be called with the stream lock held.
1787 * Return 0 on success, a negative value on error.
1790 int try_rotate_stream(struct relay_stream
*stream
)
1794 /* No rotation expected. */
1795 if (stream
->rotate_at_seq_num
== -1ULL) {
1799 if (stream
->prev_seq
< stream
->rotate_at_seq_num
||
1800 stream
->prev_seq
== -1ULL) {
1801 DBG("Stream %" PRIu64
" no yet ready for rotation",
1802 stream
->stream_handle
);
1804 } else if (stream
->prev_seq
> stream
->rotate_at_seq_num
) {
1805 DBG("Rotation after too much data has been written in tracefile "
1806 "for stream %" PRIu64
", need to truncate before "
1807 "rotating", stream
->stream_handle
);
1808 ret
= rotate_truncate_stream(stream
);
1810 ERR("Failed to truncate stream");
1814 /* stream->prev_seq == stream->rotate_at_seq_num */
1815 DBG("Stream %" PRIu64
" ready for rotation",
1816 stream
->stream_handle
);
1817 ret
= do_rotate_stream(stream
);
1825 * relay_recv_metadata: receive the metadata for the session.
1827 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1828 struct relay_connection
*conn
,
1829 const struct lttng_buffer_view
*payload
)
1833 struct relay_session
*session
= conn
->session
;
1834 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1835 struct relay_stream
*metadata_stream
;
1836 uint64_t metadata_payload_size
;
1839 ERR("Metadata sent before version check");
1844 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1845 ERR("Incorrect data size");
1849 metadata_payload_size
= recv_hdr
->data_size
-
1850 sizeof(struct lttcomm_relayd_metadata_payload
);
1852 memcpy(&metadata_payload_header
, payload
->data
,
1853 sizeof(metadata_payload_header
));
1854 metadata_payload_header
.stream_id
= be64toh(
1855 metadata_payload_header
.stream_id
);
1856 metadata_payload_header
.padding_size
= be32toh(
1857 metadata_payload_header
.padding_size
);
1859 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1860 if (!metadata_stream
) {
1865 pthread_mutex_lock(&metadata_stream
->lock
);
1867 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1868 payload
->data
+ sizeof(metadata_payload_header
),
1869 metadata_payload_size
);
1870 if (size_ret
< metadata_payload_size
) {
1871 ERR("Relay error writing metadata on file");
1876 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1877 metadata_payload_header
.padding_size
);
1878 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1883 metadata_stream
->metadata_received
+=
1884 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1885 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1886 metadata_stream
->metadata_received
);
1888 ret
= try_rotate_stream(metadata_stream
);
1894 pthread_mutex_unlock(&metadata_stream
->lock
);
1895 stream_put(metadata_stream
);
1901 * relay_send_version: send relayd version number
1903 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1904 struct relay_connection
*conn
,
1905 const struct lttng_buffer_view
*payload
)
1909 struct lttcomm_relayd_version reply
, msg
;
1910 bool compatible
= true;
1912 conn
->version_check_done
= true;
1914 /* Get version from the other side. */
1915 if (payload
->size
< sizeof(msg
)) {
1916 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1917 sizeof(msg
), payload
->size
);
1922 memcpy(&msg
, payload
->data
, sizeof(msg
));
1923 msg
.major
= be32toh(msg
.major
);
1924 msg
.minor
= be32toh(msg
.minor
);
1926 memset(&reply
, 0, sizeof(reply
));
1927 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1928 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1930 /* Major versions must be the same */
1931 if (reply
.major
!= msg
.major
) {
1932 DBG("Incompatible major versions (%u vs %u), deleting session",
1933 reply
.major
, msg
.major
);
1937 conn
->major
= reply
.major
;
1938 /* We adapt to the lowest compatible version */
1939 if (reply
.minor
<= msg
.minor
) {
1940 conn
->minor
= reply
.minor
;
1942 conn
->minor
= msg
.minor
;
1945 reply
.major
= htobe32(reply
.major
);
1946 reply
.minor
= htobe32(reply
.minor
);
1947 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1949 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1950 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1963 DBG("Version check done using protocol %u.%u", conn
->major
,
1971 * Check for data pending for a given stream id from the session daemon.
1973 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1974 struct relay_connection
*conn
,
1975 const struct lttng_buffer_view
*payload
)
1977 struct relay_session
*session
= conn
->session
;
1978 struct lttcomm_relayd_data_pending msg
;
1979 struct lttcomm_relayd_generic_reply reply
;
1980 struct relay_stream
*stream
;
1984 DBG("Data pending command received");
1986 if (!session
|| !conn
->version_check_done
) {
1987 ERR("Trying to check for data before version check");
1989 goto end_no_session
;
1992 if (payload
->size
< sizeof(msg
)) {
1993 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1994 sizeof(msg
), payload
->size
);
1996 goto end_no_session
;
1998 memcpy(&msg
, payload
->data
, sizeof(msg
));
1999 msg
.stream_id
= be64toh(msg
.stream_id
);
2000 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2002 stream
= stream_get_by_id(msg
.stream_id
);
2003 if (stream
== NULL
) {
2008 pthread_mutex_lock(&stream
->lock
);
2010 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
2011 " and last_seq %" PRIu64
, msg
.stream_id
,
2012 stream
->prev_seq
, msg
.last_net_seq_num
);
2014 /* Avoid wrapping issue */
2015 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
2016 /* Data has in fact been written and is NOT pending */
2019 /* Data still being streamed thus pending */
2023 stream
->data_pending_check_done
= true;
2024 pthread_mutex_unlock(&stream
->lock
);
2029 memset(&reply
, 0, sizeof(reply
));
2030 reply
.ret_code
= htobe32(ret
);
2031 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2032 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2033 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2043 * Wait for the control socket to reach a quiescent state.
2045 * Note that for now, when receiving this command from the session
2046 * daemon, this means that every subsequent commands or data received on
2047 * the control socket has been handled. So, this is why we simply return
2050 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2051 struct relay_connection
*conn
,
2052 const struct lttng_buffer_view
*payload
)
2056 struct relay_stream
*stream
;
2057 struct lttcomm_relayd_quiescent_control msg
;
2058 struct lttcomm_relayd_generic_reply reply
;
2060 DBG("Checking quiescent state on control socket");
2062 if (!conn
->session
|| !conn
->version_check_done
) {
2063 ERR("Trying to check for data before version check");
2065 goto end_no_session
;
2068 if (payload
->size
< sizeof(msg
)) {
2069 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2070 sizeof(msg
), payload
->size
);
2072 goto end_no_session
;
2074 memcpy(&msg
, payload
->data
, sizeof(msg
));
2075 msg
.stream_id
= be64toh(msg
.stream_id
);
2077 stream
= stream_get_by_id(msg
.stream_id
);
2081 pthread_mutex_lock(&stream
->lock
);
2082 stream
->data_pending_check_done
= true;
2083 pthread_mutex_unlock(&stream
->lock
);
2085 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2088 memset(&reply
, 0, sizeof(reply
));
2089 reply
.ret_code
= htobe32(LTTNG_OK
);
2090 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2091 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2092 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2104 * Initialize a data pending command. This means that a consumer is about
2105 * to ask for data pending for each stream it holds. Simply iterate over
2106 * all streams of a session and set the data_pending_check_done flag.
2108 * This command returns to the client a LTTNG_OK code.
2110 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2111 struct relay_connection
*conn
,
2112 const struct lttng_buffer_view
*payload
)
2116 struct lttng_ht_iter iter
;
2117 struct lttcomm_relayd_begin_data_pending msg
;
2118 struct lttcomm_relayd_generic_reply reply
;
2119 struct relay_stream
*stream
;
2124 DBG("Init streams for data pending");
2126 if (!conn
->session
|| !conn
->version_check_done
) {
2127 ERR("Trying to check for data before version check");
2129 goto end_no_session
;
2132 if (payload
->size
< sizeof(msg
)) {
2133 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2134 sizeof(msg
), payload
->size
);
2136 goto end_no_session
;
2138 memcpy(&msg
, payload
->data
, sizeof(msg
));
2139 msg
.session_id
= be64toh(msg
.session_id
);
2142 * Iterate over all streams to set the begin data pending flag.
2143 * For now, the streams are indexed by stream handle so we have
2144 * to iterate over all streams to find the one associated with
2145 * the right session_id.
2148 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2150 if (!stream_get(stream
)) {
2153 if (stream
->trace
->session
->id
== msg
.session_id
) {
2154 pthread_mutex_lock(&stream
->lock
);
2155 stream
->data_pending_check_done
= false;
2156 pthread_mutex_unlock(&stream
->lock
);
2157 DBG("Set begin data pending flag to stream %" PRIu64
,
2158 stream
->stream_handle
);
2164 memset(&reply
, 0, sizeof(reply
));
2165 /* All good, send back reply. */
2166 reply
.ret_code
= htobe32(LTTNG_OK
);
2168 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2169 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2170 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2182 * End data pending command. This will check, for a given session id, if
2183 * each stream associated with it has its data_pending_check_done flag
2184 * set. If not, this means that the client lost track of the stream but
2185 * the data is still being streamed on our side. In this case, we inform
2186 * the client that data is in flight.
2188 * Return to the client if there is data in flight or not with a ret_code.
2190 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2191 struct relay_connection
*conn
,
2192 const struct lttng_buffer_view
*payload
)
2196 struct lttng_ht_iter iter
;
2197 struct lttcomm_relayd_end_data_pending msg
;
2198 struct lttcomm_relayd_generic_reply reply
;
2199 struct relay_stream
*stream
;
2200 uint32_t is_data_inflight
= 0;
2202 DBG("End data pending command");
2204 if (!conn
->session
|| !conn
->version_check_done
) {
2205 ERR("Trying to check for data before version check");
2207 goto end_no_session
;
2210 if (payload
->size
< sizeof(msg
)) {
2211 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2212 sizeof(msg
), payload
->size
);
2214 goto end_no_session
;
2216 memcpy(&msg
, payload
->data
, sizeof(msg
));
2217 msg
.session_id
= be64toh(msg
.session_id
);
2220 * Iterate over all streams to see if the begin data pending
2224 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2226 if (!stream_get(stream
)) {
2229 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2233 pthread_mutex_lock(&stream
->lock
);
2234 if (!stream
->data_pending_check_done
) {
2235 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2236 is_data_inflight
= 1;
2237 DBG("Data is still in flight for stream %" PRIu64
,
2238 stream
->stream_handle
);
2239 pthread_mutex_unlock(&stream
->lock
);
2244 pthread_mutex_unlock(&stream
->lock
);
2249 memset(&reply
, 0, sizeof(reply
));
2250 /* All good, send back reply. */
2251 reply
.ret_code
= htobe32(is_data_inflight
);
2253 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2254 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2255 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2267 * Receive an index for a specific stream.
2269 * Return 0 on success else a negative value.
2271 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2272 struct relay_connection
*conn
,
2273 const struct lttng_buffer_view
*payload
)
2277 struct relay_session
*session
= conn
->session
;
2278 struct lttcomm_relayd_index index_info
;
2279 struct relay_index
*index
;
2280 struct lttcomm_relayd_generic_reply reply
;
2281 struct relay_stream
*stream
;
2286 DBG("Relay receiving index");
2288 if (!session
|| !conn
->version_check_done
) {
2289 ERR("Trying to close a stream before version check");
2291 goto end_no_session
;
2294 msg_len
= lttcomm_relayd_index_len(
2295 lttng_to_index_major(conn
->major
, conn
->minor
),
2296 lttng_to_index_minor(conn
->major
, conn
->minor
));
2297 if (payload
->size
< msg_len
) {
2298 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2299 msg_len
, payload
->size
);
2301 goto end_no_session
;
2303 memcpy(&index_info
, payload
->data
, msg_len
);
2304 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2305 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2306 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2307 index_info
.content_size
= be64toh(index_info
.content_size
);
2308 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2309 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2310 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2311 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2313 if (conn
->minor
>= 8) {
2314 index_info
.stream_instance_id
=
2315 be64toh(index_info
.stream_instance_id
);
2316 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2319 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2321 ERR("stream_get_by_id not found");
2325 pthread_mutex_lock(&stream
->lock
);
2327 /* Live beacon handling */
2328 if (index_info
.packet_size
== 0) {
2329 DBG("Received live beacon for stream %" PRIu64
,
2330 stream
->stream_handle
);
2333 * Only flag a stream inactive when it has already
2334 * received data and no indexes are in flight.
2336 if (stream
->index_received_seqcount
> 0
2337 && stream
->indexes_in_flight
== 0) {
2338 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2341 goto end_stream_put
;
2343 stream
->beacon_ts_end
= -1ULL;
2346 if (stream
->ctf_stream_id
== -1ULL) {
2347 stream
->ctf_stream_id
= index_info
.stream_id
;
2349 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2352 ERR("relay_index_get_by_id_or_create index NULL");
2353 goto end_stream_put
;
2355 if (set_index_control_data(index
, &index_info
, conn
)) {
2356 ERR("set_index_control_data error");
2357 relay_index_put(index
);
2359 goto end_stream_put
;
2361 ret
= relay_index_try_flush(index
);
2363 tracefile_array_commit_seq(stream
->tfa
);
2364 stream
->index_received_seqcount
++;
2365 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2366 } else if (ret
> 0) {
2370 ERR("relay_index_try_flush error %d", ret
);
2371 relay_index_put(index
);
2376 pthread_mutex_unlock(&stream
->lock
);
2381 memset(&reply
, 0, sizeof(reply
));
2383 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2385 reply
.ret_code
= htobe32(LTTNG_OK
);
2387 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2388 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2389 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2398 * Receive the streams_sent message.
2400 * Return 0 on success else a negative value.
2402 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2403 struct relay_connection
*conn
,
2404 const struct lttng_buffer_view
*payload
)
2408 struct lttcomm_relayd_generic_reply reply
;
2412 DBG("Relay receiving streams_sent");
2414 if (!conn
->session
|| !conn
->version_check_done
) {
2415 ERR("Trying to close a stream before version check");
2417 goto end_no_session
;
2421 * Publish every pending stream in the connection recv list which are
2422 * now ready to be used by the viewer.
2424 publish_connection_local_streams(conn
);
2426 memset(&reply
, 0, sizeof(reply
));
2427 reply
.ret_code
= htobe32(LTTNG_OK
);
2428 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2429 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2430 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2443 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2444 * rotation feature (not the tracefile rotation feature).
2446 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2447 struct relay_connection
*conn
,
2448 const struct lttng_buffer_view
*payload
)
2452 struct relay_session
*session
= conn
->session
;
2453 struct lttcomm_relayd_rotate_stream stream_info
;
2454 struct lttcomm_relayd_generic_reply reply
;
2455 struct relay_stream
*stream
;
2458 struct lttng_buffer_view new_path_view
;
2460 DBG("Rotate stream received");
2462 if (!session
|| !conn
->version_check_done
) {
2463 ERR("Trying to rotate a stream before version check");
2468 if (session
->major
== 2 && session
->minor
< 11) {
2469 ERR("Unsupported feature before 2.11");
2474 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2476 if (payload
->size
< header_len
) {
2477 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2478 header_len
, payload
->size
);
2483 memcpy(&stream_info
, payload
->data
, header_len
);
2485 /* Convert to host */
2486 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2487 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2488 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2489 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2491 path_len
= stream_info
.pathname_length
;
2492 if (payload
->size
< header_len
+ path_len
) {
2493 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2494 header_len
+ path_len
, payload
->size
);
2499 /* Ensure it fits in local filename length. */
2500 if (path_len
>= LTTNG_PATH_MAX
) {
2501 ret
= -ENAMETOOLONG
;
2502 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2503 path_len
, LTTNG_PATH_MAX
);
2507 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2508 stream_info
.pathname_length
);
2510 stream
= stream_get_by_id(stream_info
.stream_id
);
2516 pthread_mutex_lock(&stream
->lock
);
2519 * Update the trace path (just the folder, the stream name does not
2522 free(stream
->path_name
);
2523 stream
->path_name
= create_output_path(new_path_view
.data
);
2524 if (!stream
->path_name
) {
2525 ERR("Failed to create a new output path");
2527 goto end_stream_unlock
;
2529 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2532 ERR("relay creating output directory");
2534 goto end_stream_unlock
;
2537 assert(stream
->current_chunk_id
.is_set
);
2538 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2540 if (stream
->is_metadata
) {
2542 * The metadata stream is sent only over the control connection
2543 * so we know we have all the data to perform the stream
2546 ret
= do_rotate_stream(stream
);
2548 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2549 ret
= try_rotate_stream(stream
);
2552 goto end_stream_unlock
;
2556 pthread_mutex_unlock(&stream
->lock
);
2559 memset(&reply
, 0, sizeof(reply
));
2561 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2563 reply
.ret_code
= htobe32(LTTNG_OK
);
2565 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2566 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2567 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2568 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2578 * relay_mkdir: Create a folder on the disk.
2580 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2581 struct relay_connection
*conn
,
2582 const struct lttng_buffer_view
*payload
)
2585 struct relay_session
*session
= conn
->session
;
2586 struct lttcomm_relayd_mkdir path_info_header
;
2587 struct lttcomm_relayd_generic_reply reply
;
2591 struct lttng_buffer_view path_view
;
2593 if (!session
|| !conn
->version_check_done
) {
2594 ERR("Trying to create a directory before version check");
2596 goto end_no_session
;
2599 if (session
->major
== 2 && session
->minor
< 11) {
2601 * This client is not supposed to use this command since
2602 * it predates its introduction.
2604 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2606 goto end_no_session
;
2609 header_len
= sizeof(path_info_header
);
2610 if (payload
->size
< header_len
) {
2611 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2612 header_len
, payload
->size
);
2614 goto end_no_session
;
2617 memcpy(&path_info_header
, payload
->data
, header_len
);
2619 path_info_header
.length
= be32toh(path_info_header
.length
);
2621 if (payload
->size
< header_len
+ path_info_header
.length
) {
2622 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2623 header_len
+ path_info_header
.length
, payload
->size
);
2625 goto end_no_session
;
2628 /* Ensure that it fits in local path length. */
2629 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2630 ret
= -ENAMETOOLONG
;
2631 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2632 path_info_header
.length
, LTTNG_PATH_MAX
);
2636 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2637 path_info_header
.length
);
2639 path
= create_output_path(path_view
.data
);
2641 ERR("Failed to create output path");
2646 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2648 ERR("relay creating output directory");
2655 memset(&reply
, 0, sizeof(reply
));
2657 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2659 reply
.ret_code
= htobe32(LTTNG_OK
);
2661 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2662 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2663 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2672 static int validate_rotate_rename_path_length(const char *path_type
,
2673 uint32_t path_length
)
2677 if (path_length
> LTTNG_PATH_MAX
) {
2678 ret
= -ENAMETOOLONG
;
2679 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2680 path_type
, path_length
, LTTNG_PATH_MAX
);
2681 } else if (path_length
== 0) {
2683 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2689 * relay_rotate_rename: rename the trace folder after a rotation is
2690 * completed. We are not closing any fd here, just moving the folder, so it
2691 * works even if data is still in-flight.
2693 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2694 struct relay_connection
*conn
,
2695 const struct lttng_buffer_view
*payload
)
2699 struct relay_session
*session
= conn
->session
;
2700 struct lttcomm_relayd_generic_reply reply
;
2701 struct lttcomm_relayd_rotate_rename header
;
2703 size_t received_paths_size
;
2704 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2705 struct lttng_buffer_view old_path_view
;
2706 struct lttng_buffer_view new_path_view
;
2708 if (!session
|| !conn
->version_check_done
) {
2709 ERR("Trying to rename a trace folder before version check");
2714 if (session
->major
== 2 && session
->minor
< 11) {
2715 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2720 header_len
= sizeof(header
);
2721 if (payload
->size
< header_len
) {
2722 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2723 header_len
, payload
->size
);
2728 memcpy(&header
, payload
->data
, header_len
);
2730 header
.old_path_length
= be32toh(header
.old_path_length
);
2731 header
.new_path_length
= be32toh(header
.new_path_length
);
2732 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2734 if (payload
->size
< header_len
+ received_paths_size
) {
2735 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2736 header_len
, payload
->size
);
2741 /* Ensure the paths don't exceed their allowed size. */
2742 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2746 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2751 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2752 header
.old_path_length
);
2753 new_path_view
= lttng_buffer_view_from_view(payload
,
2754 header_len
+ header
.old_path_length
,
2755 header
.new_path_length
);
2757 /* Validate that both paths received are NULL terminated. */
2758 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2759 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2763 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2764 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2769 complete_old_path
= create_output_path(old_path_view
.data
);
2770 if (!complete_old_path
) {
2771 ERR("Failed to build old output path in rotate_rename command");
2776 complete_new_path
= create_output_path(new_path_view
.data
);
2777 if (!complete_new_path
) {
2778 ERR("Failed to build new output path in rotate_rename command");
2783 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2786 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2792 * If a domain has not yet created its channel, the domain-specific
2793 * folder might not exist, but this is not an error.
2795 ret
= rename(complete_old_path
, complete_new_path
);
2796 if (ret
< 0 && errno
!= ENOENT
) {
2797 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2798 complete_old_path
, complete_new_path
);
2804 memset(&reply
, 0, sizeof(reply
));
2806 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2808 reply
.ret_code
= htobe32(LTTNG_OK
);
2810 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2812 if (send_ret
< sizeof(reply
)) {
2813 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2819 free(complete_old_path
);
2820 free(complete_new_path
);
2825 * Check if all the streams in the session have completed the last rotation.
2826 * The chunk_id value is used to distinguish the cases where a stream was
2827 * closed on the consumerd before the rotation started but it still active on
2828 * the relayd, and the case where a stream appeared on the consumerd/relayd
2829 * after the last rotation started (in that case, it is already writing in the
2830 * new chunk folder).
2833 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2834 struct relay_connection
*conn
,
2835 const struct lttng_buffer_view
*payload
)
2837 struct relay_session
*session
= conn
->session
;
2838 struct lttcomm_relayd_rotate_pending msg
;
2839 struct lttcomm_relayd_rotate_pending_reply reply
;
2840 struct lttng_ht_iter iter
;
2841 struct relay_stream
*stream
;
2845 bool rotate_pending
= false;
2847 DBG("Rotate pending command received");
2849 if (!session
|| !conn
->version_check_done
) {
2850 ERR("Trying to check for data before version check");
2855 if (session
->major
== 2 && session
->minor
< 11) {
2856 ERR("Unsupported feature before 2.11");
2861 if (payload
->size
< sizeof(msg
)) {
2862 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2863 sizeof(msg
), payload
->size
);
2868 memcpy(&msg
, payload
->data
, sizeof(msg
));
2870 chunk_id
= be64toh(msg
.chunk_id
);
2872 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2873 session
->session_name
, chunk_id
);
2876 * Iterate over all the streams in the session and check if they are
2877 * still waiting for data to perform their rotation.
2880 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2882 if (!stream_get(stream
)) {
2885 if (stream
->trace
->session
!= session
) {
2889 pthread_mutex_lock(&stream
->lock
);
2890 if (stream
->rotate_at_seq_num
!= -1ULL) {
2891 /* We have not yet performed the rotation. */
2892 rotate_pending
= true;
2893 DBG("Stream %" PRIu64
" is still rotating",
2894 stream
->stream_handle
);
2895 } else if (stream
->current_chunk_id
.value
< chunk_id
) {
2897 * Stream closed on the consumer but still active on the
2900 rotate_pending
= true;
2901 DBG("Stream %" PRIu64
" did not exist on the consumer "
2902 "when the last rotation started, but is"
2903 "still waiting for data before getting"
2905 stream
->stream_handle
);
2907 pthread_mutex_unlock(&stream
->lock
);
2909 if (rotate_pending
) {
2916 memset(&reply
, 0, sizeof(reply
));
2917 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
2918 reply
.is_pending
= (uint8_t) !!rotate_pending
;
2919 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2921 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2922 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
2931 #define DBG_CMD(cmd_name, conn) \
2932 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2934 static int relay_process_control_command(struct relay_connection
*conn
,
2935 const struct lttcomm_relayd_hdr
*header
,
2936 const struct lttng_buffer_view
*payload
)
2940 switch (header
->cmd
) {
2941 case RELAYD_CREATE_SESSION
:
2942 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2943 ret
= relay_create_session(header
, conn
, payload
);
2945 case RELAYD_ADD_STREAM
:
2946 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2947 ret
= relay_add_stream(header
, conn
, payload
);
2949 case RELAYD_START_DATA
:
2950 DBG_CMD("RELAYD_START_DATA", conn
);
2951 ret
= relay_start(header
, conn
, payload
);
2953 case RELAYD_SEND_METADATA
:
2954 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2955 ret
= relay_recv_metadata(header
, conn
, payload
);
2957 case RELAYD_VERSION
:
2958 DBG_CMD("RELAYD_VERSION", conn
);
2959 ret
= relay_send_version(header
, conn
, payload
);
2961 case RELAYD_CLOSE_STREAM
:
2962 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2963 ret
= relay_close_stream(header
, conn
, payload
);
2965 case RELAYD_DATA_PENDING
:
2966 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2967 ret
= relay_data_pending(header
, conn
, payload
);
2969 case RELAYD_QUIESCENT_CONTROL
:
2970 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2971 ret
= relay_quiescent_control(header
, conn
, payload
);
2973 case RELAYD_BEGIN_DATA_PENDING
:
2974 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2975 ret
= relay_begin_data_pending(header
, conn
, payload
);
2977 case RELAYD_END_DATA_PENDING
:
2978 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2979 ret
= relay_end_data_pending(header
, conn
, payload
);
2981 case RELAYD_SEND_INDEX
:
2982 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2983 ret
= relay_recv_index(header
, conn
, payload
);
2985 case RELAYD_STREAMS_SENT
:
2986 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2987 ret
= relay_streams_sent(header
, conn
, payload
);
2989 case RELAYD_RESET_METADATA
:
2990 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2991 ret
= relay_reset_metadata(header
, conn
, payload
);
2993 case RELAYD_ROTATE_STREAM
:
2994 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
2995 ret
= relay_rotate_session_stream(header
, conn
, payload
);
2997 case RELAYD_ROTATE_RENAME
:
2998 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
2999 ret
= relay_rotate_rename(header
, conn
, payload
);
3001 case RELAYD_ROTATE_PENDING
:
3002 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3003 ret
= relay_rotate_pending(header
, conn
, payload
);
3006 DBG_CMD("RELAYD_MKDIR", conn
);
3007 ret
= relay_mkdir(header
, conn
, payload
);
3009 case RELAYD_UPDATE_SYNC_INFO
:
3011 ERR("Received unknown command (%u)", header
->cmd
);
3012 relay_unknown_command(conn
);
3021 static enum relay_connection_status
relay_process_control_receive_payload(
3022 struct relay_connection
*conn
)
3025 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3026 struct lttng_dynamic_buffer
*reception_buffer
=
3027 &conn
->protocol
.ctrl
.reception_buffer
;
3028 struct ctrl_connection_state_receive_payload
*state
=
3029 &conn
->protocol
.ctrl
.state
.receive_payload
;
3030 struct lttng_buffer_view payload_view
;
3032 if (state
->left_to_receive
== 0) {
3033 /* Short-circuit for payload-less commands. */
3034 goto reception_complete
;
3037 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3038 reception_buffer
->data
+ state
->received
,
3039 state
->left_to_receive
, MSG_DONTWAIT
);
3041 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3042 PERROR("Unable to receive command payload on sock %d",
3044 status
= RELAY_CONNECTION_STATUS_ERROR
;
3047 } else if (ret
== 0) {
3048 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3049 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3054 assert(ret
<= state
->left_to_receive
);
3056 state
->left_to_receive
-= ret
;
3057 state
->received
+= ret
;
3059 if (state
->left_to_receive
> 0) {
3061 * Can't transition to the protocol's next state, wait to
3062 * receive the rest of the header.
3064 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3065 state
->received
, state
->left_to_receive
,
3071 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3072 conn
->sock
->fd
, state
->received
);
3074 * The payload required to process the command has been received.
3075 * A view to the reception buffer is forwarded to the various
3076 * commands and the state of the control is reset on success.
3078 * Commands are responsible for sending their reply to the peer.
3080 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3082 ret
= relay_process_control_command(conn
,
3083 &state
->header
, &payload_view
);
3085 status
= RELAY_CONNECTION_STATUS_ERROR
;
3089 ret
= connection_reset_protocol_state(conn
);
3091 status
= RELAY_CONNECTION_STATUS_ERROR
;
3097 static enum relay_connection_status
relay_process_control_receive_header(
3098 struct relay_connection
*conn
)
3101 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3102 struct lttcomm_relayd_hdr header
;
3103 struct lttng_dynamic_buffer
*reception_buffer
=
3104 &conn
->protocol
.ctrl
.reception_buffer
;
3105 struct ctrl_connection_state_receive_header
*state
=
3106 &conn
->protocol
.ctrl
.state
.receive_header
;
3108 assert(state
->left_to_receive
!= 0);
3110 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3111 reception_buffer
->data
+ state
->received
,
3112 state
->left_to_receive
, MSG_DONTWAIT
);
3114 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3115 PERROR("Unable to receive control command header on sock %d",
3117 status
= RELAY_CONNECTION_STATUS_ERROR
;
3120 } else if (ret
== 0) {
3121 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3122 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3127 assert(ret
<= state
->left_to_receive
);
3129 state
->left_to_receive
-= ret
;
3130 state
->received
+= ret
;
3132 if (state
->left_to_receive
> 0) {
3134 * Can't transition to the protocol's next state, wait to
3135 * receive the rest of the header.
3137 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3138 state
->received
, state
->left_to_receive
,
3143 /* Transition to next state: receiving the command's payload. */
3144 conn
->protocol
.ctrl
.state_id
=
3145 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3146 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3147 header
.circuit_id
= be64toh(header
.circuit_id
);
3148 header
.data_size
= be64toh(header
.data_size
);
3149 header
.cmd
= be32toh(header
.cmd
);
3150 header
.cmd_version
= be32toh(header
.cmd_version
);
3151 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3152 &header
, sizeof(header
));
3154 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3155 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3158 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3159 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3161 status
= RELAY_CONNECTION_STATUS_ERROR
;
3165 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3167 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3168 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3171 status
= RELAY_CONNECTION_STATUS_ERROR
;
3175 if (header
.data_size
== 0) {
3177 * Manually invoke the next state as the poll loop
3178 * will not wake-up to allow us to proceed further.
3180 status
= relay_process_control_receive_payload(conn
);
3187 * Process the commands received on the control socket
3189 static enum relay_connection_status
relay_process_control(
3190 struct relay_connection
*conn
)
3192 enum relay_connection_status status
;
3194 switch (conn
->protocol
.ctrl
.state_id
) {
3195 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3196 status
= relay_process_control_receive_header(conn
);
3198 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3199 status
= relay_process_control_receive_payload(conn
);
3202 ERR("Unknown control connection protocol state encountered.");
3210 * Handle index for a data stream.
3212 * Called with the stream lock held.
3214 * Return 0 on success else a negative value.
3216 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3217 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3220 uint64_t data_offset
;
3221 struct relay_index
*index
;
3223 /* Get data offset because we are about to update the index. */
3224 data_offset
= htobe64(stream
->tracefile_size_current
);
3226 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3227 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3230 * Lookup for an existing index for that stream id/sequence
3231 * number. If it exists, the control thread has already received the
3232 * data for it, thus we need to write it to disk.
3234 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3240 if (rotate_index
|| !stream
->index_file
) {
3241 ret
= create_rotate_index_file(stream
);
3243 ERR("Failed to rotate index");
3244 /* Put self-ref for this index due to error. */
3245 relay_index_put(index
);
3251 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3253 /* Put self-ref for this index due to error. */
3254 relay_index_put(index
);
3259 ret
= relay_index_try_flush(index
);
3261 tracefile_array_commit_seq(stream
->tfa
);
3262 stream
->index_received_seqcount
++;
3264 } else if (ret
> 0) {
3265 index
->total_size
= total_size
;
3269 /* Put self-ref for this index due to error. */
3270 relay_index_put(index
);
3278 static enum relay_connection_status
relay_process_data_receive_header(
3279 struct relay_connection
*conn
)
3282 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3283 struct data_connection_state_receive_header
*state
=
3284 &conn
->protocol
.data
.state
.receive_header
;
3285 struct lttcomm_relayd_data_hdr header
;
3286 struct relay_stream
*stream
;
3288 assert(state
->left_to_receive
!= 0);
3290 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3291 state
->header_reception_buffer
+ state
->received
,
3292 state
->left_to_receive
, MSG_DONTWAIT
);
3294 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3295 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3296 status
= RELAY_CONNECTION_STATUS_ERROR
;
3299 } else if (ret
== 0) {
3300 /* Orderly shutdown. Not necessary to print an error. */
3301 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3302 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3307 assert(ret
<= state
->left_to_receive
);
3309 state
->left_to_receive
-= ret
;
3310 state
->received
+= ret
;
3312 if (state
->left_to_receive
> 0) {
3314 * Can't transition to the protocol's next state, wait to
3315 * receive the rest of the header.
3317 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3318 state
->received
, state
->left_to_receive
,
3323 /* Transition to next state: receiving the payload. */
3324 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3326 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3327 header
.circuit_id
= be64toh(header
.circuit_id
);
3328 header
.stream_id
= be64toh(header
.stream_id
);
3329 header
.data_size
= be32toh(header
.data_size
);
3330 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3331 header
.padding_size
= be32toh(header
.padding_size
);
3332 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3334 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3336 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3337 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3339 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3340 conn
->sock
->fd
, header
.circuit_id
,
3341 header
.stream_id
, header
.data_size
,
3342 header
.net_seq_num
, header
.padding_size
);
3344 stream
= stream_get_by_id(header
.stream_id
);
3346 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3348 /* Protocol error. */
3349 status
= RELAY_CONNECTION_STATUS_ERROR
;
3353 pthread_mutex_lock(&stream
->lock
);
3355 /* Check if a rotation is needed. */
3356 if (stream
->tracefile_size
> 0 &&
3357 (stream
->tracefile_size_current
+ header
.data_size
) >
3358 stream
->tracefile_size
) {
3359 uint64_t old_id
, new_id
;
3361 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3362 tracefile_array_file_rotate(stream
->tfa
);
3364 /* new_id is updated by utils_rotate_stream_file. */
3367 ret
= utils_rotate_stream_file(stream
->path_name
,
3368 stream
->channel_name
, stream
->tracefile_size
,
3369 stream
->tracefile_count
, -1,
3370 -1, stream
->stream_fd
->fd
,
3371 &new_id
, &stream
->stream_fd
->fd
);
3373 ERR("Failed to rotate stream output file");
3374 status
= RELAY_CONNECTION_STATUS_ERROR
;
3375 goto end_stream_unlock
;
3379 * Reset current size because we just performed a stream
3382 stream
->tracefile_size_current
= 0;
3383 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3387 pthread_mutex_unlock(&stream
->lock
);
3393 static enum relay_connection_status
relay_process_data_receive_payload(
3394 struct relay_connection
*conn
)
3397 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3398 struct relay_stream
*stream
;
3399 struct data_connection_state_receive_payload
*state
=
3400 &conn
->protocol
.data
.state
.receive_payload
;
3401 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3402 char data_buffer
[chunk_size
];
3403 bool partial_recv
= false;
3404 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3405 uint64_t left_to_receive
= state
->left_to_receive
;
3406 struct relay_session
*session
;
3408 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3409 state
->header
.stream_id
, state
->header
.net_seq_num
,
3410 state
->received
, left_to_receive
);
3412 stream
= stream_get_by_id(state
->header
.stream_id
);
3414 /* Protocol error. */
3415 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3416 state
->header
.stream_id
);
3417 status
= RELAY_CONNECTION_STATUS_ERROR
;
3421 pthread_mutex_lock(&stream
->lock
);
3422 session
= stream
->trace
->session
;
3423 if (!conn
->session
) {
3424 ret
= connection_set_session(conn
, session
);
3426 status
= RELAY_CONNECTION_STATUS_ERROR
;
3427 goto end_stream_unlock
;
3432 * The size of the "chunk" received on any iteration is bounded by:
3433 * - the data left to receive,
3434 * - the data immediately available on the socket,
3435 * - the on-stack data buffer
3437 while (left_to_receive
> 0 && !partial_recv
) {
3439 size_t recv_size
= min(left_to_receive
, chunk_size
);
3441 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3442 recv_size
, MSG_DONTWAIT
);
3444 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3445 PERROR("Socket %d error", conn
->sock
->fd
);
3446 status
= RELAY_CONNECTION_STATUS_ERROR
;
3448 goto end_stream_unlock
;
3449 } else if (ret
== 0) {
3450 /* No more data ready to be consumed on socket. */
3451 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3452 state
->header
.stream_id
);
3453 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3455 } else if (ret
< (int) recv_size
) {
3457 * All the data available on the socket has been
3460 partial_recv
= true;
3465 /* Write data to stream output fd. */
3466 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3468 if (write_ret
< (ssize_t
) recv_size
) {
3469 ERR("Relay error writing data to file");
3470 status
= RELAY_CONNECTION_STATUS_ERROR
;
3471 goto end_stream_unlock
;
3474 left_to_receive
-= recv_size
;
3475 state
->received
+= recv_size
;
3476 state
->left_to_receive
= left_to_receive
;
3478 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3479 write_ret
, stream
->stream_handle
);
3482 if (state
->left_to_receive
> 0) {
3484 * Did not receive all the data expected, wait for more data to
3485 * become available on the socket.
3487 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3488 state
->header
.stream_id
, state
->received
,
3489 state
->left_to_receive
);
3490 goto end_stream_unlock
;
3493 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3494 state
->header
.padding_size
);
3495 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3496 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3497 stream
->stream_handle
,
3498 state
->header
.net_seq_num
, ret
);
3499 status
= RELAY_CONNECTION_STATUS_ERROR
;
3500 goto end_stream_unlock
;
3504 if (session
->minor
>= 4 && !session
->snapshot
) {
3505 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3506 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3508 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3509 stream
->stream_handle
,
3510 state
->header
.net_seq_num
, ret
);
3511 status
= RELAY_CONNECTION_STATUS_ERROR
;
3512 goto end_stream_unlock
;
3516 stream
->tracefile_size_current
+= state
->header
.data_size
+
3517 state
->header
.padding_size
;
3519 if (stream
->prev_seq
== -1ULL) {
3522 if (index_flushed
) {
3523 stream
->pos_after_last_complete_data_index
=
3524 stream
->tracefile_size_current
;
3527 stream
->prev_seq
= state
->header
.net_seq_num
;
3530 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3531 * contents of *state which are aliased (union) to the same location as
3532 * the new state. Don't use it beyond this point.
3534 connection_reset_protocol_state(conn
);
3537 ret
= try_rotate_stream(stream
);
3539 status
= RELAY_CONNECTION_STATUS_ERROR
;
3540 goto end_stream_unlock
;
3544 close_requested
= stream
->close_requested
;
3545 pthread_mutex_unlock(&stream
->lock
);
3546 if (close_requested
&& left_to_receive
== 0) {
3547 try_stream_close(stream
);
3551 pthread_mutex_lock(&session
->lock
);
3552 uatomic_set(&session
->new_streams
, 1);
3553 pthread_mutex_unlock(&session
->lock
);
3562 * relay_process_data: Process the data received on the data socket
3564 static enum relay_connection_status
relay_process_data(
3565 struct relay_connection
*conn
)
3567 enum relay_connection_status status
;
3569 switch (conn
->protocol
.data
.state_id
) {
3570 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3571 status
= relay_process_data_receive_header(conn
);
3573 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3574 status
= relay_process_data_receive_payload(conn
);
3577 ERR("Unexpected data connection communication state.");
3584 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3588 (void) lttng_poll_del(events
, pollfd
);
3590 ret
= close(pollfd
);
3592 ERR("Closing pollfd %d", pollfd
);
3596 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3597 int pollfd
, struct relay_connection
*conn
)
3599 const char *type_str
;
3601 switch (conn
->type
) {
3606 type_str
= "Control";
3608 case RELAY_VIEWER_COMMAND
:
3609 type_str
= "Viewer Command";
3611 case RELAY_VIEWER_NOTIFICATION
:
3612 type_str
= "Viewer Notification";
3615 type_str
= "Unknown";
3617 cleanup_connection_pollfd(events
, pollfd
);
3618 connection_put(conn
);
3619 DBG("%s connection closed with %d", type_str
, pollfd
);
3623 * This thread does the actual work
3625 static void *relay_thread_worker(void *data
)
3627 int ret
, err
= -1, last_seen_data_fd
= -1;
3629 struct lttng_poll_event events
;
3630 struct lttng_ht
*relay_connections_ht
;
3631 struct lttng_ht_iter iter
;
3632 struct relay_connection
*destroy_conn
= NULL
;
3634 DBG("[thread] Relay worker started");
3636 rcu_register_thread();
3638 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3640 if (testpoint(relayd_thread_worker
)) {
3641 goto error_testpoint
;
3644 health_code_update();
3646 /* table of connections indexed on socket */
3647 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3648 if (!relay_connections_ht
) {
3649 goto relay_connections_ht_error
;
3652 ret
= create_named_thread_poll_set(&events
, 2, "Worker thread epoll");
3654 goto error_poll_create
;
3657 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3664 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3666 health_code_update();
3668 /* Infinite blocking call, waiting for transmission */
3669 DBG3("Relayd worker thread polling...");
3670 health_poll_entry();
3671 ret
= lttng_poll_wait(&events
, -1);
3675 * Restart interrupted system call.
3677 if (errno
== EINTR
) {
3686 * Process control. The control connection is
3687 * prioritized so we don't starve it with high
3688 * throughput tracing data on the data connection.
3690 for (i
= 0; i
< nb_fd
; i
++) {
3691 /* Fetch once the poll data */
3692 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3693 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3695 health_code_update();
3699 * No activity for this FD (poll
3705 /* Thread quit pipe has been closed. Killing thread. */
3706 ret
= check_thread_quit_pipe(pollfd
, revents
);
3712 /* Inspect the relay conn pipe for new connection */
3713 if (pollfd
== relay_conn_pipe
[0]) {
3714 if (revents
& LPOLLIN
) {
3715 struct relay_connection
*conn
;
3717 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3721 lttng_poll_add(&events
, conn
->sock
->fd
,
3722 LPOLLIN
| LPOLLRDHUP
);
3723 connection_ht_add(relay_connections_ht
, conn
);
3724 DBG("Connection socket %d added", conn
->sock
->fd
);
3725 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3726 ERR("Relay connection pipe error");
3729 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3733 struct relay_connection
*ctrl_conn
;
3735 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3736 /* If not found, there is a synchronization issue. */
3739 if (ctrl_conn
->type
== RELAY_DATA
) {
3740 if (revents
& LPOLLIN
) {
3742 * Flag the last seen data fd not deleted. It will be
3743 * used as the last seen fd if any fd gets deleted in
3746 last_notdel_data_fd
= pollfd
;
3748 goto put_ctrl_connection
;
3750 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3752 if (revents
& LPOLLIN
) {
3753 enum relay_connection_status status
;
3755 status
= relay_process_control(ctrl_conn
);
3756 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3758 * On socket error flag the session as aborted to force
3759 * the cleanup of its stream otherwise it can leak
3760 * during the lifetime of the relayd.
3762 * This prevents situations in which streams can be
3763 * left opened because an index was received, the
3764 * control connection is closed, and the data
3765 * connection is closed (uncleanly) before the packet's
3768 * Since the control connection encountered an error,
3769 * it is okay to be conservative and close the
3770 * session right now as we can't rely on the protocol
3771 * being respected anymore.
3773 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3774 session_abort(ctrl_conn
->session
);
3777 /* Clear the connection on error or close. */
3778 relay_thread_close_connection(&events
,
3783 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3784 relay_thread_close_connection(&events
,
3786 if (last_seen_data_fd
== pollfd
) {
3787 last_seen_data_fd
= last_notdel_data_fd
;
3790 ERR("Unexpected poll events %u for control sock %d",
3792 connection_put(ctrl_conn
);
3795 put_ctrl_connection
:
3796 connection_put(ctrl_conn
);
3801 * The last loop handled a control request, go back to poll to make
3802 * sure we prioritise the control socket.
3808 if (last_seen_data_fd
>= 0) {
3809 for (i
= 0; i
< nb_fd
; i
++) {
3810 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3812 health_code_update();
3814 if (last_seen_data_fd
== pollfd
) {
3821 /* Process data connection. */
3822 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3823 /* Fetch the poll data. */
3824 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3825 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3826 struct relay_connection
*data_conn
;
3828 health_code_update();
3831 /* No activity for this FD (poll implementation). */
3835 /* Skip the command pipe. It's handled in the first loop. */
3836 if (pollfd
== relay_conn_pipe
[0]) {
3840 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3842 /* Skip it. Might be removed before. */
3845 if (data_conn
->type
== RELAY_CONTROL
) {
3846 goto put_data_connection
;
3848 assert(data_conn
->type
== RELAY_DATA
);
3850 if (revents
& LPOLLIN
) {
3851 enum relay_connection_status status
;
3853 status
= relay_process_data(data_conn
);
3854 /* Connection closed or error. */
3855 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3857 * On socket error flag the session as aborted to force
3858 * the cleanup of its stream otherwise it can leak
3859 * during the lifetime of the relayd.
3861 * This prevents situations in which streams can be
3862 * left opened because an index was received, the
3863 * control connection is closed, and the data
3864 * connection is closed (uncleanly) before the packet's
3867 * Since the data connection encountered an error,
3868 * it is okay to be conservative and close the
3869 * session right now as we can't rely on the protocol
3870 * being respected anymore.
3872 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3873 session_abort(data_conn
->session
);
3875 relay_thread_close_connection(&events
, pollfd
,
3878 * Every goto restart call sets the last seen fd where
3879 * here we don't really care since we gracefully
3880 * continue the loop after the connection is deleted.
3883 /* Keep last seen port. */
3884 last_seen_data_fd
= pollfd
;
3885 connection_put(data_conn
);
3888 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3889 relay_thread_close_connection(&events
, pollfd
,
3892 ERR("Unknown poll events %u for data sock %d",
3895 put_data_connection
:
3896 connection_put(data_conn
);
3898 last_seen_data_fd
= -1;
3901 /* Normal exit, no error */
3906 /* Cleanup remaining connection object. */
3908 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3911 health_code_update();
3913 session_abort(destroy_conn
->session
);
3916 * No need to grab another ref, because we own
3919 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3924 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
3926 lttng_ht_destroy(relay_connections_ht
);
3927 relay_connections_ht_error
:
3928 /* Close relay conn pipes */
3929 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3932 DBG("Thread exited with error");
3934 DBG("Worker thread cleanup complete");
3938 ERR("Health error occurred in %s", __func__
);
3940 health_unregister(health_relayd
);
3941 rcu_unregister_thread();
3942 lttng_relay_stop_threads();
3947 * Create the relay command pipe to wake thread_manage_apps.
3948 * Closed in cleanup().
3950 static int create_relay_conn_pipe(void)
3952 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3953 "Relayd connection pipe", relay_conn_pipe
);
3957 int stdio_open(void *data
, int *fds
)
3959 fds
[0] = fileno(stdout
);
3960 fds
[1] = fileno(stderr
);
3965 int noop_close(void *data
, int *fds
)
3971 int track_stdio(void)
3974 const char *names
[] = { "stdout", "stderr" };
3976 return fd_tracker_open_unsuspendable_fd(the_fd_tracker
, fds
,
3977 names
, 2, stdio_open
, NULL
);
3981 void untrack_stdio(void)
3983 int fds
[] = { fileno(stdout
), fileno(stderr
) };
3986 * noop_close is used since we don't really want to close
3987 * the stdio output fds; we merely want to stop tracking them.
3989 (void) fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
3990 fds
, 2, noop_close
, NULL
);
3996 int main(int argc
, char **argv
)
3998 int ret
= 0, retval
= 0;
4001 /* Parse arguments */
4003 if (set_options(argc
, argv
)) {
4008 if (set_signal_handler()) {
4013 ret
= fclose(stdin
);
4015 PERROR("Failed to close stdin");
4018 /* Try to create directory if -o, --output is specified. */
4019 if (opt_output_path
) {
4020 if (*opt_output_path
!= '/') {
4021 ERR("Please specify an absolute path for -o, --output PATH");
4026 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4029 ERR("Unable to create %s", opt_output_path
);
4036 if (opt_daemon
|| opt_background
) {
4037 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4046 * The RCU thread registration (and use, through the fd-tracker's
4047 * creation) is done after the daemonization to allow us to not
4048 * deal with liburcu's fork() management as the call RCU needs to
4051 rcu_register_thread();
4053 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
4054 if (!the_fd_tracker
) {
4059 ret
= track_stdio();
4065 /* Initialize thread health monitoring */
4066 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4067 if (!health_relayd
) {
4068 PERROR("health_app_create error");
4070 goto exit_health_app_create
;
4073 /* Create thread quit pipe */
4074 if (init_thread_quit_pipe()) {
4076 goto exit_init_data
;
4079 /* Setup the thread apps communication pipe. */
4080 if (create_relay_conn_pipe()) {
4082 goto exit_init_data
;
4085 /* Init relay command queue. */
4086 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4088 /* Initialize communication library */
4090 lttcomm_inet_init();
4092 /* tables of sessions indexed by session ID */
4093 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4096 goto exit_init_data
;
4099 /* tables of streams indexed by stream ID */
4100 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4101 if (!relay_streams_ht
) {
4103 goto exit_init_data
;
4106 /* tables of streams indexed by stream ID */
4107 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4108 if (!viewer_streams_ht
) {
4110 goto exit_init_data
;
4113 ret
= init_health_quit_pipe();
4116 goto exit_health_quit_pipe
;
4119 /* Create thread to manage the client socket */
4120 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4121 thread_manage_health
, (void *) NULL
);
4124 PERROR("pthread_create health");
4126 goto exit_health_thread
;
4129 /* Setup the dispatcher thread */
4130 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4131 relay_thread_dispatcher
, (void *) NULL
);
4134 PERROR("pthread_create dispatcher");
4136 goto exit_dispatcher_thread
;
4139 /* Setup the worker thread */
4140 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4141 relay_thread_worker
, NULL
);
4144 PERROR("pthread_create worker");
4146 goto exit_worker_thread
;
4149 /* Setup the listener thread */
4150 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4151 relay_thread_listener
, (void *) NULL
);
4154 PERROR("pthread_create listener");
4156 goto exit_listener_thread
;
4159 ret
= relayd_live_create(live_uri
);
4161 ERR("Starting live viewer threads");
4167 * This is where we start awaiting program completion (e.g. through
4168 * signal that asks threads to teardown).
4171 ret
= relayd_live_join();
4177 ret
= pthread_join(listener_thread
, &status
);
4180 PERROR("pthread_join listener_thread");
4184 exit_listener_thread
:
4185 ret
= pthread_join(worker_thread
, &status
);
4188 PERROR("pthread_join worker_thread");
4193 ret
= pthread_join(dispatcher_thread
, &status
);
4196 PERROR("pthread_join dispatcher_thread");
4199 exit_dispatcher_thread
:
4201 ret
= pthread_join(health_thread
, &status
);
4204 PERROR("pthread_join health_thread");
4209 (void) fd_tracker_util_pipe_close(the_fd_tracker
, health_quit_pipe
);
4210 exit_health_quit_pipe
:
4213 health_app_destroy(health_relayd
);
4214 exit_health_app_create
:
4217 * Wait for all pending call_rcu work to complete before tearing
4218 * down data structures. call_rcu worker may be trying to
4219 * perform lookups in those structures.
4224 /* Ensure all prior call_rcu are done. */
4229 * fd_tracker_destroy() will log the contents of the fd-tracker
4230 * if a leak is detected.
4232 fd_tracker_destroy(the_fd_tracker
);
4233 rcu_unregister_thread();