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
;
101 enum relay_group_output_by opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
;
104 * We need to wait for listener and live listener threads, as well as
105 * health check thread, before being ready to signal readiness.
107 #define NR_LTTNG_RELAY_READY 3
108 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
110 /* Size of receive buffer. */
111 #define RECV_DATA_BUFFER_SIZE 65536
113 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
114 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
116 static struct lttng_uri
*control_uri
;
117 static struct lttng_uri
*data_uri
;
118 static struct lttng_uri
*live_uri
;
120 const char *progname
;
122 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
123 static int tracing_group_name_override
;
125 const char * const config_section_name
= "relayd";
128 * Quit pipe for all threads. This permits a single cancellation point
129 * for all threads when receiving an event on the pipe.
131 int thread_quit_pipe
[2] = { -1, -1 };
134 * This pipe is used to inform the worker thread that a command is queued and
135 * ready to be processed.
137 static int relay_conn_pipe
[2] = { -1, -1 };
139 /* Shared between threads */
140 static int dispatch_thread_exit
;
142 static pthread_t listener_thread
;
143 static pthread_t dispatcher_thread
;
144 static pthread_t worker_thread
;
145 static pthread_t health_thread
;
148 * last_relay_stream_id_lock protects last_relay_stream_id increment
149 * atomicity on 32-bit architectures.
151 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
152 static uint64_t last_relay_stream_id
;
155 * Relay command queue.
157 * The relay_thread_listener and relay_thread_dispatcher communicate with this
160 static struct relay_conn_queue relay_conn_queue
;
162 /* Global relay stream hash table. */
163 struct lttng_ht
*relay_streams_ht
;
165 /* Global relay viewer stream hash table. */
166 struct lttng_ht
*viewer_streams_ht
;
168 /* Global relay sessions hash table. */
169 struct lttng_ht
*sessions_ht
;
171 /* Relayd health monitoring */
172 struct health_app
*health_relayd
;
174 struct sessiond_trace_chunk_registry
*sessiond_trace_chunk_registry
;
176 static struct option long_options
[] = {
177 { "control-port", 1, 0, 'C', },
178 { "data-port", 1, 0, 'D', },
179 { "live-port", 1, 0, 'L', },
180 { "daemonize", 0, 0, 'd', },
181 { "background", 0, 0, 'b', },
182 { "group", 1, 0, 'g', },
183 { "help", 0, 0, 'h', },
184 { "output", 1, 0, 'o', },
185 { "verbose", 0, 0, 'v', },
186 { "config", 1, 0, 'f' },
187 { "version", 0, 0, 'V' },
188 { "working-directory", 1, 0, 'w', },
189 { "group-output-by-session", 0, 0, 's', },
190 { "group-output-by-host", 0, 0, 'p', },
194 static const char *config_ignore_options
[] = { "help", "config", "version" };
196 static void print_version(void) {
197 fprintf(stdout
, "%s\n", VERSION
);
200 static void relayd_config_log(void)
202 DBG("LTTng-relayd " VERSION
" - " VERSION_NAME
"%s%s",
203 GIT_VERSION
[0] == '\0' ? "" : " - " GIT_VERSION
,
204 EXTRA_VERSION_NAME
[0] == '\0' ? "" : " - " EXTRA_VERSION_NAME
);
205 if (EXTRA_VERSION_DESCRIPTION
[0] != '\0') {
206 DBG("LTTng-relayd extra version description:\n\t" EXTRA_VERSION_DESCRIPTION
"\n");
208 if (EXTRA_VERSION_PATCHES
[0] != '\0') {
209 DBG("LTTng-relayd extra patches:\n\t" EXTRA_VERSION_PATCHES
"\n");
214 * Take an option from the getopt output and set it in the right variable to be
217 * Return 0 on success else a negative value.
219 static int set_option(int opt
, const char *arg
, const char *optname
)
225 fprintf(stderr
, "option %s", optname
);
227 fprintf(stderr
, " with arg %s\n", arg
);
231 if (lttng_is_setuid_setgid()) {
232 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
233 "-C, --control-port");
235 ret
= uri_parse(arg
, &control_uri
);
237 ERR("Invalid control URI specified");
240 if (control_uri
->port
== 0) {
241 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
246 if (lttng_is_setuid_setgid()) {
247 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
250 ret
= uri_parse(arg
, &data_uri
);
252 ERR("Invalid data URI specified");
255 if (data_uri
->port
== 0) {
256 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
261 if (lttng_is_setuid_setgid()) {
262 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
265 ret
= uri_parse(arg
, &live_uri
);
267 ERR("Invalid live URI specified");
270 if (live_uri
->port
== 0) {
271 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
282 if (lttng_is_setuid_setgid()) {
283 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 tracing_group_name
= strdup(arg
);
287 if (tracing_group_name
== NULL
) {
292 tracing_group_name_override
= 1;
296 ret
= utils_show_help(8, "lttng-relayd", help_msg
);
298 ERR("Cannot show --help for `lttng-relayd`");
303 opt_print_version
= 1;
306 if (lttng_is_setuid_setgid()) {
307 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
310 ret
= asprintf(&opt_output_path
, "%s", arg
);
313 PERROR("asprintf opt_output_path");
319 if (lttng_is_setuid_setgid()) {
320 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
321 "-w, --working-directory");
323 ret
= asprintf(&opt_working_directory
, "%s", arg
);
326 PERROR("asprintf opt_working_directory");
333 /* Verbose level can increase using multiple -v */
335 lttng_opt_verbose
= config_parse_value(arg
);
337 /* Only 3 level of verbosity (-vvv). */
338 if (lttng_opt_verbose
< 3) {
339 lttng_opt_verbose
+= 1;
344 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
345 ERR("Cannot set --group-output-by-session, another --group-output-by argument is present");
348 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_SESSION
;
351 if (opt_group_output_by
!= RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
352 ERR("Cannot set --group-output-by-host, another --group-output-by argument is present");
355 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
358 /* Unknown option or other error.
359 * Error is printed by getopt, just return */
372 * config_entry_handler_cb used to handle options read from a config file.
373 * See config_entry_handler_cb comment in common/config/session-config.h for the
374 * return value conventions.
376 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
380 if (!entry
|| !entry
->name
|| !entry
->value
) {
385 /* Check if the option is to be ignored */
386 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
387 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
392 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
393 /* Ignore if entry name is not fully matched. */
394 if (strcmp(entry
->name
, long_options
[i
].name
)) {
399 * If the option takes no argument on the command line,
400 * we have to check if the value is "true". We support
401 * non-zero numeric values, true, on and yes.
403 if (!long_options
[i
].has_arg
) {
404 ret
= config_parse_value(entry
->value
);
407 WARN("Invalid configuration value \"%s\" for option %s",
408 entry
->value
, entry
->name
);
410 /* False, skip boolean config option. */
415 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
419 WARN("Unrecognized option \"%s\" in daemon configuration file.",
426 static int parse_env_options(void)
431 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
433 opt_working_directory
= strdup(value
);
434 if (!opt_working_directory
) {
435 ERR("Failed to allocate working directory string (\"%s\")",
443 static int set_options(int argc
, char **argv
)
445 int c
, ret
= 0, option_index
= 0, retval
= 0;
446 int orig_optopt
= optopt
, orig_optind
= optind
;
447 char *default_address
, *optstring
;
448 const char *config_path
= NULL
;
450 optstring
= utils_generate_optstring(long_options
,
451 sizeof(long_options
) / sizeof(struct option
));
457 /* Check for the --config option */
459 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
460 &option_index
)) != -1) {
464 } else if (c
!= 'f') {
468 if (lttng_is_setuid_setgid()) {
469 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
472 config_path
= utils_expand_path(optarg
);
474 ERR("Failed to resolve path: %s", optarg
);
479 ret
= config_get_section_entries(config_path
, config_section_name
,
480 config_entry_handler
, NULL
);
483 ERR("Invalid configuration option at line %i", ret
);
489 /* Reset getopt's global state */
490 optopt
= orig_optopt
;
491 optind
= orig_optind
;
493 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
498 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
505 /* assign default values */
506 if (control_uri
== NULL
) {
507 ret
= asprintf(&default_address
,
508 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
509 DEFAULT_NETWORK_CONTROL_PORT
);
511 PERROR("asprintf default data address");
516 ret
= uri_parse(default_address
, &control_uri
);
517 free(default_address
);
519 ERR("Invalid control URI specified");
524 if (data_uri
== NULL
) {
525 ret
= asprintf(&default_address
,
526 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
527 DEFAULT_NETWORK_DATA_PORT
);
529 PERROR("asprintf default data address");
534 ret
= uri_parse(default_address
, &data_uri
);
535 free(default_address
);
537 ERR("Invalid data URI specified");
542 if (live_uri
== NULL
) {
543 ret
= asprintf(&default_address
,
544 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
545 DEFAULT_NETWORK_VIEWER_PORT
);
547 PERROR("asprintf default viewer control address");
552 ret
= uri_parse(default_address
, &live_uri
);
553 free(default_address
);
555 ERR("Invalid viewer control URI specified");
561 if (opt_group_output_by
== RELAYD_GROUP_OUTPUT_BY_UNKNOWN
) {
562 opt_group_output_by
= RELAYD_GROUP_OUTPUT_BY_HOST
;
570 static void print_global_objects(void)
572 rcu_register_thread();
574 print_viewer_streams();
575 print_relay_streams();
578 rcu_unregister_thread();
584 static void relayd_cleanup(void)
586 print_global_objects();
590 if (viewer_streams_ht
)
591 lttng_ht_destroy(viewer_streams_ht
);
592 if (relay_streams_ht
)
593 lttng_ht_destroy(relay_streams_ht
);
595 lttng_ht_destroy(sessions_ht
);
597 free(opt_output_path
);
598 free(opt_working_directory
);
600 /* Close thread quit pipes */
601 utils_close_pipe(thread_quit_pipe
);
603 uri_free(control_uri
);
605 /* Live URI is freed in the live thread. */
607 if (tracing_group_name_override
) {
608 free((void *) tracing_group_name
);
613 * Write to writable pipe used to notify a thread.
615 static int notify_thread_pipe(int wpipe
)
619 ret
= lttng_write(wpipe
, "!", 1);
621 PERROR("write poll pipe");
629 static int notify_health_quit_pipe(int *pipe
)
633 ret
= lttng_write(pipe
[1], "4", 1);
635 PERROR("write relay health quit");
644 * Stop all relayd and relayd-live threads.
646 int lttng_relay_stop_threads(void)
650 /* Stopping all threads */
651 DBG("Terminating all threads");
652 if (notify_thread_pipe(thread_quit_pipe
[1])) {
653 ERR("write error on thread quit pipe");
657 if (notify_health_quit_pipe(health_quit_pipe
)) {
658 ERR("write error on health quit pipe");
661 /* Dispatch thread */
662 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
663 futex_nto1_wake(&relay_conn_queue
.futex
);
665 if (relayd_live_stop()) {
666 ERR("Error stopping live threads");
673 * Signal handler for the daemon
675 * Simply stop all worker threads, leaving main() return gracefully after
676 * joining all threads and calling cleanup().
678 static void sighandler(int sig
)
682 DBG("SIGINT caught");
683 if (lttng_relay_stop_threads()) {
684 ERR("Error stopping threads");
688 DBG("SIGTERM caught");
689 if (lttng_relay_stop_threads()) {
690 ERR("Error stopping threads");
694 CMM_STORE_SHARED(recv_child_signal
, 1);
702 * Setup signal handler for :
703 * SIGINT, SIGTERM, SIGPIPE
705 static int set_signal_handler(void)
711 if ((ret
= sigemptyset(&sigset
)) < 0) {
712 PERROR("sigemptyset");
719 sa
.sa_handler
= sighandler
;
720 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
725 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
730 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
735 sa
.sa_handler
= SIG_IGN
;
736 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
741 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
746 void lttng_relay_notify_ready(void)
748 /* Notify the parent of the fork() process that we are ready. */
749 if (opt_daemon
|| opt_background
) {
750 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
751 kill(child_ppid
, SIGUSR1
);
757 * Init thread quit pipe.
759 * Return -1 on error or 0 if all pipes are created.
761 static int init_thread_quit_pipe(void)
765 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
771 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
773 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
777 if (events
== NULL
|| size
== 0) {
782 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
788 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
800 * Check if the thread quit pipe was triggered.
802 * Return 1 if it was triggered else 0;
804 static int check_thread_quit_pipe(int fd
, uint32_t events
)
806 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
814 * Create and init socket from uri.
816 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
819 struct lttcomm_sock
*sock
= NULL
;
821 sock
= lttcomm_alloc_sock_from_uri(uri
);
823 ERR("Allocating socket");
827 ret
= lttcomm_create_sock(sock
);
831 DBG("Listening on sock %d", sock
->fd
);
833 ret
= sock
->ops
->bind(sock
);
835 PERROR("Failed to bind socket");
839 ret
= sock
->ops
->listen(sock
, -1);
849 lttcomm_destroy_sock(sock
);
855 * This thread manages the listening for new connections on the network
857 static void *relay_thread_listener(void *data
)
859 int i
, ret
, pollfd
, err
= -1;
860 uint32_t revents
, nb_fd
;
861 struct lttng_poll_event events
;
862 struct lttcomm_sock
*control_sock
, *data_sock
;
864 DBG("[thread] Relay listener started");
866 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
868 health_code_update();
870 control_sock
= relay_socket_create(control_uri
);
872 goto error_sock_control
;
875 data_sock
= relay_socket_create(data_uri
);
877 goto error_sock_relay
;
881 * Pass 3 as size here for the thread quit pipe, control and
884 ret
= create_thread_poll_set(&events
, 3);
886 goto error_create_poll
;
889 /* Add the control socket */
890 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
895 /* Add the data socket */
896 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
901 lttng_relay_notify_ready();
903 if (testpoint(relayd_thread_listener
)) {
904 goto error_testpoint
;
908 health_code_update();
910 DBG("Listener accepting connections");
914 ret
= lttng_poll_wait(&events
, -1);
918 * Restart interrupted system call.
920 if (errno
== EINTR
) {
928 DBG("Relay new connection received");
929 for (i
= 0; i
< nb_fd
; i
++) {
930 health_code_update();
932 /* Fetch once the poll data */
933 revents
= LTTNG_POLL_GETEV(&events
, i
);
934 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
936 /* Thread quit pipe has been closed. Killing thread. */
937 ret
= check_thread_quit_pipe(pollfd
, revents
);
943 if (revents
& LPOLLIN
) {
945 * A new connection is requested, therefore a
946 * sessiond/consumerd connection is allocated in
947 * this thread, enqueued to a global queue and
948 * dequeued (and freed) in the worker thread.
951 struct relay_connection
*new_conn
;
952 struct lttcomm_sock
*newsock
;
953 enum connection_type type
;
955 if (pollfd
== data_sock
->fd
) {
957 newsock
= data_sock
->ops
->accept(data_sock
);
958 DBG("Relay data connection accepted, socket %d",
961 assert(pollfd
== control_sock
->fd
);
962 type
= RELAY_CONTROL
;
963 newsock
= control_sock
->ops
->accept(control_sock
);
964 DBG("Relay control connection accepted, socket %d",
968 PERROR("accepting sock");
972 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
975 PERROR("setsockopt inet");
976 lttcomm_destroy_sock(newsock
);
980 ret
= socket_apply_keep_alive_config(newsock
->fd
);
982 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
984 lttcomm_destroy_sock(newsock
);
988 new_conn
= connection_create(newsock
, type
);
990 lttcomm_destroy_sock(newsock
);
994 /* Enqueue request for the dispatcher thread. */
995 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
999 * Wake the dispatch queue futex.
1000 * Implicit memory barrier with the
1001 * exchange in cds_wfcq_enqueue.
1003 futex_nto1_wake(&relay_conn_queue
.futex
);
1004 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
1005 ERR("socket poll error");
1008 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
1018 lttng_poll_clean(&events
);
1020 if (data_sock
->fd
>= 0) {
1021 ret
= data_sock
->ops
->close(data_sock
);
1026 lttcomm_destroy_sock(data_sock
);
1028 if (control_sock
->fd
>= 0) {
1029 ret
= control_sock
->ops
->close(control_sock
);
1034 lttcomm_destroy_sock(control_sock
);
1038 ERR("Health error occurred in %s", __func__
);
1040 health_unregister(health_relayd
);
1041 DBG("Relay listener thread cleanup complete");
1042 lttng_relay_stop_threads();
1047 * This thread manages the dispatching of the requests to worker threads
1049 static void *relay_thread_dispatcher(void *data
)
1053 struct cds_wfcq_node
*node
;
1054 struct relay_connection
*new_conn
= NULL
;
1056 DBG("[thread] Relay dispatcher started");
1058 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1060 if (testpoint(relayd_thread_dispatcher
)) {
1061 goto error_testpoint
;
1064 health_code_update();
1067 health_code_update();
1069 /* Atomically prepare the queue futex */
1070 futex_nto1_prepare(&relay_conn_queue
.futex
);
1072 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1077 health_code_update();
1079 /* Dequeue commands */
1080 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1081 &relay_conn_queue
.tail
);
1083 DBG("Woken up but nothing in the relay command queue");
1084 /* Continue thread execution */
1087 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1089 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1092 * Inform worker thread of the new request. This
1093 * call is blocking so we can be assured that
1094 * the data will be read at some point in time
1095 * or wait to the end of the world :)
1097 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1099 PERROR("write connection pipe");
1100 connection_put(new_conn
);
1103 } while (node
!= NULL
);
1105 /* Futex wait on queue. Blocking call on futex() */
1106 health_poll_entry();
1107 futex_nto1_wait(&relay_conn_queue
.futex
);
1111 /* Normal exit, no error */
1118 ERR("Health error occurred in %s", __func__
);
1120 health_unregister(health_relayd
);
1121 DBG("Dispatch thread dying");
1122 lttng_relay_stop_threads();
1126 static bool session_streams_have_index(const struct relay_session
*session
)
1128 return session
->minor
>= 4 && !session
->snapshot
;
1132 * Handle the RELAYD_CREATE_SESSION command.
1134 * On success, send back the session id or else return a negative value.
1136 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1137 struct relay_connection
*conn
,
1138 const struct lttng_buffer_view
*payload
)
1142 struct relay_session
*session
= NULL
;
1143 struct lttcomm_relayd_create_session_reply_2_11 reply
= {};
1144 char session_name
[LTTNG_NAME_MAX
] = {};
1145 char hostname
[LTTNG_HOST_NAME_MAX
] = {};
1146 uint32_t live_timer
= 0;
1147 bool snapshot
= false;
1148 bool session_name_contains_creation_timestamp
= false;
1149 /* Left nil for peers < 2.11. */
1150 char base_path
[LTTNG_PATH_MAX
] = {};
1151 lttng_uuid sessiond_uuid
= {};
1152 LTTNG_OPTIONAL(uint64_t) id_sessiond
= {};
1153 LTTNG_OPTIONAL(uint64_t) current_chunk_id
= {};
1154 LTTNG_OPTIONAL(time_t) creation_time
= {};
1155 struct lttng_dynamic_buffer reply_payload
;
1157 lttng_dynamic_buffer_init(&reply_payload
);
1159 if (conn
->minor
< 4) {
1160 /* From 2.1 to 2.3 */
1162 } else if (conn
->minor
>= 4 && conn
->minor
< 11) {
1163 /* From 2.4 to 2.10 */
1164 ret
= cmd_create_session_2_4(payload
, session_name
,
1165 hostname
, &live_timer
, &snapshot
);
1167 bool has_current_chunk
;
1168 uint64_t current_chunk_id_value
;
1169 time_t creation_time_value
;
1170 uint64_t id_sessiond_value
;
1172 /* From 2.11 to ... */
1173 ret
= cmd_create_session_2_11(payload
, session_name
, hostname
,
1174 base_path
, &live_timer
, &snapshot
, &id_sessiond_value
,
1175 sessiond_uuid
, &has_current_chunk
,
1176 ¤t_chunk_id_value
, &creation_time_value
,
1177 &session_name_contains_creation_timestamp
);
1178 if (lttng_uuid_is_nil(sessiond_uuid
)) {
1179 /* The nil UUID is reserved for pre-2.11 clients. */
1180 ERR("Illegal nil UUID announced by peer in create session command");
1184 LTTNG_OPTIONAL_SET(&id_sessiond
, id_sessiond_value
);
1185 LTTNG_OPTIONAL_SET(&creation_time
, creation_time_value
);
1186 if (has_current_chunk
) {
1187 LTTNG_OPTIONAL_SET(¤t_chunk_id
,
1188 current_chunk_id_value
);
1196 session
= session_create(session_name
, hostname
, base_path
, live_timer
,
1197 snapshot
, sessiond_uuid
,
1198 id_sessiond
.is_set
? &id_sessiond
.value
: NULL
,
1199 current_chunk_id
.is_set
? ¤t_chunk_id
.value
: NULL
,
1200 creation_time
.is_set
? &creation_time
.value
: NULL
,
1201 conn
->major
, conn
->minor
,
1202 session_name_contains_creation_timestamp
);
1207 assert(!conn
->session
);
1208 conn
->session
= session
;
1209 DBG("Created session %" PRIu64
, session
->id
);
1211 reply
.generic
.session_id
= htobe64(session
->id
);
1215 reply
.generic
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1217 reply
.generic
.ret_code
= htobe32(LTTNG_OK
);
1220 if (conn
->minor
< 11) {
1221 /* From 2.1 to 2.10 */
1222 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1223 &reply
.generic
, sizeof(reply
.generic
));
1225 ERR("Failed to append \"create session\" command reply header to payload buffer");
1230 const uint32_t output_path_length
=
1231 session
? strlen(session
->output_path
) + 1 : 0;
1233 reply
.output_path_length
= htobe32(output_path_length
);
1234 ret
= lttng_dynamic_buffer_append(
1235 &reply_payload
, &reply
, sizeof(reply
));
1237 ERR("Failed to append \"create session\" command reply header to payload buffer");
1241 if (output_path_length
) {
1242 ret
= lttng_dynamic_buffer_append(&reply_payload
,
1243 session
->output_path
,
1244 output_path_length
);
1246 ERR("Failed to append \"create session\" command reply path to payload buffer");
1252 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, reply_payload
.data
,
1253 reply_payload
.size
, 0);
1254 if (send_ret
< (ssize_t
) reply_payload
.size
) {
1255 ERR("Failed to send \"create session\" command reply of %zu bytes (ret = %zd)",
1256 reply_payload
.size
, send_ret
);
1260 if (ret
< 0 && session
) {
1261 session_put(session
);
1263 lttng_dynamic_buffer_reset(&reply_payload
);
1268 * When we have received all the streams and the metadata for a channel,
1269 * we make them visible to the viewer threads.
1271 static void publish_connection_local_streams(struct relay_connection
*conn
)
1273 struct relay_stream
*stream
;
1274 struct relay_session
*session
= conn
->session
;
1277 * We publish all streams belonging to a session atomically wrt
1280 pthread_mutex_lock(&session
->lock
);
1282 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1284 stream_publish(stream
);
1289 * Inform the viewer that there are new streams in the session.
1291 if (session
->viewer_attached
) {
1292 uatomic_set(&session
->new_streams
, 1);
1294 pthread_mutex_unlock(&session
->lock
);
1297 static int conform_channel_path(char *channel_path
)
1301 if (strstr("../", channel_path
)) {
1302 ERR("Refusing channel path as it walks up the path hierarchy: \"%s\"",
1308 if (*channel_path
== '/') {
1309 const size_t len
= strlen(channel_path
);
1312 * Channel paths from peers prior to 2.11 are expressed as an
1313 * absolute path that is, in reality, relative to the relay
1314 * daemon's output directory. Remove the leading slash so it
1315 * is correctly interpreted as a relative path later on.
1317 * len (and not len - 1) is used to copy the trailing NULL.
1319 bcopy(channel_path
+ 1, channel_path
, len
);
1326 * relay_add_stream: allocate a new stream for a session
1328 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1329 struct relay_connection
*conn
,
1330 const struct lttng_buffer_view
*payload
)
1334 struct relay_session
*session
= conn
->session
;
1335 struct relay_stream
*stream
= NULL
;
1336 struct lttcomm_relayd_status_stream reply
;
1337 struct ctf_trace
*trace
= NULL
;
1338 uint64_t stream_handle
= -1ULL;
1339 char *path_name
= NULL
, *channel_name
= NULL
;
1340 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1341 LTTNG_OPTIONAL(uint64_t) stream_chunk_id
= {};
1343 if (!session
|| !conn
->version_check_done
) {
1344 ERR("Trying to add a stream before version check");
1346 goto end_no_session
;
1349 if (session
->minor
== 1) {
1351 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1353 } else if (session
->minor
> 1 && session
->minor
< 11) {
1354 /* From 2.2 to 2.10 */
1355 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1356 &channel_name
, &tracefile_size
, &tracefile_count
);
1358 /* From 2.11 to ... */
1359 ret
= cmd_recv_stream_2_11(payload
, &path_name
,
1360 &channel_name
, &tracefile_size
, &tracefile_count
,
1361 &stream_chunk_id
.value
);
1362 stream_chunk_id
.is_set
= true;
1369 if (conform_channel_path(path_name
)) {
1373 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1377 /* This stream here has one reference on the trace. */
1379 pthread_mutex_lock(&last_relay_stream_id_lock
);
1380 stream_handle
= ++last_relay_stream_id
;
1381 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1383 /* We pass ownership of path_name and channel_name. */
1384 stream
= stream_create(trace
, stream_handle
, path_name
,
1385 channel_name
, tracefile_size
, tracefile_count
);
1387 channel_name
= NULL
;
1390 * Streams are the owners of their trace. Reference to trace is
1391 * kept within stream_create().
1393 ctf_trace_put(trace
);
1396 memset(&reply
, 0, sizeof(reply
));
1397 reply
.handle
= htobe64(stream_handle
);
1399 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1401 reply
.ret_code
= htobe32(LTTNG_OK
);
1404 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1405 sizeof(struct lttcomm_relayd_status_stream
), 0);
1406 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1407 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1419 * relay_close_stream: close a specific stream
1421 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1422 struct relay_connection
*conn
,
1423 const struct lttng_buffer_view
*payload
)
1427 struct relay_session
*session
= conn
->session
;
1428 struct lttcomm_relayd_close_stream stream_info
;
1429 struct lttcomm_relayd_generic_reply reply
;
1430 struct relay_stream
*stream
;
1432 DBG("Close stream received");
1434 if (!session
|| !conn
->version_check_done
) {
1435 ERR("Trying to close a stream before version check");
1437 goto end_no_session
;
1440 if (payload
->size
< sizeof(stream_info
)) {
1441 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1442 sizeof(stream_info
), payload
->size
);
1444 goto end_no_session
;
1446 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1447 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1448 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1450 stream
= stream_get_by_id(stream_info
.stream_id
);
1457 * Set last_net_seq_num before the close flag. Required by data
1460 pthread_mutex_lock(&stream
->lock
);
1461 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1462 pthread_mutex_unlock(&stream
->lock
);
1465 * This is one of the conditions which may trigger a stream close
1466 * with the others being:
1467 * 1) A close command is received for a stream
1468 * 2) The control connection owning the stream is closed
1469 * 3) We have received all of the stream's data _after_ a close
1472 try_stream_close(stream
);
1473 if (stream
->is_metadata
) {
1474 struct relay_viewer_stream
*vstream
;
1476 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1478 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1480 * Since all the metadata has been sent to the
1481 * viewer and that we have a request to close
1482 * its stream, we can safely teardown the
1483 * corresponding metadata viewer stream.
1485 viewer_stream_put(vstream
);
1487 /* Put local reference. */
1488 viewer_stream_put(vstream
);
1495 memset(&reply
, 0, sizeof(reply
));
1497 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1499 reply
.ret_code
= htobe32(LTTNG_OK
);
1501 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1502 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1503 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1504 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1514 * relay_reset_metadata: reset a metadata stream
1517 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1518 struct relay_connection
*conn
,
1519 const struct lttng_buffer_view
*payload
)
1523 struct relay_session
*session
= conn
->session
;
1524 struct lttcomm_relayd_reset_metadata stream_info
;
1525 struct lttcomm_relayd_generic_reply reply
;
1526 struct relay_stream
*stream
;
1528 DBG("Reset metadata received");
1530 if (!session
|| !conn
->version_check_done
) {
1531 ERR("Trying to reset a metadata stream before version check");
1533 goto end_no_session
;
1536 if (payload
->size
< sizeof(stream_info
)) {
1537 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1538 sizeof(stream_info
), payload
->size
);
1540 goto end_no_session
;
1542 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1543 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1544 stream_info
.version
= be64toh(stream_info
.version
);
1546 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1548 /* Unsupported for live sessions for now. */
1549 if (session
->live_timer
!= 0) {
1554 stream
= stream_get_by_id(stream_info
.stream_id
);
1559 pthread_mutex_lock(&stream
->lock
);
1560 if (!stream
->is_metadata
) {
1565 ret
= stream_reset_file(stream
);
1567 ERR("Failed to reset metadata stream %" PRIu64
1568 ": stream_path = %s, channel = %s",
1569 stream
->stream_handle
, stream
->path_name
,
1570 stream
->channel_name
);
1574 pthread_mutex_unlock(&stream
->lock
);
1578 memset(&reply
, 0, sizeof(reply
));
1580 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1582 reply
.ret_code
= htobe32(LTTNG_OK
);
1584 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1585 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1586 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1587 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1597 * relay_unknown_command: send -1 if received unknown command
1599 static void relay_unknown_command(struct relay_connection
*conn
)
1601 struct lttcomm_relayd_generic_reply reply
;
1604 memset(&reply
, 0, sizeof(reply
));
1605 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1606 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1607 if (send_ret
< sizeof(reply
)) {
1608 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1613 * relay_start: send an acknowledgment to the client to tell if we are
1614 * ready to receive data. We are ready if a session is established.
1616 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1617 struct relay_connection
*conn
,
1618 const struct lttng_buffer_view
*payload
)
1622 struct lttcomm_relayd_generic_reply reply
;
1623 struct relay_session
*session
= conn
->session
;
1626 DBG("Trying to start the streaming without a session established");
1627 ret
= htobe32(LTTNG_ERR_UNK
);
1630 memset(&reply
, 0, sizeof(reply
));
1631 reply
.ret_code
= htobe32(LTTNG_OK
);
1632 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1634 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1635 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1644 * relay_recv_metadata: receive the metadata for the session.
1646 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1647 struct relay_connection
*conn
,
1648 const struct lttng_buffer_view
*payload
)
1651 struct relay_session
*session
= conn
->session
;
1652 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1653 struct relay_stream
*metadata_stream
;
1654 uint64_t metadata_payload_size
;
1655 struct lttng_buffer_view packet_view
;
1658 ERR("Metadata sent before version check");
1663 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1664 ERR("Incorrect data size");
1668 metadata_payload_size
= recv_hdr
->data_size
-
1669 sizeof(struct lttcomm_relayd_metadata_payload
);
1671 memcpy(&metadata_payload_header
, payload
->data
,
1672 sizeof(metadata_payload_header
));
1673 metadata_payload_header
.stream_id
= be64toh(
1674 metadata_payload_header
.stream_id
);
1675 metadata_payload_header
.padding_size
= be32toh(
1676 metadata_payload_header
.padding_size
);
1678 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1679 if (!metadata_stream
) {
1684 packet_view
= lttng_buffer_view_from_view(payload
,
1685 sizeof(metadata_payload_header
), metadata_payload_size
);
1686 if (!packet_view
.data
) {
1687 ERR("Invalid metadata packet length announced by header");
1692 pthread_mutex_lock(&metadata_stream
->lock
);
1693 ret
= stream_write(metadata_stream
, &packet_view
,
1694 metadata_payload_header
.padding_size
);
1695 pthread_mutex_unlock(&metadata_stream
->lock
);
1701 stream_put(metadata_stream
);
1707 * relay_send_version: send relayd version number
1709 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1710 struct relay_connection
*conn
,
1711 const struct lttng_buffer_view
*payload
)
1715 struct lttcomm_relayd_version reply
, msg
;
1716 bool compatible
= true;
1718 conn
->version_check_done
= true;
1720 /* Get version from the other side. */
1721 if (payload
->size
< sizeof(msg
)) {
1722 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1723 sizeof(msg
), payload
->size
);
1728 memcpy(&msg
, payload
->data
, sizeof(msg
));
1729 msg
.major
= be32toh(msg
.major
);
1730 msg
.minor
= be32toh(msg
.minor
);
1732 memset(&reply
, 0, sizeof(reply
));
1733 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1734 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1736 /* Major versions must be the same */
1737 if (reply
.major
!= msg
.major
) {
1738 DBG("Incompatible major versions (%u vs %u), deleting session",
1739 reply
.major
, msg
.major
);
1743 conn
->major
= reply
.major
;
1744 /* We adapt to the lowest compatible version */
1745 if (reply
.minor
<= msg
.minor
) {
1746 conn
->minor
= reply
.minor
;
1748 conn
->minor
= msg
.minor
;
1751 reply
.major
= htobe32(reply
.major
);
1752 reply
.minor
= htobe32(reply
.minor
);
1753 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1755 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1756 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1769 DBG("Version check done using protocol %u.%u", conn
->major
,
1777 * Check for data pending for a given stream id from the session daemon.
1779 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1780 struct relay_connection
*conn
,
1781 const struct lttng_buffer_view
*payload
)
1783 struct relay_session
*session
= conn
->session
;
1784 struct lttcomm_relayd_data_pending msg
;
1785 struct lttcomm_relayd_generic_reply reply
;
1786 struct relay_stream
*stream
;
1789 uint64_t stream_seq
;
1791 DBG("Data pending command received");
1793 if (!session
|| !conn
->version_check_done
) {
1794 ERR("Trying to check for data before version check");
1796 goto end_no_session
;
1799 if (payload
->size
< sizeof(msg
)) {
1800 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1801 sizeof(msg
), payload
->size
);
1803 goto end_no_session
;
1805 memcpy(&msg
, payload
->data
, sizeof(msg
));
1806 msg
.stream_id
= be64toh(msg
.stream_id
);
1807 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1809 stream
= stream_get_by_id(msg
.stream_id
);
1810 if (stream
== NULL
) {
1815 pthread_mutex_lock(&stream
->lock
);
1817 if (session_streams_have_index(session
)) {
1819 * Ensure that both the index and stream data have been
1820 * flushed up to the requested point.
1822 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
1824 stream_seq
= stream
->prev_data_seq
;
1826 DBG("Data pending for stream id %" PRIu64
": prev_data_seq %" PRIu64
1827 ", prev_index_seq %" PRIu64
1828 ", and last_seq %" PRIu64
, msg
.stream_id
,
1829 stream
->prev_data_seq
, stream
->prev_index_seq
,
1830 msg
.last_net_seq_num
);
1832 /* Avoid wrapping issue */
1833 if (((int64_t) (stream_seq
- msg
.last_net_seq_num
)) >= 0) {
1834 /* Data has in fact been written and is NOT pending */
1837 /* Data still being streamed thus pending */
1841 stream
->data_pending_check_done
= true;
1842 pthread_mutex_unlock(&stream
->lock
);
1847 memset(&reply
, 0, sizeof(reply
));
1848 reply
.ret_code
= htobe32(ret
);
1849 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1850 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1851 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1861 * Wait for the control socket to reach a quiescent state.
1863 * Note that for now, when receiving this command from the session
1864 * daemon, this means that every subsequent commands or data received on
1865 * the control socket has been handled. So, this is why we simply return
1868 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1869 struct relay_connection
*conn
,
1870 const struct lttng_buffer_view
*payload
)
1874 struct relay_stream
*stream
;
1875 struct lttcomm_relayd_quiescent_control msg
;
1876 struct lttcomm_relayd_generic_reply reply
;
1878 DBG("Checking quiescent state on control socket");
1880 if (!conn
->session
|| !conn
->version_check_done
) {
1881 ERR("Trying to check for data before version check");
1883 goto end_no_session
;
1886 if (payload
->size
< sizeof(msg
)) {
1887 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1888 sizeof(msg
), payload
->size
);
1890 goto end_no_session
;
1892 memcpy(&msg
, payload
->data
, sizeof(msg
));
1893 msg
.stream_id
= be64toh(msg
.stream_id
);
1895 stream
= stream_get_by_id(msg
.stream_id
);
1899 pthread_mutex_lock(&stream
->lock
);
1900 stream
->data_pending_check_done
= true;
1901 pthread_mutex_unlock(&stream
->lock
);
1903 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1906 memset(&reply
, 0, sizeof(reply
));
1907 reply
.ret_code
= htobe32(LTTNG_OK
);
1908 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1909 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1910 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1922 * Initialize a data pending command. This means that a consumer is about
1923 * to ask for data pending for each stream it holds. Simply iterate over
1924 * all streams of a session and set the data_pending_check_done flag.
1926 * This command returns to the client a LTTNG_OK code.
1928 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1929 struct relay_connection
*conn
,
1930 const struct lttng_buffer_view
*payload
)
1934 struct lttng_ht_iter iter
;
1935 struct lttcomm_relayd_begin_data_pending msg
;
1936 struct lttcomm_relayd_generic_reply reply
;
1937 struct relay_stream
*stream
;
1942 DBG("Init streams for data pending");
1944 if (!conn
->session
|| !conn
->version_check_done
) {
1945 ERR("Trying to check for data before version check");
1947 goto end_no_session
;
1950 if (payload
->size
< sizeof(msg
)) {
1951 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1952 sizeof(msg
), payload
->size
);
1954 goto end_no_session
;
1956 memcpy(&msg
, payload
->data
, sizeof(msg
));
1957 msg
.session_id
= be64toh(msg
.session_id
);
1960 * Iterate over all streams to set the begin data pending flag.
1961 * For now, the streams are indexed by stream handle so we have
1962 * to iterate over all streams to find the one associated with
1963 * the right session_id.
1966 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1968 if (!stream_get(stream
)) {
1971 if (stream
->trace
->session
->id
== msg
.session_id
) {
1972 pthread_mutex_lock(&stream
->lock
);
1973 stream
->data_pending_check_done
= false;
1974 pthread_mutex_unlock(&stream
->lock
);
1975 DBG("Set begin data pending flag to stream %" PRIu64
,
1976 stream
->stream_handle
);
1982 memset(&reply
, 0, sizeof(reply
));
1983 /* All good, send back reply. */
1984 reply
.ret_code
= htobe32(LTTNG_OK
);
1986 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1987 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1988 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
2000 * End data pending command. This will check, for a given session id, if
2001 * each stream associated with it has its data_pending_check_done flag
2002 * set. If not, this means that the client lost track of the stream but
2003 * the data is still being streamed on our side. In this case, we inform
2004 * the client that data is in flight.
2006 * Return to the client if there is data in flight or not with a ret_code.
2008 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
2009 struct relay_connection
*conn
,
2010 const struct lttng_buffer_view
*payload
)
2014 struct lttng_ht_iter iter
;
2015 struct lttcomm_relayd_end_data_pending msg
;
2016 struct lttcomm_relayd_generic_reply reply
;
2017 struct relay_stream
*stream
;
2018 uint32_t is_data_inflight
= 0;
2020 DBG("End data pending command");
2022 if (!conn
->session
|| !conn
->version_check_done
) {
2023 ERR("Trying to check for data before version check");
2025 goto end_no_session
;
2028 if (payload
->size
< sizeof(msg
)) {
2029 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
2030 sizeof(msg
), payload
->size
);
2032 goto end_no_session
;
2034 memcpy(&msg
, payload
->data
, sizeof(msg
));
2035 msg
.session_id
= be64toh(msg
.session_id
);
2038 * Iterate over all streams to see if the begin data pending
2042 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
2044 if (!stream_get(stream
)) {
2047 if (stream
->trace
->session
->id
!= msg
.session_id
) {
2051 pthread_mutex_lock(&stream
->lock
);
2052 if (!stream
->data_pending_check_done
) {
2053 uint64_t stream_seq
;
2055 if (session_streams_have_index(conn
->session
)) {
2057 * Ensure that both the index and stream data have been
2058 * flushed up to the requested point.
2060 stream_seq
= min(stream
->prev_data_seq
, stream
->prev_index_seq
);
2062 stream_seq
= stream
->prev_data_seq
;
2064 if (!stream
->closed
|| !(((int64_t) (stream_seq
- stream
->last_net_seq_num
)) >= 0)) {
2065 is_data_inflight
= 1;
2066 DBG("Data is still in flight for stream %" PRIu64
,
2067 stream
->stream_handle
);
2068 pthread_mutex_unlock(&stream
->lock
);
2073 pthread_mutex_unlock(&stream
->lock
);
2078 memset(&reply
, 0, sizeof(reply
));
2079 /* All good, send back reply. */
2080 reply
.ret_code
= htobe32(is_data_inflight
);
2082 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2083 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2084 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
2096 * Receive an index for a specific stream.
2098 * Return 0 on success else a negative value.
2100 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2101 struct relay_connection
*conn
,
2102 const struct lttng_buffer_view
*payload
)
2106 struct relay_session
*session
= conn
->session
;
2107 struct lttcomm_relayd_index index_info
;
2108 struct lttcomm_relayd_generic_reply reply
;
2109 struct relay_stream
*stream
;
2114 DBG("Relay receiving index");
2116 if (!session
|| !conn
->version_check_done
) {
2117 ERR("Trying to close a stream before version check");
2119 goto end_no_session
;
2122 msg_len
= lttcomm_relayd_index_len(
2123 lttng_to_index_major(conn
->major
, conn
->minor
),
2124 lttng_to_index_minor(conn
->major
, conn
->minor
));
2125 if (payload
->size
< msg_len
) {
2126 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2127 msg_len
, payload
->size
);
2129 goto end_no_session
;
2131 memcpy(&index_info
, payload
->data
, msg_len
);
2132 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2133 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2134 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2135 index_info
.content_size
= be64toh(index_info
.content_size
);
2136 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2137 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2138 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2139 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2141 if (conn
->minor
>= 8) {
2142 index_info
.stream_instance_id
=
2143 be64toh(index_info
.stream_instance_id
);
2144 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2147 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2149 ERR("stream_get_by_id not found");
2154 pthread_mutex_lock(&stream
->lock
);
2155 ret
= stream_add_index(stream
, &index_info
);
2156 pthread_mutex_unlock(&stream
->lock
);
2158 goto end_stream_put
;
2164 memset(&reply
, 0, sizeof(reply
));
2166 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2168 reply
.ret_code
= htobe32(LTTNG_OK
);
2170 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2171 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2172 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2181 * Receive the streams_sent message.
2183 * Return 0 on success else a negative value.
2185 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2186 struct relay_connection
*conn
,
2187 const struct lttng_buffer_view
*payload
)
2191 struct lttcomm_relayd_generic_reply reply
;
2195 DBG("Relay receiving streams_sent");
2197 if (!conn
->session
|| !conn
->version_check_done
) {
2198 ERR("Trying to close a stream before version check");
2200 goto end_no_session
;
2204 * Publish every pending stream in the connection recv list which are
2205 * now ready to be used by the viewer.
2207 publish_connection_local_streams(conn
);
2209 memset(&reply
, 0, sizeof(reply
));
2210 reply
.ret_code
= htobe32(LTTNG_OK
);
2211 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2212 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2213 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2226 * relay_rotate_session_stream: rotate a stream to a new tracefile for the
2227 * session rotation feature (not the tracefile rotation feature).
2229 static int relay_rotate_session_streams(
2230 const struct lttcomm_relayd_hdr
*recv_hdr
,
2231 struct relay_connection
*conn
,
2232 const struct lttng_buffer_view
*payload
)
2237 enum lttng_error_code reply_code
= LTTNG_ERR_UNK
;
2238 struct relay_session
*session
= conn
->session
;
2239 struct lttcomm_relayd_rotate_streams rotate_streams
;
2240 struct lttcomm_relayd_generic_reply reply
= {};
2241 struct relay_stream
*stream
= NULL
;
2242 const size_t header_len
= sizeof(struct lttcomm_relayd_rotate_streams
);
2243 struct lttng_trace_chunk
*next_trace_chunk
= NULL
;
2244 struct lttng_buffer_view stream_positions
;
2245 char chunk_id_buf
[MAX_INT_DEC_LEN(uint64_t)];
2246 const char *chunk_id_str
= "none";
2248 if (!session
|| !conn
->version_check_done
) {
2249 ERR("Trying to rotate a stream before version check");
2254 if (session
->major
== 2 && session
->minor
< 11) {
2255 ERR("Unsupported feature before 2.11");
2260 if (payload
->size
< header_len
) {
2261 ERR("Unexpected payload size in \"relay_rotate_session_stream\": expected >= %zu bytes, got %zu bytes",
2262 header_len
, payload
->size
);
2267 memcpy(&rotate_streams
, payload
->data
, header_len
);
2269 /* Convert header to host endianness. */
2270 rotate_streams
= (typeof(rotate_streams
)) {
2271 .stream_count
= be32toh(rotate_streams
.stream_count
),
2272 .new_chunk_id
= (typeof(rotate_streams
.new_chunk_id
)) {
2273 .is_set
= !!rotate_streams
.new_chunk_id
.is_set
,
2274 .value
= be64toh(rotate_streams
.new_chunk_id
.value
),
2278 if (rotate_streams
.new_chunk_id
.is_set
) {
2280 * Retrieve the trace chunk the stream must transition to. As
2281 * per the protocol, this chunk should have been created
2282 * before this command is received.
2284 next_trace_chunk
= sessiond_trace_chunk_registry_get_chunk(
2285 sessiond_trace_chunk_registry
,
2286 session
->sessiond_uuid
, session
->id
,
2287 rotate_streams
.new_chunk_id
.value
);
2288 if (!next_trace_chunk
) {
2289 char uuid_str
[UUID_STR_LEN
];
2291 lttng_uuid_to_str(session
->sessiond_uuid
, uuid_str
);
2292 ERR("Unknown next trace chunk in ROTATE_STREAMS command: sessiond_uuid = {%s}, session_id = %" PRIu64
2293 ", trace_chunk_id = %" PRIu64
,
2294 uuid_str
, session
->id
,
2295 rotate_streams
.new_chunk_id
.value
);
2296 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2301 ret
= snprintf(chunk_id_buf
, sizeof(chunk_id_buf
), "%" PRIu64
,
2302 rotate_streams
.new_chunk_id
.value
);
2303 if (ret
< 0 || ret
>= sizeof(chunk_id_buf
)) {
2304 chunk_id_str
= "formatting error";
2306 chunk_id_str
= chunk_id_buf
;
2308 session
->has_rotated
= true;
2311 DBG("Rotate %" PRIu32
" streams of session \"%s\" to chunk \"%s\"",
2312 rotate_streams
.stream_count
, session
->session_name
,
2315 stream_positions
= lttng_buffer_view_from_view(payload
,
2316 sizeof(rotate_streams
), -1);
2317 if (!stream_positions
.data
||
2318 stream_positions
.size
<
2319 (rotate_streams
.stream_count
*
2320 sizeof(struct lttcomm_relayd_stream_rotation_position
))) {
2321 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2326 for (i
= 0; i
< rotate_streams
.stream_count
; i
++) {
2327 struct lttcomm_relayd_stream_rotation_position
*position_comm
=
2328 &((typeof(position_comm
)) stream_positions
.data
)[i
];
2329 const struct lttcomm_relayd_stream_rotation_position pos
= {
2330 .stream_id
= be64toh(position_comm
->stream_id
),
2331 .rotate_at_seq_num
= be64toh(
2332 position_comm
->rotate_at_seq_num
),
2335 stream
= stream_get_by_id(pos
.stream_id
);
2337 reply_code
= LTTNG_ERR_INVALID
;
2342 pthread_mutex_lock(&stream
->lock
);
2343 ret
= stream_set_pending_rotation(stream
, next_trace_chunk
,
2344 pos
.rotate_at_seq_num
);
2345 pthread_mutex_unlock(&stream
->lock
);
2347 reply_code
= LTTNG_ERR_FILE_CREATION_ERROR
;
2355 reply_code
= LTTNG_OK
;
2362 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2363 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
2364 sizeof(struct lttcomm_relayd_generic_reply
), 0);
2365 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2366 ERR("Failed to send \"rotate session stream\" command reply (ret = %zd)",
2371 lttng_trace_chunk_put(next_trace_chunk
);
2378 * relay_create_trace_chunk: create a new trace chunk
2380 static int relay_create_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2381 struct relay_connection
*conn
,
2382 const struct lttng_buffer_view
*payload
)
2386 struct relay_session
*session
= conn
->session
;
2387 struct lttcomm_relayd_create_trace_chunk
*msg
;
2388 struct lttcomm_relayd_generic_reply reply
= {};
2389 struct lttng_buffer_view header_view
;
2390 struct lttng_buffer_view chunk_name_view
;
2391 struct lttng_trace_chunk
*chunk
= NULL
, *published_chunk
= NULL
;
2392 enum lttng_error_code reply_code
= LTTNG_OK
;
2393 enum lttng_trace_chunk_status chunk_status
;
2394 struct lttng_directory_handle session_output
;
2396 if (!session
|| !conn
->version_check_done
) {
2397 ERR("Trying to create a trace chunk before version check");
2402 if (session
->major
== 2 && session
->minor
< 11) {
2403 ERR("Chunk creation command is unsupported before 2.11");
2408 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2409 if (!header_view
.data
) {
2410 ERR("Failed to receive payload of chunk creation command");
2415 /* Convert to host endianness. */
2416 msg
= (typeof(msg
)) header_view
.data
;
2417 msg
->chunk_id
= be64toh(msg
->chunk_id
);
2418 msg
->creation_timestamp
= be64toh(msg
->creation_timestamp
);
2419 msg
->override_name_length
= be32toh(msg
->override_name_length
);
2421 chunk
= lttng_trace_chunk_create(
2422 msg
->chunk_id
, msg
->creation_timestamp
);
2424 ERR("Failed to create trace chunk in trace chunk creation command");
2426 reply_code
= LTTNG_ERR_NOMEM
;
2430 if (msg
->override_name_length
) {
2433 chunk_name_view
= lttng_buffer_view_from_view(payload
,
2435 msg
->override_name_length
);
2436 name
= chunk_name_view
.data
;
2437 if (!name
|| name
[msg
->override_name_length
- 1]) {
2438 ERR("Failed to receive payload of chunk creation command");
2440 reply_code
= LTTNG_ERR_INVALID
;
2444 chunk_status
= lttng_trace_chunk_override_name(
2445 chunk
, chunk_name_view
.data
);
2446 switch (chunk_status
) {
2447 case LTTNG_TRACE_CHUNK_STATUS_OK
:
2449 case LTTNG_TRACE_CHUNK_STATUS_INVALID_ARGUMENT
:
2450 ERR("Failed to set the name of new trace chunk in trace chunk creation command (invalid name)");
2451 reply_code
= LTTNG_ERR_INVALID
;
2455 ERR("Failed to set the name of new trace chunk in trace chunk creation command (unknown error)");
2456 reply_code
= LTTNG_ERR_UNK
;
2462 chunk_status
= lttng_trace_chunk_set_credentials_current_user(chunk
);
2463 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2464 reply_code
= LTTNG_ERR_UNK
;
2469 ret
= session_init_output_directory_handle(
2470 conn
->session
, &session_output
);
2472 reply_code
= LTTNG_ERR_CREATE_DIR_FAIL
;
2475 chunk_status
= lttng_trace_chunk_set_as_owner(chunk
, &session_output
);
2476 lttng_directory_handle_fini(&session_output
);
2477 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2478 reply_code
= LTTNG_ERR_UNK
;
2483 published_chunk
= sessiond_trace_chunk_registry_publish_chunk(
2484 sessiond_trace_chunk_registry
,
2485 conn
->session
->sessiond_uuid
,
2488 if (!published_chunk
) {
2489 char uuid_str
[UUID_STR_LEN
];
2491 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2492 ERR("Failed to publish chunk: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2497 reply_code
= LTTNG_ERR_NOMEM
;
2501 pthread_mutex_lock(&conn
->session
->lock
);
2502 if (conn
->session
->pending_closure_trace_chunk
) {
2504 * Invalid; this means a second create_trace_chunk command was
2505 * received before a close_trace_chunk.
2507 ERR("Invalid trace chunk close command received; a trace chunk is already waiting for a trace chunk close command");
2508 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2510 goto end_unlock_session
;
2512 conn
->session
->pending_closure_trace_chunk
=
2513 conn
->session
->current_trace_chunk
;
2514 conn
->session
->current_trace_chunk
= published_chunk
;
2515 published_chunk
= NULL
;
2517 pthread_mutex_unlock(&conn
->session
->lock
);
2519 reply
.ret_code
= htobe32((uint32_t) reply_code
);
2520 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2522 sizeof(struct lttcomm_relayd_generic_reply
),
2524 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2525 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2530 lttng_trace_chunk_put(chunk
);
2531 lttng_trace_chunk_put(published_chunk
);
2536 * relay_close_trace_chunk: close a trace chunk
2538 static int relay_close_trace_chunk(const struct lttcomm_relayd_hdr
*recv_hdr
,
2539 struct relay_connection
*conn
,
2540 const struct lttng_buffer_view
*payload
)
2542 int ret
= 0, buf_ret
;
2544 struct relay_session
*session
= conn
->session
;
2545 struct lttcomm_relayd_close_trace_chunk
*msg
;
2546 struct lttcomm_relayd_close_trace_chunk_reply reply
= {};
2547 struct lttng_buffer_view header_view
;
2548 struct lttng_trace_chunk
*chunk
= NULL
;
2549 enum lttng_error_code reply_code
= LTTNG_OK
;
2550 enum lttng_trace_chunk_status chunk_status
;
2552 LTTNG_OPTIONAL(enum lttng_trace_chunk_command_type
) close_command
= {};
2553 time_t close_timestamp
;
2554 char closed_trace_chunk_path
[LTTNG_PATH_MAX
];
2555 size_t path_length
= 0;
2556 const char *chunk_name
= NULL
;
2557 struct lttng_dynamic_buffer reply_payload
;
2559 lttng_dynamic_buffer_init(&reply_payload
);
2561 if (!session
|| !conn
->version_check_done
) {
2562 ERR("Trying to close a trace chunk before version check");
2567 if (session
->major
== 2 && session
->minor
< 11) {
2568 ERR("Chunk close command is unsupported before 2.11");
2573 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2574 if (!header_view
.data
) {
2575 ERR("Failed to receive payload of chunk close command");
2580 /* Convert to host endianness. */
2581 msg
= (typeof(msg
)) header_view
.data
;
2582 chunk_id
= be64toh(msg
->chunk_id
);
2583 close_timestamp
= (time_t) be64toh(msg
->close_timestamp
);
2584 close_command
= (typeof(close_command
)){
2585 .value
= be32toh(msg
->close_command
.value
),
2586 .is_set
= msg
->close_command
.is_set
,
2589 chunk
= sessiond_trace_chunk_registry_get_chunk(
2590 sessiond_trace_chunk_registry
,
2591 conn
->session
->sessiond_uuid
,
2595 char uuid_str
[UUID_STR_LEN
];
2597 lttng_uuid_to_str(conn
->session
->sessiond_uuid
, uuid_str
);
2598 ERR("Failed to find chunk to close: sessiond_uuid = %s, session_id = %" PRIu64
", chunk_id = %" PRIu64
,
2603 reply_code
= LTTNG_ERR_NOMEM
;
2607 pthread_mutex_lock(&session
->lock
);
2608 if (session
->pending_closure_trace_chunk
&&
2609 session
->pending_closure_trace_chunk
!= chunk
) {
2610 ERR("Trace chunk close command for session \"%s\" does not target the trace chunk pending closure",
2611 session
->session_name
);
2612 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2614 goto end_unlock_session
;
2617 chunk_status
= lttng_trace_chunk_set_close_timestamp(
2618 chunk
, close_timestamp
);
2619 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2620 ERR("Failed to set trace chunk close timestamp");
2622 reply_code
= LTTNG_ERR_UNK
;
2623 goto end_unlock_session
;
2626 if (close_command
.is_set
) {
2627 chunk_status
= lttng_trace_chunk_set_close_command(
2628 chunk
, close_command
.value
);
2629 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2631 reply_code
= LTTNG_ERR_INVALID
;
2632 goto end_unlock_session
;
2635 chunk_status
= lttng_trace_chunk_get_name(chunk
, &chunk_name
, NULL
);
2636 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2637 ERR("Failed to get chunk name");
2639 reply_code
= LTTNG_ERR_UNK
;
2640 goto end_unlock_session
;
2642 if (!session
->has_rotated
&& !session
->snapshot
) {
2643 ret
= lttng_strncpy(closed_trace_chunk_path
,
2644 session
->output_path
,
2645 sizeof(closed_trace_chunk_path
));
2647 ERR("Failed to send trace chunk path: path length of %zu bytes exceeds the maximal allowed length of %zu bytes",
2648 strlen(session
->output_path
),
2649 sizeof(closed_trace_chunk_path
));
2650 reply_code
= LTTNG_ERR_NOMEM
;
2652 goto end_unlock_session
;
2655 if (session
->snapshot
) {
2656 ret
= snprintf(closed_trace_chunk_path
,
2657 sizeof(closed_trace_chunk_path
),
2658 "%s/%s", session
->output_path
,
2661 ret
= snprintf(closed_trace_chunk_path
,
2662 sizeof(closed_trace_chunk_path
),
2663 "%s/" DEFAULT_ARCHIVED_TRACE_CHUNKS_DIRECTORY
2665 session
->output_path
, chunk_name
);
2667 if (ret
< 0 || ret
== sizeof(closed_trace_chunk_path
)) {
2668 ERR("Failed to format closed trace chunk resulting path");
2669 reply_code
= ret
< 0 ? LTTNG_ERR_UNK
: LTTNG_ERR_NOMEM
;
2671 goto end_unlock_session
;
2674 DBG("Reply chunk path on close: %s", closed_trace_chunk_path
);
2675 path_length
= strlen(closed_trace_chunk_path
) + 1;
2676 if (path_length
> UINT32_MAX
) {
2677 ERR("Closed trace chunk path exceeds the maximal length allowed by the protocol");
2679 reply_code
= LTTNG_ERR_INVALID_PROTOCOL
;
2680 goto end_unlock_session
;
2683 if (session
->current_trace_chunk
== chunk
) {
2685 * After a trace chunk close command, no new streams
2686 * referencing the chunk may be created. Hence, on the
2687 * event that no new trace chunk have been created for
2688 * the session, the reference to the current trace chunk
2689 * is released in order to allow it to be reclaimed when
2690 * the last stream releases its reference to it.
2692 lttng_trace_chunk_put(session
->current_trace_chunk
);
2693 session
->current_trace_chunk
= NULL
;
2695 lttng_trace_chunk_put(session
->pending_closure_trace_chunk
);
2696 session
->pending_closure_trace_chunk
= NULL
;
2698 pthread_mutex_unlock(&session
->lock
);
2701 reply
.generic
.ret_code
= htobe32((uint32_t) reply_code
);
2702 reply
.path_length
= htobe32((uint32_t) path_length
);
2703 buf_ret
= lttng_dynamic_buffer_append(
2704 &reply_payload
, &reply
, sizeof(reply
));
2706 ERR("Failed to append \"close trace chunk\" command reply header to payload buffer");
2710 if (reply_code
== LTTNG_OK
) {
2711 buf_ret
= lttng_dynamic_buffer_append(&reply_payload
,
2712 closed_trace_chunk_path
, path_length
);
2714 ERR("Failed to append \"close trace chunk\" command reply path to payload buffer");
2719 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
,
2723 if (send_ret
< reply_payload
.size
) {
2724 ERR("Failed to send \"close trace chunk\" command reply of %zu bytes (ret = %zd)",
2725 reply_payload
.size
, send_ret
);
2730 lttng_trace_chunk_put(chunk
);
2731 lttng_dynamic_buffer_reset(&reply_payload
);
2736 * relay_trace_chunk_exists: check if a trace chunk exists
2738 static int relay_trace_chunk_exists(const struct lttcomm_relayd_hdr
*recv_hdr
,
2739 struct relay_connection
*conn
,
2740 const struct lttng_buffer_view
*payload
)
2744 struct relay_session
*session
= conn
->session
;
2745 struct lttcomm_relayd_trace_chunk_exists
*msg
;
2746 struct lttcomm_relayd_trace_chunk_exists_reply reply
= {};
2747 struct lttng_buffer_view header_view
;
2751 if (!session
|| !conn
->version_check_done
) {
2752 ERR("Trying to close a trace chunk before version check");
2757 if (session
->major
== 2 && session
->minor
< 11) {
2758 ERR("Chunk close command is unsupported before 2.11");
2763 header_view
= lttng_buffer_view_from_view(payload
, 0, sizeof(*msg
));
2764 if (!header_view
.data
) {
2765 ERR("Failed to receive payload of chunk close command");
2770 /* Convert to host endianness. */
2771 msg
= (typeof(msg
)) header_view
.data
;
2772 chunk_id
= be64toh(msg
->chunk_id
);
2774 ret
= sessiond_trace_chunk_registry_chunk_exists(
2775 sessiond_trace_chunk_registry
,
2776 conn
->session
->sessiond_uuid
,
2778 chunk_id
, &chunk_exists
);
2780 * If ret is not 0, send the reply and report the error to the caller.
2781 * It is a protocol (or internal) error and the session/connection
2782 * should be torn down.
2784 reply
= (typeof(reply
)){
2785 .generic
.ret_code
= htobe32((uint32_t)
2786 (ret
== 0 ? LTTNG_OK
: LTTNG_ERR_INVALID_PROTOCOL
)),
2787 .trace_chunk_exists
= ret
== 0 ? chunk_exists
: 0,
2789 send_ret
= conn
->sock
->ops
->sendmsg(
2790 conn
->sock
, &reply
, sizeof(reply
), 0);
2791 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2792 ERR("Failed to send \"create trace chunk\" command reply (ret = %zd)",
2800 #define DBG_CMD(cmd_name, conn) \
2801 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2803 static int relay_process_control_command(struct relay_connection
*conn
,
2804 const struct lttcomm_relayd_hdr
*header
,
2805 const struct lttng_buffer_view
*payload
)
2809 switch (header
->cmd
) {
2810 case RELAYD_CREATE_SESSION
:
2811 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2812 ret
= relay_create_session(header
, conn
, payload
);
2814 case RELAYD_ADD_STREAM
:
2815 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2816 ret
= relay_add_stream(header
, conn
, payload
);
2818 case RELAYD_START_DATA
:
2819 DBG_CMD("RELAYD_START_DATA", conn
);
2820 ret
= relay_start(header
, conn
, payload
);
2822 case RELAYD_SEND_METADATA
:
2823 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2824 ret
= relay_recv_metadata(header
, conn
, payload
);
2826 case RELAYD_VERSION
:
2827 DBG_CMD("RELAYD_VERSION", conn
);
2828 ret
= relay_send_version(header
, conn
, payload
);
2830 case RELAYD_CLOSE_STREAM
:
2831 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2832 ret
= relay_close_stream(header
, conn
, payload
);
2834 case RELAYD_DATA_PENDING
:
2835 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2836 ret
= relay_data_pending(header
, conn
, payload
);
2838 case RELAYD_QUIESCENT_CONTROL
:
2839 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2840 ret
= relay_quiescent_control(header
, conn
, payload
);
2842 case RELAYD_BEGIN_DATA_PENDING
:
2843 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2844 ret
= relay_begin_data_pending(header
, conn
, payload
);
2846 case RELAYD_END_DATA_PENDING
:
2847 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2848 ret
= relay_end_data_pending(header
, conn
, payload
);
2850 case RELAYD_SEND_INDEX
:
2851 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2852 ret
= relay_recv_index(header
, conn
, payload
);
2854 case RELAYD_STREAMS_SENT
:
2855 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2856 ret
= relay_streams_sent(header
, conn
, payload
);
2858 case RELAYD_RESET_METADATA
:
2859 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2860 ret
= relay_reset_metadata(header
, conn
, payload
);
2862 case RELAYD_ROTATE_STREAMS
:
2863 DBG_CMD("RELAYD_ROTATE_STREAMS", conn
);
2864 ret
= relay_rotate_session_streams(header
, conn
, payload
);
2866 case RELAYD_CREATE_TRACE_CHUNK
:
2867 DBG_CMD("RELAYD_CREATE_TRACE_CHUNK", conn
);
2868 ret
= relay_create_trace_chunk(header
, conn
, payload
);
2870 case RELAYD_CLOSE_TRACE_CHUNK
:
2871 DBG_CMD("RELAYD_CLOSE_TRACE_CHUNK", conn
);
2872 ret
= relay_close_trace_chunk(header
, conn
, payload
);
2874 case RELAYD_TRACE_CHUNK_EXISTS
:
2875 DBG_CMD("RELAYD_TRACE_CHUNK_EXISTS", conn
);
2876 ret
= relay_trace_chunk_exists(header
, conn
, payload
);
2878 case RELAYD_UPDATE_SYNC_INFO
:
2880 ERR("Received unknown command (%u)", header
->cmd
);
2881 relay_unknown_command(conn
);
2890 static enum relay_connection_status
relay_process_control_receive_payload(
2891 struct relay_connection
*conn
)
2894 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2895 struct lttng_dynamic_buffer
*reception_buffer
=
2896 &conn
->protocol
.ctrl
.reception_buffer
;
2897 struct ctrl_connection_state_receive_payload
*state
=
2898 &conn
->protocol
.ctrl
.state
.receive_payload
;
2899 struct lttng_buffer_view payload_view
;
2901 if (state
->left_to_receive
== 0) {
2902 /* Short-circuit for payload-less commands. */
2903 goto reception_complete
;
2906 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2907 reception_buffer
->data
+ state
->received
,
2908 state
->left_to_receive
, MSG_DONTWAIT
);
2910 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2911 PERROR("Unable to receive command payload on sock %d",
2913 status
= RELAY_CONNECTION_STATUS_ERROR
;
2916 } else if (ret
== 0) {
2917 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2918 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2923 assert(ret
<= state
->left_to_receive
);
2925 state
->left_to_receive
-= ret
;
2926 state
->received
+= ret
;
2928 if (state
->left_to_receive
> 0) {
2930 * Can't transition to the protocol's next state, wait to
2931 * receive the rest of the header.
2933 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2934 state
->received
, state
->left_to_receive
,
2940 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2941 conn
->sock
->fd
, state
->received
);
2943 * The payload required to process the command has been received.
2944 * A view to the reception buffer is forwarded to the various
2945 * commands and the state of the control is reset on success.
2947 * Commands are responsible for sending their reply to the peer.
2949 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2951 ret
= relay_process_control_command(conn
,
2952 &state
->header
, &payload_view
);
2954 status
= RELAY_CONNECTION_STATUS_ERROR
;
2958 ret
= connection_reset_protocol_state(conn
);
2960 status
= RELAY_CONNECTION_STATUS_ERROR
;
2966 static enum relay_connection_status
relay_process_control_receive_header(
2967 struct relay_connection
*conn
)
2970 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2971 struct lttcomm_relayd_hdr header
;
2972 struct lttng_dynamic_buffer
*reception_buffer
=
2973 &conn
->protocol
.ctrl
.reception_buffer
;
2974 struct ctrl_connection_state_receive_header
*state
=
2975 &conn
->protocol
.ctrl
.state
.receive_header
;
2977 assert(state
->left_to_receive
!= 0);
2979 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2980 reception_buffer
->data
+ state
->received
,
2981 state
->left_to_receive
, MSG_DONTWAIT
);
2983 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2984 PERROR("Unable to receive control command header on sock %d",
2986 status
= RELAY_CONNECTION_STATUS_ERROR
;
2989 } else if (ret
== 0) {
2990 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2991 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2996 assert(ret
<= state
->left_to_receive
);
2998 state
->left_to_receive
-= ret
;
2999 state
->received
+= ret
;
3001 if (state
->left_to_receive
> 0) {
3003 * Can't transition to the protocol's next state, wait to
3004 * receive the rest of the header.
3006 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3007 state
->received
, state
->left_to_receive
,
3012 /* Transition to next state: receiving the command's payload. */
3013 conn
->protocol
.ctrl
.state_id
=
3014 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3015 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
3016 header
.circuit_id
= be64toh(header
.circuit_id
);
3017 header
.data_size
= be64toh(header
.data_size
);
3018 header
.cmd
= be32toh(header
.cmd
);
3019 header
.cmd_version
= be32toh(header
.cmd_version
);
3020 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
3021 &header
, sizeof(header
));
3023 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
3024 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
3027 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
3028 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
3030 status
= RELAY_CONNECTION_STATUS_ERROR
;
3034 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
3036 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
3037 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
3040 status
= RELAY_CONNECTION_STATUS_ERROR
;
3044 if (header
.data_size
== 0) {
3046 * Manually invoke the next state as the poll loop
3047 * will not wake-up to allow us to proceed further.
3049 status
= relay_process_control_receive_payload(conn
);
3056 * Process the commands received on the control socket
3058 static enum relay_connection_status
relay_process_control(
3059 struct relay_connection
*conn
)
3061 enum relay_connection_status status
;
3063 switch (conn
->protocol
.ctrl
.state_id
) {
3064 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
3065 status
= relay_process_control_receive_header(conn
);
3067 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3068 status
= relay_process_control_receive_payload(conn
);
3071 ERR("Unknown control connection protocol state encountered.");
3078 static enum relay_connection_status
relay_process_data_receive_header(
3079 struct relay_connection
*conn
)
3082 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3083 struct data_connection_state_receive_header
*state
=
3084 &conn
->protocol
.data
.state
.receive_header
;
3085 struct lttcomm_relayd_data_hdr header
;
3086 struct relay_stream
*stream
;
3088 assert(state
->left_to_receive
!= 0);
3090 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
3091 state
->header_reception_buffer
+ state
->received
,
3092 state
->left_to_receive
, MSG_DONTWAIT
);
3094 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3095 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
3096 status
= RELAY_CONNECTION_STATUS_ERROR
;
3099 } else if (ret
== 0) {
3100 /* Orderly shutdown. Not necessary to print an error. */
3101 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
3102 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3107 assert(ret
<= state
->left_to_receive
);
3109 state
->left_to_receive
-= ret
;
3110 state
->received
+= ret
;
3112 if (state
->left_to_receive
> 0) {
3114 * Can't transition to the protocol's next state, wait to
3115 * receive the rest of the header.
3117 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
3118 state
->received
, state
->left_to_receive
,
3123 /* Transition to next state: receiving the payload. */
3124 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
3126 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
3127 header
.circuit_id
= be64toh(header
.circuit_id
);
3128 header
.stream_id
= be64toh(header
.stream_id
);
3129 header
.data_size
= be32toh(header
.data_size
);
3130 header
.net_seq_num
= be64toh(header
.net_seq_num
);
3131 header
.padding_size
= be32toh(header
.padding_size
);
3132 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
3134 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
3136 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
3137 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
3139 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
3140 conn
->sock
->fd
, header
.circuit_id
,
3141 header
.stream_id
, header
.data_size
,
3142 header
.net_seq_num
, header
.padding_size
);
3144 stream
= stream_get_by_id(header
.stream_id
);
3146 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
3148 /* Protocol error. */
3149 status
= RELAY_CONNECTION_STATUS_ERROR
;
3153 pthread_mutex_lock(&stream
->lock
);
3154 /* Prepare stream for the reception of a new packet. */
3155 ret
= stream_init_packet(stream
, header
.data_size
,
3156 &conn
->protocol
.data
.state
.receive_payload
.rotate_index
);
3157 pthread_mutex_unlock(&stream
->lock
);
3159 ERR("Failed to rotate stream output file");
3160 status
= RELAY_CONNECTION_STATUS_ERROR
;
3161 goto end_stream_unlock
;
3170 static enum relay_connection_status
relay_process_data_receive_payload(
3171 struct relay_connection
*conn
)
3174 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
3175 struct relay_stream
*stream
;
3176 struct data_connection_state_receive_payload
*state
=
3177 &conn
->protocol
.data
.state
.receive_payload
;
3178 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
3179 char data_buffer
[chunk_size
];
3180 bool partial_recv
= false;
3181 bool new_stream
= false, close_requested
= false, index_flushed
= false;
3182 uint64_t left_to_receive
= state
->left_to_receive
;
3183 struct relay_session
*session
;
3185 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3186 state
->header
.stream_id
, state
->header
.net_seq_num
,
3187 state
->received
, left_to_receive
);
3189 stream
= stream_get_by_id(state
->header
.stream_id
);
3191 /* Protocol error. */
3192 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
3193 state
->header
.stream_id
);
3194 status
= RELAY_CONNECTION_STATUS_ERROR
;
3198 pthread_mutex_lock(&stream
->lock
);
3199 session
= stream
->trace
->session
;
3200 if (!conn
->session
) {
3201 ret
= connection_set_session(conn
, session
);
3203 status
= RELAY_CONNECTION_STATUS_ERROR
;
3204 goto end_stream_unlock
;
3209 * The size of the "chunk" received on any iteration is bounded by:
3210 * - the data left to receive,
3211 * - the data immediately available on the socket,
3212 * - the on-stack data buffer
3214 while (left_to_receive
> 0 && !partial_recv
) {
3215 size_t recv_size
= min(left_to_receive
, chunk_size
);
3216 struct lttng_buffer_view packet_chunk
;
3218 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
3219 recv_size
, MSG_DONTWAIT
);
3221 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
3222 PERROR("Socket %d error", conn
->sock
->fd
);
3223 status
= RELAY_CONNECTION_STATUS_ERROR
;
3225 goto end_stream_unlock
;
3226 } else if (ret
== 0) {
3227 /* No more data ready to be consumed on socket. */
3228 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
3229 state
->header
.stream_id
);
3230 status
= RELAY_CONNECTION_STATUS_CLOSED
;
3232 } else if (ret
< (int) recv_size
) {
3234 * All the data available on the socket has been
3237 partial_recv
= true;
3241 packet_chunk
= lttng_buffer_view_init(data_buffer
,
3243 assert(packet_chunk
.data
);
3245 ret
= stream_write(stream
, &packet_chunk
, 0);
3247 ERR("Relay error writing data to file");
3248 status
= RELAY_CONNECTION_STATUS_ERROR
;
3249 goto end_stream_unlock
;
3252 left_to_receive
-= recv_size
;
3253 state
->received
+= recv_size
;
3254 state
->left_to_receive
= left_to_receive
;
3257 if (state
->left_to_receive
> 0) {
3259 * Did not receive all the data expected, wait for more data to
3260 * become available on the socket.
3262 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
3263 state
->header
.stream_id
, state
->received
,
3264 state
->left_to_receive
);
3265 goto end_stream_unlock
;
3268 ret
= stream_write(stream
, NULL
, state
->header
.padding_size
);
3270 status
= RELAY_CONNECTION_STATUS_ERROR
;
3271 goto end_stream_unlock
;
3274 if (session_streams_have_index(session
)) {
3275 ret
= stream_update_index(stream
, state
->header
.net_seq_num
,
3276 state
->rotate_index
, &index_flushed
,
3277 state
->header
.data_size
+ state
->header
.padding_size
);
3279 ERR("Failed to update index: stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
3280 stream
->stream_handle
,
3281 state
->header
.net_seq_num
, ret
);
3282 status
= RELAY_CONNECTION_STATUS_ERROR
;
3283 goto end_stream_unlock
;
3287 if (stream
->prev_data_seq
== -1ULL) {
3291 ret
= stream_complete_packet(stream
, state
->header
.data_size
+
3292 state
->header
.padding_size
, state
->header
.net_seq_num
,
3295 status
= RELAY_CONNECTION_STATUS_ERROR
;
3296 goto end_stream_unlock
;
3300 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
3301 * contents of *state which are aliased (union) to the same location as
3302 * the new state. Don't use it beyond this point.
3304 connection_reset_protocol_state(conn
);
3308 close_requested
= stream
->close_requested
;
3309 pthread_mutex_unlock(&stream
->lock
);
3310 if (close_requested
&& left_to_receive
== 0) {
3311 try_stream_close(stream
);
3315 pthread_mutex_lock(&session
->lock
);
3316 uatomic_set(&session
->new_streams
, 1);
3317 pthread_mutex_unlock(&session
->lock
);
3326 * relay_process_data: Process the data received on the data socket
3328 static enum relay_connection_status
relay_process_data(
3329 struct relay_connection
*conn
)
3331 enum relay_connection_status status
;
3333 switch (conn
->protocol
.data
.state_id
) {
3334 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
3335 status
= relay_process_data_receive_header(conn
);
3337 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
3338 status
= relay_process_data_receive_payload(conn
);
3341 ERR("Unexpected data connection communication state.");
3348 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
3352 (void) lttng_poll_del(events
, pollfd
);
3354 ret
= close(pollfd
);
3356 ERR("Closing pollfd %d", pollfd
);
3360 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
3361 int pollfd
, struct relay_connection
*conn
)
3363 const char *type_str
;
3365 switch (conn
->type
) {
3370 type_str
= "Control";
3372 case RELAY_VIEWER_COMMAND
:
3373 type_str
= "Viewer Command";
3375 case RELAY_VIEWER_NOTIFICATION
:
3376 type_str
= "Viewer Notification";
3379 type_str
= "Unknown";
3381 cleanup_connection_pollfd(events
, pollfd
);
3382 connection_put(conn
);
3383 DBG("%s connection closed with %d", type_str
, pollfd
);
3387 * This thread does the actual work
3389 static void *relay_thread_worker(void *data
)
3391 int ret
, err
= -1, last_seen_data_fd
= -1;
3393 struct lttng_poll_event events
;
3394 struct lttng_ht
*relay_connections_ht
;
3395 struct lttng_ht_iter iter
;
3396 struct relay_connection
*destroy_conn
= NULL
;
3398 DBG("[thread] Relay worker started");
3400 rcu_register_thread();
3402 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
3404 if (testpoint(relayd_thread_worker
)) {
3405 goto error_testpoint
;
3408 health_code_update();
3410 /* table of connections indexed on socket */
3411 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
3412 if (!relay_connections_ht
) {
3413 goto relay_connections_ht_error
;
3416 ret
= create_thread_poll_set(&events
, 2);
3418 goto error_poll_create
;
3421 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
3428 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
3430 health_code_update();
3432 /* Infinite blocking call, waiting for transmission */
3433 DBG3("Relayd worker thread polling...");
3434 health_poll_entry();
3435 ret
= lttng_poll_wait(&events
, -1);
3439 * Restart interrupted system call.
3441 if (errno
== EINTR
) {
3450 * Process control. The control connection is
3451 * prioritized so we don't starve it with high
3452 * throughput tracing data on the data connection.
3454 for (i
= 0; i
< nb_fd
; i
++) {
3455 /* Fetch once the poll data */
3456 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3457 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3459 health_code_update();
3461 /* Thread quit pipe has been closed. Killing thread. */
3462 ret
= check_thread_quit_pipe(pollfd
, revents
);
3468 /* Inspect the relay conn pipe for new connection */
3469 if (pollfd
== relay_conn_pipe
[0]) {
3470 if (revents
& LPOLLIN
) {
3471 struct relay_connection
*conn
;
3473 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
3477 ret
= lttng_poll_add(&events
,
3479 LPOLLIN
| LPOLLRDHUP
);
3481 ERR("Failed to add new connection file descriptor to poll set");
3484 connection_ht_add(relay_connections_ht
, conn
);
3485 DBG("Connection socket %d added", conn
->sock
->fd
);
3486 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3487 ERR("Relay connection pipe error");
3490 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
3494 struct relay_connection
*ctrl_conn
;
3496 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3497 /* If not found, there is a synchronization issue. */
3500 if (ctrl_conn
->type
== RELAY_DATA
) {
3501 if (revents
& LPOLLIN
) {
3503 * Flag the last seen data fd not deleted. It will be
3504 * used as the last seen fd if any fd gets deleted in
3507 last_notdel_data_fd
= pollfd
;
3509 goto put_ctrl_connection
;
3511 assert(ctrl_conn
->type
== RELAY_CONTROL
);
3513 if (revents
& LPOLLIN
) {
3514 enum relay_connection_status status
;
3516 status
= relay_process_control(ctrl_conn
);
3517 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3519 * On socket error flag the session as aborted to force
3520 * the cleanup of its stream otherwise it can leak
3521 * during the lifetime of the relayd.
3523 * This prevents situations in which streams can be
3524 * left opened because an index was received, the
3525 * control connection is closed, and the data
3526 * connection is closed (uncleanly) before the packet's
3529 * Since the control connection encountered an error,
3530 * it is okay to be conservative and close the
3531 * session right now as we can't rely on the protocol
3532 * being respected anymore.
3534 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3535 session_abort(ctrl_conn
->session
);
3538 /* Clear the connection on error or close. */
3539 relay_thread_close_connection(&events
,
3544 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3545 relay_thread_close_connection(&events
,
3547 if (last_seen_data_fd
== pollfd
) {
3548 last_seen_data_fd
= last_notdel_data_fd
;
3551 ERR("Unexpected poll events %u for control sock %d",
3553 connection_put(ctrl_conn
);
3556 put_ctrl_connection
:
3557 connection_put(ctrl_conn
);
3562 * The last loop handled a control request, go back to poll to make
3563 * sure we prioritise the control socket.
3569 if (last_seen_data_fd
>= 0) {
3570 for (i
= 0; i
< nb_fd
; i
++) {
3571 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3573 health_code_update();
3575 if (last_seen_data_fd
== pollfd
) {
3582 /* Process data connection. */
3583 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3584 /* Fetch the poll data. */
3585 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3586 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3587 struct relay_connection
*data_conn
;
3589 health_code_update();
3592 /* No activity for this FD (poll implementation). */
3596 /* Skip the command pipe. It's handled in the first loop. */
3597 if (pollfd
== relay_conn_pipe
[0]) {
3601 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3603 /* Skip it. Might be removed before. */
3606 if (data_conn
->type
== RELAY_CONTROL
) {
3607 goto put_data_connection
;
3609 assert(data_conn
->type
== RELAY_DATA
);
3611 if (revents
& LPOLLIN
) {
3612 enum relay_connection_status status
;
3614 status
= relay_process_data(data_conn
);
3615 /* Connection closed or error. */
3616 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3618 * On socket error flag the session as aborted to force
3619 * the cleanup of its stream otherwise it can leak
3620 * during the lifetime of the relayd.
3622 * This prevents situations in which streams can be
3623 * left opened because an index was received, the
3624 * control connection is closed, and the data
3625 * connection is closed (uncleanly) before the packet's
3628 * Since the data connection encountered an error,
3629 * it is okay to be conservative and close the
3630 * session right now as we can't rely on the protocol
3631 * being respected anymore.
3633 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3634 session_abort(data_conn
->session
);
3636 relay_thread_close_connection(&events
, pollfd
,
3639 * Every goto restart call sets the last seen fd where
3640 * here we don't really care since we gracefully
3641 * continue the loop after the connection is deleted.
3644 /* Keep last seen port. */
3645 last_seen_data_fd
= pollfd
;
3646 connection_put(data_conn
);
3649 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3650 relay_thread_close_connection(&events
, pollfd
,
3653 ERR("Unknown poll events %u for data sock %d",
3656 put_data_connection
:
3657 connection_put(data_conn
);
3659 last_seen_data_fd
= -1;
3662 /* Normal exit, no error */
3667 /* Cleanup remaining connection object. */
3669 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3672 health_code_update();
3674 session_abort(destroy_conn
->session
);
3677 * No need to grab another ref, because we own
3680 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3685 lttng_poll_clean(&events
);
3687 lttng_ht_destroy(relay_connections_ht
);
3688 relay_connections_ht_error
:
3689 /* Close relay conn pipes */
3690 utils_close_pipe(relay_conn_pipe
);
3692 DBG("Thread exited with error");
3694 DBG("Worker thread cleanup complete");
3698 ERR("Health error occurred in %s", __func__
);
3700 health_unregister(health_relayd
);
3701 rcu_unregister_thread();
3702 lttng_relay_stop_threads();
3707 * Create the relay command pipe to wake thread_manage_apps.
3708 * Closed in cleanup().
3710 static int create_relay_conn_pipe(void)
3714 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3722 int main(int argc
, char **argv
)
3724 int ret
= 0, retval
= 0;
3727 /* Parse environment variables */
3728 ret
= parse_env_options();
3736 * Command line arguments overwrite environment.
3739 if (set_options(argc
, argv
)) {
3744 if (set_signal_handler()) {
3749 relayd_config_log();
3751 if (opt_print_version
) {
3757 /* Try to create directory if -o, --output is specified. */
3758 if (opt_output_path
) {
3759 if (*opt_output_path
!= '/') {
3760 ERR("Please specify an absolute path for -o, --output PATH");
3765 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3768 ERR("Unable to create %s", opt_output_path
);
3775 if (opt_daemon
|| opt_background
) {
3778 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3786 * We are in the child. Make sure all other file
3787 * descriptors are closed, in case we are called with
3788 * more opened file descriptors than the standard ones.
3790 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3795 if (opt_working_directory
) {
3796 ret
= utils_change_working_directory(opt_working_directory
);
3798 /* All errors are already logged. */
3803 sessiond_trace_chunk_registry
= sessiond_trace_chunk_registry_create();
3804 if (!sessiond_trace_chunk_registry
) {
3805 ERR("Failed to initialize session daemon trace chunk registry");
3807 goto exit_sessiond_trace_chunk_registry
;
3810 /* Initialize thread health monitoring */
3811 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3812 if (!health_relayd
) {
3813 PERROR("health_app_create error");
3815 goto exit_health_app_create
;
3818 /* Create thread quit pipe */
3819 if (init_thread_quit_pipe()) {
3821 goto exit_init_data
;
3824 /* Setup the thread apps communication pipe. */
3825 if (create_relay_conn_pipe()) {
3827 goto exit_init_data
;
3830 /* Init relay command queue. */
3831 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3833 /* Initialize communication library */
3835 lttcomm_inet_init();
3837 /* tables of sessions indexed by session ID */
3838 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3841 goto exit_init_data
;
3844 /* tables of streams indexed by stream ID */
3845 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3846 if (!relay_streams_ht
) {
3848 goto exit_init_data
;
3851 /* tables of streams indexed by stream ID */
3852 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3853 if (!viewer_streams_ht
) {
3855 goto exit_init_data
;
3858 ret
= utils_create_pipe(health_quit_pipe
);
3861 goto exit_health_quit_pipe
;
3864 /* Create thread to manage the client socket */
3865 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3866 thread_manage_health
, (void *) NULL
);
3869 PERROR("pthread_create health");
3871 goto exit_health_thread
;
3874 /* Setup the dispatcher thread */
3875 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3876 relay_thread_dispatcher
, (void *) NULL
);
3879 PERROR("pthread_create dispatcher");
3881 goto exit_dispatcher_thread
;
3884 /* Setup the worker thread */
3885 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3886 relay_thread_worker
, NULL
);
3889 PERROR("pthread_create worker");
3891 goto exit_worker_thread
;
3894 /* Setup the listener thread */
3895 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3896 relay_thread_listener
, (void *) NULL
);
3899 PERROR("pthread_create listener");
3901 goto exit_listener_thread
;
3904 ret
= relayd_live_create(live_uri
);
3906 ERR("Starting live viewer threads");
3912 * This is where we start awaiting program completion (e.g. through
3913 * signal that asks threads to teardown).
3916 ret
= relayd_live_join();
3922 ret
= pthread_join(listener_thread
, &status
);
3925 PERROR("pthread_join listener_thread");
3929 exit_listener_thread
:
3930 ret
= pthread_join(worker_thread
, &status
);
3933 PERROR("pthread_join worker_thread");
3938 ret
= pthread_join(dispatcher_thread
, &status
);
3941 PERROR("pthread_join dispatcher_thread");
3944 exit_dispatcher_thread
:
3946 ret
= pthread_join(health_thread
, &status
);
3949 PERROR("pthread_join health_thread");
3954 utils_close_pipe(health_quit_pipe
);
3955 exit_health_quit_pipe
:
3958 health_app_destroy(health_relayd
);
3959 sessiond_trace_chunk_registry_destroy(sessiond_trace_chunk_registry
);
3960 exit_health_app_create
:
3961 exit_sessiond_trace_chunk_registry
:
3964 * Wait for all pending call_rcu work to complete before tearing
3965 * down data structures. call_rcu worker may be trying to
3966 * perform lookups in those structures.
3971 /* Ensure all prior call_rcu are done. */