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/align.h>
58 #include <common/config/session-config.h>
59 #include <common/dynamic-buffer.h>
60 #include <common/buffer-view.h>
61 #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 static const char *help_msg
=
79 #ifdef LTTNG_EMBED_HELP
80 #include <lttng-relayd.8.h>
86 enum relay_connection_status
{
87 RELAY_CONNECTION_STATUS_OK
,
88 /* An error occurred while processing an event on the connection. */
89 RELAY_CONNECTION_STATUS_ERROR
,
90 /* Connection closed/shutdown cleanly. */
91 RELAY_CONNECTION_STATUS_CLOSED
,
94 /* command line options */
95 char *opt_output_path
;
96 static int opt_daemon
, opt_background
;
97 static int opt_allow_clear
= 1;
100 * We need to wait for listener and live listener threads, as well as
101 * health check thread, before being ready to signal readiness.
103 #define NR_LTTNG_RELAY_READY 3
104 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
106 /* Size of receive buffer. */
107 #define RECV_DATA_BUFFER_SIZE 65536
108 #define FILE_COPY_BUFFER_SIZE 65536
110 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
111 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
113 static struct lttng_uri
*control_uri
;
114 static struct lttng_uri
*data_uri
;
115 static struct lttng_uri
*live_uri
;
117 const char *progname
;
119 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
120 static int tracing_group_name_override
;
122 const char * const config_section_name
= "relayd";
125 * Quit pipe for all threads. This permits a single cancellation point
126 * for all threads when receiving an event on the pipe.
128 int thread_quit_pipe
[2] = { -1, -1 };
131 * This pipe is used to inform the worker thread that a command is queued and
132 * ready to be processed.
134 static int relay_conn_pipe
[2] = { -1, -1 };
136 /* Shared between threads */
137 static int dispatch_thread_exit
;
139 static pthread_t listener_thread
;
140 static pthread_t dispatcher_thread
;
141 static pthread_t worker_thread
;
142 static pthread_t health_thread
;
145 * last_relay_stream_id_lock protects last_relay_stream_id increment
146 * atomicity on 32-bit architectures.
148 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
149 static uint64_t last_relay_stream_id
;
152 * Relay command queue.
154 * The relay_thread_listener and relay_thread_dispatcher communicate with this
157 static struct relay_conn_queue relay_conn_queue
;
159 /* Global relay stream hash table. */
160 struct lttng_ht
*relay_streams_ht
;
162 /* Global relay viewer stream hash table. */
163 struct lttng_ht
*viewer_streams_ht
;
165 /* Global relay sessions hash table. */
166 struct lttng_ht
*sessions_ht
;
168 /* Relayd health monitoring */
169 struct health_app
*health_relayd
;
171 static struct option long_options
[] = {
172 { "control-port", 1, 0, 'C', },
173 { "data-port", 1, 0, 'D', },
174 { "live-port", 1, 0, 'L', },
175 { "daemonize", 0, 0, 'd', },
176 { "background", 0, 0, 'b', },
177 { "group", 1, 0, 'g', },
178 { "help", 0, 0, 'h', },
179 { "output", 1, 0, 'o', },
180 { "verbose", 0, 0, 'v', },
181 { "config", 1, 0, 'f' },
182 { "version", 0, 0, 'V' },
183 { "disallow-clear", 0, 0, 'x' },
187 static const char *config_ignore_options
[] = { "help", "config", "version" };
190 * Take an option from the getopt output and set it in the right variable to be
193 * Return 0 on success else a negative value.
195 static int set_option(int opt
, const char *arg
, const char *optname
)
201 fprintf(stderr
, "option %s", optname
);
203 fprintf(stderr
, " with arg %s\n", arg
);
207 if (lttng_is_setuid_setgid()) {
208 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
209 "-C, --control-port");
211 ret
= uri_parse(arg
, &control_uri
);
213 ERR("Invalid control URI specified");
216 if (control_uri
->port
== 0) {
217 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
222 if (lttng_is_setuid_setgid()) {
223 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
226 ret
= uri_parse(arg
, &data_uri
);
228 ERR("Invalid data URI specified");
231 if (data_uri
->port
== 0) {
232 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
237 if (lttng_is_setuid_setgid()) {
238 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
241 ret
= uri_parse(arg
, &live_uri
);
243 ERR("Invalid live URI specified");
246 if (live_uri
->port
== 0) {
247 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
258 if (lttng_is_setuid_setgid()) {
259 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
262 tracing_group_name
= strdup(arg
);
263 if (tracing_group_name
== NULL
) {
268 tracing_group_name_override
= 1;
272 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
274 ERR("Cannot show --help for `lttng-relayd`");
279 fprintf(stdout
, "%s\n", VERSION
);
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 ret
= asprintf(&opt_output_path
, "%s", arg
);
289 PERROR("asprintf opt_output_path");
295 /* Verbose level can increase using multiple -v */
297 lttng_opt_verbose
= config_parse_value(arg
);
299 /* Only 3 level of verbosity (-vvv). */
300 if (lttng_opt_verbose
< 3) {
301 lttng_opt_verbose
+= 1;
310 /* Unknown option or other error.
311 * Error is printed by getopt, just return */
324 * config_entry_handler_cb used to handle options read from a config file.
325 * See config_entry_handler_cb comment in common/config/session-config.h for the
326 * return value conventions.
328 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
332 if (!entry
|| !entry
->name
|| !entry
->value
) {
337 /* Check if the option is to be ignored */
338 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
339 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
344 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
345 /* Ignore if entry name is not fully matched. */
346 if (strcmp(entry
->name
, long_options
[i
].name
)) {
351 * If the option takes no argument on the command line,
352 * we have to check if the value is "true". We support
353 * non-zero numeric values, true, on and yes.
355 if (!long_options
[i
].has_arg
) {
356 ret
= config_parse_value(entry
->value
);
359 WARN("Invalid configuration value \"%s\" for option %s",
360 entry
->value
, entry
->name
);
362 /* False, skip boolean config option. */
367 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
371 WARN("Unrecognized option \"%s\" in daemon configuration file.",
378 static int set_options(int argc
, char **argv
)
380 int c
, ret
= 0, option_index
= 0, retval
= 0;
381 int orig_optopt
= optopt
, orig_optind
= optind
;
382 char *default_address
, *optstring
;
383 const char *config_path
= NULL
;
384 const char *value
= NULL
;
386 optstring
= utils_generate_optstring(long_options
,
387 sizeof(long_options
) / sizeof(struct option
));
393 /* Check for the --config option */
395 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
396 &option_index
)) != -1) {
400 } else if (c
!= 'f') {
404 if (lttng_is_setuid_setgid()) {
405 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
408 config_path
= utils_expand_path(optarg
);
410 ERR("Failed to resolve path: %s", optarg
);
415 ret
= config_get_section_entries(config_path
, config_section_name
,
416 config_entry_handler
, NULL
);
419 ERR("Invalid configuration option at line %i", ret
);
425 /* Reset getopt's global state */
426 optopt
= orig_optopt
;
427 optind
= orig_optind
;
429 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
434 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
441 /* assign default values */
442 if (control_uri
== NULL
) {
443 ret
= asprintf(&default_address
,
444 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
445 DEFAULT_NETWORK_CONTROL_PORT
);
447 PERROR("asprintf default data address");
452 ret
= uri_parse(default_address
, &control_uri
);
453 free(default_address
);
455 ERR("Invalid control URI specified");
460 if (data_uri
== NULL
) {
461 ret
= asprintf(&default_address
,
462 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
463 DEFAULT_NETWORK_DATA_PORT
);
465 PERROR("asprintf default data address");
470 ret
= uri_parse(default_address
, &data_uri
);
471 free(default_address
);
473 ERR("Invalid data URI specified");
478 if (live_uri
== NULL
) {
479 ret
= asprintf(&default_address
,
480 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
481 DEFAULT_NETWORK_VIEWER_PORT
);
483 PERROR("asprintf default viewer control address");
488 ret
= uri_parse(default_address
, &live_uri
);
489 free(default_address
);
491 ERR("Invalid viewer control URI specified");
497 if (opt_allow_clear
) {
498 /* Check if env variable exists. */
499 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
501 ret
= config_parse_value(value
);
503 ERR("Invalid value for %s specified", DEFAULT_LTTNG_RELAYD_DISALLOW_CLEAR_ENV
);
507 opt_allow_clear
= !ret
;
516 static void print_global_objects(void)
518 rcu_register_thread();
520 print_viewer_streams();
521 print_relay_streams();
524 rcu_unregister_thread();
530 static void relayd_cleanup(void)
532 print_global_objects();
536 if (viewer_streams_ht
)
537 lttng_ht_destroy(viewer_streams_ht
);
538 if (relay_streams_ht
)
539 lttng_ht_destroy(relay_streams_ht
);
541 lttng_ht_destroy(sessions_ht
);
543 /* free the dynamically allocated opt_output_path */
544 free(opt_output_path
);
546 /* Close thread quit pipes */
547 utils_close_pipe(thread_quit_pipe
);
549 uri_free(control_uri
);
551 /* Live URI is freed in the live thread. */
553 if (tracing_group_name_override
) {
554 free((void *) tracing_group_name
);
559 * Write to writable pipe used to notify a thread.
561 static int notify_thread_pipe(int wpipe
)
565 ret
= lttng_write(wpipe
, "!", 1);
567 PERROR("write poll pipe");
575 static int notify_health_quit_pipe(int *pipe
)
579 ret
= lttng_write(pipe
[1], "4", 1);
581 PERROR("write relay health quit");
590 * Stop all relayd and relayd-live threads.
592 int lttng_relay_stop_threads(void)
596 /* Stopping all threads */
597 DBG("Terminating all threads");
598 if (notify_thread_pipe(thread_quit_pipe
[1])) {
599 ERR("write error on thread quit pipe");
603 if (notify_health_quit_pipe(health_quit_pipe
)) {
604 ERR("write error on health quit pipe");
607 /* Dispatch thread */
608 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
609 futex_nto1_wake(&relay_conn_queue
.futex
);
611 if (relayd_live_stop()) {
612 ERR("Error stopping live threads");
619 * Signal handler for the daemon
621 * Simply stop all worker threads, leaving main() return gracefully after
622 * joining all threads and calling cleanup().
624 static void sighandler(int sig
)
628 DBG("SIGINT caught");
629 if (lttng_relay_stop_threads()) {
630 ERR("Error stopping threads");
634 DBG("SIGTERM caught");
635 if (lttng_relay_stop_threads()) {
636 ERR("Error stopping threads");
640 CMM_STORE_SHARED(recv_child_signal
, 1);
648 * Setup signal handler for :
649 * SIGINT, SIGTERM, SIGPIPE
651 static int set_signal_handler(void)
657 if ((ret
= sigemptyset(&sigset
)) < 0) {
658 PERROR("sigemptyset");
665 sa
.sa_handler
= sighandler
;
666 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
671 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
676 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
681 sa
.sa_handler
= SIG_IGN
;
682 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
687 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
692 void lttng_relay_notify_ready(void)
694 /* Notify the parent of the fork() process that we are ready. */
695 if (opt_daemon
|| opt_background
) {
696 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
697 kill(child_ppid
, SIGUSR1
);
703 * Init thread quit pipe.
705 * Return -1 on error or 0 if all pipes are created.
707 static int init_thread_quit_pipe(void)
711 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
717 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
719 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
723 if (events
== NULL
|| size
== 0) {
728 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
734 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
746 * Check if the thread quit pipe was triggered.
748 * Return 1 if it was triggered else 0;
750 static int check_thread_quit_pipe(int fd
, uint32_t events
)
752 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
760 * Create and init socket from uri.
762 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
765 struct lttcomm_sock
*sock
= NULL
;
767 sock
= lttcomm_alloc_sock_from_uri(uri
);
769 ERR("Allocating socket");
773 ret
= lttcomm_create_sock(sock
);
777 DBG("Listening on sock %d", sock
->fd
);
779 ret
= sock
->ops
->bind(sock
);
781 PERROR("Failed to bind socket");
785 ret
= sock
->ops
->listen(sock
, -1);
795 lttcomm_destroy_sock(sock
);
801 * This thread manages the listening for new connections on the network
803 static void *relay_thread_listener(void *data
)
805 int i
, ret
, pollfd
, err
= -1;
806 uint32_t revents
, nb_fd
;
807 struct lttng_poll_event events
;
808 struct lttcomm_sock
*control_sock
, *data_sock
;
810 DBG("[thread] Relay listener started");
812 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
814 health_code_update();
816 control_sock
= relay_socket_create(control_uri
);
818 goto error_sock_control
;
821 data_sock
= relay_socket_create(data_uri
);
823 goto error_sock_relay
;
827 * Pass 3 as size here for the thread quit pipe, control and
830 ret
= create_thread_poll_set(&events
, 3);
832 goto error_create_poll
;
835 /* Add the control socket */
836 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
841 /* Add the data socket */
842 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
847 lttng_relay_notify_ready();
849 if (testpoint(relayd_thread_listener
)) {
850 goto error_testpoint
;
854 health_code_update();
856 DBG("Listener accepting connections");
860 ret
= lttng_poll_wait(&events
, -1);
864 * Restart interrupted system call.
866 if (errno
== EINTR
) {
874 DBG("Relay new connection received");
875 for (i
= 0; i
< nb_fd
; i
++) {
876 health_code_update();
878 /* Fetch once the poll data */
879 revents
= LTTNG_POLL_GETEV(&events
, i
);
880 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
884 * No activity for this FD (poll
890 /* Thread quit pipe has been closed. Killing thread. */
891 ret
= check_thread_quit_pipe(pollfd
, revents
);
897 if (revents
& LPOLLIN
) {
899 * A new connection is requested, therefore a
900 * sessiond/consumerd connection is allocated in
901 * this thread, enqueued to a global queue and
902 * dequeued (and freed) in the worker thread.
905 struct relay_connection
*new_conn
;
906 struct lttcomm_sock
*newsock
;
907 enum connection_type type
;
909 if (pollfd
== data_sock
->fd
) {
911 newsock
= data_sock
->ops
->accept(data_sock
);
912 DBG("Relay data connection accepted, socket %d",
915 assert(pollfd
== control_sock
->fd
);
916 type
= RELAY_CONTROL
;
917 newsock
= control_sock
->ops
->accept(control_sock
);
918 DBG("Relay control connection accepted, socket %d",
922 PERROR("accepting sock");
926 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
929 PERROR("setsockopt inet");
930 lttcomm_destroy_sock(newsock
);
934 ret
= socket_apply_keep_alive_config(newsock
->fd
);
936 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
938 lttcomm_destroy_sock(newsock
);
942 new_conn
= connection_create(newsock
, type
);
944 lttcomm_destroy_sock(newsock
);
948 /* Enqueue request for the dispatcher thread. */
949 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
953 * Wake the dispatch queue futex.
954 * Implicit memory barrier with the
955 * exchange in cds_wfcq_enqueue.
957 futex_nto1_wake(&relay_conn_queue
.futex
);
958 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
959 ERR("socket poll error");
962 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
972 lttng_poll_clean(&events
);
974 if (data_sock
->fd
>= 0) {
975 ret
= data_sock
->ops
->close(data_sock
);
980 lttcomm_destroy_sock(data_sock
);
982 if (control_sock
->fd
>= 0) {
983 ret
= control_sock
->ops
->close(control_sock
);
988 lttcomm_destroy_sock(control_sock
);
992 ERR("Health error occurred in %s", __func__
);
994 health_unregister(health_relayd
);
995 DBG("Relay listener thread cleanup complete");
996 lttng_relay_stop_threads();
1001 * This thread manages the dispatching of the requests to worker threads
1003 static void *relay_thread_dispatcher(void *data
)
1007 struct cds_wfcq_node
*node
;
1008 struct relay_connection
*new_conn
= NULL
;
1010 DBG("[thread] Relay dispatcher started");
1012 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1014 if (testpoint(relayd_thread_dispatcher
)) {
1015 goto error_testpoint
;
1018 health_code_update();
1021 health_code_update();
1023 /* Atomically prepare the queue futex */
1024 futex_nto1_prepare(&relay_conn_queue
.futex
);
1026 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1031 health_code_update();
1033 /* Dequeue commands */
1034 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1035 &relay_conn_queue
.tail
);
1037 DBG("Woken up but nothing in the relay command queue");
1038 /* Continue thread execution */
1041 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1043 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1046 * Inform worker thread of the new request. This
1047 * call is blocking so we can be assured that
1048 * the data will be read at some point in time
1049 * or wait to the end of the world :)
1051 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1053 PERROR("write connection pipe");
1054 connection_put(new_conn
);
1057 } while (node
!= NULL
);
1059 /* Futex wait on queue. Blocking call on futex() */
1060 health_poll_entry();
1061 futex_nto1_wait(&relay_conn_queue
.futex
);
1065 /* Normal exit, no error */
1072 ERR("Health error occurred in %s", __func__
);
1074 health_unregister(health_relayd
);
1075 DBG("Dispatch thread dying");
1076 lttng_relay_stop_threads();
1081 * Set index data from the control port to a given index object.
1083 static int set_index_control_data(struct relay_index
*index
,
1084 struct lttcomm_relayd_index
*data
,
1085 struct relay_connection
*conn
)
1087 struct ctf_packet_index index_data
;
1090 * The index on disk is encoded in big endian.
1092 index_data
.packet_size
= htobe64(data
->packet_size
);
1093 index_data
.content_size
= htobe64(data
->content_size
);
1094 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1095 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1096 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1097 index_data
.stream_id
= htobe64(data
->stream_id
);
1099 if (conn
->minor
>= 8) {
1100 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1101 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1104 return relay_index_set_data(index
, &index_data
);
1107 static bool session_streams_have_index(const struct relay_session
*session
)
1109 return session
->minor
>= 4 && !session
->snapshot
;
1113 * Handle the RELAYD_CREATE_SESSION command.
1115 * On success, send back the session id or else return a negative value.
1117 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1118 struct relay_connection
*conn
,
1119 const struct lttng_buffer_view
*payload
)
1123 struct relay_session
*session
;
1124 struct lttcomm_relayd_status_session reply
;
1125 char session_name
[LTTNG_NAME_MAX
];
1126 char hostname
[LTTNG_HOST_NAME_MAX
];
1127 uint32_t live_timer
= 0;
1128 bool snapshot
= false;
1130 memset(session_name
, 0, LTTNG_NAME_MAX
);
1131 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1133 memset(&reply
, 0, sizeof(reply
));
1135 if (conn
->minor
< 4) {
1136 /* From 2.1 to 2.3 */
1138 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1139 /* From 2.4 to 2.10 */
1140 ret
= cmd_create_session_2_4(payload
, session_name
,
1141 hostname
, &live_timer
, &snapshot
);
1143 /* From 2.11 to ... */
1144 ret
= cmd_create_session_2_11(payload
, session_name
,
1145 hostname
, &live_timer
, &snapshot
);
1152 session
= session_create(session_name
, hostname
, live_timer
,
1153 snapshot
, conn
->major
, conn
->minor
);
1158 assert(!conn
->session
);
1159 conn
->session
= session
;
1160 DBG("Created session %" PRIu64
, session
->id
);
1162 reply
.session_id
= htobe64(session
->id
);
1166 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1168 reply
.ret_code
= htobe32(LTTNG_OK
);
1171 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1172 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1173 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1182 * When we have received all the streams and the metadata for a channel,
1183 * we make them visible to the viewer threads.
1185 static void publish_connection_local_streams(struct relay_connection
*conn
)
1187 struct relay_stream
*stream
;
1188 struct relay_session
*session
= conn
->session
;
1191 * We publish all streams belonging to a session atomically wrt
1194 pthread_mutex_lock(&session
->lock
);
1196 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1198 stream_publish(stream
);
1203 * Inform the viewer that there are new streams in the session.
1205 if (session
->viewer_attached
) {
1206 uatomic_set(&session
->new_streams
, 1);
1208 pthread_mutex_unlock(&session
->lock
);
1212 * relay_add_stream: allocate a new stream for a session
1214 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1215 struct relay_connection
*conn
,
1216 const struct lttng_buffer_view
*payload
)
1220 struct relay_session
*session
= conn
->session
;
1221 struct relay_stream
*stream
= NULL
;
1222 struct lttcomm_relayd_status_stream reply
;
1223 struct ctf_trace
*trace
= NULL
;
1224 uint64_t stream_handle
= -1ULL;
1225 char *path_name
= NULL
, *channel_name
= NULL
;
1226 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1227 struct relay_stream_chunk_id stream_chunk_id
= { 0 };
1229 if (!session
|| !conn
->version_check_done
) {
1230 ERR("Trying to add a stream before version check");
1232 goto end_no_session
;
1235 if (session
->minor
== 1) {
1237 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1239 } else if (session
->minor
> 1 && session
->minor
< 11) {
1240 /* From 2.2 to 2.10 */
1241 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1242 &channel_name
, &tracefile_size
, &tracefile_count
);
1244 /* From 2.11 to ... */
1245 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1246 &channel_name
, &tracefile_size
, &tracefile_count
,
1247 &stream_chunk_id
.value
);
1248 stream_chunk_id
.is_set
= true;
1255 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1259 /* This stream here has one reference on the trace. */
1261 pthread_mutex_lock(&last_relay_stream_id_lock
);
1262 stream_handle
= ++last_relay_stream_id
;
1263 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1265 /* We pass ownership of path_name and channel_name. */
1266 stream
= stream_create(trace
, stream_handle
, path_name
,
1267 channel_name
, tracefile_size
, tracefile_count
,
1270 channel_name
= NULL
;
1273 * Streams are the owners of their trace. Reference to trace is
1274 * kept within stream_create().
1276 ctf_trace_put(trace
);
1279 memset(&reply
, 0, sizeof(reply
));
1280 reply
.handle
= htobe64(stream_handle
);
1282 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1284 reply
.ret_code
= htobe32(LTTNG_OK
);
1287 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1288 sizeof(struct lttcomm_relayd_status_stream
), 0);
1289 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1290 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1302 * relay_close_stream: close a specific stream
1304 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1305 struct relay_connection
*conn
,
1306 const struct lttng_buffer_view
*payload
)
1310 struct relay_session
*session
= conn
->session
;
1311 struct lttcomm_relayd_close_stream stream_info
;
1312 struct lttcomm_relayd_generic_reply reply
;
1313 struct relay_stream
*stream
;
1315 DBG("Close stream received");
1317 if (!session
|| !conn
->version_check_done
) {
1318 ERR("Trying to close a stream before version check");
1320 goto end_no_session
;
1323 if (payload
->size
< sizeof(stream_info
)) {
1324 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1325 sizeof(stream_info
), payload
->size
);
1327 goto end_no_session
;
1329 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1330 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1331 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1333 stream
= stream_get_by_id(stream_info
.stream_id
);
1340 * Set last_net_seq_num before the close flag. Required by data
1343 pthread_mutex_lock(&stream
->lock
);
1344 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1345 pthread_mutex_unlock(&stream
->lock
);
1348 * This is one of the conditions which may trigger a stream close
1349 * with the others being:
1350 * 1) A close command is received for a stream
1351 * 2) The control connection owning the stream is closed
1352 * 3) We have received all of the stream's data _after_ a close
1355 try_stream_close(stream
);
1356 if (stream
->is_metadata
) {
1357 struct relay_viewer_stream
*vstream
;
1359 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1361 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1363 * Since all the metadata has been sent to the
1364 * viewer and that we have a request to close
1365 * its stream, we can safely teardown the
1366 * corresponding metadata viewer stream.
1368 viewer_stream_put(vstream
);
1370 /* Put local reference. */
1371 viewer_stream_put(vstream
);
1378 memset(&reply
, 0, sizeof(reply
));
1380 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1382 reply
.ret_code
= htobe32(LTTNG_OK
);
1384 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1385 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1386 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1387 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1397 * relay_reset_metadata: reset a metadata stream
1400 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1401 struct relay_connection
*conn
,
1402 const struct lttng_buffer_view
*payload
)
1406 struct relay_session
*session
= conn
->session
;
1407 struct lttcomm_relayd_reset_metadata stream_info
;
1408 struct lttcomm_relayd_generic_reply reply
;
1409 struct relay_stream
*stream
;
1411 DBG("Reset metadata received");
1413 if (!session
|| !conn
->version_check_done
) {
1414 ERR("Trying to reset a metadata stream before version check");
1416 goto end_no_session
;
1419 if (payload
->size
< sizeof(stream_info
)) {
1420 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1421 sizeof(stream_info
), payload
->size
);
1423 goto end_no_session
;
1425 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1426 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1427 stream_info
.version
= be64toh(stream_info
.version
);
1429 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1431 /* Unsupported for live sessions for now. */
1432 if (session
->live_timer
!= 0) {
1437 stream
= stream_get_by_id(stream_info
.stream_id
);
1442 pthread_mutex_lock(&stream
->lock
);
1443 if (!stream
->is_metadata
) {
1448 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1449 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1450 &stream
->stream_fd
->fd
);
1452 ERR("Failed to rotate metadata file %s of channel %s",
1453 stream
->path_name
, stream
->channel_name
);
1458 pthread_mutex_unlock(&stream
->lock
);
1462 memset(&reply
, 0, sizeof(reply
));
1464 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1466 reply
.ret_code
= htobe32(LTTNG_OK
);
1468 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1469 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1470 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1471 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1481 * relay_unknown_command: send -1 if received unknown command
1483 static void relay_unknown_command(struct relay_connection
*conn
)
1485 struct lttcomm_relayd_generic_reply reply
;
1488 memset(&reply
, 0, sizeof(reply
));
1489 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1490 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1491 if (send_ret
< sizeof(reply
)) {
1492 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1497 * relay_start: send an acknowledgment to the client to tell if we are
1498 * ready to receive data. We are ready if a session is established.
1500 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1501 struct relay_connection
*conn
,
1502 const struct lttng_buffer_view
*payload
)
1506 struct lttcomm_relayd_generic_reply reply
;
1507 struct relay_session
*session
= conn
->session
;
1510 DBG("Trying to start the streaming without a session established");
1511 ret
= htobe32(LTTNG_ERR_UNK
);
1514 memset(&reply
, 0, sizeof(reply
));
1515 reply
.ret_code
= htobe32(LTTNG_OK
);
1516 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1518 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1519 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1528 * Append padding to the file pointed by the file descriptor fd.
1530 static int write_padding_to_file(int fd
, uint32_t size
)
1539 zeros
= zmalloc(size
);
1540 if (zeros
== NULL
) {
1541 PERROR("zmalloc zeros for padding");
1546 ret
= lttng_write(fd
, zeros
, size
);
1548 PERROR("write padding to file");
1558 * Close the current index file if it is open, and create a new one.
1560 * Return 0 on success, -1 on error.
1563 int create_rotate_index_file(struct relay_stream
*stream
,
1564 const char *stream_path
)
1567 uint32_t major
, minor
;
1569 /* Put ref on previous index_file. */
1570 if (stream
->index_file
) {
1571 lttng_index_file_put(stream
->index_file
);
1572 stream
->index_file
= NULL
;
1574 major
= stream
->trace
->session
->major
;
1575 minor
= stream
->trace
->session
->minor
;
1576 stream
->index_file
= lttng_index_file_create(stream_path
,
1577 stream
->channel_name
,
1578 -1, -1, stream
->tracefile_size
,
1579 tracefile_array_get_file_index_head(stream
->tfa
),
1580 lttng_to_index_major(major
, minor
),
1581 lttng_to_index_minor(major
, minor
));
1582 if (!stream
->index_file
) {
1594 int do_rotate_stream_data(struct relay_stream
*stream
)
1598 DBG("Rotating stream %" PRIu64
" data file",
1599 stream
->stream_handle
);
1600 /* Perform the stream rotation. */
1601 ret
= utils_rotate_stream_file(stream
->path_name
,
1602 stream
->channel_name
, stream
->tracefile_size
,
1603 stream
->tracefile_count
, -1,
1604 -1, stream
->stream_fd
->fd
,
1605 NULL
, &stream
->stream_fd
->fd
);
1607 ERR("Rotating stream output file");
1610 stream
->tracefile_size_current
= 0;
1611 stream
->pos_after_last_complete_data_index
= 0;
1612 stream
->data_rotated
= true;
1614 if (stream
->data_rotated
&& stream
->index_rotated
) {
1615 /* Rotation completed; reset its state. */
1616 DBG("Rotation completed for stream %" PRIu64
,
1617 stream
->stream_handle
);
1618 stream
->rotate_at_seq_num
= -1ULL;
1619 stream
->data_rotated
= false;
1620 stream
->index_rotated
= false;
1627 * If too much data has been written in a tracefile before we received the
1628 * rotation command, we have to move the excess data to the new tracefile and
1629 * perform the rotation. This can happen because the control and data
1630 * connections are separate, the indexes as well as the commands arrive from
1631 * the control connection and we have no control over the order so we could be
1632 * in a situation where too much data has been received on the data connection
1633 * before the rotation command on the control connection arrives.
1636 int rotate_truncate_stream(struct relay_stream
*stream
)
1640 uint64_t diff
, pos
= 0;
1641 char buf
[FILE_COPY_BUFFER_SIZE
];
1643 assert(!stream
->is_metadata
);
1645 assert(stream
->tracefile_size_current
>
1646 stream
->pos_after_last_complete_data_index
);
1647 diff
= stream
->tracefile_size_current
-
1648 stream
->pos_after_last_complete_data_index
;
1650 /* Create the new tracefile. */
1651 new_fd
= utils_create_stream_file(stream
->path_name
,
1652 stream
->channel_name
,
1653 stream
->tracefile_size
, stream
->tracefile_count
,
1654 /* uid */ -1, /* gid */ -1, /* suffix */ NULL
);
1656 ERR("Failed to create new stream file at path %s for channel %s",
1657 stream
->path_name
, stream
->channel_name
);
1663 * Rewind the current tracefile to the position at which the rotation
1664 * should have occurred.
1666 lseek_ret
= lseek(stream
->stream_fd
->fd
,
1667 stream
->pos_after_last_complete_data_index
, SEEK_SET
);
1668 if (lseek_ret
< 0) {
1669 PERROR("seek truncate stream");
1674 /* Move data from the old file to the new file. */
1675 while (pos
< diff
) {
1676 uint64_t count
, bytes_left
;
1679 bytes_left
= diff
- pos
;
1680 count
= bytes_left
> sizeof(buf
) ? sizeof(buf
) : bytes_left
;
1681 assert(count
<= SIZE_MAX
);
1683 io_ret
= lttng_read(stream
->stream_fd
->fd
, buf
, count
);
1684 if (io_ret
< (ssize_t
) count
) {
1685 char error_string
[256];
1687 snprintf(error_string
, sizeof(error_string
),
1688 "Failed to read %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1689 count
, stream
->stream_fd
->fd
, io_ret
);
1691 PERROR("%s", error_string
);
1693 ERR("%s", error_string
);
1699 io_ret
= lttng_write(new_fd
, buf
, count
);
1700 if (io_ret
< (ssize_t
) count
) {
1701 char error_string
[256];
1703 snprintf(error_string
, sizeof(error_string
),
1704 "Failed to write %" PRIu64
" bytes from fd %i in rotate_truncate_stream(), returned %zi",
1705 count
, new_fd
, io_ret
);
1707 PERROR("%s", error_string
);
1709 ERR("%s", error_string
);
1718 /* Truncate the file to get rid of the excess data. */
1719 ret
= ftruncate(stream
->stream_fd
->fd
,
1720 stream
->pos_after_last_complete_data_index
);
1722 PERROR("ftruncate");
1726 ret
= close(stream
->stream_fd
->fd
);
1728 PERROR("Closing tracefile");
1733 * Update the offset and FD of all the eventual indexes created by the
1734 * data connection before the rotation command arrived.
1736 ret
= relay_index_switch_all_files(stream
);
1738 ERR("Failed to rotate index file");
1742 stream
->stream_fd
->fd
= new_fd
;
1743 stream
->tracefile_size_current
= diff
;
1744 stream
->pos_after_last_complete_data_index
= 0;
1745 stream
->rotate_at_seq_num
= -1ULL;
1754 * Check if a stream's index file should be rotated (for session rotation).
1755 * Must be called with the stream lock held.
1757 * Return 0 on success, a negative value on error.
1760 int try_rotate_stream_index(struct relay_stream
*stream
)
1764 if (stream
->rotate_at_seq_num
== -1ULL) {
1765 /* No rotation expected. */
1769 if (stream
->index_rotated
) {
1770 /* Rotation of the index has already occurred. */
1774 if (stream
->prev_index_seq
== -1ULL ||
1775 stream
->prev_index_seq
< stream
->rotate_at_seq_num
) {
1776 DBG("Stream %" PRIu64
" index not yet ready for rotation (rotate_at_seq_num = %" PRIu64
", prev_index_seq = %" PRIu64
")",
1777 stream
->stream_handle
,
1778 stream
->rotate_at_seq_num
,
1779 stream
->prev_index_seq
);
1781 } else if (stream
->prev_index_seq
!= stream
->rotate_at_seq_num
) {
1783 * Unexpected, protocol error/bug.
1784 * It could mean that we received a rotation position
1785 * that is in the past.
1787 ERR("Stream %" PRIu64
" index is in an inconsistent state (rotate_at_seq_num = %" PRIu64
", prev_data_seq = %" PRIu64
", prev_index_seq = %" PRIu64
")",
1788 stream
->stream_handle
,
1789 stream
->rotate_at_seq_num
,
1790 stream
->prev_data_seq
,
1791 stream
->prev_index_seq
);
1795 DBG("Rotating stream %" PRIu64
" index file",
1796 stream
->stream_handle
);
1797 ret
= create_rotate_index_file(stream
, stream
->path_name
);
1798 stream
->index_rotated
= true;
1800 if (stream
->data_rotated
&& stream
->index_rotated
) {
1801 /* Rotation completed; reset its state. */
1802 DBG("Rotation completed for stream %" PRIu64
,
1803 stream
->stream_handle
);
1804 stream
->rotate_at_seq_num
= -1ULL;
1805 stream
->data_rotated
= false;
1806 stream
->index_rotated
= false;
1815 * Check if a stream's data file (as opposed to index) should be rotated
1816 * (for session rotation).
1817 * Must be called with the stream lock held.
1819 * Return 0 on success, a negative value on error.
1822 int try_rotate_stream_data(struct relay_stream
*stream
)
1826 if (stream
->rotate_at_seq_num
== -1ULL) {
1827 /* No rotation expected. */
1831 if (stream
->data_rotated
) {
1832 /* Rotation of the data file has already occurred. */
1836 if (stream
->prev_data_seq
== -1ULL ||
1837 stream
->prev_data_seq
< stream
->rotate_at_seq_num
) {
1838 DBG("Stream %" PRIu64
" not yet ready for rotation (rotate_at_seq_num = %" PRIu64
", prev_data_seq = %" PRIu64
")",
1839 stream
->stream_handle
,
1840 stream
->rotate_at_seq_num
,
1841 stream
->prev_data_seq
);
1843 } else if (stream
->prev_data_seq
> stream
->rotate_at_seq_num
) {
1845 * prev_data_seq is checked here since indexes and rotation
1846 * commands are serialized with respect to each other.
1848 DBG("Rotation after too much data has been written in tracefile "
1849 "for stream %" PRIu64
", need to truncate before "
1850 "rotating", stream
->stream_handle
);
1851 ret
= rotate_truncate_stream(stream
);
1853 ERR("Failed to truncate stream");
1856 } else if (stream
->prev_data_seq
!= stream
->rotate_at_seq_num
) {
1858 * Unexpected, protocol error/bug.
1859 * It could mean that we received a rotation position
1860 * that is in the past.
1862 ERR("Stream %" PRIu64
" data is in an inconsistent state (rotate_at_seq_num = %" PRIu64
", prev_data_seq = %" PRIu64
")",
1863 stream
->stream_handle
,
1864 stream
->rotate_at_seq_num
,
1865 stream
->prev_data_seq
);
1869 ret
= do_rotate_stream_data(stream
);
1877 * relay_recv_metadata: receive the metadata for the session.
1879 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1880 struct relay_connection
*conn
,
1881 const struct lttng_buffer_view
*payload
)
1885 struct relay_session
*session
= conn
->session
;
1886 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1887 struct relay_stream
*metadata_stream
;
1888 uint64_t metadata_payload_size
;
1891 ERR("Metadata sent before version check");
1896 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1897 ERR("Incorrect data size");
1901 metadata_payload_size
= recv_hdr
->data_size
-
1902 sizeof(struct lttcomm_relayd_metadata_payload
);
1904 memcpy(&metadata_payload_header
, payload
->data
,
1905 sizeof(metadata_payload_header
));
1906 metadata_payload_header
.stream_id
= be64toh(
1907 metadata_payload_header
.stream_id
);
1908 metadata_payload_header
.padding_size
= be32toh(
1909 metadata_payload_header
.padding_size
);
1911 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1912 if (!metadata_stream
) {
1917 pthread_mutex_lock(&metadata_stream
->lock
);
1919 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1920 payload
->data
+ sizeof(metadata_payload_header
),
1921 metadata_payload_size
);
1922 if (size_ret
< metadata_payload_size
) {
1923 ERR("Relay error writing metadata on file");
1928 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1929 metadata_payload_header
.padding_size
);
1930 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1935 metadata_stream
->metadata_received
+=
1936 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1937 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1938 metadata_stream
->metadata_received
);
1940 ret
= try_rotate_stream_data(metadata_stream
);
1946 pthread_mutex_unlock(&metadata_stream
->lock
);
1947 stream_put(metadata_stream
);
1953 * relay_send_version: send relayd version number
1955 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1956 struct relay_connection
*conn
,
1957 const struct lttng_buffer_view
*payload
)
1961 struct lttcomm_relayd_version reply
, msg
;
1962 bool compatible
= true;
1964 conn
->version_check_done
= true;
1966 /* Get version from the other side. */
1967 if (payload
->size
< sizeof(msg
)) {
1968 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1969 sizeof(msg
), payload
->size
);
1974 memcpy(&msg
, payload
->data
, sizeof(msg
));
1975 msg
.major
= be32toh(msg
.major
);
1976 msg
.minor
= be32toh(msg
.minor
);
1978 memset(&reply
, 0, sizeof(reply
));
1979 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1980 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1982 /* Major versions must be the same */
1983 if (reply
.major
!= msg
.major
) {
1984 DBG("Incompatible major versions (%u vs %u), deleting session",
1985 reply
.major
, msg
.major
);
1989 conn
->major
= reply
.major
;
1990 /* We adapt to the lowest compatible version */
1991 if (reply
.minor
<= msg
.minor
) {
1992 conn
->minor
= reply
.minor
;
1994 conn
->minor
= msg
.minor
;
1997 reply
.major
= htobe32(reply
.major
);
1998 reply
.minor
= htobe32(reply
.minor
);
1999 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2001 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2002 ERR("Failed to send \"send version\" command reply (ret = %zd)",
2015 DBG("Version check done using protocol %u.%u", conn
->major
,
2023 * Check for data pending for a given stream id from the session daemon.
2025 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2026 struct relay_connection
*conn
,
2027 const struct lttng_buffer_view
*payload
)
2029 struct relay_session
*session
= conn
->session
;
2030 struct lttcomm_relayd_data_pending msg
;
2031 struct lttcomm_relayd_generic_reply reply
;
2032 struct relay_stream
*stream
;
2035 uint64_t stream_seq
;
2037 DBG("Data pending command received");
2039 if (!session
|| !conn
->version_check_done
) {
2040 ERR("Trying to check for data before version check");
2042 goto end_no_session
;
2045 if (payload
->size
< sizeof(msg
)) {
2046 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
2047 sizeof(msg
), payload
->size
);
2049 goto end_no_session
;
2051 memcpy(&msg
, payload
->data
, sizeof(msg
));
2052 msg
.stream_id
= be64toh(msg
.stream_id
);
2053 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
2055 stream
= stream_get_by_id(msg
.stream_id
);
2056 if (stream
== NULL
) {
2061 pthread_mutex_lock(&stream
->lock
);
2063 if (session_streams_have_index(session
)) {
2065 * Ensure that both the index and stream data have been
2066 * flushed up to the requested point.
2068 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2070 stream_seq
= stream
->prev_data_seq
;
2072 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
2073 ", prev_index_seq %" PRIu64
2074 ", and last_seq %" PRIu64
, msg
.stream_id
,
2075 stream
->prev_data_seq
, stream
->prev_index_seq
,
2076 msg
.last_net_seq_num
);
2078 /* Avoid wrapping issue */
2079 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
2080 /* Data has in fact been written and is NOT pending */
2083 /* Data still being streamed thus pending */
2087 stream
->data_pending_check_done
= true;
2088 pthread_mutex_unlock(&stream
->lock
);
2093 memset(&reply
, 0, sizeof(reply
));
2094 reply
.ret_code
= htobe32(ret
);
2095 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2096 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2097 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
2107 * Wait for the control socket to reach a quiescent state.
2109 * Note that for now, when receiving this command from the session
2110 * daemon, this means that every subsequent commands or data received on
2111 * the control socket has been handled. So, this is why we simply return
2114 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
2115 struct relay_connection
*conn
,
2116 const struct lttng_buffer_view
*payload
)
2120 struct relay_stream
*stream
;
2121 struct lttcomm_relayd_quiescent_control msg
;
2122 struct lttcomm_relayd_generic_reply reply
;
2124 DBG("Checking quiescent state on control socket");
2126 if (!conn
->session
|| !conn
->version_check_done
) {
2127 ERR("Trying to check for data before version check");
2129 goto end_no_session
;
2132 if (payload
->size
< sizeof(msg
)) {
2133 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
2134 sizeof(msg
), payload
->size
);
2136 goto end_no_session
;
2138 memcpy(&msg
, payload
->data
, sizeof(msg
));
2139 msg
.stream_id
= be64toh(msg
.stream_id
);
2141 stream
= stream_get_by_id(msg
.stream_id
);
2145 pthread_mutex_lock(&stream
->lock
);
2146 stream
->data_pending_check_done
= true;
2147 pthread_mutex_unlock(&stream
->lock
);
2149 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
2152 memset(&reply
, 0, sizeof(reply
));
2153 reply
.ret_code
= htobe32(LTTNG_OK
);
2154 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2155 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2156 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
2168 * Initialize a data pending command. This means that a consumer is about
2169 * to ask for data pending for each stream it holds. Simply iterate over
2170 * all streams of a session and set the data_pending_check_done flag.
2172 * This command returns to the client a LTTNG_OK code.
2174 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2175 struct relay_connection
*conn
,
2176 const struct lttng_buffer_view
*payload
)
2180 struct lttng_ht_iter iter
;
2181 struct lttcomm_relayd_begin_data_pending msg
;
2182 struct lttcomm_relayd_generic_reply reply
;
2183 struct relay_stream
*stream
;
2188 DBG("Init streams for data pending");
2190 if (!conn
->session
|| !conn
->version_check_done
) {
2191 ERR("Trying to check for data before version check");
2193 goto end_no_session
;
2196 if (payload
->size
< sizeof(msg
)) {
2197 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
2198 sizeof(msg
), payload
->size
);
2200 goto end_no_session
;
2202 memcpy(&msg
, payload
->data
, sizeof(msg
));
2203 msg
.session_id
= be64toh(msg
.session_id
);
2206 * Iterate over all streams to set the begin data pending flag.
2207 * For now, the streams are indexed by stream handle so we have
2208 * to iterate over all streams to find the one associated with
2209 * the right session_id.
2212 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2214 if (!stream_get(stream
)) {
2217 if (stream
->trace
->session
->id
== msg
.session_id
) {
2218 pthread_mutex_lock(&stream
->lock
);
2219 stream
->data_pending_check_done
= false;
2220 pthread_mutex_unlock(&stream
->lock
);
2221 DBG("Set begin data pending flag to stream %" PRIu64
,
2222 stream
->stream_handle
);
2228 memset(&reply
, 0, sizeof(reply
));
2229 /* All good, send back reply. */
2230 reply
.ret_code
= htobe32(LTTNG_OK
);
2232 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2233 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2234 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2246 * End data pending command. This will check, for a given session id, if
2247 * each stream associated with it has its data_pending_check_done flag
2248 * set. If not, this means that the client lost track of the stream but
2249 * the data is still being streamed on our side. In this case, we inform
2250 * the client that data is in flight.
2252 * Return to the client if there is data in flight or not with a ret_code.
2254 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2255 struct relay_connection
*conn
,
2256 const struct lttng_buffer_view
*payload
)
2260 struct lttng_ht_iter iter
;
2261 struct lttcomm_relayd_end_data_pending msg
;
2262 struct lttcomm_relayd_generic_reply reply
;
2263 struct relay_stream
*stream
;
2264 uint32_t is_data_inflight
= 0;
2266 DBG("End data pending command");
2268 if (!conn
->session
|| !conn
->version_check_done
) {
2269 ERR("Trying to check for data before version check");
2271 goto end_no_session
;
2274 if (payload
->size
< sizeof(msg
)) {
2275 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2276 sizeof(msg
), payload
->size
);
2278 goto end_no_session
;
2280 memcpy(&msg
, payload
->data
, sizeof(msg
));
2281 msg
.session_id
= be64toh(msg
.session_id
);
2284 * Iterate over all streams to see if the begin data pending
2288 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2290 if (!stream_get(stream
)) {
2293 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2297 pthread_mutex_lock(&stream
->lock
);
2298 if (!stream
->data_pending_check_done
) {
2299 uint64_t stream_seq
;
2301 if (session_streams_have_index(conn
->session
)) {
2303 * Ensure that both the index and stream data have been
2304 * flushed up to the requested point.
2306 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2308 stream_seq
= stream
->prev_data_seq
;
2310 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2311 is_data_inflight
= 1;
2312 DBG("Data is still in flight for stream %" PRIu64
,
2313 stream
->stream_handle
);
2314 pthread_mutex_unlock(&stream
->lock
);
2319 pthread_mutex_unlock(&stream
->lock
);
2324 memset(&reply
, 0, sizeof(reply
));
2325 /* All good, send back reply. */
2326 reply
.ret_code
= htobe32(is_data_inflight
);
2328 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2329 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2330 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2342 * Receive an index for a specific stream.
2344 * Return 0 on success else a negative value.
2346 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2347 struct relay_connection
*conn
,
2348 const struct lttng_buffer_view
*payload
)
2352 struct relay_session
*session
= conn
->session
;
2353 struct lttcomm_relayd_index index_info
;
2354 struct relay_index
*index
;
2355 struct lttcomm_relayd_generic_reply reply
;
2356 struct relay_stream
*stream
;
2361 DBG("Relay receiving index");
2363 if (!session
|| !conn
->version_check_done
) {
2364 ERR("Trying to close a stream before version check");
2366 goto end_no_session
;
2369 msg_len
= lttcomm_relayd_index_len(
2370 lttng_to_index_major(conn
->major
, conn
->minor
),
2371 lttng_to_index_minor(conn
->major
, conn
->minor
));
2372 if (payload
->size
< msg_len
) {
2373 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2374 msg_len
, payload
->size
);
2376 goto end_no_session
;
2378 memcpy(&index_info
, payload
->data
, msg_len
);
2379 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2380 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2381 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2382 index_info
.content_size
= be64toh(index_info
.content_size
);
2383 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2384 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2385 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2386 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2388 if (conn
->minor
>= 8) {
2389 index_info
.stream_instance_id
=
2390 be64toh(index_info
.stream_instance_id
);
2391 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2394 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2396 ERR("stream_get_by_id not found");
2400 pthread_mutex_lock(&stream
->lock
);
2402 /* Live beacon handling */
2403 if (index_info
.packet_size
== 0) {
2404 DBG("Received live beacon for stream %" PRIu64
,
2405 stream
->stream_handle
);
2408 * Only flag a stream inactive when it has already
2409 * received data and no indexes are in flight.
2411 if (stream
->index_received_seqcount
> 0
2412 && stream
->indexes_in_flight
== 0) {
2413 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2416 goto end_stream_put
;
2418 stream
->beacon_ts_end
= -1ULL;
2421 if (stream
->ctf_stream_id
== -1ULL) {
2422 stream
->ctf_stream_id
= index_info
.stream_id
;
2424 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2427 ERR("relay_index_get_by_id_or_create index NULL");
2428 goto end_stream_put
;
2430 if (set_index_control_data(index
, &index_info
, conn
)) {
2431 ERR("set_index_control_data error");
2432 relay_index_put(index
);
2434 goto end_stream_put
;
2436 ret
= relay_index_try_flush(index
);
2438 tracefile_array_commit_seq(stream
->tfa
);
2439 stream
->index_received_seqcount
++;
2440 stream
->pos_after_last_complete_data_index
+= index
->total_size
;
2441 stream
->prev_index_seq
= index_info
.net_seq_num
;
2443 ret
= try_rotate_stream_index(stream
);
2445 goto end_stream_put
;
2447 } else if (ret
> 0) {
2454 * relay_index_try_flush is responsible for the self-reference
2455 * put of the index object on error.
2457 ERR("relay_index_try_flush error %d", ret
);
2462 pthread_mutex_unlock(&stream
->lock
);
2467 memset(&reply
, 0, sizeof(reply
));
2469 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2471 reply
.ret_code
= htobe32(LTTNG_OK
);
2473 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2474 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2475 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2484 * Receive the streams_sent message.
2486 * Return 0 on success else a negative value.
2488 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2489 struct relay_connection
*conn
,
2490 const struct lttng_buffer_view
*payload
)
2494 struct lttcomm_relayd_generic_reply reply
;
2498 DBG("Relay receiving streams_sent");
2500 if (!conn
->session
|| !conn
->version_check_done
) {
2501 ERR("Trying to close a stream before version check");
2503 goto end_no_session
;
2507 * Publish every pending stream in the connection recv list which are
2508 * now ready to be used by the viewer.
2510 publish_connection_local_streams(conn
);
2512 memset(&reply
, 0, sizeof(reply
));
2513 reply
.ret_code
= htobe32(LTTNG_OK
);
2514 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2515 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2516 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2529 * relay_rotate_session_stream: rotate a stream to a new tracefile for the session
2530 * rotation feature (not the tracefile rotation feature).
2532 static int relay_rotate_session_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
2533 struct relay_connection
*conn
,
2534 const struct lttng_buffer_view
*payload
)
2538 struct relay_session
*session
= conn
->session
;
2539 struct lttcomm_relayd_rotate_stream stream_info
;
2540 struct lttcomm_relayd_generic_reply reply
;
2541 struct relay_stream
*stream
;
2544 struct lttng_buffer_view new_path_view
;
2546 DBG("Rotate stream received");
2548 if (!session
|| !conn
->version_check_done
) {
2549 ERR("Trying to rotate a stream before version check");
2554 if (session
->major
== 2 && session
->minor
< 11) {
2555 ERR("Unsupported feature before 2.11");
2560 header_len
= sizeof(struct lttcomm_relayd_rotate_stream
);
2562 if (payload
->size
< header_len
) {
2563 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2564 header_len
, payload
->size
);
2569 memcpy(&stream_info
, payload
->data
, header_len
);
2571 /* Convert to host */
2572 stream_info
.pathname_length
= be32toh(stream_info
.pathname_length
);
2573 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
2574 stream_info
.new_chunk_id
= be64toh(stream_info
.new_chunk_id
);
2575 stream_info
.rotate_at_seq_num
= be64toh(stream_info
.rotate_at_seq_num
);
2577 path_len
= stream_info
.pathname_length
;
2578 if (payload
->size
< header_len
+ path_len
) {
2579 ERR("Unexpected payload size in \"relay_rotate_session_stream\" including path: expected >= %zu bytes, got %zu bytes",
2580 header_len
+ path_len
, payload
->size
);
2585 /* Ensure it fits in local filename length. */
2586 if (path_len
>= LTTNG_PATH_MAX
) {
2587 ret
= -ENAMETOOLONG
;
2588 ERR("Length of relay_rotate_session_stream command's path name (%zu bytes) exceeds the maximal allowed length of %i bytes",
2589 path_len
, LTTNG_PATH_MAX
);
2593 new_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2594 stream_info
.pathname_length
);
2596 stream
= stream_get_by_id(stream_info
.stream_id
);
2602 pthread_mutex_lock(&stream
->lock
);
2605 * Update the trace path (just the folder, the stream name does not
2608 free(stream
->prev_path_name
);
2609 stream
->prev_path_name
= stream
->path_name
;
2610 stream
->path_name
= create_output_path(new_path_view
.data
);
2611 if (!stream
->path_name
) {
2612 ERR("Failed to create a new output path");
2614 goto end_stream_unlock
;
2616 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
,
2619 ERR("relay creating output directory");
2621 goto end_stream_unlock
;
2624 assert(stream
->current_chunk_id
.is_set
);
2625 stream
->current_chunk_id
.value
= stream_info
.new_chunk_id
;
2627 if (stream
->is_metadata
) {
2629 * Metadata streams have no index; consider its rotation
2632 stream
->index_rotated
= true;
2634 * The metadata stream is sent only over the control connection
2635 * so we know we have all the data to perform the stream
2638 ret
= do_rotate_stream_data(stream
);
2640 stream
->rotate_at_seq_num
= stream_info
.rotate_at_seq_num
;
2641 ret
= try_rotate_stream_data(stream
);
2643 goto end_stream_unlock
;
2646 ret
= try_rotate_stream_index(stream
);
2648 goto end_stream_unlock
;
2653 pthread_mutex_unlock(&stream
->lock
);
2656 memset(&reply
, 0, sizeof(reply
));
2658 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2660 reply
.ret_code
= htobe32(LTTNG_OK
);
2662 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2663 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2664 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2665 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2675 * relay_mkdir: Create a folder on the disk.
2677 static int relay_mkdir(const struct lttcomm_relayd_hdr
*recv_hdr
,
2678 struct relay_connection
*conn
,
2679 const struct lttng_buffer_view
*payload
)
2682 struct relay_session
*session
= conn
->session
;
2683 struct lttcomm_relayd_mkdir path_info_header
;
2684 struct lttcomm_relayd_generic_reply reply
;
2688 struct lttng_buffer_view path_view
;
2690 if (!session
|| !conn
->version_check_done
) {
2691 ERR("Trying to create a directory before version check");
2693 goto end_no_session
;
2696 if (session
->major
== 2 && session
->minor
< 11) {
2698 * This client is not supposed to use this command since
2699 * it predates its introduction.
2701 ERR("relay_mkdir command is unsupported before LTTng 2.11");
2703 goto end_no_session
;
2706 header_len
= sizeof(path_info_header
);
2707 if (payload
->size
< header_len
) {
2708 ERR("Unexpected payload size in \"relay_mkdir\": expected >= %zu bytes, got %zu bytes",
2709 header_len
, payload
->size
);
2711 goto end_no_session
;
2714 memcpy(&path_info_header
, payload
->data
, header_len
);
2716 path_info_header
.length
= be32toh(path_info_header
.length
);
2718 if (payload
->size
< header_len
+ path_info_header
.length
) {
2719 ERR("Unexpected payload size in \"relay_mkdir\" including path: expected >= %zu bytes, got %zu bytes",
2720 header_len
+ path_info_header
.length
, payload
->size
);
2722 goto end_no_session
;
2725 /* Ensure that it fits in local path length. */
2726 if (path_info_header
.length
>= LTTNG_PATH_MAX
) {
2727 ret
= -ENAMETOOLONG
;
2728 ERR("Path name argument of mkdir command (%" PRIu32
" bytes) exceeds the maximal length allowed (%d bytes)",
2729 path_info_header
.length
, LTTNG_PATH_MAX
);
2733 path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2734 path_info_header
.length
);
2736 path
= create_output_path(path_view
.data
);
2738 ERR("Failed to create output path");
2743 DBG("MKDIR command has path \"%s\", changed to \"%s\"", path_view
.data
, path
);
2744 ret
= utils_mkdir_recursive(path
, S_IRWXU
| S_IRWXG
, -1, -1);
2746 ERR("relay creating output directory");
2753 memset(&reply
, 0, sizeof(reply
));
2755 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2757 reply
.ret_code
= htobe32(LTTNG_OK
);
2759 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2760 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2761 ERR("Failed to send \"mkdir\" command reply (ret = %zd)", send_ret
);
2770 static int validate_rotate_rename_path_length(const char *path_type
,
2771 uint32_t path_length
)
2775 if (path_length
> LTTNG_PATH_MAX
) {
2776 ret
= -ENAMETOOLONG
;
2777 ERR("rotate rename \"%s\" path name length (%" PRIu32
" bytes) exceeds the allowed size of %i bytes",
2778 path_type
, path_length
, LTTNG_PATH_MAX
);
2779 } else if (path_length
== 0) {
2781 ERR("rotate rename \"%s\" path name has an illegal length of 0", path_type
);
2787 * relay_rotate_rename: rename the trace folder after a rotation is
2788 * completed. We are not closing any fd here, just moving the folder, so it
2789 * works even if data is still in-flight.
2791 static int relay_rotate_rename(const struct lttcomm_relayd_hdr
*recv_hdr
,
2792 struct relay_connection
*conn
,
2793 const struct lttng_buffer_view
*payload
)
2797 struct relay_session
*session
= conn
->session
;
2798 struct lttcomm_relayd_generic_reply reply
;
2799 struct lttcomm_relayd_rotate_rename header
;
2801 size_t received_paths_size
;
2802 char *complete_old_path
= NULL
, *complete_new_path
= NULL
;
2803 struct lttng_buffer_view old_path_view
;
2804 struct lttng_buffer_view new_path_view
;
2806 if (!session
|| !conn
->version_check_done
) {
2807 ERR("Trying to rename a trace folder before version check");
2812 if (session
->major
== 2 && session
->minor
< 11) {
2813 ERR("relay_rotate_rename command is unsupported before LTTng 2.11");
2818 header_len
= sizeof(header
);
2819 if (payload
->size
< header_len
) {
2820 ERR("Unexpected payload size in \"relay_rotate_rename\": expected >= %zu bytes, got %zu bytes",
2821 header_len
, payload
->size
);
2826 memcpy(&header
, payload
->data
, header_len
);
2828 header
.old_path_length
= be32toh(header
.old_path_length
);
2829 header
.new_path_length
= be32toh(header
.new_path_length
);
2830 received_paths_size
= header
.old_path_length
+ header
.new_path_length
;
2832 if (payload
->size
< header_len
+ received_paths_size
) {
2833 ERR("Unexpected payload size in \"relay_rotate_rename\" including paths: expected >= %zu bytes, got %zu bytes",
2834 header_len
, payload
->size
);
2839 /* Ensure the paths don't exceed their allowed size. */
2840 ret
= validate_rotate_rename_path_length("old", header
.old_path_length
);
2844 ret
= validate_rotate_rename_path_length("new", header
.new_path_length
);
2849 old_path_view
= lttng_buffer_view_from_view(payload
, header_len
,
2850 header
.old_path_length
);
2851 new_path_view
= lttng_buffer_view_from_view(payload
,
2852 header_len
+ header
.old_path_length
,
2853 header
.new_path_length
);
2855 /* Validate that both paths received are NULL terminated. */
2856 if (old_path_view
.data
[old_path_view
.size
- 1] != '\0') {
2857 ERR("relay_rotate_rename command's \"old\" path is invalid (not NULL terminated)");
2861 if (new_path_view
.data
[new_path_view
.size
- 1] != '\0') {
2862 ERR("relay_rotate_rename command's \"new\" path is invalid (not NULL terminated)");
2867 DBG("ROTATE_RENAME command has argument old path = \"%s\", new_path = \"%s\"",
2868 old_path_view
.data
, new_path_view
.data
);
2869 complete_old_path
= create_output_path(old_path_view
.data
);
2870 if (!complete_old_path
) {
2871 ERR("Failed to build old output path in rotate_rename command");
2876 complete_new_path
= create_output_path(new_path_view
.data
);
2877 if (!complete_new_path
) {
2878 ERR("Failed to build new output path in rotate_rename command");
2882 DBG("Expanded ROTATE_RENAME arguments to old path = \"%s\", new_path = \"%s\"",
2883 complete_old_path
, complete_new_path
);
2885 ret
= utils_mkdir_recursive(complete_new_path
, S_IRWXU
| S_IRWXG
,
2888 ERR("Failed to mkdir() rotate_rename's \"new\" output directory at \"%s\"",
2894 * If a domain has not yet created its channel, the domain-specific
2895 * folder might not exist, but this is not an error.
2897 ret
= rename(complete_old_path
, complete_new_path
);
2898 if (ret
< 0 && errno
!= ENOENT
) {
2899 PERROR("Renaming chunk in rotate_rename command from \"%s\" to \"%s\"",
2900 complete_old_path
, complete_new_path
);
2906 memset(&reply
, 0, sizeof(reply
));
2908 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2910 reply
.ret_code
= htobe32(LTTNG_OK
);
2912 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2914 if (send_ret
< sizeof(reply
)) {
2915 ERR("Failed to send \"rotate rename\" command reply (ret = %zd)",
2921 free(complete_old_path
);
2922 free(complete_new_path
);
2927 * Check if all the streams in the session have completed the last rotation.
2928 * The chunk_id value is used to distinguish the cases where a stream was
2929 * closed on the consumerd before the rotation started but it still active on
2930 * the relayd, and the case where a stream appeared on the consumerd/relayd
2931 * after the last rotation started (in that case, it is already writing in the
2932 * new chunk folder).
2935 int relay_rotate_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2936 struct relay_connection
*conn
,
2937 const struct lttng_buffer_view
*payload
)
2939 struct relay_session
*session
= conn
->session
;
2940 struct lttcomm_relayd_rotate_pending msg
;
2941 struct lttcomm_relayd_rotate_pending_reply reply
;
2942 struct lttng_ht_iter iter
;
2943 struct relay_stream
*stream
;
2947 bool rotate_pending
= false;
2949 DBG("Rotate pending command received");
2951 if (!session
|| !conn
->version_check_done
) {
2952 ERR("Trying to check for data before version check");
2957 if (session
->major
== 2 && session
->minor
< 11) {
2958 ERR("Unsupported feature before 2.11");
2963 if (payload
->size
< sizeof(msg
)) {
2964 ERR("Unexpected payload size in \"relay_rotate_pending\": expected >= %zu bytes, got %zu bytes",
2965 sizeof(msg
), payload
->size
);
2970 memcpy(&msg
, payload
->data
, sizeof(msg
));
2972 chunk_id
= be64toh(msg
.chunk_id
);
2974 DBG("Evaluating rotate pending for session \"%s\" and chunk id %" PRIu64
,
2975 session
->session_name
, chunk_id
);
2978 * Iterate over all the streams in the session and check if they are
2979 * still waiting for data to perform their rotation.
2982 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2984 if (!stream_get(stream
)) {
2987 if (stream
->trace
->session
!= session
) {
2991 pthread_mutex_lock(&stream
->lock
);
2992 if (stream
->rotate_at_seq_num
!= -1ULL) {
2993 /* We have not yet performed the rotation. */
2994 rotate_pending
= true;
2995 DBG("Stream %" PRIu64
" is still rotating",
2996 stream
->stream_handle
);
2997 } else if (stream
->current_chunk_id
.value
<= chunk_id
) {
2999 * Stream closed on the consumer but still active on the
3002 rotate_pending
= true;
3003 DBG("Stream %" PRIu64
" did not exist on the consumer "
3004 "when the last rotation started, but is"
3005 "still waiting for data before getting"
3007 stream
->stream_handle
);
3009 pthread_mutex_unlock(&stream
->lock
);
3011 if (rotate_pending
) {
3018 memset(&reply
, 0, sizeof(reply
));
3019 reply
.generic
.ret_code
= htobe32((uint32_t) LTTNG_OK
);
3020 reply
.is_pending
= (uint8_t) !!rotate_pending
;
3021 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
3023 if (send_ret
< (ssize_t
) sizeof(reply
)) {
3024 ERR("Failed to send \"rotate pending\" command reply (ret = %zd)",
3033 #define DBG_CMD(cmd_name, conn) \
3034 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
3036 static int relay_process_control_command(struct relay_connection
*conn
,
3037 const struct lttcomm_relayd_hdr
*header
,
3038 const struct lttng_buffer_view
*payload
)
3042 switch (header
->cmd
) {
3043 case RELAYD_CREATE_SESSION
:
3044 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
3045 ret
= relay_create_session(header
, conn
, payload
);
3047 case RELAYD_ADD_STREAM
:
3048 DBG_CMD("RELAYD_ADD_STREAM", conn
);
3049 ret
= relay_add_stream(header
, conn
, payload
);
3051 case RELAYD_START_DATA
:
3052 DBG_CMD("RELAYD_START_DATA", conn
);
3053 ret
= relay_start(header
, conn
, payload
);
3055 case RELAYD_SEND_METADATA
:
3056 DBG_CMD("RELAYD_SEND_METADATA", conn
);
3057 ret
= relay_recv_metadata(header
, conn
, payload
);
3059 case RELAYD_VERSION
:
3060 DBG_CMD("RELAYD_VERSION", conn
);
3061 ret
= relay_send_version(header
, conn
, payload
);
3063 case RELAYD_CLOSE_STREAM
:
3064 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
3065 ret
= relay_close_stream(header
, conn
, payload
);
3067 case RELAYD_DATA_PENDING
:
3068 DBG_CMD("RELAYD_DATA_PENDING", conn
);
3069 ret
= relay_data_pending(header
, conn
, payload
);
3071 case RELAYD_QUIESCENT_CONTROL
:
3072 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
3073 ret
= relay_quiescent_control(header
, conn
, payload
);
3075 case RELAYD_BEGIN_DATA_PENDING
:
3076 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
3077 ret
= relay_begin_data_pending(header
, conn
, payload
);
3079 case RELAYD_END_DATA_PENDING
:
3080 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
3081 ret
= relay_end_data_pending(header
, conn
, payload
);
3083 case RELAYD_SEND_INDEX
:
3084 DBG_CMD("RELAYD_SEND_INDEX", conn
);
3085 ret
= relay_recv_index(header
, conn
, payload
);
3087 case RELAYD_STREAMS_SENT
:
3088 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
3089 ret
= relay_streams_sent(header
, conn
, payload
);
3091 case RELAYD_RESET_METADATA
:
3092 DBG_CMD("RELAYD_RESET_METADATA", conn
);
3093 ret
= relay_reset_metadata(header
, conn
, payload
);
3095 case RELAYD_ROTATE_STREAM
:
3096 DBG_CMD("RELAYD_ROTATE_STREAM", conn
);
3097 ret
= relay_rotate_session_stream(header
, conn
, payload
);
3099 case RELAYD_ROTATE_RENAME
:
3100 DBG_CMD("RELAYD_ROTATE_RENAME", conn
);
3101 ret
= relay_rotate_rename(header
, conn
, payload
);
3103 case RELAYD_ROTATE_PENDING
:
3104 DBG_CMD("RELAYD_ROTATE_PENDING", conn
);
3105 ret
= relay_rotate_pending(header
, conn
, payload
);
3108 DBG_CMD("RELAYD_MKDIR", conn
);
3109 ret
= relay_mkdir(header
, conn
, payload
);
3111 case RELAYD_UPDATE_SYNC_INFO
:
3113 ERR("Received unknown command (%u)", header
->cmd
);
3114 relay_unknown_command(conn
);
3123 static enum relay_connection_status
relay_process_control_receive_payload(
3124 struct relay_connection
*conn
)
3127 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3128 struct lttng_dynamic_buffer
*reception_buffer
=
3129 &conn
->protocol
.ctrl
.reception_buffer
;
3130 struct ctrl_connection_state_receive_payload
*state
=
3131 &conn
->protocol
.ctrl
.state
.receive_payload
;
3132 struct lttng_buffer_view payload_view
;
3134 if (state
->left_to_receive
== 0) {
3135 /* Short-circuit for payload-less commands. */
3136 goto reception_complete
;
3139 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3140 reception_buffer
->data
+ state
->received
,
3141 state
->left_to_receive
, MSG_DONTWAIT
);
3143 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3144 PERROR("Unable to receive command payload on sock %d",
3146 status
= RELAY_CONNECTION_STATUS_ERROR
;
3149 } else if (ret
== 0) {
3150 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3151 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3156 assert(ret
<= state
->left_to_receive
);
3158 state
->left_to_receive
-= ret
;
3159 state
->received
+= ret
;
3161 if (state
->left_to_receive
> 0) {
3163 * Can't transition to the protocol's next state, wait to
3164 * receive the rest of the header.
3166 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3167 state
->received
, state
->left_to_receive
,
3173 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
3174 conn
->sock
->fd
, state
->received
);
3176 * The payload required to process the command has been received.
3177 * A view to the reception buffer is forwarded to the various
3178 * commands and the state of the control is reset on success.
3180 * Commands are responsible for sending their reply to the peer.
3182 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
3184 ret
= relay_process_control_command(conn
,
3185 &state
->header
, &payload_view
);
3187 status
= RELAY_CONNECTION_STATUS_ERROR
;
3191 ret
= connection_reset_protocol_state(conn
);
3193 status
= RELAY_CONNECTION_STATUS_ERROR
;
3199 static enum relay_connection_status
relay_process_control_receive_header(
3200 struct relay_connection
*conn
)
3203 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3204 struct lttcomm_relayd_hdr header
;
3205 struct lttng_dynamic_buffer
*reception_buffer
=
3206 &conn
->protocol
.ctrl
.reception_buffer
;
3207 struct ctrl_connection_state_receive_header
*state
=
3208 &conn
->protocol
.ctrl
.state
.receive_header
;
3210 assert(state
->left_to_receive
!= 0);
3212 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3213 reception_buffer
->data
+ state
->received
,
3214 state
->left_to_receive
, MSG_DONTWAIT
);
3216 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3217 PERROR("Unable to receive control command header on sock %d",
3219 status
= RELAY_CONNECTION_STATUS_ERROR
;
3222 } else if (ret
== 0) {
3223 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3224 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3229 assert(ret
<= state
->left_to_receive
);
3231 state
->left_to_receive
-= ret
;
3232 state
->received
+= ret
;
3234 if (state
->left_to_receive
> 0) {
3236 * Can't transition to the protocol's next state, wait to
3237 * receive the rest of the header.
3239 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3240 state
->received
, state
->left_to_receive
,
3245 /* Transition to next state: receiving the command's payload. */
3246 conn
->protocol
.ctrl
.state_id
=
3247 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3248 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3249 header
.circuit_id
= be64toh(header
.circuit_id
);
3250 header
.data_size
= be64toh(header
.data_size
);
3251 header
.cmd
= be32toh(header
.cmd
);
3252 header
.cmd_version
= be32toh(header
.cmd_version
);
3253 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3254 &header
, sizeof(header
));
3256 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3257 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3260 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3261 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3263 status
= RELAY_CONNECTION_STATUS_ERROR
;
3267 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3269 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3270 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3273 status
= RELAY_CONNECTION_STATUS_ERROR
;
3277 if (header
.data_size
== 0) {
3279 * Manually invoke the next state as the poll loop
3280 * will not wake-up to allow us to proceed further.
3282 status
= relay_process_control_receive_payload(conn
);
3289 * Process the commands received on the control socket
3291 static enum relay_connection_status
relay_process_control(
3292 struct relay_connection
*conn
)
3294 enum relay_connection_status status
;
3296 switch (conn
->protocol
.ctrl
.state_id
) {
3297 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3298 status
= relay_process_control_receive_header(conn
);
3300 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3301 status
= relay_process_control_receive_payload(conn
);
3304 ERR("Unknown control connection protocol state encountered.");
3312 * Handle index for a data stream.
3314 * Called with the stream lock held.
3316 * Return 0 on success else a negative value.
3318 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
3319 bool rotate_index
, bool *flushed
, uint64_t total_size
)
3322 uint64_t data_offset
;
3323 struct relay_index
*index
;
3325 /* Get data offset because we are about to update the index. */
3326 data_offset
= htobe64(stream
->tracefile_size_current
);
3328 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
3329 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
3332 * Lookup for an existing index for that stream id/sequence
3333 * number. If it exists, the control thread has already received the
3334 * data for it, thus we need to write it to disk.
3336 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
3342 if (rotate_index
|| !stream
->index_file
) {
3343 const char *stream_path
;
3346 * The data connection creates the stream's first index file.
3348 * This can happen _after_ a ROTATE_STREAM command. In
3349 * other words, the data of the first packet of this stream
3350 * can be received after a ROTATE_STREAM command.
3352 * The ROTATE_STREAM command changes the stream's path_name
3353 * to point to the "next" chunk. If a rotation is pending for
3354 * this stream, as indicated by "rotate_at_seq_num != -1ULL",
3355 * it means that we are still receiving data that belongs in the
3356 * stream's former path.
3358 * In this very specific case, we must ensure that the index
3359 * file is created in the streams's former path,
3362 * All other rotations beyond the first one are not affected
3363 * by this problem since the actual rotation operation creates
3364 * the new chunk's index file.
3366 stream_path
= stream
->rotate_at_seq_num
== -1ULL ?
3368 stream
->prev_path_name
;
3370 ret
= create_rotate_index_file(stream
, stream_path
);
3372 ERR("Failed to rotate index");
3373 /* Put self-ref for this index due to error. */
3374 relay_index_put(index
);
3380 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
3382 /* Put self-ref for this index due to error. */
3383 relay_index_put(index
);
3388 ret
= relay_index_try_flush(index
);
3390 tracefile_array_commit_seq(stream
->tfa
);
3391 stream
->index_received_seqcount
++;
3393 } else if (ret
> 0) {
3394 index
->total_size
= total_size
;
3401 * relay_index_try_flush is responsible for the self-reference
3402 * put of the index object on error.
3404 ERR("relay_index_try_flush error %d", ret
);
3411 static enum relay_connection_status
relay_process_data_receive_header(
3412 struct relay_connection
*conn
)
3415 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3416 struct data_connection_state_receive_header
*state
=
3417 &conn
->protocol
.data
.state
.receive_header
;
3418 struct lttcomm_relayd_data_hdr header
;
3419 struct relay_stream
*stream
;
3421 assert(state
->left_to_receive
!= 0);
3423 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3424 state
->header_reception_buffer
+ state
->received
,
3425 state
->left_to_receive
, MSG_DONTWAIT
);
3427 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3428 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3429 status
= RELAY_CONNECTION_STATUS_ERROR
;
3432 } else if (ret
== 0) {
3433 /* Orderly shutdown. Not necessary to print an error. */
3434 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3435 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3440 assert(ret
<= state
->left_to_receive
);
3442 state
->left_to_receive
-= ret
;
3443 state
->received
+= ret
;
3445 if (state
->left_to_receive
> 0) {
3447 * Can't transition to the protocol's next state, wait to
3448 * receive the rest of the header.
3450 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3451 state
->received
, state
->left_to_receive
,
3456 /* Transition to next state: receiving the payload. */
3457 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3459 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3460 header
.circuit_id
= be64toh(header
.circuit_id
);
3461 header
.stream_id
= be64toh(header
.stream_id
);
3462 header
.data_size
= be32toh(header
.data_size
);
3463 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3464 header
.padding_size
= be32toh(header
.padding_size
);
3465 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3467 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3469 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3470 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3472 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3473 conn
->sock
->fd
, header
.circuit_id
,
3474 header
.stream_id
, header
.data_size
,
3475 header
.net_seq_num
, header
.padding_size
);
3477 stream
= stream_get_by_id(header
.stream_id
);
3479 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3481 /* Protocol error. */
3482 status
= RELAY_CONNECTION_STATUS_ERROR
;
3486 pthread_mutex_lock(&stream
->lock
);
3488 /* Check if a rotation is needed. */
3489 if (stream
->tracefile_size
> 0 &&
3490 (stream
->tracefile_size_current
+ header
.data_size
) >
3491 stream
->tracefile_size
) {
3492 uint64_t old_id
, new_id
;
3494 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
3495 tracefile_array_file_rotate(stream
->tfa
);
3497 /* new_id is updated by utils_rotate_stream_file. */
3500 ret
= utils_rotate_stream_file(stream
->path_name
,
3501 stream
->channel_name
, stream
->tracefile_size
,
3502 stream
->tracefile_count
, -1,
3503 -1, stream
->stream_fd
->fd
,
3504 &new_id
, &stream
->stream_fd
->fd
);
3506 ERR("Failed to rotate stream output file");
3507 status
= RELAY_CONNECTION_STATUS_ERROR
;
3508 goto end_stream_unlock
;
3512 * Reset current size because we just performed a stream
3515 stream
->tracefile_size_current
= 0;
3516 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
3520 pthread_mutex_unlock(&stream
->lock
);
3526 static enum relay_connection_status
relay_process_data_receive_payload(
3527 struct relay_connection
*conn
)
3530 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3531 struct relay_stream
*stream
;
3532 struct data_connection_state_receive_payload
*state
=
3533 &conn
->protocol
.data
.state
.receive_payload
;
3534 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3535 char data_buffer
[chunk_size
];
3536 bool partial_recv
= false;
3537 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3538 uint64_t left_to_receive
= state
->left_to_receive
;
3539 struct relay_session
*session
;
3541 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3542 state
->header
.stream_id
, state
->header
.net_seq_num
,
3543 state
->received
, left_to_receive
);
3545 stream
= stream_get_by_id(state
->header
.stream_id
);
3547 /* Protocol error. */
3548 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3549 state
->header
.stream_id
);
3550 status
= RELAY_CONNECTION_STATUS_ERROR
;
3554 pthread_mutex_lock(&stream
->lock
);
3555 session
= stream
->trace
->session
;
3556 if (!conn
->session
) {
3557 ret
= connection_set_session(conn
, session
);
3559 status
= RELAY_CONNECTION_STATUS_ERROR
;
3560 goto end_stream_unlock
;
3565 * The size of the "chunk" received on any iteration is bounded by:
3566 * - the data left to receive,
3567 * - the data immediately available on the socket,
3568 * - the on-stack data buffer
3570 while (left_to_receive
> 0 && !partial_recv
) {
3572 size_t recv_size
= min(left_to_receive
, chunk_size
);
3574 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3575 recv_size
, MSG_DONTWAIT
);
3577 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3578 PERROR("Socket %d error", conn
->sock
->fd
);
3579 status
= RELAY_CONNECTION_STATUS_ERROR
;
3581 goto end_stream_unlock
;
3582 } else if (ret
== 0) {
3583 /* No more data ready to be consumed on socket. */
3584 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3585 state
->header
.stream_id
);
3586 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3588 } else if (ret
< (int) recv_size
) {
3590 * All the data available on the socket has been
3593 partial_recv
= true;
3598 /* Write data to stream output fd. */
3599 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
3601 if (write_ret
< (ssize_t
) recv_size
) {
3602 ERR("Relay error writing data to file");
3603 status
= RELAY_CONNECTION_STATUS_ERROR
;
3604 goto end_stream_unlock
;
3607 left_to_receive
-= recv_size
;
3608 state
->received
+= recv_size
;
3609 state
->left_to_receive
= left_to_receive
;
3611 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
3612 write_ret
, stream
->stream_handle
);
3615 if (state
->left_to_receive
> 0) {
3617 * Did not receive all the data expected, wait for more data to
3618 * become available on the socket.
3620 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3621 state
->header
.stream_id
, state
->received
,
3622 state
->left_to_receive
);
3623 goto end_stream_unlock
;
3626 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
3627 state
->header
.padding_size
);
3628 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
3629 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3630 stream
->stream_handle
,
3631 state
->header
.net_seq_num
, ret
);
3632 status
= RELAY_CONNECTION_STATUS_ERROR
;
3633 goto end_stream_unlock
;
3637 if (session_streams_have_index(session
)) {
3638 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
3639 state
->rotate_index
, &index_flushed
, state
->header
.data_size
+ state
->header
.padding_size
);
3641 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3642 stream
->stream_handle
,
3643 state
->header
.net_seq_num
, ret
);
3644 status
= RELAY_CONNECTION_STATUS_ERROR
;
3645 goto end_stream_unlock
;
3649 stream
->tracefile_size_current
+= state
->header
.data_size
+
3650 state
->header
.padding_size
;
3652 if (stream
->prev_data_seq
== -1ULL) {
3655 if (index_flushed
) {
3656 stream
->pos_after_last_complete_data_index
=
3657 stream
->tracefile_size_current
;
3658 stream
->prev_index_seq
= state
->header
.net_seq_num
;
3659 ret
= try_rotate_stream_index(stream
);
3661 goto end_stream_unlock
;
3665 stream
->prev_data_seq
= state
->header
.net_seq_num
;
3668 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3669 * contents of *state which are aliased (union) to the same location as
3670 * the new state. Don't use it beyond this point.
3672 connection_reset_protocol_state(conn
);
3675 ret
= try_rotate_stream_data(stream
);
3677 status
= RELAY_CONNECTION_STATUS_ERROR
;
3678 goto end_stream_unlock
;
3682 close_requested
= stream
->close_requested
;
3683 pthread_mutex_unlock(&stream
->lock
);
3684 if (close_requested
&& left_to_receive
== 0) {
3685 try_stream_close(stream
);
3689 pthread_mutex_lock(&session
->lock
);
3690 uatomic_set(&session
->new_streams
, 1);
3691 pthread_mutex_unlock(&session
->lock
);
3700 * relay_process_data: Process the data received on the data socket
3702 static enum relay_connection_status
relay_process_data(
3703 struct relay_connection
*conn
)
3705 enum relay_connection_status status
;
3707 switch (conn
->protocol
.data
.state_id
) {
3708 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3709 status
= relay_process_data_receive_header(conn
);
3711 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3712 status
= relay_process_data_receive_payload(conn
);
3715 ERR("Unexpected data connection communication state.");
3722 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3726 (void) lttng_poll_del(events
, pollfd
);
3728 ret
= close(pollfd
);
3730 ERR("Closing pollfd %d", pollfd
);
3734 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3735 int pollfd
, struct relay_connection
*conn
)
3737 const char *type_str
;
3739 switch (conn
->type
) {
3744 type_str
= "Control";
3746 case RELAY_VIEWER_COMMAND
:
3747 type_str
= "Viewer Command";
3749 case RELAY_VIEWER_NOTIFICATION
:
3750 type_str
= "Viewer Notification";
3753 type_str
= "Unknown";
3755 cleanup_connection_pollfd(events
, pollfd
);
3756 connection_put(conn
);
3757 DBG("%s connection closed with %d", type_str
, pollfd
);
3761 * This thread does the actual work
3763 static void *relay_thread_worker(void *data
)
3765 int ret
, err
= -1, last_seen_data_fd
= -1;
3767 struct lttng_poll_event events
;
3768 struct lttng_ht
*relay_connections_ht
;
3769 struct lttng_ht_iter iter
;
3770 struct relay_connection
*destroy_conn
= NULL
;
3772 DBG("[thread] Relay worker started");
3774 rcu_register_thread();
3776 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3778 if (testpoint(relayd_thread_worker
)) {
3779 goto error_testpoint
;
3782 health_code_update();
3784 /* table of connections indexed on socket */
3785 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3786 if (!relay_connections_ht
) {
3787 goto relay_connections_ht_error
;
3790 ret
= create_thread_poll_set(&events
, 2);
3792 goto error_poll_create
;
3795 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3802 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3804 health_code_update();
3806 /* Infinite blocking call, waiting for transmission */
3807 DBG3("Relayd worker thread polling...");
3808 health_poll_entry();
3809 ret
= lttng_poll_wait(&events
, -1);
3813 * Restart interrupted system call.
3815 if (errno
== EINTR
) {
3824 * Process control. The control connection is
3825 * prioritized so we don't starve it with high
3826 * throughput tracing data on the data connection.
3828 for (i
= 0; i
< nb_fd
; i
++) {
3829 /* Fetch once the poll data */
3830 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3831 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3833 health_code_update();
3837 * No activity for this FD (poll
3843 /* Thread quit pipe has been closed. Killing thread. */
3844 ret
= check_thread_quit_pipe(pollfd
, revents
);
3850 /* Inspect the relay conn pipe for new connection */
3851 if (pollfd
== relay_conn_pipe
[0]) {
3852 if (revents
& LPOLLIN
) {
3853 struct relay_connection
*conn
;
3855 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3859 lttng_poll_add(&events
, conn
->sock
->fd
,
3860 LPOLLIN
| LPOLLRDHUP
);
3861 connection_ht_add(relay_connections_ht
, conn
);
3862 DBG("Connection socket %d added", conn
->sock
->fd
);
3863 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3864 ERR("Relay connection pipe error");
3867 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3871 struct relay_connection
*ctrl_conn
;
3873 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3874 /* If not found, there is a synchronization issue. */
3877 if (ctrl_conn
->type
== RELAY_DATA
) {
3878 if (revents
& LPOLLIN
) {
3880 * Flag the last seen data fd not deleted. It will be
3881 * used as the last seen fd if any fd gets deleted in
3884 last_notdel_data_fd
= pollfd
;
3886 goto put_ctrl_connection
;
3888 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3890 if (revents
& LPOLLIN
) {
3891 enum relay_connection_status status
;
3893 status
= relay_process_control(ctrl_conn
);
3894 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3896 * On socket error flag the session as aborted to force
3897 * the cleanup of its stream otherwise it can leak
3898 * during the lifetime of the relayd.
3900 * This prevents situations in which streams can be
3901 * left opened because an index was received, the
3902 * control connection is closed, and the data
3903 * connection is closed (uncleanly) before the packet's
3906 * Since the control connection encountered an error,
3907 * it is okay to be conservative and close the
3908 * session right now as we can't rely on the protocol
3909 * being respected anymore.
3911 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3912 session_abort(ctrl_conn
->session
);
3915 /* Clear the connection on error or close. */
3916 relay_thread_close_connection(&events
,
3921 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3922 relay_thread_close_connection(&events
,
3924 if (last_seen_data_fd
== pollfd
) {
3925 last_seen_data_fd
= last_notdel_data_fd
;
3928 ERR("Unexpected poll events %u for control sock %d",
3930 connection_put(ctrl_conn
);
3933 put_ctrl_connection
:
3934 connection_put(ctrl_conn
);
3939 * The last loop handled a control request, go back to poll to make
3940 * sure we prioritise the control socket.
3946 if (last_seen_data_fd
>= 0) {
3947 for (i
= 0; i
< nb_fd
; i
++) {
3948 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3950 health_code_update();
3952 if (last_seen_data_fd
== pollfd
) {
3959 /* Process data connection. */
3960 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3961 /* Fetch the poll data. */
3962 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3963 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3964 struct relay_connection
*data_conn
;
3966 health_code_update();
3969 /* No activity for this FD (poll implementation). */
3973 /* Skip the command pipe. It's handled in the first loop. */
3974 if (pollfd
== relay_conn_pipe
[0]) {
3978 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3980 /* Skip it. Might be removed before. */
3983 if (data_conn
->type
== RELAY_CONTROL
) {
3984 goto put_data_connection
;
3986 assert(data_conn
->type
== RELAY_DATA
);
3988 if (revents
& LPOLLIN
) {
3989 enum relay_connection_status status
;
3991 status
= relay_process_data(data_conn
);
3992 /* Connection closed or error. */
3993 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3995 * On socket error flag the session as aborted to force
3996 * the cleanup of its stream otherwise it can leak
3997 * during the lifetime of the relayd.
3999 * This prevents situations in which streams can be
4000 * left opened because an index was received, the
4001 * control connection is closed, and the data
4002 * connection is closed (uncleanly) before the packet's
4005 * Since the data connection encountered an error,
4006 * it is okay to be conservative and close the
4007 * session right now as we can't rely on the protocol
4008 * being respected anymore.
4010 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
4011 session_abort(data_conn
->session
);
4013 relay_thread_close_connection(&events
, pollfd
,
4016 * Every goto restart call sets the last seen fd where
4017 * here we don't really care since we gracefully
4018 * continue the loop after the connection is deleted.
4021 /* Keep last seen port. */
4022 last_seen_data_fd
= pollfd
;
4023 connection_put(data_conn
);
4026 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
4027 relay_thread_close_connection(&events
, pollfd
,
4030 ERR("Unknown poll events %u for data sock %d",
4033 put_data_connection
:
4034 connection_put(data_conn
);
4036 last_seen_data_fd
= -1;
4039 /* Normal exit, no error */
4044 /* Cleanup remaining connection object. */
4046 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
4049 health_code_update();
4051 session_abort(destroy_conn
->session
);
4054 * No need to grab another ref, because we own
4057 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
4062 lttng_poll_clean(&events
);
4064 lttng_ht_destroy(relay_connections_ht
);
4065 relay_connections_ht_error
:
4066 /* Close relay conn pipes */
4067 utils_close_pipe(relay_conn_pipe
);
4069 DBG("Thread exited with error");
4071 DBG("Worker thread cleanup complete");
4075 ERR("Health error occurred in %s", __func__
);
4077 health_unregister(health_relayd
);
4078 rcu_unregister_thread();
4079 lttng_relay_stop_threads();
4084 * Create the relay command pipe to wake thread_manage_apps.
4085 * Closed in cleanup().
4087 static int create_relay_conn_pipe(void)
4091 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
4099 int main(int argc
, char **argv
)
4101 int ret
= 0, retval
= 0;
4104 /* Parse arguments */
4106 if (set_options(argc
, argv
)) {
4111 if (set_signal_handler()) {
4116 if (!opt_allow_clear
) {
4117 DBG("Clear command disallowed.");
4120 /* Try to create directory if -o, --output is specified. */
4121 if (opt_output_path
) {
4122 if (*opt_output_path
!= '/') {
4123 ERR("Please specify an absolute path for -o, --output PATH");
4128 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
4131 ERR("Unable to create %s", opt_output_path
);
4138 if (opt_daemon
|| opt_background
) {
4141 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
4149 * We are in the child. Make sure all other file
4150 * descriptors are closed, in case we are called with
4151 * more opened file descriptors than the standard ones.
4153 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
4158 /* Initialize thread health monitoring */
4159 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
4160 if (!health_relayd
) {
4161 PERROR("health_app_create error");
4163 goto exit_health_app_create
;
4166 /* Create thread quit pipe */
4167 if (init_thread_quit_pipe()) {
4169 goto exit_init_data
;
4172 /* Setup the thread apps communication pipe. */
4173 if (create_relay_conn_pipe()) {
4175 goto exit_init_data
;
4178 /* Init relay command queue. */
4179 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
4181 /* Initialize communication library */
4183 lttcomm_inet_init();
4185 /* tables of sessions indexed by session ID */
4186 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4189 goto exit_init_data
;
4192 /* tables of streams indexed by stream ID */
4193 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4194 if (!relay_streams_ht
) {
4196 goto exit_init_data
;
4199 /* tables of streams indexed by stream ID */
4200 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
4201 if (!viewer_streams_ht
) {
4203 goto exit_init_data
;
4206 ret
= utils_create_pipe(health_quit_pipe
);
4209 goto exit_health_quit_pipe
;
4212 /* Create thread to manage the client socket */
4213 ret
= pthread_create(&health_thread
, default_pthread_attr(),
4214 thread_manage_health
, (void *) NULL
);
4217 PERROR("pthread_create health");
4219 goto exit_health_thread
;
4222 /* Setup the dispatcher thread */
4223 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
4224 relay_thread_dispatcher
, (void *) NULL
);
4227 PERROR("pthread_create dispatcher");
4229 goto exit_dispatcher_thread
;
4232 /* Setup the worker thread */
4233 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
4234 relay_thread_worker
, NULL
);
4237 PERROR("pthread_create worker");
4239 goto exit_worker_thread
;
4242 /* Setup the listener thread */
4243 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
4244 relay_thread_listener
, (void *) NULL
);
4247 PERROR("pthread_create listener");
4249 goto exit_listener_thread
;
4252 ret
= relayd_live_create(live_uri
);
4254 ERR("Starting live viewer threads");
4260 * This is where we start awaiting program completion (e.g. through
4261 * signal that asks threads to teardown).
4264 ret
= relayd_live_join();
4270 ret
= pthread_join(listener_thread
, &status
);
4273 PERROR("pthread_join listener_thread");
4277 exit_listener_thread
:
4278 ret
= pthread_join(worker_thread
, &status
);
4281 PERROR("pthread_join worker_thread");
4286 ret
= pthread_join(dispatcher_thread
, &status
);
4289 PERROR("pthread_join dispatcher_thread");
4292 exit_dispatcher_thread
:
4294 ret
= pthread_join(health_thread
, &status
);
4297 PERROR("pthread_join health_thread");
4302 utils_close_pipe(health_quit_pipe
);
4303 exit_health_quit_pipe
:
4306 health_app_destroy(health_relayd
);
4307 exit_health_app_create
:
4310 * Wait for all pending call_rcu work to complete before tearing
4311 * down data structures. call_rcu worker may be trying to
4312 * perform lookups in those structures.
4317 /* Ensure all prior call_rcu are done. */