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"
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
;
84 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
85 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
87 static struct lttng_uri
*control_uri
;
88 static struct lttng_uri
*data_uri
;
89 static struct lttng_uri
*live_uri
;
93 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
94 static int tracing_group_name_override
;
96 const char * const config_section_name
= "relayd";
99 * Quit pipe for all threads. This permits a single cancellation point
100 * for all threads when receiving an event on the pipe.
102 int thread_quit_pipe
[2] = { -1, -1 };
105 * This pipe is used to inform the worker thread that a command is queued and
106 * ready to be processed.
108 static int relay_conn_pipe
[2] = { -1, -1 };
110 /* Shared between threads */
111 static int dispatch_thread_exit
;
113 static pthread_t listener_thread
;
114 static pthread_t dispatcher_thread
;
115 static pthread_t worker_thread
;
116 static pthread_t health_thread
;
119 * last_relay_stream_id_lock protects last_relay_stream_id increment
120 * atomicity on 32-bit architectures.
122 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
123 static uint64_t last_relay_stream_id
;
126 * Relay command queue.
128 * The relay_thread_listener and relay_thread_dispatcher communicate with this
131 static struct relay_conn_queue relay_conn_queue
;
133 /* buffer allocated at startup, used to store the trace data */
134 static char *data_buffer
;
135 static unsigned int data_buffer_size
;
137 /* Global relay stream hash table. */
138 struct lttng_ht
*relay_streams_ht
;
140 /* Global relay viewer stream hash table. */
141 struct lttng_ht
*viewer_streams_ht
;
143 /* Global relay sessions hash table. */
144 struct lttng_ht
*sessions_ht
;
146 /* Relayd health monitoring */
147 struct health_app
*health_relayd
;
149 static struct option long_options
[] = {
150 { "control-port", 1, 0, 'C', },
151 { "data-port", 1, 0, 'D', },
152 { "live-port", 1, 0, 'L', },
153 { "daemonize", 0, 0, 'd', },
154 { "background", 0, 0, 'b', },
155 { "group", 1, 0, 'g', },
156 { "help", 0, 0, 'h', },
157 { "output", 1, 0, 'o', },
158 { "verbose", 0, 0, 'v', },
159 { "config", 1, 0, 'f' },
163 static const char *config_ignore_options
[] = { "help", "config" };
166 * usage function on stderr
168 static void usage(void)
170 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
171 fprintf(stderr
, " -h, --help Display this usage.\n");
172 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
173 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
174 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
175 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
176 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
177 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
178 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
179 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
180 fprintf(stderr
, " -f --config Load daemon configuration file\n");
184 * Take an option from the getopt output and set it in the right variable to be
187 * Return 0 on success else a negative value.
189 static int set_option(int opt
, const char *arg
, const char *optname
)
195 fprintf(stderr
, "option %s", optname
);
197 fprintf(stderr
, " with arg %s\n", arg
);
201 ret
= uri_parse(arg
, &control_uri
);
203 ERR("Invalid control URI specified");
206 if (control_uri
->port
== 0) {
207 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
211 ret
= uri_parse(arg
, &data_uri
);
213 ERR("Invalid data URI specified");
216 if (data_uri
->port
== 0) {
217 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
221 ret
= uri_parse(arg
, &live_uri
);
223 ERR("Invalid live URI specified");
226 if (live_uri
->port
== 0) {
227 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
237 tracing_group_name
= strdup(arg
);
238 if (tracing_group_name
== NULL
) {
243 tracing_group_name_override
= 1;
249 ret
= asprintf(&opt_output_path
, "%s", arg
);
252 PERROR("asprintf opt_output_path");
257 /* Verbose level can increase using multiple -v */
259 lttng_opt_verbose
= config_parse_value(arg
);
261 /* Only 3 level of verbosity (-vvv). */
262 if (lttng_opt_verbose
< 3) {
263 lttng_opt_verbose
+= 1;
268 /* Unknown option or other error.
269 * Error is printed by getopt, just return */
282 * config_entry_handler_cb used to handle options read from a config file.
283 * See config_entry_handler_cb comment in common/config/config.h for the
284 * return value conventions.
286 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
290 if (!entry
|| !entry
->name
|| !entry
->value
) {
295 /* Check if the option is to be ignored */
296 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
297 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
302 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
303 /* Ignore if entry name is not fully matched. */
304 if (strcmp(entry
->name
, long_options
[i
].name
)) {
309 * If the option takes no argument on the command line,
310 * we have to check if the value is "true". We support
311 * non-zero numeric values, true, on and yes.
313 if (!long_options
[i
].has_arg
) {
314 ret
= config_parse_value(entry
->value
);
317 WARN("Invalid configuration value \"%s\" for option %s",
318 entry
->value
, entry
->name
);
320 /* False, skip boolean config option. */
325 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
329 WARN("Unrecognized option \"%s\" in daemon configuration file.",
336 static int set_options(int argc
, char **argv
)
338 int c
, ret
= 0, option_index
= 0, retval
= 0;
339 int orig_optopt
= optopt
, orig_optind
= optind
;
340 char *default_address
, *optstring
;
341 const char *config_path
= NULL
;
343 optstring
= utils_generate_optstring(long_options
,
344 sizeof(long_options
) / sizeof(struct option
));
350 /* Check for the --config option */
352 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
353 &option_index
)) != -1) {
357 } else if (c
!= 'f') {
361 config_path
= utils_expand_path(optarg
);
363 ERR("Failed to resolve path: %s", optarg
);
367 ret
= config_get_section_entries(config_path
, config_section_name
,
368 config_entry_handler
, NULL
);
371 ERR("Invalid configuration option at line %i", ret
);
377 /* Reset getopt's global state */
378 optopt
= orig_optopt
;
379 optind
= orig_optind
;
381 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
386 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
393 /* assign default values */
394 if (control_uri
== NULL
) {
395 ret
= asprintf(&default_address
,
396 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
397 DEFAULT_NETWORK_CONTROL_PORT
);
399 PERROR("asprintf default data address");
404 ret
= uri_parse(default_address
, &control_uri
);
405 free(default_address
);
407 ERR("Invalid control URI specified");
412 if (data_uri
== NULL
) {
413 ret
= asprintf(&default_address
,
414 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
415 DEFAULT_NETWORK_DATA_PORT
);
417 PERROR("asprintf default data address");
422 ret
= uri_parse(default_address
, &data_uri
);
423 free(default_address
);
425 ERR("Invalid data URI specified");
430 if (live_uri
== NULL
) {
431 ret
= asprintf(&default_address
,
432 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
433 DEFAULT_NETWORK_VIEWER_PORT
);
435 PERROR("asprintf default viewer control address");
440 ret
= uri_parse(default_address
, &live_uri
);
441 free(default_address
);
443 ERR("Invalid viewer control URI specified");
454 static void print_global_objects(void)
456 rcu_register_thread();
458 print_viewer_streams();
459 print_relay_streams();
462 rcu_unregister_thread();
468 static void relayd_cleanup(void)
470 print_global_objects();
474 if (viewer_streams_ht
)
475 lttng_ht_destroy(viewer_streams_ht
);
476 if (relay_streams_ht
)
477 lttng_ht_destroy(relay_streams_ht
);
479 lttng_ht_destroy(sessions_ht
);
481 /* free the dynamically allocated opt_output_path */
482 free(opt_output_path
);
484 /* Close thread quit pipes */
485 utils_close_pipe(thread_quit_pipe
);
487 uri_free(control_uri
);
489 /* Live URI is freed in the live thread. */
491 if (tracing_group_name_override
) {
492 free((void *) tracing_group_name
);
497 * Write to writable pipe used to notify a thread.
499 static int notify_thread_pipe(int wpipe
)
503 ret
= lttng_write(wpipe
, "!", 1);
505 PERROR("write poll pipe");
513 static int notify_health_quit_pipe(int *pipe
)
517 ret
= lttng_write(pipe
[1], "4", 1);
519 PERROR("write relay health quit");
528 * Stop all relayd and relayd-live threads.
530 int lttng_relay_stop_threads(void)
534 /* Stopping all threads */
535 DBG("Terminating all threads");
536 if (notify_thread_pipe(thread_quit_pipe
[1])) {
537 ERR("write error on thread quit pipe");
541 if (notify_health_quit_pipe(health_quit_pipe
)) {
542 ERR("write error on health quit pipe");
545 /* Dispatch thread */
546 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
547 futex_nto1_wake(&relay_conn_queue
.futex
);
549 if (relayd_live_stop()) {
550 ERR("Error stopping live threads");
557 * Signal handler for the daemon
559 * Simply stop all worker threads, leaving main() return gracefully after
560 * joining all threads and calling cleanup().
562 static void sighandler(int sig
)
566 DBG("SIGPIPE caught");
569 DBG("SIGINT caught");
570 if (lttng_relay_stop_threads()) {
571 ERR("Error stopping threads");
575 DBG("SIGTERM caught");
576 if (lttng_relay_stop_threads()) {
577 ERR("Error stopping threads");
581 CMM_STORE_SHARED(recv_child_signal
, 1);
589 * Setup signal handler for :
590 * SIGINT, SIGTERM, SIGPIPE
592 static int set_signal_handler(void)
598 if ((ret
= sigemptyset(&sigset
)) < 0) {
599 PERROR("sigemptyset");
603 sa
.sa_handler
= sighandler
;
606 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
611 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
616 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
621 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
626 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
631 void lttng_relay_notify_ready(void)
633 /* Notify the parent of the fork() process that we are ready. */
634 if (opt_daemon
|| opt_background
) {
635 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
636 kill(child_ppid
, SIGUSR1
);
642 * Init thread quit pipe.
644 * Return -1 on error or 0 if all pipes are created.
646 static int init_thread_quit_pipe(void)
650 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
656 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
658 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
662 if (events
== NULL
|| size
== 0) {
667 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
673 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
685 * Check if the thread quit pipe was triggered.
687 * Return 1 if it was triggered else 0;
689 static int check_thread_quit_pipe(int fd
, uint32_t events
)
691 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
699 * Create and init socket from uri.
701 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
704 struct lttcomm_sock
*sock
= NULL
;
706 sock
= lttcomm_alloc_sock_from_uri(uri
);
708 ERR("Allocating socket");
712 ret
= lttcomm_create_sock(sock
);
716 DBG("Listening on sock %d", sock
->fd
);
718 ret
= sock
->ops
->bind(sock
);
723 ret
= sock
->ops
->listen(sock
, -1);
733 lttcomm_destroy_sock(sock
);
739 * This thread manages the listening for new connections on the network
741 static void *relay_thread_listener(void *data
)
743 int i
, ret
, pollfd
, err
= -1;
744 uint32_t revents
, nb_fd
;
745 struct lttng_poll_event events
;
746 struct lttcomm_sock
*control_sock
, *data_sock
;
748 DBG("[thread] Relay listener started");
750 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
752 health_code_update();
754 control_sock
= relay_socket_create(control_uri
);
756 goto error_sock_control
;
759 data_sock
= relay_socket_create(data_uri
);
761 goto error_sock_relay
;
765 * Pass 3 as size here for the thread quit pipe, control and
768 ret
= create_thread_poll_set(&events
, 3);
770 goto error_create_poll
;
773 /* Add the control socket */
774 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
779 /* Add the data socket */
780 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
785 lttng_relay_notify_ready();
787 if (testpoint(relayd_thread_listener
)) {
788 goto error_testpoint
;
792 health_code_update();
794 DBG("Listener accepting connections");
798 ret
= lttng_poll_wait(&events
, -1);
802 * Restart interrupted system call.
804 if (errno
== EINTR
) {
812 DBG("Relay new connection received");
813 for (i
= 0; i
< nb_fd
; i
++) {
814 health_code_update();
816 /* Fetch once the poll data */
817 revents
= LTTNG_POLL_GETEV(&events
, i
);
818 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
822 * No activity for this FD (poll
828 /* Thread quit pipe has been closed. Killing thread. */
829 ret
= check_thread_quit_pipe(pollfd
, revents
);
835 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
836 ERR("socket poll error");
838 } else if (revents
& LPOLLIN
) {
840 * A new connection is requested, therefore a
841 * sessiond/consumerd connection is allocated in
842 * this thread, enqueued to a global queue and
843 * dequeued (and freed) in the worker thread.
846 struct relay_connection
*new_conn
;
847 struct lttcomm_sock
*newsock
;
848 enum connection_type type
;
850 if (pollfd
== data_sock
->fd
) {
852 newsock
= data_sock
->ops
->accept(data_sock
);
853 DBG("Relay data connection accepted, socket %d",
856 assert(pollfd
== control_sock
->fd
);
857 type
= RELAY_CONTROL
;
858 newsock
= control_sock
->ops
->accept(control_sock
);
859 DBG("Relay control connection accepted, socket %d",
863 PERROR("accepting sock");
867 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
870 PERROR("setsockopt inet");
871 lttcomm_destroy_sock(newsock
);
874 new_conn
= connection_create(newsock
, type
);
876 lttcomm_destroy_sock(newsock
);
880 /* Enqueue request for the dispatcher thread. */
881 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
885 * Wake the dispatch queue futex.
886 * Implicit memory barrier with the
887 * exchange in cds_wfcq_enqueue.
889 futex_nto1_wake(&relay_conn_queue
.futex
);
898 lttng_poll_clean(&events
);
900 if (data_sock
->fd
>= 0) {
901 ret
= data_sock
->ops
->close(data_sock
);
906 lttcomm_destroy_sock(data_sock
);
908 if (control_sock
->fd
>= 0) {
909 ret
= control_sock
->ops
->close(control_sock
);
914 lttcomm_destroy_sock(control_sock
);
918 ERR("Health error occurred in %s", __func__
);
920 health_unregister(health_relayd
);
921 DBG("Relay listener thread cleanup complete");
922 lttng_relay_stop_threads();
927 * This thread manages the dispatching of the requests to worker threads
929 static void *relay_thread_dispatcher(void *data
)
933 struct cds_wfcq_node
*node
;
934 struct relay_connection
*new_conn
= NULL
;
936 DBG("[thread] Relay dispatcher started");
938 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
940 if (testpoint(relayd_thread_dispatcher
)) {
941 goto error_testpoint
;
944 health_code_update();
946 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
947 health_code_update();
949 /* Atomically prepare the queue futex */
950 futex_nto1_prepare(&relay_conn_queue
.futex
);
953 health_code_update();
955 /* Dequeue commands */
956 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
957 &relay_conn_queue
.tail
);
959 DBG("Woken up but nothing in the relay command queue");
960 /* Continue thread execution */
963 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
965 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
968 * Inform worker thread of the new request. This
969 * call is blocking so we can be assured that
970 * the data will be read at some point in time
971 * or wait to the end of the world :)
973 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
975 PERROR("write connection pipe");
976 connection_put(new_conn
);
979 } while (node
!= NULL
);
981 /* Futex wait on queue. Blocking call on futex() */
983 futex_nto1_wait(&relay_conn_queue
.futex
);
987 /* Normal exit, no error */
994 ERR("Health error occurred in %s", __func__
);
996 health_unregister(health_relayd
);
997 DBG("Dispatch thread dying");
998 lttng_relay_stop_threads();
1003 * Set index data from the control port to a given index object.
1005 static int set_index_control_data(struct relay_index
*index
,
1006 struct lttcomm_relayd_index
*data
)
1008 struct ctf_packet_index index_data
;
1011 * The index on disk is encoded in big endian, so we don't need
1012 * to convert the data received on the network. The data_offset
1013 * value is NEVER modified here and is updated by the data
1016 index_data
.packet_size
= data
->packet_size
;
1017 index_data
.content_size
= data
->content_size
;
1018 index_data
.timestamp_begin
= data
->timestamp_begin
;
1019 index_data
.timestamp_end
= data
->timestamp_end
;
1020 index_data
.events_discarded
= data
->events_discarded
;
1021 index_data
.stream_id
= data
->stream_id
;
1022 return relay_index_set_data(index
, &index_data
);
1026 * Handle the RELAYD_CREATE_SESSION command.
1028 * On success, send back the session id or else return a negative value.
1030 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1031 struct relay_connection
*conn
)
1033 int ret
= 0, send_ret
;
1034 struct relay_session
*session
;
1035 struct lttcomm_relayd_status_session reply
;
1036 char session_name
[NAME_MAX
];
1037 char hostname
[HOST_NAME_MAX
];
1038 uint32_t live_timer
= 0;
1039 bool snapshot
= false;
1041 memset(session_name
, 0, NAME_MAX
);
1042 memset(hostname
, 0, HOST_NAME_MAX
);
1044 memset(&reply
, 0, sizeof(reply
));
1046 switch (conn
->minor
) {
1051 case 4: /* LTTng sessiond 2.4 */
1053 ret
= cmd_create_session_2_4(conn
, session_name
,
1054 hostname
, &live_timer
, &snapshot
);
1060 session
= session_create(session_name
, hostname
, live_timer
,
1061 snapshot
, conn
->major
, conn
->minor
);
1066 assert(!conn
->session
);
1067 conn
->session
= session
;
1068 DBG("Created session %" PRIu64
, session
->id
);
1070 reply
.session_id
= htobe64(session
->id
);
1074 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1076 reply
.ret_code
= htobe32(LTTNG_OK
);
1079 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1081 ERR("Relayd sending session id");
1089 * When we have received all the streams and the metadata for a channel,
1090 * we make them visible to the viewer threads.
1092 static void publish_connection_local_streams(struct relay_connection
*conn
)
1094 struct relay_stream
*stream
;
1095 struct relay_session
*session
= conn
->session
;
1098 * We publish all streams belonging to a session atomically wrt
1101 pthread_mutex_lock(&session
->lock
);
1103 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1105 stream_publish(stream
);
1110 * Inform the viewer that there are new streams in the session.
1112 if (session
->viewer_attached
) {
1113 uatomic_set(&session
->new_streams
, 1);
1115 pthread_mutex_unlock(&session
->lock
);
1119 * relay_add_stream: allocate a new stream for a session
1121 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1122 struct relay_connection
*conn
)
1126 struct relay_session
*session
= conn
->session
;
1127 struct relay_stream
*stream
= NULL
;
1128 struct lttcomm_relayd_status_stream reply
;
1129 struct ctf_trace
*trace
= NULL
;
1130 uint64_t stream_handle
= -1ULL;
1131 char *path_name
= NULL
, *channel_name
= NULL
;
1132 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1134 if (!session
|| conn
->version_check_done
== 0) {
1135 ERR("Trying to add a stream before version check");
1137 goto end_no_session
;
1140 switch (session
->minor
) {
1141 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1142 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1145 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1147 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1148 &channel_name
, &tracefile_size
, &tracefile_count
);
1155 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1159 /* This stream here has one reference on the trace. */
1161 pthread_mutex_lock(&last_relay_stream_id_lock
);
1162 stream_handle
= ++last_relay_stream_id
;
1163 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1165 /* We pass ownership of path_name and channel_name. */
1166 stream
= stream_create(trace
, stream_handle
, path_name
,
1167 channel_name
, tracefile_size
, tracefile_count
);
1169 channel_name
= NULL
;
1172 * Streams are the owners of their trace. Reference to trace is
1173 * kept within stream_create().
1175 ctf_trace_put(trace
);
1178 memset(&reply
, 0, sizeof(reply
));
1179 reply
.handle
= htobe64(stream_handle
);
1181 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1183 reply
.ret_code
= htobe32(LTTNG_OK
);
1186 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1187 sizeof(struct lttcomm_relayd_status_stream
), 0);
1189 ERR("Relay sending stream id");
1190 ret
= (int) send_ret
;
1200 * relay_close_stream: close a specific stream
1202 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1203 struct relay_connection
*conn
)
1206 struct relay_session
*session
= conn
->session
;
1207 struct lttcomm_relayd_close_stream stream_info
;
1208 struct lttcomm_relayd_generic_reply reply
;
1209 struct relay_stream
*stream
;
1211 DBG("Close stream received");
1213 if (!session
|| conn
->version_check_done
== 0) {
1214 ERR("Trying to close a stream before version check");
1216 goto end_no_session
;
1219 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1220 sizeof(struct lttcomm_relayd_close_stream
), 0);
1221 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1223 /* Orderly shutdown. Not necessary to print an error. */
1224 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1226 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1229 goto end_no_session
;
1232 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1239 * Set last_net_seq_num before the close flag. Required by data
1242 pthread_mutex_lock(&stream
->lock
);
1243 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1244 pthread_mutex_unlock(&stream
->lock
);
1247 * This is one of the conditions which may trigger a stream close
1248 * with the others being:
1249 * 1) A close command is received for a stream
1250 * 2) The control connection owning the stream is closed
1251 * 3) We have received all of the stream's data _after_ a close
1254 try_stream_close(stream
);
1255 if (stream
->is_metadata
) {
1256 struct relay_viewer_stream
*vstream
;
1258 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1260 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1262 * Since all the metadata has been sent to the
1263 * viewer and that we have a request to close
1264 * its stream, we can safely teardown the
1265 * corresponding metadata viewer stream.
1267 viewer_stream_put(vstream
);
1269 /* Put local reference. */
1270 viewer_stream_put(vstream
);
1276 memset(&reply
, 0, sizeof(reply
));
1278 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1280 reply
.ret_code
= htobe32(LTTNG_OK
);
1282 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1283 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1285 ERR("Relay sending stream id");
1294 * relay_unknown_command: send -1 if received unknown command
1296 static void relay_unknown_command(struct relay_connection
*conn
)
1298 struct lttcomm_relayd_generic_reply reply
;
1301 memset(&reply
, 0, sizeof(reply
));
1302 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1303 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1304 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1306 ERR("Relay sending unknown command");
1311 * relay_start: send an acknowledgment to the client to tell if we are
1312 * ready to receive data. We are ready if a session is established.
1314 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1315 struct relay_connection
*conn
)
1317 int ret
= htobe32(LTTNG_OK
);
1318 struct lttcomm_relayd_generic_reply reply
;
1319 struct relay_session
*session
= conn
->session
;
1322 DBG("Trying to start the streaming without a session established");
1323 ret
= htobe32(LTTNG_ERR_UNK
);
1326 memset(&reply
, 0, sizeof(reply
));
1327 reply
.ret_code
= ret
;
1328 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1329 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1331 ERR("Relay sending start ack");
1338 * Append padding to the file pointed by the file descriptor fd.
1340 static int write_padding_to_file(int fd
, uint32_t size
)
1349 zeros
= zmalloc(size
);
1350 if (zeros
== NULL
) {
1351 PERROR("zmalloc zeros for padding");
1356 ret
= lttng_write(fd
, zeros
, size
);
1358 PERROR("write padding to file");
1368 * relay_recv_metadata: receive the metadata for the session.
1370 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1371 struct relay_connection
*conn
)
1373 int ret
= htobe32(LTTNG_OK
);
1375 struct relay_session
*session
= conn
->session
;
1376 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1377 struct relay_stream
*metadata_stream
;
1378 uint64_t data_size
, payload_size
;
1381 ERR("Metadata sent before version check");
1386 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1387 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1388 ERR("Incorrect data size");
1392 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1394 if (data_buffer_size
< data_size
) {
1395 /* In case the realloc fails, we can free the memory */
1398 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1399 if (!tmp_data_ptr
) {
1400 ERR("Allocating data buffer");
1405 data_buffer
= tmp_data_ptr
;
1406 data_buffer_size
= data_size
;
1408 memset(data_buffer
, 0, data_size
);
1409 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1410 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1411 if (ret
< 0 || ret
!= data_size
) {
1413 /* Orderly shutdown. Not necessary to print an error. */
1414 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1416 ERR("Relay didn't receive the whole metadata");
1421 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1423 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1424 if (!metadata_stream
) {
1429 pthread_mutex_lock(&metadata_stream
->lock
);
1431 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1433 if (size_ret
< payload_size
) {
1434 ERR("Relay error writing metadata on file");
1439 ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1440 be32toh(metadata_struct
->padding_size
));
1445 metadata_stream
->metadata_received
+=
1446 payload_size
+ be32toh(metadata_struct
->padding_size
);
1447 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1448 metadata_stream
->metadata_received
);
1451 pthread_mutex_unlock(&metadata_stream
->lock
);
1452 stream_put(metadata_stream
);
1459 * relay_send_version: send relayd version number
1461 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1462 struct relay_connection
*conn
)
1465 struct lttcomm_relayd_version reply
, msg
;
1467 conn
->version_check_done
= 1;
1469 /* Get version from the other side. */
1470 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1471 if (ret
< 0 || ret
!= sizeof(msg
)) {
1473 /* Orderly shutdown. Not necessary to print an error. */
1474 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1476 ERR("Relay failed to receive the version values.");
1482 memset(&reply
, 0, sizeof(reply
));
1483 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1484 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1486 /* Major versions must be the same */
1487 if (reply
.major
!= be32toh(msg
.major
)) {
1488 DBG("Incompatible major versions (%u vs %u), deleting session",
1489 reply
.major
, be32toh(msg
.major
));
1490 connection_put(conn
);
1495 conn
->major
= reply
.major
;
1496 /* We adapt to the lowest compatible version */
1497 if (reply
.minor
<= be32toh(msg
.minor
)) {
1498 conn
->minor
= reply
.minor
;
1500 conn
->minor
= be32toh(msg
.minor
);
1503 reply
.major
= htobe32(reply
.major
);
1504 reply
.minor
= htobe32(reply
.minor
);
1505 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1506 sizeof(struct lttcomm_relayd_version
), 0);
1508 ERR("Relay sending version");
1511 DBG("Version check done using protocol %u.%u", conn
->major
,
1519 * Check for data pending for a given stream id from the session daemon.
1521 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1522 struct relay_connection
*conn
)
1524 struct relay_session
*session
= conn
->session
;
1525 struct lttcomm_relayd_data_pending msg
;
1526 struct lttcomm_relayd_generic_reply reply
;
1527 struct relay_stream
*stream
;
1529 uint64_t last_net_seq_num
, stream_id
;
1531 DBG("Data pending command received");
1533 if (!session
|| conn
->version_check_done
== 0) {
1534 ERR("Trying to check for data before version check");
1536 goto end_no_session
;
1539 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1540 if (ret
< sizeof(msg
)) {
1542 /* Orderly shutdown. Not necessary to print an error. */
1543 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1545 ERR("Relay didn't receive valid data_pending struct size : %d",
1549 goto end_no_session
;
1552 stream_id
= be64toh(msg
.stream_id
);
1553 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1555 stream
= stream_get_by_id(stream_id
);
1556 if (stream
== NULL
) {
1561 pthread_mutex_lock(&stream
->lock
);
1563 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1564 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1567 /* Avoid wrapping issue */
1568 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1569 /* Data has in fact been written and is NOT pending */
1572 /* Data still being streamed thus pending */
1576 stream
->data_pending_check_done
= true;
1577 pthread_mutex_unlock(&stream
->lock
);
1582 memset(&reply
, 0, sizeof(reply
));
1583 reply
.ret_code
= htobe32(ret
);
1584 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1586 ERR("Relay data pending ret code failed");
1594 * Wait for the control socket to reach a quiescent state.
1596 * Note that for now, when receiving this command from the session
1597 * daemon, this means that every subsequent commands or data received on
1598 * the control socket has been handled. So, this is why we simply return
1601 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1602 struct relay_connection
*conn
)
1606 struct relay_stream
*stream
;
1607 struct lttcomm_relayd_quiescent_control msg
;
1608 struct lttcomm_relayd_generic_reply reply
;
1610 DBG("Checking quiescent state on control socket");
1612 if (!conn
->session
|| conn
->version_check_done
== 0) {
1613 ERR("Trying to check for data before version check");
1615 goto end_no_session
;
1618 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1619 if (ret
< sizeof(msg
)) {
1621 /* Orderly shutdown. Not necessary to print an error. */
1622 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1624 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1628 goto end_no_session
;
1631 stream_id
= be64toh(msg
.stream_id
);
1632 stream
= stream_get_by_id(stream_id
);
1636 pthread_mutex_lock(&stream
->lock
);
1637 stream
->data_pending_check_done
= true;
1638 pthread_mutex_unlock(&stream
->lock
);
1639 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1642 memset(&reply
, 0, sizeof(reply
));
1643 reply
.ret_code
= htobe32(LTTNG_OK
);
1644 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1646 ERR("Relay data quiescent control ret code failed");
1654 * Initialize a data pending command. This means that a consumer is about
1655 * to ask for data pending for each stream it holds. Simply iterate over
1656 * all streams of a session and set the data_pending_check_done flag.
1658 * This command returns to the client a LTTNG_OK code.
1660 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1661 struct relay_connection
*conn
)
1664 struct lttng_ht_iter iter
;
1665 struct lttcomm_relayd_begin_data_pending msg
;
1666 struct lttcomm_relayd_generic_reply reply
;
1667 struct relay_stream
*stream
;
1668 uint64_t session_id
;
1673 DBG("Init streams for data pending");
1675 if (!conn
->session
|| conn
->version_check_done
== 0) {
1676 ERR("Trying to check for data before version check");
1678 goto end_no_session
;
1681 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1682 if (ret
< sizeof(msg
)) {
1684 /* Orderly shutdown. Not necessary to print an error. */
1685 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1687 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1691 goto end_no_session
;
1694 session_id
= be64toh(msg
.session_id
);
1697 * Iterate over all streams to set the begin data pending flag.
1698 * For now, the streams are indexed by stream handle so we have
1699 * to iterate over all streams to find the one associated with
1700 * the right session_id.
1703 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1705 if (!stream_get(stream
)) {
1708 if (stream
->trace
->session
->id
== session_id
) {
1709 pthread_mutex_lock(&stream
->lock
);
1710 stream
->data_pending_check_done
= false;
1711 pthread_mutex_unlock(&stream
->lock
);
1712 DBG("Set begin data pending flag to stream %" PRIu64
,
1713 stream
->stream_handle
);
1719 memset(&reply
, 0, sizeof(reply
));
1720 /* All good, send back reply. */
1721 reply
.ret_code
= htobe32(LTTNG_OK
);
1723 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1725 ERR("Relay begin data pending send reply failed");
1733 * End data pending command. This will check, for a given session id, if
1734 * each stream associated with it has its data_pending_check_done flag
1735 * set. If not, this means that the client lost track of the stream but
1736 * the data is still being streamed on our side. In this case, we inform
1737 * the client that data is in flight.
1739 * Return to the client if there is data in flight or not with a ret_code.
1741 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1742 struct relay_connection
*conn
)
1745 struct lttng_ht_iter iter
;
1746 struct lttcomm_relayd_end_data_pending msg
;
1747 struct lttcomm_relayd_generic_reply reply
;
1748 struct relay_stream
*stream
;
1749 uint64_t session_id
;
1750 uint32_t is_data_inflight
= 0;
1752 DBG("End data pending command");
1754 if (!conn
->session
|| conn
->version_check_done
== 0) {
1755 ERR("Trying to check for data before version check");
1757 goto end_no_session
;
1760 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1761 if (ret
< sizeof(msg
)) {
1763 /* Orderly shutdown. Not necessary to print an error. */
1764 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1766 ERR("Relay didn't receive valid end data_pending struct size: %d",
1770 goto end_no_session
;
1773 session_id
= be64toh(msg
.session_id
);
1776 * Iterate over all streams to see if the begin data pending
1780 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1782 if (!stream_get(stream
)) {
1785 if (stream
->trace
->session
->id
!= session_id
) {
1789 pthread_mutex_lock(&stream
->lock
);
1790 if (!stream
->data_pending_check_done
) {
1791 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1792 is_data_inflight
= 1;
1793 DBG("Data is still in flight for stream %" PRIu64
,
1794 stream
->stream_handle
);
1795 pthread_mutex_unlock(&stream
->lock
);
1800 pthread_mutex_unlock(&stream
->lock
);
1805 memset(&reply
, 0, sizeof(reply
));
1806 /* All good, send back reply. */
1807 reply
.ret_code
= htobe32(is_data_inflight
);
1809 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1811 ERR("Relay end data pending send reply failed");
1819 * Receive an index for a specific stream.
1821 * Return 0 on success else a negative value.
1823 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1824 struct relay_connection
*conn
)
1827 struct relay_session
*session
= conn
->session
;
1828 struct lttcomm_relayd_index index_info
;
1829 struct relay_index
*index
;
1830 struct lttcomm_relayd_generic_reply reply
;
1831 struct relay_stream
*stream
;
1832 uint64_t net_seq_num
;
1836 DBG("Relay receiving index");
1838 if (!session
|| conn
->version_check_done
== 0) {
1839 ERR("Trying to close a stream before version check");
1841 goto end_no_session
;
1844 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1845 sizeof(index_info
), 0);
1846 if (ret
< sizeof(index_info
)) {
1848 /* Orderly shutdown. Not necessary to print an error. */
1849 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1851 ERR("Relay didn't receive valid index struct size : %d", ret
);
1854 goto end_no_session
;
1857 net_seq_num
= be64toh(index_info
.net_seq_num
);
1859 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1861 ERR("stream_get_by_id not found");
1865 pthread_mutex_lock(&stream
->lock
);
1867 /* Live beacon handling */
1868 if (index_info
.packet_size
== 0) {
1869 DBG("Received live beacon for stream %" PRIu64
,
1870 stream
->stream_handle
);
1873 * Only flag a stream inactive when it has already
1874 * received data and no indexes are in flight.
1876 if (stream
->index_received_seqcount
> 0
1877 && stream
->indexes_in_flight
== 0) {
1878 stream
->beacon_ts_end
=
1879 be64toh(index_info
.timestamp_end
);
1882 goto end_stream_put
;
1884 stream
->beacon_ts_end
= -1ULL;
1887 if (stream
->ctf_stream_id
== -1ULL) {
1888 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1890 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1893 ERR("relay_index_get_by_id_or_create index NULL");
1894 goto end_stream_put
;
1896 if (set_index_control_data(index
, &index_info
)) {
1897 ERR("set_index_control_data error");
1898 relay_index_put(index
);
1900 goto end_stream_put
;
1902 ret
= relay_index_try_flush(index
);
1904 tracefile_array_commit_seq(stream
->tfa
);
1905 stream
->index_received_seqcount
++;
1906 } else if (ret
> 0) {
1910 ERR("relay_index_try_flush error %d", ret
);
1911 relay_index_put(index
);
1916 pthread_mutex_unlock(&stream
->lock
);
1921 memset(&reply
, 0, sizeof(reply
));
1923 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1925 reply
.ret_code
= htobe32(LTTNG_OK
);
1927 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1929 ERR("Relay sending close index id reply");
1938 * Receive the streams_sent message.
1940 * Return 0 on success else a negative value.
1942 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1943 struct relay_connection
*conn
)
1946 struct lttcomm_relayd_generic_reply reply
;
1950 DBG("Relay receiving streams_sent");
1952 if (!conn
->session
|| conn
->version_check_done
== 0) {
1953 ERR("Trying to close a stream before version check");
1955 goto end_no_session
;
1959 * Publish every pending stream in the connection recv list which are
1960 * now ready to be used by the viewer.
1962 publish_connection_local_streams(conn
);
1964 memset(&reply
, 0, sizeof(reply
));
1965 reply
.ret_code
= htobe32(LTTNG_OK
);
1966 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1968 ERR("Relay sending sent_stream reply");
1980 * Process the commands received on the control socket
1982 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1983 struct relay_connection
*conn
)
1987 switch (be32toh(recv_hdr
->cmd
)) {
1988 case RELAYD_CREATE_SESSION
:
1989 ret
= relay_create_session(recv_hdr
, conn
);
1991 case RELAYD_ADD_STREAM
:
1992 ret
= relay_add_stream(recv_hdr
, conn
);
1994 case RELAYD_START_DATA
:
1995 ret
= relay_start(recv_hdr
, conn
);
1997 case RELAYD_SEND_METADATA
:
1998 ret
= relay_recv_metadata(recv_hdr
, conn
);
2000 case RELAYD_VERSION
:
2001 ret
= relay_send_version(recv_hdr
, conn
);
2003 case RELAYD_CLOSE_STREAM
:
2004 ret
= relay_close_stream(recv_hdr
, conn
);
2006 case RELAYD_DATA_PENDING
:
2007 ret
= relay_data_pending(recv_hdr
, conn
);
2009 case RELAYD_QUIESCENT_CONTROL
:
2010 ret
= relay_quiescent_control(recv_hdr
, conn
);
2012 case RELAYD_BEGIN_DATA_PENDING
:
2013 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2015 case RELAYD_END_DATA_PENDING
:
2016 ret
= relay_end_data_pending(recv_hdr
, conn
);
2018 case RELAYD_SEND_INDEX
:
2019 ret
= relay_recv_index(recv_hdr
, conn
);
2021 case RELAYD_STREAMS_SENT
:
2022 ret
= relay_streams_sent(recv_hdr
, conn
);
2024 case RELAYD_UPDATE_SYNC_INFO
:
2026 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2027 relay_unknown_command(conn
);
2037 * Handle index for a data stream.
2039 * Called with the stream lock held.
2041 * Return 0 on success else a negative value.
2043 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2047 uint64_t data_offset
;
2048 struct relay_index
*index
;
2050 /* Get data offset because we are about to update the index. */
2051 data_offset
= htobe64(stream
->tracefile_size_current
);
2053 DBG("handle_index_data: stream %" PRIu64
" data offset %" PRIu64
,
2054 stream
->stream_handle
, stream
->tracefile_size_current
);
2057 * Lookup for an existing index for that stream id/sequence
2058 * number. If it exists, the control thread has already received the
2059 * data for it, thus we need to write it to disk.
2061 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2067 if (rotate_index
|| !stream
->index_fd
) {
2070 /* Put ref on previous index_fd. */
2071 if (stream
->index_fd
) {
2072 stream_fd_put(stream
->index_fd
);
2073 stream
->index_fd
= NULL
;
2076 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2077 -1, -1, stream
->tracefile_size
,
2078 tracefile_array_get_file_index_head(stream
->tfa
));
2081 /* Put self-ref for this index due to error. */
2082 relay_index_put(index
);
2085 stream
->index_fd
= stream_fd_create(fd
);
2086 if (!stream
->index_fd
) {
2089 PERROR("Error closing FD %d", fd
);
2091 /* Put self-ref for this index due to error. */
2092 relay_index_put(index
);
2093 /* Will put the local ref. */
2098 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2100 /* Put self-ref for this index due to error. */
2101 relay_index_put(index
);
2105 ret
= relay_index_try_flush(index
);
2107 tracefile_array_commit_seq(stream
->tfa
);
2108 stream
->index_received_seqcount
++;
2109 } else if (ret
> 0) {
2113 /* Put self-ref for this index due to error. */
2114 relay_index_put(index
);
2122 * relay_process_data: Process the data received on the data socket
2124 static int relay_process_data(struct relay_connection
*conn
)
2126 int ret
= 0, rotate_index
= 0;
2128 struct relay_stream
*stream
;
2129 struct lttcomm_relayd_data_hdr data_hdr
;
2131 uint64_t net_seq_num
;
2133 struct relay_session
*session
;
2134 bool new_stream
= false, close_requested
= false;
2136 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2137 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2140 /* Orderly shutdown. Not necessary to print an error. */
2141 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2143 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2149 stream_id
= be64toh(data_hdr
.stream_id
);
2150 stream
= stream_get_by_id(stream_id
);
2155 session
= stream
->trace
->session
;
2156 data_size
= be32toh(data_hdr
.data_size
);
2157 if (data_buffer_size
< data_size
) {
2160 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2161 if (!tmp_data_ptr
) {
2162 ERR("Allocating data buffer");
2165 goto end_stream_put
;
2167 data_buffer
= tmp_data_ptr
;
2168 data_buffer_size
= data_size
;
2170 memset(data_buffer
, 0, data_size
);
2172 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2174 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2175 data_size
, stream_id
, net_seq_num
);
2176 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2179 /* Orderly shutdown. Not necessary to print an error. */
2180 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2183 goto end_stream_put
;
2186 pthread_mutex_lock(&stream
->lock
);
2188 /* Check if a rotation is needed. */
2189 if (stream
->tracefile_size
> 0 &&
2190 (stream
->tracefile_size_current
+ data_size
) >
2191 stream
->tracefile_size
) {
2192 uint64_t old_id
, new_id
;
2194 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2195 tracefile_array_file_rotate(stream
->tfa
);
2197 /* new_id is updated by utils_rotate_stream_file. */
2200 ret
= utils_rotate_stream_file(stream
->path_name
,
2201 stream
->channel_name
, stream
->tracefile_size
,
2202 stream
->tracefile_count
, -1,
2203 -1, stream
->stream_fd
->fd
,
2204 &new_id
, &stream
->stream_fd
->fd
);
2206 ERR("Rotating stream output file");
2207 goto end_stream_unlock
;
2210 * Reset current size because we just performed a stream
2213 stream
->tracefile_size_current
= 0;
2218 * Index are handled in protocol version 2.4 and above. Also,
2219 * snapshot and index are NOT supported.
2221 if (session
->minor
>= 4 && !session
->snapshot
) {
2222 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2224 goto end_stream_unlock
;
2228 /* Write data to stream output fd. */
2229 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2230 if (size_ret
< data_size
) {
2231 ERR("Relay error writing data to file");
2233 goto end_stream_unlock
;
2236 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2237 size_ret
, stream
->stream_handle
);
2239 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2240 be32toh(data_hdr
.padding_size
));
2242 goto end_stream_unlock
;
2244 stream
->tracefile_size_current
+=
2245 data_size
+ be32toh(data_hdr
.padding_size
);
2246 if (stream
->prev_seq
== -1ULL) {
2250 stream
->prev_seq
= net_seq_num
;
2253 close_requested
= stream
->close_requested
;
2254 pthread_mutex_unlock(&stream
->lock
);
2255 if (close_requested
) {
2256 try_stream_close(stream
);
2260 pthread_mutex_lock(&session
->lock
);
2261 uatomic_set(&session
->new_streams
, 1);
2262 pthread_mutex_unlock(&session
->lock
);
2270 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2274 (void) lttng_poll_del(events
, pollfd
);
2276 ret
= close(pollfd
);
2278 ERR("Closing pollfd %d", pollfd
);
2282 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2283 int pollfd
, struct relay_connection
*conn
)
2285 const char *type_str
;
2287 switch (conn
->type
) {
2292 type_str
= "Control";
2294 case RELAY_VIEWER_COMMAND
:
2295 type_str
= "Viewer Command";
2297 case RELAY_VIEWER_NOTIFICATION
:
2298 type_str
= "Viewer Notification";
2301 type_str
= "Unknown";
2303 cleanup_connection_pollfd(events
, pollfd
);
2304 connection_put(conn
);
2305 DBG("%s connection closed with %d", type_str
, pollfd
);
2309 * This thread does the actual work
2311 static void *relay_thread_worker(void *data
)
2313 int ret
, err
= -1, last_seen_data_fd
= -1;
2315 struct lttng_poll_event events
;
2316 struct lttng_ht
*relay_connections_ht
;
2317 struct lttng_ht_iter iter
;
2318 struct lttcomm_relayd_hdr recv_hdr
;
2319 struct relay_connection
*destroy_conn
= NULL
;
2321 DBG("[thread] Relay worker started");
2323 rcu_register_thread();
2325 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2327 if (testpoint(relayd_thread_worker
)) {
2328 goto error_testpoint
;
2331 health_code_update();
2333 /* table of connections indexed on socket */
2334 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2335 if (!relay_connections_ht
) {
2336 goto relay_connections_ht_error
;
2339 ret
= create_thread_poll_set(&events
, 2);
2341 goto error_poll_create
;
2344 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2351 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2353 health_code_update();
2355 /* Infinite blocking call, waiting for transmission */
2356 DBG3("Relayd worker thread polling...");
2357 health_poll_entry();
2358 ret
= lttng_poll_wait(&events
, -1);
2362 * Restart interrupted system call.
2364 if (errno
== EINTR
) {
2373 * Process control. The control connection is
2374 * prioritized so we don't starve it with high
2375 * throughput tracing data on the data connection.
2377 for (i
= 0; i
< nb_fd
; i
++) {
2378 /* Fetch once the poll data */
2379 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2380 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2382 health_code_update();
2386 * No activity for this FD (poll
2392 /* Thread quit pipe has been closed. Killing thread. */
2393 ret
= check_thread_quit_pipe(pollfd
, revents
);
2399 /* Inspect the relay conn pipe for new connection */
2400 if (pollfd
== relay_conn_pipe
[0]) {
2401 if (revents
& LPOLLIN
) {
2402 struct relay_connection
*conn
;
2404 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2408 lttng_poll_add(&events
, conn
->sock
->fd
,
2409 LPOLLIN
| LPOLLRDHUP
);
2410 connection_ht_add(relay_connections_ht
, conn
);
2411 DBG("Connection socket %d added", conn
->sock
->fd
);
2412 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2413 ERR("Relay connection pipe error");
2416 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2420 struct relay_connection
*ctrl_conn
;
2422 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2423 /* If not found, there is a synchronization issue. */
2426 if (ctrl_conn
->type
== RELAY_DATA
) {
2427 if (revents
& LPOLLIN
) {
2429 * Flag the last seen data fd not deleted. It will be
2430 * used as the last seen fd if any fd gets deleted in
2433 last_notdel_data_fd
= pollfd
;
2435 goto put_ctrl_connection
;
2437 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2439 if (revents
& LPOLLIN
) {
2440 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2441 &recv_hdr
, sizeof(recv_hdr
), 0);
2443 /* Connection closed */
2444 relay_thread_close_connection(&events
, pollfd
,
2447 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2449 /* Clear the session on error. */
2450 relay_thread_close_connection(&events
,
2455 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2456 relay_thread_close_connection(&events
,
2458 if (last_seen_data_fd
== pollfd
) {
2459 last_seen_data_fd
= last_notdel_data_fd
;
2462 ERR("Unexpected poll events %u for control sock %d",
2464 connection_put(ctrl_conn
);
2467 put_ctrl_connection
:
2468 connection_put(ctrl_conn
);
2473 * The last loop handled a control request, go back to poll to make
2474 * sure we prioritise the control socket.
2480 if (last_seen_data_fd
>= 0) {
2481 for (i
= 0; i
< nb_fd
; i
++) {
2482 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2484 health_code_update();
2486 if (last_seen_data_fd
== pollfd
) {
2493 /* Process data connection. */
2494 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2495 /* Fetch the poll data. */
2496 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2497 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2498 struct relay_connection
*data_conn
;
2500 health_code_update();
2503 /* No activity for this FD (poll implementation). */
2507 /* Skip the command pipe. It's handled in the first loop. */
2508 if (pollfd
== relay_conn_pipe
[0]) {
2512 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2514 /* Skip it. Might be removed before. */
2517 if (data_conn
->type
== RELAY_CONTROL
) {
2518 goto put_data_connection
;
2520 assert(data_conn
->type
== RELAY_DATA
);
2522 if (revents
& LPOLLIN
) {
2523 ret
= relay_process_data(data_conn
);
2524 /* Connection closed */
2526 relay_thread_close_connection(&events
, pollfd
,
2529 * Every goto restart call sets the last seen fd where
2530 * here we don't really care since we gracefully
2531 * continue the loop after the connection is deleted.
2534 /* Keep last seen port. */
2535 last_seen_data_fd
= pollfd
;
2536 connection_put(data_conn
);
2539 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2540 relay_thread_close_connection(&events
, pollfd
,
2543 ERR("Unknown poll events %u for data sock %d",
2546 put_data_connection
:
2547 connection_put(data_conn
);
2549 last_seen_data_fd
= -1;
2552 /* Normal exit, no error */
2557 /* Cleanup reamaining connection object. */
2559 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2562 health_code_update();
2564 * No need to grab another ref, because we own
2567 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2572 lttng_poll_clean(&events
);
2574 lttng_ht_destroy(relay_connections_ht
);
2575 relay_connections_ht_error
:
2576 /* Close relay conn pipes */
2577 utils_close_pipe(relay_conn_pipe
);
2579 DBG("Thread exited with error");
2581 DBG("Worker thread cleanup complete");
2586 ERR("Health error occurred in %s", __func__
);
2588 health_unregister(health_relayd
);
2589 rcu_unregister_thread();
2590 lttng_relay_stop_threads();
2595 * Create the relay command pipe to wake thread_manage_apps.
2596 * Closed in cleanup().
2598 static int create_relay_conn_pipe(void)
2602 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2610 int main(int argc
, char **argv
)
2612 int ret
= 0, retval
= 0;
2615 /* Parse arguments */
2617 if (set_options(argc
, argv
)) {
2622 if (set_signal_handler()) {
2627 /* Try to create directory if -o, --output is specified. */
2628 if (opt_output_path
) {
2629 if (*opt_output_path
!= '/') {
2630 ERR("Please specify an absolute path for -o, --output PATH");
2635 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2638 ERR("Unable to create %s", opt_output_path
);
2645 if (opt_daemon
|| opt_background
) {
2648 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2656 * We are in the child. Make sure all other file
2657 * descriptors are closed, in case we are called with
2658 * more opened file descriptors than the standard ones.
2660 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2666 /* Initialize thread health monitoring */
2667 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2668 if (!health_relayd
) {
2669 PERROR("health_app_create error");
2671 goto exit_health_app_create
;
2674 /* Create thread quit pipe */
2675 if (init_thread_quit_pipe()) {
2677 goto exit_init_data
;
2680 /* Check if daemon is UID = 0 */
2682 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2683 ERR("Need to be root to use ports < 1024");
2685 goto exit_init_data
;
2689 /* Setup the thread apps communication pipe. */
2690 if (create_relay_conn_pipe()) {
2692 goto exit_init_data
;
2695 /* Init relay command queue. */
2696 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2698 /* Set up max poll set size */
2699 lttng_poll_set_max_size();
2701 /* Initialize communication library */
2703 lttcomm_inet_init();
2705 /* tables of sessions indexed by session ID */
2706 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2709 goto exit_init_data
;
2712 /* tables of streams indexed by stream ID */
2713 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2714 if (!relay_streams_ht
) {
2716 goto exit_init_data
;
2719 /* tables of streams indexed by stream ID */
2720 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2721 if (!viewer_streams_ht
) {
2723 goto exit_init_data
;
2726 ret
= utils_create_pipe(health_quit_pipe
);
2729 goto exit_health_quit_pipe
;
2732 /* Create thread to manage the client socket */
2733 ret
= pthread_create(&health_thread
, NULL
,
2734 thread_manage_health
, (void *) NULL
);
2737 PERROR("pthread_create health");
2739 goto exit_health_thread
;
2742 /* Setup the dispatcher thread */
2743 ret
= pthread_create(&dispatcher_thread
, NULL
,
2744 relay_thread_dispatcher
, (void *) NULL
);
2747 PERROR("pthread_create dispatcher");
2749 goto exit_dispatcher_thread
;
2752 /* Setup the worker thread */
2753 ret
= pthread_create(&worker_thread
, NULL
,
2754 relay_thread_worker
, NULL
);
2757 PERROR("pthread_create worker");
2759 goto exit_worker_thread
;
2762 /* Setup the listener thread */
2763 ret
= pthread_create(&listener_thread
, NULL
,
2764 relay_thread_listener
, (void *) NULL
);
2767 PERROR("pthread_create listener");
2769 goto exit_listener_thread
;
2772 ret
= relayd_live_create(live_uri
);
2774 ERR("Starting live viewer threads");
2780 * This is where we start awaiting program completion (e.g. through
2781 * signal that asks threads to teardown).
2784 ret
= relayd_live_join();
2790 ret
= pthread_join(listener_thread
, &status
);
2793 PERROR("pthread_join listener_thread");
2797 exit_listener_thread
:
2798 ret
= pthread_join(worker_thread
, &status
);
2801 PERROR("pthread_join worker_thread");
2806 ret
= pthread_join(dispatcher_thread
, &status
);
2809 PERROR("pthread_join dispatcher_thread");
2812 exit_dispatcher_thread
:
2814 ret
= pthread_join(health_thread
, &status
);
2817 PERROR("pthread_join health_thread");
2822 utils_close_pipe(health_quit_pipe
);
2823 exit_health_quit_pipe
:
2826 health_app_destroy(health_relayd
);
2827 exit_health_app_create
:
2831 /* Ensure all prior call_rcu are done. */