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/config/session-config.h>
60 #include <common/dynamic-buffer.h>
61 #include <common/buffer-view.h>
62 #include <urcu/rculist.h>
66 #include "ctf-trace.h"
69 #include "lttng-relayd.h"
71 #include "health-relayd.h"
72 #include "testpoint.h"
73 #include "viewer-stream.h"
76 #include "connection.h"
77 #include "tracefile-array.h"
78 #include "tcp_keep_alive.h"
80 enum relay_connection_status
{
81 RELAY_CONNECTION_STATUS_OK
,
82 /* An error occured while processing an event on the connection. */
83 RELAY_CONNECTION_STATUS_ERROR
,
84 /* Connection closed/shutdown cleanly. */
85 RELAY_CONNECTION_STATUS_CLOSED
,
88 /* command line options */
89 char *opt_output_path
, *opt_working_directory
;
90 static int opt_daemon
, opt_background
, opt_print_version
;
91 int opt_group_output_by_session
;
92 int opt_group_output_by_host
;
95 * We need to wait for listener and live listener threads, as well as
96 * health check thread, before being ready to signal readiness.
98 #define NR_LTTNG_RELAY_READY 3
99 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
101 /* Size of receive buffer. */
102 #define RECV_DATA_BUFFER_SIZE 65536
104 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
105 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
107 static struct lttng_uri
*control_uri
;
108 static struct lttng_uri
*data_uri
;
109 static struct lttng_uri
*live_uri
;
111 const char *progname
;
113 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
114 static int tracing_group_name_override
;
116 const char * const config_section_name
= "relayd";
119 * Quit pipe for all threads. This permits a single cancellation point
120 * for all threads when receiving an event on the pipe.
122 int thread_quit_pipe
[2] = { -1, -1 };
125 * This pipe is used to inform the worker thread that a command is queued and
126 * ready to be processed.
128 static int relay_conn_pipe
[2] = { -1, -1 };
130 /* Shared between threads */
131 static int dispatch_thread_exit
;
133 static pthread_t listener_thread
;
134 static pthread_t dispatcher_thread
;
135 static pthread_t worker_thread
;
136 static pthread_t health_thread
;
139 * last_relay_stream_id_lock protects last_relay_stream_id increment
140 * atomicity on 32-bit architectures.
142 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
143 static uint64_t last_relay_stream_id
;
146 * Relay command queue.
148 * The relay_thread_listener and relay_thread_dispatcher communicate with this
151 static struct relay_conn_queue relay_conn_queue
;
153 /* Cap of file desriptors to be in simultaneous use by the relay daemon. */
154 static unsigned int lttng_opt_fd_cap
;
156 /* Global relay stream hash table. */
157 struct lttng_ht
*relay_streams_ht
;
159 /* Global relay viewer stream hash table. */
160 struct lttng_ht
*viewer_streams_ht
;
162 /* Global relay sessions hash table. */
163 struct lttng_ht
*sessions_ht
;
165 /* Relayd health monitoring */
166 struct health_app
*health_relayd
;
168 /* Global fd tracker. */
169 struct fd_tracker
*the_fd_tracker
;
171 static struct option long_options
[] = {
172 { "control-port", 1, 0, 'C', },
173 { "data-port", 1, 0, 'D', },
174 { "live-port", 1, 0, 'L', },
175 { "daemonize", 0, 0, 'd', },
176 { "background", 0, 0, 'b', },
177 { "group", 1, 0, 'g', },
178 { "fd-cap", 1, 0, '\0', },
179 { "help", 0, 0, 'h', },
180 { "output", 1, 0, 'o', },
181 { "verbose", 0, 0, 'v', },
182 { "config", 1, 0, 'f' },
183 { "version", 0, 0, 'V' },
184 { "working-directory", 1, 0, 'w', },
185 { "group-output-by-session", 0, 0, 's', },
186 { "group-output-by-host", 0, 0, 'p', },
190 static const char *config_ignore_options
[] = { "help", "config", "version" };
192 static void print_version(void) {
193 fprintf(stdout
, "%s\n", VERSION
);
196 static void relayd_config_log(void)
198 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
199 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
200 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
201 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
202 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
204 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
205 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
210 * Take an option from the getopt output and set it in the right variable to be
213 * Return 0 on success else a negative value.
215 static int set_option(int opt
, const char *arg
, const char *optname
)
221 if (!strcmp(optname
, "fd-cap")) {
225 v
= strtoul(arg
, NULL
, 0);
226 if (errno
!= 0 || !isdigit(arg
[0])) {
227 ERR("Wrong value in --fd-cap parameter: %s", arg
);
231 if (v
< DEFAULT_RELAYD_MINIMAL_FD_CAP
) {
232 ERR("File descriptor cap must be set to at least %d",
233 DEFAULT_RELAYD_MINIMAL_FD_CAP
);
236 ERR("File descriptor cap overflow in --fd-cap parameter: %s", arg
);
240 lttng_opt_fd_cap
= (unsigned int) v
;
241 DBG3("File descriptor cap set to %u", lttng_opt_fd_cap
);
244 fprintf(stderr
, "unknown option %s", optname
);
246 fprintf(stderr
, " with arg %s\n", arg
);
251 if (lttng_is_setuid_setgid()) {
252 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
253 "-C, --control-port");
255 ret
= uri_parse(arg
, &control_uri
);
257 ERR("Invalid control URI specified");
260 if (control_uri
->port
== 0) {
261 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
266 if (lttng_is_setuid_setgid()) {
267 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
270 ret
= uri_parse(arg
, &data_uri
);
272 ERR("Invalid data URI specified");
275 if (data_uri
->port
== 0) {
276 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
281 if (lttng_is_setuid_setgid()) {
282 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
285 ret
= uri_parse(arg
, &live_uri
);
287 ERR("Invalid live URI specified");
290 if (live_uri
->port
== 0) {
291 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
302 if (lttng_is_setuid_setgid()) {
303 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
306 tracing_group_name
= strdup(arg
);
307 if (tracing_group_name
== NULL
) {
312 tracing_group_name_override
= 1;
316 ret
= utils_show_man_page(8, "lttng-relayd");
318 ERR("Cannot view man page lttng-relayd(8)");
323 opt_print_version
= 1;
326 if (lttng_is_setuid_setgid()) {
327 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
330 ret
= asprintf(&opt_output_path
, "%s", arg
);
333 PERROR("asprintf opt_output_path");
339 if (lttng_is_setuid_setgid()) {
340 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
341 "-w, --working-directory");
343 ret
= asprintf(&opt_working_directory
, "%s", arg
);
346 PERROR("asprintf working_directory");
353 /* Verbose level can increase using multiple -v */
355 lttng_opt_verbose
= config_parse_value(arg
);
357 /* Only 3 level of verbosity (-vvv). */
358 if (lttng_opt_verbose
< 3) {
359 lttng_opt_verbose
+= 1;
364 if (opt_group_output_by_host
) {
365 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
368 opt_group_output_by_session
= 1;
371 if (opt_group_output_by_session
) {
372 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
375 opt_group_output_by_host
= 1;
378 /* Unknown option or other error.
379 * Error is printed by getopt, just return */
392 * config_entry_handler_cb used to handle options read from a config file.
393 * See config_entry_handler_cb comment in common/config/session-config.h for the
394 * return value conventions.
396 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
400 if (!entry
|| !entry
->name
|| !entry
->value
) {
405 /* Check if the option is to be ignored */
406 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
407 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
412 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
413 /* Ignore if entry name is not fully matched. */
414 if (strcmp(entry
->name
, long_options
[i
].name
)) {
419 * If the option takes no argument on the command line,
420 * we have to check if the value is "true". We support
421 * non-zero numeric values, true, on and yes.
423 if (!long_options
[i
].has_arg
) {
424 ret
= config_parse_value(entry
->value
);
427 WARN("Invalid configuration value \"%s\" for option %s",
428 entry
->value
, entry
->name
);
430 /* False, skip boolean config option. */
435 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
439 WARN("Unrecognized option \"%s\" in daemon configuration file.",
446 static void parse_env_options(void)
450 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
452 opt_working_directory
= value
;
456 static int set_options(int argc
, char **argv
)
458 int c
, ret
= 0, option_index
= 0, retval
= 0;
459 int orig_optopt
= optopt
, orig_optind
= optind
;
460 char *default_address
, *optstring
;
461 const char *config_path
= NULL
;
463 optstring
= utils_generate_optstring(long_options
,
464 sizeof(long_options
) / sizeof(struct option
));
470 /* Check for the --config option */
472 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
473 &option_index
)) != -1) {
477 } else if (c
!= 'f') {
481 if (lttng_is_setuid_setgid()) {
482 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
485 config_path
= utils_expand_path(optarg
);
487 ERR("Failed to resolve path: %s", optarg
);
492 ret
= config_get_section_entries(config_path
, config_section_name
,
493 config_entry_handler
, NULL
);
496 ERR("Invalid configuration option at line %i", ret
);
502 /* Reset getopt's global state */
503 optopt
= orig_optopt
;
504 optind
= orig_optind
;
506 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
511 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
518 /* assign default values */
519 if (control_uri
== NULL
) {
520 ret
= asprintf(&default_address
,
521 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
522 DEFAULT_NETWORK_CONTROL_PORT
);
524 PERROR("asprintf default data address");
529 ret
= uri_parse(default_address
, &control_uri
);
530 free(default_address
);
532 ERR("Invalid control URI specified");
537 if (data_uri
== NULL
) {
538 ret
= asprintf(&default_address
,
539 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
540 DEFAULT_NETWORK_DATA_PORT
);
542 PERROR("asprintf default data address");
547 ret
= uri_parse(default_address
, &data_uri
);
548 free(default_address
);
550 ERR("Invalid data URI specified");
555 if (live_uri
== NULL
) {
556 ret
= asprintf(&default_address
,
557 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
558 DEFAULT_NETWORK_VIEWER_PORT
);
560 PERROR("asprintf default viewer control address");
565 ret
= uri_parse(default_address
, &live_uri
);
566 free(default_address
);
568 ERR("Invalid viewer control URI specified");
573 if (lttng_opt_fd_cap
== 0) {
575 struct rlimit rlimit
;
577 ret
= getrlimit(RLIMIT_NOFILE
, &rlimit
);
579 PERROR("Failed to get file descriptor limit");
583 lttng_opt_fd_cap
= rlimit
.rlim_cur
;
586 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
587 /* Group by host by default */
588 opt_group_output_by_host
= 1;
596 static void print_global_objects(void)
598 print_viewer_streams();
599 print_relay_streams();
606 static void relayd_cleanup(void)
608 print_global_objects();
612 if (viewer_streams_ht
)
613 lttng_ht_destroy(viewer_streams_ht
);
614 if (relay_streams_ht
)
615 lttng_ht_destroy(relay_streams_ht
);
617 lttng_ht_destroy(sessions_ht
);
619 /* free the dynamically allocated opt_output_path */
620 free(opt_output_path
);
622 /* Close thread quit pipes */
623 (void) fd_tracker_util_pipe_close(the_fd_tracker
, thread_quit_pipe
);
625 uri_free(control_uri
);
627 /* Live URI is freed in the live thread. */
629 if (tracing_group_name_override
) {
630 free((void *) tracing_group_name
);
632 fd_tracker_log(the_fd_tracker
);
636 * Write to writable pipe used to notify a thread.
638 static int notify_thread_pipe(int wpipe
)
642 ret
= lttng_write(wpipe
, "!", 1);
644 PERROR("write poll pipe");
652 static int notify_health_quit_pipe(int *pipe
)
656 ret
= lttng_write(pipe
[1], "4", 1);
658 PERROR("write relay health quit");
667 * Stop all relayd and relayd-live threads.
669 int lttng_relay_stop_threads(void)
673 /* Stopping all threads */
674 DBG("Terminating all threads");
675 if (notify_thread_pipe(thread_quit_pipe
[1])) {
676 ERR("write error on thread quit pipe");
680 if (notify_health_quit_pipe(health_quit_pipe
)) {
681 ERR("write error on health quit pipe");
684 /* Dispatch thread */
685 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
686 futex_nto1_wake(&relay_conn_queue
.futex
);
688 if (relayd_live_stop()) {
689 ERR("Error stopping live threads");
696 * Signal handler for the daemon
698 * Simply stop all worker threads, leaving main() return gracefully after
699 * joining all threads and calling cleanup().
701 static void sighandler(int sig
)
705 DBG("SIGINT caught");
706 if (lttng_relay_stop_threads()) {
707 ERR("Error stopping threads");
711 DBG("SIGTERM caught");
712 if (lttng_relay_stop_threads()) {
713 ERR("Error stopping threads");
717 CMM_STORE_SHARED(recv_child_signal
, 1);
725 * Setup signal handler for :
726 * SIGINT, SIGTERM, SIGPIPE
728 static int set_signal_handler(void)
734 if ((ret
= sigemptyset(&sigset
)) < 0) {
735 PERROR("sigemptyset");
742 sa
.sa_handler
= sighandler
;
743 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
748 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
753 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
758 sa
.sa_handler
= SIG_IGN
;
759 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
764 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
769 void lttng_relay_notify_ready(void)
771 /* Notify the parent of the fork() process that we are ready. */
772 if (opt_daemon
|| opt_background
) {
773 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
774 kill(child_ppid
, SIGUSR1
);
780 * Init thread quit pipe.
782 * Return -1 on error or 0 if all pipes are created.
784 static int init_thread_quit_pipe(void)
786 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
787 "Quit pipe", thread_quit_pipe
);
791 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
793 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
797 if (events
== NULL
|| size
== 0) {
802 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
808 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
820 * Check if the thread quit pipe was triggered.
822 * Return 1 if it was triggered else 0;
824 static int check_thread_quit_pipe(int fd
, uint32_t events
)
826 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
834 * Create and init socket from uri.
836 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
839 struct lttcomm_sock
*sock
= NULL
;
841 sock
= lttcomm_alloc_sock_from_uri(uri
);
843 ERR("Allocating socket");
847 ret
= lttcomm_create_sock(sock
);
851 DBG("Listening on sock %d", sock
->fd
);
853 ret
= sock
->ops
->bind(sock
);
858 ret
= sock
->ops
->listen(sock
, -1);
868 lttcomm_destroy_sock(sock
);
874 * This thread manages the listening for new connections on the network
876 static void *relay_thread_listener(void *data
)
878 int i
, ret
, pollfd
, err
= -1;
879 uint32_t revents
, nb_fd
;
880 struct lttng_poll_event events
;
881 struct lttcomm_sock
*control_sock
, *data_sock
;
883 DBG("[thread] Relay listener started");
885 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
887 health_code_update();
889 control_sock
= relay_socket_create(control_uri
);
891 goto error_sock_control
;
894 data_sock
= relay_socket_create(data_uri
);
896 goto error_sock_relay
;
900 * Pass 3 as size here for the thread quit pipe, control and
903 ret
= create_thread_poll_set(&events
, 3);
905 goto error_create_poll
;
908 /* Add the control socket */
909 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
914 /* Add the data socket */
915 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
920 lttng_relay_notify_ready();
922 if (testpoint(relayd_thread_listener
)) {
923 goto error_testpoint
;
927 health_code_update();
929 DBG("Listener accepting connections");
933 ret
= lttng_poll_wait(&events
, -1);
937 * Restart interrupted system call.
939 if (errno
== EINTR
) {
947 DBG("Relay new connection received");
948 for (i
= 0; i
< nb_fd
; i
++) {
949 health_code_update();
951 /* Fetch once the poll data */
952 revents
= LTTNG_POLL_GETEV(&events
, i
);
953 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
957 * No activity for this FD (poll
963 /* Thread quit pipe has been closed. Killing thread. */
964 ret
= check_thread_quit_pipe(pollfd
, revents
);
970 if (revents
& LPOLLIN
) {
972 * A new connection is requested, therefore a
973 * sessiond/consumerd connection is allocated in
974 * this thread, enqueued to a global queue and
975 * dequeued (and freed) in the worker thread.
978 struct relay_connection
*new_conn
;
979 struct lttcomm_sock
*newsock
;
980 enum connection_type type
;
982 if (pollfd
== data_sock
->fd
) {
984 newsock
= data_sock
->ops
->accept(data_sock
);
985 DBG("Relay data connection accepted, socket %d",
988 assert(pollfd
== control_sock
->fd
);
989 type
= RELAY_CONTROL
;
990 newsock
= control_sock
->ops
->accept(control_sock
);
991 DBG("Relay control connection accepted, socket %d",
995 PERROR("accepting sock");
999 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
1002 PERROR("setsockopt inet");
1003 lttcomm_destroy_sock(newsock
);
1007 ret
= socket_apply_keep_alive_config(newsock
->fd
);
1009 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
1011 lttcomm_destroy_sock(newsock
);
1015 new_conn
= connection_create(newsock
, type
);
1017 lttcomm_destroy_sock(newsock
);
1021 /* Enqueue request for the dispatcher thread. */
1022 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
1026 * Wake the dispatch queue futex.
1027 * Implicit memory barrier with the
1028 * exchange in cds_wfcq_enqueue.
1030 futex_nto1_wake(&relay_conn_queue
.futex
);
1031 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1032 ERR("socket poll error");
1035 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1045 lttng_poll_clean(&events
);
1047 if (data_sock
->fd
>= 0) {
1048 ret
= data_sock
->ops
->close(data_sock
);
1053 lttcomm_destroy_sock(data_sock
);
1055 if (control_sock
->fd
>= 0) {
1056 ret
= control_sock
->ops
->close(control_sock
);
1061 lttcomm_destroy_sock(control_sock
);
1065 ERR("Health error occurred in %s", __func__
);
1067 health_unregister(health_relayd
);
1068 DBG("Relay listener thread cleanup complete");
1069 lttng_relay_stop_threads();
1074 * This thread manages the dispatching of the requests to worker threads
1076 static void *relay_thread_dispatcher(void *data
)
1080 struct cds_wfcq_node
*node
;
1081 struct relay_connection
*new_conn
= NULL
;
1083 DBG("[thread] Relay dispatcher started");
1085 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1087 if (testpoint(relayd_thread_dispatcher
)) {
1088 goto error_testpoint
;
1091 health_code_update();
1094 health_code_update();
1096 /* Atomically prepare the queue futex */
1097 futex_nto1_prepare(&relay_conn_queue
.futex
);
1099 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1104 health_code_update();
1106 /* Dequeue commands */
1107 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1108 &relay_conn_queue
.tail
);
1110 DBG("Woken up but nothing in the relay command queue");
1111 /* Continue thread execution */
1114 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1116 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1119 * Inform worker thread of the new request. This
1120 * call is blocking so we can be assured that
1121 * the data will be read at some point in time
1122 * or wait to the end of the world :)
1124 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1126 PERROR("write connection pipe");
1127 connection_put(new_conn
);
1130 } while (node
!= NULL
);
1132 /* Futex wait on queue. Blocking call on futex() */
1133 health_poll_entry();
1134 futex_nto1_wait(&relay_conn_queue
.futex
);
1138 /* Normal exit, no error */
1145 ERR("Health error occurred in %s", __func__
);
1147 health_unregister(health_relayd
);
1148 DBG("Dispatch thread dying");
1149 lttng_relay_stop_threads();
1154 * Set index data from the control port to a given index object.
1156 static int set_index_control_data(struct relay_index
*index
,
1157 struct lttcomm_relayd_index
*data
,
1158 struct relay_connection
*conn
)
1160 struct ctf_packet_index index_data
;
1163 * The index on disk is encoded in big endian.
1165 index_data
.packet_size
= htobe64(data
->packet_size
);
1166 index_data
.content_size
= htobe64(data
->content_size
);
1167 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1168 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1169 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1170 index_data
.stream_id
= htobe64(data
->stream_id
);
1172 if (conn
->minor
>= 8) {
1173 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1174 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1177 return relay_index_set_data(index
, &index_data
);
1181 * Handle the RELAYD_CREATE_SESSION command.
1183 * On success, send back the session id or else return a negative value.
1185 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1186 struct relay_connection
*conn
,
1187 const struct lttng_buffer_view
*payload
)
1191 struct relay_session
*session
;
1192 struct lttcomm_relayd_status_session reply
;
1193 char session_name
[LTTNG_NAME_MAX
];
1194 char hostname
[LTTNG_HOST_NAME_MAX
];
1195 uint32_t live_timer
= 0;
1196 bool snapshot
= false;
1198 memset(session_name
, 0, LTTNG_NAME_MAX
);
1199 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1201 memset(&reply
, 0, sizeof(reply
));
1203 switch (conn
->minor
) {
1208 case 4: /* LTTng sessiond 2.4 */
1210 ret
= cmd_create_session_2_4(payload
, session_name
,
1211 hostname
, &live_timer
, &snapshot
);
1217 session
= session_create(session_name
, hostname
, live_timer
,
1218 snapshot
, conn
->major
, conn
->minor
);
1223 assert(!conn
->session
);
1224 conn
->session
= session
;
1225 DBG("Created session %" PRIu64
, session
->id
);
1227 reply
.session_id
= htobe64(session
->id
);
1231 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1233 reply
.ret_code
= htobe32(LTTNG_OK
);
1236 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1237 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1238 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1247 * When we have received all the streams and the metadata for a channel,
1248 * we make them visible to the viewer threads.
1250 static void publish_connection_local_streams(struct relay_connection
*conn
)
1252 struct relay_stream
*stream
;
1253 struct relay_session
*session
= conn
->session
;
1256 * We publish all streams belonging to a session atomically wrt
1259 pthread_mutex_lock(&session
->lock
);
1261 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1263 stream_publish(stream
);
1268 * Inform the viewer that there are new streams in the session.
1270 if (session
->viewer_attached
) {
1271 uatomic_set(&session
->new_streams
, 1);
1273 pthread_mutex_unlock(&session
->lock
);
1277 * relay_add_stream: allocate a new stream for a session
1279 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1280 struct relay_connection
*conn
,
1281 const struct lttng_buffer_view
*payload
)
1285 struct relay_session
*session
= conn
->session
;
1286 struct relay_stream
*stream
= NULL
;
1287 struct lttcomm_relayd_status_stream reply
;
1288 struct ctf_trace
*trace
= NULL
;
1289 uint64_t stream_handle
= -1ULL;
1290 char *path_name
= NULL
, *channel_name
= NULL
;
1291 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1293 if (!session
|| !conn
->version_check_done
) {
1294 ERR("Trying to add a stream before version check");
1296 goto end_no_session
;
1299 switch (session
->minor
) {
1300 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1301 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1302 &channel_name
, session
);
1304 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1306 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1307 &channel_name
, &tracefile_size
, &tracefile_count
,
1315 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1319 /* This stream here has one reference on the trace. */
1321 pthread_mutex_lock(&last_relay_stream_id_lock
);
1322 stream_handle
= ++last_relay_stream_id
;
1323 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1325 /* We pass ownership of path_name and channel_name. */
1326 stream
= stream_create(trace
, stream_handle
, path_name
,
1327 channel_name
, tracefile_size
, tracefile_count
);
1329 channel_name
= NULL
;
1332 * Streams are the owners of their trace. Reference to trace is
1333 * kept within stream_create().
1335 ctf_trace_put(trace
);
1338 memset(&reply
, 0, sizeof(reply
));
1339 reply
.handle
= htobe64(stream_handle
);
1341 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1343 reply
.ret_code
= htobe32(LTTNG_OK
);
1346 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1347 sizeof(struct lttcomm_relayd_status_stream
), 0);
1348 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1349 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1361 * relay_close_stream: close a specific stream
1363 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1364 struct relay_connection
*conn
,
1365 const struct lttng_buffer_view
*payload
)
1369 struct relay_session
*session
= conn
->session
;
1370 struct lttcomm_relayd_close_stream stream_info
;
1371 struct lttcomm_relayd_generic_reply reply
;
1372 struct relay_stream
*stream
;
1374 DBG("Close stream received");
1376 if (!session
|| !conn
->version_check_done
) {
1377 ERR("Trying to close a stream before version check");
1379 goto end_no_session
;
1382 if (payload
->size
< sizeof(stream_info
)) {
1383 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1384 sizeof(stream_info
), payload
->size
);
1386 goto end_no_session
;
1388 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1389 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1390 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1392 stream
= stream_get_by_id(stream_info
.stream_id
);
1399 * Set last_net_seq_num before the close flag. Required by data
1402 pthread_mutex_lock(&stream
->lock
);
1403 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1404 pthread_mutex_unlock(&stream
->lock
);
1407 * This is one of the conditions which may trigger a stream close
1408 * with the others being:
1409 * 1) A close command is received for a stream
1410 * 2) The control connection owning the stream is closed
1411 * 3) We have received all of the stream's data _after_ a close
1414 try_stream_close(stream
);
1415 if (stream
->is_metadata
) {
1416 struct relay_viewer_stream
*vstream
;
1418 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1420 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1422 * Since all the metadata has been sent to the
1423 * viewer and that we have a request to close
1424 * its stream, we can safely teardown the
1425 * corresponding metadata viewer stream.
1427 viewer_stream_put(vstream
);
1429 /* Put local reference. */
1430 viewer_stream_put(vstream
);
1437 memset(&reply
, 0, sizeof(reply
));
1439 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1441 reply
.ret_code
= htobe32(LTTNG_OK
);
1443 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1444 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1445 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1446 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1456 * relay_reset_metadata: reset a metadata stream
1459 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1460 struct relay_connection
*conn
,
1461 const struct lttng_buffer_view
*payload
)
1465 struct relay_session
*session
= conn
->session
;
1466 struct lttcomm_relayd_reset_metadata stream_info
;
1467 struct lttcomm_relayd_generic_reply reply
;
1468 struct relay_stream
*stream
;
1470 DBG("Reset metadata received");
1472 if (!session
|| !conn
->version_check_done
) {
1473 ERR("Trying to reset a metadata stream before version check");
1475 goto end_no_session
;
1478 if (payload
->size
< sizeof(stream_info
)) {
1479 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1480 sizeof(stream_info
), payload
->size
);
1482 goto end_no_session
;
1484 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1485 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1486 stream_info
.version
= be64toh(stream_info
.version
);
1488 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1490 /* Unsupported for live sessions for now. */
1491 if (session
->live_timer
!= 0) {
1496 stream
= stream_get_by_id(stream_info
.stream_id
);
1501 pthread_mutex_lock(&stream
->lock
);
1502 if (!stream
->is_metadata
) {
1507 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1508 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1509 &stream
->stream_fd
->fd
);
1511 ERR("Failed to rotate metadata file %s of channel %s",
1512 stream
->path_name
, stream
->channel_name
);
1517 pthread_mutex_unlock(&stream
->lock
);
1521 memset(&reply
, 0, sizeof(reply
));
1523 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1525 reply
.ret_code
= htobe32(LTTNG_OK
);
1527 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1528 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1529 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1530 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1540 * relay_unknown_command: send -1 if received unknown command
1542 static void relay_unknown_command(struct relay_connection
*conn
)
1544 struct lttcomm_relayd_generic_reply reply
;
1547 memset(&reply
, 0, sizeof(reply
));
1548 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1549 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1550 if (send_ret
< sizeof(reply
)) {
1551 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1556 * relay_start: send an acknowledgment to the client to tell if we are
1557 * ready to receive data. We are ready if a session is established.
1559 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1560 struct relay_connection
*conn
,
1561 const struct lttng_buffer_view
*payload
)
1565 struct lttcomm_relayd_generic_reply reply
;
1566 struct relay_session
*session
= conn
->session
;
1569 DBG("Trying to start the streaming without a session established");
1570 ret
= htobe32(LTTNG_ERR_UNK
);
1573 memset(&reply
, 0, sizeof(reply
));
1574 reply
.ret_code
= htobe32(LTTNG_OK
);
1575 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1577 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1578 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1587 * Append padding to the file pointed by the file descriptor fd.
1589 static int write_padding_to_file(int fd
, uint32_t size
)
1598 zeros
= zmalloc(size
);
1599 if (zeros
== NULL
) {
1600 PERROR("zmalloc zeros for padding");
1605 ret
= lttng_write(fd
, zeros
, size
);
1607 PERROR("write padding to file");
1617 * relay_recv_metadata: receive the metadata for the session.
1619 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1620 struct relay_connection
*conn
,
1621 const struct lttng_buffer_view
*payload
)
1625 struct relay_session
*session
= conn
->session
;
1626 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1627 struct relay_stream
*metadata_stream
;
1628 uint64_t metadata_payload_size
;
1631 ERR("Metadata sent before version check");
1636 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1637 ERR("Incorrect data size");
1641 metadata_payload_size
= recv_hdr
->data_size
-
1642 sizeof(struct lttcomm_relayd_metadata_payload
);
1644 memcpy(&metadata_payload_header
, payload
->data
,
1645 sizeof(metadata_payload_header
));
1646 metadata_payload_header
.stream_id
= be64toh(
1647 metadata_payload_header
.stream_id
);
1648 metadata_payload_header
.padding_size
= be32toh(
1649 metadata_payload_header
.padding_size
);
1651 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1652 if (!metadata_stream
) {
1657 pthread_mutex_lock(&metadata_stream
->lock
);
1659 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1660 payload
->data
+ sizeof(metadata_payload_header
),
1661 metadata_payload_size
);
1662 if (size_ret
< metadata_payload_size
) {
1663 ERR("Relay error writing metadata on file");
1668 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1669 metadata_payload_header
.padding_size
);
1670 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1675 metadata_stream
->metadata_received
+=
1676 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1677 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1678 metadata_stream
->metadata_received
);
1681 pthread_mutex_unlock(&metadata_stream
->lock
);
1682 stream_put(metadata_stream
);
1688 * relay_send_version: send relayd version number
1690 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1691 struct relay_connection
*conn
,
1692 const struct lttng_buffer_view
*payload
)
1696 struct lttcomm_relayd_version reply
, msg
;
1697 bool compatible
= true;
1699 conn
->version_check_done
= true;
1701 /* Get version from the other side. */
1702 if (payload
->size
< sizeof(msg
)) {
1703 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1704 sizeof(msg
), payload
->size
);
1709 memcpy(&msg
, payload
->data
, sizeof(msg
));
1710 msg
.major
= be32toh(msg
.major
);
1711 msg
.minor
= be32toh(msg
.minor
);
1713 memset(&reply
, 0, sizeof(reply
));
1714 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1715 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1717 /* Major versions must be the same */
1718 if (reply
.major
!= msg
.major
) {
1719 DBG("Incompatible major versions (%u vs %u), deleting session",
1720 reply
.major
, msg
.major
);
1724 conn
->major
= reply
.major
;
1725 /* We adapt to the lowest compatible version */
1726 if (reply
.minor
<= msg
.minor
) {
1727 conn
->minor
= reply
.minor
;
1729 conn
->minor
= msg
.minor
;
1732 reply
.major
= htobe32(reply
.major
);
1733 reply
.minor
= htobe32(reply
.minor
);
1734 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1736 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1737 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1750 DBG("Version check done using protocol %u.%u", conn
->major
,
1758 * Check for data pending for a given stream id from the session daemon.
1760 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1761 struct relay_connection
*conn
,
1762 const struct lttng_buffer_view
*payload
)
1764 struct relay_session
*session
= conn
->session
;
1765 struct lttcomm_relayd_data_pending msg
;
1766 struct lttcomm_relayd_generic_reply reply
;
1767 struct relay_stream
*stream
;
1771 DBG("Data pending command received");
1773 if (!session
|| !conn
->version_check_done
) {
1774 ERR("Trying to check for data before version check");
1776 goto end_no_session
;
1779 if (payload
->size
< sizeof(msg
)) {
1780 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1781 sizeof(msg
), payload
->size
);
1783 goto end_no_session
;
1785 memcpy(&msg
, payload
->data
, sizeof(msg
));
1786 msg
.stream_id
= be64toh(msg
.stream_id
);
1787 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1789 stream
= stream_get_by_id(msg
.stream_id
);
1790 if (stream
== NULL
) {
1795 pthread_mutex_lock(&stream
->lock
);
1797 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1798 " and last_seq %" PRIu64
, msg
.stream_id
,
1799 stream
->prev_seq
, msg
.last_net_seq_num
);
1801 /* Avoid wrapping issue */
1802 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1803 /* Data has in fact been written and is NOT pending */
1806 /* Data still being streamed thus pending */
1810 stream
->data_pending_check_done
= true;
1811 pthread_mutex_unlock(&stream
->lock
);
1816 memset(&reply
, 0, sizeof(reply
));
1817 reply
.ret_code
= htobe32(ret
);
1818 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1819 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1820 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1830 * Wait for the control socket to reach a quiescent state.
1832 * Note that for now, when receiving this command from the session
1833 * daemon, this means that every subsequent commands or data received on
1834 * the control socket has been handled. So, this is why we simply return
1837 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1838 struct relay_connection
*conn
,
1839 const struct lttng_buffer_view
*payload
)
1843 struct relay_stream
*stream
;
1844 struct lttcomm_relayd_quiescent_control msg
;
1845 struct lttcomm_relayd_generic_reply reply
;
1847 DBG("Checking quiescent state on control socket");
1849 if (!conn
->session
|| !conn
->version_check_done
) {
1850 ERR("Trying to check for data before version check");
1852 goto end_no_session
;
1855 if (payload
->size
< sizeof(msg
)) {
1856 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1857 sizeof(msg
), payload
->size
);
1859 goto end_no_session
;
1861 memcpy(&msg
, payload
->data
, sizeof(msg
));
1862 msg
.stream_id
= be64toh(msg
.stream_id
);
1864 stream
= stream_get_by_id(msg
.stream_id
);
1868 pthread_mutex_lock(&stream
->lock
);
1869 stream
->data_pending_check_done
= true;
1870 pthread_mutex_unlock(&stream
->lock
);
1872 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1875 memset(&reply
, 0, sizeof(reply
));
1876 reply
.ret_code
= htobe32(LTTNG_OK
);
1877 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1878 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1879 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1891 * Initialize a data pending command. This means that a consumer is about
1892 * to ask for data pending for each stream it holds. Simply iterate over
1893 * all streams of a session and set the data_pending_check_done flag.
1895 * This command returns to the client a LTTNG_OK code.
1897 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1898 struct relay_connection
*conn
,
1899 const struct lttng_buffer_view
*payload
)
1903 struct lttng_ht_iter iter
;
1904 struct lttcomm_relayd_begin_data_pending msg
;
1905 struct lttcomm_relayd_generic_reply reply
;
1906 struct relay_stream
*stream
;
1911 DBG("Init streams for data pending");
1913 if (!conn
->session
|| !conn
->version_check_done
) {
1914 ERR("Trying to check for data before version check");
1916 goto end_no_session
;
1919 if (payload
->size
< sizeof(msg
)) {
1920 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1921 sizeof(msg
), payload
->size
);
1923 goto end_no_session
;
1925 memcpy(&msg
, payload
->data
, sizeof(msg
));
1926 msg
.session_id
= be64toh(msg
.session_id
);
1929 * Iterate over all streams to set the begin data pending flag.
1930 * For now, the streams are indexed by stream handle so we have
1931 * to iterate over all streams to find the one associated with
1932 * the right session_id.
1935 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1937 if (!stream_get(stream
)) {
1940 if (stream
->trace
->session
->id
== msg
.session_id
) {
1941 pthread_mutex_lock(&stream
->lock
);
1942 stream
->data_pending_check_done
= false;
1943 pthread_mutex_unlock(&stream
->lock
);
1944 DBG("Set begin data pending flag to stream %" PRIu64
,
1945 stream
->stream_handle
);
1951 memset(&reply
, 0, sizeof(reply
));
1952 /* All good, send back reply. */
1953 reply
.ret_code
= htobe32(LTTNG_OK
);
1955 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1956 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1957 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1969 * End data pending command. This will check, for a given session id, if
1970 * each stream associated with it has its data_pending_check_done flag
1971 * set. If not, this means that the client lost track of the stream but
1972 * the data is still being streamed on our side. In this case, we inform
1973 * the client that data is in flight.
1975 * Return to the client if there is data in flight or not with a ret_code.
1977 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1978 struct relay_connection
*conn
,
1979 const struct lttng_buffer_view
*payload
)
1983 struct lttng_ht_iter iter
;
1984 struct lttcomm_relayd_end_data_pending msg
;
1985 struct lttcomm_relayd_generic_reply reply
;
1986 struct relay_stream
*stream
;
1987 uint32_t is_data_inflight
= 0;
1989 DBG("End data pending command");
1991 if (!conn
->session
|| !conn
->version_check_done
) {
1992 ERR("Trying to check for data before version check");
1994 goto end_no_session
;
1997 if (payload
->size
< sizeof(msg
)) {
1998 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1999 sizeof(msg
), payload
->size
);
2001 goto end_no_session
;
2003 memcpy(&msg
, payload
->data
, sizeof(msg
));
2004 msg
.session_id
= be64toh(msg
.session_id
);
2007 * Iterate over all streams to see if the begin data pending
2011 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2013 if (!stream_get(stream
)) {
2016 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2020 pthread_mutex_lock(&stream
->lock
);
2021 if (!stream
->data_pending_check_done
) {
2022 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
2023 is_data_inflight
= 1;
2024 DBG("Data is still in flight for stream %" PRIu64
,
2025 stream
->stream_handle
);
2026 pthread_mutex_unlock(&stream
->lock
);
2031 pthread_mutex_unlock(&stream
->lock
);
2036 memset(&reply
, 0, sizeof(reply
));
2037 /* All good, send back reply. */
2038 reply
.ret_code
= htobe32(is_data_inflight
);
2040 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2041 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2042 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2054 * Receive an index for a specific stream.
2056 * Return 0 on success else a negative value.
2058 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2059 struct relay_connection
*conn
,
2060 const struct lttng_buffer_view
*payload
)
2064 struct relay_session
*session
= conn
->session
;
2065 struct lttcomm_relayd_index index_info
;
2066 struct relay_index
*index
;
2067 struct lttcomm_relayd_generic_reply reply
;
2068 struct relay_stream
*stream
;
2073 DBG("Relay receiving index");
2075 if (!session
|| !conn
->version_check_done
) {
2076 ERR("Trying to close a stream before version check");
2078 goto end_no_session
;
2081 msg_len
= lttcomm_relayd_index_len(
2082 lttng_to_index_major(conn
->major
, conn
->minor
),
2083 lttng_to_index_minor(conn
->major
, conn
->minor
));
2084 if (payload
->size
< msg_len
) {
2085 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2086 msg_len
, payload
->size
);
2088 goto end_no_session
;
2090 memcpy(&index_info
, payload
->data
, msg_len
);
2091 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2092 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2093 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2094 index_info
.content_size
= be64toh(index_info
.content_size
);
2095 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2096 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2097 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2098 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2100 if (conn
->minor
>= 8) {
2101 index_info
.stream_instance_id
=
2102 be64toh(index_info
.stream_instance_id
);
2103 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2106 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2108 ERR("stream_get_by_id not found");
2112 pthread_mutex_lock(&stream
->lock
);
2114 /* Live beacon handling */
2115 if (index_info
.packet_size
== 0) {
2116 DBG("Received live beacon for stream %" PRIu64
,
2117 stream
->stream_handle
);
2120 * Only flag a stream inactive when it has already
2121 * received data and no indexes are in flight.
2123 if (stream
->index_received_seqcount
> 0
2124 && stream
->indexes_in_flight
== 0) {
2125 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2128 goto end_stream_put
;
2130 stream
->beacon_ts_end
= -1ULL;
2133 if (stream
->ctf_stream_id
== -1ULL) {
2134 stream
->ctf_stream_id
= index_info
.stream_id
;
2136 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2139 ERR("relay_index_get_by_id_or_create index NULL");
2140 goto end_stream_put
;
2142 if (set_index_control_data(index
, &index_info
, conn
)) {
2143 ERR("set_index_control_data error");
2144 relay_index_put(index
);
2146 goto end_stream_put
;
2148 ret
= relay_index_try_flush(index
);
2150 tracefile_array_commit_seq(stream
->tfa
);
2151 stream
->index_received_seqcount
++;
2152 } else if (ret
> 0) {
2156 ERR("relay_index_try_flush error %d", ret
);
2157 relay_index_put(index
);
2162 pthread_mutex_unlock(&stream
->lock
);
2167 memset(&reply
, 0, sizeof(reply
));
2169 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2171 reply
.ret_code
= htobe32(LTTNG_OK
);
2173 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2174 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2175 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2184 * Receive the streams_sent message.
2186 * Return 0 on success else a negative value.
2188 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2189 struct relay_connection
*conn
,
2190 const struct lttng_buffer_view
*payload
)
2194 struct lttcomm_relayd_generic_reply reply
;
2198 DBG("Relay receiving streams_sent");
2200 if (!conn
->session
|| !conn
->version_check_done
) {
2201 ERR("Trying to close a stream before version check");
2203 goto end_no_session
;
2207 * Publish every pending stream in the connection recv list which are
2208 * now ready to be used by the viewer.
2210 publish_connection_local_streams(conn
);
2212 memset(&reply
, 0, sizeof(reply
));
2213 reply
.ret_code
= htobe32(LTTNG_OK
);
2214 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2215 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2216 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2228 #define DBG_CMD(cmd_name, conn) \
2229 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2231 static int relay_process_control_command(struct relay_connection
*conn
,
2232 const struct lttcomm_relayd_hdr
*header
,
2233 const struct lttng_buffer_view
*payload
)
2237 switch (header
->cmd
) {
2238 case RELAYD_CREATE_SESSION
:
2239 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2240 ret
= relay_create_session(header
, conn
, payload
);
2242 case RELAYD_ADD_STREAM
:
2243 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2244 ret
= relay_add_stream(header
, conn
, payload
);
2246 case RELAYD_START_DATA
:
2247 DBG_CMD("RELAYD_START_DATA", conn
);
2248 ret
= relay_start(header
, conn
, payload
);
2250 case RELAYD_SEND_METADATA
:
2251 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2252 ret
= relay_recv_metadata(header
, conn
, payload
);
2254 case RELAYD_VERSION
:
2255 DBG_CMD("RELAYD_VERSION", conn
);
2256 ret
= relay_send_version(header
, conn
, payload
);
2258 case RELAYD_CLOSE_STREAM
:
2259 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2260 ret
= relay_close_stream(header
, conn
, payload
);
2262 case RELAYD_DATA_PENDING
:
2263 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2264 ret
= relay_data_pending(header
, conn
, payload
);
2266 case RELAYD_QUIESCENT_CONTROL
:
2267 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2268 ret
= relay_quiescent_control(header
, conn
, payload
);
2270 case RELAYD_BEGIN_DATA_PENDING
:
2271 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2272 ret
= relay_begin_data_pending(header
, conn
, payload
);
2274 case RELAYD_END_DATA_PENDING
:
2275 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2276 ret
= relay_end_data_pending(header
, conn
, payload
);
2278 case RELAYD_SEND_INDEX
:
2279 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2280 ret
= relay_recv_index(header
, conn
, payload
);
2282 case RELAYD_STREAMS_SENT
:
2283 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2284 ret
= relay_streams_sent(header
, conn
, payload
);
2286 case RELAYD_RESET_METADATA
:
2287 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2288 ret
= relay_reset_metadata(header
, conn
, payload
);
2290 case RELAYD_UPDATE_SYNC_INFO
:
2292 ERR("Received unknown command (%u)", header
->cmd
);
2293 relay_unknown_command(conn
);
2302 static enum relay_connection_status
relay_process_control_receive_payload(
2303 struct relay_connection
*conn
)
2306 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2307 struct lttng_dynamic_buffer
*reception_buffer
=
2308 &conn
->protocol
.ctrl
.reception_buffer
;
2309 struct ctrl_connection_state_receive_payload
*state
=
2310 &conn
->protocol
.ctrl
.state
.receive_payload
;
2311 struct lttng_buffer_view payload_view
;
2313 if (state
->left_to_receive
== 0) {
2314 /* Short-circuit for payload-less commands. */
2315 goto reception_complete
;
2317 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2318 reception_buffer
->data
+ state
->received
,
2319 state
->left_to_receive
, MSG_DONTWAIT
);
2321 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2322 PERROR("Unable to receive command payload on sock %d",
2324 status
= RELAY_CONNECTION_STATUS_ERROR
;
2327 } else if (ret
== 0) {
2328 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2329 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2334 assert(ret
<= state
->left_to_receive
);
2336 state
->left_to_receive
-= ret
;
2337 state
->received
+= ret
;
2339 if (state
->left_to_receive
> 0) {
2341 * Can't transition to the protocol's next state, wait to
2342 * receive the rest of the header.
2344 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2345 state
->received
, state
->left_to_receive
,
2351 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2352 conn
->sock
->fd
, state
->received
);
2354 * The payload required to process the command has been received.
2355 * A view to the reception buffer is forwarded to the various
2356 * commands and the state of the control is reset on success.
2358 * Commands are responsible for sending their reply to the peer.
2360 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2362 ret
= relay_process_control_command(conn
,
2363 &state
->header
, &payload_view
);
2365 status
= RELAY_CONNECTION_STATUS_ERROR
;
2369 ret
= connection_reset_protocol_state(conn
);
2371 status
= RELAY_CONNECTION_STATUS_ERROR
;
2377 static enum relay_connection_status
relay_process_control_receive_header(
2378 struct relay_connection
*conn
)
2381 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2382 struct lttcomm_relayd_hdr header
;
2383 struct lttng_dynamic_buffer
*reception_buffer
=
2384 &conn
->protocol
.ctrl
.reception_buffer
;
2385 struct ctrl_connection_state_receive_header
*state
=
2386 &conn
->protocol
.ctrl
.state
.receive_header
;
2388 assert(state
->left_to_receive
!= 0);
2390 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2391 reception_buffer
->data
+ state
->received
,
2392 state
->left_to_receive
, MSG_DONTWAIT
);
2394 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2395 PERROR("Unable to receive control command header on sock %d",
2397 status
= RELAY_CONNECTION_STATUS_ERROR
;
2400 } else if (ret
== 0) {
2401 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2402 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2407 assert(ret
<= state
->left_to_receive
);
2409 state
->left_to_receive
-= ret
;
2410 state
->received
+= ret
;
2412 if (state
->left_to_receive
> 0) {
2414 * Can't transition to the protocol's next state, wait to
2415 * receive the rest of the header.
2417 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2418 state
->received
, state
->left_to_receive
,
2423 /* Transition to next state: receiving the command's payload. */
2424 conn
->protocol
.ctrl
.state_id
=
2425 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2426 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2427 header
.circuit_id
= be64toh(header
.circuit_id
);
2428 header
.data_size
= be64toh(header
.data_size
);
2429 header
.cmd
= be32toh(header
.cmd
);
2430 header
.cmd_version
= be32toh(header
.cmd_version
);
2431 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2432 &header
, sizeof(header
));
2434 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2435 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2438 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2439 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2441 status
= RELAY_CONNECTION_STATUS_ERROR
;
2445 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2447 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2448 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2451 status
= RELAY_CONNECTION_STATUS_ERROR
;
2455 if (header
.data_size
== 0) {
2457 * Manually invoke the next state as the poll loop
2458 * will not wake-up to allow us to proceed further.
2460 status
= relay_process_control_receive_payload(conn
);
2467 * Process the commands received on the control socket
2469 static enum relay_connection_status
relay_process_control(
2470 struct relay_connection
*conn
)
2472 enum relay_connection_status status
;
2474 switch (conn
->protocol
.ctrl
.state_id
) {
2475 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2476 status
= relay_process_control_receive_header(conn
);
2478 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2479 status
= relay_process_control_receive_payload(conn
);
2482 ERR("Unknown control connection protocol state encountered.");
2490 * Handle index for a data stream.
2492 * Called with the stream lock held.
2494 * Return 0 on success else a negative value.
2496 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2500 uint64_t data_offset
;
2501 struct relay_index
*index
;
2503 /* Get data offset because we are about to update the index. */
2504 data_offset
= htobe64(stream
->tracefile_size_current
);
2506 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2507 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2510 * Lookup for an existing index for that stream id/sequence
2511 * number. If it exists, the control thread has already received the
2512 * data for it, thus we need to write it to disk.
2514 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2520 if (rotate_index
|| !stream
->index_file
) {
2521 uint32_t major
, minor
;
2523 /* Put ref on previous index_file. */
2524 if (stream
->index_file
) {
2525 lttng_index_file_put(stream
->index_file
);
2526 stream
->index_file
= NULL
;
2528 major
= stream
->trace
->session
->major
;
2529 minor
= stream
->trace
->session
->minor
;
2530 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2531 stream
->channel_name
,
2532 -1, -1, stream
->tracefile_size
,
2533 tracefile_array_get_file_index_head(stream
->tfa
),
2534 lttng_to_index_major(major
, minor
),
2535 lttng_to_index_minor(major
, minor
));
2536 if (!stream
->index_file
) {
2538 /* Put self-ref for this index due to error. */
2539 relay_index_put(index
);
2545 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2547 /* Put self-ref for this index due to error. */
2548 relay_index_put(index
);
2553 ret
= relay_index_try_flush(index
);
2555 tracefile_array_commit_seq(stream
->tfa
);
2556 stream
->index_received_seqcount
++;
2557 } else if (ret
> 0) {
2561 /* Put self-ref for this index due to error. */
2562 relay_index_put(index
);
2570 static enum relay_connection_status
relay_process_data_receive_header(
2571 struct relay_connection
*conn
)
2574 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2575 struct data_connection_state_receive_header
*state
=
2576 &conn
->protocol
.data
.state
.receive_header
;
2577 struct lttcomm_relayd_data_hdr header
;
2578 struct relay_stream
*stream
;
2580 assert(state
->left_to_receive
!= 0);
2582 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2583 state
->header_reception_buffer
+ state
->received
,
2584 state
->left_to_receive
, MSG_DONTWAIT
);
2586 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2587 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2588 status
= RELAY_CONNECTION_STATUS_ERROR
;
2591 } else if (ret
== 0) {
2592 /* Orderly shutdown. Not necessary to print an error. */
2593 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2594 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2599 assert(ret
<= state
->left_to_receive
);
2601 state
->left_to_receive
-= ret
;
2602 state
->received
+= ret
;
2604 if (state
->left_to_receive
> 0) {
2606 * Can't transition to the protocol's next state, wait to
2607 * receive the rest of the header.
2609 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2610 state
->received
, state
->left_to_receive
,
2616 /* Transition to next state: receiving the payload. */
2617 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2619 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2620 header
.circuit_id
= be64toh(header
.circuit_id
);
2621 header
.stream_id
= be64toh(header
.stream_id
);
2622 header
.data_size
= be32toh(header
.data_size
);
2623 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2624 header
.padding_size
= be32toh(header
.padding_size
);
2625 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2627 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2629 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2630 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2632 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2633 conn
->sock
->fd
, header
.circuit_id
,
2634 header
.stream_id
, header
.data_size
,
2635 header
.net_seq_num
, header
.padding_size
);
2637 stream
= stream_get_by_id(header
.stream_id
);
2639 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2641 /* Protocol error. */
2642 status
= RELAY_CONNECTION_STATUS_ERROR
;
2646 pthread_mutex_lock(&stream
->lock
);
2648 /* Check if a rotation is needed. */
2649 if (stream
->tracefile_size
> 0 &&
2650 (stream
->tracefile_size_current
+ header
.data_size
) >
2651 stream
->tracefile_size
) {
2652 uint64_t old_id
, new_id
;
2654 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2655 tracefile_array_file_rotate(stream
->tfa
);
2657 /* new_id is updated by utils_rotate_stream_file. */
2660 ret
= utils_rotate_stream_file(stream
->path_name
,
2661 stream
->channel_name
, stream
->tracefile_size
,
2662 stream
->tracefile_count
, -1,
2663 -1, stream
->stream_fd
->fd
,
2664 &new_id
, &stream
->stream_fd
->fd
);
2666 ERR("Failed to rotate stream output file");
2667 status
= RELAY_CONNECTION_STATUS_ERROR
;
2668 goto end_stream_unlock
;
2672 * Reset current size because we just performed a stream
2675 stream
->tracefile_size_current
= 0;
2676 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2681 pthread_mutex_unlock(&stream
->lock
);
2687 static enum relay_connection_status
relay_process_data_receive_payload(
2688 struct relay_connection
*conn
)
2691 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2692 struct relay_stream
*stream
;
2693 struct data_connection_state_receive_payload
*state
=
2694 &conn
->protocol
.data
.state
.receive_payload
;
2695 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2696 char data_buffer
[chunk_size
];
2697 bool partial_recv
= false;
2698 bool new_stream
= false, close_requested
= false;
2699 uint64_t left_to_receive
= state
->left_to_receive
;
2700 struct relay_session
*session
;
2702 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2703 state
->header
.stream_id
, state
->header
.net_seq_num
,
2704 state
->received
, left_to_receive
);
2706 stream
= stream_get_by_id(state
->header
.stream_id
);
2708 /* Protocol error. */
2709 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2710 state
->header
.stream_id
);
2711 status
= RELAY_CONNECTION_STATUS_ERROR
;
2715 pthread_mutex_lock(&stream
->lock
);
2716 session
= stream
->trace
->session
;
2717 if (!conn
->session
) {
2718 ret
= connection_set_session(conn
, session
);
2720 status
= RELAY_CONNECTION_STATUS_ERROR
;
2721 goto end_stream_unlock
;
2726 * The size of the "chunk" received on any iteration is bounded by:
2727 * - the data left to receive,
2728 * - the data immediately available on the socket,
2729 * - the on-stack data buffer
2731 while (left_to_receive
> 0 && !partial_recv
) {
2733 size_t recv_size
= min(left_to_receive
, chunk_size
);
2735 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2736 recv_size
, MSG_DONTWAIT
);
2738 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2739 PERROR("Socket %d error", conn
->sock
->fd
);
2740 status
= RELAY_CONNECTION_STATUS_ERROR
;
2742 goto end_stream_unlock
;
2743 } else if (ret
== 0) {
2744 /* No more data ready to be consumed on socket. */
2745 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2746 state
->header
.stream_id
);
2747 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2749 } else if (ret
< (int) recv_size
) {
2751 * All the data available on the socket has been
2754 partial_recv
= true;
2759 /* Write data to stream output fd. */
2760 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2762 if (write_ret
< (ssize_t
) recv_size
) {
2763 ERR("Relay error writing data to file");
2764 status
= RELAY_CONNECTION_STATUS_ERROR
;
2765 goto end_stream_unlock
;
2768 left_to_receive
-= recv_size
;
2769 state
->received
+= recv_size
;
2770 state
->left_to_receive
= left_to_receive
;
2772 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2773 write_ret
, stream
->stream_handle
);
2776 if (state
->left_to_receive
> 0) {
2778 * Did not receive all the data expected, wait for more data to
2779 * become available on the socket.
2781 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2782 state
->header
.stream_id
, state
->received
,
2783 state
->left_to_receive
);
2784 goto end_stream_unlock
;
2787 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2788 state
->header
.padding_size
);
2789 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2790 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2791 stream
->stream_handle
,
2792 state
->header
.net_seq_num
, ret
);
2793 status
= RELAY_CONNECTION_STATUS_ERROR
;
2794 goto end_stream_unlock
;
2798 if (session
->minor
>= 4 && !session
->snapshot
) {
2799 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2800 state
->rotate_index
);
2802 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2803 stream
->stream_handle
,
2804 state
->header
.net_seq_num
, ret
);
2805 status
= RELAY_CONNECTION_STATUS_ERROR
;
2806 goto end_stream_unlock
;
2810 stream
->tracefile_size_current
+= state
->header
.data_size
+
2811 state
->header
.padding_size
;
2813 if (stream
->prev_seq
== -1ULL) {
2817 stream
->prev_seq
= state
->header
.net_seq_num
;
2820 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2821 * contents of *state which are aliased (union) to the same location as
2822 * the new state. Don't use it beyond this point.
2824 connection_reset_protocol_state(conn
);
2828 close_requested
= stream
->close_requested
;
2829 pthread_mutex_unlock(&stream
->lock
);
2830 if (close_requested
&& left_to_receive
== 0) {
2831 try_stream_close(stream
);
2835 pthread_mutex_lock(&session
->lock
);
2836 uatomic_set(&session
->new_streams
, 1);
2837 pthread_mutex_unlock(&session
->lock
);
2846 * relay_process_data: Process the data received on the data socket
2848 static enum relay_connection_status
relay_process_data(
2849 struct relay_connection
*conn
)
2851 enum relay_connection_status status
;
2853 switch (conn
->protocol
.data
.state_id
) {
2854 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2855 status
= relay_process_data_receive_header(conn
);
2857 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2858 status
= relay_process_data_receive_payload(conn
);
2861 ERR("Unexpected data connection communication state.");
2868 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2872 (void) lttng_poll_del(events
, pollfd
);
2874 ret
= close(pollfd
);
2876 ERR("Closing pollfd %d", pollfd
);
2880 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2881 int pollfd
, struct relay_connection
*conn
)
2883 const char *type_str
;
2885 switch (conn
->type
) {
2890 type_str
= "Control";
2892 case RELAY_VIEWER_COMMAND
:
2893 type_str
= "Viewer Command";
2895 case RELAY_VIEWER_NOTIFICATION
:
2896 type_str
= "Viewer Notification";
2899 type_str
= "Unknown";
2901 cleanup_connection_pollfd(events
, pollfd
);
2902 connection_put(conn
);
2903 DBG("%s connection closed with %d", type_str
, pollfd
);
2907 * This thread does the actual work
2909 static void *relay_thread_worker(void *data
)
2911 int ret
, err
= -1, last_seen_data_fd
= -1;
2913 struct lttng_poll_event events
;
2914 struct lttng_ht
*relay_connections_ht
;
2915 struct lttng_ht_iter iter
;
2916 struct relay_connection
*destroy_conn
= NULL
;
2918 DBG("[thread] Relay worker started");
2920 rcu_register_thread();
2922 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2924 if (testpoint(relayd_thread_worker
)) {
2925 goto error_testpoint
;
2928 health_code_update();
2930 /* table of connections indexed on socket */
2931 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2932 if (!relay_connections_ht
) {
2933 goto relay_connections_ht_error
;
2936 ret
= create_thread_poll_set(&events
, 2);
2938 goto error_poll_create
;
2941 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2948 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2950 health_code_update();
2952 /* Infinite blocking call, waiting for transmission */
2953 DBG3("Relayd worker thread polling...");
2954 health_poll_entry();
2955 ret
= lttng_poll_wait(&events
, -1);
2959 * Restart interrupted system call.
2961 if (errno
== EINTR
) {
2970 * Process control. The control connection is
2971 * prioritized so we don't starve it with high
2972 * throughput tracing data on the data connection.
2974 for (i
= 0; i
< nb_fd
; i
++) {
2975 /* Fetch once the poll data */
2976 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2977 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2979 health_code_update();
2983 * No activity for this FD (poll
2989 /* Thread quit pipe has been closed. Killing thread. */
2990 ret
= check_thread_quit_pipe(pollfd
, revents
);
2996 /* Inspect the relay conn pipe for new connection */
2997 if (pollfd
== relay_conn_pipe
[0]) {
2998 if (revents
& LPOLLIN
) {
2999 struct relay_connection
*conn
;
3001 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3005 lttng_poll_add(&events
, conn
->sock
->fd
,
3006 LPOLLIN
| LPOLLRDHUP
);
3007 connection_ht_add(relay_connections_ht
, conn
);
3008 DBG("Connection socket %d added", conn
->sock
->fd
);
3009 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3010 ERR("Relay connection pipe error");
3013 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3017 struct relay_connection
*ctrl_conn
;
3019 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3020 /* If not found, there is a synchronization issue. */
3023 if (ctrl_conn
->type
== RELAY_DATA
) {
3024 if (revents
& LPOLLIN
) {
3026 * Flag the last seen data fd not deleted. It will be
3027 * used as the last seen fd if any fd gets deleted in
3030 last_notdel_data_fd
= pollfd
;
3032 goto put_ctrl_connection
;
3034 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3036 if (revents
& LPOLLIN
) {
3037 enum relay_connection_status status
;
3039 status
= relay_process_control(ctrl_conn
);
3040 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3042 * On socket error flag the session as aborted to force
3043 * the cleanup of its stream otherwise it can leak
3044 * during the lifetime of the relayd.
3046 * This prevents situations in which streams can be
3047 * left opened because an index was received, the
3048 * control connection is closed, and the data
3049 * connection is closed (uncleanly) before the packet's
3052 * Since the control connection encountered an error,
3053 * it is okay to be conservative and close the
3054 * session right now as we can't rely on the protocol
3055 * being respected anymore.
3057 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3058 session_abort(ctrl_conn
->session
);
3061 /* Clear the connection on error or close. */
3062 relay_thread_close_connection(&events
,
3067 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3068 relay_thread_close_connection(&events
,
3070 if (last_seen_data_fd
== pollfd
) {
3071 last_seen_data_fd
= last_notdel_data_fd
;
3074 ERR("Unexpected poll events %u for control sock %d",
3076 connection_put(ctrl_conn
);
3079 put_ctrl_connection
:
3080 connection_put(ctrl_conn
);
3085 * The last loop handled a control request, go back to poll to make
3086 * sure we prioritise the control socket.
3092 if (last_seen_data_fd
>= 0) {
3093 for (i
= 0; i
< nb_fd
; i
++) {
3094 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3096 health_code_update();
3098 if (last_seen_data_fd
== pollfd
) {
3105 /* Process data connection. */
3106 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3107 /* Fetch the poll data. */
3108 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3109 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3110 struct relay_connection
*data_conn
;
3112 health_code_update();
3115 /* No activity for this FD (poll implementation). */
3119 /* Skip the command pipe. It's handled in the first loop. */
3120 if (pollfd
== relay_conn_pipe
[0]) {
3124 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3126 /* Skip it. Might be removed before. */
3129 if (data_conn
->type
== RELAY_CONTROL
) {
3130 goto put_data_connection
;
3132 assert(data_conn
->type
== RELAY_DATA
);
3134 if (revents
& LPOLLIN
) {
3135 enum relay_connection_status status
;
3137 status
= relay_process_data(data_conn
);
3138 /* Connection closed or error. */
3139 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3141 * On socket error flag the session as aborted to force
3142 * the cleanup of its stream otherwise it can leak
3143 * during the lifetime of the relayd.
3145 * This prevents situations in which streams can be
3146 * left opened because an index was received, the
3147 * control connection is closed, and the data
3148 * connection is closed (uncleanly) before the packet's
3151 * Since the data connection encountered an error,
3152 * it is okay to be conservative and close the
3153 * session right now as we can't rely on the protocol
3154 * being respected anymore.
3156 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3157 session_abort(data_conn
->session
);
3159 relay_thread_close_connection(&events
, pollfd
,
3162 * Every goto restart call sets the last seen fd where
3163 * here we don't really care since we gracefully
3164 * continue the loop after the connection is deleted.
3167 /* Keep last seen port. */
3168 last_seen_data_fd
= pollfd
;
3169 connection_put(data_conn
);
3172 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3173 relay_thread_close_connection(&events
, pollfd
,
3176 ERR("Unknown poll events %u for data sock %d",
3179 put_data_connection
:
3180 connection_put(data_conn
);
3182 last_seen_data_fd
= -1;
3185 /* Normal exit, no error */
3190 /* Cleanup reamaining connection object. */
3192 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3195 health_code_update();
3197 session_abort(destroy_conn
->session
);
3200 * No need to grab another ref, because we own
3203 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3208 lttng_poll_clean(&events
);
3210 lttng_ht_destroy(relay_connections_ht
);
3211 relay_connections_ht_error
:
3212 /* Close relay conn pipes */
3213 (void) fd_tracker_util_pipe_close(the_fd_tracker
,
3216 DBG("Thread exited with error");
3218 DBG("Worker thread cleanup complete");
3222 ERR("Health error occurred in %s", __func__
);
3224 health_unregister(health_relayd
);
3225 rcu_unregister_thread();
3226 lttng_relay_stop_threads();
3231 * Create the relay command pipe to wake thread_manage_apps.
3232 * Closed in cleanup().
3234 static int create_relay_conn_pipe(void)
3236 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
3237 "Relayd connection pipe", relay_conn_pipe
);
3243 int main(int argc
, char **argv
)
3245 int ret
= 0, retval
= 0;
3248 /* Parse environment variables */
3249 parse_env_options();
3253 * Command line arguments overwrite environment.
3256 if (set_options(argc
, argv
)) {
3261 if (set_signal_handler()) {
3266 relayd_config_log();
3268 if (opt_print_version
) {
3274 ret
= fclose(stdin
);
3276 PERROR("Failed to close stdin");
3279 /* Try to create directory if -o, --output is specified. */
3280 if (opt_output_path
) {
3281 if (*opt_output_path
!= '/') {
3282 ERR("Please specify an absolute path for -o, --output PATH");
3287 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3290 ERR("Unable to create %s", opt_output_path
);
3297 if (opt_daemon
|| opt_background
) {
3298 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3306 if (opt_working_directory
) {
3307 ret
= utils_change_working_dir(opt_working_directory
);
3309 ERR("Changing working directory");
3314 * The RCU thread registration (and use, through the fd-tracker's
3315 * creation) is done after the daemonization to allow us to not
3316 * deal with liburcu's fork() management as the call RCU needs to
3319 rcu_register_thread();
3321 the_fd_tracker
= fd_tracker_create(lttng_opt_fd_cap
);
3322 if (!the_fd_tracker
) {
3327 /* Initialize thread health monitoring */
3328 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3329 if (!health_relayd
) {
3330 PERROR("health_app_create error");
3332 goto exit_health_app_create
;
3335 /* Create thread quit pipe */
3336 if (init_thread_quit_pipe()) {
3338 goto exit_init_data
;
3341 /* Setup the thread apps communication pipe. */
3342 if (create_relay_conn_pipe()) {
3344 goto exit_init_data
;
3347 /* Init relay command queue. */
3348 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3350 /* Initialize communication library */
3352 lttcomm_inet_init();
3354 /* tables of sessions indexed by session ID */
3355 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3358 goto exit_init_data
;
3361 /* tables of streams indexed by stream ID */
3362 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3363 if (!relay_streams_ht
) {
3365 goto exit_init_data
;
3368 /* tables of streams indexed by stream ID */
3369 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3370 if (!viewer_streams_ht
) {
3372 goto exit_init_data
;
3375 ret
= utils_create_pipe(health_quit_pipe
);
3378 goto exit_health_quit_pipe
;
3381 /* Create thread to manage the client socket */
3382 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3383 thread_manage_health
, (void *) NULL
);
3386 PERROR("pthread_create health");
3388 goto exit_health_thread
;
3391 /* Setup the dispatcher thread */
3392 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3393 relay_thread_dispatcher
, (void *) NULL
);
3396 PERROR("pthread_create dispatcher");
3398 goto exit_dispatcher_thread
;
3401 /* Setup the worker thread */
3402 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3403 relay_thread_worker
, NULL
);
3406 PERROR("pthread_create worker");
3408 goto exit_worker_thread
;
3411 /* Setup the listener thread */
3412 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3413 relay_thread_listener
, (void *) NULL
);
3416 PERROR("pthread_create listener");
3418 goto exit_listener_thread
;
3421 ret
= relayd_live_create(live_uri
);
3423 ERR("Starting live viewer threads");
3429 * This is where we start awaiting program completion (e.g. through
3430 * signal that asks threads to teardown).
3433 ret
= relayd_live_join();
3439 ret
= pthread_join(listener_thread
, &status
);
3442 PERROR("pthread_join listener_thread");
3446 exit_listener_thread
:
3447 ret
= pthread_join(worker_thread
, &status
);
3450 PERROR("pthread_join worker_thread");
3455 ret
= pthread_join(dispatcher_thread
, &status
);
3458 PERROR("pthread_join dispatcher_thread");
3461 exit_dispatcher_thread
:
3463 ret
= pthread_join(health_thread
, &status
);
3466 PERROR("pthread_join health_thread");
3471 utils_close_pipe(health_quit_pipe
);
3472 exit_health_quit_pipe
:
3475 health_app_destroy(health_relayd
);
3476 exit_health_app_create
:
3479 * Wait for all pending call_rcu work to complete before tearing
3480 * down data structures. call_rcu worker may be trying to
3481 * perform lookups in those structures.
3486 /* Ensure all prior call_rcu are done. */
3489 fd_tracker_destroy(the_fd_tracker
);
3490 rcu_unregister_thread();