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>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
43 #include <lttng/lttng.h>
44 #include <common/common.h>
45 #include <common/compat/poll.h>
46 #include <common/compat/socket.h>
47 #include <common/compat/endian.h>
48 #include <common/compat/getenv.h>
49 #include <common/defaults.h>
50 #include <common/daemonize.h>
51 #include <common/futex.h>
52 #include <common/sessiond-comm/sessiond-comm.h>
53 #include <common/sessiond-comm/inet.h>
54 #include <common/sessiond-comm/relayd.h>
55 #include <common/uri.h>
56 #include <common/utils.h>
57 #include <common/config/session-config.h>
58 #include <common/dynamic-buffer.h>
59 #include <common/buffer-view.h>
60 #include <urcu/rculist.h>
64 #include "ctf-trace.h"
67 #include "lttng-relayd.h"
69 #include "health-relayd.h"
70 #include "testpoint.h"
71 #include "viewer-stream.h"
74 #include "connection.h"
75 #include "tracefile-array.h"
76 #include "tcp_keep_alive.h"
78 enum relay_connection_status
{
79 RELAY_CONNECTION_STATUS_OK
,
80 /* An error occured while processing an event on the connection. */
81 RELAY_CONNECTION_STATUS_ERROR
,
82 /* Connection closed/shutdown cleanly. */
83 RELAY_CONNECTION_STATUS_CLOSED
,
86 /* command line options */
87 char *opt_output_path
, *opt_working_directory
;
88 static int opt_daemon
, opt_background
, opt_print_version
;
89 int opt_group_output_by_session
;
90 int opt_group_output_by_host
;
93 * We need to wait for listener and live listener threads, as well as
94 * health check thread, before being ready to signal readiness.
96 #define NR_LTTNG_RELAY_READY 3
97 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
99 /* Size of receive buffer. */
100 #define RECV_DATA_BUFFER_SIZE 65536
102 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
103 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
105 static struct lttng_uri
*control_uri
;
106 static struct lttng_uri
*data_uri
;
107 static struct lttng_uri
*live_uri
;
109 const char *progname
;
111 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
112 static int tracing_group_name_override
;
114 const char * const config_section_name
= "relayd";
117 * Quit pipe for all threads. This permits a single cancellation point
118 * for all threads when receiving an event on the pipe.
120 int thread_quit_pipe
[2] = { -1, -1 };
123 * This pipe is used to inform the worker thread that a command is queued and
124 * ready to be processed.
126 static int relay_conn_pipe
[2] = { -1, -1 };
128 /* Shared between threads */
129 static int dispatch_thread_exit
;
131 static pthread_t listener_thread
;
132 static pthread_t dispatcher_thread
;
133 static pthread_t worker_thread
;
134 static pthread_t health_thread
;
137 * last_relay_stream_id_lock protects last_relay_stream_id increment
138 * atomicity on 32-bit architectures.
140 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
141 static uint64_t last_relay_stream_id
;
144 * Relay command queue.
146 * The relay_thread_listener and relay_thread_dispatcher communicate with this
149 static struct relay_conn_queue relay_conn_queue
;
151 /* Global relay stream hash table. */
152 struct lttng_ht
*relay_streams_ht
;
154 /* Global relay viewer stream hash table. */
155 struct lttng_ht
*viewer_streams_ht
;
157 /* Global relay sessions hash table. */
158 struct lttng_ht
*sessions_ht
;
160 /* Relayd health monitoring */
161 struct health_app
*health_relayd
;
163 static struct option long_options
[] = {
164 { "control-port", 1, 0, 'C', },
165 { "data-port", 1, 0, 'D', },
166 { "live-port", 1, 0, 'L', },
167 { "daemonize", 0, 0, 'd', },
168 { "background", 0, 0, 'b', },
169 { "group", 1, 0, 'g', },
170 { "help", 0, 0, 'h', },
171 { "output", 1, 0, 'o', },
172 { "verbose", 0, 0, 'v', },
173 { "config", 1, 0, 'f' },
174 { "version", 0, 0, 'V' },
175 { "working-directory", 1, 0, 'w', },
176 { "group-output-by-session", 0, 0, 's', },
177 { "group-output-by-host", 0, 0, 'p', },
181 static const char *config_ignore_options
[] = { "help", "config", "version" };
183 static void print_version(void) {
184 fprintf(stdout
, "%s\n", VERSION
);
187 static void relayd_config_log(void)
189 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
190 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
191 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
192 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
193 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
195 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
196 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
201 * Take an option from the getopt output and set it in the right variable to be
204 * Return 0 on success else a negative value.
206 static int set_option(int opt
, const char *arg
, const char *optname
)
212 fprintf(stderr
, "option %s", optname
);
214 fprintf(stderr
, " with arg %s\n", arg
);
218 if (lttng_is_setuid_setgid()) {
219 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
220 "-C, --control-port");
222 ret
= uri_parse(arg
, &control_uri
);
224 ERR("Invalid control URI specified");
227 if (control_uri
->port
== 0) {
228 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
233 if (lttng_is_setuid_setgid()) {
234 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
237 ret
= uri_parse(arg
, &data_uri
);
239 ERR("Invalid data URI specified");
242 if (data_uri
->port
== 0) {
243 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
248 if (lttng_is_setuid_setgid()) {
249 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
252 ret
= uri_parse(arg
, &live_uri
);
254 ERR("Invalid live URI specified");
257 if (live_uri
->port
== 0) {
258 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
269 if (lttng_is_setuid_setgid()) {
270 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
273 tracing_group_name
= strdup(arg
);
274 if (tracing_group_name
== NULL
) {
279 tracing_group_name_override
= 1;
283 ret
= utils_show_man_page(8, "lttng-relayd");
285 ERR("Cannot view man page lttng-relayd(8)");
290 opt_print_version
= 1;
293 if (lttng_is_setuid_setgid()) {
294 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
297 ret
= asprintf(&opt_output_path
, "%s", arg
);
300 PERROR("asprintf opt_output_path");
306 if (lttng_is_setuid_setgid()) {
307 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
308 "-w, --working-directory");
310 ret
= asprintf(&opt_working_directory
, "%s", arg
);
313 PERROR("asprintf working_directory");
320 /* Verbose level can increase using multiple -v */
322 lttng_opt_verbose
= config_parse_value(arg
);
324 /* Only 3 level of verbosity (-vvv). */
325 if (lttng_opt_verbose
< 3) {
326 lttng_opt_verbose
+= 1;
331 if (opt_group_output_by_host
) {
332 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
335 opt_group_output_by_session
= 1;
338 if (opt_group_output_by_session
) {
339 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
342 opt_group_output_by_host
= 1;
345 /* Unknown option or other error.
346 * Error is printed by getopt, just return */
359 * config_entry_handler_cb used to handle options read from a config file.
360 * See config_entry_handler_cb comment in common/config/session-config.h for the
361 * return value conventions.
363 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
367 if (!entry
|| !entry
->name
|| !entry
->value
) {
372 /* Check if the option is to be ignored */
373 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
374 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
379 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
380 /* Ignore if entry name is not fully matched. */
381 if (strcmp(entry
->name
, long_options
[i
].name
)) {
386 * If the option takes no argument on the command line,
387 * we have to check if the value is "true". We support
388 * non-zero numeric values, true, on and yes.
390 if (!long_options
[i
].has_arg
) {
391 ret
= config_parse_value(entry
->value
);
394 WARN("Invalid configuration value \"%s\" for option %s",
395 entry
->value
, entry
->name
);
397 /* False, skip boolean config option. */
402 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
406 WARN("Unrecognized option \"%s\" in daemon configuration file.",
413 static void parse_env_options(void)
417 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
419 opt_working_directory
= value
;
423 static int set_options(int argc
, char **argv
)
425 int c
, ret
= 0, option_index
= 0, retval
= 0;
426 int orig_optopt
= optopt
, orig_optind
= optind
;
427 char *default_address
, *optstring
;
428 const char *config_path
= NULL
;
430 optstring
= utils_generate_optstring(long_options
,
431 sizeof(long_options
) / sizeof(struct option
));
437 /* Check for the --config option */
439 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
440 &option_index
)) != -1) {
444 } else if (c
!= 'f') {
448 if (lttng_is_setuid_setgid()) {
449 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
452 config_path
= utils_expand_path(optarg
);
454 ERR("Failed to resolve path: %s", optarg
);
459 ret
= config_get_section_entries(config_path
, config_section_name
,
460 config_entry_handler
, NULL
);
463 ERR("Invalid configuration option at line %i", ret
);
469 /* Reset getopt's global state */
470 optopt
= orig_optopt
;
471 optind
= orig_optind
;
473 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
478 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
485 /* assign default values */
486 if (control_uri
== NULL
) {
487 ret
= asprintf(&default_address
,
488 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
489 DEFAULT_NETWORK_CONTROL_PORT
);
491 PERROR("asprintf default data address");
496 ret
= uri_parse(default_address
, &control_uri
);
497 free(default_address
);
499 ERR("Invalid control URI specified");
504 if (data_uri
== NULL
) {
505 ret
= asprintf(&default_address
,
506 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
507 DEFAULT_NETWORK_DATA_PORT
);
509 PERROR("asprintf default data address");
514 ret
= uri_parse(default_address
, &data_uri
);
515 free(default_address
);
517 ERR("Invalid data URI specified");
522 if (live_uri
== NULL
) {
523 ret
= asprintf(&default_address
,
524 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
525 DEFAULT_NETWORK_VIEWER_PORT
);
527 PERROR("asprintf default viewer control address");
532 ret
= uri_parse(default_address
, &live_uri
);
533 free(default_address
);
535 ERR("Invalid viewer control URI specified");
541 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
542 /* Group by host by default */
543 opt_group_output_by_host
= 1;
551 static void print_global_objects(void)
553 rcu_register_thread();
555 print_viewer_streams();
556 print_relay_streams();
559 rcu_unregister_thread();
565 static void relayd_cleanup(void)
567 print_global_objects();
571 if (viewer_streams_ht
)
572 lttng_ht_destroy(viewer_streams_ht
);
573 if (relay_streams_ht
)
574 lttng_ht_destroy(relay_streams_ht
);
576 lttng_ht_destroy(sessions_ht
);
578 /* free the dynamically allocated opt_output_path */
579 free(opt_output_path
);
581 /* Close thread quit pipes */
582 utils_close_pipe(thread_quit_pipe
);
584 uri_free(control_uri
);
586 /* Live URI is freed in the live thread. */
588 if (tracing_group_name_override
) {
589 free((void *) tracing_group_name
);
594 * Write to writable pipe used to notify a thread.
596 static int notify_thread_pipe(int wpipe
)
600 ret
= lttng_write(wpipe
, "!", 1);
602 PERROR("write poll pipe");
610 static int notify_health_quit_pipe(int *pipe
)
614 ret
= lttng_write(pipe
[1], "4", 1);
616 PERROR("write relay health quit");
625 * Stop all relayd and relayd-live threads.
627 int lttng_relay_stop_threads(void)
631 /* Stopping all threads */
632 DBG("Terminating all threads");
633 if (notify_thread_pipe(thread_quit_pipe
[1])) {
634 ERR("write error on thread quit pipe");
638 if (notify_health_quit_pipe(health_quit_pipe
)) {
639 ERR("write error on health quit pipe");
642 /* Dispatch thread */
643 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
644 futex_nto1_wake(&relay_conn_queue
.futex
);
646 if (relayd_live_stop()) {
647 ERR("Error stopping live threads");
654 * Signal handler for the daemon
656 * Simply stop all worker threads, leaving main() return gracefully after
657 * joining all threads and calling cleanup().
659 static void sighandler(int sig
)
663 DBG("SIGINT caught");
664 if (lttng_relay_stop_threads()) {
665 ERR("Error stopping threads");
669 DBG("SIGTERM caught");
670 if (lttng_relay_stop_threads()) {
671 ERR("Error stopping threads");
675 CMM_STORE_SHARED(recv_child_signal
, 1);
683 * Setup signal handler for :
684 * SIGINT, SIGTERM, SIGPIPE
686 static int set_signal_handler(void)
692 if ((ret
= sigemptyset(&sigset
)) < 0) {
693 PERROR("sigemptyset");
700 sa
.sa_handler
= sighandler
;
701 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
706 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
711 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
716 sa
.sa_handler
= SIG_IGN
;
717 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
722 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
727 void lttng_relay_notify_ready(void)
729 /* Notify the parent of the fork() process that we are ready. */
730 if (opt_daemon
|| opt_background
) {
731 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
732 kill(child_ppid
, SIGUSR1
);
738 * Init thread quit pipe.
740 * Return -1 on error or 0 if all pipes are created.
742 static int init_thread_quit_pipe(void)
746 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
752 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
754 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
758 if (events
== NULL
|| size
== 0) {
763 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
769 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
781 * Check if the thread quit pipe was triggered.
783 * Return 1 if it was triggered else 0;
785 static int check_thread_quit_pipe(int fd
, uint32_t events
)
787 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
795 * Create and init socket from uri.
797 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
800 struct lttcomm_sock
*sock
= NULL
;
802 sock
= lttcomm_alloc_sock_from_uri(uri
);
804 ERR("Allocating socket");
808 ret
= lttcomm_create_sock(sock
);
812 DBG("Listening on sock %d", sock
->fd
);
814 ret
= sock
->ops
->bind(sock
);
819 ret
= sock
->ops
->listen(sock
, -1);
829 lttcomm_destroy_sock(sock
);
835 * This thread manages the listening for new connections on the network
837 static void *relay_thread_listener(void *data
)
839 int i
, ret
, pollfd
, err
= -1;
840 uint32_t revents
, nb_fd
;
841 struct lttng_poll_event events
;
842 struct lttcomm_sock
*control_sock
, *data_sock
;
844 DBG("[thread] Relay listener started");
846 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
848 health_code_update();
850 control_sock
= relay_socket_create(control_uri
);
852 goto error_sock_control
;
855 data_sock
= relay_socket_create(data_uri
);
857 goto error_sock_relay
;
861 * Pass 3 as size here for the thread quit pipe, control and
864 ret
= create_thread_poll_set(&events
, 3);
866 goto error_create_poll
;
869 /* Add the control socket */
870 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
875 /* Add the data socket */
876 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
881 lttng_relay_notify_ready();
883 if (testpoint(relayd_thread_listener
)) {
884 goto error_testpoint
;
888 health_code_update();
890 DBG("Listener accepting connections");
894 ret
= lttng_poll_wait(&events
, -1);
898 * Restart interrupted system call.
900 if (errno
== EINTR
) {
908 DBG("Relay new connection received");
909 for (i
= 0; i
< nb_fd
; i
++) {
910 health_code_update();
912 /* Fetch once the poll data */
913 revents
= LTTNG_POLL_GETEV(&events
, i
);
914 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
918 * No activity for this FD (poll
924 /* Thread quit pipe has been closed. Killing thread. */
925 ret
= check_thread_quit_pipe(pollfd
, revents
);
931 if (revents
& LPOLLIN
) {
933 * A new connection is requested, therefore a
934 * sessiond/consumerd connection is allocated in
935 * this thread, enqueued to a global queue and
936 * dequeued (and freed) in the worker thread.
939 struct relay_connection
*new_conn
;
940 struct lttcomm_sock
*newsock
;
941 enum connection_type type
;
943 if (pollfd
== data_sock
->fd
) {
945 newsock
= data_sock
->ops
->accept(data_sock
);
946 DBG("Relay data connection accepted, socket %d",
949 assert(pollfd
== control_sock
->fd
);
950 type
= RELAY_CONTROL
;
951 newsock
= control_sock
->ops
->accept(control_sock
);
952 DBG("Relay control connection accepted, socket %d",
956 PERROR("accepting sock");
960 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
963 PERROR("setsockopt inet");
964 lttcomm_destroy_sock(newsock
);
968 ret
= socket_apply_keep_alive_config(newsock
->fd
);
970 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
972 lttcomm_destroy_sock(newsock
);
976 new_conn
= connection_create(newsock
, type
);
978 lttcomm_destroy_sock(newsock
);
982 /* Enqueue request for the dispatcher thread. */
983 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
987 * Wake the dispatch queue futex.
988 * Implicit memory barrier with the
989 * exchange in cds_wfcq_enqueue.
991 futex_nto1_wake(&relay_conn_queue
.futex
);
992 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
993 ERR("socket poll error");
996 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1006 lttng_poll_clean(&events
);
1008 if (data_sock
->fd
>= 0) {
1009 ret
= data_sock
->ops
->close(data_sock
);
1014 lttcomm_destroy_sock(data_sock
);
1016 if (control_sock
->fd
>= 0) {
1017 ret
= control_sock
->ops
->close(control_sock
);
1022 lttcomm_destroy_sock(control_sock
);
1026 ERR("Health error occurred in %s", __func__
);
1028 health_unregister(health_relayd
);
1029 DBG("Relay listener thread cleanup complete");
1030 lttng_relay_stop_threads();
1035 * This thread manages the dispatching of the requests to worker threads
1037 static void *relay_thread_dispatcher(void *data
)
1041 struct cds_wfcq_node
*node
;
1042 struct relay_connection
*new_conn
= NULL
;
1044 DBG("[thread] Relay dispatcher started");
1046 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1048 if (testpoint(relayd_thread_dispatcher
)) {
1049 goto error_testpoint
;
1052 health_code_update();
1055 health_code_update();
1057 /* Atomically prepare the queue futex */
1058 futex_nto1_prepare(&relay_conn_queue
.futex
);
1060 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1065 health_code_update();
1067 /* Dequeue commands */
1068 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1069 &relay_conn_queue
.tail
);
1071 DBG("Woken up but nothing in the relay command queue");
1072 /* Continue thread execution */
1075 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1077 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1080 * Inform worker thread of the new request. This
1081 * call is blocking so we can be assured that
1082 * the data will be read at some point in time
1083 * or wait to the end of the world :)
1085 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1087 PERROR("write connection pipe");
1088 connection_put(new_conn
);
1091 } while (node
!= NULL
);
1093 /* Futex wait on queue. Blocking call on futex() */
1094 health_poll_entry();
1095 futex_nto1_wait(&relay_conn_queue
.futex
);
1099 /* Normal exit, no error */
1106 ERR("Health error occurred in %s", __func__
);
1108 health_unregister(health_relayd
);
1109 DBG("Dispatch thread dying");
1110 lttng_relay_stop_threads();
1115 * Set index data from the control port to a given index object.
1117 static int set_index_control_data(struct relay_index
*index
,
1118 struct lttcomm_relayd_index
*data
,
1119 struct relay_connection
*conn
)
1121 struct ctf_packet_index index_data
;
1124 * The index on disk is encoded in big endian.
1126 index_data
.packet_size
= htobe64(data
->packet_size
);
1127 index_data
.content_size
= htobe64(data
->content_size
);
1128 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1129 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1130 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1131 index_data
.stream_id
= htobe64(data
->stream_id
);
1133 if (conn
->minor
>= 8) {
1134 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1135 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1138 return relay_index_set_data(index
, &index_data
);
1142 * Handle the RELAYD_CREATE_SESSION command.
1144 * On success, send back the session id or else return a negative value.
1146 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1147 struct relay_connection
*conn
,
1148 const struct lttng_buffer_view
*payload
)
1152 struct relay_session
*session
;
1153 struct lttcomm_relayd_status_session reply
;
1154 char session_name
[LTTNG_NAME_MAX
];
1155 char hostname
[LTTNG_HOST_NAME_MAX
];
1156 uint32_t live_timer
= 0;
1157 bool snapshot
= false;
1159 memset(session_name
, 0, LTTNG_NAME_MAX
);
1160 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1162 memset(&reply
, 0, sizeof(reply
));
1164 switch (conn
->minor
) {
1169 case 4: /* LTTng sessiond 2.4 */
1171 ret
= cmd_create_session_2_4(payload
, session_name
,
1172 hostname
, &live_timer
, &snapshot
);
1178 session
= session_create(session_name
, hostname
, live_timer
,
1179 snapshot
, conn
->major
, conn
->minor
);
1184 assert(!conn
->session
);
1185 conn
->session
= session
;
1186 DBG("Created session %" PRIu64
, session
->id
);
1188 reply
.session_id
= htobe64(session
->id
);
1192 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1194 reply
.ret_code
= htobe32(LTTNG_OK
);
1197 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1198 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1199 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1208 * When we have received all the streams and the metadata for a channel,
1209 * we make them visible to the viewer threads.
1211 static void publish_connection_local_streams(struct relay_connection
*conn
)
1213 struct relay_stream
*stream
;
1214 struct relay_session
*session
= conn
->session
;
1217 * We publish all streams belonging to a session atomically wrt
1220 pthread_mutex_lock(&session
->lock
);
1222 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1224 stream_publish(stream
);
1229 * Inform the viewer that there are new streams in the session.
1231 if (session
->viewer_attached
) {
1232 uatomic_set(&session
->new_streams
, 1);
1234 pthread_mutex_unlock(&session
->lock
);
1238 * relay_add_stream: allocate a new stream for a session
1240 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1241 struct relay_connection
*conn
,
1242 const struct lttng_buffer_view
*payload
)
1246 struct relay_session
*session
= conn
->session
;
1247 struct relay_stream
*stream
= NULL
;
1248 struct lttcomm_relayd_status_stream reply
;
1249 struct ctf_trace
*trace
= NULL
;
1250 uint64_t stream_handle
= -1ULL;
1251 char *path_name
= NULL
, *channel_name
= NULL
;
1252 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1254 if (!session
|| !conn
->version_check_done
) {
1255 ERR("Trying to add a stream before version check");
1257 goto end_no_session
;
1260 switch (session
->minor
) {
1261 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1262 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1263 &channel_name
, session
);
1265 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1267 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1268 &channel_name
, &tracefile_size
, &tracefile_count
,
1276 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1280 /* This stream here has one reference on the trace. */
1282 pthread_mutex_lock(&last_relay_stream_id_lock
);
1283 stream_handle
= ++last_relay_stream_id
;
1284 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1286 /* We pass ownership of path_name and channel_name. */
1287 stream
= stream_create(trace
, stream_handle
, path_name
,
1288 channel_name
, tracefile_size
, tracefile_count
);
1290 channel_name
= NULL
;
1293 * Streams are the owners of their trace. Reference to trace is
1294 * kept within stream_create().
1296 ctf_trace_put(trace
);
1299 memset(&reply
, 0, sizeof(reply
));
1300 reply
.handle
= htobe64(stream_handle
);
1302 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1304 reply
.ret_code
= htobe32(LTTNG_OK
);
1307 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1308 sizeof(struct lttcomm_relayd_status_stream
), 0);
1309 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1310 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1322 * relay_close_stream: close a specific stream
1324 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1325 struct relay_connection
*conn
,
1326 const struct lttng_buffer_view
*payload
)
1330 struct relay_session
*session
= conn
->session
;
1331 struct lttcomm_relayd_close_stream stream_info
;
1332 struct lttcomm_relayd_generic_reply reply
;
1333 struct relay_stream
*stream
;
1335 DBG("Close stream received");
1337 if (!session
|| !conn
->version_check_done
) {
1338 ERR("Trying to close a stream before version check");
1340 goto end_no_session
;
1343 if (payload
->size
< sizeof(stream_info
)) {
1344 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1345 sizeof(stream_info
), payload
->size
);
1347 goto end_no_session
;
1349 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1350 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1351 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1353 stream
= stream_get_by_id(stream_info
.stream_id
);
1360 * Set last_net_seq_num before the close flag. Required by data
1363 pthread_mutex_lock(&stream
->lock
);
1364 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1365 pthread_mutex_unlock(&stream
->lock
);
1368 * This is one of the conditions which may trigger a stream close
1369 * with the others being:
1370 * 1) A close command is received for a stream
1371 * 2) The control connection owning the stream is closed
1372 * 3) We have received all of the stream's data _after_ a close
1375 try_stream_close(stream
);
1376 if (stream
->is_metadata
) {
1377 struct relay_viewer_stream
*vstream
;
1379 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1381 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1383 * Since all the metadata has been sent to the
1384 * viewer and that we have a request to close
1385 * its stream, we can safely teardown the
1386 * corresponding metadata viewer stream.
1388 viewer_stream_put(vstream
);
1390 /* Put local reference. */
1391 viewer_stream_put(vstream
);
1398 memset(&reply
, 0, sizeof(reply
));
1400 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1402 reply
.ret_code
= htobe32(LTTNG_OK
);
1404 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1405 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1406 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1407 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1417 * relay_reset_metadata: reset a metadata stream
1420 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1421 struct relay_connection
*conn
,
1422 const struct lttng_buffer_view
*payload
)
1426 struct relay_session
*session
= conn
->session
;
1427 struct lttcomm_relayd_reset_metadata stream_info
;
1428 struct lttcomm_relayd_generic_reply reply
;
1429 struct relay_stream
*stream
;
1431 DBG("Reset metadata received");
1433 if (!session
|| !conn
->version_check_done
) {
1434 ERR("Trying to reset a metadata stream before version check");
1436 goto end_no_session
;
1439 if (payload
->size
< sizeof(stream_info
)) {
1440 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1441 sizeof(stream_info
), payload
->size
);
1443 goto end_no_session
;
1445 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1446 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1447 stream_info
.version
= be64toh(stream_info
.version
);
1449 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1451 /* Unsupported for live sessions for now. */
1452 if (session
->live_timer
!= 0) {
1457 stream
= stream_get_by_id(stream_info
.stream_id
);
1462 pthread_mutex_lock(&stream
->lock
);
1463 if (!stream
->is_metadata
) {
1468 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1469 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1470 &stream
->stream_fd
->fd
);
1472 ERR("Failed to rotate metadata file %s of channel %s",
1473 stream
->path_name
, stream
->channel_name
);
1478 pthread_mutex_unlock(&stream
->lock
);
1482 memset(&reply
, 0, sizeof(reply
));
1484 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1486 reply
.ret_code
= htobe32(LTTNG_OK
);
1488 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1489 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1490 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1491 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1501 * relay_unknown_command: send -1 if received unknown command
1503 static void relay_unknown_command(struct relay_connection
*conn
)
1505 struct lttcomm_relayd_generic_reply reply
;
1508 memset(&reply
, 0, sizeof(reply
));
1509 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1510 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1511 if (send_ret
< sizeof(reply
)) {
1512 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1517 * relay_start: send an acknowledgment to the client to tell if we are
1518 * ready to receive data. We are ready if a session is established.
1520 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1521 struct relay_connection
*conn
,
1522 const struct lttng_buffer_view
*payload
)
1526 struct lttcomm_relayd_generic_reply reply
;
1527 struct relay_session
*session
= conn
->session
;
1530 DBG("Trying to start the streaming without a session established");
1531 ret
= htobe32(LTTNG_ERR_UNK
);
1534 memset(&reply
, 0, sizeof(reply
));
1535 reply
.ret_code
= htobe32(LTTNG_OK
);
1536 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1538 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1539 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1548 * Append padding to the file pointed by the file descriptor fd.
1550 static int write_padding_to_file(int fd
, uint32_t size
)
1559 zeros
= zmalloc(size
);
1560 if (zeros
== NULL
) {
1561 PERROR("zmalloc zeros for padding");
1566 ret
= lttng_write(fd
, zeros
, size
);
1568 PERROR("write padding to file");
1578 * relay_recv_metadata: receive the metadata for the session.
1580 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1581 struct relay_connection
*conn
,
1582 const struct lttng_buffer_view
*payload
)
1586 struct relay_session
*session
= conn
->session
;
1587 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1588 struct relay_stream
*metadata_stream
;
1589 uint64_t metadata_payload_size
;
1592 ERR("Metadata sent before version check");
1597 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1598 ERR("Incorrect data size");
1602 metadata_payload_size
= recv_hdr
->data_size
-
1603 sizeof(struct lttcomm_relayd_metadata_payload
);
1605 memcpy(&metadata_payload_header
, payload
->data
,
1606 sizeof(metadata_payload_header
));
1607 metadata_payload_header
.stream_id
= be64toh(
1608 metadata_payload_header
.stream_id
);
1609 metadata_payload_header
.padding_size
= be32toh(
1610 metadata_payload_header
.padding_size
);
1612 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1613 if (!metadata_stream
) {
1618 pthread_mutex_lock(&metadata_stream
->lock
);
1620 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1621 payload
->data
+ sizeof(metadata_payload_header
),
1622 metadata_payload_size
);
1623 if (size_ret
< metadata_payload_size
) {
1624 ERR("Relay error writing metadata on file");
1629 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1630 metadata_payload_header
.padding_size
);
1631 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1636 metadata_stream
->metadata_received
+=
1637 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1638 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1639 metadata_stream
->metadata_received
);
1642 pthread_mutex_unlock(&metadata_stream
->lock
);
1643 stream_put(metadata_stream
);
1649 * relay_send_version: send relayd version number
1651 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1652 struct relay_connection
*conn
,
1653 const struct lttng_buffer_view
*payload
)
1657 struct lttcomm_relayd_version reply
, msg
;
1658 bool compatible
= true;
1660 conn
->version_check_done
= true;
1662 /* Get version from the other side. */
1663 if (payload
->size
< sizeof(msg
)) {
1664 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1665 sizeof(msg
), payload
->size
);
1670 memcpy(&msg
, payload
->data
, sizeof(msg
));
1671 msg
.major
= be32toh(msg
.major
);
1672 msg
.minor
= be32toh(msg
.minor
);
1674 memset(&reply
, 0, sizeof(reply
));
1675 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1676 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1678 /* Major versions must be the same */
1679 if (reply
.major
!= msg
.major
) {
1680 DBG("Incompatible major versions (%u vs %u), deleting session",
1681 reply
.major
, msg
.major
);
1685 conn
->major
= reply
.major
;
1686 /* We adapt to the lowest compatible version */
1687 if (reply
.minor
<= msg
.minor
) {
1688 conn
->minor
= reply
.minor
;
1690 conn
->minor
= msg
.minor
;
1693 reply
.major
= htobe32(reply
.major
);
1694 reply
.minor
= htobe32(reply
.minor
);
1695 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1697 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1698 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1711 DBG("Version check done using protocol %u.%u", conn
->major
,
1719 * Check for data pending for a given stream id from the session daemon.
1721 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1722 struct relay_connection
*conn
,
1723 const struct lttng_buffer_view
*payload
)
1725 struct relay_session
*session
= conn
->session
;
1726 struct lttcomm_relayd_data_pending msg
;
1727 struct lttcomm_relayd_generic_reply reply
;
1728 struct relay_stream
*stream
;
1732 DBG("Data pending command received");
1734 if (!session
|| !conn
->version_check_done
) {
1735 ERR("Trying to check for data before version check");
1737 goto end_no_session
;
1740 if (payload
->size
< sizeof(msg
)) {
1741 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1742 sizeof(msg
), payload
->size
);
1744 goto end_no_session
;
1746 memcpy(&msg
, payload
->data
, sizeof(msg
));
1747 msg
.stream_id
= be64toh(msg
.stream_id
);
1748 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1750 stream
= stream_get_by_id(msg
.stream_id
);
1751 if (stream
== NULL
) {
1756 pthread_mutex_lock(&stream
->lock
);
1758 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1759 " and last_seq %" PRIu64
, msg
.stream_id
,
1760 stream
->prev_seq
, msg
.last_net_seq_num
);
1762 /* Avoid wrapping issue */
1763 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1764 /* Data has in fact been written and is NOT pending */
1767 /* Data still being streamed thus pending */
1771 stream
->data_pending_check_done
= true;
1772 pthread_mutex_unlock(&stream
->lock
);
1777 memset(&reply
, 0, sizeof(reply
));
1778 reply
.ret_code
= htobe32(ret
);
1779 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1780 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1781 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1791 * Wait for the control socket to reach a quiescent state.
1793 * Note that for now, when receiving this command from the session
1794 * daemon, this means that every subsequent commands or data received on
1795 * the control socket has been handled. So, this is why we simply return
1798 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1799 struct relay_connection
*conn
,
1800 const struct lttng_buffer_view
*payload
)
1804 struct relay_stream
*stream
;
1805 struct lttcomm_relayd_quiescent_control msg
;
1806 struct lttcomm_relayd_generic_reply reply
;
1808 DBG("Checking quiescent state on control socket");
1810 if (!conn
->session
|| !conn
->version_check_done
) {
1811 ERR("Trying to check for data before version check");
1813 goto end_no_session
;
1816 if (payload
->size
< sizeof(msg
)) {
1817 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1818 sizeof(msg
), payload
->size
);
1820 goto end_no_session
;
1822 memcpy(&msg
, payload
->data
, sizeof(msg
));
1823 msg
.stream_id
= be64toh(msg
.stream_id
);
1825 stream
= stream_get_by_id(msg
.stream_id
);
1829 pthread_mutex_lock(&stream
->lock
);
1830 stream
->data_pending_check_done
= true;
1831 pthread_mutex_unlock(&stream
->lock
);
1833 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1836 memset(&reply
, 0, sizeof(reply
));
1837 reply
.ret_code
= htobe32(LTTNG_OK
);
1838 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1839 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1840 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1852 * Initialize a data pending command. This means that a consumer is about
1853 * to ask for data pending for each stream it holds. Simply iterate over
1854 * all streams of a session and set the data_pending_check_done flag.
1856 * This command returns to the client a LTTNG_OK code.
1858 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1859 struct relay_connection
*conn
,
1860 const struct lttng_buffer_view
*payload
)
1864 struct lttng_ht_iter iter
;
1865 struct lttcomm_relayd_begin_data_pending msg
;
1866 struct lttcomm_relayd_generic_reply reply
;
1867 struct relay_stream
*stream
;
1872 DBG("Init streams for data pending");
1874 if (!conn
->session
|| !conn
->version_check_done
) {
1875 ERR("Trying to check for data before version check");
1877 goto end_no_session
;
1880 if (payload
->size
< sizeof(msg
)) {
1881 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1882 sizeof(msg
), payload
->size
);
1884 goto end_no_session
;
1886 memcpy(&msg
, payload
->data
, sizeof(msg
));
1887 msg
.session_id
= be64toh(msg
.session_id
);
1890 * Iterate over all streams to set the begin data pending flag.
1891 * For now, the streams are indexed by stream handle so we have
1892 * to iterate over all streams to find the one associated with
1893 * the right session_id.
1896 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1898 if (!stream_get(stream
)) {
1901 if (stream
->trace
->session
->id
== msg
.session_id
) {
1902 pthread_mutex_lock(&stream
->lock
);
1903 stream
->data_pending_check_done
= false;
1904 pthread_mutex_unlock(&stream
->lock
);
1905 DBG("Set begin data pending flag to stream %" PRIu64
,
1906 stream
->stream_handle
);
1912 memset(&reply
, 0, sizeof(reply
));
1913 /* All good, send back reply. */
1914 reply
.ret_code
= htobe32(LTTNG_OK
);
1916 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1917 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1918 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1930 * End data pending command. This will check, for a given session id, if
1931 * each stream associated with it has its data_pending_check_done flag
1932 * set. If not, this means that the client lost track of the stream but
1933 * the data is still being streamed on our side. In this case, we inform
1934 * the client that data is in flight.
1936 * Return to the client if there is data in flight or not with a ret_code.
1938 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1939 struct relay_connection
*conn
,
1940 const struct lttng_buffer_view
*payload
)
1944 struct lttng_ht_iter iter
;
1945 struct lttcomm_relayd_end_data_pending msg
;
1946 struct lttcomm_relayd_generic_reply reply
;
1947 struct relay_stream
*stream
;
1948 uint32_t is_data_inflight
= 0;
1950 DBG("End data pending command");
1952 if (!conn
->session
|| !conn
->version_check_done
) {
1953 ERR("Trying to check for data before version check");
1955 goto end_no_session
;
1958 if (payload
->size
< sizeof(msg
)) {
1959 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1960 sizeof(msg
), payload
->size
);
1962 goto end_no_session
;
1964 memcpy(&msg
, payload
->data
, sizeof(msg
));
1965 msg
.session_id
= be64toh(msg
.session_id
);
1968 * Iterate over all streams to see if the begin data pending
1972 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1974 if (!stream_get(stream
)) {
1977 if (stream
->trace
->session
->id
!= msg
.session_id
) {
1981 pthread_mutex_lock(&stream
->lock
);
1982 if (!stream
->data_pending_check_done
) {
1983 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1984 is_data_inflight
= 1;
1985 DBG("Data is still in flight for stream %" PRIu64
,
1986 stream
->stream_handle
);
1987 pthread_mutex_unlock(&stream
->lock
);
1992 pthread_mutex_unlock(&stream
->lock
);
1997 memset(&reply
, 0, sizeof(reply
));
1998 /* All good, send back reply. */
1999 reply
.ret_code
= htobe32(is_data_inflight
);
2001 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2002 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2003 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2015 * Receive an index for a specific stream.
2017 * Return 0 on success else a negative value.
2019 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2020 struct relay_connection
*conn
,
2021 const struct lttng_buffer_view
*payload
)
2025 struct relay_session
*session
= conn
->session
;
2026 struct lttcomm_relayd_index index_info
;
2027 struct relay_index
*index
;
2028 struct lttcomm_relayd_generic_reply reply
;
2029 struct relay_stream
*stream
;
2034 DBG("Relay receiving index");
2036 if (!session
|| !conn
->version_check_done
) {
2037 ERR("Trying to close a stream before version check");
2039 goto end_no_session
;
2042 msg_len
= lttcomm_relayd_index_len(
2043 lttng_to_index_major(conn
->major
, conn
->minor
),
2044 lttng_to_index_minor(conn
->major
, conn
->minor
));
2045 if (payload
->size
< msg_len
) {
2046 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2047 msg_len
, payload
->size
);
2049 goto end_no_session
;
2051 memcpy(&index_info
, payload
->data
, msg_len
);
2052 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2053 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2054 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2055 index_info
.content_size
= be64toh(index_info
.content_size
);
2056 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2057 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2058 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2059 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2061 if (conn
->minor
>= 8) {
2062 index_info
.stream_instance_id
=
2063 be64toh(index_info
.stream_instance_id
);
2064 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2067 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2069 ERR("stream_get_by_id not found");
2073 pthread_mutex_lock(&stream
->lock
);
2075 /* Live beacon handling */
2076 if (index_info
.packet_size
== 0) {
2077 DBG("Received live beacon for stream %" PRIu64
,
2078 stream
->stream_handle
);
2081 * Only flag a stream inactive when it has already
2082 * received data and no indexes are in flight.
2084 if (stream
->index_received_seqcount
> 0
2085 && stream
->indexes_in_flight
== 0) {
2086 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2089 goto end_stream_put
;
2091 stream
->beacon_ts_end
= -1ULL;
2094 if (stream
->ctf_stream_id
== -1ULL) {
2095 stream
->ctf_stream_id
= index_info
.stream_id
;
2097 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2100 ERR("relay_index_get_by_id_or_create index NULL");
2101 goto end_stream_put
;
2103 if (set_index_control_data(index
, &index_info
, conn
)) {
2104 ERR("set_index_control_data error");
2105 relay_index_put(index
);
2107 goto end_stream_put
;
2109 ret
= relay_index_try_flush(index
);
2111 tracefile_array_commit_seq(stream
->tfa
);
2112 stream
->index_received_seqcount
++;
2113 } else if (ret
> 0) {
2117 ERR("relay_index_try_flush error %d", ret
);
2118 relay_index_put(index
);
2123 pthread_mutex_unlock(&stream
->lock
);
2128 memset(&reply
, 0, sizeof(reply
));
2130 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2132 reply
.ret_code
= htobe32(LTTNG_OK
);
2134 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2135 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2136 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2145 * Receive the streams_sent message.
2147 * Return 0 on success else a negative value.
2149 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2150 struct relay_connection
*conn
,
2151 const struct lttng_buffer_view
*payload
)
2155 struct lttcomm_relayd_generic_reply reply
;
2159 DBG("Relay receiving streams_sent");
2161 if (!conn
->session
|| !conn
->version_check_done
) {
2162 ERR("Trying to close a stream before version check");
2164 goto end_no_session
;
2168 * Publish every pending stream in the connection recv list which are
2169 * now ready to be used by the viewer.
2171 publish_connection_local_streams(conn
);
2173 memset(&reply
, 0, sizeof(reply
));
2174 reply
.ret_code
= htobe32(LTTNG_OK
);
2175 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2176 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2177 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2189 #define DBG_CMD(cmd_name, conn) \
2190 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2192 static int relay_process_control_command(struct relay_connection
*conn
,
2193 const struct lttcomm_relayd_hdr
*header
,
2194 const struct lttng_buffer_view
*payload
)
2198 switch (header
->cmd
) {
2199 case RELAYD_CREATE_SESSION
:
2200 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2201 ret
= relay_create_session(header
, conn
, payload
);
2203 case RELAYD_ADD_STREAM
:
2204 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2205 ret
= relay_add_stream(header
, conn
, payload
);
2207 case RELAYD_START_DATA
:
2208 DBG_CMD("RELAYD_START_DATA", conn
);
2209 ret
= relay_start(header
, conn
, payload
);
2211 case RELAYD_SEND_METADATA
:
2212 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2213 ret
= relay_recv_metadata(header
, conn
, payload
);
2215 case RELAYD_VERSION
:
2216 DBG_CMD("RELAYD_VERSION", conn
);
2217 ret
= relay_send_version(header
, conn
, payload
);
2219 case RELAYD_CLOSE_STREAM
:
2220 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2221 ret
= relay_close_stream(header
, conn
, payload
);
2223 case RELAYD_DATA_PENDING
:
2224 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2225 ret
= relay_data_pending(header
, conn
, payload
);
2227 case RELAYD_QUIESCENT_CONTROL
:
2228 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2229 ret
= relay_quiescent_control(header
, conn
, payload
);
2231 case RELAYD_BEGIN_DATA_PENDING
:
2232 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2233 ret
= relay_begin_data_pending(header
, conn
, payload
);
2235 case RELAYD_END_DATA_PENDING
:
2236 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2237 ret
= relay_end_data_pending(header
, conn
, payload
);
2239 case RELAYD_SEND_INDEX
:
2240 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2241 ret
= relay_recv_index(header
, conn
, payload
);
2243 case RELAYD_STREAMS_SENT
:
2244 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2245 ret
= relay_streams_sent(header
, conn
, payload
);
2247 case RELAYD_RESET_METADATA
:
2248 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2249 ret
= relay_reset_metadata(header
, conn
, payload
);
2251 case RELAYD_UPDATE_SYNC_INFO
:
2253 ERR("Received unknown command (%u)", header
->cmd
);
2254 relay_unknown_command(conn
);
2263 static enum relay_connection_status
relay_process_control_receive_payload(
2264 struct relay_connection
*conn
)
2267 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2268 struct lttng_dynamic_buffer
*reception_buffer
=
2269 &conn
->protocol
.ctrl
.reception_buffer
;
2270 struct ctrl_connection_state_receive_payload
*state
=
2271 &conn
->protocol
.ctrl
.state
.receive_payload
;
2272 struct lttng_buffer_view payload_view
;
2274 if (state
->left_to_receive
== 0) {
2275 /* Short-circuit for payload-less commands. */
2276 goto reception_complete
;
2278 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2279 reception_buffer
->data
+ state
->received
,
2280 state
->left_to_receive
, MSG_DONTWAIT
);
2282 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2283 PERROR("Unable to receive command payload on sock %d",
2285 status
= RELAY_CONNECTION_STATUS_ERROR
;
2288 } else if (ret
== 0) {
2289 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2290 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2295 assert(ret
<= state
->left_to_receive
);
2297 state
->left_to_receive
-= ret
;
2298 state
->received
+= ret
;
2300 if (state
->left_to_receive
> 0) {
2302 * Can't transition to the protocol's next state, wait to
2303 * receive the rest of the header.
2305 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2306 state
->received
, state
->left_to_receive
,
2312 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2313 conn
->sock
->fd
, state
->received
);
2315 * The payload required to process the command has been received.
2316 * A view to the reception buffer is forwarded to the various
2317 * commands and the state of the control is reset on success.
2319 * Commands are responsible for sending their reply to the peer.
2321 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2323 ret
= relay_process_control_command(conn
,
2324 &state
->header
, &payload_view
);
2326 status
= RELAY_CONNECTION_STATUS_ERROR
;
2330 ret
= connection_reset_protocol_state(conn
);
2332 status
= RELAY_CONNECTION_STATUS_ERROR
;
2338 static enum relay_connection_status
relay_process_control_receive_header(
2339 struct relay_connection
*conn
)
2342 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2343 struct lttcomm_relayd_hdr header
;
2344 struct lttng_dynamic_buffer
*reception_buffer
=
2345 &conn
->protocol
.ctrl
.reception_buffer
;
2346 struct ctrl_connection_state_receive_header
*state
=
2347 &conn
->protocol
.ctrl
.state
.receive_header
;
2349 assert(state
->left_to_receive
!= 0);
2351 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2352 reception_buffer
->data
+ state
->received
,
2353 state
->left_to_receive
, MSG_DONTWAIT
);
2355 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2356 PERROR("Unable to receive control command header on sock %d",
2358 status
= RELAY_CONNECTION_STATUS_ERROR
;
2361 } else if (ret
== 0) {
2362 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2363 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2368 assert(ret
<= state
->left_to_receive
);
2370 state
->left_to_receive
-= ret
;
2371 state
->received
+= ret
;
2373 if (state
->left_to_receive
> 0) {
2375 * Can't transition to the protocol's next state, wait to
2376 * receive the rest of the header.
2378 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2379 state
->received
, state
->left_to_receive
,
2384 /* Transition to next state: receiving the command's payload. */
2385 conn
->protocol
.ctrl
.state_id
=
2386 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2387 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2388 header
.circuit_id
= be64toh(header
.circuit_id
);
2389 header
.data_size
= be64toh(header
.data_size
);
2390 header
.cmd
= be32toh(header
.cmd
);
2391 header
.cmd_version
= be32toh(header
.cmd_version
);
2392 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2393 &header
, sizeof(header
));
2395 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2396 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2399 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2400 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2402 status
= RELAY_CONNECTION_STATUS_ERROR
;
2406 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2408 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2409 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2412 status
= RELAY_CONNECTION_STATUS_ERROR
;
2416 if (header
.data_size
== 0) {
2418 * Manually invoke the next state as the poll loop
2419 * will not wake-up to allow us to proceed further.
2421 status
= relay_process_control_receive_payload(conn
);
2428 * Process the commands received on the control socket
2430 static enum relay_connection_status
relay_process_control(
2431 struct relay_connection
*conn
)
2433 enum relay_connection_status status
;
2435 switch (conn
->protocol
.ctrl
.state_id
) {
2436 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2437 status
= relay_process_control_receive_header(conn
);
2439 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2440 status
= relay_process_control_receive_payload(conn
);
2443 ERR("Unknown control connection protocol state encountered.");
2451 * Handle index for a data stream.
2453 * Called with the stream lock held.
2455 * Return 0 on success else a negative value.
2457 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2461 uint64_t data_offset
;
2462 struct relay_index
*index
;
2464 /* Get data offset because we are about to update the index. */
2465 data_offset
= htobe64(stream
->tracefile_size_current
);
2467 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2468 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2471 * Lookup for an existing index for that stream id/sequence
2472 * number. If it exists, the control thread has already received the
2473 * data for it, thus we need to write it to disk.
2475 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2481 if (rotate_index
|| !stream
->index_file
) {
2482 uint32_t major
, minor
;
2484 /* Put ref on previous index_file. */
2485 if (stream
->index_file
) {
2486 lttng_index_file_put(stream
->index_file
);
2487 stream
->index_file
= NULL
;
2489 major
= stream
->trace
->session
->major
;
2490 minor
= stream
->trace
->session
->minor
;
2491 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2492 stream
->channel_name
,
2493 -1, -1, stream
->tracefile_size
,
2494 tracefile_array_get_file_index_head(stream
->tfa
),
2495 lttng_to_index_major(major
, minor
),
2496 lttng_to_index_minor(major
, minor
));
2497 if (!stream
->index_file
) {
2499 /* Put self-ref for this index due to error. */
2500 relay_index_put(index
);
2506 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2508 /* Put self-ref for this index due to error. */
2509 relay_index_put(index
);
2514 ret
= relay_index_try_flush(index
);
2516 tracefile_array_commit_seq(stream
->tfa
);
2517 stream
->index_received_seqcount
++;
2518 } else if (ret
> 0) {
2522 /* Put self-ref for this index due to error. */
2523 relay_index_put(index
);
2531 static enum relay_connection_status
relay_process_data_receive_header(
2532 struct relay_connection
*conn
)
2535 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2536 struct data_connection_state_receive_header
*state
=
2537 &conn
->protocol
.data
.state
.receive_header
;
2538 struct lttcomm_relayd_data_hdr header
;
2539 struct relay_stream
*stream
;
2541 assert(state
->left_to_receive
!= 0);
2543 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2544 state
->header_reception_buffer
+ state
->received
,
2545 state
->left_to_receive
, MSG_DONTWAIT
);
2547 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2548 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2549 status
= RELAY_CONNECTION_STATUS_ERROR
;
2552 } else if (ret
== 0) {
2553 /* Orderly shutdown. Not necessary to print an error. */
2554 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2555 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2560 assert(ret
<= state
->left_to_receive
);
2562 state
->left_to_receive
-= ret
;
2563 state
->received
+= ret
;
2565 if (state
->left_to_receive
> 0) {
2567 * Can't transition to the protocol's next state, wait to
2568 * receive the rest of the header.
2570 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2571 state
->received
, state
->left_to_receive
,
2577 /* Transition to next state: receiving the payload. */
2578 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2580 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2581 header
.circuit_id
= be64toh(header
.circuit_id
);
2582 header
.stream_id
= be64toh(header
.stream_id
);
2583 header
.data_size
= be32toh(header
.data_size
);
2584 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2585 header
.padding_size
= be32toh(header
.padding_size
);
2586 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2588 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2590 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2591 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2593 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2594 conn
->sock
->fd
, header
.circuit_id
,
2595 header
.stream_id
, header
.data_size
,
2596 header
.net_seq_num
, header
.padding_size
);
2598 stream
= stream_get_by_id(header
.stream_id
);
2600 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2602 /* Protocol error. */
2603 status
= RELAY_CONNECTION_STATUS_ERROR
;
2607 pthread_mutex_lock(&stream
->lock
);
2609 /* Check if a rotation is needed. */
2610 if (stream
->tracefile_size
> 0 &&
2611 (stream
->tracefile_size_current
+ header
.data_size
) >
2612 stream
->tracefile_size
) {
2613 uint64_t old_id
, new_id
;
2615 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2616 tracefile_array_file_rotate(stream
->tfa
);
2618 /* new_id is updated by utils_rotate_stream_file. */
2621 ret
= utils_rotate_stream_file(stream
->path_name
,
2622 stream
->channel_name
, stream
->tracefile_size
,
2623 stream
->tracefile_count
, -1,
2624 -1, stream
->stream_fd
->fd
,
2625 &new_id
, &stream
->stream_fd
->fd
);
2627 ERR("Failed to rotate stream output file");
2628 status
= RELAY_CONNECTION_STATUS_ERROR
;
2629 goto end_stream_unlock
;
2633 * Reset current size because we just performed a stream
2636 stream
->tracefile_size_current
= 0;
2637 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2642 pthread_mutex_unlock(&stream
->lock
);
2648 static enum relay_connection_status
relay_process_data_receive_payload(
2649 struct relay_connection
*conn
)
2652 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2653 struct relay_stream
*stream
;
2654 struct data_connection_state_receive_payload
*state
=
2655 &conn
->protocol
.data
.state
.receive_payload
;
2656 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2657 char data_buffer
[chunk_size
];
2658 bool partial_recv
= false;
2659 bool new_stream
= false, close_requested
= false;
2660 uint64_t left_to_receive
= state
->left_to_receive
;
2661 struct relay_session
*session
;
2663 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2664 state
->header
.stream_id
, state
->header
.net_seq_num
,
2665 state
->received
, left_to_receive
);
2667 stream
= stream_get_by_id(state
->header
.stream_id
);
2669 /* Protocol error. */
2670 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2671 state
->header
.stream_id
);
2672 status
= RELAY_CONNECTION_STATUS_ERROR
;
2676 pthread_mutex_lock(&stream
->lock
);
2677 session
= stream
->trace
->session
;
2678 if (!conn
->session
) {
2679 ret
= connection_set_session(conn
, session
);
2681 status
= RELAY_CONNECTION_STATUS_ERROR
;
2682 goto end_stream_unlock
;
2687 * The size of the "chunk" received on any iteration is bounded by:
2688 * - the data left to receive,
2689 * - the data immediately available on the socket,
2690 * - the on-stack data buffer
2692 while (left_to_receive
> 0 && !partial_recv
) {
2694 size_t recv_size
= min(left_to_receive
, chunk_size
);
2696 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2697 recv_size
, MSG_DONTWAIT
);
2699 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2700 PERROR("Socket %d error", conn
->sock
->fd
);
2701 status
= RELAY_CONNECTION_STATUS_ERROR
;
2703 goto end_stream_unlock
;
2704 } else if (ret
== 0) {
2705 /* No more data ready to be consumed on socket. */
2706 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2707 state
->header
.stream_id
);
2708 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2710 } else if (ret
< (int) recv_size
) {
2712 * All the data available on the socket has been
2715 partial_recv
= true;
2720 /* Write data to stream output fd. */
2721 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2723 if (write_ret
< (ssize_t
) recv_size
) {
2724 ERR("Relay error writing data to file");
2725 status
= RELAY_CONNECTION_STATUS_ERROR
;
2726 goto end_stream_unlock
;
2729 left_to_receive
-= recv_size
;
2730 state
->received
+= recv_size
;
2731 state
->left_to_receive
= left_to_receive
;
2733 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2734 write_ret
, stream
->stream_handle
);
2737 if (state
->left_to_receive
> 0) {
2739 * Did not receive all the data expected, wait for more data to
2740 * become available on the socket.
2742 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2743 state
->header
.stream_id
, state
->received
,
2744 state
->left_to_receive
);
2745 goto end_stream_unlock
;
2748 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2749 state
->header
.padding_size
);
2750 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2751 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2752 stream
->stream_handle
,
2753 state
->header
.net_seq_num
, ret
);
2754 status
= RELAY_CONNECTION_STATUS_ERROR
;
2755 goto end_stream_unlock
;
2759 if (session
->minor
>= 4 && !session
->snapshot
) {
2760 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2761 state
->rotate_index
);
2763 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2764 stream
->stream_handle
,
2765 state
->header
.net_seq_num
, ret
);
2766 status
= RELAY_CONNECTION_STATUS_ERROR
;
2767 goto end_stream_unlock
;
2771 stream
->tracefile_size_current
+= state
->header
.data_size
+
2772 state
->header
.padding_size
;
2774 if (stream
->prev_seq
== -1ULL) {
2778 stream
->prev_seq
= state
->header
.net_seq_num
;
2781 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2782 * contents of *state which are aliased (union) to the same location as
2783 * the new state. Don't use it beyond this point.
2785 connection_reset_protocol_state(conn
);
2789 close_requested
= stream
->close_requested
;
2790 pthread_mutex_unlock(&stream
->lock
);
2791 if (close_requested
&& left_to_receive
== 0) {
2792 try_stream_close(stream
);
2796 pthread_mutex_lock(&session
->lock
);
2797 uatomic_set(&session
->new_streams
, 1);
2798 pthread_mutex_unlock(&session
->lock
);
2807 * relay_process_data: Process the data received on the data socket
2809 static enum relay_connection_status
relay_process_data(
2810 struct relay_connection
*conn
)
2812 enum relay_connection_status status
;
2814 switch (conn
->protocol
.data
.state_id
) {
2815 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2816 status
= relay_process_data_receive_header(conn
);
2818 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2819 status
= relay_process_data_receive_payload(conn
);
2822 ERR("Unexpected data connection communication state.");
2829 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2833 (void) lttng_poll_del(events
, pollfd
);
2835 ret
= close(pollfd
);
2837 ERR("Closing pollfd %d", pollfd
);
2841 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2842 int pollfd
, struct relay_connection
*conn
)
2844 const char *type_str
;
2846 switch (conn
->type
) {
2851 type_str
= "Control";
2853 case RELAY_VIEWER_COMMAND
:
2854 type_str
= "Viewer Command";
2856 case RELAY_VIEWER_NOTIFICATION
:
2857 type_str
= "Viewer Notification";
2860 type_str
= "Unknown";
2862 cleanup_connection_pollfd(events
, pollfd
);
2863 connection_put(conn
);
2864 DBG("%s connection closed with %d", type_str
, pollfd
);
2868 * This thread does the actual work
2870 static void *relay_thread_worker(void *data
)
2872 int ret
, err
= -1, last_seen_data_fd
= -1;
2874 struct lttng_poll_event events
;
2875 struct lttng_ht
*relay_connections_ht
;
2876 struct lttng_ht_iter iter
;
2877 struct relay_connection
*destroy_conn
= NULL
;
2879 DBG("[thread] Relay worker started");
2881 rcu_register_thread();
2883 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2885 if (testpoint(relayd_thread_worker
)) {
2886 goto error_testpoint
;
2889 health_code_update();
2891 /* table of connections indexed on socket */
2892 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2893 if (!relay_connections_ht
) {
2894 goto relay_connections_ht_error
;
2897 ret
= create_thread_poll_set(&events
, 2);
2899 goto error_poll_create
;
2902 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2909 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2911 health_code_update();
2913 /* Infinite blocking call, waiting for transmission */
2914 DBG3("Relayd worker thread polling...");
2915 health_poll_entry();
2916 ret
= lttng_poll_wait(&events
, -1);
2920 * Restart interrupted system call.
2922 if (errno
== EINTR
) {
2931 * Process control. The control connection is
2932 * prioritized so we don't starve it with high
2933 * throughput tracing data on the data connection.
2935 for (i
= 0; i
< nb_fd
; i
++) {
2936 /* Fetch once the poll data */
2937 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2938 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2940 health_code_update();
2944 * No activity for this FD (poll
2950 /* Thread quit pipe has been closed. Killing thread. */
2951 ret
= check_thread_quit_pipe(pollfd
, revents
);
2957 /* Inspect the relay conn pipe for new connection */
2958 if (pollfd
== relay_conn_pipe
[0]) {
2959 if (revents
& LPOLLIN
) {
2960 struct relay_connection
*conn
;
2962 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2966 lttng_poll_add(&events
, conn
->sock
->fd
,
2967 LPOLLIN
| LPOLLRDHUP
);
2968 connection_ht_add(relay_connections_ht
, conn
);
2969 DBG("Connection socket %d added", conn
->sock
->fd
);
2970 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2971 ERR("Relay connection pipe error");
2974 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2978 struct relay_connection
*ctrl_conn
;
2980 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2981 /* If not found, there is a synchronization issue. */
2984 if (ctrl_conn
->type
== RELAY_DATA
) {
2985 if (revents
& LPOLLIN
) {
2987 * Flag the last seen data fd not deleted. It will be
2988 * used as the last seen fd if any fd gets deleted in
2991 last_notdel_data_fd
= pollfd
;
2993 goto put_ctrl_connection
;
2995 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2997 if (revents
& LPOLLIN
) {
2998 enum relay_connection_status status
;
3000 status
= relay_process_control(ctrl_conn
);
3001 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3003 * On socket error flag the session as aborted to force
3004 * the cleanup of its stream otherwise it can leak
3005 * during the lifetime of the relayd.
3007 * This prevents situations in which streams can be
3008 * left opened because an index was received, the
3009 * control connection is closed, and the data
3010 * connection is closed (uncleanly) before the packet's
3013 * Since the control connection encountered an error,
3014 * it is okay to be conservative and close the
3015 * session right now as we can't rely on the protocol
3016 * being respected anymore.
3018 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3019 session_abort(ctrl_conn
->session
);
3022 /* Clear the connection on error or close. */
3023 relay_thread_close_connection(&events
,
3028 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3029 relay_thread_close_connection(&events
,
3031 if (last_seen_data_fd
== pollfd
) {
3032 last_seen_data_fd
= last_notdel_data_fd
;
3035 ERR("Unexpected poll events %u for control sock %d",
3037 connection_put(ctrl_conn
);
3040 put_ctrl_connection
:
3041 connection_put(ctrl_conn
);
3046 * The last loop handled a control request, go back to poll to make
3047 * sure we prioritise the control socket.
3053 if (last_seen_data_fd
>= 0) {
3054 for (i
= 0; i
< nb_fd
; i
++) {
3055 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3057 health_code_update();
3059 if (last_seen_data_fd
== pollfd
) {
3066 /* Process data connection. */
3067 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3068 /* Fetch the poll data. */
3069 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3070 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3071 struct relay_connection
*data_conn
;
3073 health_code_update();
3076 /* No activity for this FD (poll implementation). */
3080 /* Skip the command pipe. It's handled in the first loop. */
3081 if (pollfd
== relay_conn_pipe
[0]) {
3085 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3087 /* Skip it. Might be removed before. */
3090 if (data_conn
->type
== RELAY_CONTROL
) {
3091 goto put_data_connection
;
3093 assert(data_conn
->type
== RELAY_DATA
);
3095 if (revents
& LPOLLIN
) {
3096 enum relay_connection_status status
;
3098 status
= relay_process_data(data_conn
);
3099 /* Connection closed or error. */
3100 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3102 * On socket error flag the session as aborted to force
3103 * the cleanup of its stream otherwise it can leak
3104 * during the lifetime of the relayd.
3106 * This prevents situations in which streams can be
3107 * left opened because an index was received, the
3108 * control connection is closed, and the data
3109 * connection is closed (uncleanly) before the packet's
3112 * Since the data connection encountered an error,
3113 * it is okay to be conservative and close the
3114 * session right now as we can't rely on the protocol
3115 * being respected anymore.
3117 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3118 session_abort(data_conn
->session
);
3120 relay_thread_close_connection(&events
, pollfd
,
3123 * Every goto restart call sets the last seen fd where
3124 * here we don't really care since we gracefully
3125 * continue the loop after the connection is deleted.
3128 /* Keep last seen port. */
3129 last_seen_data_fd
= pollfd
;
3130 connection_put(data_conn
);
3133 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3134 relay_thread_close_connection(&events
, pollfd
,
3137 ERR("Unknown poll events %u for data sock %d",
3140 put_data_connection
:
3141 connection_put(data_conn
);
3143 last_seen_data_fd
= -1;
3146 /* Normal exit, no error */
3151 /* Cleanup reamaining connection object. */
3153 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3156 health_code_update();
3158 session_abort(destroy_conn
->session
);
3161 * No need to grab another ref, because we own
3164 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3169 lttng_poll_clean(&events
);
3171 lttng_ht_destroy(relay_connections_ht
);
3172 relay_connections_ht_error
:
3173 /* Close relay conn pipes */
3174 utils_close_pipe(relay_conn_pipe
);
3176 DBG("Thread exited with error");
3178 DBG("Worker thread cleanup complete");
3182 ERR("Health error occurred in %s", __func__
);
3184 health_unregister(health_relayd
);
3185 rcu_unregister_thread();
3186 lttng_relay_stop_threads();
3191 * Create the relay command pipe to wake thread_manage_apps.
3192 * Closed in cleanup().
3194 static int create_relay_conn_pipe(void)
3198 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3206 int main(int argc
, char **argv
)
3208 int ret
= 0, retval
= 0;
3211 /* Parse environment variables */
3212 parse_env_options();
3216 * Command line arguments overwrite environment.
3219 if (set_options(argc
, argv
)) {
3224 if (set_signal_handler()) {
3229 relayd_config_log();
3231 if (opt_print_version
) {
3237 /* Try to create directory if -o, --output is specified. */
3238 if (opt_output_path
) {
3239 if (*opt_output_path
!= '/') {
3240 ERR("Please specify an absolute path for -o, --output PATH");
3245 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3248 ERR("Unable to create %s", opt_output_path
);
3255 if (opt_daemon
|| opt_background
) {
3258 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3266 * We are in the child. Make sure all other file
3267 * descriptors are closed, in case we are called with
3268 * more opened file descriptors than the standard ones.
3270 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3276 if (opt_working_directory
) {
3277 ret
= utils_change_working_dir(opt_working_directory
);
3279 ERR("Changing working directory");
3284 /* Initialize thread health monitoring */
3285 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3286 if (!health_relayd
) {
3287 PERROR("health_app_create error");
3289 goto exit_health_app_create
;
3292 /* Create thread quit pipe */
3293 if (init_thread_quit_pipe()) {
3295 goto exit_init_data
;
3298 /* Setup the thread apps communication pipe. */
3299 if (create_relay_conn_pipe()) {
3301 goto exit_init_data
;
3304 /* Init relay command queue. */
3305 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3307 /* Initialize communication library */
3309 lttcomm_inet_init();
3311 /* tables of sessions indexed by session ID */
3312 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3315 goto exit_init_data
;
3318 /* tables of streams indexed by stream ID */
3319 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3320 if (!relay_streams_ht
) {
3322 goto exit_init_data
;
3325 /* tables of streams indexed by stream ID */
3326 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3327 if (!viewer_streams_ht
) {
3329 goto exit_init_data
;
3332 ret
= utils_create_pipe(health_quit_pipe
);
3335 goto exit_health_quit_pipe
;
3338 /* Create thread to manage the client socket */
3339 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3340 thread_manage_health
, (void *) NULL
);
3343 PERROR("pthread_create health");
3345 goto exit_health_thread
;
3348 /* Setup the dispatcher thread */
3349 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3350 relay_thread_dispatcher
, (void *) NULL
);
3353 PERROR("pthread_create dispatcher");
3355 goto exit_dispatcher_thread
;
3358 /* Setup the worker thread */
3359 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3360 relay_thread_worker
, NULL
);
3363 PERROR("pthread_create worker");
3365 goto exit_worker_thread
;
3368 /* Setup the listener thread */
3369 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3370 relay_thread_listener
, (void *) NULL
);
3373 PERROR("pthread_create listener");
3375 goto exit_listener_thread
;
3378 ret
= relayd_live_create(live_uri
);
3380 ERR("Starting live viewer threads");
3386 * This is where we start awaiting program completion (e.g. through
3387 * signal that asks threads to teardown).
3390 ret
= relayd_live_join();
3396 ret
= pthread_join(listener_thread
, &status
);
3399 PERROR("pthread_join listener_thread");
3403 exit_listener_thread
:
3404 ret
= pthread_join(worker_thread
, &status
);
3407 PERROR("pthread_join worker_thread");
3412 ret
= pthread_join(dispatcher_thread
, &status
);
3415 PERROR("pthread_join dispatcher_thread");
3418 exit_dispatcher_thread
:
3420 ret
= pthread_join(health_thread
, &status
);
3423 PERROR("pthread_join health_thread");
3428 utils_close_pipe(health_quit_pipe
);
3429 exit_health_quit_pipe
:
3432 health_app_destroy(health_relayd
);
3433 exit_health_app_create
:
3436 * Wait for all pending call_rcu work to complete before tearing
3437 * down data structures. call_rcu worker may be trying to
3438 * perform lookups in those structures.
3443 /* Ensure all prior call_rcu are done. */