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
;
88 int opt_group_output_by_session
;
89 int opt_group_output_by_host
;
92 * We need to wait for listener and live listener threads, as well as
93 * health check thread, before being ready to signal readiness.
95 #define NR_LTTNG_RELAY_READY 3
96 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
98 /* Size of receive buffer. */
99 #define RECV_DATA_BUFFER_SIZE 65536
101 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
102 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
104 static struct lttng_uri
*control_uri
;
105 static struct lttng_uri
*data_uri
;
106 static struct lttng_uri
*live_uri
;
108 const char *progname
;
110 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
111 static int tracing_group_name_override
;
113 const char * const config_section_name
= "relayd";
116 * Quit pipe for all threads. This permits a single cancellation point
117 * for all threads when receiving an event on the pipe.
119 int thread_quit_pipe
[2] = { -1, -1 };
122 * This pipe is used to inform the worker thread that a command is queued and
123 * ready to be processed.
125 static int relay_conn_pipe
[2] = { -1, -1 };
127 /* Shared between threads */
128 static int dispatch_thread_exit
;
130 static pthread_t listener_thread
;
131 static pthread_t dispatcher_thread
;
132 static pthread_t worker_thread
;
133 static pthread_t health_thread
;
136 * last_relay_stream_id_lock protects last_relay_stream_id increment
137 * atomicity on 32-bit architectures.
139 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
140 static uint64_t last_relay_stream_id
;
143 * Relay command queue.
145 * The relay_thread_listener and relay_thread_dispatcher communicate with this
148 static struct relay_conn_queue relay_conn_queue
;
150 /* Global relay stream hash table. */
151 struct lttng_ht
*relay_streams_ht
;
153 /* Global relay viewer stream hash table. */
154 struct lttng_ht
*viewer_streams_ht
;
156 /* Global relay sessions hash table. */
157 struct lttng_ht
*sessions_ht
;
159 /* Relayd health monitoring */
160 struct health_app
*health_relayd
;
162 static struct option long_options
[] = {
163 { "control-port", 1, 0, 'C', },
164 { "data-port", 1, 0, 'D', },
165 { "live-port", 1, 0, 'L', },
166 { "daemonize", 0, 0, 'd', },
167 { "background", 0, 0, 'b', },
168 { "group", 1, 0, 'g', },
169 { "help", 0, 0, 'h', },
170 { "output", 1, 0, 'o', },
171 { "verbose", 0, 0, 'v', },
172 { "config", 1, 0, 'f' },
173 { "version", 0, 0, 'V' },
174 { "working-directory", 1, 0, 'w', },
175 { "group-output-by-session", 0, 0, 's', },
176 { "group-output-by-host", 0, 0, 'p', },
180 static const char *config_ignore_options
[] = { "help", "config", "version" };
183 * Take an option from the getopt output and set it in the right variable to be
186 * Return 0 on success else a negative value.
188 static int set_option(int opt
, const char *arg
, const char *optname
)
194 fprintf(stderr
, "option %s", optname
);
196 fprintf(stderr
, " with arg %s\n", arg
);
200 if (lttng_is_setuid_setgid()) {
201 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
202 "-C, --control-port");
204 ret
= uri_parse(arg
, &control_uri
);
206 ERR("Invalid control URI specified");
209 if (control_uri
->port
== 0) {
210 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
215 if (lttng_is_setuid_setgid()) {
216 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
219 ret
= uri_parse(arg
, &data_uri
);
221 ERR("Invalid data URI specified");
224 if (data_uri
->port
== 0) {
225 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
230 if (lttng_is_setuid_setgid()) {
231 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
234 ret
= uri_parse(arg
, &live_uri
);
236 ERR("Invalid live URI specified");
239 if (live_uri
->port
== 0) {
240 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
251 if (lttng_is_setuid_setgid()) {
252 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
255 tracing_group_name
= strdup(arg
);
256 if (tracing_group_name
== NULL
) {
261 tracing_group_name_override
= 1;
265 ret
= utils_show_man_page(8, "lttng-relayd");
267 ERR("Cannot view man page lttng-relayd(8)");
272 fprintf(stdout
, "%s\n", VERSION
);
275 if (lttng_is_setuid_setgid()) {
276 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
279 ret
= asprintf(&opt_output_path
, "%s", arg
);
282 PERROR("asprintf opt_output_path");
288 if (lttng_is_setuid_setgid()) {
289 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
290 "-w, --working-directory");
292 ret
= asprintf(&opt_working_directory
, "%s", arg
);
295 PERROR("asprintf working_directory");
302 /* Verbose level can increase using multiple -v */
304 lttng_opt_verbose
= config_parse_value(arg
);
306 /* Only 3 level of verbosity (-vvv). */
307 if (lttng_opt_verbose
< 3) {
308 lttng_opt_verbose
+= 1;
313 if (opt_group_output_by_host
) {
314 ERR("Cannot set --group-output-by-session, --group-output-by-host already defined");
317 opt_group_output_by_session
= 1;
320 if (opt_group_output_by_session
) {
321 ERR("Cannot set --group-output-by-host, --group-output-by-session already defined");
324 opt_group_output_by_host
= 1;
327 /* Unknown option or other error.
328 * Error is printed by getopt, just return */
341 * config_entry_handler_cb used to handle options read from a config file.
342 * See config_entry_handler_cb comment in common/config/session-config.h for the
343 * return value conventions.
345 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
349 if (!entry
|| !entry
->name
|| !entry
->value
) {
354 /* Check if the option is to be ignored */
355 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
356 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
361 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
362 /* Ignore if entry name is not fully matched. */
363 if (strcmp(entry
->name
, long_options
[i
].name
)) {
368 * If the option takes no argument on the command line,
369 * we have to check if the value is "true". We support
370 * non-zero numeric values, true, on and yes.
372 if (!long_options
[i
].has_arg
) {
373 ret
= config_parse_value(entry
->value
);
376 WARN("Invalid configuration value \"%s\" for option %s",
377 entry
->value
, entry
->name
);
379 /* False, skip boolean config option. */
384 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
388 WARN("Unrecognized option \"%s\" in daemon configuration file.",
395 static void parse_env_options(void)
399 value
= lttng_secure_getenv(DEFAULT_LTTNG_RELAYD_WORKING_DIRECTORY_ENV
);
401 opt_working_directory
= value
;
405 static int set_options(int argc
, char **argv
)
407 int c
, ret
= 0, option_index
= 0, retval
= 0;
408 int orig_optopt
= optopt
, orig_optind
= optind
;
409 char *default_address
, *optstring
;
410 const char *config_path
= NULL
;
412 optstring
= utils_generate_optstring(long_options
,
413 sizeof(long_options
) / sizeof(struct option
));
419 /* Check for the --config option */
421 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
422 &option_index
)) != -1) {
426 } else if (c
!= 'f') {
430 if (lttng_is_setuid_setgid()) {
431 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
434 config_path
= utils_expand_path(optarg
);
436 ERR("Failed to resolve path: %s", optarg
);
441 ret
= config_get_section_entries(config_path
, config_section_name
,
442 config_entry_handler
, NULL
);
445 ERR("Invalid configuration option at line %i", ret
);
451 /* Reset getopt's global state */
452 optopt
= orig_optopt
;
453 optind
= orig_optind
;
455 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
460 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
467 /* assign default values */
468 if (control_uri
== NULL
) {
469 ret
= asprintf(&default_address
,
470 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
471 DEFAULT_NETWORK_CONTROL_PORT
);
473 PERROR("asprintf default data address");
478 ret
= uri_parse(default_address
, &control_uri
);
479 free(default_address
);
481 ERR("Invalid control URI specified");
486 if (data_uri
== NULL
) {
487 ret
= asprintf(&default_address
,
488 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
489 DEFAULT_NETWORK_DATA_PORT
);
491 PERROR("asprintf default data address");
496 ret
= uri_parse(default_address
, &data_uri
);
497 free(default_address
);
499 ERR("Invalid data URI specified");
504 if (live_uri
== NULL
) {
505 ret
= asprintf(&default_address
,
506 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
507 DEFAULT_NETWORK_VIEWER_PORT
);
509 PERROR("asprintf default viewer control address");
514 ret
= uri_parse(default_address
, &live_uri
);
515 free(default_address
);
517 ERR("Invalid viewer control URI specified");
523 if (!opt_group_output_by_session
&& !opt_group_output_by_host
) {
524 /* Group by host by default */
525 opt_group_output_by_host
= 1;
533 static void print_global_objects(void)
535 rcu_register_thread();
537 print_viewer_streams();
538 print_relay_streams();
541 rcu_unregister_thread();
547 static void relayd_cleanup(void)
549 print_global_objects();
553 if (viewer_streams_ht
)
554 lttng_ht_destroy(viewer_streams_ht
);
555 if (relay_streams_ht
)
556 lttng_ht_destroy(relay_streams_ht
);
558 lttng_ht_destroy(sessions_ht
);
560 /* free the dynamically allocated opt_output_path */
561 free(opt_output_path
);
563 /* Close thread quit pipes */
564 utils_close_pipe(thread_quit_pipe
);
566 uri_free(control_uri
);
568 /* Live URI is freed in the live thread. */
570 if (tracing_group_name_override
) {
571 free((void *) tracing_group_name
);
576 * Write to writable pipe used to notify a thread.
578 static int notify_thread_pipe(int wpipe
)
582 ret
= lttng_write(wpipe
, "!", 1);
584 PERROR("write poll pipe");
592 static int notify_health_quit_pipe(int *pipe
)
596 ret
= lttng_write(pipe
[1], "4", 1);
598 PERROR("write relay health quit");
607 * Stop all relayd and relayd-live threads.
609 int lttng_relay_stop_threads(void)
613 /* Stopping all threads */
614 DBG("Terminating all threads");
615 if (notify_thread_pipe(thread_quit_pipe
[1])) {
616 ERR("write error on thread quit pipe");
620 if (notify_health_quit_pipe(health_quit_pipe
)) {
621 ERR("write error on health quit pipe");
624 /* Dispatch thread */
625 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
626 futex_nto1_wake(&relay_conn_queue
.futex
);
628 if (relayd_live_stop()) {
629 ERR("Error stopping live threads");
636 * Signal handler for the daemon
638 * Simply stop all worker threads, leaving main() return gracefully after
639 * joining all threads and calling cleanup().
641 static void sighandler(int sig
)
645 DBG("SIGINT caught");
646 if (lttng_relay_stop_threads()) {
647 ERR("Error stopping threads");
651 DBG("SIGTERM caught");
652 if (lttng_relay_stop_threads()) {
653 ERR("Error stopping threads");
657 CMM_STORE_SHARED(recv_child_signal
, 1);
665 * Setup signal handler for :
666 * SIGINT, SIGTERM, SIGPIPE
668 static int set_signal_handler(void)
674 if ((ret
= sigemptyset(&sigset
)) < 0) {
675 PERROR("sigemptyset");
682 sa
.sa_handler
= sighandler
;
683 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
688 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
693 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
698 sa
.sa_handler
= SIG_IGN
;
699 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
704 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
709 void lttng_relay_notify_ready(void)
711 /* Notify the parent of the fork() process that we are ready. */
712 if (opt_daemon
|| opt_background
) {
713 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
714 kill(child_ppid
, SIGUSR1
);
720 * Init thread quit pipe.
722 * Return -1 on error or 0 if all pipes are created.
724 static int init_thread_quit_pipe(void)
728 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
734 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
736 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
740 if (events
== NULL
|| size
== 0) {
745 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
751 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
763 * Check if the thread quit pipe was triggered.
765 * Return 1 if it was triggered else 0;
767 static int check_thread_quit_pipe(int fd
, uint32_t events
)
769 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
777 * Create and init socket from uri.
779 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
782 struct lttcomm_sock
*sock
= NULL
;
784 sock
= lttcomm_alloc_sock_from_uri(uri
);
786 ERR("Allocating socket");
790 ret
= lttcomm_create_sock(sock
);
794 DBG("Listening on sock %d", sock
->fd
);
796 ret
= sock
->ops
->bind(sock
);
801 ret
= sock
->ops
->listen(sock
, -1);
811 lttcomm_destroy_sock(sock
);
817 * This thread manages the listening for new connections on the network
819 static void *relay_thread_listener(void *data
)
821 int i
, ret
, pollfd
, err
= -1;
822 uint32_t revents
, nb_fd
;
823 struct lttng_poll_event events
;
824 struct lttcomm_sock
*control_sock
, *data_sock
;
826 DBG("[thread] Relay listener started");
828 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
830 health_code_update();
832 control_sock
= relay_socket_create(control_uri
);
834 goto error_sock_control
;
837 data_sock
= relay_socket_create(data_uri
);
839 goto error_sock_relay
;
843 * Pass 3 as size here for the thread quit pipe, control and
846 ret
= create_thread_poll_set(&events
, 3);
848 goto error_create_poll
;
851 /* Add the control socket */
852 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
857 /* Add the data socket */
858 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
863 lttng_relay_notify_ready();
865 if (testpoint(relayd_thread_listener
)) {
866 goto error_testpoint
;
870 health_code_update();
872 DBG("Listener accepting connections");
876 ret
= lttng_poll_wait(&events
, -1);
880 * Restart interrupted system call.
882 if (errno
== EINTR
) {
890 DBG("Relay new connection received");
891 for (i
= 0; i
< nb_fd
; i
++) {
892 health_code_update();
894 /* Fetch once the poll data */
895 revents
= LTTNG_POLL_GETEV(&events
, i
);
896 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
900 * No activity for this FD (poll
906 /* Thread quit pipe has been closed. Killing thread. */
907 ret
= check_thread_quit_pipe(pollfd
, revents
);
913 if (revents
& LPOLLIN
) {
915 * A new connection is requested, therefore a
916 * sessiond/consumerd connection is allocated in
917 * this thread, enqueued to a global queue and
918 * dequeued (and freed) in the worker thread.
921 struct relay_connection
*new_conn
;
922 struct lttcomm_sock
*newsock
;
923 enum connection_type type
;
925 if (pollfd
== data_sock
->fd
) {
927 newsock
= data_sock
->ops
->accept(data_sock
);
928 DBG("Relay data connection accepted, socket %d",
931 assert(pollfd
== control_sock
->fd
);
932 type
= RELAY_CONTROL
;
933 newsock
= control_sock
->ops
->accept(control_sock
);
934 DBG("Relay control connection accepted, socket %d",
938 PERROR("accepting sock");
942 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
945 PERROR("setsockopt inet");
946 lttcomm_destroy_sock(newsock
);
950 ret
= socket_apply_keep_alive_config(newsock
->fd
);
952 ERR("Failed to apply TCP keep-alive configuration on socket (%i)",
954 lttcomm_destroy_sock(newsock
);
958 new_conn
= connection_create(newsock
, type
);
960 lttcomm_destroy_sock(newsock
);
964 /* Enqueue request for the dispatcher thread. */
965 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
969 * Wake the dispatch queue futex.
970 * Implicit memory barrier with the
971 * exchange in cds_wfcq_enqueue.
973 futex_nto1_wake(&relay_conn_queue
.futex
);
974 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
975 ERR("socket poll error");
978 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
988 lttng_poll_clean(&events
);
990 if (data_sock
->fd
>= 0) {
991 ret
= data_sock
->ops
->close(data_sock
);
996 lttcomm_destroy_sock(data_sock
);
998 if (control_sock
->fd
>= 0) {
999 ret
= control_sock
->ops
->close(control_sock
);
1004 lttcomm_destroy_sock(control_sock
);
1008 ERR("Health error occurred in %s", __func__
);
1010 health_unregister(health_relayd
);
1011 DBG("Relay listener thread cleanup complete");
1012 lttng_relay_stop_threads();
1017 * This thread manages the dispatching of the requests to worker threads
1019 static void *relay_thread_dispatcher(void *data
)
1023 struct cds_wfcq_node
*node
;
1024 struct relay_connection
*new_conn
= NULL
;
1026 DBG("[thread] Relay dispatcher started");
1028 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
1030 if (testpoint(relayd_thread_dispatcher
)) {
1031 goto error_testpoint
;
1034 health_code_update();
1037 health_code_update();
1039 /* Atomically prepare the queue futex */
1040 futex_nto1_prepare(&relay_conn_queue
.futex
);
1042 if (CMM_LOAD_SHARED(dispatch_thread_exit
)) {
1047 health_code_update();
1049 /* Dequeue commands */
1050 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
1051 &relay_conn_queue
.tail
);
1053 DBG("Woken up but nothing in the relay command queue");
1054 /* Continue thread execution */
1057 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1059 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1062 * Inform worker thread of the new request. This
1063 * call is blocking so we can be assured that
1064 * the data will be read at some point in time
1065 * or wait to the end of the world :)
1067 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1069 PERROR("write connection pipe");
1070 connection_put(new_conn
);
1073 } while (node
!= NULL
);
1075 /* Futex wait on queue. Blocking call on futex() */
1076 health_poll_entry();
1077 futex_nto1_wait(&relay_conn_queue
.futex
);
1081 /* Normal exit, no error */
1088 ERR("Health error occurred in %s", __func__
);
1090 health_unregister(health_relayd
);
1091 DBG("Dispatch thread dying");
1092 lttng_relay_stop_threads();
1097 * Set index data from the control port to a given index object.
1099 static int set_index_control_data(struct relay_index
*index
,
1100 struct lttcomm_relayd_index
*data
,
1101 struct relay_connection
*conn
)
1103 struct ctf_packet_index index_data
;
1106 * The index on disk is encoded in big endian.
1108 index_data
.packet_size
= htobe64(data
->packet_size
);
1109 index_data
.content_size
= htobe64(data
->content_size
);
1110 index_data
.timestamp_begin
= htobe64(data
->timestamp_begin
);
1111 index_data
.timestamp_end
= htobe64(data
->timestamp_end
);
1112 index_data
.events_discarded
= htobe64(data
->events_discarded
);
1113 index_data
.stream_id
= htobe64(data
->stream_id
);
1115 if (conn
->minor
>= 8) {
1116 index
->index_data
.stream_instance_id
= htobe64(data
->stream_instance_id
);
1117 index
->index_data
.packet_seq_num
= htobe64(data
->packet_seq_num
);
1120 return relay_index_set_data(index
, &index_data
);
1124 * Handle the RELAYD_CREATE_SESSION command.
1126 * On success, send back the session id or else return a negative value.
1128 static int relay_create_session(const struct lttcomm_relayd_hdr
*recv_hdr
,
1129 struct relay_connection
*conn
,
1130 const struct lttng_buffer_view
*payload
)
1134 struct relay_session
*session
;
1135 struct lttcomm_relayd_status_session reply
;
1136 char session_name
[LTTNG_NAME_MAX
];
1137 char hostname
[LTTNG_HOST_NAME_MAX
];
1138 uint32_t live_timer
= 0;
1139 bool snapshot
= false;
1141 memset(session_name
, 0, LTTNG_NAME_MAX
);
1142 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1144 memset(&reply
, 0, sizeof(reply
));
1146 switch (conn
->minor
) {
1151 case 4: /* LTTng sessiond 2.4 */
1153 ret
= cmd_create_session_2_4(payload
, session_name
,
1154 hostname
, &live_timer
, &snapshot
);
1160 session
= session_create(session_name
, hostname
, live_timer
,
1161 snapshot
, conn
->major
, conn
->minor
);
1166 assert(!conn
->session
);
1167 conn
->session
= session
;
1168 DBG("Created session %" PRIu64
, session
->id
);
1170 reply
.session_id
= htobe64(session
->id
);
1174 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1176 reply
.ret_code
= htobe32(LTTNG_OK
);
1179 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1180 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1181 ERR("Failed to send \"create session\" command reply (ret = %zd)",
1190 * When we have received all the streams and the metadata for a channel,
1191 * we make them visible to the viewer threads.
1193 static void publish_connection_local_streams(struct relay_connection
*conn
)
1195 struct relay_stream
*stream
;
1196 struct relay_session
*session
= conn
->session
;
1199 * We publish all streams belonging to a session atomically wrt
1202 pthread_mutex_lock(&session
->lock
);
1204 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1206 stream_publish(stream
);
1211 * Inform the viewer that there are new streams in the session.
1213 if (session
->viewer_attached
) {
1214 uatomic_set(&session
->new_streams
, 1);
1216 pthread_mutex_unlock(&session
->lock
);
1220 * relay_add_stream: allocate a new stream for a session
1222 static int relay_add_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1223 struct relay_connection
*conn
,
1224 const struct lttng_buffer_view
*payload
)
1228 struct relay_session
*session
= conn
->session
;
1229 struct relay_stream
*stream
= NULL
;
1230 struct lttcomm_relayd_status_stream reply
;
1231 struct ctf_trace
*trace
= NULL
;
1232 uint64_t stream_handle
= -1ULL;
1233 char *path_name
= NULL
, *channel_name
= NULL
;
1234 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1236 if (!session
|| !conn
->version_check_done
) {
1237 ERR("Trying to add a stream before version check");
1239 goto end_no_session
;
1242 switch (session
->minor
) {
1243 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1244 ret
= cmd_recv_stream_2_1(payload
, &path_name
,
1245 &channel_name
, session
);
1247 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1249 ret
= cmd_recv_stream_2_2(payload
, &path_name
,
1250 &channel_name
, &tracefile_size
, &tracefile_count
,
1258 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1262 /* This stream here has one reference on the trace. */
1264 pthread_mutex_lock(&last_relay_stream_id_lock
);
1265 stream_handle
= ++last_relay_stream_id
;
1266 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1268 /* We pass ownership of path_name and channel_name. */
1269 stream
= stream_create(trace
, stream_handle
, path_name
,
1270 channel_name
, tracefile_size
, tracefile_count
);
1272 channel_name
= NULL
;
1275 * Streams are the owners of their trace. Reference to trace is
1276 * kept within stream_create().
1278 ctf_trace_put(trace
);
1281 memset(&reply
, 0, sizeof(reply
));
1282 reply
.handle
= htobe64(stream_handle
);
1284 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1286 reply
.ret_code
= htobe32(LTTNG_OK
);
1289 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1290 sizeof(struct lttcomm_relayd_status_stream
), 0);
1291 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1292 ERR("Failed to send \"add stream\" command reply (ret = %zd)",
1304 * relay_close_stream: close a specific stream
1306 static int relay_close_stream(const struct lttcomm_relayd_hdr
*recv_hdr
,
1307 struct relay_connection
*conn
,
1308 const struct lttng_buffer_view
*payload
)
1312 struct relay_session
*session
= conn
->session
;
1313 struct lttcomm_relayd_close_stream stream_info
;
1314 struct lttcomm_relayd_generic_reply reply
;
1315 struct relay_stream
*stream
;
1317 DBG("Close stream received");
1319 if (!session
|| !conn
->version_check_done
) {
1320 ERR("Trying to close a stream before version check");
1322 goto end_no_session
;
1325 if (payload
->size
< sizeof(stream_info
)) {
1326 ERR("Unexpected payload size in \"relay_close_stream\": expected >= %zu bytes, got %zu bytes",
1327 sizeof(stream_info
), payload
->size
);
1329 goto end_no_session
;
1331 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1332 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1333 stream_info
.last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1335 stream
= stream_get_by_id(stream_info
.stream_id
);
1342 * Set last_net_seq_num before the close flag. Required by data
1345 pthread_mutex_lock(&stream
->lock
);
1346 stream
->last_net_seq_num
= stream_info
.last_net_seq_num
;
1347 pthread_mutex_unlock(&stream
->lock
);
1350 * This is one of the conditions which may trigger a stream close
1351 * with the others being:
1352 * 1) A close command is received for a stream
1353 * 2) The control connection owning the stream is closed
1354 * 3) We have received all of the stream's data _after_ a close
1357 try_stream_close(stream
);
1358 if (stream
->is_metadata
) {
1359 struct relay_viewer_stream
*vstream
;
1361 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1363 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1365 * Since all the metadata has been sent to the
1366 * viewer and that we have a request to close
1367 * its stream, we can safely teardown the
1368 * corresponding metadata viewer stream.
1370 viewer_stream_put(vstream
);
1372 /* Put local reference. */
1373 viewer_stream_put(vstream
);
1380 memset(&reply
, 0, sizeof(reply
));
1382 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1384 reply
.ret_code
= htobe32(LTTNG_OK
);
1386 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1387 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1388 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1389 ERR("Failed to send \"close stream\" command reply (ret = %zd)",
1399 * relay_reset_metadata: reset a metadata stream
1402 int relay_reset_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1403 struct relay_connection
*conn
,
1404 const struct lttng_buffer_view
*payload
)
1408 struct relay_session
*session
= conn
->session
;
1409 struct lttcomm_relayd_reset_metadata stream_info
;
1410 struct lttcomm_relayd_generic_reply reply
;
1411 struct relay_stream
*stream
;
1413 DBG("Reset metadata received");
1415 if (!session
|| !conn
->version_check_done
) {
1416 ERR("Trying to reset a metadata stream before version check");
1418 goto end_no_session
;
1421 if (payload
->size
< sizeof(stream_info
)) {
1422 ERR("Unexpected payload size in \"relay_reset_metadata\": expected >= %zu bytes, got %zu bytes",
1423 sizeof(stream_info
), payload
->size
);
1425 goto end_no_session
;
1427 memcpy(&stream_info
, payload
->data
, sizeof(stream_info
));
1428 stream_info
.stream_id
= be64toh(stream_info
.stream_id
);
1429 stream_info
.version
= be64toh(stream_info
.version
);
1431 DBG("Update metadata to version %" PRIu64
, stream_info
.version
);
1433 /* Unsupported for live sessions for now. */
1434 if (session
->live_timer
!= 0) {
1439 stream
= stream_get_by_id(stream_info
.stream_id
);
1444 pthread_mutex_lock(&stream
->lock
);
1445 if (!stream
->is_metadata
) {
1450 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1451 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1452 &stream
->stream_fd
->fd
);
1454 ERR("Failed to rotate metadata file %s of channel %s",
1455 stream
->path_name
, stream
->channel_name
);
1460 pthread_mutex_unlock(&stream
->lock
);
1464 memset(&reply
, 0, sizeof(reply
));
1466 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1468 reply
.ret_code
= htobe32(LTTNG_OK
);
1470 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1471 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1472 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1473 ERR("Failed to send \"reset metadata\" command reply (ret = %zd)",
1483 * relay_unknown_command: send -1 if received unknown command
1485 static void relay_unknown_command(struct relay_connection
*conn
)
1487 struct lttcomm_relayd_generic_reply reply
;
1490 memset(&reply
, 0, sizeof(reply
));
1491 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1492 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1493 if (send_ret
< sizeof(reply
)) {
1494 ERR("Failed to send \"unknown command\" command reply (ret = %zd)", send_ret
);
1499 * relay_start: send an acknowledgment to the client to tell if we are
1500 * ready to receive data. We are ready if a session is established.
1502 static int relay_start(const struct lttcomm_relayd_hdr
*recv_hdr
,
1503 struct relay_connection
*conn
,
1504 const struct lttng_buffer_view
*payload
)
1508 struct lttcomm_relayd_generic_reply reply
;
1509 struct relay_session
*session
= conn
->session
;
1512 DBG("Trying to start the streaming without a session established");
1513 ret
= htobe32(LTTNG_ERR_UNK
);
1516 memset(&reply
, 0, sizeof(reply
));
1517 reply
.ret_code
= htobe32(LTTNG_OK
);
1518 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1520 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1521 ERR("Failed to send \"relay_start\" command reply (ret = %zd)",
1530 * Append padding to the file pointed by the file descriptor fd.
1532 static int write_padding_to_file(int fd
, uint32_t size
)
1541 zeros
= zmalloc(size
);
1542 if (zeros
== NULL
) {
1543 PERROR("zmalloc zeros for padding");
1548 ret
= lttng_write(fd
, zeros
, size
);
1550 PERROR("write padding to file");
1560 * relay_recv_metadata: receive the metadata for the session.
1562 static int relay_recv_metadata(const struct lttcomm_relayd_hdr
*recv_hdr
,
1563 struct relay_connection
*conn
,
1564 const struct lttng_buffer_view
*payload
)
1568 struct relay_session
*session
= conn
->session
;
1569 struct lttcomm_relayd_metadata_payload metadata_payload_header
;
1570 struct relay_stream
*metadata_stream
;
1571 uint64_t metadata_payload_size
;
1574 ERR("Metadata sent before version check");
1579 if (recv_hdr
->data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1580 ERR("Incorrect data size");
1584 metadata_payload_size
= recv_hdr
->data_size
-
1585 sizeof(struct lttcomm_relayd_metadata_payload
);
1587 memcpy(&metadata_payload_header
, payload
->data
,
1588 sizeof(metadata_payload_header
));
1589 metadata_payload_header
.stream_id
= be64toh(
1590 metadata_payload_header
.stream_id
);
1591 metadata_payload_header
.padding_size
= be32toh(
1592 metadata_payload_header
.padding_size
);
1594 metadata_stream
= stream_get_by_id(metadata_payload_header
.stream_id
);
1595 if (!metadata_stream
) {
1600 pthread_mutex_lock(&metadata_stream
->lock
);
1602 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
,
1603 payload
->data
+ sizeof(metadata_payload_header
),
1604 metadata_payload_size
);
1605 if (size_ret
< metadata_payload_size
) {
1606 ERR("Relay error writing metadata on file");
1611 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1612 metadata_payload_header
.padding_size
);
1613 if (size_ret
< (int64_t) metadata_payload_header
.padding_size
) {
1618 metadata_stream
->metadata_received
+=
1619 metadata_payload_size
+ metadata_payload_header
.padding_size
;
1620 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1621 metadata_stream
->metadata_received
);
1624 pthread_mutex_unlock(&metadata_stream
->lock
);
1625 stream_put(metadata_stream
);
1631 * relay_send_version: send relayd version number
1633 static int relay_send_version(const struct lttcomm_relayd_hdr
*recv_hdr
,
1634 struct relay_connection
*conn
,
1635 const struct lttng_buffer_view
*payload
)
1639 struct lttcomm_relayd_version reply
, msg
;
1640 bool compatible
= true;
1642 conn
->version_check_done
= true;
1644 /* Get version from the other side. */
1645 if (payload
->size
< sizeof(msg
)) {
1646 ERR("Unexpected payload size in \"relay_send_version\": expected >= %zu bytes, got %zu bytes",
1647 sizeof(msg
), payload
->size
);
1652 memcpy(&msg
, payload
->data
, sizeof(msg
));
1653 msg
.major
= be32toh(msg
.major
);
1654 msg
.minor
= be32toh(msg
.minor
);
1656 memset(&reply
, 0, sizeof(reply
));
1657 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1658 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1660 /* Major versions must be the same */
1661 if (reply
.major
!= msg
.major
) {
1662 DBG("Incompatible major versions (%u vs %u), deleting session",
1663 reply
.major
, msg
.major
);
1667 conn
->major
= reply
.major
;
1668 /* We adapt to the lowest compatible version */
1669 if (reply
.minor
<= msg
.minor
) {
1670 conn
->minor
= reply
.minor
;
1672 conn
->minor
= msg
.minor
;
1675 reply
.major
= htobe32(reply
.major
);
1676 reply
.minor
= htobe32(reply
.minor
);
1677 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1679 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1680 ERR("Failed to send \"send version\" command reply (ret = %zd)",
1693 DBG("Version check done using protocol %u.%u", conn
->major
,
1701 * Check for data pending for a given stream id from the session daemon.
1703 static int relay_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1704 struct relay_connection
*conn
,
1705 const struct lttng_buffer_view
*payload
)
1707 struct relay_session
*session
= conn
->session
;
1708 struct lttcomm_relayd_data_pending msg
;
1709 struct lttcomm_relayd_generic_reply reply
;
1710 struct relay_stream
*stream
;
1714 DBG("Data pending command received");
1716 if (!session
|| !conn
->version_check_done
) {
1717 ERR("Trying to check for data before version check");
1719 goto end_no_session
;
1722 if (payload
->size
< sizeof(msg
)) {
1723 ERR("Unexpected payload size in \"relay_data_pending\": expected >= %zu bytes, got %zu bytes",
1724 sizeof(msg
), payload
->size
);
1726 goto end_no_session
;
1728 memcpy(&msg
, payload
->data
, sizeof(msg
));
1729 msg
.stream_id
= be64toh(msg
.stream_id
);
1730 msg
.last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1732 stream
= stream_get_by_id(msg
.stream_id
);
1733 if (stream
== NULL
) {
1738 pthread_mutex_lock(&stream
->lock
);
1740 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1741 " and last_seq %" PRIu64
, msg
.stream_id
,
1742 stream
->prev_seq
, msg
.last_net_seq_num
);
1744 /* Avoid wrapping issue */
1745 if (((int64_t) (stream
->prev_seq
- msg
.last_net_seq_num
)) >= 0) {
1746 /* Data has in fact been written and is NOT pending */
1749 /* Data still being streamed thus pending */
1753 stream
->data_pending_check_done
= true;
1754 pthread_mutex_unlock(&stream
->lock
);
1759 memset(&reply
, 0, sizeof(reply
));
1760 reply
.ret_code
= htobe32(ret
);
1761 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1762 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1763 ERR("Failed to send \"data pending\" command reply (ret = %zd)",
1773 * Wait for the control socket to reach a quiescent state.
1775 * Note that for now, when receiving this command from the session
1776 * daemon, this means that every subsequent commands or data received on
1777 * the control socket has been handled. So, this is why we simply return
1780 static int relay_quiescent_control(const struct lttcomm_relayd_hdr
*recv_hdr
,
1781 struct relay_connection
*conn
,
1782 const struct lttng_buffer_view
*payload
)
1786 struct relay_stream
*stream
;
1787 struct lttcomm_relayd_quiescent_control msg
;
1788 struct lttcomm_relayd_generic_reply reply
;
1790 DBG("Checking quiescent state on control socket");
1792 if (!conn
->session
|| !conn
->version_check_done
) {
1793 ERR("Trying to check for data before version check");
1795 goto end_no_session
;
1798 if (payload
->size
< sizeof(msg
)) {
1799 ERR("Unexpected payload size in \"relay_quiescent_control\": expected >= %zu bytes, got %zu bytes",
1800 sizeof(msg
), payload
->size
);
1802 goto end_no_session
;
1804 memcpy(&msg
, payload
->data
, sizeof(msg
));
1805 msg
.stream_id
= be64toh(msg
.stream_id
);
1807 stream
= stream_get_by_id(msg
.stream_id
);
1811 pthread_mutex_lock(&stream
->lock
);
1812 stream
->data_pending_check_done
= true;
1813 pthread_mutex_unlock(&stream
->lock
);
1815 DBG("Relay quiescent control pending flag set to %" PRIu64
, msg
.stream_id
);
1818 memset(&reply
, 0, sizeof(reply
));
1819 reply
.ret_code
= htobe32(LTTNG_OK
);
1820 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1821 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1822 ERR("Failed to send \"quiescent control\" command reply (ret = %zd)",
1834 * Initialize a data pending command. This means that a consumer is about
1835 * to ask for data pending for each stream it holds. Simply iterate over
1836 * all streams of a session and set the data_pending_check_done flag.
1838 * This command returns to the client a LTTNG_OK code.
1840 static int relay_begin_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1841 struct relay_connection
*conn
,
1842 const struct lttng_buffer_view
*payload
)
1846 struct lttng_ht_iter iter
;
1847 struct lttcomm_relayd_begin_data_pending msg
;
1848 struct lttcomm_relayd_generic_reply reply
;
1849 struct relay_stream
*stream
;
1854 DBG("Init streams for data pending");
1856 if (!conn
->session
|| !conn
->version_check_done
) {
1857 ERR("Trying to check for data before version check");
1859 goto end_no_session
;
1862 if (payload
->size
< sizeof(msg
)) {
1863 ERR("Unexpected payload size in \"relay_begin_data_pending\": expected >= %zu bytes, got %zu bytes",
1864 sizeof(msg
), payload
->size
);
1866 goto end_no_session
;
1868 memcpy(&msg
, payload
->data
, sizeof(msg
));
1869 msg
.session_id
= be64toh(msg
.session_id
);
1872 * Iterate over all streams to set the begin data pending flag.
1873 * For now, the streams are indexed by stream handle so we have
1874 * to iterate over all streams to find the one associated with
1875 * the right session_id.
1878 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1880 if (!stream_get(stream
)) {
1883 if (stream
->trace
->session
->id
== msg
.session_id
) {
1884 pthread_mutex_lock(&stream
->lock
);
1885 stream
->data_pending_check_done
= false;
1886 pthread_mutex_unlock(&stream
->lock
);
1887 DBG("Set begin data pending flag to stream %" PRIu64
,
1888 stream
->stream_handle
);
1894 memset(&reply
, 0, sizeof(reply
));
1895 /* All good, send back reply. */
1896 reply
.ret_code
= htobe32(LTTNG_OK
);
1898 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1899 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1900 ERR("Failed to send \"begin data pending\" command reply (ret = %zd)",
1912 * End data pending command. This will check, for a given session id, if
1913 * each stream associated with it has its data_pending_check_done flag
1914 * set. If not, this means that the client lost track of the stream but
1915 * the data is still being streamed on our side. In this case, we inform
1916 * the client that data is in flight.
1918 * Return to the client if there is data in flight or not with a ret_code.
1920 static int relay_end_data_pending(const struct lttcomm_relayd_hdr
*recv_hdr
,
1921 struct relay_connection
*conn
,
1922 const struct lttng_buffer_view
*payload
)
1926 struct lttng_ht_iter iter
;
1927 struct lttcomm_relayd_end_data_pending msg
;
1928 struct lttcomm_relayd_generic_reply reply
;
1929 struct relay_stream
*stream
;
1930 uint32_t is_data_inflight
= 0;
1932 DBG("End data pending command");
1934 if (!conn
->session
|| !conn
->version_check_done
) {
1935 ERR("Trying to check for data before version check");
1937 goto end_no_session
;
1940 if (payload
->size
< sizeof(msg
)) {
1941 ERR("Unexpected payload size in \"relay_end_data_pending\": expected >= %zu bytes, got %zu bytes",
1942 sizeof(msg
), payload
->size
);
1944 goto end_no_session
;
1946 memcpy(&msg
, payload
->data
, sizeof(msg
));
1947 msg
.session_id
= be64toh(msg
.session_id
);
1950 * Iterate over all streams to see if the begin data pending
1954 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1956 if (!stream_get(stream
)) {
1959 if (stream
->trace
->session
->id
!= msg
.session_id
) {
1963 pthread_mutex_lock(&stream
->lock
);
1964 if (!stream
->data_pending_check_done
) {
1965 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1966 is_data_inflight
= 1;
1967 DBG("Data is still in flight for stream %" PRIu64
,
1968 stream
->stream_handle
);
1969 pthread_mutex_unlock(&stream
->lock
);
1974 pthread_mutex_unlock(&stream
->lock
);
1979 memset(&reply
, 0, sizeof(reply
));
1980 /* All good, send back reply. */
1981 reply
.ret_code
= htobe32(is_data_inflight
);
1983 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1984 if (send_ret
< (ssize_t
) sizeof(reply
)) {
1985 ERR("Failed to send \"end data pending\" command reply (ret = %zd)",
1997 * Receive an index for a specific stream.
1999 * Return 0 on success else a negative value.
2001 static int relay_recv_index(const struct lttcomm_relayd_hdr
*recv_hdr
,
2002 struct relay_connection
*conn
,
2003 const struct lttng_buffer_view
*payload
)
2007 struct relay_session
*session
= conn
->session
;
2008 struct lttcomm_relayd_index index_info
;
2009 struct relay_index
*index
;
2010 struct lttcomm_relayd_generic_reply reply
;
2011 struct relay_stream
*stream
;
2016 DBG("Relay receiving index");
2018 if (!session
|| !conn
->version_check_done
) {
2019 ERR("Trying to close a stream before version check");
2021 goto end_no_session
;
2024 msg_len
= lttcomm_relayd_index_len(
2025 lttng_to_index_major(conn
->major
, conn
->minor
),
2026 lttng_to_index_minor(conn
->major
, conn
->minor
));
2027 if (payload
->size
< msg_len
) {
2028 ERR("Unexpected payload size in \"relay_recv_index\": expected >= %zu bytes, got %zu bytes",
2029 msg_len
, payload
->size
);
2031 goto end_no_session
;
2033 memcpy(&index_info
, payload
->data
, msg_len
);
2034 index_info
.relay_stream_id
= be64toh(index_info
.relay_stream_id
);
2035 index_info
.net_seq_num
= be64toh(index_info
.net_seq_num
);
2036 index_info
.packet_size
= be64toh(index_info
.packet_size
);
2037 index_info
.content_size
= be64toh(index_info
.content_size
);
2038 index_info
.timestamp_begin
= be64toh(index_info
.timestamp_begin
);
2039 index_info
.timestamp_end
= be64toh(index_info
.timestamp_end
);
2040 index_info
.events_discarded
= be64toh(index_info
.events_discarded
);
2041 index_info
.stream_id
= be64toh(index_info
.stream_id
);
2043 if (conn
->minor
>= 8) {
2044 index_info
.stream_instance_id
=
2045 be64toh(index_info
.stream_instance_id
);
2046 index_info
.packet_seq_num
= be64toh(index_info
.packet_seq_num
);
2049 stream
= stream_get_by_id(index_info
.relay_stream_id
);
2051 ERR("stream_get_by_id not found");
2055 pthread_mutex_lock(&stream
->lock
);
2057 /* Live beacon handling */
2058 if (index_info
.packet_size
== 0) {
2059 DBG("Received live beacon for stream %" PRIu64
,
2060 stream
->stream_handle
);
2063 * Only flag a stream inactive when it has already
2064 * received data and no indexes are in flight.
2066 if (stream
->index_received_seqcount
> 0
2067 && stream
->indexes_in_flight
== 0) {
2068 stream
->beacon_ts_end
= index_info
.timestamp_end
;
2071 goto end_stream_put
;
2073 stream
->beacon_ts_end
= -1ULL;
2076 if (stream
->ctf_stream_id
== -1ULL) {
2077 stream
->ctf_stream_id
= index_info
.stream_id
;
2079 index
= relay_index_get_by_id_or_create(stream
, index_info
.net_seq_num
);
2082 ERR("relay_index_get_by_id_or_create index NULL");
2083 goto end_stream_put
;
2085 if (set_index_control_data(index
, &index_info
, conn
)) {
2086 ERR("set_index_control_data error");
2087 relay_index_put(index
);
2089 goto end_stream_put
;
2091 ret
= relay_index_try_flush(index
);
2093 tracefile_array_commit_seq(stream
->tfa
);
2094 stream
->index_received_seqcount
++;
2095 } else if (ret
> 0) {
2099 ERR("relay_index_try_flush error %d", ret
);
2100 relay_index_put(index
);
2105 pthread_mutex_unlock(&stream
->lock
);
2110 memset(&reply
, 0, sizeof(reply
));
2112 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2114 reply
.ret_code
= htobe32(LTTNG_OK
);
2116 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2117 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2118 ERR("Failed to send \"recv index\" command reply (ret = %zd)", send_ret
);
2127 * Receive the streams_sent message.
2129 * Return 0 on success else a negative value.
2131 static int relay_streams_sent(const struct lttcomm_relayd_hdr
*recv_hdr
,
2132 struct relay_connection
*conn
,
2133 const struct lttng_buffer_view
*payload
)
2137 struct lttcomm_relayd_generic_reply reply
;
2141 DBG("Relay receiving streams_sent");
2143 if (!conn
->session
|| !conn
->version_check_done
) {
2144 ERR("Trying to close a stream before version check");
2146 goto end_no_session
;
2150 * Publish every pending stream in the connection recv list which are
2151 * now ready to be used by the viewer.
2153 publish_connection_local_streams(conn
);
2155 memset(&reply
, 0, sizeof(reply
));
2156 reply
.ret_code
= htobe32(LTTNG_OK
);
2157 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2158 if (send_ret
< (ssize_t
) sizeof(reply
)) {
2159 ERR("Failed to send \"streams sent\" command reply (ret = %zd)",
2171 #define DBG_CMD(cmd_name, conn) \
2172 DBG3("Processing \"%s\" command for socket %i", cmd_name, conn->sock->fd);
2174 static int relay_process_control_command(struct relay_connection
*conn
,
2175 const struct lttcomm_relayd_hdr
*header
,
2176 const struct lttng_buffer_view
*payload
)
2180 switch (header
->cmd
) {
2181 case RELAYD_CREATE_SESSION
:
2182 DBG_CMD("RELAYD_CREATE_SESSION", conn
);
2183 ret
= relay_create_session(header
, conn
, payload
);
2185 case RELAYD_ADD_STREAM
:
2186 DBG_CMD("RELAYD_ADD_STREAM", conn
);
2187 ret
= relay_add_stream(header
, conn
, payload
);
2189 case RELAYD_START_DATA
:
2190 DBG_CMD("RELAYD_START_DATA", conn
);
2191 ret
= relay_start(header
, conn
, payload
);
2193 case RELAYD_SEND_METADATA
:
2194 DBG_CMD("RELAYD_SEND_METADATA", conn
);
2195 ret
= relay_recv_metadata(header
, conn
, payload
);
2197 case RELAYD_VERSION
:
2198 DBG_CMD("RELAYD_VERSION", conn
);
2199 ret
= relay_send_version(header
, conn
, payload
);
2201 case RELAYD_CLOSE_STREAM
:
2202 DBG_CMD("RELAYD_CLOSE_STREAM", conn
);
2203 ret
= relay_close_stream(header
, conn
, payload
);
2205 case RELAYD_DATA_PENDING
:
2206 DBG_CMD("RELAYD_DATA_PENDING", conn
);
2207 ret
= relay_data_pending(header
, conn
, payload
);
2209 case RELAYD_QUIESCENT_CONTROL
:
2210 DBG_CMD("RELAYD_QUIESCENT_CONTROL", conn
);
2211 ret
= relay_quiescent_control(header
, conn
, payload
);
2213 case RELAYD_BEGIN_DATA_PENDING
:
2214 DBG_CMD("RELAYD_BEGIN_DATA_PENDING", conn
);
2215 ret
= relay_begin_data_pending(header
, conn
, payload
);
2217 case RELAYD_END_DATA_PENDING
:
2218 DBG_CMD("RELAYD_END_DATA_PENDING", conn
);
2219 ret
= relay_end_data_pending(header
, conn
, payload
);
2221 case RELAYD_SEND_INDEX
:
2222 DBG_CMD("RELAYD_SEND_INDEX", conn
);
2223 ret
= relay_recv_index(header
, conn
, payload
);
2225 case RELAYD_STREAMS_SENT
:
2226 DBG_CMD("RELAYD_STREAMS_SENT", conn
);
2227 ret
= relay_streams_sent(header
, conn
, payload
);
2229 case RELAYD_RESET_METADATA
:
2230 DBG_CMD("RELAYD_RESET_METADATA", conn
);
2231 ret
= relay_reset_metadata(header
, conn
, payload
);
2233 case RELAYD_UPDATE_SYNC_INFO
:
2235 ERR("Received unknown command (%u)", header
->cmd
);
2236 relay_unknown_command(conn
);
2245 static enum relay_connection_status
relay_process_control_receive_payload(
2246 struct relay_connection
*conn
)
2249 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2250 struct lttng_dynamic_buffer
*reception_buffer
=
2251 &conn
->protocol
.ctrl
.reception_buffer
;
2252 struct ctrl_connection_state_receive_payload
*state
=
2253 &conn
->protocol
.ctrl
.state
.receive_payload
;
2254 struct lttng_buffer_view payload_view
;
2256 if (state
->left_to_receive
== 0) {
2257 /* Short-circuit for payload-less commands. */
2258 goto reception_complete
;
2260 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2261 reception_buffer
->data
+ state
->received
,
2262 state
->left_to_receive
, MSG_DONTWAIT
);
2264 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2265 PERROR("Unable to receive command payload on sock %d",
2267 status
= RELAY_CONNECTION_STATUS_ERROR
;
2270 } else if (ret
== 0) {
2271 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2272 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2277 assert(ret
<= state
->left_to_receive
);
2279 state
->left_to_receive
-= ret
;
2280 state
->received
+= ret
;
2282 if (state
->left_to_receive
> 0) {
2284 * Can't transition to the protocol's next state, wait to
2285 * receive the rest of the header.
2287 DBG3("Partial reception of control connection protocol payload (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2288 state
->received
, state
->left_to_receive
,
2294 DBG("Done receiving control command payload: fd = %i, payload size = %" PRIu64
" bytes",
2295 conn
->sock
->fd
, state
->received
);
2297 * The payload required to process the command has been received.
2298 * A view to the reception buffer is forwarded to the various
2299 * commands and the state of the control is reset on success.
2301 * Commands are responsible for sending their reply to the peer.
2303 payload_view
= lttng_buffer_view_from_dynamic_buffer(reception_buffer
,
2305 ret
= relay_process_control_command(conn
,
2306 &state
->header
, &payload_view
);
2308 status
= RELAY_CONNECTION_STATUS_ERROR
;
2312 ret
= connection_reset_protocol_state(conn
);
2314 status
= RELAY_CONNECTION_STATUS_ERROR
;
2320 static enum relay_connection_status
relay_process_control_receive_header(
2321 struct relay_connection
*conn
)
2324 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2325 struct lttcomm_relayd_hdr header
;
2326 struct lttng_dynamic_buffer
*reception_buffer
=
2327 &conn
->protocol
.ctrl
.reception_buffer
;
2328 struct ctrl_connection_state_receive_header
*state
=
2329 &conn
->protocol
.ctrl
.state
.receive_header
;
2331 assert(state
->left_to_receive
!= 0);
2333 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2334 reception_buffer
->data
+ state
->received
,
2335 state
->left_to_receive
, MSG_DONTWAIT
);
2337 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2338 PERROR("Unable to receive control command header on sock %d",
2340 status
= RELAY_CONNECTION_STATUS_ERROR
;
2343 } else if (ret
== 0) {
2344 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2345 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2350 assert(ret
<= state
->left_to_receive
);
2352 state
->left_to_receive
-= ret
;
2353 state
->received
+= ret
;
2355 if (state
->left_to_receive
> 0) {
2357 * Can't transition to the protocol's next state, wait to
2358 * receive the rest of the header.
2360 DBG3("Partial reception of control connection protocol header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2361 state
->received
, state
->left_to_receive
,
2366 /* Transition to next state: receiving the command's payload. */
2367 conn
->protocol
.ctrl
.state_id
=
2368 CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2369 memcpy(&header
, reception_buffer
->data
, sizeof(header
));
2370 header
.circuit_id
= be64toh(header
.circuit_id
);
2371 header
.data_size
= be64toh(header
.data_size
);
2372 header
.cmd
= be32toh(header
.cmd
);
2373 header
.cmd_version
= be32toh(header
.cmd_version
);
2374 memcpy(&conn
->protocol
.ctrl
.state
.receive_payload
.header
,
2375 &header
, sizeof(header
));
2377 DBG("Done receiving control command header: fd = %i, cmd = %" PRIu32
", cmd_version = %" PRIu32
", payload size = %" PRIu64
" bytes",
2378 conn
->sock
->fd
, header
.cmd
, header
.cmd_version
,
2381 if (header
.data_size
> DEFAULT_NETWORK_RELAYD_CTRL_MAX_PAYLOAD_SIZE
) {
2382 ERR("Command header indicates a payload (%" PRIu64
" bytes) that exceeds the maximal payload size allowed on a control connection.",
2384 status
= RELAY_CONNECTION_STATUS_ERROR
;
2388 conn
->protocol
.ctrl
.state
.receive_payload
.left_to_receive
=
2390 conn
->protocol
.ctrl
.state
.receive_payload
.received
= 0;
2391 ret
= lttng_dynamic_buffer_set_size(reception_buffer
,
2394 status
= RELAY_CONNECTION_STATUS_ERROR
;
2398 if (header
.data_size
== 0) {
2400 * Manually invoke the next state as the poll loop
2401 * will not wake-up to allow us to proceed further.
2403 status
= relay_process_control_receive_payload(conn
);
2410 * Process the commands received on the control socket
2412 static enum relay_connection_status
relay_process_control(
2413 struct relay_connection
*conn
)
2415 enum relay_connection_status status
;
2417 switch (conn
->protocol
.ctrl
.state_id
) {
2418 case CTRL_CONNECTION_STATE_RECEIVE_HEADER
:
2419 status
= relay_process_control_receive_header(conn
);
2421 case CTRL_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2422 status
= relay_process_control_receive_payload(conn
);
2425 ERR("Unknown control connection protocol state encountered.");
2433 * Handle index for a data stream.
2435 * Called with the stream lock held.
2437 * Return 0 on success else a negative value.
2439 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2443 uint64_t data_offset
;
2444 struct relay_index
*index
;
2446 /* Get data offset because we are about to update the index. */
2447 data_offset
= htobe64(stream
->tracefile_size_current
);
2449 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2450 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2453 * Lookup for an existing index for that stream id/sequence
2454 * number. If it exists, the control thread has already received the
2455 * data for it, thus we need to write it to disk.
2457 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2463 if (rotate_index
|| !stream
->index_file
) {
2464 uint32_t major
, minor
;
2466 /* Put ref on previous index_file. */
2467 if (stream
->index_file
) {
2468 lttng_index_file_put(stream
->index_file
);
2469 stream
->index_file
= NULL
;
2471 major
= stream
->trace
->session
->major
;
2472 minor
= stream
->trace
->session
->minor
;
2473 stream
->index_file
= lttng_index_file_create(stream
->path_name
,
2474 stream
->channel_name
,
2475 -1, -1, stream
->tracefile_size
,
2476 tracefile_array_get_file_index_head(stream
->tfa
),
2477 lttng_to_index_major(major
, minor
),
2478 lttng_to_index_minor(major
, minor
));
2479 if (!stream
->index_file
) {
2481 /* Put self-ref for this index due to error. */
2482 relay_index_put(index
);
2488 if (relay_index_set_file(index
, stream
->index_file
, data_offset
)) {
2490 /* Put self-ref for this index due to error. */
2491 relay_index_put(index
);
2496 ret
= relay_index_try_flush(index
);
2498 tracefile_array_commit_seq(stream
->tfa
);
2499 stream
->index_received_seqcount
++;
2500 } else if (ret
> 0) {
2504 /* Put self-ref for this index due to error. */
2505 relay_index_put(index
);
2513 static enum relay_connection_status
relay_process_data_receive_header(
2514 struct relay_connection
*conn
)
2517 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2518 struct data_connection_state_receive_header
*state
=
2519 &conn
->protocol
.data
.state
.receive_header
;
2520 struct lttcomm_relayd_data_hdr header
;
2521 struct relay_stream
*stream
;
2523 assert(state
->left_to_receive
!= 0);
2525 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
,
2526 state
->header_reception_buffer
+ state
->received
,
2527 state
->left_to_receive
, MSG_DONTWAIT
);
2529 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2530 PERROR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2531 status
= RELAY_CONNECTION_STATUS_ERROR
;
2534 } else if (ret
== 0) {
2535 /* Orderly shutdown. Not necessary to print an error. */
2536 DBG("Socket %d performed an orderly shutdown (received EOF)", conn
->sock
->fd
);
2537 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2542 assert(ret
<= state
->left_to_receive
);
2544 state
->left_to_receive
-= ret
;
2545 state
->received
+= ret
;
2547 if (state
->left_to_receive
> 0) {
2549 * Can't transition to the protocol's next state, wait to
2550 * receive the rest of the header.
2552 DBG3("Partial reception of data connection header (received %" PRIu64
" bytes, %" PRIu64
" bytes left to receive, fd = %i)",
2553 state
->received
, state
->left_to_receive
,
2559 /* Transition to next state: receiving the payload. */
2560 conn
->protocol
.data
.state_id
= DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
;
2562 memcpy(&header
, state
->header_reception_buffer
, sizeof(header
));
2563 header
.circuit_id
= be64toh(header
.circuit_id
);
2564 header
.stream_id
= be64toh(header
.stream_id
);
2565 header
.data_size
= be32toh(header
.data_size
);
2566 header
.net_seq_num
= be64toh(header
.net_seq_num
);
2567 header
.padding_size
= be32toh(header
.padding_size
);
2568 memcpy(&conn
->protocol
.data
.state
.receive_payload
.header
, &header
, sizeof(header
));
2570 conn
->protocol
.data
.state
.receive_payload
.left_to_receive
=
2572 conn
->protocol
.data
.state
.receive_payload
.received
= 0;
2573 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= false;
2575 DBG("Received data connection header on fd %i: circuit_id = %" PRIu64
", stream_id = %" PRIu64
", data_size = %" PRIu32
", net_seq_num = %" PRIu64
", padding_size = %" PRIu32
,
2576 conn
->sock
->fd
, header
.circuit_id
,
2577 header
.stream_id
, header
.data_size
,
2578 header
.net_seq_num
, header
.padding_size
);
2580 stream
= stream_get_by_id(header
.stream_id
);
2582 DBG("relay_process_data_receive_payload: Cannot find stream %" PRIu64
,
2584 /* Protocol error. */
2585 status
= RELAY_CONNECTION_STATUS_ERROR
;
2589 pthread_mutex_lock(&stream
->lock
);
2591 /* Check if a rotation is needed. */
2592 if (stream
->tracefile_size
> 0 &&
2593 (stream
->tracefile_size_current
+ header
.data_size
) >
2594 stream
->tracefile_size
) {
2595 uint64_t old_id
, new_id
;
2597 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2598 tracefile_array_file_rotate(stream
->tfa
);
2600 /* new_id is updated by utils_rotate_stream_file. */
2603 ret
= utils_rotate_stream_file(stream
->path_name
,
2604 stream
->channel_name
, stream
->tracefile_size
,
2605 stream
->tracefile_count
, -1,
2606 -1, stream
->stream_fd
->fd
,
2607 &new_id
, &stream
->stream_fd
->fd
);
2609 ERR("Failed to rotate stream output file");
2610 status
= RELAY_CONNECTION_STATUS_ERROR
;
2611 goto end_stream_unlock
;
2615 * Reset current size because we just performed a stream
2618 stream
->tracefile_size_current
= 0;
2619 conn
->protocol
.data
.state
.receive_payload
.rotate_index
= true;
2624 pthread_mutex_unlock(&stream
->lock
);
2630 static enum relay_connection_status
relay_process_data_receive_payload(
2631 struct relay_connection
*conn
)
2634 enum relay_connection_status status
= RELAY_CONNECTION_STATUS_OK
;
2635 struct relay_stream
*stream
;
2636 struct data_connection_state_receive_payload
*state
=
2637 &conn
->protocol
.data
.state
.receive_payload
;
2638 const size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2639 char data_buffer
[chunk_size
];
2640 bool partial_recv
= false;
2641 bool new_stream
= false, close_requested
= false;
2642 uint64_t left_to_receive
= state
->left_to_receive
;
2643 struct relay_session
*session
;
2645 DBG3("Receiving data for stream id %" PRIu64
" seqnum %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2646 state
->header
.stream_id
, state
->header
.net_seq_num
,
2647 state
->received
, left_to_receive
);
2649 stream
= stream_get_by_id(state
->header
.stream_id
);
2651 /* Protocol error. */
2652 ERR("relay_process_data_receive_payload: cannot find stream %" PRIu64
,
2653 state
->header
.stream_id
);
2654 status
= RELAY_CONNECTION_STATUS_ERROR
;
2658 pthread_mutex_lock(&stream
->lock
);
2659 session
= stream
->trace
->session
;
2660 if (!conn
->session
) {
2661 ret
= connection_set_session(conn
, session
);
2663 status
= RELAY_CONNECTION_STATUS_ERROR
;
2664 goto end_stream_unlock
;
2669 * The size of the "chunk" received on any iteration is bounded by:
2670 * - the data left to receive,
2671 * - the data immediately available on the socket,
2672 * - the on-stack data buffer
2674 while (left_to_receive
> 0 && !partial_recv
) {
2676 size_t recv_size
= min(left_to_receive
, chunk_size
);
2678 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
,
2679 recv_size
, MSG_DONTWAIT
);
2681 if (errno
!= EAGAIN
&& errno
!= EWOULDBLOCK
) {
2682 PERROR("Socket %d error", conn
->sock
->fd
);
2683 status
= RELAY_CONNECTION_STATUS_ERROR
;
2685 goto end_stream_unlock
;
2686 } else if (ret
== 0) {
2687 /* No more data ready to be consumed on socket. */
2688 DBG3("No more data ready for consumption on data socket of stream id %" PRIu64
,
2689 state
->header
.stream_id
);
2690 status
= RELAY_CONNECTION_STATUS_CLOSED
;
2692 } else if (ret
< (int) recv_size
) {
2694 * All the data available on the socket has been
2697 partial_recv
= true;
2702 /* Write data to stream output fd. */
2703 write_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2705 if (write_ret
< (ssize_t
) recv_size
) {
2706 ERR("Relay error writing data to file");
2707 status
= RELAY_CONNECTION_STATUS_ERROR
;
2708 goto end_stream_unlock
;
2711 left_to_receive
-= recv_size
;
2712 state
->received
+= recv_size
;
2713 state
->left_to_receive
= left_to_receive
;
2715 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2716 write_ret
, stream
->stream_handle
);
2719 if (state
->left_to_receive
> 0) {
2721 * Did not receive all the data expected, wait for more data to
2722 * become available on the socket.
2724 DBG3("Partial receive on data connection of stream id %" PRIu64
", %" PRIu64
" bytes received, %" PRIu64
" bytes left to receive",
2725 state
->header
.stream_id
, state
->received
,
2726 state
->left_to_receive
);
2727 goto end_stream_unlock
;
2730 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2731 state
->header
.padding_size
);
2732 if ((int64_t) ret
< (int64_t) state
->header
.padding_size
) {
2733 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2734 stream
->stream_handle
,
2735 state
->header
.net_seq_num
, ret
);
2736 status
= RELAY_CONNECTION_STATUS_ERROR
;
2737 goto end_stream_unlock
;
2741 if (session
->minor
>= 4 && !session
->snapshot
) {
2742 ret
= handle_index_data(stream
, state
->header
.net_seq_num
,
2743 state
->rotate_index
);
2745 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2746 stream
->stream_handle
,
2747 state
->header
.net_seq_num
, ret
);
2748 status
= RELAY_CONNECTION_STATUS_ERROR
;
2749 goto end_stream_unlock
;
2753 stream
->tracefile_size_current
+= state
->header
.data_size
+
2754 state
->header
.padding_size
;
2756 if (stream
->prev_seq
== -1ULL) {
2760 stream
->prev_seq
= state
->header
.net_seq_num
;
2763 * Resetting the protocol state (to RECEIVE_HEADER) will trash the
2764 * contents of *state which are aliased (union) to the same location as
2765 * the new state. Don't use it beyond this point.
2767 connection_reset_protocol_state(conn
);
2771 close_requested
= stream
->close_requested
;
2772 pthread_mutex_unlock(&stream
->lock
);
2773 if (close_requested
&& left_to_receive
== 0) {
2774 try_stream_close(stream
);
2778 pthread_mutex_lock(&session
->lock
);
2779 uatomic_set(&session
->new_streams
, 1);
2780 pthread_mutex_unlock(&session
->lock
);
2789 * relay_process_data: Process the data received on the data socket
2791 static enum relay_connection_status
relay_process_data(
2792 struct relay_connection
*conn
)
2794 enum relay_connection_status status
;
2796 switch (conn
->protocol
.data
.state_id
) {
2797 case DATA_CONNECTION_STATE_RECEIVE_HEADER
:
2798 status
= relay_process_data_receive_header(conn
);
2800 case DATA_CONNECTION_STATE_RECEIVE_PAYLOAD
:
2801 status
= relay_process_data_receive_payload(conn
);
2804 ERR("Unexpected data connection communication state.");
2811 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2815 (void) lttng_poll_del(events
, pollfd
);
2817 ret
= close(pollfd
);
2819 ERR("Closing pollfd %d", pollfd
);
2823 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2824 int pollfd
, struct relay_connection
*conn
)
2826 const char *type_str
;
2828 switch (conn
->type
) {
2833 type_str
= "Control";
2835 case RELAY_VIEWER_COMMAND
:
2836 type_str
= "Viewer Command";
2838 case RELAY_VIEWER_NOTIFICATION
:
2839 type_str
= "Viewer Notification";
2842 type_str
= "Unknown";
2844 cleanup_connection_pollfd(events
, pollfd
);
2845 connection_put(conn
);
2846 DBG("%s connection closed with %d", type_str
, pollfd
);
2850 * This thread does the actual work
2852 static void *relay_thread_worker(void *data
)
2854 int ret
, err
= -1, last_seen_data_fd
= -1;
2856 struct lttng_poll_event events
;
2857 struct lttng_ht
*relay_connections_ht
;
2858 struct lttng_ht_iter iter
;
2859 struct relay_connection
*destroy_conn
= NULL
;
2861 DBG("[thread] Relay worker started");
2863 rcu_register_thread();
2865 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2867 if (testpoint(relayd_thread_worker
)) {
2868 goto error_testpoint
;
2871 health_code_update();
2873 /* table of connections indexed on socket */
2874 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2875 if (!relay_connections_ht
) {
2876 goto relay_connections_ht_error
;
2879 ret
= create_thread_poll_set(&events
, 2);
2881 goto error_poll_create
;
2884 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2891 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2893 health_code_update();
2895 /* Infinite blocking call, waiting for transmission */
2896 DBG3("Relayd worker thread polling...");
2897 health_poll_entry();
2898 ret
= lttng_poll_wait(&events
, -1);
2902 * Restart interrupted system call.
2904 if (errno
== EINTR
) {
2913 * Process control. The control connection is
2914 * prioritized so we don't starve it with high
2915 * throughput tracing data on the data connection.
2917 for (i
= 0; i
< nb_fd
; i
++) {
2918 /* Fetch once the poll data */
2919 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2920 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2922 health_code_update();
2926 * No activity for this FD (poll
2932 /* Thread quit pipe has been closed. Killing thread. */
2933 ret
= check_thread_quit_pipe(pollfd
, revents
);
2939 /* Inspect the relay conn pipe for new connection */
2940 if (pollfd
== relay_conn_pipe
[0]) {
2941 if (revents
& LPOLLIN
) {
2942 struct relay_connection
*conn
;
2944 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2948 lttng_poll_add(&events
, conn
->sock
->fd
,
2949 LPOLLIN
| LPOLLRDHUP
);
2950 connection_ht_add(relay_connections_ht
, conn
);
2951 DBG("Connection socket %d added", conn
->sock
->fd
);
2952 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2953 ERR("Relay connection pipe error");
2956 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2960 struct relay_connection
*ctrl_conn
;
2962 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2963 /* If not found, there is a synchronization issue. */
2966 if (ctrl_conn
->type
== RELAY_DATA
) {
2967 if (revents
& LPOLLIN
) {
2969 * Flag the last seen data fd not deleted. It will be
2970 * used as the last seen fd if any fd gets deleted in
2973 last_notdel_data_fd
= pollfd
;
2975 goto put_ctrl_connection
;
2977 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2979 if (revents
& LPOLLIN
) {
2980 enum relay_connection_status status
;
2982 status
= relay_process_control(ctrl_conn
);
2983 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
2985 * On socket error flag the session as aborted to force
2986 * the cleanup of its stream otherwise it can leak
2987 * during the lifetime of the relayd.
2989 * This prevents situations in which streams can be
2990 * left opened because an index was received, the
2991 * control connection is closed, and the data
2992 * connection is closed (uncleanly) before the packet's
2995 * Since the control connection encountered an error,
2996 * it is okay to be conservative and close the
2997 * session right now as we can't rely on the protocol
2998 * being respected anymore.
3000 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3001 session_abort(ctrl_conn
->session
);
3004 /* Clear the connection on error or close. */
3005 relay_thread_close_connection(&events
,
3010 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3011 relay_thread_close_connection(&events
,
3013 if (last_seen_data_fd
== pollfd
) {
3014 last_seen_data_fd
= last_notdel_data_fd
;
3017 ERR("Unexpected poll events %u for control sock %d",
3019 connection_put(ctrl_conn
);
3022 put_ctrl_connection
:
3023 connection_put(ctrl_conn
);
3028 * The last loop handled a control request, go back to poll to make
3029 * sure we prioritise the control socket.
3035 if (last_seen_data_fd
>= 0) {
3036 for (i
= 0; i
< nb_fd
; i
++) {
3037 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3039 health_code_update();
3041 if (last_seen_data_fd
== pollfd
) {
3048 /* Process data connection. */
3049 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
3050 /* Fetch the poll data. */
3051 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
3052 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
3053 struct relay_connection
*data_conn
;
3055 health_code_update();
3058 /* No activity for this FD (poll implementation). */
3062 /* Skip the command pipe. It's handled in the first loop. */
3063 if (pollfd
== relay_conn_pipe
[0]) {
3067 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
3069 /* Skip it. Might be removed before. */
3072 if (data_conn
->type
== RELAY_CONTROL
) {
3073 goto put_data_connection
;
3075 assert(data_conn
->type
== RELAY_DATA
);
3077 if (revents
& LPOLLIN
) {
3078 enum relay_connection_status status
;
3080 status
= relay_process_data(data_conn
);
3081 /* Connection closed or error. */
3082 if (status
!= RELAY_CONNECTION_STATUS_OK
) {
3084 * On socket error flag the session as aborted to force
3085 * the cleanup of its stream otherwise it can leak
3086 * during the lifetime of the relayd.
3088 * This prevents situations in which streams can be
3089 * left opened because an index was received, the
3090 * control connection is closed, and the data
3091 * connection is closed (uncleanly) before the packet's
3094 * Since the data connection encountered an error,
3095 * it is okay to be conservative and close the
3096 * session right now as we can't rely on the protocol
3097 * being respected anymore.
3099 if (status
== RELAY_CONNECTION_STATUS_ERROR
) {
3100 session_abort(data_conn
->session
);
3102 relay_thread_close_connection(&events
, pollfd
,
3105 * Every goto restart call sets the last seen fd where
3106 * here we don't really care since we gracefully
3107 * continue the loop after the connection is deleted.
3110 /* Keep last seen port. */
3111 last_seen_data_fd
= pollfd
;
3112 connection_put(data_conn
);
3115 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
3116 relay_thread_close_connection(&events
, pollfd
,
3119 ERR("Unknown poll events %u for data sock %d",
3122 put_data_connection
:
3123 connection_put(data_conn
);
3125 last_seen_data_fd
= -1;
3128 /* Normal exit, no error */
3133 /* Cleanup reamaining connection object. */
3135 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
3138 health_code_update();
3140 session_abort(destroy_conn
->session
);
3143 * No need to grab another ref, because we own
3146 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
3151 lttng_poll_clean(&events
);
3153 lttng_ht_destroy(relay_connections_ht
);
3154 relay_connections_ht_error
:
3155 /* Close relay conn pipes */
3156 utils_close_pipe(relay_conn_pipe
);
3158 DBG("Thread exited with error");
3160 DBG("Worker thread cleanup complete");
3164 ERR("Health error occurred in %s", __func__
);
3166 health_unregister(health_relayd
);
3167 rcu_unregister_thread();
3168 lttng_relay_stop_threads();
3173 * Create the relay command pipe to wake thread_manage_apps.
3174 * Closed in cleanup().
3176 static int create_relay_conn_pipe(void)
3180 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
3188 int main(int argc
, char **argv
)
3190 int ret
= 0, retval
= 0;
3193 /* Parse environment variables */
3194 parse_env_options();
3198 * Command line arguments overwrite environment.
3201 if (set_options(argc
, argv
)) {
3206 if (set_signal_handler()) {
3211 /* Try to create directory if -o, --output is specified. */
3212 if (opt_output_path
) {
3213 if (*opt_output_path
!= '/') {
3214 ERR("Please specify an absolute path for -o, --output PATH");
3219 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
3222 ERR("Unable to create %s", opt_output_path
);
3229 if (opt_daemon
|| opt_background
) {
3232 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
3240 * We are in the child. Make sure all other file
3241 * descriptors are closed, in case we are called with
3242 * more opened file descriptors than the standard ones.
3244 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
3250 if (opt_working_directory
) {
3251 ret
= utils_change_working_dir(opt_working_directory
);
3253 ERR("Changing working directory");
3258 /* Initialize thread health monitoring */
3259 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
3260 if (!health_relayd
) {
3261 PERROR("health_app_create error");
3263 goto exit_health_app_create
;
3266 /* Create thread quit pipe */
3267 if (init_thread_quit_pipe()) {
3269 goto exit_init_data
;
3272 /* Setup the thread apps communication pipe. */
3273 if (create_relay_conn_pipe()) {
3275 goto exit_init_data
;
3278 /* Init relay command queue. */
3279 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
3281 /* Initialize communication library */
3283 lttcomm_inet_init();
3285 /* tables of sessions indexed by session ID */
3286 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3289 goto exit_init_data
;
3292 /* tables of streams indexed by stream ID */
3293 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3294 if (!relay_streams_ht
) {
3296 goto exit_init_data
;
3299 /* tables of streams indexed by stream ID */
3300 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
3301 if (!viewer_streams_ht
) {
3303 goto exit_init_data
;
3306 ret
= utils_create_pipe(health_quit_pipe
);
3309 goto exit_health_quit_pipe
;
3312 /* Create thread to manage the client socket */
3313 ret
= pthread_create(&health_thread
, default_pthread_attr(),
3314 thread_manage_health
, (void *) NULL
);
3317 PERROR("pthread_create health");
3319 goto exit_health_thread
;
3322 /* Setup the dispatcher thread */
3323 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
3324 relay_thread_dispatcher
, (void *) NULL
);
3327 PERROR("pthread_create dispatcher");
3329 goto exit_dispatcher_thread
;
3332 /* Setup the worker thread */
3333 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
3334 relay_thread_worker
, NULL
);
3337 PERROR("pthread_create worker");
3339 goto exit_worker_thread
;
3342 /* Setup the listener thread */
3343 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
3344 relay_thread_listener
, (void *) NULL
);
3347 PERROR("pthread_create listener");
3349 goto exit_listener_thread
;
3352 ret
= relayd_live_create(live_uri
);
3354 ERR("Starting live viewer threads");
3360 * This is where we start awaiting program completion (e.g. through
3361 * signal that asks threads to teardown).
3364 ret
= relayd_live_join();
3370 ret
= pthread_join(listener_thread
, &status
);
3373 PERROR("pthread_join listener_thread");
3377 exit_listener_thread
:
3378 ret
= pthread_join(worker_thread
, &status
);
3381 PERROR("pthread_join worker_thread");
3386 ret
= pthread_join(dispatcher_thread
, &status
);
3389 PERROR("pthread_join dispatcher_thread");
3392 exit_dispatcher_thread
:
3394 ret
= pthread_join(health_thread
, &status
);
3397 PERROR("pthread_join health_thread");
3402 utils_close_pipe(health_quit_pipe
);
3403 exit_health_quit_pipe
:
3406 health_app_destroy(health_relayd
);
3407 exit_health_app_create
:
3410 * Wait for all pending call_rcu work to complete before tearing
3411 * down data structures. call_rcu worker may be trying to
3412 * perform lookups in those structures.
3417 /* Ensure all prior call_rcu are done. */