2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
43 #include <lttng/lttng.h>
44 #include <common/common.h>
45 #include <common/compat/poll.h>
46 #include <common/compat/socket.h>
47 #include <common/compat/endian.h>
48 #include <common/compat/getenv.h>
49 #include <common/defaults.h>
50 #include <common/daemonize.h>
51 #include <common/futex.h>
52 #include <common/sessiond-comm/sessiond-comm.h>
53 #include <common/sessiond-comm/inet.h>
54 #include <common/sessiond-comm/relayd.h>
55 #include <common/uri.h>
56 #include <common/utils.h>
57 #include <common/config/session-config.h>
58 #include <common/dynamic-buffer.h>
59 #include <common/buffer-view.h>
60 #include <urcu/rculist.h>
63 #include "ctf-trace.h"
66 #include "lttng-relayd.h"
68 #include "health-relayd.h"
69 #include "testpoint.h"
70 #include "viewer-stream.h"
73 #include "connection.h"
74 #include "tracefile-array.h"
75 #include "tcp_keep_alive.h"
77 enum relay_connection_status
{
78 RELAY_CONNECTION_STATUS_OK
,
79 /* An error occured while processing an event on the connection. */
80 RELAY_CONNECTION_STATUS_ERROR
,
81 /* Connection closed/shutdown cleanly. */
82 RELAY_CONNECTION_STATUS_CLOSED
,
85 /* command line options */
86 char *opt_output_path
, *opt_working_directory
;
87 static int opt_daemon
, opt_background
;
90 * We need to wait for listener and live listener threads, as well as
91 * health check thread, before being ready to signal readiness.
93 #define NR_LTTNG_RELAY_READY 3
94 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
96 /* Size of receive buffer. */
97 #define RECV_DATA_BUFFER_SIZE 65536
99 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
100 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
102 static struct lttng_uri
*control_uri
;
103 static struct lttng_uri
*data_uri
;
104 static struct lttng_uri
*live_uri
;
106 const char *progname
;
108 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
109 static int tracing_group_name_override
;
111 const char * const config_section_name
= "relayd";
114 * Quit pipe for all threads. This permits a single cancellation point
115 * for all threads when receiving an event on the pipe.
117 int thread_quit_pipe
[2] = { -1, -1 };
120 * This pipe is used to inform the worker thread that a command is queued and
121 * ready to be processed.
123 static int relay_conn_pipe
[2] = { -1, -1 };
125 /* Shared between threads */
126 static int dispatch_thread_exit
;
128 static pthread_t listener_thread
;
129 static pthread_t dispatcher_thread
;
130 static pthread_t worker_thread
;
131 static pthread_t health_thread
;
134 * last_relay_stream_id_lock protects last_relay_stream_id increment
135 * atomicity on 32-bit architectures.
137 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
138 static uint64_t last_relay_stream_id
;
141 * Relay command queue.
143 * The relay_thread_listener and relay_thread_dispatcher communicate with this
146 static struct relay_conn_queue relay_conn_queue
;
148 /* Global relay stream hash table. */
149 struct lttng_ht
*relay_streams_ht
;
151 /* Global relay viewer stream hash table. */
152 struct lttng_ht
*viewer_streams_ht
;
154 /* Global relay sessions hash table. */
155 struct lttng_ht
*sessions_ht
;
157 /* Relayd health monitoring */
158 struct health_app
*health_relayd
;
160 static struct option long_options
[] = {
161 { "control-port", 1, 0, 'C', },
162 { "data-port", 1, 0, 'D', },
163 { "live-port", 1, 0, 'L', },
164 { "daemonize", 0, 0, 'd', },
165 { "background", 0, 0, 'b', },
166 { "group", 1, 0, 'g', },
167 { "help", 0, 0, 'h', },
168 { "output", 1, 0, 'o', },
169 { "verbose", 0, 0, 'v', },
170 { "config", 1, 0, 'f' },
171 { "version", 0, 0, 'V' },
172 { "working-directory", 1, 0, 'w', },
176 static const char *config_ignore_options
[] = { "help", "config", "version" };
179 * Take an option from the getopt output and set it in the right variable to be
182 * Return 0 on success else a negative value.
184 static int set_option(int opt
, const char *arg
, const char *optname
)
190 fprintf(stderr
, "option %s", optname
);
192 fprintf(stderr
, " with arg %s\n", arg
);
196 if (lttng_is_setuid_setgid()) {
197 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
198 "-C, --control-port");
200 ret
= uri_parse(arg
, &control_uri
);
202 ERR("Invalid control URI specified");
205 if (control_uri
->port
== 0) {
206 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
211 if (lttng_is_setuid_setgid()) {
212 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
215 ret
= uri_parse(arg
, &data_uri
);
217 ERR("Invalid data URI specified");
220 if (data_uri
->port
== 0) {
221 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
226 if (lttng_is_setuid_setgid()) {
227 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
230 ret
= uri_parse(arg
, &live_uri
);
232 ERR("Invalid live URI specified");
235 if (live_uri
->port
== 0) {
236 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
247 if (lttng_is_setuid_setgid()) {
248 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
251 tracing_group_name
= strdup(arg
);
252 if (tracing_group_name
== NULL
) {
257 tracing_group_name_override
= 1;
261 ret
= utils_show_man_page(8, "lttng-relayd");
263 ERR("Cannot view man page lttng-relayd(8)");
268 fprintf(stdout
, "%s\n", VERSION
);
271 if (lttng_is_setuid_setgid()) {
272 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
275 ret
= asprintf(&opt_output_path
, "%s", arg
);
278 PERROR("asprintf opt_output_path");
284 if (lttng_is_setuid_setgid()) {
285 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
286 "-w, --working-directory");
288 ret
= asprintf(&opt_working_directory
, "%s", arg
);
291 PERROR("asprintf working_directory");
298 /* Verbose level can increase using multiple -v */
300 lttng_opt_verbose
= config_parse_value(arg
);
302 /* Only 3 level of verbosity (-vvv). */
303 if (lttng_opt_verbose
< 3) {
304 lttng_opt_verbose
+= 1;
309 /* Unknown option or other error.
310 * Error is printed by getopt, just return */
323 * config_entry_handler_cb used to handle options read from a config file.
324 * See config_entry_handler_cb comment in common/config/session-config.h for the
325 * return value conventions.
327 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
331 if (!entry
|| !entry
->name
|| !entry
->value
) {
336 /* Check if the option is to be ignored */
337 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
338 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
343 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
344 /* Ignore if entry name is not fully matched. */
345 if (strcmp(entry
->name
, long_options
[i
].name
)) {
350 * If the option takes no argument on the command line,
351 * we have to check if the value is "true". We support
352 * non-zero numeric values, true, on and yes.
354 if (!long_options
[i
].has_arg
) {
355 ret
= config_parse_value(entry
->value
);
358 WARN("Invalid configuration value \"%s\" for option %s",
359 entry
->value
, entry
->name
);
361 /* False, skip boolean config option. */
366 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
370 WARN("Unrecognized option \"%s\" in daemon configuration file.",
377 static void parse_env_options(void)
381 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
383 opt_working_directory
= value
;
387 static int set_options(int argc
, char **argv
)
389 int c
, ret
= 0, option_index
= 0, retval
= 0;
390 int orig_optopt
= optopt
, orig_optind
= optind
;
391 char *default_address
, *optstring
;
392 const char *config_path
= NULL
;
394 optstring
= utils_generate_optstring(long_options
,
395 sizeof(long_options
) / sizeof(struct option
));
401 /* Check for the --config option */
403 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
404 &option_index
)) != -1) {
408 } else if (c
!= 'f') {
412 if (lttng_is_setuid_setgid()) {
413 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
416 config_path
= utils_expand_path(optarg
);
418 ERR("Failed to resolve path: %s", optarg
);
423 ret
= config_get_section_entries(config_path
, config_section_name
,
424 config_entry_handler
, NULL
);
427 ERR("Invalid configuration option at line %i", ret
);
433 /* Reset getopt's global state */
434 optopt
= orig_optopt
;
435 optind
= orig_optind
;
437 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
442 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
449 /* assign default values */
450 if (control_uri
== NULL
) {
451 ret
= asprintf(&default_address
,
452 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
453 DEFAULT_NETWORK_CONTROL_PORT
);
455 PERROR("asprintf default data address");
460 ret
= uri_parse(default_address
, &control_uri
);
461 free(default_address
);
463 ERR("Invalid control URI specified");
468 if (data_uri
== NULL
) {
469 ret
= asprintf(&default_address
,
470 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
471 DEFAULT_NETWORK_DATA_PORT
);
473 PERROR("asprintf default data address");
478 ret
= uri_parse(default_address
, &data_uri
);
479 free(default_address
);
481 ERR("Invalid data URI specified");
486 if (live_uri
== NULL
) {
487 ret
= asprintf(&default_address
,
488 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
489 DEFAULT_NETWORK_VIEWER_PORT
);
491 PERROR("asprintf default viewer control address");
496 ret
= uri_parse(default_address
, &live_uri
);
497 free(default_address
);
499 ERR("Invalid viewer control URI specified");
510 static void print_global_objects(void)
512 rcu_register_thread();
514 print_viewer_streams();
515 print_relay_streams();
518 rcu_unregister_thread();
524 static void relayd_cleanup(void)
526 print_global_objects();
530 if (viewer_streams_ht
)
531 lttng_ht_destroy(viewer_streams_ht
);
532 if (relay_streams_ht
)
533 lttng_ht_destroy(relay_streams_ht
);
535 lttng_ht_destroy(sessions_ht
);
537 /* free the dynamically allocated opt_output_path */
538 free(opt_output_path
);
540 /* Close thread quit pipes */
541 utils_close_pipe(thread_quit_pipe
);
543 uri_free(control_uri
);
545 /* Live URI is freed in the live thread. */
547 if (tracing_group_name_override
) {
548 free((void *) tracing_group_name
);
553 * Write to writable pipe used to notify a thread.
555 static int notify_thread_pipe(int wpipe
)
559 ret
= lttng_write(wpipe
, "!", 1);
561 PERROR("write poll pipe");
569 static int notify_health_quit_pipe(int *pipe
)
573 ret
= lttng_write(pipe
[1], "4", 1);
575 PERROR("write relay health quit");
584 * Stop all relayd and relayd-live threads.
586 int lttng_relay_stop_threads(void)
590 /* Stopping all threads */
591 DBG("Terminating all threads");
592 if (notify_thread_pipe(thread_quit_pipe
[1])) {
593 ERR("write error on thread quit pipe");
597 if (notify_health_quit_pipe(health_quit_pipe
)) {
598 ERR("write error on health quit pipe");
601 /* Dispatch thread */
602 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
603 futex_nto1_wake(&relay_conn_queue
.futex
);
605 if (relayd_live_stop()) {
606 ERR("Error stopping live threads");
613 * Signal handler for the daemon
615 * Simply stop all worker threads, leaving main() return gracefully after
616 * joining all threads and calling cleanup().
618 static void sighandler(int sig
)
622 DBG("SIGINT caught");
623 if (lttng_relay_stop_threads()) {
624 ERR("Error stopping threads");
628 DBG("SIGTERM caught");
629 if (lttng_relay_stop_threads()) {
630 ERR("Error stopping threads");
634 CMM_STORE_SHARED(recv_child_signal
, 1);
642 * Setup signal handler for :
643 * SIGINT, SIGTERM, SIGPIPE
645 static int set_signal_handler(void)
651 if ((ret
= sigemptyset(&sigset
)) < 0) {
652 PERROR("sigemptyset");
659 sa
.sa_handler
= sighandler
;
660 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
665 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
670 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
675 sa
.sa_handler
= SIG_IGN
;
676 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
681 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
686 void lttng_relay_notify_ready(void)
688 /* Notify the parent of the fork() process that we are ready. */
689 if (opt_daemon
|| opt_background
) {
690 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
691 kill(child_ppid
, SIGUSR1
);
697 * Init thread quit pipe.
699 * Return -1 on error or 0 if all pipes are created.
701 static int init_thread_quit_pipe(void)
705 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
711 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
713 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
717 if (events
== NULL
|| size
== 0) {
722 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
728 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
740 * Check if the thread quit pipe was triggered.
742 * Return 1 if it was triggered else 0;
744 static int check_thread_quit_pipe(int fd
, uint32_t events
)
746 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
754 * Create and init socket from uri.
756 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
759 struct lttcomm_sock
*sock
= NULL
;
761 sock
= lttcomm_alloc_sock_from_uri(uri
);
763 ERR("Allocating socket");
767 ret
= lttcomm_create_sock(sock
);
771 DBG("Listening on sock %d", sock
->fd
);
773 ret
= sock
->ops
->bind(sock
);
778 ret
= sock
->ops
->listen(sock
, -1);
788 lttcomm_destroy_sock(sock
);
794 * This thread manages the listening for new connections on the network
796 static void *relay_thread_listener(void *data
)
798 int i
, ret
, pollfd
, err
= -1;
799 uint32_t revents
, nb_fd
;
800 struct lttng_poll_event events
;
801 struct lttcomm_sock
*control_sock
, *data_sock
;
803 DBG("[thread] Relay listener started");
805 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
807 health_code_update();
809 control_sock
= relay_socket_create(control_uri
);
811 goto error_sock_control
;
814 data_sock
= relay_socket_create(data_uri
);
816 goto error_sock_relay
;
820 * Pass 3 as size here for the thread quit pipe, control and
823 ret
= create_thread_poll_set(&events
, 3);
825 goto error_create_poll
;
828 /* Add the control socket */
829 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
834 /* Add the data socket */
835 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
840 lttng_relay_notify_ready();
842 if (testpoint(relayd_thread_listener
)) {
843 goto error_testpoint
;
847 health_code_update();
849 DBG("Listener accepting connections");
853 ret
= lttng_poll_wait(&events
, -1);
857 * Restart interrupted system call.
859 if (errno
== EINTR
) {
867 DBG("Relay new connection received");
868 for (i
= 0; i
< nb_fd
; i
++) {
869 health_code_update();
871 /* Fetch once the poll data */
872 revents
= LTTNG_POLL_GETEV(&events
, i
);
873 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
877 * No activity for this FD (poll
883 /* Thread quit pipe has been closed. Killing thread. */
884 ret
= check_thread_quit_pipe(pollfd
, revents
);
890 if (revents
& LPOLLIN
) {
892 * A new connection is requested, therefore a
893 * sessiond/consumerd connection is allocated in
894 * this thread, enqueued to a global queue and
895 * dequeued (and freed) in the worker thread.
898 struct relay_connection
*new_conn
;
899 struct lttcomm_sock
*newsock
;
900 enum connection_type type
;
902 if (pollfd
== data_sock
->fd
) {
904 newsock
= data_sock
->ops
->accept(data_sock
);
905 DBG("Relay data connection accepted, socket %d",
908 assert(pollfd
== control_sock
->fd
);
909 type
= RELAY_CONTROL
;
910 newsock
= control_sock
->ops
->accept(control_sock
);
911 DBG("Relay control connection accepted, socket %d",
915 PERROR("accepting sock");
919 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
922 PERROR("setsockopt inet");
923 lttcomm_destroy_sock(newsock
);
927 ret
= socket_apply_keep_alive_config(newsock
->fd
);
929 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
931 lttcomm_destroy_sock(newsock
);
935 new_conn
= connection_create(newsock
, type
);
937 lttcomm_destroy_sock(newsock
);
941 /* Enqueue request for the dispatcher thread. */
942 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
946 * Wake the dispatch queue futex.
947 * Implicit memory barrier with the
948 * exchange in cds_wfcq_enqueue.
950 futex_nto1_wake(&relay_conn_queue
.futex
);
951 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
952 ERR("socket poll error");
955 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
965 lttng_poll_clean(&events
);
967 if (data_sock
->fd
>= 0) {
968 ret
= data_sock
->ops
->close(data_sock
);
973 lttcomm_destroy_sock(data_sock
);
975 if (control_sock
->fd
>= 0) {
976 ret
= control_sock
->ops
->close(control_sock
);
981 lttcomm_destroy_sock(control_sock
);
985 ERR("Health error occurred in %s", __func__
);
987 health_unregister(health_relayd
);
988 DBG("Relay listener thread cleanup complete");
989 lttng_relay_stop_threads();
994 * This thread manages the dispatching of the requests to worker threads
996 static void *relay_thread_dispatcher(void *data
)
1000 struct cds_wfcq_node
*node
;
1001 struct relay_connection
*new_conn
= NULL
;
1003 DBG("[thread] Relay dispatcher started");
1005 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1007 if (testpoint(relayd_thread_dispatcher
)) {
1008 goto error_testpoint
;
1011 health_code_update();
1014 health_code_update();
1016 /* Atomically prepare the queue futex */
1017 futex_nto1_prepare(&relay_conn_queue
.futex
);
1019 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1024 health_code_update();
1026 /* Dequeue commands */
1027 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1028 &relay_conn_queue
.tail
);
1030 DBG("Woken up but nothing in the relay command queue");
1031 /* Continue thread execution */
1034 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1036 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1039 * Inform worker thread of the new request. This
1040 * call is blocking so we can be assured that
1041 * the data will be read at some point in time
1042 * or wait to the end of the world :)
1044 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1046 PERROR("write connection pipe");
1047 connection_put(new_conn
);
1050 } while (node
!= NULL
);
1052 /* Futex wait on queue. Blocking call on futex() */
1053 health_poll_entry();
1054 futex_nto1_wait(&relay_conn_queue
.futex
);
1058 /* Normal exit, no error */
1065 ERR("Health error occurred in %s", __func__
);
1067 health_unregister(health_relayd
);
1068 DBG("Dispatch thread dying");
1069 lttng_relay_stop_threads();
1074 * Set index data from the control port to a given index object.
1076 static int set_index_control_data(struct relay_index
*index
,
1077 struct lttcomm_relayd_index
*data
,
1078 struct relay_connection
*conn
)
1080 struct ctf_packet_index index_data
;
1083 * The index on disk is encoded in big endian.
1085 index_data
.packet_size
= htobe64(data
->packet_size
);
1086 index_data
.content_size
= htobe64(data
->content_size
);
1087 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1088 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1089 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1090 index_data
.stream_id
= htobe64(data
->stream_id
);
1092 if (conn
->minor
>= 8) {
1093 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1094 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1097 return relay_index_set_data(index
, &index_data
);
1101 * Handle the RELAYD_CREATE_SESSION command.
1103 * On success, send back the session id or else return a negative value.
1105 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1106 struct relay_connection
*conn
,
1107 const struct lttng_buffer_view
*payload
)
1111 struct relay_session
*session
;
1112 struct lttcomm_relayd_status_session reply
;
1113 char session_name
[LTTNG_NAME_MAX
];
1114 char hostname
[LTTNG_HOST_NAME_MAX
];
1115 uint32_t live_timer
= 0;
1116 bool snapshot
= false;
1118 memset(session_name
, 0, LTTNG_NAME_MAX
);
1119 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1121 memset(&reply
, 0, sizeof(reply
));
1123 switch (conn
->minor
) {
1128 case 4: /* LTTng sessiond 2.4 */
1130 ret
= cmd_create_session_2_4(payload
, session_name
,
1131 hostname
, &live_timer
, &snapshot
);
1137 session
= session_create(session_name
, hostname
, live_timer
,
1138 snapshot
, conn
->major
, conn
->minor
);
1143 assert(!conn
->session
);
1144 conn
->session
= session
;
1145 DBG("Created session %" PRIu64
, session
->id
);
1147 reply
.session_id
= htobe64(session
->id
);
1151 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1153 reply
.ret_code
= htobe32(LTTNG_OK
);
1156 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1157 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1158 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1167 * When we have received all the streams and the metadata for a channel,
1168 * we make them visible to the viewer threads.
1170 static void publish_connection_local_streams(struct relay_connection
*conn
)
1172 struct relay_stream
*stream
;
1173 struct relay_session
*session
= conn
->session
;
1176 * We publish all streams belonging to a session atomically wrt
1179 pthread_mutex_lock(&session
->lock
);
1181 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1183 stream_publish(stream
);
1188 * Inform the viewer that there are new streams in the session.
1190 if (session
->viewer_attached
) {
1191 uatomic_set(&session
->new_streams
, 1);
1193 pthread_mutex_unlock(&session
->lock
);
1197 * relay_add_stream: allocate a new stream for a session
1199 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1200 struct relay_connection
*conn
,
1201 const struct lttng_buffer_view
*payload
)
1205 struct relay_session
*session
= conn
->session
;
1206 struct relay_stream
*stream
= NULL
;
1207 struct lttcomm_relayd_status_stream reply
;
1208 struct ctf_trace
*trace
= NULL
;
1209 uint64_t stream_handle
= -1ULL;
1210 char *path_name
= NULL
, *channel_name
= NULL
;
1211 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1213 if (!session
|| !conn
->version_check_done
) {
1214 ERR("Trying to add a stream before version check");
1216 goto end_no_session
;
1219 switch (session
->minor
) {
1220 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1221 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1224 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1226 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1227 &channel_name
, &tracefile_size
, &tracefile_count
);
1234 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1238 /* This stream here has one reference on the trace. */
1240 pthread_mutex_lock(&last_relay_stream_id_lock
);
1241 stream_handle
= ++last_relay_stream_id
;
1242 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1244 /* We pass ownership of path_name and channel_name. */
1245 stream
= stream_create(trace
, stream_handle
, path_name
,
1246 channel_name
, tracefile_size
, tracefile_count
);
1248 channel_name
= NULL
;
1251 * Streams are the owners of their trace. Reference to trace is
1252 * kept within stream_create().
1254 ctf_trace_put(trace
);
1257 memset(&reply
, 0, sizeof(reply
));
1258 reply
.handle
= htobe64(stream_handle
);
1260 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1262 reply
.ret_code
= htobe32(LTTNG_OK
);
1265 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1266 sizeof(struct lttcomm_relayd_status_stream
), 0);
1267 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1268 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1280 * relay_close_stream: close a specific stream
1282 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1283 struct relay_connection
*conn
,
1284 const struct lttng_buffer_view
*payload
)
1288 struct relay_session
*session
= conn
->session
;
1289 struct lttcomm_relayd_close_stream stream_info
;
1290 struct lttcomm_relayd_generic_reply reply
;
1291 struct relay_stream
*stream
;
1293 DBG("Close stream received");
1295 if (!session
|| !conn
->version_check_done
) {
1296 ERR("Trying to close a stream before version check");
1298 goto end_no_session
;
1301 if (payload
->size
< sizeof(stream_info
)) {
1302 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1303 sizeof(stream_info
), payload
->size
);
1305 goto end_no_session
;
1307 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1308 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1309 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1311 stream
= stream_get_by_id(stream_info
.stream_id
);
1318 * Set last_net_seq_num before the close flag. Required by data
1321 pthread_mutex_lock(&stream
->lock
);
1322 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1323 pthread_mutex_unlock(&stream
->lock
);
1326 * This is one of the conditions which may trigger a stream close
1327 * with the others being:
1328 * 1) A close command is received for a stream
1329 * 2) The control connection owning the stream is closed
1330 * 3) We have received all of the stream's data _after_ a close
1333 try_stream_close(stream
);
1334 if (stream
->is_metadata
) {
1335 struct relay_viewer_stream
*vstream
;
1337 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1339 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1341 * Since all the metadata has been sent to the
1342 * viewer and that we have a request to close
1343 * its stream, we can safely teardown the
1344 * corresponding metadata viewer stream.
1346 viewer_stream_put(vstream
);
1348 /* Put local reference. */
1349 viewer_stream_put(vstream
);
1356 memset(&reply
, 0, sizeof(reply
));
1358 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1360 reply
.ret_code
= htobe32(LTTNG_OK
);
1362 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1363 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1364 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1365 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1375 * relay_reset_metadata: reset a metadata stream
1378 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1379 struct relay_connection
*conn
,
1380 const struct lttng_buffer_view
*payload
)
1384 struct relay_session
*session
= conn
->session
;
1385 struct lttcomm_relayd_reset_metadata stream_info
;
1386 struct lttcomm_relayd_generic_reply reply
;
1387 struct relay_stream
*stream
;
1389 DBG("Reset metadata received");
1391 if (!session
|| !conn
->version_check_done
) {
1392 ERR("Trying to reset a metadata stream before version check");
1394 goto end_no_session
;
1397 if (payload
->size
< sizeof(stream_info
)) {
1398 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1399 sizeof(stream_info
), payload
->size
);
1401 goto end_no_session
;
1403 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1404 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1405 stream_info
.version
= be64toh(stream_info
.version
);
1407 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1409 /* Unsupported for live sessions for now. */
1410 if (session
->live_timer
!= 0) {
1415 stream
= stream_get_by_id(stream_info
.stream_id
);
1420 pthread_mutex_lock(&stream
->lock
);
1421 if (!stream
->is_metadata
) {
1426 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1427 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1428 &stream
->stream_fd
->fd
);
1430 ERR("Failed to rotate metadata file %s of channel %s",
1431 stream
->path_name
, stream
->channel_name
);
1436 pthread_mutex_unlock(&stream
->lock
);
1440 memset(&reply
, 0, sizeof(reply
));
1442 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1444 reply
.ret_code
= htobe32(LTTNG_OK
);
1446 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1447 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1448 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1449 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1459 * relay_unknown_command: send -1 if received unknown command
1461 static void relay_unknown_command(struct relay_connection
*conn
)
1463 struct lttcomm_relayd_generic_reply reply
;
1466 memset(&reply
, 0, sizeof(reply
));
1467 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1468 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1469 if (send_ret
< sizeof(reply
)) {
1470 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1475 * relay_start: send an acknowledgment to the client to tell if we are
1476 * ready to receive data. We are ready if a session is established.
1478 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1479 struct relay_connection
*conn
,
1480 const struct lttng_buffer_view
*payload
)
1484 struct lttcomm_relayd_generic_reply reply
;
1485 struct relay_session
*session
= conn
->session
;
1488 DBG("Trying to start the streaming without a session established");
1489 ret
= htobe32(LTTNG_ERR_UNK
);
1492 memset(&reply
, 0, sizeof(reply
));
1493 reply
.ret_code
= htobe32(LTTNG_OK
);
1494 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1496 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1497 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1506 * Append padding to the file pointed by the file descriptor fd.
1508 static int write_padding_to_file(int fd
, uint32_t size
)
1517 zeros
= zmalloc(size
);
1518 if (zeros
== NULL
) {
1519 PERROR("zmalloc zeros for padding");
1524 ret
= lttng_write(fd
, zeros
, size
);
1526 PERROR("write padding to file");
1536 * relay_recv_metadata: receive the metadata for the session.
1538 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1539 struct relay_connection
*conn
,
1540 const struct lttng_buffer_view
*payload
)
1544 struct relay_session
*session
= conn
->session
;
1545 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1546 struct relay_stream
*metadata_stream
;
1547 uint64_t metadata_payload_size
;
1550 ERR("Metadata sent before version check");
1555 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1556 ERR("Incorrect data size");
1560 metadata_payload_size
= recv_hdr
->data_size
-
1561 sizeof(struct lttcomm_relayd_metadata_payload
);
1563 memcpy(&metadata_payload_header
, payload
->data
,
1564 sizeof(metadata_payload_header
));
1565 metadata_payload_header
.stream_id
= be64toh(
1566 metadata_payload_header
.stream_id
);
1567 metadata_payload_header
.padding_size
= be32toh(
1568 metadata_payload_header
.padding_size
);
1570 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1571 if (!metadata_stream
) {
1576 pthread_mutex_lock(&metadata_stream
->lock
);
1578 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1579 payload
->data
+ sizeof(metadata_payload_header
),
1580 metadata_payload_size
);
1581 if (size_ret
< metadata_payload_size
) {
1582 ERR("Relay error writing metadata on file");
1587 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1588 metadata_payload_header
.padding_size
);
1589 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1594 metadata_stream
->metadata_received
+=
1595 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1596 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1597 metadata_stream
->metadata_received
);
1600 pthread_mutex_unlock(&metadata_stream
->lock
);
1601 stream_put(metadata_stream
);
1607 * relay_send_version: send relayd version number
1609 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1610 struct relay_connection
*conn
,
1611 const struct lttng_buffer_view
*payload
)
1615 struct lttcomm_relayd_version reply
, msg
;
1616 bool compatible
= true;
1618 conn
->version_check_done
= true;
1620 /* Get version from the other side. */
1621 if (payload
->size
< sizeof(msg
)) {
1622 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1623 sizeof(msg
), payload
->size
);
1628 memcpy(&msg
, payload
->data
, sizeof(msg
));
1629 msg
.major
= be32toh(msg
.major
);
1630 msg
.minor
= be32toh(msg
.minor
);
1632 memset(&reply
, 0, sizeof(reply
));
1633 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1634 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1636 /* Major versions must be the same */
1637 if (reply
.major
!= msg
.major
) {
1638 DBG("Incompatible major versions (%u vs %u), deleting session",
1639 reply
.major
, msg
.major
);
1643 conn
->major
= reply
.major
;
1644 /* We adapt to the lowest compatible version */
1645 if (reply
.minor
<= msg
.minor
) {
1646 conn
->minor
= reply
.minor
;
1648 conn
->minor
= msg
.minor
;
1651 reply
.major
= htobe32(reply
.major
);
1652 reply
.minor
= htobe32(reply
.minor
);
1653 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1655 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1656 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1669 DBG("Version check done using protocol %u.%u", conn
->major
,
1677 * Check for data pending for a given stream id from the session daemon.
1679 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1680 struct relay_connection
*conn
,
1681 const struct lttng_buffer_view
*payload
)
1683 struct relay_session
*session
= conn
->session
;
1684 struct lttcomm_relayd_data_pending msg
;
1685 struct lttcomm_relayd_generic_reply reply
;
1686 struct relay_stream
*stream
;
1690 DBG("Data pending command received");
1692 if (!session
|| !conn
->version_check_done
) {
1693 ERR("Trying to check for data before version check");
1695 goto end_no_session
;
1698 if (payload
->size
< sizeof(msg
)) {
1699 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1700 sizeof(msg
), payload
->size
);
1702 goto end_no_session
;
1704 memcpy(&msg
, payload
->data
, sizeof(msg
));
1705 msg
.stream_id
= be64toh(msg
.stream_id
);
1706 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1708 stream
= stream_get_by_id(msg
.stream_id
);
1709 if (stream
== NULL
) {
1714 pthread_mutex_lock(&stream
->lock
);
1716 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1717 " and last_seq %" PRIu64
, msg
.stream_id
,
1718 stream
->prev_seq
, msg
.last_net_seq_num
);
1720 /* Avoid wrapping issue */
1721 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1722 /* Data has in fact been written and is NOT pending */
1725 /* Data still being streamed thus pending */
1729 stream
->data_pending_check_done
= true;
1730 pthread_mutex_unlock(&stream
->lock
);
1735 memset(&reply
, 0, sizeof(reply
));
1736 reply
.ret_code
= htobe32(ret
);
1737 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1738 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1739 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1749 * Wait for the control socket to reach a quiescent state.
1751 * Note that for now, when receiving this command from the session
1752 * daemon, this means that every subsequent commands or data received on
1753 * the control socket has been handled. So, this is why we simply return
1756 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1757 struct relay_connection
*conn
,
1758 const struct lttng_buffer_view
*payload
)
1762 struct relay_stream
*stream
;
1763 struct lttcomm_relayd_quiescent_control msg
;
1764 struct lttcomm_relayd_generic_reply reply
;
1766 DBG("Checking quiescent state on control socket");
1768 if (!conn
->session
|| !conn
->version_check_done
) {
1769 ERR("Trying to check for data before version check");
1771 goto end_no_session
;
1774 if (payload
->size
< sizeof(msg
)) {
1775 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1776 sizeof(msg
), payload
->size
);
1778 goto end_no_session
;
1780 memcpy(&msg
, payload
->data
, sizeof(msg
));
1781 msg
.stream_id
= be64toh(msg
.stream_id
);
1783 stream
= stream_get_by_id(msg
.stream_id
);
1787 pthread_mutex_lock(&stream
->lock
);
1788 stream
->data_pending_check_done
= true;
1789 pthread_mutex_unlock(&stream
->lock
);
1791 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1794 memset(&reply
, 0, sizeof(reply
));
1795 reply
.ret_code
= htobe32(LTTNG_OK
);
1796 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1797 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1798 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1810 * Initialize a data pending command. This means that a consumer is about
1811 * to ask for data pending for each stream it holds. Simply iterate over
1812 * all streams of a session and set the data_pending_check_done flag.
1814 * This command returns to the client a LTTNG_OK code.
1816 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1817 struct relay_connection
*conn
,
1818 const struct lttng_buffer_view
*payload
)
1822 struct lttng_ht_iter iter
;
1823 struct lttcomm_relayd_begin_data_pending msg
;
1824 struct lttcomm_relayd_generic_reply reply
;
1825 struct relay_stream
*stream
;
1830 DBG("Init streams for data pending");
1832 if (!conn
->session
|| !conn
->version_check_done
) {
1833 ERR("Trying to check for data before version check");
1835 goto end_no_session
;
1838 if (payload
->size
< sizeof(msg
)) {
1839 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1840 sizeof(msg
), payload
->size
);
1842 goto end_no_session
;
1844 memcpy(&msg
, payload
->data
, sizeof(msg
));
1845 msg
.session_id
= be64toh(msg
.session_id
);
1848 * Iterate over all streams to set the begin data pending flag.
1849 * For now, the streams are indexed by stream handle so we have
1850 * to iterate over all streams to find the one associated with
1851 * the right session_id.
1854 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1856 if (!stream_get(stream
)) {
1859 if (stream
->trace
->session
->id
== msg
.session_id
) {
1860 pthread_mutex_lock(&stream
->lock
);
1861 stream
->data_pending_check_done
= false;
1862 pthread_mutex_unlock(&stream
->lock
);
1863 DBG("Set begin data pending flag to stream %" PRIu64
,
1864 stream
->stream_handle
);
1870 memset(&reply
, 0, sizeof(reply
));
1871 /* All good, send back reply. */
1872 reply
.ret_code
= htobe32(LTTNG_OK
);
1874 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1875 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1876 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1888 * End data pending command. This will check, for a given session id, if
1889 * each stream associated with it has its data_pending_check_done flag
1890 * set. If not, this means that the client lost track of the stream but
1891 * the data is still being streamed on our side. In this case, we inform
1892 * the client that data is in flight.
1894 * Return to the client if there is data in flight or not with a ret_code.
1896 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1897 struct relay_connection
*conn
,
1898 const struct lttng_buffer_view
*payload
)
1902 struct lttng_ht_iter iter
;
1903 struct lttcomm_relayd_end_data_pending msg
;
1904 struct lttcomm_relayd_generic_reply reply
;
1905 struct relay_stream
*stream
;
1906 uint32_t is_data_inflight
= 0;
1908 DBG("End data pending command");
1910 if (!conn
->session
|| !conn
->version_check_done
) {
1911 ERR("Trying to check for data before version check");
1913 goto end_no_session
;
1916 if (payload
->size
< sizeof(msg
)) {
1917 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1918 sizeof(msg
), payload
->size
);
1920 goto end_no_session
;
1922 memcpy(&msg
, payload
->data
, sizeof(msg
));
1923 msg
.session_id
= be64toh(msg
.session_id
);
1926 * Iterate over all streams to see if the begin data pending
1930 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1932 if (!stream_get(stream
)) {
1935 if (stream
->trace
->session
->id
!= msg
.session_id
) {
1939 pthread_mutex_lock(&stream
->lock
);
1940 if (!stream
->data_pending_check_done
) {
1941 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1942 is_data_inflight
= 1;
1943 DBG("Data is still in flight for stream %" PRIu64
,
1944 stream
->stream_handle
);
1945 pthread_mutex_unlock(&stream
->lock
);
1950 pthread_mutex_unlock(&stream
->lock
);
1955 memset(&reply
, 0, sizeof(reply
));
1956 /* All good, send back reply. */
1957 reply
.ret_code
= htobe32(is_data_inflight
);
1959 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1960 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1961 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
1973 * Receive an index for a specific stream.
1975 * Return 0 on success else a negative value.
1977 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
1978 struct relay_connection
*conn
,
1979 const struct lttng_buffer_view
*payload
)
1983 struct relay_session
*session
= conn
->session
;
1984 struct lttcomm_relayd_index index_info
;
1985 struct relay_index
*index
;
1986 struct lttcomm_relayd_generic_reply reply
;
1987 struct relay_stream
*stream
;
1992 DBG("Relay receiving index");
1994 if (!session
|| !conn
->version_check_done
) {
1995 ERR("Trying to close a stream before version check");
1997 goto end_no_session
;
2000 msg_len
= lttcomm_relayd_index_len(
2001 lttng_to_index_major(conn
->major
, conn
->minor
),
2002 lttng_to_index_minor(conn
->major
, conn
->minor
));
2003 if (payload
->size
< msg_len
) {
2004 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2005 msg_len
, payload
->size
);
2007 goto end_no_session
;
2009 memcpy(&index_info
, payload
->data
, msg_len
);
2010 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2011 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2012 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2013 index_info
.content_size
= be64toh(index_info
.content_size
);
2014 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2015 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2016 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2017 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2019 if (conn
->minor
>= 8) {
2020 index_info
.stream_instance_id
=
2021 be64toh(index_info
.stream_instance_id
);
2022 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2025 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2027 ERR("stream_get_by_id not found");
2031 pthread_mutex_lock(&stream
->lock
);
2033 /* Live beacon handling */
2034 if (index_info
.packet_size
== 0) {
2035 DBG("Received live beacon for stream %" PRIu64
,
2036 stream
->stream_handle
);
2039 * Only flag a stream inactive when it has already
2040 * received data and no indexes are in flight.
2042 if (stream
->index_received_seqcount
> 0
2043 && stream
->indexes_in_flight
== 0) {
2044 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2047 goto end_stream_put
;
2049 stream
->beacon_ts_end
= -1ULL;
2052 if (stream
->ctf_stream_id
== -1ULL) {
2053 stream
->ctf_stream_id
= index_info
.stream_id
;
2055 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2058 ERR("relay_index_get_by_id_or_create index NULL");
2059 goto end_stream_put
;
2061 if (set_index_control_data(index
, &index_info
, conn
)) {
2062 ERR("set_index_control_data error");
2063 relay_index_put(index
);
2065 goto end_stream_put
;
2067 ret
= relay_index_try_flush(index
);
2069 tracefile_array_commit_seq(stream
->tfa
);
2070 stream
->index_received_seqcount
++;
2071 } else if (ret
> 0) {
2075 ERR("relay_index_try_flush error %d", ret
);
2076 relay_index_put(index
);
2081 pthread_mutex_unlock(&stream
->lock
);
2086 memset(&reply
, 0, sizeof(reply
));
2088 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2090 reply
.ret_code
= htobe32(LTTNG_OK
);
2092 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2093 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2094 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2103 * Receive the streams_sent message.
2105 * Return 0 on success else a negative value.
2107 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2108 struct relay_connection
*conn
,
2109 const struct lttng_buffer_view
*payload
)
2113 struct lttcomm_relayd_generic_reply reply
;
2117 DBG("Relay receiving streams_sent");
2119 if (!conn
->session
|| !conn
->version_check_done
) {
2120 ERR("Trying to close a stream before version check");
2122 goto end_no_session
;
2126 * Publish every pending stream in the connection recv list which are
2127 * now ready to be used by the viewer.
2129 publish_connection_local_streams(conn
);
2131 memset(&reply
, 0, sizeof(reply
));
2132 reply
.ret_code
= htobe32(LTTNG_OK
);
2133 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2134 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2135 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2147 #define DBG_CMD(cmd_name, conn) \
2148 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2150 static int relay_process_control_command(struct relay_connection
*conn
,
2151 const struct lttcomm_relayd_hdr
*header
,
2152 const struct lttng_buffer_view
*payload
)
2156 switch (header
->cmd
) {
2157 case RELAYD_CREATE_SESSION
:
2158 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2159 ret
= relay_create_session(header
, conn
, payload
);
2161 case RELAYD_ADD_STREAM
:
2162 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2163 ret
= relay_add_stream(header
, conn
, payload
);
2165 case RELAYD_START_DATA
:
2166 DBG_CMD("RELAYD_START_DATA", conn
);
2167 ret
= relay_start(header
, conn
, payload
);
2169 case RELAYD_SEND_METADATA
:
2170 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2171 ret
= relay_recv_metadata(header
, conn
, payload
);
2173 case RELAYD_VERSION
:
2174 DBG_CMD("RELAYD_VERSION", conn
);
2175 ret
= relay_send_version(header
, conn
, payload
);
2177 case RELAYD_CLOSE_STREAM
:
2178 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2179 ret
= relay_close_stream(header
, conn
, payload
);
2181 case RELAYD_DATA_PENDING
:
2182 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2183 ret
= relay_data_pending(header
, conn
, payload
);
2185 case RELAYD_QUIESCENT_CONTROL
:
2186 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2187 ret
= relay_quiescent_control(header
, conn
, payload
);
2189 case RELAYD_BEGIN_DATA_PENDING
:
2190 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2191 ret
= relay_begin_data_pending(header
, conn
, payload
);
2193 case RELAYD_END_DATA_PENDING
:
2194 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2195 ret
= relay_end_data_pending(header
, conn
, payload
);
2197 case RELAYD_SEND_INDEX
:
2198 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2199 ret
= relay_recv_index(header
, conn
, payload
);
2201 case RELAYD_STREAMS_SENT
:
2202 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2203 ret
= relay_streams_sent(header
, conn
, payload
);
2205 case RELAYD_RESET_METADATA
:
2206 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2207 ret
= relay_reset_metadata(header
, conn
, payload
);
2209 case RELAYD_UPDATE_SYNC_INFO
:
2211 ERR("Received unknown command (%u)", header
->cmd
);
2212 relay_unknown_command(conn
);
2221 static enum relay_connection_status
relay_process_control_receive_payload(
2222 struct relay_connection
*conn
)
2225 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2226 struct lttng_dynamic_buffer
*reception_buffer
=
2227 &conn
->protocol
.ctrl
.reception_buffer
;
2228 struct ctrl_connection_state_receive_payload
*state
=
2229 &conn
->protocol
.ctrl
.state
.receive_payload
;
2230 struct lttng_buffer_view payload_view
;
2232 if (state
->left_to_receive
== 0) {
2233 /* Short-circuit for payload-less commands. */
2234 goto reception_complete
;
2236 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2237 reception_buffer
->data
+ state
->received
,
2238 state
->left_to_receive
, MSG_DONTWAIT
);
2240 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2241 PERROR("Unable to receive command payload on sock %d",
2243 status
= RELAY_CONNECTION_STATUS_ERROR
;
2246 } else if (ret
== 0) {
2247 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2248 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2253 assert(ret
<= state
->left_to_receive
);
2255 state
->left_to_receive
-= ret
;
2256 state
->received
+= ret
;
2258 if (state
->left_to_receive
> 0) {
2260 * Can't transition to the protocol's next state, wait to
2261 * receive the rest of the header.
2263 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2264 state
->received
, state
->left_to_receive
,
2270 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2271 conn
->sock
->fd
, state
->received
);
2273 * The payload required to process the command has been received.
2274 * A view to the reception buffer is forwarded to the various
2275 * commands and the state of the control is reset on success.
2277 * Commands are responsible for sending their reply to the peer.
2279 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2281 ret
= relay_process_control_command(conn
,
2282 &state
->header
, &payload_view
);
2284 status
= RELAY_CONNECTION_STATUS_ERROR
;
2288 ret
= connection_reset_protocol_state(conn
);
2290 status
= RELAY_CONNECTION_STATUS_ERROR
;
2296 static enum relay_connection_status
relay_process_control_receive_header(
2297 struct relay_connection
*conn
)
2300 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2301 struct lttcomm_relayd_hdr header
;
2302 struct lttng_dynamic_buffer
*reception_buffer
=
2303 &conn
->protocol
.ctrl
.reception_buffer
;
2304 struct ctrl_connection_state_receive_header
*state
=
2305 &conn
->protocol
.ctrl
.state
.receive_header
;
2307 assert(state
->left_to_receive
!= 0);
2309 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2310 reception_buffer
->data
+ state
->received
,
2311 state
->left_to_receive
, MSG_DONTWAIT
);
2313 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2314 PERROR("Unable to receive control command header on sock %d",
2316 status
= RELAY_CONNECTION_STATUS_ERROR
;
2319 } else if (ret
== 0) {
2320 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2321 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2326 assert(ret
<= state
->left_to_receive
);
2328 state
->left_to_receive
-= ret
;
2329 state
->received
+= ret
;
2331 if (state
->left_to_receive
> 0) {
2333 * Can't transition to the protocol's next state, wait to
2334 * receive the rest of the header.
2336 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2337 state
->received
, state
->left_to_receive
,
2342 /* Transition to next state: receiving the command's payload. */
2343 conn
->protocol
.ctrl
.state_id
=
2344 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2345 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2346 header
.circuit_id
= be64toh(header
.circuit_id
);
2347 header
.data_size
= be64toh(header
.data_size
);
2348 header
.cmd
= be32toh(header
.cmd
);
2349 header
.cmd_version
= be32toh(header
.cmd_version
);
2350 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2351 &header
, sizeof(header
));
2353 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2354 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2357 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2358 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2360 status
= RELAY_CONNECTION_STATUS_ERROR
;
2364 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2366 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2367 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2370 status
= RELAY_CONNECTION_STATUS_ERROR
;
2374 if (header
.data_size
== 0) {
2376 * Manually invoke the next state as the poll loop
2377 * will not wake-up to allow us to proceed further.
2379 status
= relay_process_control_receive_payload(conn
);
2386 * Process the commands received on the control socket
2388 static enum relay_connection_status
relay_process_control(
2389 struct relay_connection
*conn
)
2391 enum relay_connection_status status
;
2393 switch (conn
->protocol
.ctrl
.state_id
) {
2394 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2395 status
= relay_process_control_receive_header(conn
);
2397 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2398 status
= relay_process_control_receive_payload(conn
);
2401 ERR("Unknown control connection protocol state encountered.");
2409 * Handle index for a data stream.
2411 * Called with the stream lock held.
2413 * Return 0 on success else a negative value.
2415 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2419 uint64_t data_offset
;
2420 struct relay_index
*index
;
2422 /* Get data offset because we are about to update the index. */
2423 data_offset
= htobe64(stream
->tracefile_size_current
);
2425 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2426 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2429 * Lookup for an existing index for that stream id/sequence
2430 * number. If it exists, the control thread has already received the
2431 * data for it, thus we need to write it to disk.
2433 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2439 if (rotate_index
|| !stream
->index_file
) {
2440 uint32_t major
, minor
;
2442 /* Put ref on previous index_file. */
2443 if (stream
->index_file
) {
2444 lttng_index_file_put(stream
->index_file
);
2445 stream
->index_file
= NULL
;
2447 major
= stream
->trace
->session
->major
;
2448 minor
= stream
->trace
->session
->minor
;
2449 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2450 stream
->channel_name
,
2451 -1, -1, stream
->tracefile_size
,
2452 tracefile_array_get_file_index_head(stream
->tfa
),
2453 lttng_to_index_major(major
, minor
),
2454 lttng_to_index_minor(major
, minor
));
2455 if (!stream
->index_file
) {
2457 /* Put self-ref for this index due to error. */
2458 relay_index_put(index
);
2464 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2466 /* Put self-ref for this index due to error. */
2467 relay_index_put(index
);
2472 ret
= relay_index_try_flush(index
);
2474 tracefile_array_commit_seq(stream
->tfa
);
2475 stream
->index_received_seqcount
++;
2476 } else if (ret
> 0) {
2480 /* Put self-ref for this index due to error. */
2481 relay_index_put(index
);
2489 static enum relay_connection_status
relay_process_data_receive_header(
2490 struct relay_connection
*conn
)
2493 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2494 struct data_connection_state_receive_header
*state
=
2495 &conn
->protocol
.data
.state
.receive_header
;
2496 struct lttcomm_relayd_data_hdr header
;
2497 struct relay_stream
*stream
;
2499 assert(state
->left_to_receive
!= 0);
2501 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2502 state
->header_reception_buffer
+ state
->received
,
2503 state
->left_to_receive
, MSG_DONTWAIT
);
2505 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2506 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2507 status
= RELAY_CONNECTION_STATUS_ERROR
;
2510 } else if (ret
== 0) {
2511 /* Orderly shutdown. Not necessary to print an error. */
2512 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2513 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2518 assert(ret
<= state
->left_to_receive
);
2520 state
->left_to_receive
-= ret
;
2521 state
->received
+= ret
;
2523 if (state
->left_to_receive
> 0) {
2525 * Can't transition to the protocol's next state, wait to
2526 * receive the rest of the header.
2528 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2529 state
->received
, state
->left_to_receive
,
2535 /* Transition to next state: receiving the payload. */
2536 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2538 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2539 header
.circuit_id
= be64toh(header
.circuit_id
);
2540 header
.stream_id
= be64toh(header
.stream_id
);
2541 header
.data_size
= be32toh(header
.data_size
);
2542 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2543 header
.padding_size
= be32toh(header
.padding_size
);
2544 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2546 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2548 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2549 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2551 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2552 conn
->sock
->fd
, header
.circuit_id
,
2553 header
.stream_id
, header
.data_size
,
2554 header
.net_seq_num
, header
.padding_size
);
2556 stream
= stream_get_by_id(header
.stream_id
);
2558 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2560 /* Protocol error. */
2561 status
= RELAY_CONNECTION_STATUS_ERROR
;
2565 pthread_mutex_lock(&stream
->lock
);
2567 /* Check if a rotation is needed. */
2568 if (stream
->tracefile_size
> 0 &&
2569 (stream
->tracefile_size_current
+ header
.data_size
) >
2570 stream
->tracefile_size
) {
2571 uint64_t old_id
, new_id
;
2573 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2574 tracefile_array_file_rotate(stream
->tfa
);
2576 /* new_id is updated by utils_rotate_stream_file. */
2579 ret
= utils_rotate_stream_file(stream
->path_name
,
2580 stream
->channel_name
, stream
->tracefile_size
,
2581 stream
->tracefile_count
, -1,
2582 -1, stream
->stream_fd
->fd
,
2583 &new_id
, &stream
->stream_fd
->fd
);
2585 ERR("Failed to rotate stream output file");
2586 status
= RELAY_CONNECTION_STATUS_ERROR
;
2587 goto end_stream_unlock
;
2591 * Reset current size because we just performed a stream
2594 stream
->tracefile_size_current
= 0;
2595 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2600 pthread_mutex_unlock(&stream
->lock
);
2606 static enum relay_connection_status
relay_process_data_receive_payload(
2607 struct relay_connection
*conn
)
2610 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2611 struct relay_stream
*stream
;
2612 struct data_connection_state_receive_payload
*state
=
2613 &conn
->protocol
.data
.state
.receive_payload
;
2614 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2615 char data_buffer
[chunk_size
];
2616 bool partial_recv
= false;
2617 bool new_stream
= false, close_requested
= false;
2618 uint64_t left_to_receive
= state
->left_to_receive
;
2619 struct relay_session
*session
;
2621 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2622 state
->header
.stream_id
, state
->header
.net_seq_num
,
2623 state
->received
, left_to_receive
);
2625 stream
= stream_get_by_id(state
->header
.stream_id
);
2627 /* Protocol error. */
2628 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2629 state
->header
.stream_id
);
2630 status
= RELAY_CONNECTION_STATUS_ERROR
;
2634 pthread_mutex_lock(&stream
->lock
);
2635 session
= stream
->trace
->session
;
2636 if (!conn
->session
) {
2637 ret
= connection_set_session(conn
, session
);
2639 status
= RELAY_CONNECTION_STATUS_ERROR
;
2640 goto end_stream_unlock
;
2645 * The size of the "chunk" received on any iteration is bounded by:
2646 * - the data left to receive,
2647 * - the data immediately available on the socket,
2648 * - the on-stack data buffer
2650 while (left_to_receive
> 0 && !partial_recv
) {
2652 size_t recv_size
= min(left_to_receive
, chunk_size
);
2654 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2655 recv_size
, MSG_DONTWAIT
);
2657 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2658 PERROR("Socket %d error", conn
->sock
->fd
);
2659 status
= RELAY_CONNECTION_STATUS_ERROR
;
2661 goto end_stream_unlock
;
2662 } else if (ret
== 0) {
2663 /* No more data ready to be consumed on socket. */
2664 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2665 state
->header
.stream_id
);
2666 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2668 } else if (ret
< (int) recv_size
) {
2670 * All the data available on the socket has been
2673 partial_recv
= true;
2678 /* Write data to stream output fd. */
2679 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2681 if (write_ret
< (ssize_t
) recv_size
) {
2682 ERR("Relay error writing data to file");
2683 status
= RELAY_CONNECTION_STATUS_ERROR
;
2684 goto end_stream_unlock
;
2687 left_to_receive
-= recv_size
;
2688 state
->received
+= recv_size
;
2689 state
->left_to_receive
= left_to_receive
;
2691 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2692 write_ret
, stream
->stream_handle
);
2695 if (state
->left_to_receive
> 0) {
2697 * Did not receive all the data expected, wait for more data to
2698 * become available on the socket.
2700 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2701 state
->header
.stream_id
, state
->received
,
2702 state
->left_to_receive
);
2703 goto end_stream_unlock
;
2706 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2707 state
->header
.padding_size
);
2708 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2709 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2710 stream
->stream_handle
,
2711 state
->header
.net_seq_num
, ret
);
2712 status
= RELAY_CONNECTION_STATUS_ERROR
;
2713 goto end_stream_unlock
;
2717 if (session
->minor
>= 4 && !session
->snapshot
) {
2718 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2719 state
->rotate_index
);
2721 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2722 stream
->stream_handle
,
2723 state
->header
.net_seq_num
, ret
);
2724 status
= RELAY_CONNECTION_STATUS_ERROR
;
2725 goto end_stream_unlock
;
2729 stream
->tracefile_size_current
+= state
->header
.data_size
+
2730 state
->header
.padding_size
;
2732 if (stream
->prev_seq
== -1ULL) {
2736 stream
->prev_seq
= state
->header
.net_seq_num
;
2739 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2740 * contents of *state which are aliased (union) to the same location as
2741 * the new state. Don't use it beyond this point.
2743 connection_reset_protocol_state(conn
);
2747 close_requested
= stream
->close_requested
;
2748 pthread_mutex_unlock(&stream
->lock
);
2749 if (close_requested
&& left_to_receive
== 0) {
2750 try_stream_close(stream
);
2754 pthread_mutex_lock(&session
->lock
);
2755 uatomic_set(&session
->new_streams
, 1);
2756 pthread_mutex_unlock(&session
->lock
);
2765 * relay_process_data: Process the data received on the data socket
2767 static enum relay_connection_status
relay_process_data(
2768 struct relay_connection
*conn
)
2770 enum relay_connection_status status
;
2772 switch (conn
->protocol
.data
.state_id
) {
2773 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2774 status
= relay_process_data_receive_header(conn
);
2776 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2777 status
= relay_process_data_receive_payload(conn
);
2780 ERR("Unexpected data connection communication state.");
2787 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2791 (void) lttng_poll_del(events
, pollfd
);
2793 ret
= close(pollfd
);
2795 ERR("Closing pollfd %d", pollfd
);
2799 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2800 int pollfd
, struct relay_connection
*conn
)
2802 const char *type_str
;
2804 switch (conn
->type
) {
2809 type_str
= "Control";
2811 case RELAY_VIEWER_COMMAND
:
2812 type_str
= "Viewer Command";
2814 case RELAY_VIEWER_NOTIFICATION
:
2815 type_str
= "Viewer Notification";
2818 type_str
= "Unknown";
2820 cleanup_connection_pollfd(events
, pollfd
);
2821 connection_put(conn
);
2822 DBG("%s connection closed with %d", type_str
, pollfd
);
2826 * This thread does the actual work
2828 static void *relay_thread_worker(void *data
)
2830 int ret
, err
= -1, last_seen_data_fd
= -1;
2832 struct lttng_poll_event events
;
2833 struct lttng_ht
*relay_connections_ht
;
2834 struct lttng_ht_iter iter
;
2835 struct relay_connection
*destroy_conn
= NULL
;
2837 DBG("[thread] Relay worker started");
2839 rcu_register_thread();
2841 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2843 if (testpoint(relayd_thread_worker
)) {
2844 goto error_testpoint
;
2847 health_code_update();
2849 /* table of connections indexed on socket */
2850 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2851 if (!relay_connections_ht
) {
2852 goto relay_connections_ht_error
;
2855 ret
= create_thread_poll_set(&events
, 2);
2857 goto error_poll_create
;
2860 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2867 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2869 health_code_update();
2871 /* Infinite blocking call, waiting for transmission */
2872 DBG3("Relayd worker thread polling...");
2873 health_poll_entry();
2874 ret
= lttng_poll_wait(&events
, -1);
2878 * Restart interrupted system call.
2880 if (errno
== EINTR
) {
2889 * Process control. The control connection is
2890 * prioritized so we don't starve it with high
2891 * throughput tracing data on the data connection.
2893 for (i
= 0; i
< nb_fd
; i
++) {
2894 /* Fetch once the poll data */
2895 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2896 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2898 health_code_update();
2902 * No activity for this FD (poll
2908 /* Thread quit pipe has been closed. Killing thread. */
2909 ret
= check_thread_quit_pipe(pollfd
, revents
);
2915 /* Inspect the relay conn pipe for new connection */
2916 if (pollfd
== relay_conn_pipe
[0]) {
2917 if (revents
& LPOLLIN
) {
2918 struct relay_connection
*conn
;
2920 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2924 lttng_poll_add(&events
, conn
->sock
->fd
,
2925 LPOLLIN
| LPOLLRDHUP
);
2926 connection_ht_add(relay_connections_ht
, conn
);
2927 DBG("Connection socket %d added", conn
->sock
->fd
);
2928 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2929 ERR("Relay connection pipe error");
2932 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2936 struct relay_connection
*ctrl_conn
;
2938 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2939 /* If not found, there is a synchronization issue. */
2942 if (ctrl_conn
->type
== RELAY_DATA
) {
2943 if (revents
& LPOLLIN
) {
2945 * Flag the last seen data fd not deleted. It will be
2946 * used as the last seen fd if any fd gets deleted in
2949 last_notdel_data_fd
= pollfd
;
2951 goto put_ctrl_connection
;
2953 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2955 if (revents
& LPOLLIN
) {
2956 enum relay_connection_status status
;
2958 status
= relay_process_control(ctrl_conn
);
2959 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
2961 * On socket error flag the session as aborted to force
2962 * the cleanup of its stream otherwise it can leak
2963 * during the lifetime of the relayd.
2965 * This prevents situations in which streams can be
2966 * left opened because an index was received, the
2967 * control connection is closed, and the data
2968 * connection is closed (uncleanly) before the packet's
2971 * Since the control connection encountered an error,
2972 * it is okay to be conservative and close the
2973 * session right now as we can't rely on the protocol
2974 * being respected anymore.
2976 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
2977 session_abort(ctrl_conn
->session
);
2980 /* Clear the connection on error or close. */
2981 relay_thread_close_connection(&events
,
2986 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2987 relay_thread_close_connection(&events
,
2989 if (last_seen_data_fd
== pollfd
) {
2990 last_seen_data_fd
= last_notdel_data_fd
;
2993 ERR("Unexpected poll events %u for control sock %d",
2995 connection_put(ctrl_conn
);
2998 put_ctrl_connection
:
2999 connection_put(ctrl_conn
);
3004 * The last loop handled a control request, go back to poll to make
3005 * sure we prioritise the control socket.
3011 if (last_seen_data_fd
>= 0) {
3012 for (i
= 0; i
< nb_fd
; i
++) {
3013 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3015 health_code_update();
3017 if (last_seen_data_fd
== pollfd
) {
3024 /* Process data connection. */
3025 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3026 /* Fetch the poll data. */
3027 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3028 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3029 struct relay_connection
*data_conn
;
3031 health_code_update();
3034 /* No activity for this FD (poll implementation). */
3038 /* Skip the command pipe. It's handled in the first loop. */
3039 if (pollfd
== relay_conn_pipe
[0]) {
3043 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3045 /* Skip it. Might be removed before. */
3048 if (data_conn
->type
== RELAY_CONTROL
) {
3049 goto put_data_connection
;
3051 assert(data_conn
->type
== RELAY_DATA
);
3053 if (revents
& LPOLLIN
) {
3054 enum relay_connection_status status
;
3056 status
= relay_process_data(data_conn
);
3057 /* Connection closed or error. */
3058 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3060 * On socket error flag the session as aborted to force
3061 * the cleanup of its stream otherwise it can leak
3062 * during the lifetime of the relayd.
3064 * This prevents situations in which streams can be
3065 * left opened because an index was received, the
3066 * control connection is closed, and the data
3067 * connection is closed (uncleanly) before the packet's
3070 * Since the data connection encountered an error,
3071 * it is okay to be conservative and close the
3072 * session right now as we can't rely on the protocol
3073 * being respected anymore.
3075 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3076 session_abort(data_conn
->session
);
3078 relay_thread_close_connection(&events
, pollfd
,
3081 * Every goto restart call sets the last seen fd where
3082 * here we don't really care since we gracefully
3083 * continue the loop after the connection is deleted.
3086 /* Keep last seen port. */
3087 last_seen_data_fd
= pollfd
;
3088 connection_put(data_conn
);
3091 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3092 relay_thread_close_connection(&events
, pollfd
,
3095 ERR("Unknown poll events %u for data sock %d",
3098 put_data_connection
:
3099 connection_put(data_conn
);
3101 last_seen_data_fd
= -1;
3104 /* Normal exit, no error */
3109 /* Cleanup reamaining connection object. */
3111 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3114 health_code_update();
3116 session_abort(destroy_conn
->session
);
3119 * No need to grab another ref, because we own
3122 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3127 lttng_poll_clean(&events
);
3129 lttng_ht_destroy(relay_connections_ht
);
3130 relay_connections_ht_error
:
3131 /* Close relay conn pipes */
3132 utils_close_pipe(relay_conn_pipe
);
3134 DBG("Thread exited with error");
3136 DBG("Worker thread cleanup complete");
3140 ERR("Health error occurred in %s", __func__
);
3142 health_unregister(health_relayd
);
3143 rcu_unregister_thread();
3144 lttng_relay_stop_threads();
3149 * Create the relay command pipe to wake thread_manage_apps.
3150 * Closed in cleanup().
3152 static int create_relay_conn_pipe(void)
3156 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3164 int main(int argc
, char **argv
)
3166 int ret
= 0, retval
= 0;
3169 /* Parse environment variables */
3170 parse_env_options();
3174 * Command line arguments overwrite environment.
3177 if (set_options(argc
, argv
)) {
3182 if (set_signal_handler()) {
3187 /* Try to create directory if -o, --output is specified. */
3188 if (opt_output_path
) {
3189 if (*opt_output_path
!= '/') {
3190 ERR("Please specify an absolute path for -o, --output PATH");
3195 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3198 ERR("Unable to create %s", opt_output_path
);
3205 if (opt_daemon
|| opt_background
) {
3208 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3216 * We are in the child. Make sure all other file
3217 * descriptors are closed, in case we are called with
3218 * more opened file descriptors than the standard ones.
3220 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3226 if (opt_working_directory
) {
3227 ret
= utils_change_working_dir(opt_working_directory
);
3229 ERR("Changing working directory");
3234 /* Initialize thread health monitoring */
3235 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3236 if (!health_relayd
) {
3237 PERROR("health_app_create error");
3239 goto exit_health_app_create
;
3242 /* Create thread quit pipe */
3243 if (init_thread_quit_pipe()) {
3245 goto exit_init_data
;
3248 /* Setup the thread apps communication pipe. */
3249 if (create_relay_conn_pipe()) {
3251 goto exit_init_data
;
3254 /* Init relay command queue. */
3255 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3257 /* Initialize communication library */
3259 lttcomm_inet_init();
3261 /* tables of sessions indexed by session ID */
3262 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3265 goto exit_init_data
;
3268 /* tables of streams indexed by stream ID */
3269 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3270 if (!relay_streams_ht
) {
3272 goto exit_init_data
;
3275 /* tables of streams indexed by stream ID */
3276 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3277 if (!viewer_streams_ht
) {
3279 goto exit_init_data
;
3282 ret
= utils_create_pipe(health_quit_pipe
);
3285 goto exit_health_quit_pipe
;
3288 /* Create thread to manage the client socket */
3289 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3290 thread_manage_health
, (void *) NULL
);
3293 PERROR("pthread_create health");
3295 goto exit_health_thread
;
3298 /* Setup the dispatcher thread */
3299 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3300 relay_thread_dispatcher
, (void *) NULL
);
3303 PERROR("pthread_create dispatcher");
3305 goto exit_dispatcher_thread
;
3308 /* Setup the worker thread */
3309 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3310 relay_thread_worker
, NULL
);
3313 PERROR("pthread_create worker");
3315 goto exit_worker_thread
;
3318 /* Setup the listener thread */
3319 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3320 relay_thread_listener
, (void *) NULL
);
3323 PERROR("pthread_create listener");
3325 goto exit_listener_thread
;
3328 ret
= relayd_live_create(live_uri
);
3330 ERR("Starting live viewer threads");
3336 * This is where we start awaiting program completion (e.g. through
3337 * signal that asks threads to teardown).
3340 ret
= relayd_live_join();
3346 ret
= pthread_join(listener_thread
, &status
);
3349 PERROR("pthread_join listener_thread");
3353 exit_listener_thread
:
3354 ret
= pthread_join(worker_thread
, &status
);
3357 PERROR("pthread_join worker_thread");
3362 ret
= pthread_join(dispatcher_thread
, &status
);
3365 PERROR("pthread_join dispatcher_thread");
3368 exit_dispatcher_thread
:
3370 ret
= pthread_join(health_thread
, &status
);
3373 PERROR("pthread_join health_thread");
3378 utils_close_pipe(health_quit_pipe
);
3379 exit_health_quit_pipe
:
3382 health_app_destroy(health_relayd
);
3383 exit_health_app_create
:
3386 * Wait for all pending call_rcu work to complete before tearing
3387 * down data structures. call_rcu worker may be trying to
3388 * perform lookups in those structures.
3393 /* Ensure all prior call_rcu are done. */