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 <urcu/rculist.h>
61 #include "ctf-trace.h"
64 #include "lttng-relayd.h"
66 #include "health-relayd.h"
67 #include "testpoint.h"
68 #include "viewer-stream.h"
71 #include "connection.h"
72 #include "tracefile-array.h"
74 /* command line options */
75 char *opt_output_path
;
76 static int opt_daemon
, opt_background
;
79 * We need to wait for listener and live listener threads, as well as
80 * health check thread, before being ready to signal readiness.
82 #define NR_LTTNG_RELAY_READY 3
83 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
85 /* Size of receive buffer. */
86 #define RECV_DATA_BUFFER_SIZE 65536
88 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
89 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
91 static struct lttng_uri
*control_uri
;
92 static struct lttng_uri
*data_uri
;
93 static struct lttng_uri
*live_uri
;
97 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
98 static int tracing_group_name_override
;
100 const char * const config_section_name
= "relayd";
103 * Quit pipe for all threads. This permits a single cancellation point
104 * for all threads when receiving an event on the pipe.
106 int thread_quit_pipe
[2] = { -1, -1 };
109 * This pipe is used to inform the worker thread that a command is queued and
110 * ready to be processed.
112 static int relay_conn_pipe
[2] = { -1, -1 };
114 /* Shared between threads */
115 static int dispatch_thread_exit
;
117 static pthread_t listener_thread
;
118 static pthread_t dispatcher_thread
;
119 static pthread_t worker_thread
;
120 static pthread_t health_thread
;
123 * last_relay_stream_id_lock protects last_relay_stream_id increment
124 * atomicity on 32-bit architectures.
126 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
127 static uint64_t last_relay_stream_id
;
130 * Relay command queue.
132 * The relay_thread_listener and relay_thread_dispatcher communicate with this
135 static struct relay_conn_queue relay_conn_queue
;
137 /* buffer allocated at startup, used to store the trace data */
138 static char *data_buffer
;
139 static unsigned int data_buffer_size
;
141 /* Global relay stream hash table. */
142 struct lttng_ht
*relay_streams_ht
;
144 /* Global relay viewer stream hash table. */
145 struct lttng_ht
*viewer_streams_ht
;
147 /* Global relay sessions hash table. */
148 struct lttng_ht
*sessions_ht
;
150 /* Relayd health monitoring */
151 struct health_app
*health_relayd
;
153 static struct option long_options
[] = {
154 { "control-port", 1, 0, 'C', },
155 { "data-port", 1, 0, 'D', },
156 { "live-port", 1, 0, 'L', },
157 { "daemonize", 0, 0, 'd', },
158 { "background", 0, 0, 'b', },
159 { "group", 1, 0, 'g', },
160 { "help", 0, 0, 'h', },
161 { "output", 1, 0, 'o', },
162 { "verbose", 0, 0, 'v', },
163 { "config", 1, 0, 'f' },
164 { "version", 0, 0, 'V' },
168 static const char *config_ignore_options
[] = { "help", "config", "version" };
171 * Take an option from the getopt output and set it in the right variable to be
174 * Return 0 on success else a negative value.
176 static int set_option(int opt
, const char *arg
, const char *optname
)
182 fprintf(stderr
, "option %s", optname
);
184 fprintf(stderr
, " with arg %s\n", arg
);
188 if (lttng_is_setuid_setgid()) {
189 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
190 "-C, --control-port");
192 ret
= uri_parse(arg
, &control_uri
);
194 ERR("Invalid control URI specified");
197 if (control_uri
->port
== 0) {
198 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
203 if (lttng_is_setuid_setgid()) {
204 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
207 ret
= uri_parse(arg
, &data_uri
);
209 ERR("Invalid data URI specified");
212 if (data_uri
->port
== 0) {
213 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
218 if (lttng_is_setuid_setgid()) {
219 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
222 ret
= uri_parse(arg
, &live_uri
);
224 ERR("Invalid live URI specified");
227 if (live_uri
->port
== 0) {
228 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
239 if (lttng_is_setuid_setgid()) {
240 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
243 tracing_group_name
= strdup(arg
);
244 if (tracing_group_name
== NULL
) {
249 tracing_group_name_override
= 1;
253 ret
= utils_show_man_page(8, "lttng-relayd");
255 ERR("Cannot view man page lttng-relayd(8)");
260 fprintf(stdout
, "%s\n", VERSION
);
263 if (lttng_is_setuid_setgid()) {
264 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
267 ret
= asprintf(&opt_output_path
, "%s", arg
);
270 PERROR("asprintf opt_output_path");
276 /* Verbose level can increase using multiple -v */
278 lttng_opt_verbose
= config_parse_value(arg
);
280 /* Only 3 level of verbosity (-vvv). */
281 if (lttng_opt_verbose
< 3) {
282 lttng_opt_verbose
+= 1;
287 /* Unknown option or other error.
288 * Error is printed by getopt, just return */
301 * config_entry_handler_cb used to handle options read from a config file.
302 * See config_entry_handler_cb comment in common/config/session-config.h for the
303 * return value conventions.
305 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
309 if (!entry
|| !entry
->name
|| !entry
->value
) {
314 /* Check if the option is to be ignored */
315 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
316 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
321 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
322 /* Ignore if entry name is not fully matched. */
323 if (strcmp(entry
->name
, long_options
[i
].name
)) {
328 * If the option takes no argument on the command line,
329 * we have to check if the value is "true". We support
330 * non-zero numeric values, true, on and yes.
332 if (!long_options
[i
].has_arg
) {
333 ret
= config_parse_value(entry
->value
);
336 WARN("Invalid configuration value \"%s\" for option %s",
337 entry
->value
, entry
->name
);
339 /* False, skip boolean config option. */
344 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
348 WARN("Unrecognized option \"%s\" in daemon configuration file.",
355 static int set_options(int argc
, char **argv
)
357 int c
, ret
= 0, option_index
= 0, retval
= 0;
358 int orig_optopt
= optopt
, orig_optind
= optind
;
359 char *default_address
, *optstring
;
360 const char *config_path
= NULL
;
362 optstring
= utils_generate_optstring(long_options
,
363 sizeof(long_options
) / sizeof(struct option
));
369 /* Check for the --config option */
371 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
372 &option_index
)) != -1) {
376 } else if (c
!= 'f') {
380 if (lttng_is_setuid_setgid()) {
381 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
384 config_path
= utils_expand_path(optarg
);
386 ERR("Failed to resolve path: %s", optarg
);
391 ret
= config_get_section_entries(config_path
, config_section_name
,
392 config_entry_handler
, NULL
);
395 ERR("Invalid configuration option at line %i", ret
);
401 /* Reset getopt's global state */
402 optopt
= orig_optopt
;
403 optind
= orig_optind
;
405 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
410 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
417 /* assign default values */
418 if (control_uri
== NULL
) {
419 ret
= asprintf(&default_address
,
420 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
421 DEFAULT_NETWORK_CONTROL_PORT
);
423 PERROR("asprintf default data address");
428 ret
= uri_parse(default_address
, &control_uri
);
429 free(default_address
);
431 ERR("Invalid control URI specified");
436 if (data_uri
== NULL
) {
437 ret
= asprintf(&default_address
,
438 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
439 DEFAULT_NETWORK_DATA_PORT
);
441 PERROR("asprintf default data address");
446 ret
= uri_parse(default_address
, &data_uri
);
447 free(default_address
);
449 ERR("Invalid data URI specified");
454 if (live_uri
== NULL
) {
455 ret
= asprintf(&default_address
,
456 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
457 DEFAULT_NETWORK_VIEWER_PORT
);
459 PERROR("asprintf default viewer control address");
464 ret
= uri_parse(default_address
, &live_uri
);
465 free(default_address
);
467 ERR("Invalid viewer control URI specified");
478 static void print_global_objects(void)
480 rcu_register_thread();
482 print_viewer_streams();
483 print_relay_streams();
486 rcu_unregister_thread();
492 static void relayd_cleanup(void)
494 print_global_objects();
498 if (viewer_streams_ht
)
499 lttng_ht_destroy(viewer_streams_ht
);
500 if (relay_streams_ht
)
501 lttng_ht_destroy(relay_streams_ht
);
503 lttng_ht_destroy(sessions_ht
);
505 /* free the dynamically allocated opt_output_path */
506 free(opt_output_path
);
508 /* Close thread quit pipes */
509 utils_close_pipe(thread_quit_pipe
);
511 uri_free(control_uri
);
513 /* Live URI is freed in the live thread. */
515 if (tracing_group_name_override
) {
516 free((void *) tracing_group_name
);
521 * Write to writable pipe used to notify a thread.
523 static int notify_thread_pipe(int wpipe
)
527 ret
= lttng_write(wpipe
, "!", 1);
529 PERROR("write poll pipe");
537 static int notify_health_quit_pipe(int *pipe
)
541 ret
= lttng_write(pipe
[1], "4", 1);
543 PERROR("write relay health quit");
552 * Stop all relayd and relayd-live threads.
554 int lttng_relay_stop_threads(void)
558 /* Stopping all threads */
559 DBG("Terminating all threads");
560 if (notify_thread_pipe(thread_quit_pipe
[1])) {
561 ERR("write error on thread quit pipe");
565 if (notify_health_quit_pipe(health_quit_pipe
)) {
566 ERR("write error on health quit pipe");
569 /* Dispatch thread */
570 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
571 futex_nto1_wake(&relay_conn_queue
.futex
);
573 if (relayd_live_stop()) {
574 ERR("Error stopping live threads");
581 * Signal handler for the daemon
583 * Simply stop all worker threads, leaving main() return gracefully after
584 * joining all threads and calling cleanup().
586 static void sighandler(int sig
)
590 DBG("SIGINT caught");
591 if (lttng_relay_stop_threads()) {
592 ERR("Error stopping threads");
596 DBG("SIGTERM caught");
597 if (lttng_relay_stop_threads()) {
598 ERR("Error stopping threads");
602 CMM_STORE_SHARED(recv_child_signal
, 1);
610 * Setup signal handler for :
611 * SIGINT, SIGTERM, SIGPIPE
613 static int set_signal_handler(void)
619 if ((ret
= sigemptyset(&sigset
)) < 0) {
620 PERROR("sigemptyset");
627 sa
.sa_handler
= sighandler
;
628 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
633 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
638 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
643 sa
.sa_handler
= SIG_IGN
;
644 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
649 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
654 void lttng_relay_notify_ready(void)
656 /* Notify the parent of the fork() process that we are ready. */
657 if (opt_daemon
|| opt_background
) {
658 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
659 kill(child_ppid
, SIGUSR1
);
665 * Init thread quit pipe.
667 * Return -1 on error or 0 if all pipes are created.
669 static int init_thread_quit_pipe(void)
673 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
679 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
681 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
685 if (events
== NULL
|| size
== 0) {
690 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
696 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
708 * Check if the thread quit pipe was triggered.
710 * Return 1 if it was triggered else 0;
712 static int check_thread_quit_pipe(int fd
, uint32_t events
)
714 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
722 * Create and init socket from uri.
724 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
727 struct lttcomm_sock
*sock
= NULL
;
729 sock
= lttcomm_alloc_sock_from_uri(uri
);
731 ERR("Allocating socket");
735 ret
= lttcomm_create_sock(sock
);
739 DBG("Listening on sock %d", sock
->fd
);
741 ret
= sock
->ops
->bind(sock
);
746 ret
= sock
->ops
->listen(sock
, -1);
756 lttcomm_destroy_sock(sock
);
762 * This thread manages the listening for new connections on the network
764 static void *relay_thread_listener(void *data
)
766 int i
, ret
, pollfd
, err
= -1;
767 uint32_t revents
, nb_fd
;
768 struct lttng_poll_event events
;
769 struct lttcomm_sock
*control_sock
, *data_sock
;
771 DBG("[thread] Relay listener started");
773 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
775 health_code_update();
777 control_sock
= relay_socket_create(control_uri
);
779 goto error_sock_control
;
782 data_sock
= relay_socket_create(data_uri
);
784 goto error_sock_relay
;
788 * Pass 3 as size here for the thread quit pipe, control and
791 ret
= create_thread_poll_set(&events
, 3);
793 goto error_create_poll
;
796 /* Add the control socket */
797 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
802 /* Add the data socket */
803 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
808 lttng_relay_notify_ready();
810 if (testpoint(relayd_thread_listener
)) {
811 goto error_testpoint
;
815 health_code_update();
817 DBG("Listener accepting connections");
821 ret
= lttng_poll_wait(&events
, -1);
825 * Restart interrupted system call.
827 if (errno
== EINTR
) {
835 DBG("Relay new connection received");
836 for (i
= 0; i
< nb_fd
; i
++) {
837 health_code_update();
839 /* Fetch once the poll data */
840 revents
= LTTNG_POLL_GETEV(&events
, i
);
841 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
845 * No activity for this FD (poll
851 /* Thread quit pipe has been closed. Killing thread. */
852 ret
= check_thread_quit_pipe(pollfd
, revents
);
858 if (revents
& LPOLLIN
) {
860 * A new connection is requested, therefore a
861 * sessiond/consumerd connection is allocated in
862 * this thread, enqueued to a global queue and
863 * dequeued (and freed) in the worker thread.
866 struct relay_connection
*new_conn
;
867 struct lttcomm_sock
*newsock
;
868 enum connection_type type
;
870 if (pollfd
== data_sock
->fd
) {
872 newsock
= data_sock
->ops
->accept(data_sock
);
873 DBG("Relay data connection accepted, socket %d",
876 assert(pollfd
== control_sock
->fd
);
877 type
= RELAY_CONTROL
;
878 newsock
= control_sock
->ops
->accept(control_sock
);
879 DBG("Relay control connection accepted, socket %d",
883 PERROR("accepting sock");
887 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
890 PERROR("setsockopt inet");
891 lttcomm_destroy_sock(newsock
);
894 new_conn
= connection_create(newsock
, type
);
896 lttcomm_destroy_sock(newsock
);
900 /* Enqueue request for the dispatcher thread. */
901 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
905 * Wake the dispatch queue futex.
906 * Implicit memory barrier with the
907 * exchange in cds_wfcq_enqueue.
909 futex_nto1_wake(&relay_conn_queue
.futex
);
910 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
911 ERR("socket poll error");
914 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
924 lttng_poll_clean(&events
);
926 if (data_sock
->fd
>= 0) {
927 ret
= data_sock
->ops
->close(data_sock
);
932 lttcomm_destroy_sock(data_sock
);
934 if (control_sock
->fd
>= 0) {
935 ret
= control_sock
->ops
->close(control_sock
);
940 lttcomm_destroy_sock(control_sock
);
944 ERR("Health error occurred in %s", __func__
);
946 health_unregister(health_relayd
);
947 DBG("Relay listener thread cleanup complete");
948 lttng_relay_stop_threads();
953 * This thread manages the dispatching of the requests to worker threads
955 static void *relay_thread_dispatcher(void *data
)
959 struct cds_wfcq_node
*node
;
960 struct relay_connection
*new_conn
= NULL
;
962 DBG("[thread] Relay dispatcher started");
964 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
966 if (testpoint(relayd_thread_dispatcher
)) {
967 goto error_testpoint
;
970 health_code_update();
972 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
973 health_code_update();
975 /* Atomically prepare the queue futex */
976 futex_nto1_prepare(&relay_conn_queue
.futex
);
979 health_code_update();
981 /* Dequeue commands */
982 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
983 &relay_conn_queue
.tail
);
985 DBG("Woken up but nothing in the relay command queue");
986 /* Continue thread execution */
989 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
991 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
994 * Inform worker thread of the new request. This
995 * call is blocking so we can be assured that
996 * the data will be read at some point in time
997 * or wait to the end of the world :)
999 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1001 PERROR("write connection pipe");
1002 connection_put(new_conn
);
1005 } while (node
!= NULL
);
1007 /* Futex wait on queue. Blocking call on futex() */
1008 health_poll_entry();
1009 futex_nto1_wait(&relay_conn_queue
.futex
);
1013 /* Normal exit, no error */
1020 ERR("Health error occurred in %s", __func__
);
1022 health_unregister(health_relayd
);
1023 DBG("Dispatch thread dying");
1024 lttng_relay_stop_threads();
1029 * Set index data from the control port to a given index object.
1031 static int set_index_control_data(struct relay_index
*index
,
1032 struct lttcomm_relayd_index
*data
,
1033 struct relay_connection
*conn
)
1035 struct ctf_packet_index index_data
;
1038 * The index on disk is encoded in big endian, so we don't need
1039 * to convert the data received on the network. The data_offset
1040 * value is NEVER modified here and is updated by the data
1043 index_data
.packet_size
= data
->packet_size
;
1044 index_data
.content_size
= data
->content_size
;
1045 index_data
.timestamp_begin
= data
->timestamp_begin
;
1046 index_data
.timestamp_end
= data
->timestamp_end
;
1047 index_data
.events_discarded
= data
->events_discarded
;
1048 index_data
.stream_id
= data
->stream_id
;
1050 if (conn
->minor
>= 8) {
1051 index
->index_data
.stream_instance_id
= data
->stream_instance_id
;
1052 index
->index_data
.packet_seq_num
= data
->packet_seq_num
;
1055 return relay_index_set_data(index
, &index_data
);
1059 * Handle the RELAYD_CREATE_SESSION command.
1061 * On success, send back the session id or else return a negative value.
1063 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1064 struct relay_connection
*conn
)
1066 int ret
= 0, send_ret
;
1067 struct relay_session
*session
;
1068 struct lttcomm_relayd_status_session reply
;
1069 char session_name
[LTTNG_NAME_MAX
];
1070 char hostname
[LTTNG_HOST_NAME_MAX
];
1071 uint32_t live_timer
= 0;
1072 bool snapshot
= false;
1074 memset(session_name
, 0, LTTNG_NAME_MAX
);
1075 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1077 memset(&reply
, 0, sizeof(reply
));
1079 switch (conn
->minor
) {
1084 case 4: /* LTTng sessiond 2.4 */
1086 ret
= cmd_create_session_2_4(conn
, session_name
,
1087 hostname
, &live_timer
, &snapshot
);
1093 session
= session_create(session_name
, hostname
, live_timer
,
1094 snapshot
, conn
->major
, conn
->minor
);
1099 assert(!conn
->session
);
1100 conn
->session
= session
;
1101 DBG("Created session %" PRIu64
, session
->id
);
1103 reply
.session_id
= htobe64(session
->id
);
1107 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1109 reply
.ret_code
= htobe32(LTTNG_OK
);
1112 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1114 ERR("Relayd sending session id");
1122 * When we have received all the streams and the metadata for a channel,
1123 * we make them visible to the viewer threads.
1125 static void publish_connection_local_streams(struct relay_connection
*conn
)
1127 struct relay_stream
*stream
;
1128 struct relay_session
*session
= conn
->session
;
1131 * We publish all streams belonging to a session atomically wrt
1134 pthread_mutex_lock(&session
->lock
);
1136 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1138 stream_publish(stream
);
1143 * Inform the viewer that there are new streams in the session.
1145 if (session
->viewer_attached
) {
1146 uatomic_set(&session
->new_streams
, 1);
1148 pthread_mutex_unlock(&session
->lock
);
1152 * relay_add_stream: allocate a new stream for a session
1154 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1155 struct relay_connection
*conn
)
1159 struct relay_session
*session
= conn
->session
;
1160 struct relay_stream
*stream
= NULL
;
1161 struct lttcomm_relayd_status_stream reply
;
1162 struct ctf_trace
*trace
= NULL
;
1163 uint64_t stream_handle
= -1ULL;
1164 char *path_name
= NULL
, *channel_name
= NULL
;
1165 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1167 if (!session
|| conn
->version_check_done
== 0) {
1168 ERR("Trying to add a stream before version check");
1170 goto end_no_session
;
1173 switch (session
->minor
) {
1174 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1175 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1178 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1180 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1181 &channel_name
, &tracefile_size
, &tracefile_count
);
1188 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1192 /* This stream here has one reference on the trace. */
1194 pthread_mutex_lock(&last_relay_stream_id_lock
);
1195 stream_handle
= ++last_relay_stream_id
;
1196 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1198 /* We pass ownership of path_name and channel_name. */
1199 stream
= stream_create(trace
, stream_handle
, path_name
,
1200 channel_name
, tracefile_size
, tracefile_count
);
1202 channel_name
= NULL
;
1205 * Streams are the owners of their trace. Reference to trace is
1206 * kept within stream_create().
1208 ctf_trace_put(trace
);
1211 memset(&reply
, 0, sizeof(reply
));
1212 reply
.handle
= htobe64(stream_handle
);
1214 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1216 reply
.ret_code
= htobe32(LTTNG_OK
);
1219 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1220 sizeof(struct lttcomm_relayd_status_stream
), 0);
1222 ERR("Relay sending stream id");
1223 ret
= (int) send_ret
;
1233 * relay_close_stream: close a specific stream
1235 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1236 struct relay_connection
*conn
)
1239 struct relay_session
*session
= conn
->session
;
1240 struct lttcomm_relayd_close_stream stream_info
;
1241 struct lttcomm_relayd_generic_reply reply
;
1242 struct relay_stream
*stream
;
1244 DBG("Close stream received");
1246 if (!session
|| conn
->version_check_done
== 0) {
1247 ERR("Trying to close a stream before version check");
1249 goto end_no_session
;
1252 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1253 sizeof(struct lttcomm_relayd_close_stream
), 0);
1254 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1256 /* Orderly shutdown. Not necessary to print an error. */
1257 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1259 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1262 goto end_no_session
;
1265 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1272 * Set last_net_seq_num before the close flag. Required by data
1275 pthread_mutex_lock(&stream
->lock
);
1276 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1277 pthread_mutex_unlock(&stream
->lock
);
1280 * This is one of the conditions which may trigger a stream close
1281 * with the others being:
1282 * 1) A close command is received for a stream
1283 * 2) The control connection owning the stream is closed
1284 * 3) We have received all of the stream's data _after_ a close
1287 try_stream_close(stream
);
1288 if (stream
->is_metadata
) {
1289 struct relay_viewer_stream
*vstream
;
1291 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1293 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1295 * Since all the metadata has been sent to the
1296 * viewer and that we have a request to close
1297 * its stream, we can safely teardown the
1298 * corresponding metadata viewer stream.
1300 viewer_stream_put(vstream
);
1302 /* Put local reference. */
1303 viewer_stream_put(vstream
);
1309 memset(&reply
, 0, sizeof(reply
));
1311 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1313 reply
.ret_code
= htobe32(LTTNG_OK
);
1315 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1316 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1318 ERR("Relay sending stream id");
1327 * relay_reset_metadata: reset a metadata stream
1330 int relay_reset_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1331 struct relay_connection
*conn
)
1334 struct relay_session
*session
= conn
->session
;
1335 struct lttcomm_relayd_reset_metadata stream_info
;
1336 struct lttcomm_relayd_generic_reply reply
;
1337 struct relay_stream
*stream
;
1339 DBG("Reset metadata received");
1341 if (!session
|| conn
->version_check_done
== 0) {
1342 ERR("Trying to reset a metadata stream before version check");
1344 goto end_no_session
;
1347 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1348 sizeof(struct lttcomm_relayd_reset_metadata
), 0);
1349 if (ret
< sizeof(struct lttcomm_relayd_reset_metadata
)) {
1351 /* Orderly shutdown. Not necessary to print an error. */
1352 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1354 ERR("Relay didn't receive valid reset_metadata struct "
1358 goto end_no_session
;
1360 DBG("Update metadata to version %" PRIu64
, be64toh(stream_info
.version
));
1362 /* Unsupported for live sessions for now. */
1363 if (session
->live_timer
!= 0) {
1368 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1373 pthread_mutex_lock(&stream
->lock
);
1374 if (!stream
->is_metadata
) {
1379 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
1380 0, 0, -1, -1, stream
->stream_fd
->fd
, NULL
,
1381 &stream
->stream_fd
->fd
);
1383 ERR("Failed to rotate metadata file %s of channel %s",
1384 stream
->path_name
, stream
->channel_name
);
1389 pthread_mutex_unlock(&stream
->lock
);
1393 memset(&reply
, 0, sizeof(reply
));
1395 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1397 reply
.ret_code
= htobe32(LTTNG_OK
);
1399 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1400 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1402 ERR("Relay sending reset metadata reply");
1411 * relay_unknown_command: send -1 if received unknown command
1413 static void relay_unknown_command(struct relay_connection
*conn
)
1415 struct lttcomm_relayd_generic_reply reply
;
1418 memset(&reply
, 0, sizeof(reply
));
1419 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1420 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1421 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1423 ERR("Relay sending unknown command");
1428 * relay_start: send an acknowledgment to the client to tell if we are
1429 * ready to receive data. We are ready if a session is established.
1431 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1432 struct relay_connection
*conn
)
1434 int ret
= htobe32(LTTNG_OK
);
1435 struct lttcomm_relayd_generic_reply reply
;
1436 struct relay_session
*session
= conn
->session
;
1439 DBG("Trying to start the streaming without a session established");
1440 ret
= htobe32(LTTNG_ERR_UNK
);
1443 memset(&reply
, 0, sizeof(reply
));
1444 reply
.ret_code
= ret
;
1445 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1446 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1448 ERR("Relay sending start ack");
1455 * Append padding to the file pointed by the file descriptor fd.
1457 static int write_padding_to_file(int fd
, uint32_t size
)
1466 zeros
= zmalloc(size
);
1467 if (zeros
== NULL
) {
1468 PERROR("zmalloc zeros for padding");
1473 ret
= lttng_write(fd
, zeros
, size
);
1475 PERROR("write padding to file");
1485 * relay_recv_metadata: receive the metadata for the session.
1487 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1488 struct relay_connection
*conn
)
1492 struct relay_session
*session
= conn
->session
;
1493 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1494 struct relay_stream
*metadata_stream
;
1495 uint64_t data_size
, payload_size
;
1498 ERR("Metadata sent before version check");
1503 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1504 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1505 ERR("Incorrect data size");
1509 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1511 if (data_buffer_size
< data_size
) {
1512 /* In case the realloc fails, we can free the memory */
1515 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1516 if (!tmp_data_ptr
) {
1517 ERR("Allocating data buffer");
1522 data_buffer
= tmp_data_ptr
;
1523 data_buffer_size
= data_size
;
1525 memset(data_buffer
, 0, data_size
);
1526 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1527 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1528 if (size_ret
< 0 || size_ret
!= data_size
) {
1529 if (size_ret
== 0) {
1530 /* Orderly shutdown. Not necessary to print an error. */
1531 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1533 ERR("Relay didn't receive the whole metadata");
1538 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1540 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1541 if (!metadata_stream
) {
1546 pthread_mutex_lock(&metadata_stream
->lock
);
1548 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1550 if (size_ret
< payload_size
) {
1551 ERR("Relay error writing metadata on file");
1556 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1557 be32toh(metadata_struct
->padding_size
));
1562 metadata_stream
->metadata_received
+=
1563 payload_size
+ be32toh(metadata_struct
->padding_size
);
1564 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1565 metadata_stream
->metadata_received
);
1568 pthread_mutex_unlock(&metadata_stream
->lock
);
1569 stream_put(metadata_stream
);
1575 * relay_send_version: send relayd version number
1577 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1578 struct relay_connection
*conn
)
1581 struct lttcomm_relayd_version reply
, msg
;
1583 conn
->version_check_done
= 1;
1585 /* Get version from the other side. */
1586 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1587 if (ret
< 0 || ret
!= sizeof(msg
)) {
1589 /* Orderly shutdown. Not necessary to print an error. */
1590 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1592 ERR("Relay failed to receive the version values.");
1598 memset(&reply
, 0, sizeof(reply
));
1599 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1600 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1602 /* Major versions must be the same */
1603 if (reply
.major
!= be32toh(msg
.major
)) {
1604 DBG("Incompatible major versions (%u vs %u), deleting session",
1605 reply
.major
, be32toh(msg
.major
));
1606 connection_put(conn
);
1611 conn
->major
= reply
.major
;
1612 /* We adapt to the lowest compatible version */
1613 if (reply
.minor
<= be32toh(msg
.minor
)) {
1614 conn
->minor
= reply
.minor
;
1616 conn
->minor
= be32toh(msg
.minor
);
1619 reply
.major
= htobe32(reply
.major
);
1620 reply
.minor
= htobe32(reply
.minor
);
1621 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1622 sizeof(struct lttcomm_relayd_version
), 0);
1624 ERR("Relay sending version");
1627 DBG("Version check done using protocol %u.%u", conn
->major
,
1635 * Check for data pending for a given stream id from the session daemon.
1637 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1638 struct relay_connection
*conn
)
1640 struct relay_session
*session
= conn
->session
;
1641 struct lttcomm_relayd_data_pending msg
;
1642 struct lttcomm_relayd_generic_reply reply
;
1643 struct relay_stream
*stream
;
1645 uint64_t last_net_seq_num
, stream_id
;
1647 DBG("Data pending command received");
1649 if (!session
|| conn
->version_check_done
== 0) {
1650 ERR("Trying to check for data before version check");
1652 goto end_no_session
;
1655 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1656 if (ret
< sizeof(msg
)) {
1658 /* Orderly shutdown. Not necessary to print an error. */
1659 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1661 ERR("Relay didn't receive valid data_pending struct size : %d",
1665 goto end_no_session
;
1668 stream_id
= be64toh(msg
.stream_id
);
1669 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1671 stream
= stream_get_by_id(stream_id
);
1672 if (stream
== NULL
) {
1677 pthread_mutex_lock(&stream
->lock
);
1679 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1680 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1683 /* Avoid wrapping issue */
1684 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1685 /* Data has in fact been written and is NOT pending */
1688 /* Data still being streamed thus pending */
1692 stream
->data_pending_check_done
= true;
1693 pthread_mutex_unlock(&stream
->lock
);
1698 memset(&reply
, 0, sizeof(reply
));
1699 reply
.ret_code
= htobe32(ret
);
1700 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1702 ERR("Relay data pending ret code failed");
1710 * Wait for the control socket to reach a quiescent state.
1712 * Note that for now, when receiving this command from the session
1713 * daemon, this means that every subsequent commands or data received on
1714 * the control socket has been handled. So, this is why we simply return
1717 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1718 struct relay_connection
*conn
)
1722 struct relay_stream
*stream
;
1723 struct lttcomm_relayd_quiescent_control msg
;
1724 struct lttcomm_relayd_generic_reply reply
;
1726 DBG("Checking quiescent state on control socket");
1728 if (!conn
->session
|| conn
->version_check_done
== 0) {
1729 ERR("Trying to check for data before version check");
1731 goto end_no_session
;
1734 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1735 if (ret
< sizeof(msg
)) {
1737 /* Orderly shutdown. Not necessary to print an error. */
1738 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1740 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1744 goto end_no_session
;
1747 stream_id
= be64toh(msg
.stream_id
);
1748 stream
= stream_get_by_id(stream_id
);
1752 pthread_mutex_lock(&stream
->lock
);
1753 stream
->data_pending_check_done
= true;
1754 pthread_mutex_unlock(&stream
->lock
);
1755 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1758 memset(&reply
, 0, sizeof(reply
));
1759 reply
.ret_code
= htobe32(LTTNG_OK
);
1760 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1762 ERR("Relay data quiescent control ret code failed");
1770 * Initialize a data pending command. This means that a consumer is about
1771 * to ask for data pending for each stream it holds. Simply iterate over
1772 * all streams of a session and set the data_pending_check_done flag.
1774 * This command returns to the client a LTTNG_OK code.
1776 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1777 struct relay_connection
*conn
)
1780 struct lttng_ht_iter iter
;
1781 struct lttcomm_relayd_begin_data_pending msg
;
1782 struct lttcomm_relayd_generic_reply reply
;
1783 struct relay_stream
*stream
;
1784 uint64_t session_id
;
1789 DBG("Init streams for data pending");
1791 if (!conn
->session
|| conn
->version_check_done
== 0) {
1792 ERR("Trying to check for data before version check");
1794 goto end_no_session
;
1797 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1798 if (ret
< sizeof(msg
)) {
1800 /* Orderly shutdown. Not necessary to print an error. */
1801 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1803 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1807 goto end_no_session
;
1810 session_id
= be64toh(msg
.session_id
);
1813 * Iterate over all streams to set the begin data pending flag.
1814 * For now, the streams are indexed by stream handle so we have
1815 * to iterate over all streams to find the one associated with
1816 * the right session_id.
1819 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1821 if (!stream_get(stream
)) {
1824 if (stream
->trace
->session
->id
== session_id
) {
1825 pthread_mutex_lock(&stream
->lock
);
1826 stream
->data_pending_check_done
= false;
1827 pthread_mutex_unlock(&stream
->lock
);
1828 DBG("Set begin data pending flag to stream %" PRIu64
,
1829 stream
->stream_handle
);
1835 memset(&reply
, 0, sizeof(reply
));
1836 /* All good, send back reply. */
1837 reply
.ret_code
= htobe32(LTTNG_OK
);
1839 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1841 ERR("Relay begin data pending send reply failed");
1849 * End data pending command. This will check, for a given session id, if
1850 * each stream associated with it has its data_pending_check_done flag
1851 * set. If not, this means that the client lost track of the stream but
1852 * the data is still being streamed on our side. In this case, we inform
1853 * the client that data is in flight.
1855 * Return to the client if there is data in flight or not with a ret_code.
1857 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1858 struct relay_connection
*conn
)
1861 struct lttng_ht_iter iter
;
1862 struct lttcomm_relayd_end_data_pending msg
;
1863 struct lttcomm_relayd_generic_reply reply
;
1864 struct relay_stream
*stream
;
1865 uint64_t session_id
;
1866 uint32_t is_data_inflight
= 0;
1868 DBG("End data pending command");
1870 if (!conn
->session
|| conn
->version_check_done
== 0) {
1871 ERR("Trying to check for data before version check");
1873 goto end_no_session
;
1876 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1877 if (ret
< sizeof(msg
)) {
1879 /* Orderly shutdown. Not necessary to print an error. */
1880 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1882 ERR("Relay didn't receive valid end data_pending struct size: %d",
1886 goto end_no_session
;
1889 session_id
= be64toh(msg
.session_id
);
1892 * Iterate over all streams to see if the begin data pending
1896 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1898 if (!stream_get(stream
)) {
1901 if (stream
->trace
->session
->id
!= session_id
) {
1905 pthread_mutex_lock(&stream
->lock
);
1906 if (!stream
->data_pending_check_done
) {
1907 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1908 is_data_inflight
= 1;
1909 DBG("Data is still in flight for stream %" PRIu64
,
1910 stream
->stream_handle
);
1911 pthread_mutex_unlock(&stream
->lock
);
1916 pthread_mutex_unlock(&stream
->lock
);
1921 memset(&reply
, 0, sizeof(reply
));
1922 /* All good, send back reply. */
1923 reply
.ret_code
= htobe32(is_data_inflight
);
1925 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1927 ERR("Relay end data pending send reply failed");
1935 * Receive an index for a specific stream.
1937 * Return 0 on success else a negative value.
1939 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1940 struct relay_connection
*conn
)
1943 struct relay_session
*session
= conn
->session
;
1944 struct lttcomm_relayd_index index_info
;
1945 struct relay_index
*index
;
1946 struct lttcomm_relayd_generic_reply reply
;
1947 struct relay_stream
*stream
;
1948 uint64_t net_seq_num
;
1952 DBG("Relay receiving index");
1954 if (!session
|| conn
->version_check_done
== 0) {
1955 ERR("Trying to close a stream before version check");
1957 goto end_no_session
;
1960 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1961 sizeof(index_info
), 0);
1962 if (ret
< sizeof(index_info
)) {
1964 /* Orderly shutdown. Not necessary to print an error. */
1965 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1967 ERR("Relay didn't receive valid index struct size : %d", ret
);
1970 goto end_no_session
;
1973 net_seq_num
= be64toh(index_info
.net_seq_num
);
1975 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1977 ERR("stream_get_by_id not found");
1981 pthread_mutex_lock(&stream
->lock
);
1983 /* Live beacon handling */
1984 if (index_info
.packet_size
== 0) {
1985 DBG("Received live beacon for stream %" PRIu64
,
1986 stream
->stream_handle
);
1989 * Only flag a stream inactive when it has already
1990 * received data and no indexes are in flight.
1992 if (stream
->index_received_seqcount
> 0
1993 && stream
->indexes_in_flight
== 0) {
1994 stream
->beacon_ts_end
=
1995 be64toh(index_info
.timestamp_end
);
1998 goto end_stream_put
;
2000 stream
->beacon_ts_end
= -1ULL;
2003 if (stream
->ctf_stream_id
== -1ULL) {
2004 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
2006 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2009 ERR("relay_index_get_by_id_or_create index NULL");
2010 goto end_stream_put
;
2012 if (set_index_control_data(index
, &index_info
, conn
)) {
2013 ERR("set_index_control_data error");
2014 relay_index_put(index
);
2016 goto end_stream_put
;
2018 ret
= relay_index_try_flush(index
);
2020 tracefile_array_commit_seq(stream
->tfa
);
2021 stream
->index_received_seqcount
++;
2022 } else if (ret
> 0) {
2026 ERR("relay_index_try_flush error %d", ret
);
2027 relay_index_put(index
);
2032 pthread_mutex_unlock(&stream
->lock
);
2037 memset(&reply
, 0, sizeof(reply
));
2039 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2041 reply
.ret_code
= htobe32(LTTNG_OK
);
2043 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2045 ERR("Relay sending close index id reply");
2054 * Receive the streams_sent message.
2056 * Return 0 on success else a negative value.
2058 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
2059 struct relay_connection
*conn
)
2062 struct lttcomm_relayd_generic_reply reply
;
2066 DBG("Relay receiving streams_sent");
2068 if (!conn
->session
|| conn
->version_check_done
== 0) {
2069 ERR("Trying to close a stream before version check");
2071 goto end_no_session
;
2075 * Publish every pending stream in the connection recv list which are
2076 * now ready to be used by the viewer.
2078 publish_connection_local_streams(conn
);
2080 memset(&reply
, 0, sizeof(reply
));
2081 reply
.ret_code
= htobe32(LTTNG_OK
);
2082 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2084 ERR("Relay sending sent_stream reply");
2096 * Process the commands received on the control socket
2098 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2099 struct relay_connection
*conn
)
2103 switch (be32toh(recv_hdr
->cmd
)) {
2104 case RELAYD_CREATE_SESSION
:
2105 ret
= relay_create_session(recv_hdr
, conn
);
2107 case RELAYD_ADD_STREAM
:
2108 ret
= relay_add_stream(recv_hdr
, conn
);
2110 case RELAYD_START_DATA
:
2111 ret
= relay_start(recv_hdr
, conn
);
2113 case RELAYD_SEND_METADATA
:
2114 ret
= relay_recv_metadata(recv_hdr
, conn
);
2116 case RELAYD_VERSION
:
2117 ret
= relay_send_version(recv_hdr
, conn
);
2119 case RELAYD_CLOSE_STREAM
:
2120 ret
= relay_close_stream(recv_hdr
, conn
);
2122 case RELAYD_DATA_PENDING
:
2123 ret
= relay_data_pending(recv_hdr
, conn
);
2125 case RELAYD_QUIESCENT_CONTROL
:
2126 ret
= relay_quiescent_control(recv_hdr
, conn
);
2128 case RELAYD_BEGIN_DATA_PENDING
:
2129 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2131 case RELAYD_END_DATA_PENDING
:
2132 ret
= relay_end_data_pending(recv_hdr
, conn
);
2134 case RELAYD_SEND_INDEX
:
2135 ret
= relay_recv_index(recv_hdr
, conn
);
2137 case RELAYD_STREAMS_SENT
:
2138 ret
= relay_streams_sent(recv_hdr
, conn
);
2140 case RELAYD_RESET_METADATA
:
2141 ret
= relay_reset_metadata(recv_hdr
, conn
);
2143 case RELAYD_UPDATE_SYNC_INFO
:
2145 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2146 relay_unknown_command(conn
);
2156 * Handle index for a data stream.
2158 * Called with the stream lock held.
2160 * Return 0 on success else a negative value.
2162 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2166 uint64_t data_offset
;
2167 struct relay_index
*index
;
2169 /* Get data offset because we are about to update the index. */
2170 data_offset
= htobe64(stream
->tracefile_size_current
);
2172 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2173 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2176 * Lookup for an existing index for that stream id/sequence
2177 * number. If it exists, the control thread has already received the
2178 * data for it, thus we need to write it to disk.
2180 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2186 if (rotate_index
|| !stream
->index_fd
) {
2189 /* Put ref on previous index_fd. */
2190 if (stream
->index_fd
) {
2191 stream_fd_put(stream
->index_fd
);
2192 stream
->index_fd
= NULL
;
2195 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2196 -1, -1, stream
->tracefile_size
,
2197 tracefile_array_get_file_index_head(stream
->tfa
));
2200 /* Put self-ref for this index due to error. */
2201 relay_index_put(index
);
2204 stream
->index_fd
= stream_fd_create(fd
);
2205 if (!stream
->index_fd
) {
2208 PERROR("Error closing FD %d", fd
);
2210 /* Put self-ref for this index due to error. */
2211 relay_index_put(index
);
2212 /* Will put the local ref. */
2217 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2219 /* Put self-ref for this index due to error. */
2220 relay_index_put(index
);
2224 ret
= relay_index_try_flush(index
);
2226 tracefile_array_commit_seq(stream
->tfa
);
2227 stream
->index_received_seqcount
++;
2228 } else if (ret
> 0) {
2232 /* Put self-ref for this index due to error. */
2233 relay_index_put(index
);
2241 * relay_process_data: Process the data received on the data socket
2243 static int relay_process_data(struct relay_connection
*conn
)
2245 int ret
= 0, rotate_index
= 0;
2247 struct relay_stream
*stream
;
2248 struct lttcomm_relayd_data_hdr data_hdr
;
2250 uint64_t net_seq_num
;
2252 struct relay_session
*session
;
2253 bool new_stream
= false, close_requested
= false;
2254 size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2255 size_t recv_off
= 0;
2256 char data_buffer
[chunk_size
];
2258 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2259 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2262 /* Orderly shutdown. Not necessary to print an error. */
2263 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2265 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2271 stream_id
= be64toh(data_hdr
.stream_id
);
2272 stream
= stream_get_by_id(stream_id
);
2274 ERR("relay_process_data: Cannot find stream %" PRIu64
, stream_id
);
2278 session
= stream
->trace
->session
;
2279 data_size
= be32toh(data_hdr
.data_size
);
2281 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2283 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2284 data_size
, stream_id
, net_seq_num
);
2286 pthread_mutex_lock(&stream
->lock
);
2288 /* Check if a rotation is needed. */
2289 if (stream
->tracefile_size
> 0 &&
2290 (stream
->tracefile_size_current
+ data_size
) >
2291 stream
->tracefile_size
) {
2292 uint64_t old_id
, new_id
;
2294 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2295 tracefile_array_file_rotate(stream
->tfa
);
2297 /* new_id is updated by utils_rotate_stream_file. */
2300 ret
= utils_rotate_stream_file(stream
->path_name
,
2301 stream
->channel_name
, stream
->tracefile_size
,
2302 stream
->tracefile_count
, -1,
2303 -1, stream
->stream_fd
->fd
,
2304 &new_id
, &stream
->stream_fd
->fd
);
2306 ERR("Rotating stream output file");
2307 goto end_stream_unlock
;
2310 * Reset current size because we just performed a stream
2313 stream
->tracefile_size_current
= 0;
2318 * Index are handled in protocol version 2.4 and above. Also,
2319 * snapshot and index are NOT supported.
2321 if (session
->minor
>= 4 && !session
->snapshot
) {
2322 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2324 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2325 stream
->stream_handle
, net_seq_num
, ret
);
2326 goto end_stream_unlock
;
2330 for (recv_off
= 0; recv_off
< data_size
; recv_off
+= chunk_size
) {
2331 size_t recv_size
= min(data_size
- recv_off
, chunk_size
);
2333 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, 0);
2336 /* Orderly shutdown. Not necessary to print an error. */
2337 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2339 ERR("Socket %d error %d", conn
->sock
->fd
, ret
);
2342 goto end_stream_unlock
;
2345 /* Write data to stream output fd. */
2346 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2348 if (size_ret
< recv_size
) {
2349 ERR("Relay error writing data to file");
2351 goto end_stream_unlock
;
2354 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2355 size_ret
, stream
->stream_handle
);
2358 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2359 be32toh(data_hdr
.padding_size
));
2361 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2362 stream
->stream_handle
, net_seq_num
, ret
);
2363 goto end_stream_unlock
;
2365 stream
->tracefile_size_current
+=
2366 data_size
+ be32toh(data_hdr
.padding_size
);
2367 if (stream
->prev_seq
== -1ULL) {
2371 stream
->prev_seq
= net_seq_num
;
2374 close_requested
= stream
->close_requested
;
2375 pthread_mutex_unlock(&stream
->lock
);
2376 if (close_requested
) {
2377 try_stream_close(stream
);
2381 pthread_mutex_lock(&session
->lock
);
2382 uatomic_set(&session
->new_streams
, 1);
2383 pthread_mutex_unlock(&session
->lock
);
2390 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2394 (void) lttng_poll_del(events
, pollfd
);
2396 ret
= close(pollfd
);
2398 ERR("Closing pollfd %d", pollfd
);
2402 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2403 int pollfd
, struct relay_connection
*conn
)
2405 const char *type_str
;
2407 switch (conn
->type
) {
2412 type_str
= "Control";
2414 case RELAY_VIEWER_COMMAND
:
2415 type_str
= "Viewer Command";
2417 case RELAY_VIEWER_NOTIFICATION
:
2418 type_str
= "Viewer Notification";
2421 type_str
= "Unknown";
2423 cleanup_connection_pollfd(events
, pollfd
);
2424 connection_put(conn
);
2425 DBG("%s connection closed with %d", type_str
, pollfd
);
2429 * This thread does the actual work
2431 static void *relay_thread_worker(void *data
)
2433 int ret
, err
= -1, last_seen_data_fd
= -1;
2435 struct lttng_poll_event events
;
2436 struct lttng_ht
*relay_connections_ht
;
2437 struct lttng_ht_iter iter
;
2438 struct lttcomm_relayd_hdr recv_hdr
;
2439 struct relay_connection
*destroy_conn
= NULL
;
2441 DBG("[thread] Relay worker started");
2443 rcu_register_thread();
2445 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2447 if (testpoint(relayd_thread_worker
)) {
2448 goto error_testpoint
;
2451 health_code_update();
2453 /* table of connections indexed on socket */
2454 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2455 if (!relay_connections_ht
) {
2456 goto relay_connections_ht_error
;
2459 ret
= create_thread_poll_set(&events
, 2);
2461 goto error_poll_create
;
2464 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2471 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2473 health_code_update();
2475 /* Infinite blocking call, waiting for transmission */
2476 DBG3("Relayd worker thread polling...");
2477 health_poll_entry();
2478 ret
= lttng_poll_wait(&events
, -1);
2482 * Restart interrupted system call.
2484 if (errno
== EINTR
) {
2493 * Process control. The control connection is
2494 * prioritized so we don't starve it with high
2495 * throughput tracing data on the data connection.
2497 for (i
= 0; i
< nb_fd
; i
++) {
2498 /* Fetch once the poll data */
2499 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2500 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2502 health_code_update();
2506 * No activity for this FD (poll
2512 /* Thread quit pipe has been closed. Killing thread. */
2513 ret
= check_thread_quit_pipe(pollfd
, revents
);
2519 /* Inspect the relay conn pipe for new connection */
2520 if (pollfd
== relay_conn_pipe
[0]) {
2521 if (revents
& LPOLLIN
) {
2522 struct relay_connection
*conn
;
2524 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2528 lttng_poll_add(&events
, conn
->sock
->fd
,
2529 LPOLLIN
| LPOLLRDHUP
);
2530 connection_ht_add(relay_connections_ht
, conn
);
2531 DBG("Connection socket %d added", conn
->sock
->fd
);
2532 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2533 ERR("Relay connection pipe error");
2536 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2540 struct relay_connection
*ctrl_conn
;
2542 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2543 /* If not found, there is a synchronization issue. */
2546 if (ctrl_conn
->type
== RELAY_DATA
) {
2547 if (revents
& LPOLLIN
) {
2549 * Flag the last seen data fd not deleted. It will be
2550 * used as the last seen fd if any fd gets deleted in
2553 last_notdel_data_fd
= pollfd
;
2555 goto put_ctrl_connection
;
2557 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2559 if (revents
& LPOLLIN
) {
2560 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2561 &recv_hdr
, sizeof(recv_hdr
), 0);
2563 /* Connection closed */
2564 relay_thread_close_connection(&events
, pollfd
,
2567 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2569 /* Clear the session on error. */
2570 relay_thread_close_connection(&events
,
2575 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2576 relay_thread_close_connection(&events
,
2578 if (last_seen_data_fd
== pollfd
) {
2579 last_seen_data_fd
= last_notdel_data_fd
;
2582 ERR("Unexpected poll events %u for control sock %d",
2584 connection_put(ctrl_conn
);
2587 put_ctrl_connection
:
2588 connection_put(ctrl_conn
);
2593 * The last loop handled a control request, go back to poll to make
2594 * sure we prioritise the control socket.
2600 if (last_seen_data_fd
>= 0) {
2601 for (i
= 0; i
< nb_fd
; i
++) {
2602 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2604 health_code_update();
2606 if (last_seen_data_fd
== pollfd
) {
2613 /* Process data connection. */
2614 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2615 /* Fetch the poll data. */
2616 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2617 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2618 struct relay_connection
*data_conn
;
2620 health_code_update();
2623 /* No activity for this FD (poll implementation). */
2627 /* Skip the command pipe. It's handled in the first loop. */
2628 if (pollfd
== relay_conn_pipe
[0]) {
2632 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2634 /* Skip it. Might be removed before. */
2637 if (data_conn
->type
== RELAY_CONTROL
) {
2638 goto put_data_connection
;
2640 assert(data_conn
->type
== RELAY_DATA
);
2642 if (revents
& LPOLLIN
) {
2643 ret
= relay_process_data(data_conn
);
2644 /* Connection closed */
2646 relay_thread_close_connection(&events
, pollfd
,
2649 * Every goto restart call sets the last seen fd where
2650 * here we don't really care since we gracefully
2651 * continue the loop after the connection is deleted.
2654 /* Keep last seen port. */
2655 last_seen_data_fd
= pollfd
;
2656 connection_put(data_conn
);
2659 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2660 relay_thread_close_connection(&events
, pollfd
,
2663 ERR("Unknown poll events %u for data sock %d",
2666 put_data_connection
:
2667 connection_put(data_conn
);
2669 last_seen_data_fd
= -1;
2672 /* Normal exit, no error */
2677 /* Cleanup reamaining connection object. */
2679 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2682 health_code_update();
2684 * No need to grab another ref, because we own
2687 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2692 lttng_poll_clean(&events
);
2694 lttng_ht_destroy(relay_connections_ht
);
2695 relay_connections_ht_error
:
2696 /* Close relay conn pipes */
2697 utils_close_pipe(relay_conn_pipe
);
2699 DBG("Thread exited with error");
2701 DBG("Worker thread cleanup complete");
2705 ERR("Health error occurred in %s", __func__
);
2707 health_unregister(health_relayd
);
2708 rcu_unregister_thread();
2709 lttng_relay_stop_threads();
2714 * Create the relay command pipe to wake thread_manage_apps.
2715 * Closed in cleanup().
2717 static int create_relay_conn_pipe(void)
2721 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2729 int main(int argc
, char **argv
)
2731 int ret
= 0, retval
= 0;
2734 /* Parse arguments */
2736 if (set_options(argc
, argv
)) {
2741 if (set_signal_handler()) {
2746 /* Try to create directory if -o, --output is specified. */
2747 if (opt_output_path
) {
2748 if (*opt_output_path
!= '/') {
2749 ERR("Please specify an absolute path for -o, --output PATH");
2754 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2757 ERR("Unable to create %s", opt_output_path
);
2764 if (opt_daemon
|| opt_background
) {
2767 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2775 * We are in the child. Make sure all other file
2776 * descriptors are closed, in case we are called with
2777 * more opened file descriptors than the standard ones.
2779 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2784 /* Initialize thread health monitoring */
2785 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2786 if (!health_relayd
) {
2787 PERROR("health_app_create error");
2789 goto exit_health_app_create
;
2792 /* Create thread quit pipe */
2793 if (init_thread_quit_pipe()) {
2795 goto exit_init_data
;
2798 /* Setup the thread apps communication pipe. */
2799 if (create_relay_conn_pipe()) {
2801 goto exit_init_data
;
2804 /* Init relay command queue. */
2805 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2807 /* Initialize communication library */
2809 lttcomm_inet_init();
2811 /* tables of sessions indexed by session ID */
2812 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2815 goto exit_init_data
;
2818 /* tables of streams indexed by stream ID */
2819 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2820 if (!relay_streams_ht
) {
2822 goto exit_init_data
;
2825 /* tables of streams indexed by stream ID */
2826 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2827 if (!viewer_streams_ht
) {
2829 goto exit_init_data
;
2832 ret
= utils_create_pipe(health_quit_pipe
);
2835 goto exit_health_quit_pipe
;
2838 /* Create thread to manage the client socket */
2839 ret
= pthread_create(&health_thread
, default_pthread_attr(),
2840 thread_manage_health
, (void *) NULL
);
2843 PERROR("pthread_create health");
2845 goto exit_health_thread
;
2848 /* Setup the dispatcher thread */
2849 ret
= pthread_create(&dispatcher_thread
, default_pthread_attr(),
2850 relay_thread_dispatcher
, (void *) NULL
);
2853 PERROR("pthread_create dispatcher");
2855 goto exit_dispatcher_thread
;
2858 /* Setup the worker thread */
2859 ret
= pthread_create(&worker_thread
, default_pthread_attr(),
2860 relay_thread_worker
, NULL
);
2863 PERROR("pthread_create worker");
2865 goto exit_worker_thread
;
2868 /* Setup the listener thread */
2869 ret
= pthread_create(&listener_thread
, default_pthread_attr(),
2870 relay_thread_listener
, (void *) NULL
);
2873 PERROR("pthread_create listener");
2875 goto exit_listener_thread
;
2878 ret
= relayd_live_create(live_uri
);
2880 ERR("Starting live viewer threads");
2886 * This is where we start awaiting program completion (e.g. through
2887 * signal that asks threads to teardown).
2890 ret
= relayd_live_join();
2896 ret
= pthread_join(listener_thread
, &status
);
2899 PERROR("pthread_join listener_thread");
2903 exit_listener_thread
:
2904 ret
= pthread_join(worker_thread
, &status
);
2907 PERROR("pthread_join worker_thread");
2912 ret
= pthread_join(dispatcher_thread
, &status
);
2915 PERROR("pthread_join dispatcher_thread");
2918 exit_dispatcher_thread
:
2920 ret
= pthread_join(health_thread
, &status
);
2923 PERROR("pthread_join health_thread");
2928 utils_close_pipe(health_quit_pipe
);
2929 exit_health_quit_pipe
:
2932 health_app_destroy(health_relayd
);
2933 exit_health_app_create
:
2937 /* Ensure all prior call_rcu are done. */