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");
198 * Take an option from the getopt output and set it in the right variable to be
201 * Return 0 on success else a negative value.
203 static int set_option(int opt
, const char *arg
, const char *optname
)
209 fprintf(stderr
, "option %s", optname
);
211 fprintf(stderr
, " with arg %s\n", arg
);
215 if (lttng_is_setuid_setgid()) {
216 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
217 "-C, --control-port");
219 ret
= uri_parse(arg
, &control_uri
);
221 ERR("Invalid control URI specified");
224 if (control_uri
->port
== 0) {
225 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
230 if (lttng_is_setuid_setgid()) {
231 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
234 ret
= uri_parse(arg
, &data_uri
);
236 ERR("Invalid data URI specified");
239 if (data_uri
->port
== 0) {
240 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
245 if (lttng_is_setuid_setgid()) {
246 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
249 ret
= uri_parse(arg
, &live_uri
);
251 ERR("Invalid live URI specified");
254 if (live_uri
->port
== 0) {
255 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
266 if (lttng_is_setuid_setgid()) {
267 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
270 tracing_group_name
= strdup(arg
);
271 if (tracing_group_name
== NULL
) {
276 tracing_group_name_override
= 1;
280 ret
= utils_show_man_page(8, "lttng-relayd");
282 ERR("Cannot view man page lttng-relayd(8)");
287 opt_print_version
= 1;
290 if (lttng_is_setuid_setgid()) {
291 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
294 ret
= asprintf(&opt_output_path
, "%s", arg
);
297 PERROR("asprintf opt_output_path");
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
305 "-w, --working-directory");
307 ret
= asprintf(&opt_working_directory
, "%s", arg
);
310 PERROR("asprintf working_directory");
317 /* Verbose level can increase using multiple -v */
319 lttng_opt_verbose
= config_parse_value(arg
);
321 /* Only 3 level of verbosity (-vvv). */
322 if (lttng_opt_verbose
< 3) {
323 lttng_opt_verbose
+= 1;
328 if (opt_group_output_by_host
) {
329 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
332 opt_group_output_by_session
= 1;
335 if (opt_group_output_by_session
) {
336 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
339 opt_group_output_by_host
= 1;
342 /* Unknown option or other error.
343 * Error is printed by getopt, just return */
356 * config_entry_handler_cb used to handle options read from a config file.
357 * See config_entry_handler_cb comment in common/config/session-config.h for the
358 * return value conventions.
360 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
364 if (!entry
|| !entry
->name
|| !entry
->value
) {
369 /* Check if the option is to be ignored */
370 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
371 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
376 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
377 /* Ignore if entry name is not fully matched. */
378 if (strcmp(entry
->name
, long_options
[i
].name
)) {
383 * If the option takes no argument on the command line,
384 * we have to check if the value is "true". We support
385 * non-zero numeric values, true, on and yes.
387 if (!long_options
[i
].has_arg
) {
388 ret
= config_parse_value(entry
->value
);
391 WARN("Invalid configuration value \"%s\" for option %s",
392 entry
->value
, entry
->name
);
394 /* False, skip boolean config option. */
399 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
403 WARN("Unrecognized option \"%s\" in daemon configuration file.",
410 static void parse_env_options(void)
414 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
416 opt_working_directory
= value
;
420 static int set_options(int argc
, char **argv
)
422 int c
, ret
= 0, option_index
= 0, retval
= 0;
423 int orig_optopt
= optopt
, orig_optind
= optind
;
424 char *default_address
, *optstring
;
425 const char *config_path
= NULL
;
427 optstring
= utils_generate_optstring(long_options
,
428 sizeof(long_options
) / sizeof(struct option
));
434 /* Check for the --config option */
436 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
437 &option_index
)) != -1) {
441 } else if (c
!= 'f') {
445 if (lttng_is_setuid_setgid()) {
446 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
449 config_path
= utils_expand_path(optarg
);
451 ERR("Failed to resolve path: %s", optarg
);
456 ret
= config_get_section_entries(config_path
, config_section_name
,
457 config_entry_handler
, NULL
);
460 ERR("Invalid configuration option at line %i", ret
);
466 /* Reset getopt's global state */
467 optopt
= orig_optopt
;
468 optind
= orig_optind
;
470 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
475 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
482 /* assign default values */
483 if (control_uri
== NULL
) {
484 ret
= asprintf(&default_address
,
485 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
486 DEFAULT_NETWORK_CONTROL_PORT
);
488 PERROR("asprintf default data address");
493 ret
= uri_parse(default_address
, &control_uri
);
494 free(default_address
);
496 ERR("Invalid control URI specified");
501 if (data_uri
== NULL
) {
502 ret
= asprintf(&default_address
,
503 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
504 DEFAULT_NETWORK_DATA_PORT
);
506 PERROR("asprintf default data address");
511 ret
= uri_parse(default_address
, &data_uri
);
512 free(default_address
);
514 ERR("Invalid data URI specified");
519 if (live_uri
== NULL
) {
520 ret
= asprintf(&default_address
,
521 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
522 DEFAULT_NETWORK_VIEWER_PORT
);
524 PERROR("asprintf default viewer control address");
529 ret
= uri_parse(default_address
, &live_uri
);
530 free(default_address
);
532 ERR("Invalid viewer control URI specified");
538 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
539 /* Group by host by default */
540 opt_group_output_by_host
= 1;
548 static void print_global_objects(void)
550 rcu_register_thread();
552 print_viewer_streams();
553 print_relay_streams();
556 rcu_unregister_thread();
562 static void relayd_cleanup(void)
564 print_global_objects();
568 if (viewer_streams_ht
)
569 lttng_ht_destroy(viewer_streams_ht
);
570 if (relay_streams_ht
)
571 lttng_ht_destroy(relay_streams_ht
);
573 lttng_ht_destroy(sessions_ht
);
575 /* free the dynamically allocated opt_output_path */
576 free(opt_output_path
);
578 /* Close thread quit pipes */
579 utils_close_pipe(thread_quit_pipe
);
581 uri_free(control_uri
);
583 /* Live URI is freed in the live thread. */
585 if (tracing_group_name_override
) {
586 free((void *) tracing_group_name
);
591 * Write to writable pipe used to notify a thread.
593 static int notify_thread_pipe(int wpipe
)
597 ret
= lttng_write(wpipe
, "!", 1);
599 PERROR("write poll pipe");
607 static int notify_health_quit_pipe(int *pipe
)
611 ret
= lttng_write(pipe
[1], "4", 1);
613 PERROR("write relay health quit");
622 * Stop all relayd and relayd-live threads.
624 int lttng_relay_stop_threads(void)
628 /* Stopping all threads */
629 DBG("Terminating all threads");
630 if (notify_thread_pipe(thread_quit_pipe
[1])) {
631 ERR("write error on thread quit pipe");
635 if (notify_health_quit_pipe(health_quit_pipe
)) {
636 ERR("write error on health quit pipe");
639 /* Dispatch thread */
640 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
641 futex_nto1_wake(&relay_conn_queue
.futex
);
643 if (relayd_live_stop()) {
644 ERR("Error stopping live threads");
651 * Signal handler for the daemon
653 * Simply stop all worker threads, leaving main() return gracefully after
654 * joining all threads and calling cleanup().
656 static void sighandler(int sig
)
660 DBG("SIGINT caught");
661 if (lttng_relay_stop_threads()) {
662 ERR("Error stopping threads");
666 DBG("SIGTERM caught");
667 if (lttng_relay_stop_threads()) {
668 ERR("Error stopping threads");
672 CMM_STORE_SHARED(recv_child_signal
, 1);
680 * Setup signal handler for :
681 * SIGINT, SIGTERM, SIGPIPE
683 static int set_signal_handler(void)
689 if ((ret
= sigemptyset(&sigset
)) < 0) {
690 PERROR("sigemptyset");
697 sa
.sa_handler
= sighandler
;
698 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
703 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
708 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
713 sa
.sa_handler
= SIG_IGN
;
714 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
719 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
724 void lttng_relay_notify_ready(void)
726 /* Notify the parent of the fork() process that we are ready. */
727 if (opt_daemon
|| opt_background
) {
728 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
729 kill(child_ppid
, SIGUSR1
);
735 * Init thread quit pipe.
737 * Return -1 on error or 0 if all pipes are created.
739 static int init_thread_quit_pipe(void)
743 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
749 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
751 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
755 if (events
== NULL
|| size
== 0) {
760 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
766 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
778 * Check if the thread quit pipe was triggered.
780 * Return 1 if it was triggered else 0;
782 static int check_thread_quit_pipe(int fd
, uint32_t events
)
784 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
792 * Create and init socket from uri.
794 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
797 struct lttcomm_sock
*sock
= NULL
;
799 sock
= lttcomm_alloc_sock_from_uri(uri
);
801 ERR("Allocating socket");
805 ret
= lttcomm_create_sock(sock
);
809 DBG("Listening on sock %d", sock
->fd
);
811 ret
= sock
->ops
->bind(sock
);
816 ret
= sock
->ops
->listen(sock
, -1);
826 lttcomm_destroy_sock(sock
);
832 * This thread manages the listening for new connections on the network
834 static void *relay_thread_listener(void *data
)
836 int i
, ret
, pollfd
, err
= -1;
837 uint32_t revents
, nb_fd
;
838 struct lttng_poll_event events
;
839 struct lttcomm_sock
*control_sock
, *data_sock
;
841 DBG("[thread] Relay listener started");
843 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
845 health_code_update();
847 control_sock
= relay_socket_create(control_uri
);
849 goto error_sock_control
;
852 data_sock
= relay_socket_create(data_uri
);
854 goto error_sock_relay
;
858 * Pass 3 as size here for the thread quit pipe, control and
861 ret
= create_thread_poll_set(&events
, 3);
863 goto error_create_poll
;
866 /* Add the control socket */
867 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
872 /* Add the data socket */
873 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
878 lttng_relay_notify_ready();
880 if (testpoint(relayd_thread_listener
)) {
881 goto error_testpoint
;
885 health_code_update();
887 DBG("Listener accepting connections");
891 ret
= lttng_poll_wait(&events
, -1);
895 * Restart interrupted system call.
897 if (errno
== EINTR
) {
905 DBG("Relay new connection received");
906 for (i
= 0; i
< nb_fd
; i
++) {
907 health_code_update();
909 /* Fetch once the poll data */
910 revents
= LTTNG_POLL_GETEV(&events
, i
);
911 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
915 * No activity for this FD (poll
921 /* Thread quit pipe has been closed. Killing thread. */
922 ret
= check_thread_quit_pipe(pollfd
, revents
);
928 if (revents
& LPOLLIN
) {
930 * A new connection is requested, therefore a
931 * sessiond/consumerd connection is allocated in
932 * this thread, enqueued to a global queue and
933 * dequeued (and freed) in the worker thread.
936 struct relay_connection
*new_conn
;
937 struct lttcomm_sock
*newsock
;
938 enum connection_type type
;
940 if (pollfd
== data_sock
->fd
) {
942 newsock
= data_sock
->ops
->accept(data_sock
);
943 DBG("Relay data connection accepted, socket %d",
946 assert(pollfd
== control_sock
->fd
);
947 type
= RELAY_CONTROL
;
948 newsock
= control_sock
->ops
->accept(control_sock
);
949 DBG("Relay control connection accepted, socket %d",
953 PERROR("accepting sock");
957 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
960 PERROR("setsockopt inet");
961 lttcomm_destroy_sock(newsock
);
965 ret
= socket_apply_keep_alive_config(newsock
->fd
);
967 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
969 lttcomm_destroy_sock(newsock
);
973 new_conn
= connection_create(newsock
, type
);
975 lttcomm_destroy_sock(newsock
);
979 /* Enqueue request for the dispatcher thread. */
980 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
984 * Wake the dispatch queue futex.
985 * Implicit memory barrier with the
986 * exchange in cds_wfcq_enqueue.
988 futex_nto1_wake(&relay_conn_queue
.futex
);
989 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
990 ERR("socket poll error");
993 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1003 lttng_poll_clean(&events
);
1005 if (data_sock
->fd
>= 0) {
1006 ret
= data_sock
->ops
->close(data_sock
);
1011 lttcomm_destroy_sock(data_sock
);
1013 if (control_sock
->fd
>= 0) {
1014 ret
= control_sock
->ops
->close(control_sock
);
1019 lttcomm_destroy_sock(control_sock
);
1023 ERR("Health error occurred in %s", __func__
);
1025 health_unregister(health_relayd
);
1026 DBG("Relay listener thread cleanup complete");
1027 lttng_relay_stop_threads();
1032 * This thread manages the dispatching of the requests to worker threads
1034 static void *relay_thread_dispatcher(void *data
)
1038 struct cds_wfcq_node
*node
;
1039 struct relay_connection
*new_conn
= NULL
;
1041 DBG("[thread] Relay dispatcher started");
1043 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1045 if (testpoint(relayd_thread_dispatcher
)) {
1046 goto error_testpoint
;
1049 health_code_update();
1052 health_code_update();
1054 /* Atomically prepare the queue futex */
1055 futex_nto1_prepare(&relay_conn_queue
.futex
);
1057 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1062 health_code_update();
1064 /* Dequeue commands */
1065 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1066 &relay_conn_queue
.tail
);
1068 DBG("Woken up but nothing in the relay command queue");
1069 /* Continue thread execution */
1072 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1074 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1077 * Inform worker thread of the new request. This
1078 * call is blocking so we can be assured that
1079 * the data will be read at some point in time
1080 * or wait to the end of the world :)
1082 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1084 PERROR("write connection pipe");
1085 connection_put(new_conn
);
1088 } while (node
!= NULL
);
1090 /* Futex wait on queue. Blocking call on futex() */
1091 health_poll_entry();
1092 futex_nto1_wait(&relay_conn_queue
.futex
);
1096 /* Normal exit, no error */
1103 ERR("Health error occurred in %s", __func__
);
1105 health_unregister(health_relayd
);
1106 DBG("Dispatch thread dying");
1107 lttng_relay_stop_threads();
1112 * Set index data from the control port to a given index object.
1114 static int set_index_control_data(struct relay_index
*index
,
1115 struct lttcomm_relayd_index
*data
,
1116 struct relay_connection
*conn
)
1118 struct ctf_packet_index index_data
;
1121 * The index on disk is encoded in big endian.
1123 index_data
.packet_size
= htobe64(data
->packet_size
);
1124 index_data
.content_size
= htobe64(data
->content_size
);
1125 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1126 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1127 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1128 index_data
.stream_id
= htobe64(data
->stream_id
);
1130 if (conn
->minor
>= 8) {
1131 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1132 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1135 return relay_index_set_data(index
, &index_data
);
1139 * Handle the RELAYD_CREATE_SESSION command.
1141 * On success, send back the session id or else return a negative value.
1143 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1144 struct relay_connection
*conn
,
1145 const struct lttng_buffer_view
*payload
)
1149 struct relay_session
*session
;
1150 struct lttcomm_relayd_status_session reply
;
1151 char session_name
[LTTNG_NAME_MAX
];
1152 char hostname
[LTTNG_HOST_NAME_MAX
];
1153 uint32_t live_timer
= 0;
1154 bool snapshot
= false;
1156 memset(session_name
, 0, LTTNG_NAME_MAX
);
1157 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1159 memset(&reply
, 0, sizeof(reply
));
1161 switch (conn
->minor
) {
1166 case 4: /* LTTng sessiond 2.4 */
1168 ret
= cmd_create_session_2_4(payload
, session_name
,
1169 hostname
, &live_timer
, &snapshot
);
1175 session
= session_create(session_name
, hostname
, live_timer
,
1176 snapshot
, conn
->major
, conn
->minor
);
1181 assert(!conn
->session
);
1182 conn
->session
= session
;
1183 DBG("Created session %" PRIu64
, session
->id
);
1185 reply
.session_id
= htobe64(session
->id
);
1189 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1191 reply
.ret_code
= htobe32(LTTNG_OK
);
1194 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1195 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1196 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1205 * When we have received all the streams and the metadata for a channel,
1206 * we make them visible to the viewer threads.
1208 static void publish_connection_local_streams(struct relay_connection
*conn
)
1210 struct relay_stream
*stream
;
1211 struct relay_session
*session
= conn
->session
;
1214 * We publish all streams belonging to a session atomically wrt
1217 pthread_mutex_lock(&session
->lock
);
1219 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1221 stream_publish(stream
);
1226 * Inform the viewer that there are new streams in the session.
1228 if (session
->viewer_attached
) {
1229 uatomic_set(&session
->new_streams
, 1);
1231 pthread_mutex_unlock(&session
->lock
);
1235 * relay_add_stream: allocate a new stream for a session
1237 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1238 struct relay_connection
*conn
,
1239 const struct lttng_buffer_view
*payload
)
1243 struct relay_session
*session
= conn
->session
;
1244 struct relay_stream
*stream
= NULL
;
1245 struct lttcomm_relayd_status_stream reply
;
1246 struct ctf_trace
*trace
= NULL
;
1247 uint64_t stream_handle
= -1ULL;
1248 char *path_name
= NULL
, *channel_name
= NULL
;
1249 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1251 if (!session
|| !conn
->version_check_done
) {
1252 ERR("Trying to add a stream before version check");
1254 goto end_no_session
;
1257 switch (session
->minor
) {
1258 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1259 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1260 &channel_name
, session
);
1262 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1264 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1265 &channel_name
, &tracefile_size
, &tracefile_count
,
1273 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1277 /* This stream here has one reference on the trace. */
1279 pthread_mutex_lock(&last_relay_stream_id_lock
);
1280 stream_handle
= ++last_relay_stream_id
;
1281 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1283 /* We pass ownership of path_name and channel_name. */
1284 stream
= stream_create(trace
, stream_handle
, path_name
,
1285 channel_name
, tracefile_size
, tracefile_count
);
1287 channel_name
= NULL
;
1290 * Streams are the owners of their trace. Reference to trace is
1291 * kept within stream_create().
1293 ctf_trace_put(trace
);
1296 memset(&reply
, 0, sizeof(reply
));
1297 reply
.handle
= htobe64(stream_handle
);
1299 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1301 reply
.ret_code
= htobe32(LTTNG_OK
);
1304 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1305 sizeof(struct lttcomm_relayd_status_stream
), 0);
1306 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1307 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1319 * relay_close_stream: close a specific stream
1321 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1322 struct relay_connection
*conn
,
1323 const struct lttng_buffer_view
*payload
)
1327 struct relay_session
*session
= conn
->session
;
1328 struct lttcomm_relayd_close_stream stream_info
;
1329 struct lttcomm_relayd_generic_reply reply
;
1330 struct relay_stream
*stream
;
1332 DBG("Close stream received");
1334 if (!session
|| !conn
->version_check_done
) {
1335 ERR("Trying to close a stream before version check");
1337 goto end_no_session
;
1340 if (payload
->size
< sizeof(stream_info
)) {
1341 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1342 sizeof(stream_info
), payload
->size
);
1344 goto end_no_session
;
1346 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1347 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1348 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1350 stream
= stream_get_by_id(stream_info
.stream_id
);
1357 * Set last_net_seq_num before the close flag. Required by data
1360 pthread_mutex_lock(&stream
->lock
);
1361 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1362 pthread_mutex_unlock(&stream
->lock
);
1365 * This is one of the conditions which may trigger a stream close
1366 * with the others being:
1367 * 1) A close command is received for a stream
1368 * 2) The control connection owning the stream is closed
1369 * 3) We have received all of the stream's data _after_ a close
1372 try_stream_close(stream
);
1373 if (stream
->is_metadata
) {
1374 struct relay_viewer_stream
*vstream
;
1376 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1378 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1380 * Since all the metadata has been sent to the
1381 * viewer and that we have a request to close
1382 * its stream, we can safely teardown the
1383 * corresponding metadata viewer stream.
1385 viewer_stream_put(vstream
);
1387 /* Put local reference. */
1388 viewer_stream_put(vstream
);
1395 memset(&reply
, 0, sizeof(reply
));
1397 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1399 reply
.ret_code
= htobe32(LTTNG_OK
);
1401 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1402 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1403 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1404 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1414 * relay_reset_metadata: reset a metadata stream
1417 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1418 struct relay_connection
*conn
,
1419 const struct lttng_buffer_view
*payload
)
1423 struct relay_session
*session
= conn
->session
;
1424 struct lttcomm_relayd_reset_metadata stream_info
;
1425 struct lttcomm_relayd_generic_reply reply
;
1426 struct relay_stream
*stream
;
1428 DBG("Reset metadata received");
1430 if (!session
|| !conn
->version_check_done
) {
1431 ERR("Trying to reset a metadata stream before version check");
1433 goto end_no_session
;
1436 if (payload
->size
< sizeof(stream_info
)) {
1437 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1438 sizeof(stream_info
), payload
->size
);
1440 goto end_no_session
;
1442 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1443 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1444 stream_info
.version
= be64toh(stream_info
.version
);
1446 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1448 /* Unsupported for live sessions for now. */
1449 if (session
->live_timer
!= 0) {
1454 stream
= stream_get_by_id(stream_info
.stream_id
);
1459 pthread_mutex_lock(&stream
->lock
);
1460 if (!stream
->is_metadata
) {
1465 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1466 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1467 &stream
->stream_fd
->fd
);
1469 ERR("Failed to rotate metadata file %s of channel %s",
1470 stream
->path_name
, stream
->channel_name
);
1475 pthread_mutex_unlock(&stream
->lock
);
1479 memset(&reply
, 0, sizeof(reply
));
1481 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1483 reply
.ret_code
= htobe32(LTTNG_OK
);
1485 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1486 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1487 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1488 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1498 * relay_unknown_command: send -1 if received unknown command
1500 static void relay_unknown_command(struct relay_connection
*conn
)
1502 struct lttcomm_relayd_generic_reply reply
;
1505 memset(&reply
, 0, sizeof(reply
));
1506 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1507 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1508 if (send_ret
< sizeof(reply
)) {
1509 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1514 * relay_start: send an acknowledgment to the client to tell if we are
1515 * ready to receive data. We are ready if a session is established.
1517 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1518 struct relay_connection
*conn
,
1519 const struct lttng_buffer_view
*payload
)
1523 struct lttcomm_relayd_generic_reply reply
;
1524 struct relay_session
*session
= conn
->session
;
1527 DBG("Trying to start the streaming without a session established");
1528 ret
= htobe32(LTTNG_ERR_UNK
);
1531 memset(&reply
, 0, sizeof(reply
));
1532 reply
.ret_code
= htobe32(LTTNG_OK
);
1533 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1535 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1536 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1545 * Append padding to the file pointed by the file descriptor fd.
1547 static int write_padding_to_file(int fd
, uint32_t size
)
1556 zeros
= zmalloc(size
);
1557 if (zeros
== NULL
) {
1558 PERROR("zmalloc zeros for padding");
1563 ret
= lttng_write(fd
, zeros
, size
);
1565 PERROR("write padding to file");
1575 * relay_recv_metadata: receive the metadata for the session.
1577 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1578 struct relay_connection
*conn
,
1579 const struct lttng_buffer_view
*payload
)
1583 struct relay_session
*session
= conn
->session
;
1584 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1585 struct relay_stream
*metadata_stream
;
1586 uint64_t metadata_payload_size
;
1589 ERR("Metadata sent before version check");
1594 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1595 ERR("Incorrect data size");
1599 metadata_payload_size
= recv_hdr
->data_size
-
1600 sizeof(struct lttcomm_relayd_metadata_payload
);
1602 memcpy(&metadata_payload_header
, payload
->data
,
1603 sizeof(metadata_payload_header
));
1604 metadata_payload_header
.stream_id
= be64toh(
1605 metadata_payload_header
.stream_id
);
1606 metadata_payload_header
.padding_size
= be32toh(
1607 metadata_payload_header
.padding_size
);
1609 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1610 if (!metadata_stream
) {
1615 pthread_mutex_lock(&metadata_stream
->lock
);
1617 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1618 payload
->data
+ sizeof(metadata_payload_header
),
1619 metadata_payload_size
);
1620 if (size_ret
< metadata_payload_size
) {
1621 ERR("Relay error writing metadata on file");
1626 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1627 metadata_payload_header
.padding_size
);
1628 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1633 metadata_stream
->metadata_received
+=
1634 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1635 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1636 metadata_stream
->metadata_received
);
1639 pthread_mutex_unlock(&metadata_stream
->lock
);
1640 stream_put(metadata_stream
);
1646 * relay_send_version: send relayd version number
1648 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1649 struct relay_connection
*conn
,
1650 const struct lttng_buffer_view
*payload
)
1654 struct lttcomm_relayd_version reply
, msg
;
1655 bool compatible
= true;
1657 conn
->version_check_done
= true;
1659 /* Get version from the other side. */
1660 if (payload
->size
< sizeof(msg
)) {
1661 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1662 sizeof(msg
), payload
->size
);
1667 memcpy(&msg
, payload
->data
, sizeof(msg
));
1668 msg
.major
= be32toh(msg
.major
);
1669 msg
.minor
= be32toh(msg
.minor
);
1671 memset(&reply
, 0, sizeof(reply
));
1672 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1673 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1675 /* Major versions must be the same */
1676 if (reply
.major
!= msg
.major
) {
1677 DBG("Incompatible major versions (%u vs %u), deleting session",
1678 reply
.major
, msg
.major
);
1682 conn
->major
= reply
.major
;
1683 /* We adapt to the lowest compatible version */
1684 if (reply
.minor
<= msg
.minor
) {
1685 conn
->minor
= reply
.minor
;
1687 conn
->minor
= msg
.minor
;
1690 reply
.major
= htobe32(reply
.major
);
1691 reply
.minor
= htobe32(reply
.minor
);
1692 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1694 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1695 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1708 DBG("Version check done using protocol %u.%u", conn
->major
,
1716 * Check for data pending for a given stream id from the session daemon.
1718 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1719 struct relay_connection
*conn
,
1720 const struct lttng_buffer_view
*payload
)
1722 struct relay_session
*session
= conn
->session
;
1723 struct lttcomm_relayd_data_pending msg
;
1724 struct lttcomm_relayd_generic_reply reply
;
1725 struct relay_stream
*stream
;
1729 DBG("Data pending command received");
1731 if (!session
|| !conn
->version_check_done
) {
1732 ERR("Trying to check for data before version check");
1734 goto end_no_session
;
1737 if (payload
->size
< sizeof(msg
)) {
1738 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1739 sizeof(msg
), payload
->size
);
1741 goto end_no_session
;
1743 memcpy(&msg
, payload
->data
, sizeof(msg
));
1744 msg
.stream_id
= be64toh(msg
.stream_id
);
1745 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1747 stream
= stream_get_by_id(msg
.stream_id
);
1748 if (stream
== NULL
) {
1753 pthread_mutex_lock(&stream
->lock
);
1755 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1756 " and last_seq %" PRIu64
, msg
.stream_id
,
1757 stream
->prev_seq
, msg
.last_net_seq_num
);
1759 /* Avoid wrapping issue */
1760 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1761 /* Data has in fact been written and is NOT pending */
1764 /* Data still being streamed thus pending */
1768 stream
->data_pending_check_done
= true;
1769 pthread_mutex_unlock(&stream
->lock
);
1774 memset(&reply
, 0, sizeof(reply
));
1775 reply
.ret_code
= htobe32(ret
);
1776 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1777 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1778 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1788 * Wait for the control socket to reach a quiescent state.
1790 * Note that for now, when receiving this command from the session
1791 * daemon, this means that every subsequent commands or data received on
1792 * the control socket has been handled. So, this is why we simply return
1795 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1796 struct relay_connection
*conn
,
1797 const struct lttng_buffer_view
*payload
)
1801 struct relay_stream
*stream
;
1802 struct lttcomm_relayd_quiescent_control msg
;
1803 struct lttcomm_relayd_generic_reply reply
;
1805 DBG("Checking quiescent state on control socket");
1807 if (!conn
->session
|| !conn
->version_check_done
) {
1808 ERR("Trying to check for data before version check");
1810 goto end_no_session
;
1813 if (payload
->size
< sizeof(msg
)) {
1814 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1815 sizeof(msg
), payload
->size
);
1817 goto end_no_session
;
1819 memcpy(&msg
, payload
->data
, sizeof(msg
));
1820 msg
.stream_id
= be64toh(msg
.stream_id
);
1822 stream
= stream_get_by_id(msg
.stream_id
);
1826 pthread_mutex_lock(&stream
->lock
);
1827 stream
->data_pending_check_done
= true;
1828 pthread_mutex_unlock(&stream
->lock
);
1830 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1833 memset(&reply
, 0, sizeof(reply
));
1834 reply
.ret_code
= htobe32(LTTNG_OK
);
1835 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1836 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1837 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1849 * Initialize a data pending command. This means that a consumer is about
1850 * to ask for data pending for each stream it holds. Simply iterate over
1851 * all streams of a session and set the data_pending_check_done flag.
1853 * This command returns to the client a LTTNG_OK code.
1855 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1856 struct relay_connection
*conn
,
1857 const struct lttng_buffer_view
*payload
)
1861 struct lttng_ht_iter iter
;
1862 struct lttcomm_relayd_begin_data_pending msg
;
1863 struct lttcomm_relayd_generic_reply reply
;
1864 struct relay_stream
*stream
;
1869 DBG("Init streams for data pending");
1871 if (!conn
->session
|| !conn
->version_check_done
) {
1872 ERR("Trying to check for data before version check");
1874 goto end_no_session
;
1877 if (payload
->size
< sizeof(msg
)) {
1878 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1879 sizeof(msg
), payload
->size
);
1881 goto end_no_session
;
1883 memcpy(&msg
, payload
->data
, sizeof(msg
));
1884 msg
.session_id
= be64toh(msg
.session_id
);
1887 * Iterate over all streams to set the begin data pending flag.
1888 * For now, the streams are indexed by stream handle so we have
1889 * to iterate over all streams to find the one associated with
1890 * the right session_id.
1893 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1895 if (!stream_get(stream
)) {
1898 if (stream
->trace
->session
->id
== msg
.session_id
) {
1899 pthread_mutex_lock(&stream
->lock
);
1900 stream
->data_pending_check_done
= false;
1901 pthread_mutex_unlock(&stream
->lock
);
1902 DBG("Set begin data pending flag to stream %" PRIu64
,
1903 stream
->stream_handle
);
1909 memset(&reply
, 0, sizeof(reply
));
1910 /* All good, send back reply. */
1911 reply
.ret_code
= htobe32(LTTNG_OK
);
1913 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1914 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1915 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1927 * End data pending command. This will check, for a given session id, if
1928 * each stream associated with it has its data_pending_check_done flag
1929 * set. If not, this means that the client lost track of the stream but
1930 * the data is still being streamed on our side. In this case, we inform
1931 * the client that data is in flight.
1933 * Return to the client if there is data in flight or not with a ret_code.
1935 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1936 struct relay_connection
*conn
,
1937 const struct lttng_buffer_view
*payload
)
1941 struct lttng_ht_iter iter
;
1942 struct lttcomm_relayd_end_data_pending msg
;
1943 struct lttcomm_relayd_generic_reply reply
;
1944 struct relay_stream
*stream
;
1945 uint32_t is_data_inflight
= 0;
1947 DBG("End data pending command");
1949 if (!conn
->session
|| !conn
->version_check_done
) {
1950 ERR("Trying to check for data before version check");
1952 goto end_no_session
;
1955 if (payload
->size
< sizeof(msg
)) {
1956 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1957 sizeof(msg
), payload
->size
);
1959 goto end_no_session
;
1961 memcpy(&msg
, payload
->data
, sizeof(msg
));
1962 msg
.session_id
= be64toh(msg
.session_id
);
1965 * Iterate over all streams to see if the begin data pending
1969 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1971 if (!stream_get(stream
)) {
1974 if (stream
->trace
->session
->id
!= msg
.session_id
) {
1978 pthread_mutex_lock(&stream
->lock
);
1979 if (!stream
->data_pending_check_done
) {
1980 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1981 is_data_inflight
= 1;
1982 DBG("Data is still in flight for stream %" PRIu64
,
1983 stream
->stream_handle
);
1984 pthread_mutex_unlock(&stream
->lock
);
1989 pthread_mutex_unlock(&stream
->lock
);
1994 memset(&reply
, 0, sizeof(reply
));
1995 /* All good, send back reply. */
1996 reply
.ret_code
= htobe32(is_data_inflight
);
1998 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1999 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2000 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2012 * Receive an index for a specific stream.
2014 * Return 0 on success else a negative value.
2016 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2017 struct relay_connection
*conn
,
2018 const struct lttng_buffer_view
*payload
)
2022 struct relay_session
*session
= conn
->session
;
2023 struct lttcomm_relayd_index index_info
;
2024 struct relay_index
*index
;
2025 struct lttcomm_relayd_generic_reply reply
;
2026 struct relay_stream
*stream
;
2031 DBG("Relay receiving index");
2033 if (!session
|| !conn
->version_check_done
) {
2034 ERR("Trying to close a stream before version check");
2036 goto end_no_session
;
2039 msg_len
= lttcomm_relayd_index_len(
2040 lttng_to_index_major(conn
->major
, conn
->minor
),
2041 lttng_to_index_minor(conn
->major
, conn
->minor
));
2042 if (payload
->size
< msg_len
) {
2043 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2044 msg_len
, payload
->size
);
2046 goto end_no_session
;
2048 memcpy(&index_info
, payload
->data
, msg_len
);
2049 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2050 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2051 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2052 index_info
.content_size
= be64toh(index_info
.content_size
);
2053 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2054 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2055 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2056 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2058 if (conn
->minor
>= 8) {
2059 index_info
.stream_instance_id
=
2060 be64toh(index_info
.stream_instance_id
);
2061 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2064 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2066 ERR("stream_get_by_id not found");
2070 pthread_mutex_lock(&stream
->lock
);
2072 /* Live beacon handling */
2073 if (index_info
.packet_size
== 0) {
2074 DBG("Received live beacon for stream %" PRIu64
,
2075 stream
->stream_handle
);
2078 * Only flag a stream inactive when it has already
2079 * received data and no indexes are in flight.
2081 if (stream
->index_received_seqcount
> 0
2082 && stream
->indexes_in_flight
== 0) {
2083 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2086 goto end_stream_put
;
2088 stream
->beacon_ts_end
= -1ULL;
2091 if (stream
->ctf_stream_id
== -1ULL) {
2092 stream
->ctf_stream_id
= index_info
.stream_id
;
2094 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2097 ERR("relay_index_get_by_id_or_create index NULL");
2098 goto end_stream_put
;
2100 if (set_index_control_data(index
, &index_info
, conn
)) {
2101 ERR("set_index_control_data error");
2102 relay_index_put(index
);
2104 goto end_stream_put
;
2106 ret
= relay_index_try_flush(index
);
2108 tracefile_array_commit_seq(stream
->tfa
);
2109 stream
->index_received_seqcount
++;
2110 } else if (ret
> 0) {
2114 ERR("relay_index_try_flush error %d", ret
);
2115 relay_index_put(index
);
2120 pthread_mutex_unlock(&stream
->lock
);
2125 memset(&reply
, 0, sizeof(reply
));
2127 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2129 reply
.ret_code
= htobe32(LTTNG_OK
);
2131 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2132 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2133 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2142 * Receive the streams_sent message.
2144 * Return 0 on success else a negative value.
2146 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2147 struct relay_connection
*conn
,
2148 const struct lttng_buffer_view
*payload
)
2152 struct lttcomm_relayd_generic_reply reply
;
2156 DBG("Relay receiving streams_sent");
2158 if (!conn
->session
|| !conn
->version_check_done
) {
2159 ERR("Trying to close a stream before version check");
2161 goto end_no_session
;
2165 * Publish every pending stream in the connection recv list which are
2166 * now ready to be used by the viewer.
2168 publish_connection_local_streams(conn
);
2170 memset(&reply
, 0, sizeof(reply
));
2171 reply
.ret_code
= htobe32(LTTNG_OK
);
2172 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2173 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2174 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2186 #define DBG_CMD(cmd_name, conn) \
2187 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2189 static int relay_process_control_command(struct relay_connection
*conn
,
2190 const struct lttcomm_relayd_hdr
*header
,
2191 const struct lttng_buffer_view
*payload
)
2195 switch (header
->cmd
) {
2196 case RELAYD_CREATE_SESSION
:
2197 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2198 ret
= relay_create_session(header
, conn
, payload
);
2200 case RELAYD_ADD_STREAM
:
2201 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2202 ret
= relay_add_stream(header
, conn
, payload
);
2204 case RELAYD_START_DATA
:
2205 DBG_CMD("RELAYD_START_DATA", conn
);
2206 ret
= relay_start(header
, conn
, payload
);
2208 case RELAYD_SEND_METADATA
:
2209 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2210 ret
= relay_recv_metadata(header
, conn
, payload
);
2212 case RELAYD_VERSION
:
2213 DBG_CMD("RELAYD_VERSION", conn
);
2214 ret
= relay_send_version(header
, conn
, payload
);
2216 case RELAYD_CLOSE_STREAM
:
2217 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2218 ret
= relay_close_stream(header
, conn
, payload
);
2220 case RELAYD_DATA_PENDING
:
2221 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2222 ret
= relay_data_pending(header
, conn
, payload
);
2224 case RELAYD_QUIESCENT_CONTROL
:
2225 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2226 ret
= relay_quiescent_control(header
, conn
, payload
);
2228 case RELAYD_BEGIN_DATA_PENDING
:
2229 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2230 ret
= relay_begin_data_pending(header
, conn
, payload
);
2232 case RELAYD_END_DATA_PENDING
:
2233 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2234 ret
= relay_end_data_pending(header
, conn
, payload
);
2236 case RELAYD_SEND_INDEX
:
2237 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2238 ret
= relay_recv_index(header
, conn
, payload
);
2240 case RELAYD_STREAMS_SENT
:
2241 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2242 ret
= relay_streams_sent(header
, conn
, payload
);
2244 case RELAYD_RESET_METADATA
:
2245 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2246 ret
= relay_reset_metadata(header
, conn
, payload
);
2248 case RELAYD_UPDATE_SYNC_INFO
:
2250 ERR("Received unknown command (%u)", header
->cmd
);
2251 relay_unknown_command(conn
);
2260 static enum relay_connection_status
relay_process_control_receive_payload(
2261 struct relay_connection
*conn
)
2264 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2265 struct lttng_dynamic_buffer
*reception_buffer
=
2266 &conn
->protocol
.ctrl
.reception_buffer
;
2267 struct ctrl_connection_state_receive_payload
*state
=
2268 &conn
->protocol
.ctrl
.state
.receive_payload
;
2269 struct lttng_buffer_view payload_view
;
2271 if (state
->left_to_receive
== 0) {
2272 /* Short-circuit for payload-less commands. */
2273 goto reception_complete
;
2275 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2276 reception_buffer
->data
+ state
->received
,
2277 state
->left_to_receive
, MSG_DONTWAIT
);
2279 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2280 PERROR("Unable to receive command payload on sock %d",
2282 status
= RELAY_CONNECTION_STATUS_ERROR
;
2285 } else if (ret
== 0) {
2286 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2287 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2292 assert(ret
<= state
->left_to_receive
);
2294 state
->left_to_receive
-= ret
;
2295 state
->received
+= ret
;
2297 if (state
->left_to_receive
> 0) {
2299 * Can't transition to the protocol's next state, wait to
2300 * receive the rest of the header.
2302 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2303 state
->received
, state
->left_to_receive
,
2309 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2310 conn
->sock
->fd
, state
->received
);
2312 * The payload required to process the command has been received.
2313 * A view to the reception buffer is forwarded to the various
2314 * commands and the state of the control is reset on success.
2316 * Commands are responsible for sending their reply to the peer.
2318 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2320 ret
= relay_process_control_command(conn
,
2321 &state
->header
, &payload_view
);
2323 status
= RELAY_CONNECTION_STATUS_ERROR
;
2327 ret
= connection_reset_protocol_state(conn
);
2329 status
= RELAY_CONNECTION_STATUS_ERROR
;
2335 static enum relay_connection_status
relay_process_control_receive_header(
2336 struct relay_connection
*conn
)
2339 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2340 struct lttcomm_relayd_hdr header
;
2341 struct lttng_dynamic_buffer
*reception_buffer
=
2342 &conn
->protocol
.ctrl
.reception_buffer
;
2343 struct ctrl_connection_state_receive_header
*state
=
2344 &conn
->protocol
.ctrl
.state
.receive_header
;
2346 assert(state
->left_to_receive
!= 0);
2348 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2349 reception_buffer
->data
+ state
->received
,
2350 state
->left_to_receive
, MSG_DONTWAIT
);
2352 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2353 PERROR("Unable to receive control command header on sock %d",
2355 status
= RELAY_CONNECTION_STATUS_ERROR
;
2358 } else if (ret
== 0) {
2359 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2360 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2365 assert(ret
<= state
->left_to_receive
);
2367 state
->left_to_receive
-= ret
;
2368 state
->received
+= ret
;
2370 if (state
->left_to_receive
> 0) {
2372 * Can't transition to the protocol's next state, wait to
2373 * receive the rest of the header.
2375 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2376 state
->received
, state
->left_to_receive
,
2381 /* Transition to next state: receiving the command's payload. */
2382 conn
->protocol
.ctrl
.state_id
=
2383 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2384 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2385 header
.circuit_id
= be64toh(header
.circuit_id
);
2386 header
.data_size
= be64toh(header
.data_size
);
2387 header
.cmd
= be32toh(header
.cmd
);
2388 header
.cmd_version
= be32toh(header
.cmd_version
);
2389 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2390 &header
, sizeof(header
));
2392 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2393 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2396 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2397 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2399 status
= RELAY_CONNECTION_STATUS_ERROR
;
2403 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2405 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2406 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2409 status
= RELAY_CONNECTION_STATUS_ERROR
;
2413 if (header
.data_size
== 0) {
2415 * Manually invoke the next state as the poll loop
2416 * will not wake-up to allow us to proceed further.
2418 status
= relay_process_control_receive_payload(conn
);
2425 * Process the commands received on the control socket
2427 static enum relay_connection_status
relay_process_control(
2428 struct relay_connection
*conn
)
2430 enum relay_connection_status status
;
2432 switch (conn
->protocol
.ctrl
.state_id
) {
2433 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2434 status
= relay_process_control_receive_header(conn
);
2436 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2437 status
= relay_process_control_receive_payload(conn
);
2440 ERR("Unknown control connection protocol state encountered.");
2448 * Handle index for a data stream.
2450 * Called with the stream lock held.
2452 * Return 0 on success else a negative value.
2454 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2458 uint64_t data_offset
;
2459 struct relay_index
*index
;
2461 /* Get data offset because we are about to update the index. */
2462 data_offset
= htobe64(stream
->tracefile_size_current
);
2464 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2465 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2468 * Lookup for an existing index for that stream id/sequence
2469 * number. If it exists, the control thread has already received the
2470 * data for it, thus we need to write it to disk.
2472 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2478 if (rotate_index
|| !stream
->index_file
) {
2479 uint32_t major
, minor
;
2481 /* Put ref on previous index_file. */
2482 if (stream
->index_file
) {
2483 lttng_index_file_put(stream
->index_file
);
2484 stream
->index_file
= NULL
;
2486 major
= stream
->trace
->session
->major
;
2487 minor
= stream
->trace
->session
->minor
;
2488 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2489 stream
->channel_name
,
2490 -1, -1, stream
->tracefile_size
,
2491 tracefile_array_get_file_index_head(stream
->tfa
),
2492 lttng_to_index_major(major
, minor
),
2493 lttng_to_index_minor(major
, minor
));
2494 if (!stream
->index_file
) {
2496 /* Put self-ref for this index due to error. */
2497 relay_index_put(index
);
2503 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2505 /* Put self-ref for this index due to error. */
2506 relay_index_put(index
);
2511 ret
= relay_index_try_flush(index
);
2513 tracefile_array_commit_seq(stream
->tfa
);
2514 stream
->index_received_seqcount
++;
2515 } else if (ret
> 0) {
2519 /* Put self-ref for this index due to error. */
2520 relay_index_put(index
);
2528 static enum relay_connection_status
relay_process_data_receive_header(
2529 struct relay_connection
*conn
)
2532 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2533 struct data_connection_state_receive_header
*state
=
2534 &conn
->protocol
.data
.state
.receive_header
;
2535 struct lttcomm_relayd_data_hdr header
;
2536 struct relay_stream
*stream
;
2538 assert(state
->left_to_receive
!= 0);
2540 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2541 state
->header_reception_buffer
+ state
->received
,
2542 state
->left_to_receive
, MSG_DONTWAIT
);
2544 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2545 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2546 status
= RELAY_CONNECTION_STATUS_ERROR
;
2549 } else if (ret
== 0) {
2550 /* Orderly shutdown. Not necessary to print an error. */
2551 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2552 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2557 assert(ret
<= state
->left_to_receive
);
2559 state
->left_to_receive
-= ret
;
2560 state
->received
+= ret
;
2562 if (state
->left_to_receive
> 0) {
2564 * Can't transition to the protocol's next state, wait to
2565 * receive the rest of the header.
2567 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2568 state
->received
, state
->left_to_receive
,
2574 /* Transition to next state: receiving the payload. */
2575 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2577 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2578 header
.circuit_id
= be64toh(header
.circuit_id
);
2579 header
.stream_id
= be64toh(header
.stream_id
);
2580 header
.data_size
= be32toh(header
.data_size
);
2581 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2582 header
.padding_size
= be32toh(header
.padding_size
);
2583 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2585 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2587 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2588 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2590 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2591 conn
->sock
->fd
, header
.circuit_id
,
2592 header
.stream_id
, header
.data_size
,
2593 header
.net_seq_num
, header
.padding_size
);
2595 stream
= stream_get_by_id(header
.stream_id
);
2597 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2599 /* Protocol error. */
2600 status
= RELAY_CONNECTION_STATUS_ERROR
;
2604 pthread_mutex_lock(&stream
->lock
);
2606 /* Check if a rotation is needed. */
2607 if (stream
->tracefile_size
> 0 &&
2608 (stream
->tracefile_size_current
+ header
.data_size
) >
2609 stream
->tracefile_size
) {
2610 uint64_t old_id
, new_id
;
2612 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2613 tracefile_array_file_rotate(stream
->tfa
);
2615 /* new_id is updated by utils_rotate_stream_file. */
2618 ret
= utils_rotate_stream_file(stream
->path_name
,
2619 stream
->channel_name
, stream
->tracefile_size
,
2620 stream
->tracefile_count
, -1,
2621 -1, stream
->stream_fd
->fd
,
2622 &new_id
, &stream
->stream_fd
->fd
);
2624 ERR("Failed to rotate stream output file");
2625 status
= RELAY_CONNECTION_STATUS_ERROR
;
2626 goto end_stream_unlock
;
2630 * Reset current size because we just performed a stream
2633 stream
->tracefile_size_current
= 0;
2634 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2639 pthread_mutex_unlock(&stream
->lock
);
2645 static enum relay_connection_status
relay_process_data_receive_payload(
2646 struct relay_connection
*conn
)
2649 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2650 struct relay_stream
*stream
;
2651 struct data_connection_state_receive_payload
*state
=
2652 &conn
->protocol
.data
.state
.receive_payload
;
2653 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2654 char data_buffer
[chunk_size
];
2655 bool partial_recv
= false;
2656 bool new_stream
= false, close_requested
= false;
2657 uint64_t left_to_receive
= state
->left_to_receive
;
2658 struct relay_session
*session
;
2660 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2661 state
->header
.stream_id
, state
->header
.net_seq_num
,
2662 state
->received
, left_to_receive
);
2664 stream
= stream_get_by_id(state
->header
.stream_id
);
2666 /* Protocol error. */
2667 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2668 state
->header
.stream_id
);
2669 status
= RELAY_CONNECTION_STATUS_ERROR
;
2673 pthread_mutex_lock(&stream
->lock
);
2674 session
= stream
->trace
->session
;
2675 if (!conn
->session
) {
2676 ret
= connection_set_session(conn
, session
);
2678 status
= RELAY_CONNECTION_STATUS_ERROR
;
2679 goto end_stream_unlock
;
2684 * The size of the "chunk" received on any iteration is bounded by:
2685 * - the data left to receive,
2686 * - the data immediately available on the socket,
2687 * - the on-stack data buffer
2689 while (left_to_receive
> 0 && !partial_recv
) {
2691 size_t recv_size
= min(left_to_receive
, chunk_size
);
2693 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2694 recv_size
, MSG_DONTWAIT
);
2696 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2697 PERROR("Socket %d error", conn
->sock
->fd
);
2698 status
= RELAY_CONNECTION_STATUS_ERROR
;
2700 goto end_stream_unlock
;
2701 } else if (ret
== 0) {
2702 /* No more data ready to be consumed on socket. */
2703 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2704 state
->header
.stream_id
);
2705 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2707 } else if (ret
< (int) recv_size
) {
2709 * All the data available on the socket has been
2712 partial_recv
= true;
2717 /* Write data to stream output fd. */
2718 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2720 if (write_ret
< (ssize_t
) recv_size
) {
2721 ERR("Relay error writing data to file");
2722 status
= RELAY_CONNECTION_STATUS_ERROR
;
2723 goto end_stream_unlock
;
2726 left_to_receive
-= recv_size
;
2727 state
->received
+= recv_size
;
2728 state
->left_to_receive
= left_to_receive
;
2730 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2731 write_ret
, stream
->stream_handle
);
2734 if (state
->left_to_receive
> 0) {
2736 * Did not receive all the data expected, wait for more data to
2737 * become available on the socket.
2739 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2740 state
->header
.stream_id
, state
->received
,
2741 state
->left_to_receive
);
2742 goto end_stream_unlock
;
2745 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2746 state
->header
.padding_size
);
2747 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2748 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2749 stream
->stream_handle
,
2750 state
->header
.net_seq_num
, ret
);
2751 status
= RELAY_CONNECTION_STATUS_ERROR
;
2752 goto end_stream_unlock
;
2756 if (session
->minor
>= 4 && !session
->snapshot
) {
2757 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2758 state
->rotate_index
);
2760 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2761 stream
->stream_handle
,
2762 state
->header
.net_seq_num
, ret
);
2763 status
= RELAY_CONNECTION_STATUS_ERROR
;
2764 goto end_stream_unlock
;
2768 stream
->tracefile_size_current
+= state
->header
.data_size
+
2769 state
->header
.padding_size
;
2771 if (stream
->prev_seq
== -1ULL) {
2775 stream
->prev_seq
= state
->header
.net_seq_num
;
2778 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2779 * contents of *state which are aliased (union) to the same location as
2780 * the new state. Don't use it beyond this point.
2782 connection_reset_protocol_state(conn
);
2786 close_requested
= stream
->close_requested
;
2787 pthread_mutex_unlock(&stream
->lock
);
2788 if (close_requested
&& left_to_receive
== 0) {
2789 try_stream_close(stream
);
2793 pthread_mutex_lock(&session
->lock
);
2794 uatomic_set(&session
->new_streams
, 1);
2795 pthread_mutex_unlock(&session
->lock
);
2804 * relay_process_data: Process the data received on the data socket
2806 static enum relay_connection_status
relay_process_data(
2807 struct relay_connection
*conn
)
2809 enum relay_connection_status status
;
2811 switch (conn
->protocol
.data
.state_id
) {
2812 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2813 status
= relay_process_data_receive_header(conn
);
2815 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2816 status
= relay_process_data_receive_payload(conn
);
2819 ERR("Unexpected data connection communication state.");
2826 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2830 (void) lttng_poll_del(events
, pollfd
);
2832 ret
= close(pollfd
);
2834 ERR("Closing pollfd %d", pollfd
);
2838 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2839 int pollfd
, struct relay_connection
*conn
)
2841 const char *type_str
;
2843 switch (conn
->type
) {
2848 type_str
= "Control";
2850 case RELAY_VIEWER_COMMAND
:
2851 type_str
= "Viewer Command";
2853 case RELAY_VIEWER_NOTIFICATION
:
2854 type_str
= "Viewer Notification";
2857 type_str
= "Unknown";
2859 cleanup_connection_pollfd(events
, pollfd
);
2860 connection_put(conn
);
2861 DBG("%s connection closed with %d", type_str
, pollfd
);
2865 * This thread does the actual work
2867 static void *relay_thread_worker(void *data
)
2869 int ret
, err
= -1, last_seen_data_fd
= -1;
2871 struct lttng_poll_event events
;
2872 struct lttng_ht
*relay_connections_ht
;
2873 struct lttng_ht_iter iter
;
2874 struct relay_connection
*destroy_conn
= NULL
;
2876 DBG("[thread] Relay worker started");
2878 rcu_register_thread();
2880 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2882 if (testpoint(relayd_thread_worker
)) {
2883 goto error_testpoint
;
2886 health_code_update();
2888 /* table of connections indexed on socket */
2889 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2890 if (!relay_connections_ht
) {
2891 goto relay_connections_ht_error
;
2894 ret
= create_thread_poll_set(&events
, 2);
2896 goto error_poll_create
;
2899 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2906 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2908 health_code_update();
2910 /* Infinite blocking call, waiting for transmission */
2911 DBG3("Relayd worker thread polling...");
2912 health_poll_entry();
2913 ret
= lttng_poll_wait(&events
, -1);
2917 * Restart interrupted system call.
2919 if (errno
== EINTR
) {
2928 * Process control. The control connection is
2929 * prioritized so we don't starve it with high
2930 * throughput tracing data on the data connection.
2932 for (i
= 0; i
< nb_fd
; i
++) {
2933 /* Fetch once the poll data */
2934 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2935 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2937 health_code_update();
2941 * No activity for this FD (poll
2947 /* Thread quit pipe has been closed. Killing thread. */
2948 ret
= check_thread_quit_pipe(pollfd
, revents
);
2954 /* Inspect the relay conn pipe for new connection */
2955 if (pollfd
== relay_conn_pipe
[0]) {
2956 if (revents
& LPOLLIN
) {
2957 struct relay_connection
*conn
;
2959 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2963 lttng_poll_add(&events
, conn
->sock
->fd
,
2964 LPOLLIN
| LPOLLRDHUP
);
2965 connection_ht_add(relay_connections_ht
, conn
);
2966 DBG("Connection socket %d added", conn
->sock
->fd
);
2967 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2968 ERR("Relay connection pipe error");
2971 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2975 struct relay_connection
*ctrl_conn
;
2977 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2978 /* If not found, there is a synchronization issue. */
2981 if (ctrl_conn
->type
== RELAY_DATA
) {
2982 if (revents
& LPOLLIN
) {
2984 * Flag the last seen data fd not deleted. It will be
2985 * used as the last seen fd if any fd gets deleted in
2988 last_notdel_data_fd
= pollfd
;
2990 goto put_ctrl_connection
;
2992 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2994 if (revents
& LPOLLIN
) {
2995 enum relay_connection_status status
;
2997 status
= relay_process_control(ctrl_conn
);
2998 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3000 * On socket error flag the session as aborted to force
3001 * the cleanup of its stream otherwise it can leak
3002 * during the lifetime of the relayd.
3004 * This prevents situations in which streams can be
3005 * left opened because an index was received, the
3006 * control connection is closed, and the data
3007 * connection is closed (uncleanly) before the packet's
3010 * Since the control connection encountered an error,
3011 * it is okay to be conservative and close the
3012 * session right now as we can't rely on the protocol
3013 * being respected anymore.
3015 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3016 session_abort(ctrl_conn
->session
);
3019 /* Clear the connection on error or close. */
3020 relay_thread_close_connection(&events
,
3025 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3026 relay_thread_close_connection(&events
,
3028 if (last_seen_data_fd
== pollfd
) {
3029 last_seen_data_fd
= last_notdel_data_fd
;
3032 ERR("Unexpected poll events %u for control sock %d",
3034 connection_put(ctrl_conn
);
3037 put_ctrl_connection
:
3038 connection_put(ctrl_conn
);
3043 * The last loop handled a control request, go back to poll to make
3044 * sure we prioritise the control socket.
3050 if (last_seen_data_fd
>= 0) {
3051 for (i
= 0; i
< nb_fd
; i
++) {
3052 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3054 health_code_update();
3056 if (last_seen_data_fd
== pollfd
) {
3063 /* Process data connection. */
3064 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3065 /* Fetch the poll data. */
3066 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3067 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3068 struct relay_connection
*data_conn
;
3070 health_code_update();
3073 /* No activity for this FD (poll implementation). */
3077 /* Skip the command pipe. It's handled in the first loop. */
3078 if (pollfd
== relay_conn_pipe
[0]) {
3082 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3084 /* Skip it. Might be removed before. */
3087 if (data_conn
->type
== RELAY_CONTROL
) {
3088 goto put_data_connection
;
3090 assert(data_conn
->type
== RELAY_DATA
);
3092 if (revents
& LPOLLIN
) {
3093 enum relay_connection_status status
;
3095 status
= relay_process_data(data_conn
);
3096 /* Connection closed or error. */
3097 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3099 * On socket error flag the session as aborted to force
3100 * the cleanup of its stream otherwise it can leak
3101 * during the lifetime of the relayd.
3103 * This prevents situations in which streams can be
3104 * left opened because an index was received, the
3105 * control connection is closed, and the data
3106 * connection is closed (uncleanly) before the packet's
3109 * Since the data connection encountered an error,
3110 * it is okay to be conservative and close the
3111 * session right now as we can't rely on the protocol
3112 * being respected anymore.
3114 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3115 session_abort(data_conn
->session
);
3117 relay_thread_close_connection(&events
, pollfd
,
3120 * Every goto restart call sets the last seen fd where
3121 * here we don't really care since we gracefully
3122 * continue the loop after the connection is deleted.
3125 /* Keep last seen port. */
3126 last_seen_data_fd
= pollfd
;
3127 connection_put(data_conn
);
3130 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3131 relay_thread_close_connection(&events
, pollfd
,
3134 ERR("Unknown poll events %u for data sock %d",
3137 put_data_connection
:
3138 connection_put(data_conn
);
3140 last_seen_data_fd
= -1;
3143 /* Normal exit, no error */
3148 /* Cleanup reamaining connection object. */
3150 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3153 health_code_update();
3155 session_abort(destroy_conn
->session
);
3158 * No need to grab another ref, because we own
3161 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3166 lttng_poll_clean(&events
);
3168 lttng_ht_destroy(relay_connections_ht
);
3169 relay_connections_ht_error
:
3170 /* Close relay conn pipes */
3171 utils_close_pipe(relay_conn_pipe
);
3173 DBG("Thread exited with error");
3175 DBG("Worker thread cleanup complete");
3179 ERR("Health error occurred in %s", __func__
);
3181 health_unregister(health_relayd
);
3182 rcu_unregister_thread();
3183 lttng_relay_stop_threads();
3188 * Create the relay command pipe to wake thread_manage_apps.
3189 * Closed in cleanup().
3191 static int create_relay_conn_pipe(void)
3195 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3203 int main(int argc
, char **argv
)
3205 int ret
= 0, retval
= 0;
3208 /* Parse environment variables */
3209 parse_env_options();
3213 * Command line arguments overwrite environment.
3216 if (set_options(argc
, argv
)) {
3221 if (set_signal_handler()) {
3226 relayd_config_log();
3228 if (opt_print_version
) {
3234 /* Try to create directory if -o, --output is specified. */
3235 if (opt_output_path
) {
3236 if (*opt_output_path
!= '/') {
3237 ERR("Please specify an absolute path for -o, --output PATH");
3242 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3245 ERR("Unable to create %s", opt_output_path
);
3252 if (opt_daemon
|| opt_background
) {
3255 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3263 * We are in the child. Make sure all other file
3264 * descriptors are closed, in case we are called with
3265 * more opened file descriptors than the standard ones.
3267 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3273 if (opt_working_directory
) {
3274 ret
= utils_change_working_dir(opt_working_directory
);
3276 ERR("Changing working directory");
3281 /* Initialize thread health monitoring */
3282 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3283 if (!health_relayd
) {
3284 PERROR("health_app_create error");
3286 goto exit_health_app_create
;
3289 /* Create thread quit pipe */
3290 if (init_thread_quit_pipe()) {
3292 goto exit_init_data
;
3295 /* Setup the thread apps communication pipe. */
3296 if (create_relay_conn_pipe()) {
3298 goto exit_init_data
;
3301 /* Init relay command queue. */
3302 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3304 /* Initialize communication library */
3306 lttcomm_inet_init();
3308 /* tables of sessions indexed by session ID */
3309 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3312 goto exit_init_data
;
3315 /* tables of streams indexed by stream ID */
3316 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3317 if (!relay_streams_ht
) {
3319 goto exit_init_data
;
3322 /* tables of streams indexed by stream ID */
3323 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3324 if (!viewer_streams_ht
) {
3326 goto exit_init_data
;
3329 ret
= utils_create_pipe(health_quit_pipe
);
3332 goto exit_health_quit_pipe
;
3335 /* Create thread to manage the client socket */
3336 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3337 thread_manage_health
, (void *) NULL
);
3340 PERROR("pthread_create health");
3342 goto exit_health_thread
;
3345 /* Setup the dispatcher thread */
3346 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3347 relay_thread_dispatcher
, (void *) NULL
);
3350 PERROR("pthread_create dispatcher");
3352 goto exit_dispatcher_thread
;
3355 /* Setup the worker thread */
3356 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3357 relay_thread_worker
, NULL
);
3360 PERROR("pthread_create worker");
3362 goto exit_worker_thread
;
3365 /* Setup the listener thread */
3366 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3367 relay_thread_listener
, (void *) NULL
);
3370 PERROR("pthread_create listener");
3372 goto exit_listener_thread
;
3375 ret
= relayd_live_create(live_uri
);
3377 ERR("Starting live viewer threads");
3383 * This is where we start awaiting program completion (e.g. through
3384 * signal that asks threads to teardown).
3387 ret
= relayd_live_join();
3393 ret
= pthread_join(listener_thread
, &status
);
3396 PERROR("pthread_join listener_thread");
3400 exit_listener_thread
:
3401 ret
= pthread_join(worker_thread
, &status
);
3404 PERROR("pthread_join worker_thread");
3409 ret
= pthread_join(dispatcher_thread
, &status
);
3412 PERROR("pthread_join dispatcher_thread");
3415 exit_dispatcher_thread
:
3417 ret
= pthread_join(health_thread
, &status
);
3420 PERROR("pthread_join health_thread");
3425 utils_close_pipe(health_quit_pipe
);
3426 exit_health_quit_pipe
:
3429 health_app_destroy(health_relayd
);
3430 exit_health_app_create
:
3433 * Wait for all pending call_rcu work to complete before tearing
3434 * down data structures. call_rcu worker may be trying to
3435 * perform lookups in those structures.
3440 /* Ensure all prior call_rcu are done. */