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>
40 #include <urcu/rculist.h>
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/align.h>
60 #include <common/config/session-config.h>
61 #include <common/dynamic-buffer.h>
62 #include <common/buffer-view.h>
63 #include <common/string-utils/format.h>
67 #include "ctf-trace.h"
70 #include "lttng-relayd.h"
72 #include "health-relayd.h"
73 #include "testpoint.h"
74 #include "viewer-stream.h"
77 #include "connection.h"
78 #include "tracefile-array.h"
79 #include "tcp_keep_alive.h"
80 #include "sessiond-trace-chunks.h"
82 static const char *help_msg
=
83 #ifdef LTTNG_EMBED_HELP
84 #include <lttng-relayd.8.h>
90 enum relay_connection_status
{
91 RELAY_CONNECTION_STATUS_OK
,
92 /* An error occurred while processing an event on the connection. */
93 RELAY_CONNECTION_STATUS_ERROR
,
94 /* Connection closed/shutdown cleanly. */
95 RELAY_CONNECTION_STATUS_CLOSED
,
98 /* command line options */
99 char *opt_output_path
, *opt_working_directory
;
100 static int opt_daemon
, opt_background
, opt_print_version
;
103 * We need to wait for listener and live listener threads, as well as
104 * health check thread, before being ready to signal readiness.
106 #define NR_LTTNG_RELAY_READY 3
107 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
109 /* Size of receive buffer. */
110 #define RECV_DATA_BUFFER_SIZE 65536
112 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
113 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
115 static struct lttng_uri
*control_uri
;
116 static struct lttng_uri
*data_uri
;
117 static struct lttng_uri
*live_uri
;
119 const char *progname
;
121 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
122 static int tracing_group_name_override
;
124 const char * const config_section_name
= "relayd";
127 * Quit pipe for all threads. This permits a single cancellation point
128 * for all threads when receiving an event on the pipe.
130 int thread_quit_pipe
[2] = { -1, -1 };
133 * This pipe is used to inform the worker thread that a command is queued and
134 * ready to be processed.
136 static int relay_conn_pipe
[2] = { -1, -1 };
138 /* Shared between threads */
139 static int dispatch_thread_exit
;
141 static pthread_t listener_thread
;
142 static pthread_t dispatcher_thread
;
143 static pthread_t worker_thread
;
144 static pthread_t health_thread
;
147 * last_relay_stream_id_lock protects last_relay_stream_id increment
148 * atomicity on 32-bit architectures.
150 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
151 static uint64_t last_relay_stream_id
;
154 * Relay command queue.
156 * The relay_thread_listener and relay_thread_dispatcher communicate with this
159 static struct relay_conn_queue relay_conn_queue
;
161 /* Global relay stream hash table. */
162 struct lttng_ht
*relay_streams_ht
;
164 /* Global relay viewer stream hash table. */
165 struct lttng_ht
*viewer_streams_ht
;
167 /* Global relay sessions hash table. */
168 struct lttng_ht
*sessions_ht
;
170 /* Relayd health monitoring */
171 struct health_app
*health_relayd
;
173 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
175 static struct option long_options
[] = {
176 { "control-port", 1, 0, 'C', },
177 { "data-port", 1, 0, 'D', },
178 { "live-port", 1, 0, 'L', },
179 { "daemonize", 0, 0, 'd', },
180 { "background", 0, 0, 'b', },
181 { "group", 1, 0, 'g', },
182 { "help", 0, 0, 'h', },
183 { "output", 1, 0, 'o', },
184 { "verbose", 0, 0, 'v', },
185 { "config", 1, 0, 'f' },
186 { "version", 0, 0, 'V' },
187 { "working-directory", 1, 0, 'w', },
191 static const char *config_ignore_options
[] = { "help", "config", "version" };
193 static void print_version(void) {
194 fprintf(stdout
, "%s\n", VERSION
);
197 static void relayd_config_log(void)
199 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
200 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
201 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
202 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
203 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
205 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
206 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
211 * Take an option from the getopt output and set it in the right variable to be
214 * Return 0 on success else a negative value.
216 static int set_option(int opt
, const char *arg
, const char *optname
)
222 fprintf(stderr
, "option %s", optname
);
224 fprintf(stderr
, " with arg %s\n", arg
);
228 if (lttng_is_setuid_setgid()) {
229 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
230 "-C, --control-port");
232 ret
= uri_parse(arg
, &control_uri
);
234 ERR("Invalid control URI specified");
237 if (control_uri
->port
== 0) {
238 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
243 if (lttng_is_setuid_setgid()) {
244 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
247 ret
= uri_parse(arg
, &data_uri
);
249 ERR("Invalid data URI specified");
252 if (data_uri
->port
== 0) {
253 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
258 if (lttng_is_setuid_setgid()) {
259 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
262 ret
= uri_parse(arg
, &live_uri
);
264 ERR("Invalid live URI specified");
267 if (live_uri
->port
== 0) {
268 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
279 if (lttng_is_setuid_setgid()) {
280 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
283 tracing_group_name
= strdup(arg
);
284 if (tracing_group_name
== NULL
) {
289 tracing_group_name_override
= 1;
293 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
295 ERR("Cannot show --help for `lttng-relayd`");
300 opt_print_version
= 1;
303 if (lttng_is_setuid_setgid()) {
304 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
307 ret
= asprintf(&opt_output_path
, "%s", arg
);
310 PERROR("asprintf opt_output_path");
316 if (lttng_is_setuid_setgid()) {
317 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
318 "-w, --working-directory");
320 ret
= asprintf(&opt_working_directory
, "%s", arg
);
323 PERROR("asprintf opt_working_directory");
330 /* Verbose level can increase using multiple -v */
332 lttng_opt_verbose
= config_parse_value(arg
);
334 /* Only 3 level of verbosity (-vvv). */
335 if (lttng_opt_verbose
< 3) {
336 lttng_opt_verbose
+= 1;
341 /* Unknown option or other error.
342 * Error is printed by getopt, just return */
355 * config_entry_handler_cb used to handle options read from a config file.
356 * See config_entry_handler_cb comment in common/config/session-config.h for the
357 * return value conventions.
359 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
363 if (!entry
|| !entry
->name
|| !entry
->value
) {
368 /* Check if the option is to be ignored */
369 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
370 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
375 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
376 /* Ignore if entry name is not fully matched. */
377 if (strcmp(entry
->name
, long_options
[i
].name
)) {
382 * If the option takes no argument on the command line,
383 * we have to check if the value is "true". We support
384 * non-zero numeric values, true, on and yes.
386 if (!long_options
[i
].has_arg
) {
387 ret
= config_parse_value(entry
->value
);
390 WARN("Invalid configuration value \"%s\" for option %s",
391 entry
->value
, entry
->name
);
393 /* False, skip boolean config option. */
398 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
402 WARN("Unrecognized option \"%s\" in daemon configuration file.",
409 static int set_options(int argc
, char **argv
)
411 int c
, ret
= 0, option_index
= 0, retval
= 0;
412 int orig_optopt
= optopt
, orig_optind
= optind
;
413 char *default_address
, *optstring
;
414 const char *config_path
= NULL
;
416 optstring
= utils_generate_optstring(long_options
,
417 sizeof(long_options
) / sizeof(struct option
));
423 /* Check for the --config option */
425 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
426 &option_index
)) != -1) {
430 } else if (c
!= 'f') {
434 if (lttng_is_setuid_setgid()) {
435 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
438 config_path
= utils_expand_path(optarg
);
440 ERR("Failed to resolve path: %s", optarg
);
445 ret
= config_get_section_entries(config_path
, config_section_name
,
446 config_entry_handler
, NULL
);
449 ERR("Invalid configuration option at line %i", ret
);
455 /* Reset getopt's global state */
456 optopt
= orig_optopt
;
457 optind
= orig_optind
;
459 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
464 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
471 /* assign default values */
472 if (control_uri
== NULL
) {
473 ret
= asprintf(&default_address
,
474 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
475 DEFAULT_NETWORK_CONTROL_PORT
);
477 PERROR("asprintf default data address");
482 ret
= uri_parse(default_address
, &control_uri
);
483 free(default_address
);
485 ERR("Invalid control URI specified");
490 if (data_uri
== NULL
) {
491 ret
= asprintf(&default_address
,
492 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
493 DEFAULT_NETWORK_DATA_PORT
);
495 PERROR("asprintf default data address");
500 ret
= uri_parse(default_address
, &data_uri
);
501 free(default_address
);
503 ERR("Invalid data URI specified");
508 if (live_uri
== NULL
) {
509 ret
= asprintf(&default_address
,
510 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
511 DEFAULT_NETWORK_VIEWER_PORT
);
513 PERROR("asprintf default viewer control address");
518 ret
= uri_parse(default_address
, &live_uri
);
519 free(default_address
);
521 ERR("Invalid viewer control URI specified");
532 static void print_global_objects(void)
534 rcu_register_thread();
536 print_viewer_streams();
537 print_relay_streams();
540 rcu_unregister_thread();
546 static void relayd_cleanup(void)
548 print_global_objects();
552 if (viewer_streams_ht
)
553 lttng_ht_destroy(viewer_streams_ht
);
554 if (relay_streams_ht
)
555 lttng_ht_destroy(relay_streams_ht
);
557 lttng_ht_destroy(sessions_ht
);
559 free(opt_output_path
);
560 free(opt_working_directory
);
562 /* Close thread quit pipes */
563 utils_close_pipe(thread_quit_pipe
);
565 uri_free(control_uri
);
567 /* Live URI is freed in the live thread. */
569 if (tracing_group_name_override
) {
570 free((void *) tracing_group_name
);
575 * Write to writable pipe used to notify a thread.
577 static int notify_thread_pipe(int wpipe
)
581 ret
= lttng_write(wpipe
, "!", 1);
583 PERROR("write poll pipe");
591 static int notify_health_quit_pipe(int *pipe
)
595 ret
= lttng_write(pipe
[1], "4", 1);
597 PERROR("write relay health quit");
606 * Stop all relayd and relayd-live threads.
608 int lttng_relay_stop_threads(void)
612 /* Stopping all threads */
613 DBG("Terminating all threads");
614 if (notify_thread_pipe(thread_quit_pipe
[1])) {
615 ERR("write error on thread quit pipe");
619 if (notify_health_quit_pipe(health_quit_pipe
)) {
620 ERR("write error on health quit pipe");
623 /* Dispatch thread */
624 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
625 futex_nto1_wake(&relay_conn_queue
.futex
);
627 if (relayd_live_stop()) {
628 ERR("Error stopping live threads");
635 * Signal handler for the daemon
637 * Simply stop all worker threads, leaving main() return gracefully after
638 * joining all threads and calling cleanup().
640 static void sighandler(int sig
)
644 DBG("SIGINT caught");
645 if (lttng_relay_stop_threads()) {
646 ERR("Error stopping threads");
650 DBG("SIGTERM caught");
651 if (lttng_relay_stop_threads()) {
652 ERR("Error stopping threads");
656 CMM_STORE_SHARED(recv_child_signal
, 1);
664 * Setup signal handler for :
665 * SIGINT, SIGTERM, SIGPIPE
667 static int set_signal_handler(void)
673 if ((ret
= sigemptyset(&sigset
)) < 0) {
674 PERROR("sigemptyset");
681 sa
.sa_handler
= sighandler
;
682 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
687 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
692 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
697 sa
.sa_handler
= SIG_IGN
;
698 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
703 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
708 void lttng_relay_notify_ready(void)
710 /* Notify the parent of the fork() process that we are ready. */
711 if (opt_daemon
|| opt_background
) {
712 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
713 kill(child_ppid
, SIGUSR1
);
719 * Init thread quit pipe.
721 * Return -1 on error or 0 if all pipes are created.
723 static int init_thread_quit_pipe(void)
727 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
733 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
735 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
739 if (events
== NULL
|| size
== 0) {
744 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
750 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
762 * Check if the thread quit pipe was triggered.
764 * Return 1 if it was triggered else 0;
766 static int check_thread_quit_pipe(int fd
, uint32_t events
)
768 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
776 * Create and init socket from uri.
778 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
781 struct lttcomm_sock
*sock
= NULL
;
783 sock
= lttcomm_alloc_sock_from_uri(uri
);
785 ERR("Allocating socket");
789 ret
= lttcomm_create_sock(sock
);
793 DBG("Listening on sock %d", sock
->fd
);
795 ret
= sock
->ops
->bind(sock
);
797 PERROR("Failed to bind socket");
801 ret
= sock
->ops
->listen(sock
, -1);
811 lttcomm_destroy_sock(sock
);
817 * This thread manages the listening for new connections on the network
819 static void *relay_thread_listener(void *data
)
821 int i
, ret
, pollfd
, err
= -1;
822 uint32_t revents
, nb_fd
;
823 struct lttng_poll_event events
;
824 struct lttcomm_sock
*control_sock
, *data_sock
;
826 DBG("[thread] Relay listener started");
828 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
830 health_code_update();
832 control_sock
= relay_socket_create(control_uri
);
834 goto error_sock_control
;
837 data_sock
= relay_socket_create(data_uri
);
839 goto error_sock_relay
;
843 * Pass 3 as size here for the thread quit pipe, control and
846 ret
= create_thread_poll_set(&events
, 3);
848 goto error_create_poll
;
851 /* Add the control socket */
852 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
857 /* Add the data socket */
858 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
863 lttng_relay_notify_ready();
865 if (testpoint(relayd_thread_listener
)) {
866 goto error_testpoint
;
870 health_code_update();
872 DBG("Listener accepting connections");
876 ret
= lttng_poll_wait(&events
, -1);
880 * Restart interrupted system call.
882 if (errno
== EINTR
) {
890 DBG("Relay new connection received");
891 for (i
= 0; i
< nb_fd
; i
++) {
892 health_code_update();
894 /* Fetch once the poll data */
895 revents
= LTTNG_POLL_GETEV(&events
, i
);
896 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
898 /* Thread quit pipe has been closed. Killing thread. */
899 ret
= check_thread_quit_pipe(pollfd
, revents
);
905 if (revents
& LPOLLIN
) {
907 * A new connection is requested, therefore a
908 * sessiond/consumerd connection is allocated in
909 * this thread, enqueued to a global queue and
910 * dequeued (and freed) in the worker thread.
913 struct relay_connection
*new_conn
;
914 struct lttcomm_sock
*newsock
;
915 enum connection_type type
;
917 if (pollfd
== data_sock
->fd
) {
919 newsock
= data_sock
->ops
->accept(data_sock
);
920 DBG("Relay data connection accepted, socket %d",
923 assert(pollfd
== control_sock
->fd
);
924 type
= RELAY_CONTROL
;
925 newsock
= control_sock
->ops
->accept(control_sock
);
926 DBG("Relay control connection accepted, socket %d",
930 PERROR("accepting sock");
934 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
937 PERROR("setsockopt inet");
938 lttcomm_destroy_sock(newsock
);
942 ret
= socket_apply_keep_alive_config(newsock
->fd
);
944 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
946 lttcomm_destroy_sock(newsock
);
950 new_conn
= connection_create(newsock
, type
);
952 lttcomm_destroy_sock(newsock
);
956 /* Enqueue request for the dispatcher thread. */
957 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
961 * Wake the dispatch queue futex.
962 * Implicit memory barrier with the
963 * exchange in cds_wfcq_enqueue.
965 futex_nto1_wake(&relay_conn_queue
.futex
);
966 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
967 ERR("socket poll error");
970 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
980 lttng_poll_clean(&events
);
982 if (data_sock
->fd
>= 0) {
983 ret
= data_sock
->ops
->close(data_sock
);
988 lttcomm_destroy_sock(data_sock
);
990 if (control_sock
->fd
>= 0) {
991 ret
= control_sock
->ops
->close(control_sock
);
996 lttcomm_destroy_sock(control_sock
);
1000 ERR("Health error occurred in %s", __func__
);
1002 health_unregister(health_relayd
);
1003 DBG("Relay listener thread cleanup complete");
1004 lttng_relay_stop_threads();
1009 * This thread manages the dispatching of the requests to worker threads
1011 static void *relay_thread_dispatcher(void *data
)
1015 struct cds_wfcq_node
*node
;
1016 struct relay_connection
*new_conn
= NULL
;
1018 DBG("[thread] Relay dispatcher started");
1020 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1022 if (testpoint(relayd_thread_dispatcher
)) {
1023 goto error_testpoint
;
1026 health_code_update();
1029 health_code_update();
1031 /* Atomically prepare the queue futex */
1032 futex_nto1_prepare(&relay_conn_queue
.futex
);
1034 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1039 health_code_update();
1041 /* Dequeue commands */
1042 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1043 &relay_conn_queue
.tail
);
1045 DBG("Woken up but nothing in the relay command queue");
1046 /* Continue thread execution */
1049 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1051 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1054 * Inform worker thread of the new request. This
1055 * call is blocking so we can be assured that
1056 * the data will be read at some point in time
1057 * or wait to the end of the world :)
1059 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1061 PERROR("write connection pipe");
1062 connection_put(new_conn
);
1065 } while (node
!= NULL
);
1067 /* Futex wait on queue. Blocking call on futex() */
1068 health_poll_entry();
1069 futex_nto1_wait(&relay_conn_queue
.futex
);
1073 /* Normal exit, no error */
1080 ERR("Health error occurred in %s", __func__
);
1082 health_unregister(health_relayd
);
1083 DBG("Dispatch thread dying");
1084 lttng_relay_stop_threads();
1088 static bool session_streams_have_index(const struct relay_session
*session
)
1090 return session
->minor
>= 4 && !session
->snapshot
;
1094 * Handle the RELAYD_CREATE_SESSION command.
1096 * On success, send back the session id or else return a negative value.
1098 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1099 struct relay_connection
*conn
,
1100 const struct lttng_buffer_view
*payload
)
1104 struct relay_session
*session
= NULL
;
1105 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1106 char session_name
[LTTNG_NAME_MAX
] = {};
1107 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1108 uint32_t live_timer
= 0;
1109 bool snapshot
= false;
1110 bool session_name_contains_creation_timestamp
= false;
1111 /* Left nil for peers < 2.11. */
1112 char base_path
[LTTNG_PATH_MAX
] = {};
1113 lttng_uuid sessiond_uuid
= {};
1114 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1115 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1116 LTTNG_OPTIONAL(time_t) creation_time
= {};
1117 struct lttng_dynamic_buffer reply_payload
;
1119 lttng_dynamic_buffer_init(&reply_payload
);
1121 if (conn
->minor
< 4) {
1122 /* From 2.1 to 2.3 */
1124 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1125 /* From 2.4 to 2.10 */
1126 ret
= cmd_create_session_2_4(payload
, session_name
,
1127 hostname
, &live_timer
, &snapshot
);
1129 bool has_current_chunk
;
1130 uint64_t current_chunk_id_value
;
1131 time_t creation_time_value
;
1132 uint64_t id_sessiond_value
;
1134 /* From 2.11 to ... */
1135 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1136 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1137 sessiond_uuid
, &has_current_chunk
,
1138 ¤t_chunk_id_value
, &creation_time_value
,
1139 &session_name_contains_creation_timestamp
);
1140 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1141 /* The nil UUID is reserved for pre-2.11 clients. */
1142 ERR("Illegal nil UUID announced by peer in create session command");
1146 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1147 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1148 if (has_current_chunk
) {
1149 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1150 current_chunk_id_value
);
1158 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1159 snapshot
, sessiond_uuid
,
1160 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1161 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1162 creation_time
.is_set
? &creation_time
.value
: NULL
,
1163 conn
->major
, conn
->minor
,
1164 session_name_contains_creation_timestamp
);
1169 assert(!conn
->session
);
1170 conn
->session
= session
;
1171 DBG("Created session %" PRIu64
, session
->id
);
1173 reply
.generic
.session_id
= htobe64(session
->id
);
1177 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1179 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1182 if (conn
->minor
< 11) {
1183 /* From 2.1 to 2.10 */
1184 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1185 &reply
.generic
, sizeof(reply
.generic
));
1187 ERR("Failed to append \"create session\" command reply header to payload buffer");
1192 const uint32_t output_path_length
=
1193 session
? strlen(session
->output_path
) + 1 : 0;
1195 reply
.output_path_length
= htobe32(output_path_length
);
1196 ret
= lttng_dynamic_buffer_append(
1197 &reply_payload
, &reply
, sizeof(reply
));
1199 ERR("Failed to append \"create session\" command reply header to payload buffer");
1203 if (output_path_length
) {
1204 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1205 session
->output_path
,
1206 output_path_length
);
1208 ERR("Failed to append \"create session\" command reply path to payload buffer");
1214 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1215 reply_payload
.size
, 0);
1216 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1217 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1218 reply_payload
.size
, send_ret
);
1222 if (ret
< 0 && session
) {
1223 session_put(session
);
1225 lttng_dynamic_buffer_reset(&reply_payload
);
1230 * When we have received all the streams and the metadata for a channel,
1231 * we make them visible to the viewer threads.
1233 static void publish_connection_local_streams(struct relay_connection
*conn
)
1235 struct relay_stream
*stream
;
1236 struct relay_session
*session
= conn
->session
;
1239 * We publish all streams belonging to a session atomically wrt
1242 pthread_mutex_lock(&session
->lock
);
1244 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1246 stream_publish(stream
);
1251 * Inform the viewer that there are new streams in the session.
1253 if (session
->viewer_attached
) {
1254 uatomic_set(&session
->new_streams
, 1);
1256 pthread_mutex_unlock(&session
->lock
);
1259 static int conform_channel_path(char *channel_path
)
1263 if (strstr("../", channel_path
)) {
1264 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1270 if (*channel_path
== '/') {
1271 const size_t len
= strlen(channel_path
);
1274 * Channel paths from peers prior to 2.11 are expressed as an
1275 * absolute path that is, in reality, relative to the relay
1276 * daemon's output directory. Remove the leading slash so it
1277 * is correctly interpreted as a relative path later on.
1279 * len (and not len - 1) is used to copy the trailing NULL.
1281 bcopy(channel_path
+ 1, channel_path
, len
);
1288 * relay_add_stream: allocate a new stream for a session
1290 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1291 struct relay_connection
*conn
,
1292 const struct lttng_buffer_view
*payload
)
1296 struct relay_session
*session
= conn
->session
;
1297 struct relay_stream
*stream
= NULL
;
1298 struct lttcomm_relayd_status_stream reply
;
1299 struct ctf_trace
*trace
= NULL
;
1300 uint64_t stream_handle
= -1ULL;
1301 char *path_name
= NULL
, *channel_name
= NULL
;
1302 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1303 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1305 if (!session
|| !conn
->version_check_done
) {
1306 ERR("Trying to add a stream before version check");
1308 goto end_no_session
;
1311 if (session
->minor
== 1) {
1313 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1315 } else if (session
->minor
> 1 && session
->minor
< 11) {
1316 /* From 2.2 to 2.10 */
1317 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1318 &channel_name
, &tracefile_size
, &tracefile_count
);
1320 /* From 2.11 to ... */
1321 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1322 &channel_name
, &tracefile_size
, &tracefile_count
,
1323 &stream_chunk_id
.value
);
1324 stream_chunk_id
.is_set
= true;
1331 if (conform_channel_path(path_name
)) {
1335 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1339 /* This stream here has one reference on the trace. */
1341 pthread_mutex_lock(&last_relay_stream_id_lock
);
1342 stream_handle
= ++last_relay_stream_id
;
1343 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1345 /* We pass ownership of path_name and channel_name. */
1346 stream
= stream_create(trace
, stream_handle
, path_name
,
1347 channel_name
, tracefile_size
, tracefile_count
);
1349 channel_name
= NULL
;
1352 * Streams are the owners of their trace. Reference to trace is
1353 * kept within stream_create().
1355 ctf_trace_put(trace
);
1358 memset(&reply
, 0, sizeof(reply
));
1359 reply
.handle
= htobe64(stream_handle
);
1361 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1363 reply
.ret_code
= htobe32(LTTNG_OK
);
1366 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1367 sizeof(struct lttcomm_relayd_status_stream
), 0);
1368 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1369 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1381 * relay_close_stream: close a specific stream
1383 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1384 struct relay_connection
*conn
,
1385 const struct lttng_buffer_view
*payload
)
1389 struct relay_session
*session
= conn
->session
;
1390 struct lttcomm_relayd_close_stream stream_info
;
1391 struct lttcomm_relayd_generic_reply reply
;
1392 struct relay_stream
*stream
;
1394 DBG("Close stream received");
1396 if (!session
|| !conn
->version_check_done
) {
1397 ERR("Trying to close a stream before version check");
1399 goto end_no_session
;
1402 if (payload
->size
< sizeof(stream_info
)) {
1403 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1404 sizeof(stream_info
), payload
->size
);
1406 goto end_no_session
;
1408 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1409 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1410 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1412 stream
= stream_get_by_id(stream_info
.stream_id
);
1419 * Set last_net_seq_num before the close flag. Required by data
1422 pthread_mutex_lock(&stream
->lock
);
1423 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1424 pthread_mutex_unlock(&stream
->lock
);
1427 * This is one of the conditions which may trigger a stream close
1428 * with the others being:
1429 * 1) A close command is received for a stream
1430 * 2) The control connection owning the stream is closed
1431 * 3) We have received all of the stream's data _after_ a close
1434 try_stream_close(stream
);
1435 if (stream
->is_metadata
) {
1436 struct relay_viewer_stream
*vstream
;
1438 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1440 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1442 * Since all the metadata has been sent to the
1443 * viewer and that we have a request to close
1444 * its stream, we can safely teardown the
1445 * corresponding metadata viewer stream.
1447 viewer_stream_put(vstream
);
1449 /* Put local reference. */
1450 viewer_stream_put(vstream
);
1457 memset(&reply
, 0, sizeof(reply
));
1459 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1461 reply
.ret_code
= htobe32(LTTNG_OK
);
1463 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1464 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1465 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1466 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1476 * relay_reset_metadata: reset a metadata stream
1479 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1480 struct relay_connection
*conn
,
1481 const struct lttng_buffer_view
*payload
)
1485 struct relay_session
*session
= conn
->session
;
1486 struct lttcomm_relayd_reset_metadata stream_info
;
1487 struct lttcomm_relayd_generic_reply reply
;
1488 struct relay_stream
*stream
;
1490 DBG("Reset metadata received");
1492 if (!session
|| !conn
->version_check_done
) {
1493 ERR("Trying to reset a metadata stream before version check");
1495 goto end_no_session
;
1498 if (payload
->size
< sizeof(stream_info
)) {
1499 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1500 sizeof(stream_info
), payload
->size
);
1502 goto end_no_session
;
1504 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1505 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1506 stream_info
.version
= be64toh(stream_info
.version
);
1508 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1510 /* Unsupported for live sessions for now. */
1511 if (session
->live_timer
!= 0) {
1516 stream
= stream_get_by_id(stream_info
.stream_id
);
1521 pthread_mutex_lock(&stream
->lock
);
1522 if (!stream
->is_metadata
) {
1527 ret
= stream_reset_file(stream
);
1529 ERR("Failed to reset metadata stream %" PRIu64
1530 ": stream_path = %s, channel = %s",
1531 stream
->stream_handle
, stream
->path_name
,
1532 stream
->channel_name
);
1536 pthread_mutex_unlock(&stream
->lock
);
1540 memset(&reply
, 0, sizeof(reply
));
1542 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1544 reply
.ret_code
= htobe32(LTTNG_OK
);
1546 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1547 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1548 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1549 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1559 * relay_unknown_command: send -1 if received unknown command
1561 static void relay_unknown_command(struct relay_connection
*conn
)
1563 struct lttcomm_relayd_generic_reply reply
;
1566 memset(&reply
, 0, sizeof(reply
));
1567 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1568 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1569 if (send_ret
< sizeof(reply
)) {
1570 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1575 * relay_start: send an acknowledgment to the client to tell if we are
1576 * ready to receive data. We are ready if a session is established.
1578 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1579 struct relay_connection
*conn
,
1580 const struct lttng_buffer_view
*payload
)
1584 struct lttcomm_relayd_generic_reply reply
;
1585 struct relay_session
*session
= conn
->session
;
1588 DBG("Trying to start the streaming without a session established");
1589 ret
= htobe32(LTTNG_ERR_UNK
);
1592 memset(&reply
, 0, sizeof(reply
));
1593 reply
.ret_code
= htobe32(LTTNG_OK
);
1594 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1596 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1597 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1606 * relay_recv_metadata: receive the metadata for the session.
1608 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1609 struct relay_connection
*conn
,
1610 const struct lttng_buffer_view
*payload
)
1613 struct relay_session
*session
= conn
->session
;
1614 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1615 struct relay_stream
*metadata_stream
;
1616 uint64_t metadata_payload_size
;
1617 struct lttng_buffer_view packet_view
;
1620 ERR("Metadata sent before version check");
1625 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1626 ERR("Incorrect data size");
1630 metadata_payload_size
= recv_hdr
->data_size
-
1631 sizeof(struct lttcomm_relayd_metadata_payload
);
1633 memcpy(&metadata_payload_header
, payload
->data
,
1634 sizeof(metadata_payload_header
));
1635 metadata_payload_header
.stream_id
= be64toh(
1636 metadata_payload_header
.stream_id
);
1637 metadata_payload_header
.padding_size
= be32toh(
1638 metadata_payload_header
.padding_size
);
1640 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1641 if (!metadata_stream
) {
1646 packet_view
= lttng_buffer_view_from_view(payload
,
1647 sizeof(metadata_payload_header
), metadata_payload_size
);
1648 if (!packet_view
.data
) {
1649 ERR("Invalid metadata packet length announced by header");
1654 pthread_mutex_lock(&metadata_stream
->lock
);
1655 ret
= stream_write(metadata_stream
, &packet_view
,
1656 metadata_payload_header
.padding_size
);
1657 pthread_mutex_unlock(&metadata_stream
->lock
);
1663 stream_put(metadata_stream
);
1669 * relay_send_version: send relayd version number
1671 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1672 struct relay_connection
*conn
,
1673 const struct lttng_buffer_view
*payload
)
1677 struct lttcomm_relayd_version reply
, msg
;
1678 bool compatible
= true;
1680 conn
->version_check_done
= true;
1682 /* Get version from the other side. */
1683 if (payload
->size
< sizeof(msg
)) {
1684 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1685 sizeof(msg
), payload
->size
);
1690 memcpy(&msg
, payload
->data
, sizeof(msg
));
1691 msg
.major
= be32toh(msg
.major
);
1692 msg
.minor
= be32toh(msg
.minor
);
1694 memset(&reply
, 0, sizeof(reply
));
1695 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1696 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1698 /* Major versions must be the same */
1699 if (reply
.major
!= msg
.major
) {
1700 DBG("Incompatible major versions (%u vs %u), deleting session",
1701 reply
.major
, msg
.major
);
1705 conn
->major
= reply
.major
;
1706 /* We adapt to the lowest compatible version */
1707 if (reply
.minor
<= msg
.minor
) {
1708 conn
->minor
= reply
.minor
;
1710 conn
->minor
= msg
.minor
;
1713 reply
.major
= htobe32(reply
.major
);
1714 reply
.minor
= htobe32(reply
.minor
);
1715 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1717 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1718 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1731 DBG("Version check done using protocol %u.%u", conn
->major
,
1739 * Check for data pending for a given stream id from the session daemon.
1741 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1742 struct relay_connection
*conn
,
1743 const struct lttng_buffer_view
*payload
)
1745 struct relay_session
*session
= conn
->session
;
1746 struct lttcomm_relayd_data_pending msg
;
1747 struct lttcomm_relayd_generic_reply reply
;
1748 struct relay_stream
*stream
;
1751 uint64_t stream_seq
;
1753 DBG("Data pending command received");
1755 if (!session
|| !conn
->version_check_done
) {
1756 ERR("Trying to check for data before version check");
1758 goto end_no_session
;
1761 if (payload
->size
< sizeof(msg
)) {
1762 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1763 sizeof(msg
), payload
->size
);
1765 goto end_no_session
;
1767 memcpy(&msg
, payload
->data
, sizeof(msg
));
1768 msg
.stream_id
= be64toh(msg
.stream_id
);
1769 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1771 stream
= stream_get_by_id(msg
.stream_id
);
1772 if (stream
== NULL
) {
1777 pthread_mutex_lock(&stream
->lock
);
1779 if (session_streams_have_index(session
)) {
1781 * Ensure that both the index and stream data have been
1782 * flushed up to the requested point.
1784 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
1786 stream_seq
= stream
->prev_data_seq
;
1788 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
1789 ", prev_index_seq %" PRIu64
1790 ", and last_seq %" PRIu64
, msg
.stream_id
,
1791 stream
->prev_data_seq
, stream
->prev_index_seq
,
1792 msg
.last_net_seq_num
);
1794 /* Avoid wrapping issue */
1795 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
1796 /* Data has in fact been written and is NOT pending */
1799 /* Data still being streamed thus pending */
1803 stream
->data_pending_check_done
= true;
1804 pthread_mutex_unlock(&stream
->lock
);
1809 memset(&reply
, 0, sizeof(reply
));
1810 reply
.ret_code
= htobe32(ret
);
1811 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1812 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1813 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1823 * Wait for the control socket to reach a quiescent state.
1825 * Note that for now, when receiving this command from the session
1826 * daemon, this means that every subsequent commands or data received on
1827 * the control socket has been handled. So, this is why we simply return
1830 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1831 struct relay_connection
*conn
,
1832 const struct lttng_buffer_view
*payload
)
1836 struct relay_stream
*stream
;
1837 struct lttcomm_relayd_quiescent_control msg
;
1838 struct lttcomm_relayd_generic_reply reply
;
1840 DBG("Checking quiescent state on control socket");
1842 if (!conn
->session
|| !conn
->version_check_done
) {
1843 ERR("Trying to check for data before version check");
1845 goto end_no_session
;
1848 if (payload
->size
< sizeof(msg
)) {
1849 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1850 sizeof(msg
), payload
->size
);
1852 goto end_no_session
;
1854 memcpy(&msg
, payload
->data
, sizeof(msg
));
1855 msg
.stream_id
= be64toh(msg
.stream_id
);
1857 stream
= stream_get_by_id(msg
.stream_id
);
1861 pthread_mutex_lock(&stream
->lock
);
1862 stream
->data_pending_check_done
= true;
1863 pthread_mutex_unlock(&stream
->lock
);
1865 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1868 memset(&reply
, 0, sizeof(reply
));
1869 reply
.ret_code
= htobe32(LTTNG_OK
);
1870 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1871 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1872 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1884 * Initialize a data pending command. This means that a consumer is about
1885 * to ask for data pending for each stream it holds. Simply iterate over
1886 * all streams of a session and set the data_pending_check_done flag.
1888 * This command returns to the client a LTTNG_OK code.
1890 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1891 struct relay_connection
*conn
,
1892 const struct lttng_buffer_view
*payload
)
1896 struct lttng_ht_iter iter
;
1897 struct lttcomm_relayd_begin_data_pending msg
;
1898 struct lttcomm_relayd_generic_reply reply
;
1899 struct relay_stream
*stream
;
1904 DBG("Init streams for data pending");
1906 if (!conn
->session
|| !conn
->version_check_done
) {
1907 ERR("Trying to check for data before version check");
1909 goto end_no_session
;
1912 if (payload
->size
< sizeof(msg
)) {
1913 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1914 sizeof(msg
), payload
->size
);
1916 goto end_no_session
;
1918 memcpy(&msg
, payload
->data
, sizeof(msg
));
1919 msg
.session_id
= be64toh(msg
.session_id
);
1922 * Iterate over all streams to set the begin data pending flag.
1923 * For now, the streams are indexed by stream handle so we have
1924 * to iterate over all streams to find the one associated with
1925 * the right session_id.
1928 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1930 if (!stream_get(stream
)) {
1933 if (stream
->trace
->session
->id
== msg
.session_id
) {
1934 pthread_mutex_lock(&stream
->lock
);
1935 stream
->data_pending_check_done
= false;
1936 pthread_mutex_unlock(&stream
->lock
);
1937 DBG("Set begin data pending flag to stream %" PRIu64
,
1938 stream
->stream_handle
);
1944 memset(&reply
, 0, sizeof(reply
));
1945 /* All good, send back reply. */
1946 reply
.ret_code
= htobe32(LTTNG_OK
);
1948 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1949 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1950 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1962 * End data pending command. This will check, for a given session id, if
1963 * each stream associated with it has its data_pending_check_done flag
1964 * set. If not, this means that the client lost track of the stream but
1965 * the data is still being streamed on our side. In this case, we inform
1966 * the client that data is in flight.
1968 * Return to the client if there is data in flight or not with a ret_code.
1970 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1971 struct relay_connection
*conn
,
1972 const struct lttng_buffer_view
*payload
)
1976 struct lttng_ht_iter iter
;
1977 struct lttcomm_relayd_end_data_pending msg
;
1978 struct lttcomm_relayd_generic_reply reply
;
1979 struct relay_stream
*stream
;
1980 uint32_t is_data_inflight
= 0;
1982 DBG("End data pending command");
1984 if (!conn
->session
|| !conn
->version_check_done
) {
1985 ERR("Trying to check for data before version check");
1987 goto end_no_session
;
1990 if (payload
->size
< sizeof(msg
)) {
1991 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1992 sizeof(msg
), payload
->size
);
1994 goto end_no_session
;
1996 memcpy(&msg
, payload
->data
, sizeof(msg
));
1997 msg
.session_id
= be64toh(msg
.session_id
);
2000 * Iterate over all streams to see if the begin data pending
2004 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2006 if (!stream_get(stream
)) {
2009 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2013 pthread_mutex_lock(&stream
->lock
);
2014 if (!stream
->data_pending_check_done
) {
2015 uint64_t stream_seq
;
2017 if (session_streams_have_index(conn
->session
)) {
2019 * Ensure that both the index and stream data have been
2020 * flushed up to the requested point.
2022 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2024 stream_seq
= stream
->prev_data_seq
;
2026 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2027 is_data_inflight
= 1;
2028 DBG("Data is still in flight for stream %" PRIu64
,
2029 stream
->stream_handle
);
2030 pthread_mutex_unlock(&stream
->lock
);
2035 pthread_mutex_unlock(&stream
->lock
);
2040 memset(&reply
, 0, sizeof(reply
));
2041 /* All good, send back reply. */
2042 reply
.ret_code
= htobe32(is_data_inflight
);
2044 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2045 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2046 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2058 * Receive an index for a specific stream.
2060 * Return 0 on success else a negative value.
2062 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2063 struct relay_connection
*conn
,
2064 const struct lttng_buffer_view
*payload
)
2068 struct relay_session
*session
= conn
->session
;
2069 struct lttcomm_relayd_index index_info
;
2070 struct lttcomm_relayd_generic_reply reply
;
2071 struct relay_stream
*stream
;
2076 DBG("Relay receiving index");
2078 if (!session
|| !conn
->version_check_done
) {
2079 ERR("Trying to close a stream before version check");
2081 goto end_no_session
;
2084 msg_len
= lttcomm_relayd_index_len(
2085 lttng_to_index_major(conn
->major
, conn
->minor
),
2086 lttng_to_index_minor(conn
->major
, conn
->minor
));
2087 if (payload
->size
< msg_len
) {
2088 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2089 msg_len
, payload
->size
);
2091 goto end_no_session
;
2093 memcpy(&index_info
, payload
->data
, msg_len
);
2094 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2095 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2096 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2097 index_info
.content_size
= be64toh(index_info
.content_size
);
2098 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2099 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2100 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2101 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2103 if (conn
->minor
>= 8) {
2104 index_info
.stream_instance_id
=
2105 be64toh(index_info
.stream_instance_id
);
2106 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2109 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2111 ERR("stream_get_by_id not found");
2116 pthread_mutex_lock(&stream
->lock
);
2117 ret
= stream_add_index(stream
, &index_info
);
2118 pthread_mutex_unlock(&stream
->lock
);
2120 goto end_stream_put
;
2126 memset(&reply
, 0, sizeof(reply
));
2128 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2130 reply
.ret_code
= htobe32(LTTNG_OK
);
2132 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2133 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2134 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2143 * Receive the streams_sent message.
2145 * Return 0 on success else a negative value.
2147 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2148 struct relay_connection
*conn
,
2149 const struct lttng_buffer_view
*payload
)
2153 struct lttcomm_relayd_generic_reply reply
;
2157 DBG("Relay receiving streams_sent");
2159 if (!conn
->session
|| !conn
->version_check_done
) {
2160 ERR("Trying to close a stream before version check");
2162 goto end_no_session
;
2166 * Publish every pending stream in the connection recv list which are
2167 * now ready to be used by the viewer.
2169 publish_connection_local_streams(conn
);
2171 memset(&reply
, 0, sizeof(reply
));
2172 reply
.ret_code
= htobe32(LTTNG_OK
);
2173 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2174 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2175 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2188 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2189 * session rotation feature (not the tracefile rotation feature).
2191 static int relay_rotate_session_streams(
2192 const struct lttcomm_relayd_hdr
*recv_hdr
,
2193 struct relay_connection
*conn
,
2194 const struct lttng_buffer_view
*payload
)
2199 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2200 struct relay_session
*session
= conn
->session
;
2201 struct lttcomm_relayd_rotate_streams rotate_streams
;
2202 struct lttcomm_relayd_generic_reply reply
= {};
2203 struct relay_stream
*stream
= NULL
;
2204 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2205 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2206 struct lttng_buffer_view stream_positions
;
2207 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2208 const char *chunk_id_str
= "none";
2210 if (!session
|| !conn
->version_check_done
) {
2211 ERR("Trying to rotate a stream before version check");
2216 if (session
->major
== 2 && session
->minor
< 11) {
2217 ERR("Unsupported feature before 2.11");
2222 if (payload
->size
< header_len
) {
2223 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2224 header_len
, payload
->size
);
2229 memcpy(&rotate_streams
, payload
->data
, header_len
);
2231 /* Convert header to host endianness. */
2232 rotate_streams
= (typeof(rotate_streams
)) {
2233 .stream_count
= be32toh(rotate_streams
.stream_count
),
2234 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2235 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2236 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2240 if (rotate_streams
.new_chunk_id
.is_set
) {
2242 * Retrieve the trace chunk the stream must transition to. As
2243 * per the protocol, this chunk should have been created
2244 * before this command is received.
2246 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2247 sessiond_trace_chunk_registry
,
2248 session
->sessiond_uuid
, session
->id
,
2249 rotate_streams
.new_chunk_id
.value
);
2250 if (!next_trace_chunk
) {
2251 char uuid_str
[UUID_STR_LEN
];
2253 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2254 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2255 ", trace_chunk_id = %" PRIu64
,
2256 uuid_str
, session
->id
,
2257 rotate_streams
.new_chunk_id
.value
);
2258 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2263 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2264 rotate_streams
.new_chunk_id
.value
);
2265 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2266 chunk_id_str
= "formatting error";
2268 chunk_id_str
= chunk_id_buf
;
2270 session
->has_rotated
= true;
2273 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2274 rotate_streams
.stream_count
, session
->session_name
,
2277 stream_positions
= lttng_buffer_view_from_view(payload
,
2278 sizeof(rotate_streams
), -1);
2279 if (!stream_positions
.data
||
2280 stream_positions
.size
<
2281 (rotate_streams
.stream_count
*
2282 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2283 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2288 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2289 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2290 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2291 const struct lttcomm_relayd_stream_rotation_position pos
= {
2292 .stream_id
= be64toh(position_comm
->stream_id
),
2293 .rotate_at_seq_num
= be64toh(
2294 position_comm
->rotate_at_seq_num
),
2297 stream
= stream_get_by_id(pos
.stream_id
);
2299 reply_code
= LTTNG_ERR_INVALID
;
2304 pthread_mutex_lock(&stream
->lock
);
2305 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2306 pos
.rotate_at_seq_num
);
2307 pthread_mutex_unlock(&stream
->lock
);
2309 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2317 reply_code
= LTTNG_OK
;
2324 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2325 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2326 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2327 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2328 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2333 lttng_trace_chunk_put(next_trace_chunk
);
2340 * relay_create_trace_chunk: create a new trace chunk
2342 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2343 struct relay_connection
*conn
,
2344 const struct lttng_buffer_view
*payload
)
2348 struct relay_session
*session
= conn
->session
;
2349 struct lttcomm_relayd_create_trace_chunk
*msg
;
2350 struct lttcomm_relayd_generic_reply reply
= {};
2351 struct lttng_buffer_view header_view
;
2352 struct lttng_buffer_view chunk_name_view
;
2353 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2354 enum lttng_error_code reply_code
= LTTNG_OK
;
2355 enum lttng_trace_chunk_status chunk_status
;
2356 struct lttng_directory_handle session_output
;
2358 if (!session
|| !conn
->version_check_done
) {
2359 ERR("Trying to create a trace chunk before version check");
2364 if (session
->major
== 2 && session
->minor
< 11) {
2365 ERR("Chunk creation command is unsupported before 2.11");
2370 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2371 if (!header_view
.data
) {
2372 ERR("Failed to receive payload of chunk creation command");
2377 /* Convert to host endianness. */
2378 msg
= (typeof(msg
)) header_view
.data
;
2379 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2380 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2381 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2383 chunk
= lttng_trace_chunk_create(
2384 msg
->chunk_id
, msg
->creation_timestamp
);
2386 ERR("Failed to create trace chunk in trace chunk creation command");
2388 reply_code
= LTTNG_ERR_NOMEM
;
2392 if (msg
->override_name_length
) {
2395 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2397 msg
->override_name_length
);
2398 name
= chunk_name_view
.data
;
2399 if (!name
|| name
[msg
->override_name_length
- 1]) {
2400 ERR("Failed to receive payload of chunk creation command");
2402 reply_code
= LTTNG_ERR_INVALID
;
2406 chunk_status
= lttng_trace_chunk_override_name(
2407 chunk
, chunk_name_view
.data
);
2408 switch (chunk_status
) {
2409 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2411 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2412 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2413 reply_code
= LTTNG_ERR_INVALID
;
2417 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2418 reply_code
= LTTNG_ERR_UNK
;
2424 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2425 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2426 reply_code
= LTTNG_ERR_UNK
;
2431 ret
= session_init_output_directory_handle(
2432 conn
->session
, &session_output
);
2434 reply_code
= LTTNG_ERR_CREATE_DIR_FAIL
;
2437 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, &session_output
);
2438 lttng_directory_handle_fini(&session_output
);
2439 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2440 reply_code
= LTTNG_ERR_UNK
;
2445 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2446 sessiond_trace_chunk_registry
,
2447 conn
->session
->sessiond_uuid
,
2450 if (!published_chunk
) {
2451 char uuid_str
[UUID_STR_LEN
];
2453 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2454 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2459 reply_code
= LTTNG_ERR_NOMEM
;
2463 pthread_mutex_lock(&conn
->session
->lock
);
2464 if (conn
->session
->pending_closure_trace_chunk
) {
2466 * Invalid; this means a second create_trace_chunk command was
2467 * received before a close_trace_chunk.
2469 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2470 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2472 goto end_unlock_session
;
2474 conn
->session
->pending_closure_trace_chunk
=
2475 conn
->session
->current_trace_chunk
;
2476 conn
->session
->current_trace_chunk
= published_chunk
;
2477 published_chunk
= NULL
;
2479 pthread_mutex_unlock(&conn
->session
->lock
);
2481 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2482 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2484 sizeof(struct lttcomm_relayd_generic_reply
),
2486 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2487 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2492 lttng_trace_chunk_put(chunk
);
2493 lttng_trace_chunk_put(published_chunk
);
2498 * relay_close_trace_chunk: close a trace chunk
2500 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2501 struct relay_connection
*conn
,
2502 const struct lttng_buffer_view
*payload
)
2504 int ret
= 0, buf_ret
;
2506 struct relay_session
*session
= conn
->session
;
2507 struct lttcomm_relayd_close_trace_chunk
*msg
;
2508 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2509 struct lttng_buffer_view header_view
;
2510 struct lttng_trace_chunk
*chunk
= NULL
;
2511 enum lttng_error_code reply_code
= LTTNG_OK
;
2512 enum lttng_trace_chunk_status chunk_status
;
2514 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2515 time_t close_timestamp
;
2516 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2517 size_t path_length
= 0;
2518 const char *chunk_name
= NULL
;
2519 struct lttng_dynamic_buffer reply_payload
;
2521 lttng_dynamic_buffer_init(&reply_payload
);
2523 if (!session
|| !conn
->version_check_done
) {
2524 ERR("Trying to close a trace chunk before version check");
2529 if (session
->major
== 2 && session
->minor
< 11) {
2530 ERR("Chunk close command is unsupported before 2.11");
2535 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2536 if (!header_view
.data
) {
2537 ERR("Failed to receive payload of chunk close command");
2542 /* Convert to host endianness. */
2543 msg
= (typeof(msg
)) header_view
.data
;
2544 chunk_id
= be64toh(msg
->chunk_id
);
2545 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2546 close_command
= (typeof(close_command
)){
2547 .value
= be32toh(msg
->close_command
.value
),
2548 .is_set
= msg
->close_command
.is_set
,
2551 chunk
= sessiond_trace_chunk_registry_get_chunk(
2552 sessiond_trace_chunk_registry
,
2553 conn
->session
->sessiond_uuid
,
2557 char uuid_str
[UUID_STR_LEN
];
2559 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2560 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2565 reply_code
= LTTNG_ERR_NOMEM
;
2569 pthread_mutex_lock(&session
->lock
);
2570 if (session
->pending_closure_trace_chunk
&&
2571 session
->pending_closure_trace_chunk
!= chunk
) {
2572 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2573 session
->session_name
);
2574 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2576 goto end_unlock_session
;
2579 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2580 chunk
, close_timestamp
);
2581 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2582 ERR("Failed to set trace chunk close timestamp");
2584 reply_code
= LTTNG_ERR_UNK
;
2585 goto end_unlock_session
;
2588 if (close_command
.is_set
) {
2589 chunk_status
= lttng_trace_chunk_set_close_command(
2590 chunk
, close_command
.value
);
2591 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2593 reply_code
= LTTNG_ERR_INVALID
;
2594 goto end_unlock_session
;
2597 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2598 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2599 ERR("Failed to get chunk name");
2601 reply_code
= LTTNG_ERR_UNK
;
2602 goto end_unlock_session
;
2604 if (!session
->has_rotated
&& !session
->snapshot
) {
2605 ret
= lttng_strncpy(closed_trace_chunk_path
,
2606 session
->output_path
,
2607 sizeof(closed_trace_chunk_path
));
2609 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2610 strlen(session
->output_path
),
2611 sizeof(closed_trace_chunk_path
));
2612 reply_code
= LTTNG_ERR_NOMEM
;
2614 goto end_unlock_session
;
2617 if (session
->snapshot
) {
2618 ret
= snprintf(closed_trace_chunk_path
,
2619 sizeof(closed_trace_chunk_path
),
2620 "%s/%s", session
->output_path
,
2623 ret
= snprintf(closed_trace_chunk_path
,
2624 sizeof(closed_trace_chunk_path
),
2625 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2627 session
->output_path
, chunk_name
);
2629 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
2630 ERR("Failed to format closed trace chunk resulting path");
2631 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
2633 goto end_unlock_session
;
2636 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
2637 path_length
= strlen(closed_trace_chunk_path
) + 1;
2638 if (path_length
> UINT32_MAX
) {
2639 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2641 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2642 goto end_unlock_session
;
2645 if (session
->current_trace_chunk
== chunk
) {
2647 * After a trace chunk close command, no new streams
2648 * referencing the chunk may be created. Hence, on the
2649 * event that no new trace chunk have been created for
2650 * the session, the reference to the current trace chunk
2651 * is released in order to allow it to be reclaimed when
2652 * the last stream releases its reference to it.
2654 lttng_trace_chunk_put(session
->current_trace_chunk
);
2655 session
->current_trace_chunk
= NULL
;
2657 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
2658 session
->pending_closure_trace_chunk
= NULL
;
2660 pthread_mutex_unlock(&session
->lock
);
2663 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
2664 reply
.path_length
= htobe32((uint32_t) path_length
);
2665 buf_ret
= lttng_dynamic_buffer_append(
2666 &reply_payload
, &reply
, sizeof(reply
));
2668 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2672 if (reply_code
== LTTNG_OK
) {
2673 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
2674 closed_trace_chunk_path
, path_length
);
2676 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2681 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2685 if (send_ret
< reply_payload
.size
) {
2686 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2687 reply_payload
.size
, send_ret
);
2692 lttng_trace_chunk_put(chunk
);
2693 lttng_dynamic_buffer_reset(&reply_payload
);
2698 * relay_trace_chunk_exists: check if a trace chunk exists
2700 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
2701 struct relay_connection
*conn
,
2702 const struct lttng_buffer_view
*payload
)
2706 struct relay_session
*session
= conn
->session
;
2707 struct lttcomm_relayd_trace_chunk_exists
*msg
;
2708 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
2709 struct lttng_buffer_view header_view
;
2713 if (!session
|| !conn
->version_check_done
) {
2714 ERR("Trying to close a trace chunk before version check");
2719 if (session
->major
== 2 && session
->minor
< 11) {
2720 ERR("Chunk close command is unsupported before 2.11");
2725 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2726 if (!header_view
.data
) {
2727 ERR("Failed to receive payload of chunk close command");
2732 /* Convert to host endianness. */
2733 msg
= (typeof(msg
)) header_view
.data
;
2734 chunk_id
= be64toh(msg
->chunk_id
);
2736 ret
= sessiond_trace_chunk_registry_chunk_exists(
2737 sessiond_trace_chunk_registry
,
2738 conn
->session
->sessiond_uuid
,
2740 chunk_id
, &chunk_exists
);
2742 * If ret is not 0, send the reply and report the error to the caller.
2743 * It is a protocol (or internal) error and the session/connection
2744 * should be torn down.
2746 reply
= (typeof(reply
)){
2747 .generic
.ret_code
= htobe32((uint32_t)
2748 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
2749 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
2751 send_ret
= conn
->sock
->ops
->sendmsg(
2752 conn
->sock
, &reply
, sizeof(reply
), 0);
2753 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2754 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2762 #define DBG_CMD(cmd_name, conn) \
2763 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2765 static int relay_process_control_command(struct relay_connection
*conn
,
2766 const struct lttcomm_relayd_hdr
*header
,
2767 const struct lttng_buffer_view
*payload
)
2771 switch (header
->cmd
) {
2772 case RELAYD_CREATE_SESSION
:
2773 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2774 ret
= relay_create_session(header
, conn
, payload
);
2776 case RELAYD_ADD_STREAM
:
2777 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2778 ret
= relay_add_stream(header
, conn
, payload
);
2780 case RELAYD_START_DATA
:
2781 DBG_CMD("RELAYD_START_DATA", conn
);
2782 ret
= relay_start(header
, conn
, payload
);
2784 case RELAYD_SEND_METADATA
:
2785 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2786 ret
= relay_recv_metadata(header
, conn
, payload
);
2788 case RELAYD_VERSION
:
2789 DBG_CMD("RELAYD_VERSION", conn
);
2790 ret
= relay_send_version(header
, conn
, payload
);
2792 case RELAYD_CLOSE_STREAM
:
2793 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2794 ret
= relay_close_stream(header
, conn
, payload
);
2796 case RELAYD_DATA_PENDING
:
2797 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2798 ret
= relay_data_pending(header
, conn
, payload
);
2800 case RELAYD_QUIESCENT_CONTROL
:
2801 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2802 ret
= relay_quiescent_control(header
, conn
, payload
);
2804 case RELAYD_BEGIN_DATA_PENDING
:
2805 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2806 ret
= relay_begin_data_pending(header
, conn
, payload
);
2808 case RELAYD_END_DATA_PENDING
:
2809 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2810 ret
= relay_end_data_pending(header
, conn
, payload
);
2812 case RELAYD_SEND_INDEX
:
2813 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2814 ret
= relay_recv_index(header
, conn
, payload
);
2816 case RELAYD_STREAMS_SENT
:
2817 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2818 ret
= relay_streams_sent(header
, conn
, payload
);
2820 case RELAYD_RESET_METADATA
:
2821 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2822 ret
= relay_reset_metadata(header
, conn
, payload
);
2824 case RELAYD_ROTATE_STREAMS
:
2825 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
2826 ret
= relay_rotate_session_streams(header
, conn
, payload
);
2828 case RELAYD_CREATE_TRACE_CHUNK
:
2829 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
2830 ret
= relay_create_trace_chunk(header
, conn
, payload
);
2832 case RELAYD_CLOSE_TRACE_CHUNK
:
2833 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
2834 ret
= relay_close_trace_chunk(header
, conn
, payload
);
2836 case RELAYD_TRACE_CHUNK_EXISTS
:
2837 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
2838 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
2840 case RELAYD_UPDATE_SYNC_INFO
:
2842 ERR("Received unknown command (%u)", header
->cmd
);
2843 relay_unknown_command(conn
);
2852 static enum relay_connection_status
relay_process_control_receive_payload(
2853 struct relay_connection
*conn
)
2856 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2857 struct lttng_dynamic_buffer
*reception_buffer
=
2858 &conn
->protocol
.ctrl
.reception_buffer
;
2859 struct ctrl_connection_state_receive_payload
*state
=
2860 &conn
->protocol
.ctrl
.state
.receive_payload
;
2861 struct lttng_buffer_view payload_view
;
2863 if (state
->left_to_receive
== 0) {
2864 /* Short-circuit for payload-less commands. */
2865 goto reception_complete
;
2868 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2869 reception_buffer
->data
+ state
->received
,
2870 state
->left_to_receive
, MSG_DONTWAIT
);
2872 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2873 PERROR("Unable to receive command payload on sock %d",
2875 status
= RELAY_CONNECTION_STATUS_ERROR
;
2878 } else if (ret
== 0) {
2879 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2880 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2885 assert(ret
<= state
->left_to_receive
);
2887 state
->left_to_receive
-= ret
;
2888 state
->received
+= ret
;
2890 if (state
->left_to_receive
> 0) {
2892 * Can't transition to the protocol's next state, wait to
2893 * receive the rest of the header.
2895 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2896 state
->received
, state
->left_to_receive
,
2902 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2903 conn
->sock
->fd
, state
->received
);
2905 * The payload required to process the command has been received.
2906 * A view to the reception buffer is forwarded to the various
2907 * commands and the state of the control is reset on success.
2909 * Commands are responsible for sending their reply to the peer.
2911 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2913 ret
= relay_process_control_command(conn
,
2914 &state
->header
, &payload_view
);
2916 status
= RELAY_CONNECTION_STATUS_ERROR
;
2920 ret
= connection_reset_protocol_state(conn
);
2922 status
= RELAY_CONNECTION_STATUS_ERROR
;
2928 static enum relay_connection_status
relay_process_control_receive_header(
2929 struct relay_connection
*conn
)
2932 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2933 struct lttcomm_relayd_hdr header
;
2934 struct lttng_dynamic_buffer
*reception_buffer
=
2935 &conn
->protocol
.ctrl
.reception_buffer
;
2936 struct ctrl_connection_state_receive_header
*state
=
2937 &conn
->protocol
.ctrl
.state
.receive_header
;
2939 assert(state
->left_to_receive
!= 0);
2941 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2942 reception_buffer
->data
+ state
->received
,
2943 state
->left_to_receive
, MSG_DONTWAIT
);
2945 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2946 PERROR("Unable to receive control command header on sock %d",
2948 status
= RELAY_CONNECTION_STATUS_ERROR
;
2951 } else if (ret
== 0) {
2952 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2953 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2958 assert(ret
<= state
->left_to_receive
);
2960 state
->left_to_receive
-= ret
;
2961 state
->received
+= ret
;
2963 if (state
->left_to_receive
> 0) {
2965 * Can't transition to the protocol's next state, wait to
2966 * receive the rest of the header.
2968 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2969 state
->received
, state
->left_to_receive
,
2974 /* Transition to next state: receiving the command's payload. */
2975 conn
->protocol
.ctrl
.state_id
=
2976 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2977 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2978 header
.circuit_id
= be64toh(header
.circuit_id
);
2979 header
.data_size
= be64toh(header
.data_size
);
2980 header
.cmd
= be32toh(header
.cmd
);
2981 header
.cmd_version
= be32toh(header
.cmd_version
);
2982 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2983 &header
, sizeof(header
));
2985 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2986 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2989 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2990 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2992 status
= RELAY_CONNECTION_STATUS_ERROR
;
2996 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2998 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2999 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3002 status
= RELAY_CONNECTION_STATUS_ERROR
;
3006 if (header
.data_size
== 0) {
3008 * Manually invoke the next state as the poll loop
3009 * will not wake-up to allow us to proceed further.
3011 status
= relay_process_control_receive_payload(conn
);
3018 * Process the commands received on the control socket
3020 static enum relay_connection_status
relay_process_control(
3021 struct relay_connection
*conn
)
3023 enum relay_connection_status status
;
3025 switch (conn
->protocol
.ctrl
.state_id
) {
3026 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3027 status
= relay_process_control_receive_header(conn
);
3029 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3030 status
= relay_process_control_receive_payload(conn
);
3033 ERR("Unknown control connection protocol state encountered.");
3040 static enum relay_connection_status
relay_process_data_receive_header(
3041 struct relay_connection
*conn
)
3044 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3045 struct data_connection_state_receive_header
*state
=
3046 &conn
->protocol
.data
.state
.receive_header
;
3047 struct lttcomm_relayd_data_hdr header
;
3048 struct relay_stream
*stream
;
3050 assert(state
->left_to_receive
!= 0);
3052 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3053 state
->header_reception_buffer
+ state
->received
,
3054 state
->left_to_receive
, MSG_DONTWAIT
);
3056 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3057 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3058 status
= RELAY_CONNECTION_STATUS_ERROR
;
3061 } else if (ret
== 0) {
3062 /* Orderly shutdown. Not necessary to print an error. */
3063 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3064 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3069 assert(ret
<= state
->left_to_receive
);
3071 state
->left_to_receive
-= ret
;
3072 state
->received
+= ret
;
3074 if (state
->left_to_receive
> 0) {
3076 * Can't transition to the protocol's next state, wait to
3077 * receive the rest of the header.
3079 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3080 state
->received
, state
->left_to_receive
,
3085 /* Transition to next state: receiving the payload. */
3086 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3088 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3089 header
.circuit_id
= be64toh(header
.circuit_id
);
3090 header
.stream_id
= be64toh(header
.stream_id
);
3091 header
.data_size
= be32toh(header
.data_size
);
3092 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3093 header
.padding_size
= be32toh(header
.padding_size
);
3094 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3096 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3098 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3099 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3101 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3102 conn
->sock
->fd
, header
.circuit_id
,
3103 header
.stream_id
, header
.data_size
,
3104 header
.net_seq_num
, header
.padding_size
);
3106 stream
= stream_get_by_id(header
.stream_id
);
3108 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3110 /* Protocol error. */
3111 status
= RELAY_CONNECTION_STATUS_ERROR
;
3115 pthread_mutex_lock(&stream
->lock
);
3116 /* Prepare stream for the reception of a new packet. */
3117 ret
= stream_init_packet(stream
, header
.data_size
,
3118 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3119 pthread_mutex_unlock(&stream
->lock
);
3121 ERR("Failed to rotate stream output file");
3122 status
= RELAY_CONNECTION_STATUS_ERROR
;
3123 goto end_stream_unlock
;
3132 static enum relay_connection_status
relay_process_data_receive_payload(
3133 struct relay_connection
*conn
)
3136 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3137 struct relay_stream
*stream
;
3138 struct data_connection_state_receive_payload
*state
=
3139 &conn
->protocol
.data
.state
.receive_payload
;
3140 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3141 char data_buffer
[chunk_size
];
3142 bool partial_recv
= false;
3143 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3144 uint64_t left_to_receive
= state
->left_to_receive
;
3145 struct relay_session
*session
;
3147 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3148 state
->header
.stream_id
, state
->header
.net_seq_num
,
3149 state
->received
, left_to_receive
);
3151 stream
= stream_get_by_id(state
->header
.stream_id
);
3153 /* Protocol error. */
3154 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3155 state
->header
.stream_id
);
3156 status
= RELAY_CONNECTION_STATUS_ERROR
;
3160 pthread_mutex_lock(&stream
->lock
);
3161 session
= stream
->trace
->session
;
3162 if (!conn
->session
) {
3163 ret
= connection_set_session(conn
, session
);
3165 status
= RELAY_CONNECTION_STATUS_ERROR
;
3166 goto end_stream_unlock
;
3171 * The size of the "chunk" received on any iteration is bounded by:
3172 * - the data left to receive,
3173 * - the data immediately available on the socket,
3174 * - the on-stack data buffer
3176 while (left_to_receive
> 0 && !partial_recv
) {
3177 size_t recv_size
= min(left_to_receive
, chunk_size
);
3178 struct lttng_buffer_view packet_chunk
;
3180 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3181 recv_size
, MSG_DONTWAIT
);
3183 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3184 PERROR("Socket %d error", conn
->sock
->fd
);
3185 status
= RELAY_CONNECTION_STATUS_ERROR
;
3187 goto end_stream_unlock
;
3188 } else if (ret
== 0) {
3189 /* No more data ready to be consumed on socket. */
3190 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3191 state
->header
.stream_id
);
3192 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3194 } else if (ret
< (int) recv_size
) {
3196 * All the data available on the socket has been
3199 partial_recv
= true;
3203 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3205 assert(packet_chunk
.data
);
3207 ret
= stream_write(stream
, &packet_chunk
, 0);
3209 ERR("Relay error writing data to file");
3210 status
= RELAY_CONNECTION_STATUS_ERROR
;
3211 goto end_stream_unlock
;
3214 left_to_receive
-= recv_size
;
3215 state
->received
+= recv_size
;
3216 state
->left_to_receive
= left_to_receive
;
3219 if (state
->left_to_receive
> 0) {
3221 * Did not receive all the data expected, wait for more data to
3222 * become available on the socket.
3224 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3225 state
->header
.stream_id
, state
->received
,
3226 state
->left_to_receive
);
3227 goto end_stream_unlock
;
3230 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3232 status
= RELAY_CONNECTION_STATUS_ERROR
;
3233 goto end_stream_unlock
;
3236 if (session_streams_have_index(session
)) {
3237 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3238 state
->rotate_index
, &index_flushed
,
3239 state
->header
.data_size
+ state
->header
.padding_size
);
3241 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3242 stream
->stream_handle
,
3243 state
->header
.net_seq_num
, ret
);
3244 status
= RELAY_CONNECTION_STATUS_ERROR
;
3245 goto end_stream_unlock
;
3249 if (stream
->prev_data_seq
== -1ULL) {
3253 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3254 state
->header
.padding_size
, state
->header
.net_seq_num
,
3257 status
= RELAY_CONNECTION_STATUS_ERROR
;
3258 goto end_stream_unlock
;
3262 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3263 * contents of *state which are aliased (union) to the same location as
3264 * the new state. Don't use it beyond this point.
3266 connection_reset_protocol_state(conn
);
3270 close_requested
= stream
->close_requested
;
3271 pthread_mutex_unlock(&stream
->lock
);
3272 if (close_requested
&& left_to_receive
== 0) {
3273 try_stream_close(stream
);
3277 pthread_mutex_lock(&session
->lock
);
3278 uatomic_set(&session
->new_streams
, 1);
3279 pthread_mutex_unlock(&session
->lock
);
3288 * relay_process_data: Process the data received on the data socket
3290 static enum relay_connection_status
relay_process_data(
3291 struct relay_connection
*conn
)
3293 enum relay_connection_status status
;
3295 switch (conn
->protocol
.data
.state_id
) {
3296 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3297 status
= relay_process_data_receive_header(conn
);
3299 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3300 status
= relay_process_data_receive_payload(conn
);
3303 ERR("Unexpected data connection communication state.");
3310 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3314 (void) lttng_poll_del(events
, pollfd
);
3316 ret
= close(pollfd
);
3318 ERR("Closing pollfd %d", pollfd
);
3322 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3323 int pollfd
, struct relay_connection
*conn
)
3325 const char *type_str
;
3327 switch (conn
->type
) {
3332 type_str
= "Control";
3334 case RELAY_VIEWER_COMMAND
:
3335 type_str
= "Viewer Command";
3337 case RELAY_VIEWER_NOTIFICATION
:
3338 type_str
= "Viewer Notification";
3341 type_str
= "Unknown";
3343 cleanup_connection_pollfd(events
, pollfd
);
3344 connection_put(conn
);
3345 DBG("%s connection closed with %d", type_str
, pollfd
);
3349 * This thread does the actual work
3351 static void *relay_thread_worker(void *data
)
3353 int ret
, err
= -1, last_seen_data_fd
= -1;
3355 struct lttng_poll_event events
;
3356 struct lttng_ht
*relay_connections_ht
;
3357 struct lttng_ht_iter iter
;
3358 struct relay_connection
*destroy_conn
= NULL
;
3360 DBG("[thread] Relay worker started");
3362 rcu_register_thread();
3364 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3366 if (testpoint(relayd_thread_worker
)) {
3367 goto error_testpoint
;
3370 health_code_update();
3372 /* table of connections indexed on socket */
3373 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3374 if (!relay_connections_ht
) {
3375 goto relay_connections_ht_error
;
3378 ret
= create_thread_poll_set(&events
, 2);
3380 goto error_poll_create
;
3383 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3390 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3392 health_code_update();
3394 /* Infinite blocking call, waiting for transmission */
3395 DBG3("Relayd worker thread polling...");
3396 health_poll_entry();
3397 ret
= lttng_poll_wait(&events
, -1);
3401 * Restart interrupted system call.
3403 if (errno
== EINTR
) {
3412 * Process control. The control connection is
3413 * prioritized so we don't starve it with high
3414 * throughput tracing data on the data connection.
3416 for (i
= 0; i
< nb_fd
; i
++) {
3417 /* Fetch once the poll data */
3418 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3419 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3421 health_code_update();
3423 /* Thread quit pipe has been closed. Killing thread. */
3424 ret
= check_thread_quit_pipe(pollfd
, revents
);
3430 /* Inspect the relay conn pipe for new connection */
3431 if (pollfd
== relay_conn_pipe
[0]) {
3432 if (revents
& LPOLLIN
) {
3433 struct relay_connection
*conn
;
3435 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3439 ret
= lttng_poll_add(&events
,
3441 LPOLLIN
| LPOLLRDHUP
);
3443 ERR("Failed to add new connection file descriptor to poll set");
3446 connection_ht_add(relay_connections_ht
, conn
);
3447 DBG("Connection socket %d added", conn
->sock
->fd
);
3448 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3449 ERR("Relay connection pipe error");
3452 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3456 struct relay_connection
*ctrl_conn
;
3458 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3459 /* If not found, there is a synchronization issue. */
3462 if (ctrl_conn
->type
== RELAY_DATA
) {
3463 if (revents
& LPOLLIN
) {
3465 * Flag the last seen data fd not deleted. It will be
3466 * used as the last seen fd if any fd gets deleted in
3469 last_notdel_data_fd
= pollfd
;
3471 goto put_ctrl_connection
;
3473 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3475 if (revents
& LPOLLIN
) {
3476 enum relay_connection_status status
;
3478 status
= relay_process_control(ctrl_conn
);
3479 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3481 * On socket error flag the session as aborted to force
3482 * the cleanup of its stream otherwise it can leak
3483 * during the lifetime of the relayd.
3485 * This prevents situations in which streams can be
3486 * left opened because an index was received, the
3487 * control connection is closed, and the data
3488 * connection is closed (uncleanly) before the packet's
3491 * Since the control connection encountered an error,
3492 * it is okay to be conservative and close the
3493 * session right now as we can't rely on the protocol
3494 * being respected anymore.
3496 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3497 session_abort(ctrl_conn
->session
);
3500 /* Clear the connection on error or close. */
3501 relay_thread_close_connection(&events
,
3506 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3507 relay_thread_close_connection(&events
,
3509 if (last_seen_data_fd
== pollfd
) {
3510 last_seen_data_fd
= last_notdel_data_fd
;
3513 ERR("Unexpected poll events %u for control sock %d",
3515 connection_put(ctrl_conn
);
3518 put_ctrl_connection
:
3519 connection_put(ctrl_conn
);
3524 * The last loop handled a control request, go back to poll to make
3525 * sure we prioritise the control socket.
3531 if (last_seen_data_fd
>= 0) {
3532 for (i
= 0; i
< nb_fd
; i
++) {
3533 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3535 health_code_update();
3537 if (last_seen_data_fd
== pollfd
) {
3544 /* Process data connection. */
3545 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3546 /* Fetch the poll data. */
3547 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3548 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3549 struct relay_connection
*data_conn
;
3551 health_code_update();
3554 /* No activity for this FD (poll implementation). */
3558 /* Skip the command pipe. It's handled in the first loop. */
3559 if (pollfd
== relay_conn_pipe
[0]) {
3563 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3565 /* Skip it. Might be removed before. */
3568 if (data_conn
->type
== RELAY_CONTROL
) {
3569 goto put_data_connection
;
3571 assert(data_conn
->type
== RELAY_DATA
);
3573 if (revents
& LPOLLIN
) {
3574 enum relay_connection_status status
;
3576 status
= relay_process_data(data_conn
);
3577 /* Connection closed or error. */
3578 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3580 * On socket error flag the session as aborted to force
3581 * the cleanup of its stream otherwise it can leak
3582 * during the lifetime of the relayd.
3584 * This prevents situations in which streams can be
3585 * left opened because an index was received, the
3586 * control connection is closed, and the data
3587 * connection is closed (uncleanly) before the packet's
3590 * Since the data connection encountered an error,
3591 * it is okay to be conservative and close the
3592 * session right now as we can't rely on the protocol
3593 * being respected anymore.
3595 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3596 session_abort(data_conn
->session
);
3598 relay_thread_close_connection(&events
, pollfd
,
3601 * Every goto restart call sets the last seen fd where
3602 * here we don't really care since we gracefully
3603 * continue the loop after the connection is deleted.
3606 /* Keep last seen port. */
3607 last_seen_data_fd
= pollfd
;
3608 connection_put(data_conn
);
3611 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3612 relay_thread_close_connection(&events
, pollfd
,
3615 ERR("Unknown poll events %u for data sock %d",
3618 put_data_connection
:
3619 connection_put(data_conn
);
3621 last_seen_data_fd
= -1;
3624 /* Normal exit, no error */
3629 /* Cleanup remaining connection object. */
3631 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3634 health_code_update();
3636 session_abort(destroy_conn
->session
);
3639 * No need to grab another ref, because we own
3642 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3647 lttng_poll_clean(&events
);
3649 lttng_ht_destroy(relay_connections_ht
);
3650 relay_connections_ht_error
:
3651 /* Close relay conn pipes */
3652 utils_close_pipe(relay_conn_pipe
);
3654 DBG("Thread exited with error");
3656 DBG("Worker thread cleanup complete");
3660 ERR("Health error occurred in %s", __func__
);
3662 health_unregister(health_relayd
);
3663 rcu_unregister_thread();
3664 lttng_relay_stop_threads();
3669 * Create the relay command pipe to wake thread_manage_apps.
3670 * Closed in cleanup().
3672 static int create_relay_conn_pipe(void)
3676 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3684 int main(int argc
, char **argv
)
3686 int ret
= 0, retval
= 0;
3689 /* Parse arguments */
3691 if (set_options(argc
, argv
)) {
3696 if (set_signal_handler()) {
3701 relayd_config_log();
3703 if (opt_print_version
) {
3709 /* Try to create directory if -o, --output is specified. */
3710 if (opt_output_path
) {
3711 if (*opt_output_path
!= '/') {
3712 ERR("Please specify an absolute path for -o, --output PATH");
3717 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3720 ERR("Unable to create %s", opt_output_path
);
3727 if (opt_daemon
|| opt_background
) {
3730 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3738 * We are in the child. Make sure all other file
3739 * descriptors are closed, in case we are called with
3740 * more opened file descriptors than the standard ones.
3742 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3747 if (opt_working_directory
) {
3748 ret
= utils_change_working_directory(opt_working_directory
);
3750 /* All errors are already logged. */
3755 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
3756 if (!sessiond_trace_chunk_registry
) {
3757 ERR("Failed to initialize session daemon trace chunk registry");
3759 goto exit_sessiond_trace_chunk_registry
;
3762 /* Initialize thread health monitoring */
3763 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3764 if (!health_relayd
) {
3765 PERROR("health_app_create error");
3767 goto exit_health_app_create
;
3770 /* Create thread quit pipe */
3771 if (init_thread_quit_pipe()) {
3773 goto exit_init_data
;
3776 /* Setup the thread apps communication pipe. */
3777 if (create_relay_conn_pipe()) {
3779 goto exit_init_data
;
3782 /* Init relay command queue. */
3783 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3785 /* Initialize communication library */
3787 lttcomm_inet_init();
3789 /* tables of sessions indexed by session ID */
3790 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3793 goto exit_init_data
;
3796 /* tables of streams indexed by stream ID */
3797 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3798 if (!relay_streams_ht
) {
3800 goto exit_init_data
;
3803 /* tables of streams indexed by stream ID */
3804 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3805 if (!viewer_streams_ht
) {
3807 goto exit_init_data
;
3810 ret
= utils_create_pipe(health_quit_pipe
);
3813 goto exit_health_quit_pipe
;
3816 /* Create thread to manage the client socket */
3817 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3818 thread_manage_health
, (void *) NULL
);
3821 PERROR("pthread_create health");
3823 goto exit_health_thread
;
3826 /* Setup the dispatcher thread */
3827 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3828 relay_thread_dispatcher
, (void *) NULL
);
3831 PERROR("pthread_create dispatcher");
3833 goto exit_dispatcher_thread
;
3836 /* Setup the worker thread */
3837 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3838 relay_thread_worker
, NULL
);
3841 PERROR("pthread_create worker");
3843 goto exit_worker_thread
;
3846 /* Setup the listener thread */
3847 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3848 relay_thread_listener
, (void *) NULL
);
3851 PERROR("pthread_create listener");
3853 goto exit_listener_thread
;
3856 ret
= relayd_live_create(live_uri
);
3858 ERR("Starting live viewer threads");
3864 * This is where we start awaiting program completion (e.g. through
3865 * signal that asks threads to teardown).
3868 ret
= relayd_live_join();
3874 ret
= pthread_join(listener_thread
, &status
);
3877 PERROR("pthread_join listener_thread");
3881 exit_listener_thread
:
3882 ret
= pthread_join(worker_thread
, &status
);
3885 PERROR("pthread_join worker_thread");
3890 ret
= pthread_join(dispatcher_thread
, &status
);
3893 PERROR("pthread_join dispatcher_thread");
3896 exit_dispatcher_thread
:
3898 ret
= pthread_join(health_thread
, &status
);
3901 PERROR("pthread_join health_thread");
3906 utils_close_pipe(health_quit_pipe
);
3907 exit_health_quit_pipe
:
3910 health_app_destroy(health_relayd
);
3911 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
3912 exit_health_app_create
:
3913 exit_sessiond_trace_chunk_registry
:
3916 * Wait for all pending call_rcu work to complete before tearing
3917 * down data structures. call_rcu worker may be trying to
3918 * perform lookups in those structures.
3923 /* Ensure all prior call_rcu are done. */