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 parse_env_options(void)
414 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
416 opt_working_directory
= strdup(value
);
417 if (!opt_working_directory
) {
418 ERR("Failed to allocate working directory string (\"%s\")",
426 static int set_options(int argc
, char **argv
)
428 int c
, ret
= 0, option_index
= 0, retval
= 0;
429 int orig_optopt
= optopt
, orig_optind
= optind
;
430 char *default_address
, *optstring
;
431 const char *config_path
= NULL
;
433 optstring
= utils_generate_optstring(long_options
,
434 sizeof(long_options
) / sizeof(struct option
));
440 /* Check for the --config option */
442 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
443 &option_index
)) != -1) {
447 } else if (c
!= 'f') {
451 if (lttng_is_setuid_setgid()) {
452 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
455 config_path
= utils_expand_path(optarg
);
457 ERR("Failed to resolve path: %s", optarg
);
462 ret
= config_get_section_entries(config_path
, config_section_name
,
463 config_entry_handler
, NULL
);
466 ERR("Invalid configuration option at line %i", ret
);
472 /* Reset getopt's global state */
473 optopt
= orig_optopt
;
474 optind
= orig_optind
;
476 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
481 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
488 /* assign default values */
489 if (control_uri
== NULL
) {
490 ret
= asprintf(&default_address
,
491 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
492 DEFAULT_NETWORK_CONTROL_PORT
);
494 PERROR("asprintf default data address");
499 ret
= uri_parse(default_address
, &control_uri
);
500 free(default_address
);
502 ERR("Invalid control URI specified");
507 if (data_uri
== NULL
) {
508 ret
= asprintf(&default_address
,
509 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
510 DEFAULT_NETWORK_DATA_PORT
);
512 PERROR("asprintf default data address");
517 ret
= uri_parse(default_address
, &data_uri
);
518 free(default_address
);
520 ERR("Invalid data URI specified");
525 if (live_uri
== NULL
) {
526 ret
= asprintf(&default_address
,
527 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
528 DEFAULT_NETWORK_VIEWER_PORT
);
530 PERROR("asprintf default viewer control address");
535 ret
= uri_parse(default_address
, &live_uri
);
536 free(default_address
);
538 ERR("Invalid viewer control URI specified");
549 static void print_global_objects(void)
551 rcu_register_thread();
553 print_viewer_streams();
554 print_relay_streams();
557 rcu_unregister_thread();
563 static void relayd_cleanup(void)
565 print_global_objects();
569 if (viewer_streams_ht
)
570 lttng_ht_destroy(viewer_streams_ht
);
571 if (relay_streams_ht
)
572 lttng_ht_destroy(relay_streams_ht
);
574 lttng_ht_destroy(sessions_ht
);
576 free(opt_output_path
);
577 free(opt_working_directory
);
579 /* Close thread quit pipes */
580 utils_close_pipe(thread_quit_pipe
);
582 uri_free(control_uri
);
584 /* Live URI is freed in the live thread. */
586 if (tracing_group_name_override
) {
587 free((void *) tracing_group_name
);
592 * Write to writable pipe used to notify a thread.
594 static int notify_thread_pipe(int wpipe
)
598 ret
= lttng_write(wpipe
, "!", 1);
600 PERROR("write poll pipe");
608 static int notify_health_quit_pipe(int *pipe
)
612 ret
= lttng_write(pipe
[1], "4", 1);
614 PERROR("write relay health quit");
623 * Stop all relayd and relayd-live threads.
625 int lttng_relay_stop_threads(void)
629 /* Stopping all threads */
630 DBG("Terminating all threads");
631 if (notify_thread_pipe(thread_quit_pipe
[1])) {
632 ERR("write error on thread quit pipe");
636 if (notify_health_quit_pipe(health_quit_pipe
)) {
637 ERR("write error on health quit pipe");
640 /* Dispatch thread */
641 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
642 futex_nto1_wake(&relay_conn_queue
.futex
);
644 if (relayd_live_stop()) {
645 ERR("Error stopping live threads");
652 * Signal handler for the daemon
654 * Simply stop all worker threads, leaving main() return gracefully after
655 * joining all threads and calling cleanup().
657 static void sighandler(int sig
)
661 DBG("SIGINT caught");
662 if (lttng_relay_stop_threads()) {
663 ERR("Error stopping threads");
667 DBG("SIGTERM caught");
668 if (lttng_relay_stop_threads()) {
669 ERR("Error stopping threads");
673 CMM_STORE_SHARED(recv_child_signal
, 1);
681 * Setup signal handler for :
682 * SIGINT, SIGTERM, SIGPIPE
684 static int set_signal_handler(void)
690 if ((ret
= sigemptyset(&sigset
)) < 0) {
691 PERROR("sigemptyset");
698 sa
.sa_handler
= sighandler
;
699 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
704 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
709 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
714 sa
.sa_handler
= SIG_IGN
;
715 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
720 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
725 void lttng_relay_notify_ready(void)
727 /* Notify the parent of the fork() process that we are ready. */
728 if (opt_daemon
|| opt_background
) {
729 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
730 kill(child_ppid
, SIGUSR1
);
736 * Init thread quit pipe.
738 * Return -1 on error or 0 if all pipes are created.
740 static int init_thread_quit_pipe(void)
744 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
750 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
752 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
756 if (events
== NULL
|| size
== 0) {
761 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
767 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
779 * Check if the thread quit pipe was triggered.
781 * Return 1 if it was triggered else 0;
783 static int check_thread_quit_pipe(int fd
, uint32_t events
)
785 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
793 * Create and init socket from uri.
795 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
798 struct lttcomm_sock
*sock
= NULL
;
800 sock
= lttcomm_alloc_sock_from_uri(uri
);
802 ERR("Allocating socket");
806 ret
= lttcomm_create_sock(sock
);
810 DBG("Listening on sock %d", sock
->fd
);
812 ret
= sock
->ops
->bind(sock
);
814 PERROR("Failed to bind socket");
818 ret
= sock
->ops
->listen(sock
, -1);
828 lttcomm_destroy_sock(sock
);
834 * This thread manages the listening for new connections on the network
836 static void *relay_thread_listener(void *data
)
838 int i
, ret
, pollfd
, err
= -1;
839 uint32_t revents
, nb_fd
;
840 struct lttng_poll_event events
;
841 struct lttcomm_sock
*control_sock
, *data_sock
;
843 DBG("[thread] Relay listener started");
845 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
847 health_code_update();
849 control_sock
= relay_socket_create(control_uri
);
851 goto error_sock_control
;
854 data_sock
= relay_socket_create(data_uri
);
856 goto error_sock_relay
;
860 * Pass 3 as size here for the thread quit pipe, control and
863 ret
= create_thread_poll_set(&events
, 3);
865 goto error_create_poll
;
868 /* Add the control socket */
869 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
874 /* Add the data socket */
875 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
880 lttng_relay_notify_ready();
882 if (testpoint(relayd_thread_listener
)) {
883 goto error_testpoint
;
887 health_code_update();
889 DBG("Listener accepting connections");
893 ret
= lttng_poll_wait(&events
, -1);
897 * Restart interrupted system call.
899 if (errno
== EINTR
) {
907 DBG("Relay new connection received");
908 for (i
= 0; i
< nb_fd
; i
++) {
909 health_code_update();
911 /* Fetch once the poll data */
912 revents
= LTTNG_POLL_GETEV(&events
, i
);
913 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
915 /* Thread quit pipe has been closed. Killing thread. */
916 ret
= check_thread_quit_pipe(pollfd
, revents
);
922 if (revents
& LPOLLIN
) {
924 * A new connection is requested, therefore a
925 * sessiond/consumerd connection is allocated in
926 * this thread, enqueued to a global queue and
927 * dequeued (and freed) in the worker thread.
930 struct relay_connection
*new_conn
;
931 struct lttcomm_sock
*newsock
;
932 enum connection_type type
;
934 if (pollfd
== data_sock
->fd
) {
936 newsock
= data_sock
->ops
->accept(data_sock
);
937 DBG("Relay data connection accepted, socket %d",
940 assert(pollfd
== control_sock
->fd
);
941 type
= RELAY_CONTROL
;
942 newsock
= control_sock
->ops
->accept(control_sock
);
943 DBG("Relay control connection accepted, socket %d",
947 PERROR("accepting sock");
951 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
954 PERROR("setsockopt inet");
955 lttcomm_destroy_sock(newsock
);
959 ret
= socket_apply_keep_alive_config(newsock
->fd
);
961 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
963 lttcomm_destroy_sock(newsock
);
967 new_conn
= connection_create(newsock
, type
);
969 lttcomm_destroy_sock(newsock
);
973 /* Enqueue request for the dispatcher thread. */
974 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
978 * Wake the dispatch queue futex.
979 * Implicit memory barrier with the
980 * exchange in cds_wfcq_enqueue.
982 futex_nto1_wake(&relay_conn_queue
.futex
);
983 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
984 ERR("socket poll error");
987 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
997 lttng_poll_clean(&events
);
999 if (data_sock
->fd
>= 0) {
1000 ret
= data_sock
->ops
->close(data_sock
);
1005 lttcomm_destroy_sock(data_sock
);
1007 if (control_sock
->fd
>= 0) {
1008 ret
= control_sock
->ops
->close(control_sock
);
1013 lttcomm_destroy_sock(control_sock
);
1017 ERR("Health error occurred in %s", __func__
);
1019 health_unregister(health_relayd
);
1020 DBG("Relay listener thread cleanup complete");
1021 lttng_relay_stop_threads();
1026 * This thread manages the dispatching of the requests to worker threads
1028 static void *relay_thread_dispatcher(void *data
)
1032 struct cds_wfcq_node
*node
;
1033 struct relay_connection
*new_conn
= NULL
;
1035 DBG("[thread] Relay dispatcher started");
1037 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1039 if (testpoint(relayd_thread_dispatcher
)) {
1040 goto error_testpoint
;
1043 health_code_update();
1046 health_code_update();
1048 /* Atomically prepare the queue futex */
1049 futex_nto1_prepare(&relay_conn_queue
.futex
);
1051 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1056 health_code_update();
1058 /* Dequeue commands */
1059 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1060 &relay_conn_queue
.tail
);
1062 DBG("Woken up but nothing in the relay command queue");
1063 /* Continue thread execution */
1066 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1068 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1071 * Inform worker thread of the new request. This
1072 * call is blocking so we can be assured that
1073 * the data will be read at some point in time
1074 * or wait to the end of the world :)
1076 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1078 PERROR("write connection pipe");
1079 connection_put(new_conn
);
1082 } while (node
!= NULL
);
1084 /* Futex wait on queue. Blocking call on futex() */
1085 health_poll_entry();
1086 futex_nto1_wait(&relay_conn_queue
.futex
);
1090 /* Normal exit, no error */
1097 ERR("Health error occurred in %s", __func__
);
1099 health_unregister(health_relayd
);
1100 DBG("Dispatch thread dying");
1101 lttng_relay_stop_threads();
1105 static bool session_streams_have_index(const struct relay_session
*session
)
1107 return session
->minor
>= 4 && !session
->snapshot
;
1111 * Handle the RELAYD_CREATE_SESSION command.
1113 * On success, send back the session id or else return a negative value.
1115 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1116 struct relay_connection
*conn
,
1117 const struct lttng_buffer_view
*payload
)
1121 struct relay_session
*session
= NULL
;
1122 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1123 char session_name
[LTTNG_NAME_MAX
] = {};
1124 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1125 uint32_t live_timer
= 0;
1126 bool snapshot
= false;
1127 bool session_name_contains_creation_timestamp
= false;
1128 /* Left nil for peers < 2.11. */
1129 char base_path
[LTTNG_PATH_MAX
] = {};
1130 lttng_uuid sessiond_uuid
= {};
1131 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1132 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1133 LTTNG_OPTIONAL(time_t) creation_time
= {};
1134 struct lttng_dynamic_buffer reply_payload
;
1136 lttng_dynamic_buffer_init(&reply_payload
);
1138 if (conn
->minor
< 4) {
1139 /* From 2.1 to 2.3 */
1141 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1142 /* From 2.4 to 2.10 */
1143 ret
= cmd_create_session_2_4(payload
, session_name
,
1144 hostname
, &live_timer
, &snapshot
);
1146 bool has_current_chunk
;
1147 uint64_t current_chunk_id_value
;
1148 time_t creation_time_value
;
1149 uint64_t id_sessiond_value
;
1151 /* From 2.11 to ... */
1152 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1153 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1154 sessiond_uuid
, &has_current_chunk
,
1155 ¤t_chunk_id_value
, &creation_time_value
,
1156 &session_name_contains_creation_timestamp
);
1157 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1158 /* The nil UUID is reserved for pre-2.11 clients. */
1159 ERR("Illegal nil UUID announced by peer in create session command");
1163 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1164 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1165 if (has_current_chunk
) {
1166 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1167 current_chunk_id_value
);
1175 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1176 snapshot
, sessiond_uuid
,
1177 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1178 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1179 creation_time
.is_set
? &creation_time
.value
: NULL
,
1180 conn
->major
, conn
->minor
,
1181 session_name_contains_creation_timestamp
);
1186 assert(!conn
->session
);
1187 conn
->session
= session
;
1188 DBG("Created session %" PRIu64
, session
->id
);
1190 reply
.generic
.session_id
= htobe64(session
->id
);
1194 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1196 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1199 if (conn
->minor
< 11) {
1200 /* From 2.1 to 2.10 */
1201 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1202 &reply
.generic
, sizeof(reply
.generic
));
1204 ERR("Failed to append \"create session\" command reply header to payload buffer");
1209 const uint32_t output_path_length
=
1210 session
? strlen(session
->output_path
) + 1 : 0;
1212 reply
.output_path_length
= htobe32(output_path_length
);
1213 ret
= lttng_dynamic_buffer_append(
1214 &reply_payload
, &reply
, sizeof(reply
));
1216 ERR("Failed to append \"create session\" command reply header to payload buffer");
1220 if (output_path_length
) {
1221 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1222 session
->output_path
,
1223 output_path_length
);
1225 ERR("Failed to append \"create session\" command reply path to payload buffer");
1231 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1232 reply_payload
.size
, 0);
1233 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1234 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1235 reply_payload
.size
, send_ret
);
1239 if (ret
< 0 && session
) {
1240 session_put(session
);
1242 lttng_dynamic_buffer_reset(&reply_payload
);
1247 * When we have received all the streams and the metadata for a channel,
1248 * we make them visible to the viewer threads.
1250 static void publish_connection_local_streams(struct relay_connection
*conn
)
1252 struct relay_stream
*stream
;
1253 struct relay_session
*session
= conn
->session
;
1256 * We publish all streams belonging to a session atomically wrt
1259 pthread_mutex_lock(&session
->lock
);
1261 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1263 stream_publish(stream
);
1268 * Inform the viewer that there are new streams in the session.
1270 if (session
->viewer_attached
) {
1271 uatomic_set(&session
->new_streams
, 1);
1273 pthread_mutex_unlock(&session
->lock
);
1276 static int conform_channel_path(char *channel_path
)
1280 if (strstr("../", channel_path
)) {
1281 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1287 if (*channel_path
== '/') {
1288 const size_t len
= strlen(channel_path
);
1291 * Channel paths from peers prior to 2.11 are expressed as an
1292 * absolute path that is, in reality, relative to the relay
1293 * daemon's output directory. Remove the leading slash so it
1294 * is correctly interpreted as a relative path later on.
1296 * len (and not len - 1) is used to copy the trailing NULL.
1298 bcopy(channel_path
+ 1, channel_path
, len
);
1305 * relay_add_stream: allocate a new stream for a session
1307 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1308 struct relay_connection
*conn
,
1309 const struct lttng_buffer_view
*payload
)
1313 struct relay_session
*session
= conn
->session
;
1314 struct relay_stream
*stream
= NULL
;
1315 struct lttcomm_relayd_status_stream reply
;
1316 struct ctf_trace
*trace
= NULL
;
1317 uint64_t stream_handle
= -1ULL;
1318 char *path_name
= NULL
, *channel_name
= NULL
;
1319 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1320 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1322 if (!session
|| !conn
->version_check_done
) {
1323 ERR("Trying to add a stream before version check");
1325 goto end_no_session
;
1328 if (session
->minor
== 1) {
1330 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1332 } else if (session
->minor
> 1 && session
->minor
< 11) {
1333 /* From 2.2 to 2.10 */
1334 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1335 &channel_name
, &tracefile_size
, &tracefile_count
);
1337 /* From 2.11 to ... */
1338 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1339 &channel_name
, &tracefile_size
, &tracefile_count
,
1340 &stream_chunk_id
.value
);
1341 stream_chunk_id
.is_set
= true;
1348 if (conform_channel_path(path_name
)) {
1352 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1356 /* This stream here has one reference on the trace. */
1358 pthread_mutex_lock(&last_relay_stream_id_lock
);
1359 stream_handle
= ++last_relay_stream_id
;
1360 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1362 /* We pass ownership of path_name and channel_name. */
1363 stream
= stream_create(trace
, stream_handle
, path_name
,
1364 channel_name
, tracefile_size
, tracefile_count
);
1366 channel_name
= NULL
;
1369 * Streams are the owners of their trace. Reference to trace is
1370 * kept within stream_create().
1372 ctf_trace_put(trace
);
1375 memset(&reply
, 0, sizeof(reply
));
1376 reply
.handle
= htobe64(stream_handle
);
1378 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1380 reply
.ret_code
= htobe32(LTTNG_OK
);
1383 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1384 sizeof(struct lttcomm_relayd_status_stream
), 0);
1385 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1386 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1398 * relay_close_stream: close a specific stream
1400 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1401 struct relay_connection
*conn
,
1402 const struct lttng_buffer_view
*payload
)
1406 struct relay_session
*session
= conn
->session
;
1407 struct lttcomm_relayd_close_stream stream_info
;
1408 struct lttcomm_relayd_generic_reply reply
;
1409 struct relay_stream
*stream
;
1411 DBG("Close stream received");
1413 if (!session
|| !conn
->version_check_done
) {
1414 ERR("Trying to close a stream before version check");
1416 goto end_no_session
;
1419 if (payload
->size
< sizeof(stream_info
)) {
1420 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1421 sizeof(stream_info
), payload
->size
);
1423 goto end_no_session
;
1425 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1426 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1427 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1429 stream
= stream_get_by_id(stream_info
.stream_id
);
1436 * Set last_net_seq_num before the close flag. Required by data
1439 pthread_mutex_lock(&stream
->lock
);
1440 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1441 pthread_mutex_unlock(&stream
->lock
);
1444 * This is one of the conditions which may trigger a stream close
1445 * with the others being:
1446 * 1) A close command is received for a stream
1447 * 2) The control connection owning the stream is closed
1448 * 3) We have received all of the stream's data _after_ a close
1451 try_stream_close(stream
);
1452 if (stream
->is_metadata
) {
1453 struct relay_viewer_stream
*vstream
;
1455 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1457 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1459 * Since all the metadata has been sent to the
1460 * viewer and that we have a request to close
1461 * its stream, we can safely teardown the
1462 * corresponding metadata viewer stream.
1464 viewer_stream_put(vstream
);
1466 /* Put local reference. */
1467 viewer_stream_put(vstream
);
1474 memset(&reply
, 0, sizeof(reply
));
1476 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1478 reply
.ret_code
= htobe32(LTTNG_OK
);
1480 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1481 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1482 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1483 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1493 * relay_reset_metadata: reset a metadata stream
1496 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1497 struct relay_connection
*conn
,
1498 const struct lttng_buffer_view
*payload
)
1502 struct relay_session
*session
= conn
->session
;
1503 struct lttcomm_relayd_reset_metadata stream_info
;
1504 struct lttcomm_relayd_generic_reply reply
;
1505 struct relay_stream
*stream
;
1507 DBG("Reset metadata received");
1509 if (!session
|| !conn
->version_check_done
) {
1510 ERR("Trying to reset a metadata stream before version check");
1512 goto end_no_session
;
1515 if (payload
->size
< sizeof(stream_info
)) {
1516 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1517 sizeof(stream_info
), payload
->size
);
1519 goto end_no_session
;
1521 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1522 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1523 stream_info
.version
= be64toh(stream_info
.version
);
1525 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1527 /* Unsupported for live sessions for now. */
1528 if (session
->live_timer
!= 0) {
1533 stream
= stream_get_by_id(stream_info
.stream_id
);
1538 pthread_mutex_lock(&stream
->lock
);
1539 if (!stream
->is_metadata
) {
1544 ret
= stream_reset_file(stream
);
1546 ERR("Failed to reset metadata stream %" PRIu64
1547 ": stream_path = %s, channel = %s",
1548 stream
->stream_handle
, stream
->path_name
,
1549 stream
->channel_name
);
1553 pthread_mutex_unlock(&stream
->lock
);
1557 memset(&reply
, 0, sizeof(reply
));
1559 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1561 reply
.ret_code
= htobe32(LTTNG_OK
);
1563 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1564 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1565 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1566 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1576 * relay_unknown_command: send -1 if received unknown command
1578 static void relay_unknown_command(struct relay_connection
*conn
)
1580 struct lttcomm_relayd_generic_reply reply
;
1583 memset(&reply
, 0, sizeof(reply
));
1584 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1585 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1586 if (send_ret
< sizeof(reply
)) {
1587 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1592 * relay_start: send an acknowledgment to the client to tell if we are
1593 * ready to receive data. We are ready if a session is established.
1595 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1596 struct relay_connection
*conn
,
1597 const struct lttng_buffer_view
*payload
)
1601 struct lttcomm_relayd_generic_reply reply
;
1602 struct relay_session
*session
= conn
->session
;
1605 DBG("Trying to start the streaming without a session established");
1606 ret
= htobe32(LTTNG_ERR_UNK
);
1609 memset(&reply
, 0, sizeof(reply
));
1610 reply
.ret_code
= htobe32(LTTNG_OK
);
1611 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1613 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1614 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1623 * relay_recv_metadata: receive the metadata for the session.
1625 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1626 struct relay_connection
*conn
,
1627 const struct lttng_buffer_view
*payload
)
1630 struct relay_session
*session
= conn
->session
;
1631 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1632 struct relay_stream
*metadata_stream
;
1633 uint64_t metadata_payload_size
;
1634 struct lttng_buffer_view packet_view
;
1637 ERR("Metadata sent before version check");
1642 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1643 ERR("Incorrect data size");
1647 metadata_payload_size
= recv_hdr
->data_size
-
1648 sizeof(struct lttcomm_relayd_metadata_payload
);
1650 memcpy(&metadata_payload_header
, payload
->data
,
1651 sizeof(metadata_payload_header
));
1652 metadata_payload_header
.stream_id
= be64toh(
1653 metadata_payload_header
.stream_id
);
1654 metadata_payload_header
.padding_size
= be32toh(
1655 metadata_payload_header
.padding_size
);
1657 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1658 if (!metadata_stream
) {
1663 packet_view
= lttng_buffer_view_from_view(payload
,
1664 sizeof(metadata_payload_header
), metadata_payload_size
);
1665 if (!packet_view
.data
) {
1666 ERR("Invalid metadata packet length announced by header");
1671 pthread_mutex_lock(&metadata_stream
->lock
);
1672 ret
= stream_write(metadata_stream
, &packet_view
,
1673 metadata_payload_header
.padding_size
);
1674 pthread_mutex_unlock(&metadata_stream
->lock
);
1680 stream_put(metadata_stream
);
1686 * relay_send_version: send relayd version number
1688 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1689 struct relay_connection
*conn
,
1690 const struct lttng_buffer_view
*payload
)
1694 struct lttcomm_relayd_version reply
, msg
;
1695 bool compatible
= true;
1697 conn
->version_check_done
= true;
1699 /* Get version from the other side. */
1700 if (payload
->size
< sizeof(msg
)) {
1701 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1702 sizeof(msg
), payload
->size
);
1707 memcpy(&msg
, payload
->data
, sizeof(msg
));
1708 msg
.major
= be32toh(msg
.major
);
1709 msg
.minor
= be32toh(msg
.minor
);
1711 memset(&reply
, 0, sizeof(reply
));
1712 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1713 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1715 /* Major versions must be the same */
1716 if (reply
.major
!= msg
.major
) {
1717 DBG("Incompatible major versions (%u vs %u), deleting session",
1718 reply
.major
, msg
.major
);
1722 conn
->major
= reply
.major
;
1723 /* We adapt to the lowest compatible version */
1724 if (reply
.minor
<= msg
.minor
) {
1725 conn
->minor
= reply
.minor
;
1727 conn
->minor
= msg
.minor
;
1730 reply
.major
= htobe32(reply
.major
);
1731 reply
.minor
= htobe32(reply
.minor
);
1732 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1734 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1735 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1748 DBG("Version check done using protocol %u.%u", conn
->major
,
1756 * Check for data pending for a given stream id from the session daemon.
1758 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1759 struct relay_connection
*conn
,
1760 const struct lttng_buffer_view
*payload
)
1762 struct relay_session
*session
= conn
->session
;
1763 struct lttcomm_relayd_data_pending msg
;
1764 struct lttcomm_relayd_generic_reply reply
;
1765 struct relay_stream
*stream
;
1768 uint64_t stream_seq
;
1770 DBG("Data pending command received");
1772 if (!session
|| !conn
->version_check_done
) {
1773 ERR("Trying to check for data before version check");
1775 goto end_no_session
;
1778 if (payload
->size
< sizeof(msg
)) {
1779 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1780 sizeof(msg
), payload
->size
);
1782 goto end_no_session
;
1784 memcpy(&msg
, payload
->data
, sizeof(msg
));
1785 msg
.stream_id
= be64toh(msg
.stream_id
);
1786 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1788 stream
= stream_get_by_id(msg
.stream_id
);
1789 if (stream
== NULL
) {
1794 pthread_mutex_lock(&stream
->lock
);
1796 if (session_streams_have_index(session
)) {
1798 * Ensure that both the index and stream data have been
1799 * flushed up to the requested point.
1801 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
1803 stream_seq
= stream
->prev_data_seq
;
1805 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
1806 ", prev_index_seq %" PRIu64
1807 ", and last_seq %" PRIu64
, msg
.stream_id
,
1808 stream
->prev_data_seq
, stream
->prev_index_seq
,
1809 msg
.last_net_seq_num
);
1811 /* Avoid wrapping issue */
1812 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
1813 /* Data has in fact been written and is NOT pending */
1816 /* Data still being streamed thus pending */
1820 stream
->data_pending_check_done
= true;
1821 pthread_mutex_unlock(&stream
->lock
);
1826 memset(&reply
, 0, sizeof(reply
));
1827 reply
.ret_code
= htobe32(ret
);
1828 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1829 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1830 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1840 * Wait for the control socket to reach a quiescent state.
1842 * Note that for now, when receiving this command from the session
1843 * daemon, this means that every subsequent commands or data received on
1844 * the control socket has been handled. So, this is why we simply return
1847 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1848 struct relay_connection
*conn
,
1849 const struct lttng_buffer_view
*payload
)
1853 struct relay_stream
*stream
;
1854 struct lttcomm_relayd_quiescent_control msg
;
1855 struct lttcomm_relayd_generic_reply reply
;
1857 DBG("Checking quiescent state on control socket");
1859 if (!conn
->session
|| !conn
->version_check_done
) {
1860 ERR("Trying to check for data before version check");
1862 goto end_no_session
;
1865 if (payload
->size
< sizeof(msg
)) {
1866 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1867 sizeof(msg
), payload
->size
);
1869 goto end_no_session
;
1871 memcpy(&msg
, payload
->data
, sizeof(msg
));
1872 msg
.stream_id
= be64toh(msg
.stream_id
);
1874 stream
= stream_get_by_id(msg
.stream_id
);
1878 pthread_mutex_lock(&stream
->lock
);
1879 stream
->data_pending_check_done
= true;
1880 pthread_mutex_unlock(&stream
->lock
);
1882 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1885 memset(&reply
, 0, sizeof(reply
));
1886 reply
.ret_code
= htobe32(LTTNG_OK
);
1887 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1888 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1889 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1901 * Initialize a data pending command. This means that a consumer is about
1902 * to ask for data pending for each stream it holds. Simply iterate over
1903 * all streams of a session and set the data_pending_check_done flag.
1905 * This command returns to the client a LTTNG_OK code.
1907 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1908 struct relay_connection
*conn
,
1909 const struct lttng_buffer_view
*payload
)
1913 struct lttng_ht_iter iter
;
1914 struct lttcomm_relayd_begin_data_pending msg
;
1915 struct lttcomm_relayd_generic_reply reply
;
1916 struct relay_stream
*stream
;
1921 DBG("Init streams for data pending");
1923 if (!conn
->session
|| !conn
->version_check_done
) {
1924 ERR("Trying to check for data before version check");
1926 goto end_no_session
;
1929 if (payload
->size
< sizeof(msg
)) {
1930 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1931 sizeof(msg
), payload
->size
);
1933 goto end_no_session
;
1935 memcpy(&msg
, payload
->data
, sizeof(msg
));
1936 msg
.session_id
= be64toh(msg
.session_id
);
1939 * Iterate over all streams to set the begin data pending flag.
1940 * For now, the streams are indexed by stream handle so we have
1941 * to iterate over all streams to find the one associated with
1942 * the right session_id.
1945 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1947 if (!stream_get(stream
)) {
1950 if (stream
->trace
->session
->id
== msg
.session_id
) {
1951 pthread_mutex_lock(&stream
->lock
);
1952 stream
->data_pending_check_done
= false;
1953 pthread_mutex_unlock(&stream
->lock
);
1954 DBG("Set begin data pending flag to stream %" PRIu64
,
1955 stream
->stream_handle
);
1961 memset(&reply
, 0, sizeof(reply
));
1962 /* All good, send back reply. */
1963 reply
.ret_code
= htobe32(LTTNG_OK
);
1965 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1966 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1967 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1979 * End data pending command. This will check, for a given session id, if
1980 * each stream associated with it has its data_pending_check_done flag
1981 * set. If not, this means that the client lost track of the stream but
1982 * the data is still being streamed on our side. In this case, we inform
1983 * the client that data is in flight.
1985 * Return to the client if there is data in flight or not with a ret_code.
1987 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1988 struct relay_connection
*conn
,
1989 const struct lttng_buffer_view
*payload
)
1993 struct lttng_ht_iter iter
;
1994 struct lttcomm_relayd_end_data_pending msg
;
1995 struct lttcomm_relayd_generic_reply reply
;
1996 struct relay_stream
*stream
;
1997 uint32_t is_data_inflight
= 0;
1999 DBG("End data pending command");
2001 if (!conn
->session
|| !conn
->version_check_done
) {
2002 ERR("Trying to check for data before version check");
2004 goto end_no_session
;
2007 if (payload
->size
< sizeof(msg
)) {
2008 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2009 sizeof(msg
), payload
->size
);
2011 goto end_no_session
;
2013 memcpy(&msg
, payload
->data
, sizeof(msg
));
2014 msg
.session_id
= be64toh(msg
.session_id
);
2017 * Iterate over all streams to see if the begin data pending
2021 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2023 if (!stream_get(stream
)) {
2026 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2030 pthread_mutex_lock(&stream
->lock
);
2031 if (!stream
->data_pending_check_done
) {
2032 uint64_t stream_seq
;
2034 if (session_streams_have_index(conn
->session
)) {
2036 * Ensure that both the index and stream data have been
2037 * flushed up to the requested point.
2039 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2041 stream_seq
= stream
->prev_data_seq
;
2043 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2044 is_data_inflight
= 1;
2045 DBG("Data is still in flight for stream %" PRIu64
,
2046 stream
->stream_handle
);
2047 pthread_mutex_unlock(&stream
->lock
);
2052 pthread_mutex_unlock(&stream
->lock
);
2057 memset(&reply
, 0, sizeof(reply
));
2058 /* All good, send back reply. */
2059 reply
.ret_code
= htobe32(is_data_inflight
);
2061 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2062 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2063 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2075 * Receive an index for a specific stream.
2077 * Return 0 on success else a negative value.
2079 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2080 struct relay_connection
*conn
,
2081 const struct lttng_buffer_view
*payload
)
2085 struct relay_session
*session
= conn
->session
;
2086 struct lttcomm_relayd_index index_info
;
2087 struct lttcomm_relayd_generic_reply reply
;
2088 struct relay_stream
*stream
;
2093 DBG("Relay receiving index");
2095 if (!session
|| !conn
->version_check_done
) {
2096 ERR("Trying to close a stream before version check");
2098 goto end_no_session
;
2101 msg_len
= lttcomm_relayd_index_len(
2102 lttng_to_index_major(conn
->major
, conn
->minor
),
2103 lttng_to_index_minor(conn
->major
, conn
->minor
));
2104 if (payload
->size
< msg_len
) {
2105 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2106 msg_len
, payload
->size
);
2108 goto end_no_session
;
2110 memcpy(&index_info
, payload
->data
, msg_len
);
2111 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2112 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2113 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2114 index_info
.content_size
= be64toh(index_info
.content_size
);
2115 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2116 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2117 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2118 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2120 if (conn
->minor
>= 8) {
2121 index_info
.stream_instance_id
=
2122 be64toh(index_info
.stream_instance_id
);
2123 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2126 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2128 ERR("stream_get_by_id not found");
2133 pthread_mutex_lock(&stream
->lock
);
2134 ret
= stream_add_index(stream
, &index_info
);
2135 pthread_mutex_unlock(&stream
->lock
);
2137 goto end_stream_put
;
2143 memset(&reply
, 0, sizeof(reply
));
2145 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2147 reply
.ret_code
= htobe32(LTTNG_OK
);
2149 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2150 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2151 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2160 * Receive the streams_sent message.
2162 * Return 0 on success else a negative value.
2164 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2165 struct relay_connection
*conn
,
2166 const struct lttng_buffer_view
*payload
)
2170 struct lttcomm_relayd_generic_reply reply
;
2174 DBG("Relay receiving streams_sent");
2176 if (!conn
->session
|| !conn
->version_check_done
) {
2177 ERR("Trying to close a stream before version check");
2179 goto end_no_session
;
2183 * Publish every pending stream in the connection recv list which are
2184 * now ready to be used by the viewer.
2186 publish_connection_local_streams(conn
);
2188 memset(&reply
, 0, sizeof(reply
));
2189 reply
.ret_code
= htobe32(LTTNG_OK
);
2190 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2191 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2192 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2205 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2206 * session rotation feature (not the tracefile rotation feature).
2208 static int relay_rotate_session_streams(
2209 const struct lttcomm_relayd_hdr
*recv_hdr
,
2210 struct relay_connection
*conn
,
2211 const struct lttng_buffer_view
*payload
)
2216 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2217 struct relay_session
*session
= conn
->session
;
2218 struct lttcomm_relayd_rotate_streams rotate_streams
;
2219 struct lttcomm_relayd_generic_reply reply
= {};
2220 struct relay_stream
*stream
= NULL
;
2221 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2222 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2223 struct lttng_buffer_view stream_positions
;
2224 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2225 const char *chunk_id_str
= "none";
2227 if (!session
|| !conn
->version_check_done
) {
2228 ERR("Trying to rotate a stream before version check");
2233 if (session
->major
== 2 && session
->minor
< 11) {
2234 ERR("Unsupported feature before 2.11");
2239 if (payload
->size
< header_len
) {
2240 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2241 header_len
, payload
->size
);
2246 memcpy(&rotate_streams
, payload
->data
, header_len
);
2248 /* Convert header to host endianness. */
2249 rotate_streams
= (typeof(rotate_streams
)) {
2250 .stream_count
= be32toh(rotate_streams
.stream_count
),
2251 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2252 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2253 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2257 if (rotate_streams
.new_chunk_id
.is_set
) {
2259 * Retrieve the trace chunk the stream must transition to. As
2260 * per the protocol, this chunk should have been created
2261 * before this command is received.
2263 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2264 sessiond_trace_chunk_registry
,
2265 session
->sessiond_uuid
, session
->id
,
2266 rotate_streams
.new_chunk_id
.value
);
2267 if (!next_trace_chunk
) {
2268 char uuid_str
[UUID_STR_LEN
];
2270 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2271 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2272 ", trace_chunk_id = %" PRIu64
,
2273 uuid_str
, session
->id
,
2274 rotate_streams
.new_chunk_id
.value
);
2275 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2280 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2281 rotate_streams
.new_chunk_id
.value
);
2282 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2283 chunk_id_str
= "formatting error";
2285 chunk_id_str
= chunk_id_buf
;
2287 session
->has_rotated
= true;
2290 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2291 rotate_streams
.stream_count
, session
->session_name
,
2294 stream_positions
= lttng_buffer_view_from_view(payload
,
2295 sizeof(rotate_streams
), -1);
2296 if (!stream_positions
.data
||
2297 stream_positions
.size
<
2298 (rotate_streams
.stream_count
*
2299 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2300 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2305 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2306 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2307 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2308 const struct lttcomm_relayd_stream_rotation_position pos
= {
2309 .stream_id
= be64toh(position_comm
->stream_id
),
2310 .rotate_at_seq_num
= be64toh(
2311 position_comm
->rotate_at_seq_num
),
2314 stream
= stream_get_by_id(pos
.stream_id
);
2316 reply_code
= LTTNG_ERR_INVALID
;
2321 pthread_mutex_lock(&stream
->lock
);
2322 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2323 pos
.rotate_at_seq_num
);
2324 pthread_mutex_unlock(&stream
->lock
);
2326 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2334 reply_code
= LTTNG_OK
;
2341 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2342 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2343 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2344 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2345 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2350 lttng_trace_chunk_put(next_trace_chunk
);
2357 * relay_create_trace_chunk: create a new trace chunk
2359 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2360 struct relay_connection
*conn
,
2361 const struct lttng_buffer_view
*payload
)
2365 struct relay_session
*session
= conn
->session
;
2366 struct lttcomm_relayd_create_trace_chunk
*msg
;
2367 struct lttcomm_relayd_generic_reply reply
= {};
2368 struct lttng_buffer_view header_view
;
2369 struct lttng_buffer_view chunk_name_view
;
2370 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2371 enum lttng_error_code reply_code
= LTTNG_OK
;
2372 enum lttng_trace_chunk_status chunk_status
;
2373 struct lttng_directory_handle session_output
;
2375 if (!session
|| !conn
->version_check_done
) {
2376 ERR("Trying to create a trace chunk before version check");
2381 if (session
->major
== 2 && session
->minor
< 11) {
2382 ERR("Chunk creation command is unsupported before 2.11");
2387 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2388 if (!header_view
.data
) {
2389 ERR("Failed to receive payload of chunk creation command");
2394 /* Convert to host endianness. */
2395 msg
= (typeof(msg
)) header_view
.data
;
2396 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2397 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2398 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2400 chunk
= lttng_trace_chunk_create(
2401 msg
->chunk_id
, msg
->creation_timestamp
);
2403 ERR("Failed to create trace chunk in trace chunk creation command");
2405 reply_code
= LTTNG_ERR_NOMEM
;
2409 if (msg
->override_name_length
) {
2412 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2414 msg
->override_name_length
);
2415 name
= chunk_name_view
.data
;
2416 if (!name
|| name
[msg
->override_name_length
- 1]) {
2417 ERR("Failed to receive payload of chunk creation command");
2419 reply_code
= LTTNG_ERR_INVALID
;
2423 chunk_status
= lttng_trace_chunk_override_name(
2424 chunk
, chunk_name_view
.data
);
2425 switch (chunk_status
) {
2426 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2428 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2429 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2430 reply_code
= LTTNG_ERR_INVALID
;
2434 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2435 reply_code
= LTTNG_ERR_UNK
;
2441 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2442 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2443 reply_code
= LTTNG_ERR_UNK
;
2448 ret
= session_init_output_directory_handle(
2449 conn
->session
, &session_output
);
2451 reply_code
= LTTNG_ERR_CREATE_DIR_FAIL
;
2454 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, &session_output
);
2455 lttng_directory_handle_fini(&session_output
);
2456 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2457 reply_code
= LTTNG_ERR_UNK
;
2462 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2463 sessiond_trace_chunk_registry
,
2464 conn
->session
->sessiond_uuid
,
2467 if (!published_chunk
) {
2468 char uuid_str
[UUID_STR_LEN
];
2470 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2471 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2476 reply_code
= LTTNG_ERR_NOMEM
;
2480 pthread_mutex_lock(&conn
->session
->lock
);
2481 if (conn
->session
->pending_closure_trace_chunk
) {
2483 * Invalid; this means a second create_trace_chunk command was
2484 * received before a close_trace_chunk.
2486 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2487 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2489 goto end_unlock_session
;
2491 conn
->session
->pending_closure_trace_chunk
=
2492 conn
->session
->current_trace_chunk
;
2493 conn
->session
->current_trace_chunk
= published_chunk
;
2494 published_chunk
= NULL
;
2496 pthread_mutex_unlock(&conn
->session
->lock
);
2498 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2499 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2501 sizeof(struct lttcomm_relayd_generic_reply
),
2503 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2504 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2509 lttng_trace_chunk_put(chunk
);
2510 lttng_trace_chunk_put(published_chunk
);
2515 * relay_close_trace_chunk: close a trace chunk
2517 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2518 struct relay_connection
*conn
,
2519 const struct lttng_buffer_view
*payload
)
2521 int ret
= 0, buf_ret
;
2523 struct relay_session
*session
= conn
->session
;
2524 struct lttcomm_relayd_close_trace_chunk
*msg
;
2525 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2526 struct lttng_buffer_view header_view
;
2527 struct lttng_trace_chunk
*chunk
= NULL
;
2528 enum lttng_error_code reply_code
= LTTNG_OK
;
2529 enum lttng_trace_chunk_status chunk_status
;
2531 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2532 time_t close_timestamp
;
2533 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2534 size_t path_length
= 0;
2535 const char *chunk_name
= NULL
;
2536 struct lttng_dynamic_buffer reply_payload
;
2538 lttng_dynamic_buffer_init(&reply_payload
);
2540 if (!session
|| !conn
->version_check_done
) {
2541 ERR("Trying to close a trace chunk before version check");
2546 if (session
->major
== 2 && session
->minor
< 11) {
2547 ERR("Chunk close command is unsupported before 2.11");
2552 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2553 if (!header_view
.data
) {
2554 ERR("Failed to receive payload of chunk close command");
2559 /* Convert to host endianness. */
2560 msg
= (typeof(msg
)) header_view
.data
;
2561 chunk_id
= be64toh(msg
->chunk_id
);
2562 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2563 close_command
= (typeof(close_command
)){
2564 .value
= be32toh(msg
->close_command
.value
),
2565 .is_set
= msg
->close_command
.is_set
,
2568 chunk
= sessiond_trace_chunk_registry_get_chunk(
2569 sessiond_trace_chunk_registry
,
2570 conn
->session
->sessiond_uuid
,
2574 char uuid_str
[UUID_STR_LEN
];
2576 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2577 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2582 reply_code
= LTTNG_ERR_NOMEM
;
2586 pthread_mutex_lock(&session
->lock
);
2587 if (session
->pending_closure_trace_chunk
&&
2588 session
->pending_closure_trace_chunk
!= chunk
) {
2589 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2590 session
->session_name
);
2591 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2593 goto end_unlock_session
;
2596 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2597 chunk
, close_timestamp
);
2598 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2599 ERR("Failed to set trace chunk close timestamp");
2601 reply_code
= LTTNG_ERR_UNK
;
2602 goto end_unlock_session
;
2605 if (close_command
.is_set
) {
2606 chunk_status
= lttng_trace_chunk_set_close_command(
2607 chunk
, close_command
.value
);
2608 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2610 reply_code
= LTTNG_ERR_INVALID
;
2611 goto end_unlock_session
;
2614 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2615 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2616 ERR("Failed to get chunk name");
2618 reply_code
= LTTNG_ERR_UNK
;
2619 goto end_unlock_session
;
2621 if (!session
->has_rotated
&& !session
->snapshot
) {
2622 ret
= lttng_strncpy(closed_trace_chunk_path
,
2623 session
->output_path
,
2624 sizeof(closed_trace_chunk_path
));
2626 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2627 strlen(session
->output_path
),
2628 sizeof(closed_trace_chunk_path
));
2629 reply_code
= LTTNG_ERR_NOMEM
;
2631 goto end_unlock_session
;
2634 if (session
->snapshot
) {
2635 ret
= snprintf(closed_trace_chunk_path
,
2636 sizeof(closed_trace_chunk_path
),
2637 "%s/%s", session
->output_path
,
2640 ret
= snprintf(closed_trace_chunk_path
,
2641 sizeof(closed_trace_chunk_path
),
2642 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2644 session
->output_path
, chunk_name
);
2646 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
2647 ERR("Failed to format closed trace chunk resulting path");
2648 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
2650 goto end_unlock_session
;
2653 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
2654 path_length
= strlen(closed_trace_chunk_path
) + 1;
2655 if (path_length
> UINT32_MAX
) {
2656 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2658 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2659 goto end_unlock_session
;
2662 if (session
->current_trace_chunk
== chunk
) {
2664 * After a trace chunk close command, no new streams
2665 * referencing the chunk may be created. Hence, on the
2666 * event that no new trace chunk have been created for
2667 * the session, the reference to the current trace chunk
2668 * is released in order to allow it to be reclaimed when
2669 * the last stream releases its reference to it.
2671 lttng_trace_chunk_put(session
->current_trace_chunk
);
2672 session
->current_trace_chunk
= NULL
;
2674 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
2675 session
->pending_closure_trace_chunk
= NULL
;
2677 pthread_mutex_unlock(&session
->lock
);
2680 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
2681 reply
.path_length
= htobe32((uint32_t) path_length
);
2682 buf_ret
= lttng_dynamic_buffer_append(
2683 &reply_payload
, &reply
, sizeof(reply
));
2685 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2689 if (reply_code
== LTTNG_OK
) {
2690 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
2691 closed_trace_chunk_path
, path_length
);
2693 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2698 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2702 if (send_ret
< reply_payload
.size
) {
2703 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2704 reply_payload
.size
, send_ret
);
2709 lttng_trace_chunk_put(chunk
);
2710 lttng_dynamic_buffer_reset(&reply_payload
);
2715 * relay_trace_chunk_exists: check if a trace chunk exists
2717 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
2718 struct relay_connection
*conn
,
2719 const struct lttng_buffer_view
*payload
)
2723 struct relay_session
*session
= conn
->session
;
2724 struct lttcomm_relayd_trace_chunk_exists
*msg
;
2725 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
2726 struct lttng_buffer_view header_view
;
2730 if (!session
|| !conn
->version_check_done
) {
2731 ERR("Trying to close a trace chunk before version check");
2736 if (session
->major
== 2 && session
->minor
< 11) {
2737 ERR("Chunk close command is unsupported before 2.11");
2742 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2743 if (!header_view
.data
) {
2744 ERR("Failed to receive payload of chunk close command");
2749 /* Convert to host endianness. */
2750 msg
= (typeof(msg
)) header_view
.data
;
2751 chunk_id
= be64toh(msg
->chunk_id
);
2753 ret
= sessiond_trace_chunk_registry_chunk_exists(
2754 sessiond_trace_chunk_registry
,
2755 conn
->session
->sessiond_uuid
,
2757 chunk_id
, &chunk_exists
);
2759 * If ret is not 0, send the reply and report the error to the caller.
2760 * It is a protocol (or internal) error and the session/connection
2761 * should be torn down.
2763 reply
= (typeof(reply
)){
2764 .generic
.ret_code
= htobe32((uint32_t)
2765 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
2766 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
2768 send_ret
= conn
->sock
->ops
->sendmsg(
2769 conn
->sock
, &reply
, sizeof(reply
), 0);
2770 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2771 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2779 #define DBG_CMD(cmd_name, conn) \
2780 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2782 static int relay_process_control_command(struct relay_connection
*conn
,
2783 const struct lttcomm_relayd_hdr
*header
,
2784 const struct lttng_buffer_view
*payload
)
2788 switch (header
->cmd
) {
2789 case RELAYD_CREATE_SESSION
:
2790 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2791 ret
= relay_create_session(header
, conn
, payload
);
2793 case RELAYD_ADD_STREAM
:
2794 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2795 ret
= relay_add_stream(header
, conn
, payload
);
2797 case RELAYD_START_DATA
:
2798 DBG_CMD("RELAYD_START_DATA", conn
);
2799 ret
= relay_start(header
, conn
, payload
);
2801 case RELAYD_SEND_METADATA
:
2802 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2803 ret
= relay_recv_metadata(header
, conn
, payload
);
2805 case RELAYD_VERSION
:
2806 DBG_CMD("RELAYD_VERSION", conn
);
2807 ret
= relay_send_version(header
, conn
, payload
);
2809 case RELAYD_CLOSE_STREAM
:
2810 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2811 ret
= relay_close_stream(header
, conn
, payload
);
2813 case RELAYD_DATA_PENDING
:
2814 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2815 ret
= relay_data_pending(header
, conn
, payload
);
2817 case RELAYD_QUIESCENT_CONTROL
:
2818 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2819 ret
= relay_quiescent_control(header
, conn
, payload
);
2821 case RELAYD_BEGIN_DATA_PENDING
:
2822 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2823 ret
= relay_begin_data_pending(header
, conn
, payload
);
2825 case RELAYD_END_DATA_PENDING
:
2826 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2827 ret
= relay_end_data_pending(header
, conn
, payload
);
2829 case RELAYD_SEND_INDEX
:
2830 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2831 ret
= relay_recv_index(header
, conn
, payload
);
2833 case RELAYD_STREAMS_SENT
:
2834 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2835 ret
= relay_streams_sent(header
, conn
, payload
);
2837 case RELAYD_RESET_METADATA
:
2838 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2839 ret
= relay_reset_metadata(header
, conn
, payload
);
2841 case RELAYD_ROTATE_STREAMS
:
2842 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
2843 ret
= relay_rotate_session_streams(header
, conn
, payload
);
2845 case RELAYD_CREATE_TRACE_CHUNK
:
2846 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
2847 ret
= relay_create_trace_chunk(header
, conn
, payload
);
2849 case RELAYD_CLOSE_TRACE_CHUNK
:
2850 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
2851 ret
= relay_close_trace_chunk(header
, conn
, payload
);
2853 case RELAYD_TRACE_CHUNK_EXISTS
:
2854 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
2855 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
2857 case RELAYD_UPDATE_SYNC_INFO
:
2859 ERR("Received unknown command (%u)", header
->cmd
);
2860 relay_unknown_command(conn
);
2869 static enum relay_connection_status
relay_process_control_receive_payload(
2870 struct relay_connection
*conn
)
2873 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2874 struct lttng_dynamic_buffer
*reception_buffer
=
2875 &conn
->protocol
.ctrl
.reception_buffer
;
2876 struct ctrl_connection_state_receive_payload
*state
=
2877 &conn
->protocol
.ctrl
.state
.receive_payload
;
2878 struct lttng_buffer_view payload_view
;
2880 if (state
->left_to_receive
== 0) {
2881 /* Short-circuit for payload-less commands. */
2882 goto reception_complete
;
2885 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2886 reception_buffer
->data
+ state
->received
,
2887 state
->left_to_receive
, MSG_DONTWAIT
);
2889 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2890 PERROR("Unable to receive command payload on sock %d",
2892 status
= RELAY_CONNECTION_STATUS_ERROR
;
2895 } else if (ret
== 0) {
2896 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2897 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2902 assert(ret
<= state
->left_to_receive
);
2904 state
->left_to_receive
-= ret
;
2905 state
->received
+= ret
;
2907 if (state
->left_to_receive
> 0) {
2909 * Can't transition to the protocol's next state, wait to
2910 * receive the rest of the header.
2912 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2913 state
->received
, state
->left_to_receive
,
2919 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2920 conn
->sock
->fd
, state
->received
);
2922 * The payload required to process the command has been received.
2923 * A view to the reception buffer is forwarded to the various
2924 * commands and the state of the control is reset on success.
2926 * Commands are responsible for sending their reply to the peer.
2928 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2930 ret
= relay_process_control_command(conn
,
2931 &state
->header
, &payload_view
);
2933 status
= RELAY_CONNECTION_STATUS_ERROR
;
2937 ret
= connection_reset_protocol_state(conn
);
2939 status
= RELAY_CONNECTION_STATUS_ERROR
;
2945 static enum relay_connection_status
relay_process_control_receive_header(
2946 struct relay_connection
*conn
)
2949 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2950 struct lttcomm_relayd_hdr header
;
2951 struct lttng_dynamic_buffer
*reception_buffer
=
2952 &conn
->protocol
.ctrl
.reception_buffer
;
2953 struct ctrl_connection_state_receive_header
*state
=
2954 &conn
->protocol
.ctrl
.state
.receive_header
;
2956 assert(state
->left_to_receive
!= 0);
2958 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2959 reception_buffer
->data
+ state
->received
,
2960 state
->left_to_receive
, MSG_DONTWAIT
);
2962 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2963 PERROR("Unable to receive control command header on sock %d",
2965 status
= RELAY_CONNECTION_STATUS_ERROR
;
2968 } else if (ret
== 0) {
2969 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2970 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2975 assert(ret
<= state
->left_to_receive
);
2977 state
->left_to_receive
-= ret
;
2978 state
->received
+= ret
;
2980 if (state
->left_to_receive
> 0) {
2982 * Can't transition to the protocol's next state, wait to
2983 * receive the rest of the header.
2985 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2986 state
->received
, state
->left_to_receive
,
2991 /* Transition to next state: receiving the command's payload. */
2992 conn
->protocol
.ctrl
.state_id
=
2993 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2994 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2995 header
.circuit_id
= be64toh(header
.circuit_id
);
2996 header
.data_size
= be64toh(header
.data_size
);
2997 header
.cmd
= be32toh(header
.cmd
);
2998 header
.cmd_version
= be32toh(header
.cmd_version
);
2999 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3000 &header
, sizeof(header
));
3002 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3003 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3006 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3007 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3009 status
= RELAY_CONNECTION_STATUS_ERROR
;
3013 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3015 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3016 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3019 status
= RELAY_CONNECTION_STATUS_ERROR
;
3023 if (header
.data_size
== 0) {
3025 * Manually invoke the next state as the poll loop
3026 * will not wake-up to allow us to proceed further.
3028 status
= relay_process_control_receive_payload(conn
);
3035 * Process the commands received on the control socket
3037 static enum relay_connection_status
relay_process_control(
3038 struct relay_connection
*conn
)
3040 enum relay_connection_status status
;
3042 switch (conn
->protocol
.ctrl
.state_id
) {
3043 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3044 status
= relay_process_control_receive_header(conn
);
3046 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3047 status
= relay_process_control_receive_payload(conn
);
3050 ERR("Unknown control connection protocol state encountered.");
3057 static enum relay_connection_status
relay_process_data_receive_header(
3058 struct relay_connection
*conn
)
3061 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3062 struct data_connection_state_receive_header
*state
=
3063 &conn
->protocol
.data
.state
.receive_header
;
3064 struct lttcomm_relayd_data_hdr header
;
3065 struct relay_stream
*stream
;
3067 assert(state
->left_to_receive
!= 0);
3069 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3070 state
->header_reception_buffer
+ state
->received
,
3071 state
->left_to_receive
, MSG_DONTWAIT
);
3073 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3074 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3075 status
= RELAY_CONNECTION_STATUS_ERROR
;
3078 } else if (ret
== 0) {
3079 /* Orderly shutdown. Not necessary to print an error. */
3080 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3081 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3086 assert(ret
<= state
->left_to_receive
);
3088 state
->left_to_receive
-= ret
;
3089 state
->received
+= ret
;
3091 if (state
->left_to_receive
> 0) {
3093 * Can't transition to the protocol's next state, wait to
3094 * receive the rest of the header.
3096 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3097 state
->received
, state
->left_to_receive
,
3102 /* Transition to next state: receiving the payload. */
3103 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3105 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3106 header
.circuit_id
= be64toh(header
.circuit_id
);
3107 header
.stream_id
= be64toh(header
.stream_id
);
3108 header
.data_size
= be32toh(header
.data_size
);
3109 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3110 header
.padding_size
= be32toh(header
.padding_size
);
3111 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3113 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3115 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3116 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3118 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3119 conn
->sock
->fd
, header
.circuit_id
,
3120 header
.stream_id
, header
.data_size
,
3121 header
.net_seq_num
, header
.padding_size
);
3123 stream
= stream_get_by_id(header
.stream_id
);
3125 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3127 /* Protocol error. */
3128 status
= RELAY_CONNECTION_STATUS_ERROR
;
3132 pthread_mutex_lock(&stream
->lock
);
3133 /* Prepare stream for the reception of a new packet. */
3134 ret
= stream_init_packet(stream
, header
.data_size
,
3135 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3136 pthread_mutex_unlock(&stream
->lock
);
3138 ERR("Failed to rotate stream output file");
3139 status
= RELAY_CONNECTION_STATUS_ERROR
;
3140 goto end_stream_unlock
;
3149 static enum relay_connection_status
relay_process_data_receive_payload(
3150 struct relay_connection
*conn
)
3153 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3154 struct relay_stream
*stream
;
3155 struct data_connection_state_receive_payload
*state
=
3156 &conn
->protocol
.data
.state
.receive_payload
;
3157 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3158 char data_buffer
[chunk_size
];
3159 bool partial_recv
= false;
3160 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3161 uint64_t left_to_receive
= state
->left_to_receive
;
3162 struct relay_session
*session
;
3164 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3165 state
->header
.stream_id
, state
->header
.net_seq_num
,
3166 state
->received
, left_to_receive
);
3168 stream
= stream_get_by_id(state
->header
.stream_id
);
3170 /* Protocol error. */
3171 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3172 state
->header
.stream_id
);
3173 status
= RELAY_CONNECTION_STATUS_ERROR
;
3177 pthread_mutex_lock(&stream
->lock
);
3178 session
= stream
->trace
->session
;
3179 if (!conn
->session
) {
3180 ret
= connection_set_session(conn
, session
);
3182 status
= RELAY_CONNECTION_STATUS_ERROR
;
3183 goto end_stream_unlock
;
3188 * The size of the "chunk" received on any iteration is bounded by:
3189 * - the data left to receive,
3190 * - the data immediately available on the socket,
3191 * - the on-stack data buffer
3193 while (left_to_receive
> 0 && !partial_recv
) {
3194 size_t recv_size
= min(left_to_receive
, chunk_size
);
3195 struct lttng_buffer_view packet_chunk
;
3197 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3198 recv_size
, MSG_DONTWAIT
);
3200 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3201 PERROR("Socket %d error", conn
->sock
->fd
);
3202 status
= RELAY_CONNECTION_STATUS_ERROR
;
3204 goto end_stream_unlock
;
3205 } else if (ret
== 0) {
3206 /* No more data ready to be consumed on socket. */
3207 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3208 state
->header
.stream_id
);
3209 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3211 } else if (ret
< (int) recv_size
) {
3213 * All the data available on the socket has been
3216 partial_recv
= true;
3220 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3222 assert(packet_chunk
.data
);
3224 ret
= stream_write(stream
, &packet_chunk
, 0);
3226 ERR("Relay error writing data to file");
3227 status
= RELAY_CONNECTION_STATUS_ERROR
;
3228 goto end_stream_unlock
;
3231 left_to_receive
-= recv_size
;
3232 state
->received
+= recv_size
;
3233 state
->left_to_receive
= left_to_receive
;
3236 if (state
->left_to_receive
> 0) {
3238 * Did not receive all the data expected, wait for more data to
3239 * become available on the socket.
3241 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3242 state
->header
.stream_id
, state
->received
,
3243 state
->left_to_receive
);
3244 goto end_stream_unlock
;
3247 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3249 status
= RELAY_CONNECTION_STATUS_ERROR
;
3250 goto end_stream_unlock
;
3253 if (session_streams_have_index(session
)) {
3254 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3255 state
->rotate_index
, &index_flushed
,
3256 state
->header
.data_size
+ state
->header
.padding_size
);
3258 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3259 stream
->stream_handle
,
3260 state
->header
.net_seq_num
, ret
);
3261 status
= RELAY_CONNECTION_STATUS_ERROR
;
3262 goto end_stream_unlock
;
3266 if (stream
->prev_data_seq
== -1ULL) {
3270 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3271 state
->header
.padding_size
, state
->header
.net_seq_num
,
3274 status
= RELAY_CONNECTION_STATUS_ERROR
;
3275 goto end_stream_unlock
;
3279 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3280 * contents of *state which are aliased (union) to the same location as
3281 * the new state. Don't use it beyond this point.
3283 connection_reset_protocol_state(conn
);
3287 close_requested
= stream
->close_requested
;
3288 pthread_mutex_unlock(&stream
->lock
);
3289 if (close_requested
&& left_to_receive
== 0) {
3290 try_stream_close(stream
);
3294 pthread_mutex_lock(&session
->lock
);
3295 uatomic_set(&session
->new_streams
, 1);
3296 pthread_mutex_unlock(&session
->lock
);
3305 * relay_process_data: Process the data received on the data socket
3307 static enum relay_connection_status
relay_process_data(
3308 struct relay_connection
*conn
)
3310 enum relay_connection_status status
;
3312 switch (conn
->protocol
.data
.state_id
) {
3313 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3314 status
= relay_process_data_receive_header(conn
);
3316 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3317 status
= relay_process_data_receive_payload(conn
);
3320 ERR("Unexpected data connection communication state.");
3327 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3331 (void) lttng_poll_del(events
, pollfd
);
3333 ret
= close(pollfd
);
3335 ERR("Closing pollfd %d", pollfd
);
3339 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3340 int pollfd
, struct relay_connection
*conn
)
3342 const char *type_str
;
3344 switch (conn
->type
) {
3349 type_str
= "Control";
3351 case RELAY_VIEWER_COMMAND
:
3352 type_str
= "Viewer Command";
3354 case RELAY_VIEWER_NOTIFICATION
:
3355 type_str
= "Viewer Notification";
3358 type_str
= "Unknown";
3360 cleanup_connection_pollfd(events
, pollfd
);
3361 connection_put(conn
);
3362 DBG("%s connection closed with %d", type_str
, pollfd
);
3366 * This thread does the actual work
3368 static void *relay_thread_worker(void *data
)
3370 int ret
, err
= -1, last_seen_data_fd
= -1;
3372 struct lttng_poll_event events
;
3373 struct lttng_ht
*relay_connections_ht
;
3374 struct lttng_ht_iter iter
;
3375 struct relay_connection
*destroy_conn
= NULL
;
3377 DBG("[thread] Relay worker started");
3379 rcu_register_thread();
3381 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3383 if (testpoint(relayd_thread_worker
)) {
3384 goto error_testpoint
;
3387 health_code_update();
3389 /* table of connections indexed on socket */
3390 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3391 if (!relay_connections_ht
) {
3392 goto relay_connections_ht_error
;
3395 ret
= create_thread_poll_set(&events
, 2);
3397 goto error_poll_create
;
3400 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3407 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3409 health_code_update();
3411 /* Infinite blocking call, waiting for transmission */
3412 DBG3("Relayd worker thread polling...");
3413 health_poll_entry();
3414 ret
= lttng_poll_wait(&events
, -1);
3418 * Restart interrupted system call.
3420 if (errno
== EINTR
) {
3429 * Process control. The control connection is
3430 * prioritized so we don't starve it with high
3431 * throughput tracing data on the data connection.
3433 for (i
= 0; i
< nb_fd
; i
++) {
3434 /* Fetch once the poll data */
3435 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3436 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3438 health_code_update();
3440 /* Thread quit pipe has been closed. Killing thread. */
3441 ret
= check_thread_quit_pipe(pollfd
, revents
);
3447 /* Inspect the relay conn pipe for new connection */
3448 if (pollfd
== relay_conn_pipe
[0]) {
3449 if (revents
& LPOLLIN
) {
3450 struct relay_connection
*conn
;
3452 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3456 ret
= lttng_poll_add(&events
,
3458 LPOLLIN
| LPOLLRDHUP
);
3460 ERR("Failed to add new connection file descriptor to poll set");
3463 connection_ht_add(relay_connections_ht
, conn
);
3464 DBG("Connection socket %d added", conn
->sock
->fd
);
3465 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3466 ERR("Relay connection pipe error");
3469 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3473 struct relay_connection
*ctrl_conn
;
3475 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3476 /* If not found, there is a synchronization issue. */
3479 if (ctrl_conn
->type
== RELAY_DATA
) {
3480 if (revents
& LPOLLIN
) {
3482 * Flag the last seen data fd not deleted. It will be
3483 * used as the last seen fd if any fd gets deleted in
3486 last_notdel_data_fd
= pollfd
;
3488 goto put_ctrl_connection
;
3490 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3492 if (revents
& LPOLLIN
) {
3493 enum relay_connection_status status
;
3495 status
= relay_process_control(ctrl_conn
);
3496 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3498 * On socket error flag the session as aborted to force
3499 * the cleanup of its stream otherwise it can leak
3500 * during the lifetime of the relayd.
3502 * This prevents situations in which streams can be
3503 * left opened because an index was received, the
3504 * control connection is closed, and the data
3505 * connection is closed (uncleanly) before the packet's
3508 * Since the control connection encountered an error,
3509 * it is okay to be conservative and close the
3510 * session right now as we can't rely on the protocol
3511 * being respected anymore.
3513 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3514 session_abort(ctrl_conn
->session
);
3517 /* Clear the connection on error or close. */
3518 relay_thread_close_connection(&events
,
3523 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3524 relay_thread_close_connection(&events
,
3526 if (last_seen_data_fd
== pollfd
) {
3527 last_seen_data_fd
= last_notdel_data_fd
;
3530 ERR("Unexpected poll events %u for control sock %d",
3532 connection_put(ctrl_conn
);
3535 put_ctrl_connection
:
3536 connection_put(ctrl_conn
);
3541 * The last loop handled a control request, go back to poll to make
3542 * sure we prioritise the control socket.
3548 if (last_seen_data_fd
>= 0) {
3549 for (i
= 0; i
< nb_fd
; i
++) {
3550 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3552 health_code_update();
3554 if (last_seen_data_fd
== pollfd
) {
3561 /* Process data connection. */
3562 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3563 /* Fetch the poll data. */
3564 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3565 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3566 struct relay_connection
*data_conn
;
3568 health_code_update();
3571 /* No activity for this FD (poll implementation). */
3575 /* Skip the command pipe. It's handled in the first loop. */
3576 if (pollfd
== relay_conn_pipe
[0]) {
3580 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3582 /* Skip it. Might be removed before. */
3585 if (data_conn
->type
== RELAY_CONTROL
) {
3586 goto put_data_connection
;
3588 assert(data_conn
->type
== RELAY_DATA
);
3590 if (revents
& LPOLLIN
) {
3591 enum relay_connection_status status
;
3593 status
= relay_process_data(data_conn
);
3594 /* Connection closed or error. */
3595 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3597 * On socket error flag the session as aborted to force
3598 * the cleanup of its stream otherwise it can leak
3599 * during the lifetime of the relayd.
3601 * This prevents situations in which streams can be
3602 * left opened because an index was received, the
3603 * control connection is closed, and the data
3604 * connection is closed (uncleanly) before the packet's
3607 * Since the data connection encountered an error,
3608 * it is okay to be conservative and close the
3609 * session right now as we can't rely on the protocol
3610 * being respected anymore.
3612 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3613 session_abort(data_conn
->session
);
3615 relay_thread_close_connection(&events
, pollfd
,
3618 * Every goto restart call sets the last seen fd where
3619 * here we don't really care since we gracefully
3620 * continue the loop after the connection is deleted.
3623 /* Keep last seen port. */
3624 last_seen_data_fd
= pollfd
;
3625 connection_put(data_conn
);
3628 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3629 relay_thread_close_connection(&events
, pollfd
,
3632 ERR("Unknown poll events %u for data sock %d",
3635 put_data_connection
:
3636 connection_put(data_conn
);
3638 last_seen_data_fd
= -1;
3641 /* Normal exit, no error */
3646 /* Cleanup remaining connection object. */
3648 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3651 health_code_update();
3653 session_abort(destroy_conn
->session
);
3656 * No need to grab another ref, because we own
3659 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3664 lttng_poll_clean(&events
);
3666 lttng_ht_destroy(relay_connections_ht
);
3667 relay_connections_ht_error
:
3668 /* Close relay conn pipes */
3669 utils_close_pipe(relay_conn_pipe
);
3671 DBG("Thread exited with error");
3673 DBG("Worker thread cleanup complete");
3677 ERR("Health error occurred in %s", __func__
);
3679 health_unregister(health_relayd
);
3680 rcu_unregister_thread();
3681 lttng_relay_stop_threads();
3686 * Create the relay command pipe to wake thread_manage_apps.
3687 * Closed in cleanup().
3689 static int create_relay_conn_pipe(void)
3693 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3701 int main(int argc
, char **argv
)
3703 int ret
= 0, retval
= 0;
3706 /* Parse environment variables */
3707 ret
= parse_env_options();
3715 * Command line arguments overwrite environment.
3718 if (set_options(argc
, argv
)) {
3723 if (set_signal_handler()) {
3728 relayd_config_log();
3730 if (opt_print_version
) {
3736 /* Try to create directory if -o, --output is specified. */
3737 if (opt_output_path
) {
3738 if (*opt_output_path
!= '/') {
3739 ERR("Please specify an absolute path for -o, --output PATH");
3744 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3747 ERR("Unable to create %s", opt_output_path
);
3754 if (opt_daemon
|| opt_background
) {
3757 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3765 * We are in the child. Make sure all other file
3766 * descriptors are closed, in case we are called with
3767 * more opened file descriptors than the standard ones.
3769 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3774 if (opt_working_directory
) {
3775 ret
= utils_change_working_directory(opt_working_directory
);
3777 /* All errors are already logged. */
3782 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
3783 if (!sessiond_trace_chunk_registry
) {
3784 ERR("Failed to initialize session daemon trace chunk registry");
3786 goto exit_sessiond_trace_chunk_registry
;
3789 /* Initialize thread health monitoring */
3790 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3791 if (!health_relayd
) {
3792 PERROR("health_app_create error");
3794 goto exit_health_app_create
;
3797 /* Create thread quit pipe */
3798 if (init_thread_quit_pipe()) {
3800 goto exit_init_data
;
3803 /* Setup the thread apps communication pipe. */
3804 if (create_relay_conn_pipe()) {
3806 goto exit_init_data
;
3809 /* Init relay command queue. */
3810 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3812 /* Initialize communication library */
3814 lttcomm_inet_init();
3816 /* tables of sessions indexed by session ID */
3817 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3820 goto exit_init_data
;
3823 /* tables of streams indexed by stream ID */
3824 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3825 if (!relay_streams_ht
) {
3827 goto exit_init_data
;
3830 /* tables of streams indexed by stream ID */
3831 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3832 if (!viewer_streams_ht
) {
3834 goto exit_init_data
;
3837 ret
= utils_create_pipe(health_quit_pipe
);
3840 goto exit_health_quit_pipe
;
3843 /* Create thread to manage the client socket */
3844 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3845 thread_manage_health
, (void *) NULL
);
3848 PERROR("pthread_create health");
3850 goto exit_health_thread
;
3853 /* Setup the dispatcher thread */
3854 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3855 relay_thread_dispatcher
, (void *) NULL
);
3858 PERROR("pthread_create dispatcher");
3860 goto exit_dispatcher_thread
;
3863 /* Setup the worker thread */
3864 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3865 relay_thread_worker
, NULL
);
3868 PERROR("pthread_create worker");
3870 goto exit_worker_thread
;
3873 /* Setup the listener thread */
3874 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3875 relay_thread_listener
, (void *) NULL
);
3878 PERROR("pthread_create listener");
3880 goto exit_listener_thread
;
3883 ret
= relayd_live_create(live_uri
);
3885 ERR("Starting live viewer threads");
3891 * This is where we start awaiting program completion (e.g. through
3892 * signal that asks threads to teardown).
3895 ret
= relayd_live_join();
3901 ret
= pthread_join(listener_thread
, &status
);
3904 PERROR("pthread_join listener_thread");
3908 exit_listener_thread
:
3909 ret
= pthread_join(worker_thread
, &status
);
3912 PERROR("pthread_join worker_thread");
3917 ret
= pthread_join(dispatcher_thread
, &status
);
3920 PERROR("pthread_join dispatcher_thread");
3923 exit_dispatcher_thread
:
3925 ret
= pthread_join(health_thread
, &status
);
3928 PERROR("pthread_join health_thread");
3933 utils_close_pipe(health_quit_pipe
);
3934 exit_health_quit_pipe
:
3937 health_app_destroy(health_relayd
);
3938 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
3939 exit_health_app_create
:
3940 exit_sessiond_trace_chunk_registry
:
3943 * Wait for all pending call_rcu work to complete before tearing
3944 * down data structures. call_rcu worker may be trying to
3945 * perform lookups in those structures.
3950 /* Ensure all prior call_rcu are done. */