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>
44 #include <lttng/lttng.h>
45 #include <common/common.h>
46 #include <common/compat/poll.h>
47 #include <common/compat/socket.h>
48 #include <common/compat/endian.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/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"
73 /* command line options */
74 char *opt_output_path
;
75 static int opt_daemon
, opt_background
;
78 * We need to wait for listener and live listener threads, as well as
79 * health check thread, before being ready to signal readiness.
81 #define NR_LTTNG_RELAY_READY 3
82 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
83 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
84 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
86 static struct lttng_uri
*control_uri
;
87 static struct lttng_uri
*data_uri
;
88 static struct lttng_uri
*live_uri
;
92 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
93 static int tracing_group_name_override
;
95 const char * const config_section_name
= "relayd";
98 * Quit pipe for all threads. This permits a single cancellation point
99 * for all threads when receiving an event on the pipe.
101 int thread_quit_pipe
[2] = { -1, -1 };
104 * This pipe is used to inform the worker thread that a command is queued and
105 * ready to be processed.
107 static int relay_conn_pipe
[2] = { -1, -1 };
109 /* Shared between threads */
110 static int dispatch_thread_exit
;
112 static pthread_t listener_thread
;
113 static pthread_t dispatcher_thread
;
114 static pthread_t worker_thread
;
115 static pthread_t health_thread
;
118 * last_relay_stream_id_lock protects last_relay_stream_id increment
119 * atomicity on 32-bit architectures.
121 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
122 static uint64_t last_relay_stream_id
;
125 * Relay command queue.
127 * The relay_thread_listener and relay_thread_dispatcher communicate with this
130 static struct relay_conn_queue relay_conn_queue
;
132 /* buffer allocated at startup, used to store the trace data */
133 static char *data_buffer
;
134 static unsigned int data_buffer_size
;
136 /* Global relay stream hash table. */
137 struct lttng_ht
*relay_streams_ht
;
139 /* Global relay viewer stream hash table. */
140 struct lttng_ht
*viewer_streams_ht
;
142 /* Global relay sessions hash table. */
143 struct lttng_ht
*sessions_ht
;
145 /* Relayd health monitoring */
146 struct health_app
*health_relayd
;
148 static struct option long_options
[] = {
149 { "control-port", 1, 0, 'C', },
150 { "data-port", 1, 0, 'D', },
151 { "live-port", 1, 0, 'L', },
152 { "daemonize", 0, 0, 'd', },
153 { "background", 0, 0, 'b', },
154 { "group", 1, 0, 'g', },
155 { "help", 0, 0, 'h', },
156 { "output", 1, 0, 'o', },
157 { "verbose", 0, 0, 'v', },
158 { "config", 1, 0, 'f' },
162 static const char *config_ignore_options
[] = { "help", "config" };
165 * usage function on stderr
167 static void usage(void)
169 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
170 fprintf(stderr
, " -h, --help Display this usage.\n");
171 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
172 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
173 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
174 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
175 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
176 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
177 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
178 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
179 fprintf(stderr
, " -f --config Load daemon configuration file\n");
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 ret
= uri_parse(arg
, &control_uri
);
202 ERR("Invalid control URI specified");
205 if (control_uri
->port
== 0) {
206 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
210 ret
= uri_parse(arg
, &data_uri
);
212 ERR("Invalid data URI specified");
215 if (data_uri
->port
== 0) {
216 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
220 ret
= uri_parse(arg
, &live_uri
);
222 ERR("Invalid live URI specified");
225 if (live_uri
->port
== 0) {
226 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
236 tracing_group_name
= strdup(arg
);
237 if (tracing_group_name
== NULL
) {
242 tracing_group_name_override
= 1;
248 ret
= asprintf(&opt_output_path
, "%s", arg
);
251 PERROR("asprintf opt_output_path");
256 /* Verbose level can increase using multiple -v */
258 lttng_opt_verbose
= config_parse_value(arg
);
260 /* Only 3 level of verbosity (-vvv). */
261 if (lttng_opt_verbose
< 3) {
262 lttng_opt_verbose
+= 1;
267 /* Unknown option or other error.
268 * Error is printed by getopt, just return */
281 * config_entry_handler_cb used to handle options read from a config file.
282 * See config_entry_handler_cb comment in common/config/config.h for the
283 * return value conventions.
285 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
289 if (!entry
|| !entry
->name
|| !entry
->value
) {
294 /* Check if the option is to be ignored */
295 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
296 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
301 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
302 /* Ignore if entry name is not fully matched. */
303 if (strcmp(entry
->name
, long_options
[i
].name
)) {
308 * If the option takes no argument on the command line,
309 * we have to check if the value is "true". We support
310 * non-zero numeric values, true, on and yes.
312 if (!long_options
[i
].has_arg
) {
313 ret
= config_parse_value(entry
->value
);
316 WARN("Invalid configuration value \"%s\" for option %s",
317 entry
->value
, entry
->name
);
319 /* False, skip boolean config option. */
324 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
328 WARN("Unrecognized option \"%s\" in daemon configuration file.",
335 static int set_options(int argc
, char **argv
)
337 int c
, ret
= 0, option_index
= 0, retval
= 0;
338 int orig_optopt
= optopt
, orig_optind
= optind
;
339 char *default_address
, *optstring
;
340 const char *config_path
= NULL
;
342 optstring
= utils_generate_optstring(long_options
,
343 sizeof(long_options
) / sizeof(struct option
));
349 /* Check for the --config option */
351 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
352 &option_index
)) != -1) {
356 } else if (c
!= 'f') {
360 config_path
= utils_expand_path(optarg
);
362 ERR("Failed to resolve path: %s", optarg
);
366 ret
= config_get_section_entries(config_path
, config_section_name
,
367 config_entry_handler
, NULL
);
370 ERR("Invalid configuration option at line %i", ret
);
376 /* Reset getopt's global state */
377 optopt
= orig_optopt
;
378 optind
= orig_optind
;
380 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
385 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
392 /* assign default values */
393 if (control_uri
== NULL
) {
394 ret
= asprintf(&default_address
,
395 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
396 DEFAULT_NETWORK_CONTROL_PORT
);
398 PERROR("asprintf default data address");
403 ret
= uri_parse(default_address
, &control_uri
);
404 free(default_address
);
406 ERR("Invalid control URI specified");
411 if (data_uri
== NULL
) {
412 ret
= asprintf(&default_address
,
413 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
414 DEFAULT_NETWORK_DATA_PORT
);
416 PERROR("asprintf default data address");
421 ret
= uri_parse(default_address
, &data_uri
);
422 free(default_address
);
424 ERR("Invalid data URI specified");
429 if (live_uri
== NULL
) {
430 ret
= asprintf(&default_address
,
431 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
432 DEFAULT_NETWORK_VIEWER_PORT
);
434 PERROR("asprintf default viewer control address");
439 ret
= uri_parse(default_address
, &live_uri
);
440 free(default_address
);
442 ERR("Invalid viewer control URI specified");
453 static void print_global_objects(void)
455 rcu_register_thread();
457 print_viewer_streams();
458 print_relay_streams();
461 rcu_unregister_thread();
467 static void relayd_cleanup(void)
469 print_global_objects();
473 if (viewer_streams_ht
)
474 lttng_ht_destroy(viewer_streams_ht
);
475 if (relay_streams_ht
)
476 lttng_ht_destroy(relay_streams_ht
);
478 lttng_ht_destroy(sessions_ht
);
480 /* free the dynamically allocated opt_output_path */
481 free(opt_output_path
);
483 /* Close thread quit pipes */
484 utils_close_pipe(thread_quit_pipe
);
486 uri_free(control_uri
);
488 /* Live URI is freed in the live thread. */
490 if (tracing_group_name_override
) {
491 free((void *) tracing_group_name
);
496 * Write to writable pipe used to notify a thread.
498 static int notify_thread_pipe(int wpipe
)
502 ret
= lttng_write(wpipe
, "!", 1);
504 PERROR("write poll pipe");
512 static int notify_health_quit_pipe(int *pipe
)
516 ret
= lttng_write(pipe
[1], "4", 1);
518 PERROR("write relay health quit");
527 * Stop all relayd and relayd-live threads.
529 int lttng_relay_stop_threads(void)
533 /* Stopping all threads */
534 DBG("Terminating all threads");
535 if (notify_thread_pipe(thread_quit_pipe
[1])) {
536 ERR("write error on thread quit pipe");
540 if (notify_health_quit_pipe(health_quit_pipe
)) {
541 ERR("write error on health quit pipe");
544 /* Dispatch thread */
545 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
546 futex_nto1_wake(&relay_conn_queue
.futex
);
548 if (relayd_live_stop()) {
549 ERR("Error stopping live threads");
556 * Signal handler for the daemon
558 * Simply stop all worker threads, leaving main() return gracefully after
559 * joining all threads and calling cleanup().
561 static void sighandler(int sig
)
565 DBG("SIGPIPE caught");
568 DBG("SIGINT caught");
569 if (lttng_relay_stop_threads()) {
570 ERR("Error stopping threads");
574 DBG("SIGTERM caught");
575 if (lttng_relay_stop_threads()) {
576 ERR("Error stopping threads");
580 CMM_STORE_SHARED(recv_child_signal
, 1);
588 * Setup signal handler for :
589 * SIGINT, SIGTERM, SIGPIPE
591 static int set_signal_handler(void)
597 if ((ret
= sigemptyset(&sigset
)) < 0) {
598 PERROR("sigemptyset");
602 sa
.sa_handler
= sighandler
;
605 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
610 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
615 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
620 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
625 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
630 void lttng_relay_notify_ready(void)
632 /* Notify the parent of the fork() process that we are ready. */
633 if (opt_daemon
|| opt_background
) {
634 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
635 kill(child_ppid
, SIGUSR1
);
641 * Init thread quit pipe.
643 * Return -1 on error or 0 if all pipes are created.
645 static int init_thread_quit_pipe(void)
649 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
655 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
657 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
661 if (events
== NULL
|| size
== 0) {
666 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
672 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
684 * Check if the thread quit pipe was triggered.
686 * Return 1 if it was triggered else 0;
688 static int check_thread_quit_pipe(int fd
, uint32_t events
)
690 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
698 * Create and init socket from uri.
700 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
703 struct lttcomm_sock
*sock
= NULL
;
705 sock
= lttcomm_alloc_sock_from_uri(uri
);
707 ERR("Allocating socket");
711 ret
= lttcomm_create_sock(sock
);
715 DBG("Listening on sock %d", sock
->fd
);
717 ret
= sock
->ops
->bind(sock
);
722 ret
= sock
->ops
->listen(sock
, -1);
732 lttcomm_destroy_sock(sock
);
738 * This thread manages the listening for new connections on the network
740 static void *relay_thread_listener(void *data
)
742 int i
, ret
, pollfd
, err
= -1;
743 uint32_t revents
, nb_fd
;
744 struct lttng_poll_event events
;
745 struct lttcomm_sock
*control_sock
, *data_sock
;
747 DBG("[thread] Relay listener started");
749 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
751 health_code_update();
753 control_sock
= relay_socket_create(control_uri
);
755 goto error_sock_control
;
758 data_sock
= relay_socket_create(data_uri
);
760 goto error_sock_relay
;
764 * Pass 3 as size here for the thread quit pipe, control and
767 ret
= create_thread_poll_set(&events
, 3);
769 goto error_create_poll
;
772 /* Add the control socket */
773 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
778 /* Add the data socket */
779 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
784 lttng_relay_notify_ready();
786 if (testpoint(relayd_thread_listener
)) {
787 goto error_testpoint
;
791 health_code_update();
793 DBG("Listener accepting connections");
797 ret
= lttng_poll_wait(&events
, -1);
801 * Restart interrupted system call.
803 if (errno
== EINTR
) {
811 DBG("Relay new connection received");
812 for (i
= 0; i
< nb_fd
; i
++) {
813 health_code_update();
815 /* Fetch once the poll data */
816 revents
= LTTNG_POLL_GETEV(&events
, i
);
817 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
821 * No activity for this FD (poll
827 /* Thread quit pipe has been closed. Killing thread. */
828 ret
= check_thread_quit_pipe(pollfd
, revents
);
834 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
835 ERR("socket poll error");
837 } else if (revents
& LPOLLIN
) {
839 * A new connection is requested, therefore a
840 * sessiond/consumerd connection is allocated in
841 * this thread, enqueued to a global queue and
842 * dequeued (and freed) in the worker thread.
845 struct relay_connection
*new_conn
;
846 struct lttcomm_sock
*newsock
;
847 enum connection_type type
;
849 if (pollfd
== data_sock
->fd
) {
851 newsock
= data_sock
->ops
->accept(data_sock
);
852 DBG("Relay data connection accepted, socket %d",
855 assert(pollfd
== control_sock
->fd
);
856 type
= RELAY_CONTROL
;
857 newsock
= control_sock
->ops
->accept(control_sock
);
858 DBG("Relay control connection accepted, socket %d",
862 PERROR("accepting sock");
866 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
869 PERROR("setsockopt inet");
870 lttcomm_destroy_sock(newsock
);
873 new_conn
= connection_create(newsock
, type
);
875 lttcomm_destroy_sock(newsock
);
879 /* Enqueue request for the dispatcher thread. */
880 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
884 * Wake the dispatch queue futex.
885 * Implicit memory barrier with the
886 * exchange in cds_wfcq_enqueue.
888 futex_nto1_wake(&relay_conn_queue
.futex
);
897 lttng_poll_clean(&events
);
899 if (data_sock
->fd
>= 0) {
900 ret
= data_sock
->ops
->close(data_sock
);
905 lttcomm_destroy_sock(data_sock
);
907 if (control_sock
->fd
>= 0) {
908 ret
= control_sock
->ops
->close(control_sock
);
913 lttcomm_destroy_sock(control_sock
);
917 ERR("Health error occurred in %s", __func__
);
919 health_unregister(health_relayd
);
920 DBG("Relay listener thread cleanup complete");
921 lttng_relay_stop_threads();
926 * This thread manages the dispatching of the requests to worker threads
928 static void *relay_thread_dispatcher(void *data
)
932 struct cds_wfcq_node
*node
;
933 struct relay_connection
*new_conn
= NULL
;
935 DBG("[thread] Relay dispatcher started");
937 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
939 if (testpoint(relayd_thread_dispatcher
)) {
940 goto error_testpoint
;
943 health_code_update();
945 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
946 health_code_update();
948 /* Atomically prepare the queue futex */
949 futex_nto1_prepare(&relay_conn_queue
.futex
);
952 health_code_update();
954 /* Dequeue commands */
955 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
956 &relay_conn_queue
.tail
);
958 DBG("Woken up but nothing in the relay command queue");
959 /* Continue thread execution */
962 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
964 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
967 * Inform worker thread of the new request. This
968 * call is blocking so we can be assured that
969 * the data will be read at some point in time
970 * or wait to the end of the world :)
972 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
974 PERROR("write connection pipe");
975 connection_put(new_conn
);
978 } while (node
!= NULL
);
980 /* Futex wait on queue. Blocking call on futex() */
982 futex_nto1_wait(&relay_conn_queue
.futex
);
986 /* Normal exit, no error */
993 ERR("Health error occurred in %s", __func__
);
995 health_unregister(health_relayd
);
996 DBG("Dispatch thread dying");
997 lttng_relay_stop_threads();
1002 * Set index data from the control port to a given index object.
1004 static int set_index_control_data(struct relay_index
*index
,
1005 struct lttcomm_relayd_index
*data
)
1007 struct ctf_packet_index index_data
;
1010 * The index on disk is encoded in big endian, so we don't need
1011 * to convert the data received on the network. The data_offset
1012 * value is NEVER modified here and is updated by the data
1015 index_data
.packet_size
= data
->packet_size
;
1016 index_data
.content_size
= data
->content_size
;
1017 index_data
.timestamp_begin
= data
->timestamp_begin
;
1018 index_data
.timestamp_end
= data
->timestamp_end
;
1019 index_data
.events_discarded
= data
->events_discarded
;
1020 index_data
.stream_id
= data
->stream_id
;
1021 return relay_index_set_data(index
, &index_data
);
1025 * Handle the RELAYD_CREATE_SESSION command.
1027 * On success, send back the session id or else return a negative value.
1029 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1030 struct relay_connection
*conn
)
1032 int ret
= 0, send_ret
;
1033 struct relay_session
*session
;
1034 struct lttcomm_relayd_status_session reply
;
1035 char session_name
[NAME_MAX
];
1036 char hostname
[HOST_NAME_MAX
];
1037 uint32_t live_timer
= 0;
1038 bool snapshot
= false;
1040 memset(session_name
, 0, NAME_MAX
);
1041 memset(hostname
, 0, HOST_NAME_MAX
);
1043 memset(&reply
, 0, sizeof(reply
));
1045 switch (conn
->minor
) {
1050 case 4: /* LTTng sessiond 2.4 */
1052 ret
= cmd_create_session_2_4(conn
, session_name
,
1053 hostname
, &live_timer
, &snapshot
);
1059 session
= session_create(session_name
, hostname
, live_timer
,
1060 snapshot
, conn
->major
, conn
->minor
);
1065 assert(!conn
->session
);
1066 conn
->session
= session
;
1067 DBG("Created session %" PRIu64
, session
->id
);
1069 reply
.session_id
= htobe64(session
->id
);
1073 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1075 reply
.ret_code
= htobe32(LTTNG_OK
);
1078 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1080 ERR("Relayd sending session id");
1088 * When we have received all the streams and the metadata for a channel,
1089 * we make them visible to the viewer threads.
1091 static void publish_connection_local_streams(struct relay_connection
*conn
)
1093 struct relay_stream
*stream
;
1094 struct relay_session
*session
= conn
->session
;
1097 * We publish all streams belonging to a session atomically wrt
1100 pthread_mutex_lock(&session
->lock
);
1102 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1104 stream_publish(stream
);
1109 * Inform the viewer that there are new streams in the session.
1111 if (session
->viewer_attached
) {
1112 uatomic_set(&session
->new_streams
, 1);
1114 pthread_mutex_unlock(&session
->lock
);
1118 * relay_add_stream: allocate a new stream for a session
1120 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1121 struct relay_connection
*conn
)
1125 struct relay_session
*session
= conn
->session
;
1126 struct relay_stream
*stream
= NULL
;
1127 struct lttcomm_relayd_status_stream reply
;
1128 struct ctf_trace
*trace
= NULL
;
1129 uint64_t stream_handle
= -1ULL;
1130 char *path_name
= NULL
, *channel_name
= NULL
;
1131 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1133 if (!session
|| conn
->version_check_done
== 0) {
1134 ERR("Trying to add a stream before version check");
1136 goto end_no_session
;
1139 switch (session
->minor
) {
1140 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1141 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1144 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1146 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1147 &channel_name
, &tracefile_size
, &tracefile_count
);
1154 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1158 /* This stream here has one reference on the trace. */
1160 pthread_mutex_lock(&last_relay_stream_id_lock
);
1161 stream_handle
= ++last_relay_stream_id
;
1162 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1164 /* We pass ownership of path_name and channel_name. */
1165 stream
= stream_create(trace
, stream_handle
, path_name
,
1166 channel_name
, tracefile_size
, tracefile_count
);
1168 channel_name
= NULL
;
1171 * Streams are the owners of their trace. Reference to trace is
1172 * kept within stream_create().
1174 ctf_trace_put(trace
);
1177 memset(&reply
, 0, sizeof(reply
));
1178 reply
.handle
= htobe64(stream_handle
);
1180 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1182 reply
.ret_code
= htobe32(LTTNG_OK
);
1185 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1186 sizeof(struct lttcomm_relayd_status_stream
), 0);
1188 ERR("Relay sending stream id");
1189 ret
= (int) send_ret
;
1199 * relay_close_stream: close a specific stream
1201 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1202 struct relay_connection
*conn
)
1205 struct relay_session
*session
= conn
->session
;
1206 struct lttcomm_relayd_close_stream stream_info
;
1207 struct lttcomm_relayd_generic_reply reply
;
1208 struct relay_stream
*stream
;
1210 DBG("Close stream received");
1212 if (!session
|| conn
->version_check_done
== 0) {
1213 ERR("Trying to close a stream before version check");
1215 goto end_no_session
;
1218 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1219 sizeof(struct lttcomm_relayd_close_stream
), 0);
1220 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1222 /* Orderly shutdown. Not necessary to print an error. */
1223 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1225 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1228 goto end_no_session
;
1231 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1236 pthread_mutex_lock(&stream
->lock
);
1237 stream
->closed
= true;
1238 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1239 if (stream
->is_metadata
) {
1240 struct relay_viewer_stream
*vstream
;
1242 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1244 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1246 * Since all the metadata has been sent to the
1247 * viewer and that we have a request to close
1248 * its stream, we can safely teardown the
1249 * corresponding metadata viewer stream.
1251 viewer_stream_put(vstream
);
1253 /* Put local reference. */
1254 viewer_stream_put(vstream
);
1257 pthread_mutex_unlock(&stream
->lock
);
1261 memset(&reply
, 0, sizeof(reply
));
1263 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1265 reply
.ret_code
= htobe32(LTTNG_OK
);
1267 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1268 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1270 ERR("Relay sending stream id");
1279 * relay_unknown_command: send -1 if received unknown command
1281 static void relay_unknown_command(struct relay_connection
*conn
)
1283 struct lttcomm_relayd_generic_reply reply
;
1286 memset(&reply
, 0, sizeof(reply
));
1287 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1288 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1289 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1291 ERR("Relay sending unknown command");
1296 * relay_start: send an acknowledgment to the client to tell if we are
1297 * ready to receive data. We are ready if a session is established.
1299 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1300 struct relay_connection
*conn
)
1302 int ret
= htobe32(LTTNG_OK
);
1303 struct lttcomm_relayd_generic_reply reply
;
1304 struct relay_session
*session
= conn
->session
;
1307 DBG("Trying to start the streaming without a session established");
1308 ret
= htobe32(LTTNG_ERR_UNK
);
1311 memset(&reply
, 0, sizeof(reply
));
1312 reply
.ret_code
= ret
;
1313 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1314 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1316 ERR("Relay sending start ack");
1323 * Append padding to the file pointed by the file descriptor fd.
1325 static int write_padding_to_file(int fd
, uint32_t size
)
1334 zeros
= zmalloc(size
);
1335 if (zeros
== NULL
) {
1336 PERROR("zmalloc zeros for padding");
1341 ret
= lttng_write(fd
, zeros
, size
);
1343 PERROR("write padding to file");
1353 * relay_recv_metadata: receive the metadata for the session.
1355 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1356 struct relay_connection
*conn
)
1358 int ret
= htobe32(LTTNG_OK
);
1360 struct relay_session
*session
= conn
->session
;
1361 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1362 struct relay_stream
*metadata_stream
;
1363 uint64_t data_size
, payload_size
;
1366 ERR("Metadata sent before version check");
1371 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1372 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1373 ERR("Incorrect data size");
1377 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1379 if (data_buffer_size
< data_size
) {
1380 /* In case the realloc fails, we can free the memory */
1383 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1384 if (!tmp_data_ptr
) {
1385 ERR("Allocating data buffer");
1390 data_buffer
= tmp_data_ptr
;
1391 data_buffer_size
= data_size
;
1393 memset(data_buffer
, 0, data_size
);
1394 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1395 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1396 if (ret
< 0 || ret
!= data_size
) {
1398 /* Orderly shutdown. Not necessary to print an error. */
1399 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1401 ERR("Relay didn't receive the whole metadata");
1406 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1408 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1409 if (!metadata_stream
) {
1414 pthread_mutex_lock(&metadata_stream
->lock
);
1416 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1418 if (size_ret
< payload_size
) {
1419 ERR("Relay error writing metadata on file");
1424 ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1425 be32toh(metadata_struct
->padding_size
));
1430 metadata_stream
->metadata_received
+=
1431 payload_size
+ be32toh(metadata_struct
->padding_size
);
1432 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1433 metadata_stream
->metadata_received
);
1436 pthread_mutex_unlock(&metadata_stream
->lock
);
1437 stream_put(metadata_stream
);
1444 * relay_send_version: send relayd version number
1446 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1447 struct relay_connection
*conn
)
1450 struct lttcomm_relayd_version reply
, msg
;
1452 conn
->version_check_done
= 1;
1454 /* Get version from the other side. */
1455 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1456 if (ret
< 0 || ret
!= sizeof(msg
)) {
1458 /* Orderly shutdown. Not necessary to print an error. */
1459 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1461 ERR("Relay failed to receive the version values.");
1467 memset(&reply
, 0, sizeof(reply
));
1468 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1469 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1471 /* Major versions must be the same */
1472 if (reply
.major
!= be32toh(msg
.major
)) {
1473 DBG("Incompatible major versions (%u vs %u), deleting session",
1474 reply
.major
, be32toh(msg
.major
));
1475 connection_put(conn
);
1480 conn
->major
= reply
.major
;
1481 /* We adapt to the lowest compatible version */
1482 if (reply
.minor
<= be32toh(msg
.minor
)) {
1483 conn
->minor
= reply
.minor
;
1485 conn
->minor
= be32toh(msg
.minor
);
1488 reply
.major
= htobe32(reply
.major
);
1489 reply
.minor
= htobe32(reply
.minor
);
1490 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1491 sizeof(struct lttcomm_relayd_version
), 0);
1493 ERR("Relay sending version");
1496 DBG("Version check done using protocol %u.%u", conn
->major
,
1504 * Check for data pending for a given stream id from the session daemon.
1506 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1507 struct relay_connection
*conn
)
1509 struct relay_session
*session
= conn
->session
;
1510 struct lttcomm_relayd_data_pending msg
;
1511 struct lttcomm_relayd_generic_reply reply
;
1512 struct relay_stream
*stream
;
1514 uint64_t last_net_seq_num
, stream_id
;
1516 DBG("Data pending command received");
1518 if (!session
|| conn
->version_check_done
== 0) {
1519 ERR("Trying to check for data before version check");
1521 goto end_no_session
;
1524 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1525 if (ret
< sizeof(msg
)) {
1527 /* Orderly shutdown. Not necessary to print an error. */
1528 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1530 ERR("Relay didn't receive valid data_pending struct size : %d",
1534 goto end_no_session
;
1537 stream_id
= be64toh(msg
.stream_id
);
1538 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1540 stream
= stream_get_by_id(stream_id
);
1541 if (stream
== NULL
) {
1546 pthread_mutex_lock(&stream
->lock
);
1548 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1549 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1552 /* Avoid wrapping issue */
1553 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1554 /* Data has in fact been written and is NOT pending */
1557 /* Data still being streamed thus pending */
1561 stream
->data_pending_check_done
= true;
1562 pthread_mutex_unlock(&stream
->lock
);
1567 memset(&reply
, 0, sizeof(reply
));
1568 reply
.ret_code
= htobe32(ret
);
1569 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1571 ERR("Relay data pending ret code failed");
1579 * Wait for the control socket to reach a quiescent state.
1581 * Note that for now, when receiving this command from the session
1582 * daemon, this means that every subsequent commands or data received on
1583 * the control socket has been handled. So, this is why we simply return
1586 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1587 struct relay_connection
*conn
)
1591 struct relay_stream
*stream
;
1592 struct lttcomm_relayd_quiescent_control msg
;
1593 struct lttcomm_relayd_generic_reply reply
;
1595 DBG("Checking quiescent state on control socket");
1597 if (!conn
->session
|| conn
->version_check_done
== 0) {
1598 ERR("Trying to check for data before version check");
1600 goto end_no_session
;
1603 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1604 if (ret
< sizeof(msg
)) {
1606 /* Orderly shutdown. Not necessary to print an error. */
1607 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1609 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1613 goto end_no_session
;
1616 stream_id
= be64toh(msg
.stream_id
);
1617 stream
= stream_get_by_id(stream_id
);
1621 pthread_mutex_lock(&stream
->lock
);
1622 stream
->data_pending_check_done
= true;
1623 pthread_mutex_unlock(&stream
->lock
);
1624 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1627 memset(&reply
, 0, sizeof(reply
));
1628 reply
.ret_code
= htobe32(LTTNG_OK
);
1629 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1631 ERR("Relay data quiescent control ret code failed");
1639 * Initialize a data pending command. This means that a consumer is about
1640 * to ask for data pending for each stream it holds. Simply iterate over
1641 * all streams of a session and set the data_pending_check_done flag.
1643 * This command returns to the client a LTTNG_OK code.
1645 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1646 struct relay_connection
*conn
)
1649 struct lttng_ht_iter iter
;
1650 struct lttcomm_relayd_begin_data_pending msg
;
1651 struct lttcomm_relayd_generic_reply reply
;
1652 struct relay_stream
*stream
;
1653 uint64_t session_id
;
1658 DBG("Init streams for data pending");
1660 if (!conn
->session
|| conn
->version_check_done
== 0) {
1661 ERR("Trying to check for data before version check");
1663 goto end_no_session
;
1666 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1667 if (ret
< sizeof(msg
)) {
1669 /* Orderly shutdown. Not necessary to print an error. */
1670 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1672 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1676 goto end_no_session
;
1679 session_id
= be64toh(msg
.session_id
);
1682 * Iterate over all streams to set the begin data pending flag.
1683 * For now, the streams are indexed by stream handle so we have
1684 * to iterate over all streams to find the one associated with
1685 * the right session_id.
1688 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1690 if (!stream_get(stream
)) {
1693 if (stream
->trace
->session
->id
== session_id
) {
1694 pthread_mutex_lock(&stream
->lock
);
1695 stream
->data_pending_check_done
= false;
1696 pthread_mutex_unlock(&stream
->lock
);
1697 DBG("Set begin data pending flag to stream %" PRIu64
,
1698 stream
->stream_handle
);
1704 memset(&reply
, 0, sizeof(reply
));
1705 /* All good, send back reply. */
1706 reply
.ret_code
= htobe32(LTTNG_OK
);
1708 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1710 ERR("Relay begin data pending send reply failed");
1718 * End data pending command. This will check, for a given session id, if
1719 * each stream associated with it has its data_pending_check_done flag
1720 * set. If not, this means that the client lost track of the stream but
1721 * the data is still being streamed on our side. In this case, we inform
1722 * the client that data is in flight.
1724 * Return to the client if there is data in flight or not with a ret_code.
1726 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1727 struct relay_connection
*conn
)
1730 struct lttng_ht_iter iter
;
1731 struct lttcomm_relayd_end_data_pending msg
;
1732 struct lttcomm_relayd_generic_reply reply
;
1733 struct relay_stream
*stream
;
1734 uint64_t session_id
;
1735 uint32_t is_data_inflight
= 0;
1737 DBG("End data pending command");
1739 if (!conn
->session
|| conn
->version_check_done
== 0) {
1740 ERR("Trying to check for data before version check");
1742 goto end_no_session
;
1745 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1746 if (ret
< sizeof(msg
)) {
1748 /* Orderly shutdown. Not necessary to print an error. */
1749 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1751 ERR("Relay didn't receive valid end data_pending struct size: %d",
1755 goto end_no_session
;
1758 session_id
= be64toh(msg
.session_id
);
1761 * Iterate over all streams to see if the begin data pending
1765 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1767 if (!stream_get(stream
)) {
1770 if (stream
->trace
->session
->id
!= session_id
) {
1774 pthread_mutex_lock(&stream
->lock
);
1775 if (!stream
->data_pending_check_done
) {
1776 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1777 is_data_inflight
= 1;
1778 DBG("Data is still in flight for stream %" PRIu64
,
1779 stream
->stream_handle
);
1780 pthread_mutex_unlock(&stream
->lock
);
1785 pthread_mutex_unlock(&stream
->lock
);
1790 memset(&reply
, 0, sizeof(reply
));
1791 /* All good, send back reply. */
1792 reply
.ret_code
= htobe32(is_data_inflight
);
1794 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1796 ERR("Relay end data pending send reply failed");
1804 * Receive an index for a specific stream.
1806 * Return 0 on success else a negative value.
1808 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1809 struct relay_connection
*conn
)
1812 struct relay_session
*session
= conn
->session
;
1813 struct lttcomm_relayd_index index_info
;
1814 struct relay_index
*index
;
1815 struct lttcomm_relayd_generic_reply reply
;
1816 struct relay_stream
*stream
;
1817 uint64_t net_seq_num
;
1821 DBG("Relay receiving index");
1823 if (!session
|| conn
->version_check_done
== 0) {
1824 ERR("Trying to close a stream before version check");
1826 goto end_no_session
;
1829 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1830 sizeof(index_info
), 0);
1831 if (ret
< sizeof(index_info
)) {
1833 /* Orderly shutdown. Not necessary to print an error. */
1834 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1836 ERR("Relay didn't receive valid index struct size : %d", ret
);
1839 goto end_no_session
;
1842 net_seq_num
= be64toh(index_info
.net_seq_num
);
1844 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1846 ERR("stream_get_by_id not found");
1850 pthread_mutex_lock(&stream
->lock
);
1852 /* Live beacon handling */
1853 if (index_info
.packet_size
== 0) {
1854 DBG("Received live beacon for stream %" PRIu64
,
1855 stream
->stream_handle
);
1858 * Only flag a stream inactive when it has already
1859 * received data and no indexes are in flight.
1861 if (stream
->total_index_received
> 0
1862 && stream
->indexes_in_flight
== 0) {
1863 stream
->beacon_ts_end
=
1864 be64toh(index_info
.timestamp_end
);
1867 goto end_stream_put
;
1869 stream
->beacon_ts_end
= -1ULL;
1872 if (stream
->ctf_stream_id
== -1ULL) {
1873 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1875 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1878 ERR("relay_index_get_by_id_or_create index NULL");
1879 goto end_stream_put
;
1881 if (set_index_control_data(index
, &index_info
)) {
1882 ERR("set_index_control_data error");
1883 relay_index_put(index
);
1885 goto end_stream_put
;
1887 ret
= relay_index_try_flush(index
);
1889 stream
->total_index_received
++;
1890 } else if (ret
> 0) {
1894 ERR("relay_index_try_flush error %d", ret
);
1895 relay_index_put(index
);
1900 pthread_mutex_unlock(&stream
->lock
);
1905 memset(&reply
, 0, sizeof(reply
));
1907 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1909 reply
.ret_code
= htobe32(LTTNG_OK
);
1911 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1913 ERR("Relay sending close index id reply");
1922 * Receive the streams_sent message.
1924 * Return 0 on success else a negative value.
1926 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1927 struct relay_connection
*conn
)
1930 struct lttcomm_relayd_generic_reply reply
;
1934 DBG("Relay receiving streams_sent");
1936 if (!conn
->session
|| conn
->version_check_done
== 0) {
1937 ERR("Trying to close a stream before version check");
1939 goto end_no_session
;
1943 * Publish every pending stream in the connection recv list which are
1944 * now ready to be used by the viewer.
1946 publish_connection_local_streams(conn
);
1948 memset(&reply
, 0, sizeof(reply
));
1949 reply
.ret_code
= htobe32(LTTNG_OK
);
1950 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1952 ERR("Relay sending sent_stream reply");
1964 * Process the commands received on the control socket
1966 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1967 struct relay_connection
*conn
)
1971 switch (be32toh(recv_hdr
->cmd
)) {
1972 case RELAYD_CREATE_SESSION
:
1973 ret
= relay_create_session(recv_hdr
, conn
);
1975 case RELAYD_ADD_STREAM
:
1976 ret
= relay_add_stream(recv_hdr
, conn
);
1978 case RELAYD_START_DATA
:
1979 ret
= relay_start(recv_hdr
, conn
);
1981 case RELAYD_SEND_METADATA
:
1982 ret
= relay_recv_metadata(recv_hdr
, conn
);
1984 case RELAYD_VERSION
:
1985 ret
= relay_send_version(recv_hdr
, conn
);
1987 case RELAYD_CLOSE_STREAM
:
1988 ret
= relay_close_stream(recv_hdr
, conn
);
1990 case RELAYD_DATA_PENDING
:
1991 ret
= relay_data_pending(recv_hdr
, conn
);
1993 case RELAYD_QUIESCENT_CONTROL
:
1994 ret
= relay_quiescent_control(recv_hdr
, conn
);
1996 case RELAYD_BEGIN_DATA_PENDING
:
1997 ret
= relay_begin_data_pending(recv_hdr
, conn
);
1999 case RELAYD_END_DATA_PENDING
:
2000 ret
= relay_end_data_pending(recv_hdr
, conn
);
2002 case RELAYD_SEND_INDEX
:
2003 ret
= relay_recv_index(recv_hdr
, conn
);
2005 case RELAYD_STREAMS_SENT
:
2006 ret
= relay_streams_sent(recv_hdr
, conn
);
2008 case RELAYD_UPDATE_SYNC_INFO
:
2010 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2011 relay_unknown_command(conn
);
2021 * Handle index for a data stream.
2023 * Called with the stream lock held.
2025 * Return 0 on success else a negative value.
2027 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2031 uint64_t data_offset
;
2032 struct relay_index
*index
;
2034 /* Get data offset because we are about to update the index. */
2035 data_offset
= htobe64(stream
->tracefile_size_current
);
2037 DBG("handle_index_data: stream %" PRIu64
" data offset %" PRIu64
,
2038 stream
->stream_handle
, stream
->tracefile_size_current
);
2041 * Lookup for an existing index for that stream id/sequence
2042 * number. If it exists, the control thread has already received the
2043 * data for it, thus we need to write it to disk.
2045 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2051 if (rotate_index
|| !stream
->index_fd
) {
2054 /* Put ref on previous index_fd. */
2055 if (stream
->index_fd
) {
2056 stream_fd_put(stream
->index_fd
);
2057 stream
->index_fd
= NULL
;
2060 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2061 -1, -1, stream
->tracefile_size
,
2062 stream
->current_tracefile_id
);
2065 /* Put self-ref for this index due to error. */
2066 relay_index_put(index
);
2069 stream
->index_fd
= stream_fd_create(fd
);
2070 if (!stream
->index_fd
) {
2073 PERROR("Error closing FD %d", fd
);
2075 /* Put self-ref for this index due to error. */
2076 relay_index_put(index
);
2077 /* Will put the local ref. */
2082 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2084 /* Put self-ref for this index due to error. */
2085 relay_index_put(index
);
2089 ret
= relay_index_try_flush(index
);
2091 stream
->total_index_received
++;
2092 } else if (ret
> 0) {
2096 /* Put self-ref for this index due to error. */
2097 relay_index_put(index
);
2105 * relay_process_data: Process the data received on the data socket
2107 static int relay_process_data(struct relay_connection
*conn
)
2109 int ret
= 0, rotate_index
= 0;
2111 struct relay_stream
*stream
;
2112 struct lttcomm_relayd_data_hdr data_hdr
;
2114 uint64_t net_seq_num
;
2116 struct relay_session
*session
;
2118 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2119 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2122 /* Orderly shutdown. Not necessary to print an error. */
2123 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2125 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2131 stream_id
= be64toh(data_hdr
.stream_id
);
2132 stream
= stream_get_by_id(stream_id
);
2137 session
= stream
->trace
->session
;
2138 data_size
= be32toh(data_hdr
.data_size
);
2139 if (data_buffer_size
< data_size
) {
2142 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2143 if (!tmp_data_ptr
) {
2144 ERR("Allocating data buffer");
2147 goto end_stream_put
;
2149 data_buffer
= tmp_data_ptr
;
2150 data_buffer_size
= data_size
;
2152 memset(data_buffer
, 0, data_size
);
2154 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2156 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2157 data_size
, stream_id
, net_seq_num
);
2158 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2161 /* Orderly shutdown. Not necessary to print an error. */
2162 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2165 goto end_stream_put
;
2168 pthread_mutex_lock(&stream
->lock
);
2170 /* Check if a rotation is needed. */
2171 if (stream
->tracefile_size
> 0 &&
2172 (stream
->tracefile_size_current
+ data_size
) >
2173 stream
->tracefile_size
) {
2176 new_id
= (stream
->current_tracefile_id
+ 1) %
2177 stream
->tracefile_count
;
2179 * Move viewer oldest available data position forward if
2180 * we are overwriting a tracefile.
2182 if (new_id
== stream
->oldest_tracefile_id
) {
2183 stream
->oldest_tracefile_id
=
2184 (stream
->oldest_tracefile_id
+ 1) %
2185 stream
->tracefile_count
;
2187 ret
= utils_rotate_stream_file(stream
->path_name
,
2188 stream
->channel_name
, stream
->tracefile_size
,
2189 stream
->tracefile_count
, -1,
2190 -1, stream
->stream_fd
->fd
,
2191 &stream
->current_tracefile_id
,
2192 &stream
->stream_fd
->fd
);
2194 ERR("Rotating stream output file");
2195 goto end_stream_unlock
;
2197 stream
->current_tracefile_seq
++;
2198 if (stream
->current_tracefile_seq
2199 - stream
->oldest_tracefile_seq
>=
2200 stream
->tracefile_count
) {
2201 stream
->oldest_tracefile_seq
++;
2204 * Reset current size because we just performed a stream
2207 stream
->tracefile_size_current
= 0;
2212 * Index are handled in protocol version 2.4 and above. Also,
2213 * snapshot and index are NOT supported.
2215 if (session
->minor
>= 4 && !session
->snapshot
) {
2216 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2218 goto end_stream_unlock
;
2222 /* Write data to stream output fd. */
2223 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2224 if (size_ret
< data_size
) {
2225 ERR("Relay error writing data to file");
2227 goto end_stream_unlock
;
2230 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2231 size_ret
, stream
->stream_handle
);
2233 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2234 be32toh(data_hdr
.padding_size
));
2236 goto end_stream_unlock
;
2238 stream
->tracefile_size_current
+=
2239 data_size
+ be32toh(data_hdr
.padding_size
);
2240 stream
->prev_seq
= net_seq_num
;
2243 pthread_mutex_unlock(&stream
->lock
);
2250 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2254 (void) lttng_poll_del(events
, pollfd
);
2256 ret
= close(pollfd
);
2258 ERR("Closing pollfd %d", pollfd
);
2262 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2263 int pollfd
, struct relay_connection
*conn
)
2265 const char *type_str
;
2267 switch (conn
->type
) {
2272 type_str
= "Control";
2274 case RELAY_VIEWER_COMMAND
:
2275 type_str
= "Viewer Command";
2277 case RELAY_VIEWER_NOTIFICATION
:
2278 type_str
= "Viewer Notification";
2281 type_str
= "Unknown";
2283 cleanup_connection_pollfd(events
, pollfd
);
2284 connection_put(conn
);
2285 DBG("%s connection closed with %d", type_str
, pollfd
);
2289 * This thread does the actual work
2291 static void *relay_thread_worker(void *data
)
2293 int ret
, err
= -1, last_seen_data_fd
= -1;
2295 struct relay_connection
*conn
;
2296 struct lttng_poll_event events
;
2297 struct lttng_ht
*relay_connections_ht
;
2298 struct lttng_ht_iter iter
;
2299 struct lttcomm_relayd_hdr recv_hdr
;
2300 struct relay_connection
*destroy_conn
= NULL
;
2302 DBG("[thread] Relay worker started");
2304 rcu_register_thread();
2306 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2308 if (testpoint(relayd_thread_worker
)) {
2309 goto error_testpoint
;
2312 health_code_update();
2314 /* table of connections indexed on socket */
2315 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2316 if (!relay_connections_ht
) {
2317 goto relay_connections_ht_error
;
2320 ret
= create_thread_poll_set(&events
, 2);
2322 goto error_poll_create
;
2325 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2332 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2334 health_code_update();
2336 /* Infinite blocking call, waiting for transmission */
2337 DBG3("Relayd worker thread polling...");
2338 health_poll_entry();
2339 ret
= lttng_poll_wait(&events
, -1);
2343 * Restart interrupted system call.
2345 if (errno
== EINTR
) {
2354 * Process control. The control connection is
2355 * prioritized so we don't starve it with high
2356 * throughput tracing data on the data connection.
2358 for (i
= 0; i
< nb_fd
; i
++) {
2359 /* Fetch once the poll data */
2360 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2361 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2363 health_code_update();
2367 * No activity for this FD (poll
2373 /* Thread quit pipe has been closed. Killing thread. */
2374 ret
= check_thread_quit_pipe(pollfd
, revents
);
2380 /* Inspect the relay conn pipe for new connection */
2381 if (pollfd
== relay_conn_pipe
[0]) {
2382 if (revents
& LPOLLIN
) {
2383 struct relay_connection
*conn
;
2385 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2389 lttng_poll_add(&events
, conn
->sock
->fd
,
2390 LPOLLIN
| LPOLLRDHUP
);
2391 connection_ht_add(relay_connections_ht
, conn
);
2392 DBG("Connection socket %d added", conn
->sock
->fd
);
2393 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2394 ERR("Relay connection pipe error");
2397 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2401 struct relay_connection
*ctrl_conn
;
2403 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2404 /* If not found, there is a synchronization issue. */
2407 if (ctrl_conn
->type
== RELAY_DATA
) {
2408 if (revents
& LPOLLIN
) {
2410 * Flag the last seen data fd not deleted. It will be
2411 * used as the last seen fd if any fd gets deleted in
2414 last_notdel_data_fd
= pollfd
;
2416 goto put_ctrl_connection
;
2418 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2420 if (revents
& LPOLLIN
) {
2421 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2422 &recv_hdr
, sizeof(recv_hdr
), 0);
2424 /* Connection closed */
2425 relay_thread_close_connection(&events
, pollfd
,
2428 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2430 /* Clear the session on error. */
2431 relay_thread_close_connection(&events
,
2436 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2437 relay_thread_close_connection(&events
,
2439 if (last_seen_data_fd
== pollfd
) {
2440 last_seen_data_fd
= last_notdel_data_fd
;
2443 ERR("Unexpected poll events %u for control sock %d",
2445 connection_put(ctrl_conn
);
2448 put_ctrl_connection
:
2449 connection_put(ctrl_conn
);
2454 * The last loop handled a control request, go back to poll to make
2455 * sure we prioritise the control socket.
2461 if (last_seen_data_fd
>= 0) {
2462 for (i
= 0; i
< nb_fd
; i
++) {
2463 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2465 health_code_update();
2467 if (last_seen_data_fd
== pollfd
) {
2474 /* Process data connection. */
2475 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2476 /* Fetch the poll data. */
2477 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2478 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2479 struct relay_connection
*data_conn
;
2481 health_code_update();
2484 /* No activity for this FD (poll implementation). */
2488 /* Skip the command pipe. It's handled in the first loop. */
2489 if (pollfd
== relay_conn_pipe
[0]) {
2493 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2495 /* Skip it. Might be removed before. */
2498 if (data_conn
->type
== RELAY_CONTROL
) {
2499 goto put_data_connection
;
2501 assert(data_conn
->type
== RELAY_DATA
);
2503 if (revents
& LPOLLIN
) {
2504 ret
= relay_process_data(data_conn
);
2505 /* Connection closed */
2507 relay_thread_close_connection(&events
, pollfd
,
2510 * Every goto restart call sets the last seen fd where
2511 * here we don't really care since we gracefully
2512 * continue the loop after the connection is deleted.
2515 /* Keep last seen port. */
2516 last_seen_data_fd
= pollfd
;
2517 connection_put(data_conn
);
2520 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2521 relay_thread_close_connection(&events
, pollfd
,
2524 ERR("Unknown poll events %u for data sock %d",
2527 put_data_connection
:
2528 connection_put(data_conn
);
2530 last_seen_data_fd
= -1;
2533 /* Normal exit, no error */
2538 /* Cleanup reamaining connection object. */
2540 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2543 health_code_update();
2545 * No need to grab another ref, because we own
2548 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2553 lttng_poll_clean(&events
);
2555 lttng_ht_destroy(relay_connections_ht
);
2556 relay_connections_ht_error
:
2557 /* Close relay conn pipes */
2558 utils_close_pipe(relay_conn_pipe
);
2560 DBG("Thread exited with error");
2562 DBG("Worker thread cleanup complete");
2567 ERR("Health error occurred in %s", __func__
);
2569 health_unregister(health_relayd
);
2570 rcu_unregister_thread();
2571 lttng_relay_stop_threads();
2576 * Create the relay command pipe to wake thread_manage_apps.
2577 * Closed in cleanup().
2579 static int create_relay_conn_pipe(void)
2583 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2591 int main(int argc
, char **argv
)
2593 int ret
= 0, retval
= 0;
2596 /* Parse arguments */
2598 if (set_options(argc
, argv
)) {
2603 if (set_signal_handler()) {
2608 /* Try to create directory if -o, --output is specified. */
2609 if (opt_output_path
) {
2610 if (*opt_output_path
!= '/') {
2611 ERR("Please specify an absolute path for -o, --output PATH");
2616 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2619 ERR("Unable to create %s", opt_output_path
);
2626 if (opt_daemon
|| opt_background
) {
2629 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2637 * We are in the child. Make sure all other file
2638 * descriptors are closed, in case we are called with
2639 * more opened file descriptors than the standard ones.
2641 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2647 /* Initialize thread health monitoring */
2648 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2649 if (!health_relayd
) {
2650 PERROR("health_app_create error");
2652 goto exit_health_app_create
;
2655 /* Create thread quit pipe */
2656 if (init_thread_quit_pipe()) {
2658 goto exit_init_data
;
2661 /* Check if daemon is UID = 0 */
2663 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2664 ERR("Need to be root to use ports < 1024");
2666 goto exit_init_data
;
2670 /* Setup the thread apps communication pipe. */
2671 if (create_relay_conn_pipe()) {
2673 goto exit_init_data
;
2676 /* Init relay command queue. */
2677 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2679 /* Set up max poll set size */
2680 lttng_poll_set_max_size();
2682 /* Initialize communication library */
2684 lttcomm_inet_init();
2686 /* tables of sessions indexed by session ID */
2687 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2690 goto exit_init_data
;
2693 /* tables of streams indexed by stream ID */
2694 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2695 if (!relay_streams_ht
) {
2697 goto exit_init_data
;
2700 /* tables of streams indexed by stream ID */
2701 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2702 if (!viewer_streams_ht
) {
2704 goto exit_init_data
;
2707 ret
= utils_create_pipe(health_quit_pipe
);
2710 goto exit_health_quit_pipe
;
2713 /* Create thread to manage the client socket */
2714 ret
= pthread_create(&health_thread
, NULL
,
2715 thread_manage_health
, (void *) NULL
);
2718 PERROR("pthread_create health");
2720 goto exit_health_thread
;
2723 /* Setup the dispatcher thread */
2724 ret
= pthread_create(&dispatcher_thread
, NULL
,
2725 relay_thread_dispatcher
, (void *) NULL
);
2728 PERROR("pthread_create dispatcher");
2730 goto exit_dispatcher_thread
;
2733 /* Setup the worker thread */
2734 ret
= pthread_create(&worker_thread
, NULL
,
2735 relay_thread_worker
, NULL
);
2738 PERROR("pthread_create worker");
2740 goto exit_worker_thread
;
2743 /* Setup the listener thread */
2744 ret
= pthread_create(&listener_thread
, NULL
,
2745 relay_thread_listener
, (void *) NULL
);
2748 PERROR("pthread_create listener");
2750 goto exit_listener_thread
;
2753 ret
= relayd_live_create(live_uri
);
2755 ERR("Starting live viewer threads");
2761 * This is where we start awaiting program completion (e.g. through
2762 * signal that asks threads to teardown).
2765 ret
= relayd_live_join();
2771 ret
= pthread_join(listener_thread
, &status
);
2774 PERROR("pthread_join listener_thread");
2778 exit_listener_thread
:
2779 ret
= pthread_join(worker_thread
, &status
);
2782 PERROR("pthread_join worker_thread");
2787 ret
= pthread_join(dispatcher_thread
, &status
);
2790 PERROR("pthread_join dispatcher_thread");
2793 exit_dispatcher_thread
:
2795 ret
= pthread_join(health_thread
, &status
);
2798 PERROR("pthread_join health_thread");
2803 utils_close_pipe(health_quit_pipe
);
2804 exit_health_quit_pipe
:
2807 health_app_destroy(health_relayd
);
2808 exit_health_app_create
:
2812 /* Ensure all prior call_rcu are done. */