2 * Copyright (C) 2012 - Julien Desfossez <jdesfossez@efficios.com>
3 * David Goulet <dgoulet@efficios.com>
4 * 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * 2015 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 2 only,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
38 #include <urcu/futex.h>
39 #include <urcu/uatomic.h>
43 #include <lttng/lttng.h>
44 #include <common/common.h>
45 #include <common/compat/poll.h>
46 #include <common/compat/socket.h>
47 #include <common/compat/endian.h>
48 #include <common/compat/getenv.h>
49 #include <common/defaults.h>
50 #include <common/daemonize.h>
51 #include <common/futex.h>
52 #include <common/sessiond-comm/sessiond-comm.h>
53 #include <common/sessiond-comm/inet.h>
54 #include <common/sessiond-comm/relayd.h>
55 #include <common/uri.h>
56 #include <common/utils.h>
57 #include <common/config/session-config.h>
58 #include <urcu/rculist.h>
61 #include "ctf-trace.h"
64 #include "lttng-relayd.h"
66 #include "health-relayd.h"
67 #include "testpoint.h"
68 #include "viewer-stream.h"
71 #include "connection.h"
72 #include "tracefile-array.h"
74 /* command line options */
75 char *opt_output_path
;
76 static int opt_daemon
, opt_background
;
79 * We need to wait for listener and live listener threads, as well as
80 * health check thread, before being ready to signal readiness.
82 #define NR_LTTNG_RELAY_READY 3
83 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
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 if (lttng_is_setuid_setgid()) {
202 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
203 "-C, --control-port");
205 ret
= uri_parse(arg
, &control_uri
);
207 ERR("Invalid control URI specified");
210 if (control_uri
->port
== 0) {
211 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
216 if (lttng_is_setuid_setgid()) {
217 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
220 ret
= uri_parse(arg
, &data_uri
);
222 ERR("Invalid data URI specified");
225 if (data_uri
->port
== 0) {
226 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
231 if (lttng_is_setuid_setgid()) {
232 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
235 ret
= uri_parse(arg
, &live_uri
);
237 ERR("Invalid live URI specified");
240 if (live_uri
->port
== 0) {
241 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
252 if (lttng_is_setuid_setgid()) {
253 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
256 tracing_group_name
= strdup(arg
);
257 if (tracing_group_name
== NULL
) {
262 tracing_group_name_override
= 1;
269 if (lttng_is_setuid_setgid()) {
270 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
273 ret
= asprintf(&opt_output_path
, "%s", arg
);
276 PERROR("asprintf opt_output_path");
282 /* Verbose level can increase using multiple -v */
284 lttng_opt_verbose
= config_parse_value(arg
);
286 /* Only 3 level of verbosity (-vvv). */
287 if (lttng_opt_verbose
< 3) {
288 lttng_opt_verbose
+= 1;
293 /* Unknown option or other error.
294 * Error is printed by getopt, just return */
307 * config_entry_handler_cb used to handle options read from a config file.
308 * See config_entry_handler_cb comment in common/config/session-config.h for the
309 * return value conventions.
311 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
315 if (!entry
|| !entry
->name
|| !entry
->value
) {
320 /* Check if the option is to be ignored */
321 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
322 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
327 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
328 /* Ignore if entry name is not fully matched. */
329 if (strcmp(entry
->name
, long_options
[i
].name
)) {
334 * If the option takes no argument on the command line,
335 * we have to check if the value is "true". We support
336 * non-zero numeric values, true, on and yes.
338 if (!long_options
[i
].has_arg
) {
339 ret
= config_parse_value(entry
->value
);
342 WARN("Invalid configuration value \"%s\" for option %s",
343 entry
->value
, entry
->name
);
345 /* False, skip boolean config option. */
350 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
354 WARN("Unrecognized option \"%s\" in daemon configuration file.",
361 static int set_options(int argc
, char **argv
)
363 int c
, ret
= 0, option_index
= 0, retval
= 0;
364 int orig_optopt
= optopt
, orig_optind
= optind
;
365 char *default_address
, *optstring
;
366 const char *config_path
= NULL
;
368 optstring
= utils_generate_optstring(long_options
,
369 sizeof(long_options
) / sizeof(struct option
));
375 /* Check for the --config option */
377 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
378 &option_index
)) != -1) {
382 } else if (c
!= 'f') {
386 if (lttng_is_setuid_setgid()) {
387 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
390 config_path
= utils_expand_path(optarg
);
392 ERR("Failed to resolve path: %s", optarg
);
397 ret
= config_get_section_entries(config_path
, config_section_name
,
398 config_entry_handler
, NULL
);
401 ERR("Invalid configuration option at line %i", ret
);
407 /* Reset getopt's global state */
408 optopt
= orig_optopt
;
409 optind
= orig_optind
;
411 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
416 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
423 /* assign default values */
424 if (control_uri
== NULL
) {
425 ret
= asprintf(&default_address
,
426 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
427 DEFAULT_NETWORK_CONTROL_PORT
);
429 PERROR("asprintf default data address");
434 ret
= uri_parse(default_address
, &control_uri
);
435 free(default_address
);
437 ERR("Invalid control URI specified");
442 if (data_uri
== NULL
) {
443 ret
= asprintf(&default_address
,
444 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
445 DEFAULT_NETWORK_DATA_PORT
);
447 PERROR("asprintf default data address");
452 ret
= uri_parse(default_address
, &data_uri
);
453 free(default_address
);
455 ERR("Invalid data URI specified");
460 if (live_uri
== NULL
) {
461 ret
= asprintf(&default_address
,
462 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
463 DEFAULT_NETWORK_VIEWER_PORT
);
465 PERROR("asprintf default viewer control address");
470 ret
= uri_parse(default_address
, &live_uri
);
471 free(default_address
);
473 ERR("Invalid viewer control URI specified");
484 static void print_global_objects(void)
486 rcu_register_thread();
488 print_viewer_streams();
489 print_relay_streams();
492 rcu_unregister_thread();
498 static void relayd_cleanup(void)
500 print_global_objects();
504 if (viewer_streams_ht
)
505 lttng_ht_destroy(viewer_streams_ht
);
506 if (relay_streams_ht
)
507 lttng_ht_destroy(relay_streams_ht
);
509 lttng_ht_destroy(sessions_ht
);
511 /* free the dynamically allocated opt_output_path */
512 free(opt_output_path
);
514 /* Close thread quit pipes */
515 utils_close_pipe(thread_quit_pipe
);
517 uri_free(control_uri
);
519 /* Live URI is freed in the live thread. */
521 if (tracing_group_name_override
) {
522 free((void *) tracing_group_name
);
527 * Write to writable pipe used to notify a thread.
529 static int notify_thread_pipe(int wpipe
)
533 ret
= lttng_write(wpipe
, "!", 1);
535 PERROR("write poll pipe");
543 static int notify_health_quit_pipe(int *pipe
)
547 ret
= lttng_write(pipe
[1], "4", 1);
549 PERROR("write relay health quit");
558 * Stop all relayd and relayd-live threads.
560 int lttng_relay_stop_threads(void)
564 /* Stopping all threads */
565 DBG("Terminating all threads");
566 if (notify_thread_pipe(thread_quit_pipe
[1])) {
567 ERR("write error on thread quit pipe");
571 if (notify_health_quit_pipe(health_quit_pipe
)) {
572 ERR("write error on health quit pipe");
575 /* Dispatch thread */
576 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
577 futex_nto1_wake(&relay_conn_queue
.futex
);
579 if (relayd_live_stop()) {
580 ERR("Error stopping live threads");
587 * Signal handler for the daemon
589 * Simply stop all worker threads, leaving main() return gracefully after
590 * joining all threads and calling cleanup().
592 static void sighandler(int sig
)
596 DBG("SIGPIPE caught");
599 DBG("SIGINT caught");
600 if (lttng_relay_stop_threads()) {
601 ERR("Error stopping threads");
605 DBG("SIGTERM caught");
606 if (lttng_relay_stop_threads()) {
607 ERR("Error stopping threads");
611 CMM_STORE_SHARED(recv_child_signal
, 1);
619 * Setup signal handler for :
620 * SIGINT, SIGTERM, SIGPIPE
622 static int set_signal_handler(void)
628 if ((ret
= sigemptyset(&sigset
)) < 0) {
629 PERROR("sigemptyset");
633 sa
.sa_handler
= sighandler
;
636 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
641 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
646 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
651 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
656 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
661 void lttng_relay_notify_ready(void)
663 /* Notify the parent of the fork() process that we are ready. */
664 if (opt_daemon
|| opt_background
) {
665 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
666 kill(child_ppid
, SIGUSR1
);
672 * Init thread quit pipe.
674 * Return -1 on error or 0 if all pipes are created.
676 static int init_thread_quit_pipe(void)
680 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
686 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
688 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
692 if (events
== NULL
|| size
== 0) {
697 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
703 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
715 * Check if the thread quit pipe was triggered.
717 * Return 1 if it was triggered else 0;
719 static int check_thread_quit_pipe(int fd
, uint32_t events
)
721 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
729 * Create and init socket from uri.
731 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
734 struct lttcomm_sock
*sock
= NULL
;
736 sock
= lttcomm_alloc_sock_from_uri(uri
);
738 ERR("Allocating socket");
742 ret
= lttcomm_create_sock(sock
);
746 DBG("Listening on sock %d", sock
->fd
);
748 ret
= sock
->ops
->bind(sock
);
753 ret
= sock
->ops
->listen(sock
, -1);
763 lttcomm_destroy_sock(sock
);
769 * This thread manages the listening for new connections on the network
771 static void *relay_thread_listener(void *data
)
773 int i
, ret
, pollfd
, err
= -1;
774 uint32_t revents
, nb_fd
;
775 struct lttng_poll_event events
;
776 struct lttcomm_sock
*control_sock
, *data_sock
;
778 DBG("[thread] Relay listener started");
780 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
782 health_code_update();
784 control_sock
= relay_socket_create(control_uri
);
786 goto error_sock_control
;
789 data_sock
= relay_socket_create(data_uri
);
791 goto error_sock_relay
;
795 * Pass 3 as size here for the thread quit pipe, control and
798 ret
= create_thread_poll_set(&events
, 3);
800 goto error_create_poll
;
803 /* Add the control socket */
804 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
809 /* Add the data socket */
810 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
815 lttng_relay_notify_ready();
817 if (testpoint(relayd_thread_listener
)) {
818 goto error_testpoint
;
822 health_code_update();
824 DBG("Listener accepting connections");
828 ret
= lttng_poll_wait(&events
, -1);
832 * Restart interrupted system call.
834 if (errno
== EINTR
) {
842 DBG("Relay new connection received");
843 for (i
= 0; i
< nb_fd
; i
++) {
844 health_code_update();
846 /* Fetch once the poll data */
847 revents
= LTTNG_POLL_GETEV(&events
, i
);
848 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
852 * No activity for this FD (poll
858 /* Thread quit pipe has been closed. Killing thread. */
859 ret
= check_thread_quit_pipe(pollfd
, revents
);
865 if (revents
& LPOLLIN
) {
867 * A new connection is requested, therefore a
868 * sessiond/consumerd connection is allocated in
869 * this thread, enqueued to a global queue and
870 * dequeued (and freed) in the worker thread.
873 struct relay_connection
*new_conn
;
874 struct lttcomm_sock
*newsock
;
875 enum connection_type type
;
877 if (pollfd
== data_sock
->fd
) {
879 newsock
= data_sock
->ops
->accept(data_sock
);
880 DBG("Relay data connection accepted, socket %d",
883 assert(pollfd
== control_sock
->fd
);
884 type
= RELAY_CONTROL
;
885 newsock
= control_sock
->ops
->accept(control_sock
);
886 DBG("Relay control connection accepted, socket %d",
890 PERROR("accepting sock");
894 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
897 PERROR("setsockopt inet");
898 lttcomm_destroy_sock(newsock
);
901 new_conn
= connection_create(newsock
, type
);
903 lttcomm_destroy_sock(newsock
);
907 /* Enqueue request for the dispatcher thread. */
908 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
912 * Wake the dispatch queue futex.
913 * Implicit memory barrier with the
914 * exchange in cds_wfcq_enqueue.
916 futex_nto1_wake(&relay_conn_queue
.futex
);
917 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
918 ERR("socket poll error");
921 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
931 lttng_poll_clean(&events
);
933 if (data_sock
->fd
>= 0) {
934 ret
= data_sock
->ops
->close(data_sock
);
939 lttcomm_destroy_sock(data_sock
);
941 if (control_sock
->fd
>= 0) {
942 ret
= control_sock
->ops
->close(control_sock
);
947 lttcomm_destroy_sock(control_sock
);
951 ERR("Health error occurred in %s", __func__
);
953 health_unregister(health_relayd
);
954 DBG("Relay listener thread cleanup complete");
955 lttng_relay_stop_threads();
960 * This thread manages the dispatching of the requests to worker threads
962 static void *relay_thread_dispatcher(void *data
)
966 struct cds_wfcq_node
*node
;
967 struct relay_connection
*new_conn
= NULL
;
969 DBG("[thread] Relay dispatcher started");
971 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
973 if (testpoint(relayd_thread_dispatcher
)) {
974 goto error_testpoint
;
977 health_code_update();
979 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
980 health_code_update();
982 /* Atomically prepare the queue futex */
983 futex_nto1_prepare(&relay_conn_queue
.futex
);
986 health_code_update();
988 /* Dequeue commands */
989 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
990 &relay_conn_queue
.tail
);
992 DBG("Woken up but nothing in the relay command queue");
993 /* Continue thread execution */
996 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
998 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1001 * Inform worker thread of the new request. This
1002 * call is blocking so we can be assured that
1003 * the data will be read at some point in time
1004 * or wait to the end of the world :)
1006 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1008 PERROR("write connection pipe");
1009 connection_put(new_conn
);
1012 } while (node
!= NULL
);
1014 /* Futex wait on queue. Blocking call on futex() */
1015 health_poll_entry();
1016 futex_nto1_wait(&relay_conn_queue
.futex
);
1020 /* Normal exit, no error */
1027 ERR("Health error occurred in %s", __func__
);
1029 health_unregister(health_relayd
);
1030 DBG("Dispatch thread dying");
1031 lttng_relay_stop_threads();
1036 * Set index data from the control port to a given index object.
1038 static int set_index_control_data(struct relay_index
*index
,
1039 struct lttcomm_relayd_index
*data
)
1041 struct ctf_packet_index index_data
;
1044 * The index on disk is encoded in big endian, so we don't need
1045 * to convert the data received on the network. The data_offset
1046 * value is NEVER modified here and is updated by the data
1049 index_data
.packet_size
= data
->packet_size
;
1050 index_data
.content_size
= data
->content_size
;
1051 index_data
.timestamp_begin
= data
->timestamp_begin
;
1052 index_data
.timestamp_end
= data
->timestamp_end
;
1053 index_data
.events_discarded
= data
->events_discarded
;
1054 index_data
.stream_id
= data
->stream_id
;
1055 return relay_index_set_data(index
, &index_data
);
1059 * Handle the RELAYD_CREATE_SESSION command.
1061 * On success, send back the session id or else return a negative value.
1063 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1064 struct relay_connection
*conn
)
1066 int ret
= 0, send_ret
;
1067 struct relay_session
*session
;
1068 struct lttcomm_relayd_status_session reply
;
1069 char session_name
[LTTNG_NAME_MAX
];
1070 char hostname
[LTTNG_HOST_NAME_MAX
];
1071 uint32_t live_timer
= 0;
1072 bool snapshot
= false;
1074 memset(session_name
, 0, LTTNG_NAME_MAX
);
1075 memset(hostname
, 0, LTTNG_HOST_NAME_MAX
);
1077 memset(&reply
, 0, sizeof(reply
));
1079 switch (conn
->minor
) {
1084 case 4: /* LTTng sessiond 2.4 */
1086 ret
= cmd_create_session_2_4(conn
, session_name
,
1087 hostname
, &live_timer
, &snapshot
);
1093 session
= session_create(session_name
, hostname
, live_timer
,
1094 snapshot
, conn
->major
, conn
->minor
);
1099 assert(!conn
->session
);
1100 conn
->session
= session
;
1101 DBG("Created session %" PRIu64
, session
->id
);
1103 reply
.session_id
= htobe64(session
->id
);
1107 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1109 reply
.ret_code
= htobe32(LTTNG_OK
);
1112 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1114 ERR("Relayd sending session id");
1122 * When we have received all the streams and the metadata for a channel,
1123 * we make them visible to the viewer threads.
1125 static void publish_connection_local_streams(struct relay_connection
*conn
)
1127 struct relay_stream
*stream
;
1128 struct relay_session
*session
= conn
->session
;
1131 * We publish all streams belonging to a session atomically wrt
1134 pthread_mutex_lock(&session
->lock
);
1136 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1138 stream_publish(stream
);
1143 * Inform the viewer that there are new streams in the session.
1145 if (session
->viewer_attached
) {
1146 uatomic_set(&session
->new_streams
, 1);
1148 pthread_mutex_unlock(&session
->lock
);
1152 * relay_add_stream: allocate a new stream for a session
1154 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1155 struct relay_connection
*conn
)
1159 struct relay_session
*session
= conn
->session
;
1160 struct relay_stream
*stream
= NULL
;
1161 struct lttcomm_relayd_status_stream reply
;
1162 struct ctf_trace
*trace
= NULL
;
1163 uint64_t stream_handle
= -1ULL;
1164 char *path_name
= NULL
, *channel_name
= NULL
;
1165 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1167 if (!session
|| conn
->version_check_done
== 0) {
1168 ERR("Trying to add a stream before version check");
1170 goto end_no_session
;
1173 switch (session
->minor
) {
1174 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1175 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1178 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1180 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1181 &channel_name
, &tracefile_size
, &tracefile_count
);
1188 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1192 /* This stream here has one reference on the trace. */
1194 pthread_mutex_lock(&last_relay_stream_id_lock
);
1195 stream_handle
= ++last_relay_stream_id
;
1196 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1198 /* We pass ownership of path_name and channel_name. */
1199 stream
= stream_create(trace
, stream_handle
, path_name
,
1200 channel_name
, tracefile_size
, tracefile_count
);
1202 channel_name
= NULL
;
1205 * Streams are the owners of their trace. Reference to trace is
1206 * kept within stream_create().
1208 ctf_trace_put(trace
);
1211 memset(&reply
, 0, sizeof(reply
));
1212 reply
.handle
= htobe64(stream_handle
);
1214 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1216 reply
.ret_code
= htobe32(LTTNG_OK
);
1219 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1220 sizeof(struct lttcomm_relayd_status_stream
), 0);
1222 ERR("Relay sending stream id");
1223 ret
= (int) send_ret
;
1233 * relay_close_stream: close a specific stream
1235 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1236 struct relay_connection
*conn
)
1239 struct relay_session
*session
= conn
->session
;
1240 struct lttcomm_relayd_close_stream stream_info
;
1241 struct lttcomm_relayd_generic_reply reply
;
1242 struct relay_stream
*stream
;
1244 DBG("Close stream received");
1246 if (!session
|| conn
->version_check_done
== 0) {
1247 ERR("Trying to close a stream before version check");
1249 goto end_no_session
;
1252 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1253 sizeof(struct lttcomm_relayd_close_stream
), 0);
1254 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1256 /* Orderly shutdown. Not necessary to print an error. */
1257 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1259 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1262 goto end_no_session
;
1265 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1272 * Set last_net_seq_num before the close flag. Required by data
1275 pthread_mutex_lock(&stream
->lock
);
1276 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1277 pthread_mutex_unlock(&stream
->lock
);
1280 * This is one of the conditions which may trigger a stream close
1281 * with the others being:
1282 * 1) A close command is received for a stream
1283 * 2) The control connection owning the stream is closed
1284 * 3) We have received all of the stream's data _after_ a close
1287 try_stream_close(stream
);
1288 if (stream
->is_metadata
) {
1289 struct relay_viewer_stream
*vstream
;
1291 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1293 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1295 * Since all the metadata has been sent to the
1296 * viewer and that we have a request to close
1297 * its stream, we can safely teardown the
1298 * corresponding metadata viewer stream.
1300 viewer_stream_put(vstream
);
1302 /* Put local reference. */
1303 viewer_stream_put(vstream
);
1309 memset(&reply
, 0, sizeof(reply
));
1311 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1313 reply
.ret_code
= htobe32(LTTNG_OK
);
1315 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1316 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1318 ERR("Relay sending stream id");
1327 * relay_unknown_command: send -1 if received unknown command
1329 static void relay_unknown_command(struct relay_connection
*conn
)
1331 struct lttcomm_relayd_generic_reply reply
;
1334 memset(&reply
, 0, sizeof(reply
));
1335 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1336 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1337 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1339 ERR("Relay sending unknown command");
1344 * relay_start: send an acknowledgment to the client to tell if we are
1345 * ready to receive data. We are ready if a session is established.
1347 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1348 struct relay_connection
*conn
)
1350 int ret
= htobe32(LTTNG_OK
);
1351 struct lttcomm_relayd_generic_reply reply
;
1352 struct relay_session
*session
= conn
->session
;
1355 DBG("Trying to start the streaming without a session established");
1356 ret
= htobe32(LTTNG_ERR_UNK
);
1359 memset(&reply
, 0, sizeof(reply
));
1360 reply
.ret_code
= ret
;
1361 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1362 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1364 ERR("Relay sending start ack");
1371 * Append padding to the file pointed by the file descriptor fd.
1373 static int write_padding_to_file(int fd
, uint32_t size
)
1382 zeros
= zmalloc(size
);
1383 if (zeros
== NULL
) {
1384 PERROR("zmalloc zeros for padding");
1389 ret
= lttng_write(fd
, zeros
, size
);
1391 PERROR("write padding to file");
1401 * relay_recv_metadata: receive the metadata for the session.
1403 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1404 struct relay_connection
*conn
)
1408 struct relay_session
*session
= conn
->session
;
1409 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1410 struct relay_stream
*metadata_stream
;
1411 uint64_t data_size
, payload_size
;
1414 ERR("Metadata sent before version check");
1419 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1420 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1421 ERR("Incorrect data size");
1425 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1427 if (data_buffer_size
< data_size
) {
1428 /* In case the realloc fails, we can free the memory */
1431 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1432 if (!tmp_data_ptr
) {
1433 ERR("Allocating data buffer");
1438 data_buffer
= tmp_data_ptr
;
1439 data_buffer_size
= data_size
;
1441 memset(data_buffer
, 0, data_size
);
1442 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1443 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1444 if (size_ret
< 0 || size_ret
!= data_size
) {
1445 if (size_ret
== 0) {
1446 /* Orderly shutdown. Not necessary to print an error. */
1447 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1449 ERR("Relay didn't receive the whole metadata");
1454 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1456 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1457 if (!metadata_stream
) {
1462 pthread_mutex_lock(&metadata_stream
->lock
);
1464 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1466 if (size_ret
< payload_size
) {
1467 ERR("Relay error writing metadata on file");
1472 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1473 be32toh(metadata_struct
->padding_size
));
1478 metadata_stream
->metadata_received
+=
1479 payload_size
+ be32toh(metadata_struct
->padding_size
);
1480 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1481 metadata_stream
->metadata_received
);
1484 pthread_mutex_unlock(&metadata_stream
->lock
);
1485 stream_put(metadata_stream
);
1491 * relay_send_version: send relayd version number
1493 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1494 struct relay_connection
*conn
)
1497 struct lttcomm_relayd_version reply
, msg
;
1499 conn
->version_check_done
= 1;
1501 /* Get version from the other side. */
1502 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1503 if (ret
< 0 || ret
!= sizeof(msg
)) {
1505 /* Orderly shutdown. Not necessary to print an error. */
1506 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1508 ERR("Relay failed to receive the version values.");
1514 memset(&reply
, 0, sizeof(reply
));
1515 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1516 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1518 /* Major versions must be the same */
1519 if (reply
.major
!= be32toh(msg
.major
)) {
1520 DBG("Incompatible major versions (%u vs %u), deleting session",
1521 reply
.major
, be32toh(msg
.major
));
1522 connection_put(conn
);
1527 conn
->major
= reply
.major
;
1528 /* We adapt to the lowest compatible version */
1529 if (reply
.minor
<= be32toh(msg
.minor
)) {
1530 conn
->minor
= reply
.minor
;
1532 conn
->minor
= be32toh(msg
.minor
);
1535 reply
.major
= htobe32(reply
.major
);
1536 reply
.minor
= htobe32(reply
.minor
);
1537 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1538 sizeof(struct lttcomm_relayd_version
), 0);
1540 ERR("Relay sending version");
1543 DBG("Version check done using protocol %u.%u", conn
->major
,
1551 * Check for data pending for a given stream id from the session daemon.
1553 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1554 struct relay_connection
*conn
)
1556 struct relay_session
*session
= conn
->session
;
1557 struct lttcomm_relayd_data_pending msg
;
1558 struct lttcomm_relayd_generic_reply reply
;
1559 struct relay_stream
*stream
;
1561 uint64_t last_net_seq_num
, stream_id
;
1563 DBG("Data pending command received");
1565 if (!session
|| conn
->version_check_done
== 0) {
1566 ERR("Trying to check for data before version check");
1568 goto end_no_session
;
1571 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1572 if (ret
< sizeof(msg
)) {
1574 /* Orderly shutdown. Not necessary to print an error. */
1575 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1577 ERR("Relay didn't receive valid data_pending struct size : %d",
1581 goto end_no_session
;
1584 stream_id
= be64toh(msg
.stream_id
);
1585 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1587 stream
= stream_get_by_id(stream_id
);
1588 if (stream
== NULL
) {
1593 pthread_mutex_lock(&stream
->lock
);
1595 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1596 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1599 /* Avoid wrapping issue */
1600 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1601 /* Data has in fact been written and is NOT pending */
1604 /* Data still being streamed thus pending */
1608 stream
->data_pending_check_done
= true;
1609 pthread_mutex_unlock(&stream
->lock
);
1614 memset(&reply
, 0, sizeof(reply
));
1615 reply
.ret_code
= htobe32(ret
);
1616 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1618 ERR("Relay data pending ret code failed");
1626 * Wait for the control socket to reach a quiescent state.
1628 * Note that for now, when receiving this command from the session
1629 * daemon, this means that every subsequent commands or data received on
1630 * the control socket has been handled. So, this is why we simply return
1633 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1634 struct relay_connection
*conn
)
1638 struct relay_stream
*stream
;
1639 struct lttcomm_relayd_quiescent_control msg
;
1640 struct lttcomm_relayd_generic_reply reply
;
1642 DBG("Checking quiescent state on control socket");
1644 if (!conn
->session
|| conn
->version_check_done
== 0) {
1645 ERR("Trying to check for data before version check");
1647 goto end_no_session
;
1650 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1651 if (ret
< sizeof(msg
)) {
1653 /* Orderly shutdown. Not necessary to print an error. */
1654 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1656 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1660 goto end_no_session
;
1663 stream_id
= be64toh(msg
.stream_id
);
1664 stream
= stream_get_by_id(stream_id
);
1668 pthread_mutex_lock(&stream
->lock
);
1669 stream
->data_pending_check_done
= true;
1670 pthread_mutex_unlock(&stream
->lock
);
1671 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1674 memset(&reply
, 0, sizeof(reply
));
1675 reply
.ret_code
= htobe32(LTTNG_OK
);
1676 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1678 ERR("Relay data quiescent control ret code failed");
1686 * Initialize a data pending command. This means that a consumer is about
1687 * to ask for data pending for each stream it holds. Simply iterate over
1688 * all streams of a session and set the data_pending_check_done flag.
1690 * This command returns to the client a LTTNG_OK code.
1692 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1693 struct relay_connection
*conn
)
1696 struct lttng_ht_iter iter
;
1697 struct lttcomm_relayd_begin_data_pending msg
;
1698 struct lttcomm_relayd_generic_reply reply
;
1699 struct relay_stream
*stream
;
1700 uint64_t session_id
;
1705 DBG("Init streams for data pending");
1707 if (!conn
->session
|| conn
->version_check_done
== 0) {
1708 ERR("Trying to check for data before version check");
1710 goto end_no_session
;
1713 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1714 if (ret
< sizeof(msg
)) {
1716 /* Orderly shutdown. Not necessary to print an error. */
1717 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1719 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1723 goto end_no_session
;
1726 session_id
= be64toh(msg
.session_id
);
1729 * Iterate over all streams to set the begin data pending flag.
1730 * For now, the streams are indexed by stream handle so we have
1731 * to iterate over all streams to find the one associated with
1732 * the right session_id.
1735 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1737 if (!stream_get(stream
)) {
1740 if (stream
->trace
->session
->id
== session_id
) {
1741 pthread_mutex_lock(&stream
->lock
);
1742 stream
->data_pending_check_done
= false;
1743 pthread_mutex_unlock(&stream
->lock
);
1744 DBG("Set begin data pending flag to stream %" PRIu64
,
1745 stream
->stream_handle
);
1751 memset(&reply
, 0, sizeof(reply
));
1752 /* All good, send back reply. */
1753 reply
.ret_code
= htobe32(LTTNG_OK
);
1755 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1757 ERR("Relay begin data pending send reply failed");
1765 * End data pending command. This will check, for a given session id, if
1766 * each stream associated with it has its data_pending_check_done flag
1767 * set. If not, this means that the client lost track of the stream but
1768 * the data is still being streamed on our side. In this case, we inform
1769 * the client that data is in flight.
1771 * Return to the client if there is data in flight or not with a ret_code.
1773 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1774 struct relay_connection
*conn
)
1777 struct lttng_ht_iter iter
;
1778 struct lttcomm_relayd_end_data_pending msg
;
1779 struct lttcomm_relayd_generic_reply reply
;
1780 struct relay_stream
*stream
;
1781 uint64_t session_id
;
1782 uint32_t is_data_inflight
= 0;
1784 DBG("End data pending command");
1786 if (!conn
->session
|| conn
->version_check_done
== 0) {
1787 ERR("Trying to check for data before version check");
1789 goto end_no_session
;
1792 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1793 if (ret
< sizeof(msg
)) {
1795 /* Orderly shutdown. Not necessary to print an error. */
1796 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1798 ERR("Relay didn't receive valid end data_pending struct size: %d",
1802 goto end_no_session
;
1805 session_id
= be64toh(msg
.session_id
);
1808 * Iterate over all streams to see if the begin data pending
1812 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1814 if (!stream_get(stream
)) {
1817 if (stream
->trace
->session
->id
!= session_id
) {
1821 pthread_mutex_lock(&stream
->lock
);
1822 if (!stream
->data_pending_check_done
) {
1823 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1824 is_data_inflight
= 1;
1825 DBG("Data is still in flight for stream %" PRIu64
,
1826 stream
->stream_handle
);
1827 pthread_mutex_unlock(&stream
->lock
);
1832 pthread_mutex_unlock(&stream
->lock
);
1837 memset(&reply
, 0, sizeof(reply
));
1838 /* All good, send back reply. */
1839 reply
.ret_code
= htobe32(is_data_inflight
);
1841 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1843 ERR("Relay end data pending send reply failed");
1851 * Receive an index for a specific stream.
1853 * Return 0 on success else a negative value.
1855 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1856 struct relay_connection
*conn
)
1859 struct relay_session
*session
= conn
->session
;
1860 struct lttcomm_relayd_index index_info
;
1861 struct relay_index
*index
;
1862 struct lttcomm_relayd_generic_reply reply
;
1863 struct relay_stream
*stream
;
1864 uint64_t net_seq_num
;
1868 DBG("Relay receiving index");
1870 if (!session
|| conn
->version_check_done
== 0) {
1871 ERR("Trying to close a stream before version check");
1873 goto end_no_session
;
1876 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1877 sizeof(index_info
), 0);
1878 if (ret
< sizeof(index_info
)) {
1880 /* Orderly shutdown. Not necessary to print an error. */
1881 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1883 ERR("Relay didn't receive valid index struct size : %d", ret
);
1886 goto end_no_session
;
1889 net_seq_num
= be64toh(index_info
.net_seq_num
);
1891 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1893 ERR("stream_get_by_id not found");
1897 pthread_mutex_lock(&stream
->lock
);
1899 /* Live beacon handling */
1900 if (index_info
.packet_size
== 0) {
1901 DBG("Received live beacon for stream %" PRIu64
,
1902 stream
->stream_handle
);
1905 * Only flag a stream inactive when it has already
1906 * received data and no indexes are in flight.
1908 if (stream
->index_received_seqcount
> 0
1909 && stream
->indexes_in_flight
== 0) {
1910 stream
->beacon_ts_end
=
1911 be64toh(index_info
.timestamp_end
);
1914 goto end_stream_put
;
1916 stream
->beacon_ts_end
= -1ULL;
1919 if (stream
->ctf_stream_id
== -1ULL) {
1920 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1922 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1925 ERR("relay_index_get_by_id_or_create index NULL");
1926 goto end_stream_put
;
1928 if (set_index_control_data(index
, &index_info
)) {
1929 ERR("set_index_control_data error");
1930 relay_index_put(index
);
1932 goto end_stream_put
;
1934 ret
= relay_index_try_flush(index
);
1936 tracefile_array_commit_seq(stream
->tfa
);
1937 stream
->index_received_seqcount
++;
1938 } else if (ret
> 0) {
1942 ERR("relay_index_try_flush error %d", ret
);
1943 relay_index_put(index
);
1948 pthread_mutex_unlock(&stream
->lock
);
1953 memset(&reply
, 0, sizeof(reply
));
1955 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1957 reply
.ret_code
= htobe32(LTTNG_OK
);
1959 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1961 ERR("Relay sending close index id reply");
1970 * Receive the streams_sent message.
1972 * Return 0 on success else a negative value.
1974 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1975 struct relay_connection
*conn
)
1978 struct lttcomm_relayd_generic_reply reply
;
1982 DBG("Relay receiving streams_sent");
1984 if (!conn
->session
|| conn
->version_check_done
== 0) {
1985 ERR("Trying to close a stream before version check");
1987 goto end_no_session
;
1991 * Publish every pending stream in the connection recv list which are
1992 * now ready to be used by the viewer.
1994 publish_connection_local_streams(conn
);
1996 memset(&reply
, 0, sizeof(reply
));
1997 reply
.ret_code
= htobe32(LTTNG_OK
);
1998 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2000 ERR("Relay sending sent_stream reply");
2012 * Process the commands received on the control socket
2014 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2015 struct relay_connection
*conn
)
2019 switch (be32toh(recv_hdr
->cmd
)) {
2020 case RELAYD_CREATE_SESSION
:
2021 ret
= relay_create_session(recv_hdr
, conn
);
2023 case RELAYD_ADD_STREAM
:
2024 ret
= relay_add_stream(recv_hdr
, conn
);
2026 case RELAYD_START_DATA
:
2027 ret
= relay_start(recv_hdr
, conn
);
2029 case RELAYD_SEND_METADATA
:
2030 ret
= relay_recv_metadata(recv_hdr
, conn
);
2032 case RELAYD_VERSION
:
2033 ret
= relay_send_version(recv_hdr
, conn
);
2035 case RELAYD_CLOSE_STREAM
:
2036 ret
= relay_close_stream(recv_hdr
, conn
);
2038 case RELAYD_DATA_PENDING
:
2039 ret
= relay_data_pending(recv_hdr
, conn
);
2041 case RELAYD_QUIESCENT_CONTROL
:
2042 ret
= relay_quiescent_control(recv_hdr
, conn
);
2044 case RELAYD_BEGIN_DATA_PENDING
:
2045 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2047 case RELAYD_END_DATA_PENDING
:
2048 ret
= relay_end_data_pending(recv_hdr
, conn
);
2050 case RELAYD_SEND_INDEX
:
2051 ret
= relay_recv_index(recv_hdr
, conn
);
2053 case RELAYD_STREAMS_SENT
:
2054 ret
= relay_streams_sent(recv_hdr
, conn
);
2056 case RELAYD_UPDATE_SYNC_INFO
:
2058 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2059 relay_unknown_command(conn
);
2069 * Handle index for a data stream.
2071 * Called with the stream lock held.
2073 * Return 0 on success else a negative value.
2075 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2079 uint64_t data_offset
;
2080 struct relay_index
*index
;
2082 /* Get data offset because we are about to update the index. */
2083 data_offset
= htobe64(stream
->tracefile_size_current
);
2085 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2086 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2089 * Lookup for an existing index for that stream id/sequence
2090 * number. If it exists, the control thread has already received the
2091 * data for it, thus we need to write it to disk.
2093 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2099 if (rotate_index
|| !stream
->index_fd
) {
2102 /* Put ref on previous index_fd. */
2103 if (stream
->index_fd
) {
2104 stream_fd_put(stream
->index_fd
);
2105 stream
->index_fd
= NULL
;
2108 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2109 -1, -1, stream
->tracefile_size
,
2110 tracefile_array_get_file_index_head(stream
->tfa
));
2113 /* Put self-ref for this index due to error. */
2114 relay_index_put(index
);
2117 stream
->index_fd
= stream_fd_create(fd
);
2118 if (!stream
->index_fd
) {
2121 PERROR("Error closing FD %d", fd
);
2123 /* Put self-ref for this index due to error. */
2124 relay_index_put(index
);
2125 /* Will put the local ref. */
2130 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2132 /* Put self-ref for this index due to error. */
2133 relay_index_put(index
);
2137 ret
= relay_index_try_flush(index
);
2139 tracefile_array_commit_seq(stream
->tfa
);
2140 stream
->index_received_seqcount
++;
2141 } else if (ret
> 0) {
2145 /* Put self-ref for this index due to error. */
2146 relay_index_put(index
);
2154 * relay_process_data: Process the data received on the data socket
2156 static int relay_process_data(struct relay_connection
*conn
)
2158 int ret
= 0, rotate_index
= 0;
2160 struct relay_stream
*stream
;
2161 struct lttcomm_relayd_data_hdr data_hdr
;
2163 uint64_t net_seq_num
;
2165 struct relay_session
*session
;
2166 bool new_stream
= false, close_requested
= false;
2168 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2169 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2172 /* Orderly shutdown. Not necessary to print an error. */
2173 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2175 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2181 stream_id
= be64toh(data_hdr
.stream_id
);
2182 stream
= stream_get_by_id(stream_id
);
2184 ERR("relay_process_data: Cannot find stream %" PRIu64
, stream_id
);
2188 session
= stream
->trace
->session
;
2189 data_size
= be32toh(data_hdr
.data_size
);
2190 if (data_buffer_size
< data_size
) {
2193 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2194 if (!tmp_data_ptr
) {
2195 ERR("Allocating data buffer");
2198 goto end_stream_put
;
2200 data_buffer
= tmp_data_ptr
;
2201 data_buffer_size
= data_size
;
2203 memset(data_buffer
, 0, data_size
);
2205 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2207 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2208 data_size
, stream_id
, net_seq_num
);
2209 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2212 /* Orderly shutdown. Not necessary to print an error. */
2213 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2215 ERR("Socket %d error %d", conn
->sock
->fd
, ret
);
2218 goto end_stream_put
;
2221 pthread_mutex_lock(&stream
->lock
);
2223 /* Check if a rotation is needed. */
2224 if (stream
->tracefile_size
> 0 &&
2225 (stream
->tracefile_size_current
+ data_size
) >
2226 stream
->tracefile_size
) {
2227 uint64_t old_id
, new_id
;
2229 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2230 tracefile_array_file_rotate(stream
->tfa
);
2232 /* new_id is updated by utils_rotate_stream_file. */
2235 ret
= utils_rotate_stream_file(stream
->path_name
,
2236 stream
->channel_name
, stream
->tracefile_size
,
2237 stream
->tracefile_count
, -1,
2238 -1, stream
->stream_fd
->fd
,
2239 &new_id
, &stream
->stream_fd
->fd
);
2241 ERR("Rotating stream output file");
2242 goto end_stream_unlock
;
2245 * Reset current size because we just performed a stream
2248 stream
->tracefile_size_current
= 0;
2253 * Index are handled in protocol version 2.4 and above. Also,
2254 * snapshot and index are NOT supported.
2256 if (session
->minor
>= 4 && !session
->snapshot
) {
2257 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2259 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2260 stream
->stream_handle
, net_seq_num
, ret
);
2261 goto end_stream_unlock
;
2265 /* Write data to stream output fd. */
2266 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2267 if (size_ret
< data_size
) {
2268 ERR("Relay error writing data to file");
2270 goto end_stream_unlock
;
2273 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2274 size_ret
, stream
->stream_handle
);
2276 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2277 be32toh(data_hdr
.padding_size
));
2279 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2280 stream
->stream_handle
, net_seq_num
, ret
);
2281 goto end_stream_unlock
;
2283 stream
->tracefile_size_current
+=
2284 data_size
+ be32toh(data_hdr
.padding_size
);
2285 if (stream
->prev_seq
== -1ULL) {
2289 stream
->prev_seq
= net_seq_num
;
2292 close_requested
= stream
->close_requested
;
2293 pthread_mutex_unlock(&stream
->lock
);
2294 if (close_requested
) {
2295 try_stream_close(stream
);
2299 pthread_mutex_lock(&session
->lock
);
2300 uatomic_set(&session
->new_streams
, 1);
2301 pthread_mutex_unlock(&session
->lock
);
2309 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2313 (void) lttng_poll_del(events
, pollfd
);
2315 ret
= close(pollfd
);
2317 ERR("Closing pollfd %d", pollfd
);
2321 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2322 int pollfd
, struct relay_connection
*conn
)
2324 const char *type_str
;
2326 switch (conn
->type
) {
2331 type_str
= "Control";
2333 case RELAY_VIEWER_COMMAND
:
2334 type_str
= "Viewer Command";
2336 case RELAY_VIEWER_NOTIFICATION
:
2337 type_str
= "Viewer Notification";
2340 type_str
= "Unknown";
2342 cleanup_connection_pollfd(events
, pollfd
);
2343 connection_put(conn
);
2344 DBG("%s connection closed with %d", type_str
, pollfd
);
2348 * This thread does the actual work
2350 static void *relay_thread_worker(void *data
)
2352 int ret
, err
= -1, last_seen_data_fd
= -1;
2354 struct lttng_poll_event events
;
2355 struct lttng_ht
*relay_connections_ht
;
2356 struct lttng_ht_iter iter
;
2357 struct lttcomm_relayd_hdr recv_hdr
;
2358 struct relay_connection
*destroy_conn
= NULL
;
2360 DBG("[thread] Relay worker started");
2362 rcu_register_thread();
2364 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2366 if (testpoint(relayd_thread_worker
)) {
2367 goto error_testpoint
;
2370 health_code_update();
2372 /* table of connections indexed on socket */
2373 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2374 if (!relay_connections_ht
) {
2375 goto relay_connections_ht_error
;
2378 ret
= create_thread_poll_set(&events
, 2);
2380 goto error_poll_create
;
2383 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2390 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2392 health_code_update();
2394 /* Infinite blocking call, waiting for transmission */
2395 DBG3("Relayd worker thread polling...");
2396 health_poll_entry();
2397 ret
= lttng_poll_wait(&events
, -1);
2401 * Restart interrupted system call.
2403 if (errno
== EINTR
) {
2412 * Process control. The control connection is
2413 * prioritized so we don't starve it with high
2414 * throughput tracing data on the data connection.
2416 for (i
= 0; i
< nb_fd
; i
++) {
2417 /* Fetch once the poll data */
2418 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2419 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2421 health_code_update();
2425 * No activity for this FD (poll
2431 /* Thread quit pipe has been closed. Killing thread. */
2432 ret
= check_thread_quit_pipe(pollfd
, revents
);
2438 /* Inspect the relay conn pipe for new connection */
2439 if (pollfd
== relay_conn_pipe
[0]) {
2440 if (revents
& LPOLLIN
) {
2441 struct relay_connection
*conn
;
2443 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2447 lttng_poll_add(&events
, conn
->sock
->fd
,
2448 LPOLLIN
| LPOLLRDHUP
);
2449 connection_ht_add(relay_connections_ht
, conn
);
2450 DBG("Connection socket %d added", conn
->sock
->fd
);
2451 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2452 ERR("Relay connection pipe error");
2455 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2459 struct relay_connection
*ctrl_conn
;
2461 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2462 /* If not found, there is a synchronization issue. */
2465 if (ctrl_conn
->type
== RELAY_DATA
) {
2466 if (revents
& LPOLLIN
) {
2468 * Flag the last seen data fd not deleted. It will be
2469 * used as the last seen fd if any fd gets deleted in
2472 last_notdel_data_fd
= pollfd
;
2474 goto put_ctrl_connection
;
2476 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2478 if (revents
& LPOLLIN
) {
2479 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2480 &recv_hdr
, sizeof(recv_hdr
), 0);
2482 /* Connection closed */
2483 relay_thread_close_connection(&events
, pollfd
,
2486 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2488 /* Clear the session on error. */
2489 relay_thread_close_connection(&events
,
2494 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2495 relay_thread_close_connection(&events
,
2497 if (last_seen_data_fd
== pollfd
) {
2498 last_seen_data_fd
= last_notdel_data_fd
;
2501 ERR("Unexpected poll events %u for control sock %d",
2503 connection_put(ctrl_conn
);
2506 put_ctrl_connection
:
2507 connection_put(ctrl_conn
);
2512 * The last loop handled a control request, go back to poll to make
2513 * sure we prioritise the control socket.
2519 if (last_seen_data_fd
>= 0) {
2520 for (i
= 0; i
< nb_fd
; i
++) {
2521 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2523 health_code_update();
2525 if (last_seen_data_fd
== pollfd
) {
2532 /* Process data connection. */
2533 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2534 /* Fetch the poll data. */
2535 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2536 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2537 struct relay_connection
*data_conn
;
2539 health_code_update();
2542 /* No activity for this FD (poll implementation). */
2546 /* Skip the command pipe. It's handled in the first loop. */
2547 if (pollfd
== relay_conn_pipe
[0]) {
2551 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2553 /* Skip it. Might be removed before. */
2556 if (data_conn
->type
== RELAY_CONTROL
) {
2557 goto put_data_connection
;
2559 assert(data_conn
->type
== RELAY_DATA
);
2561 if (revents
& LPOLLIN
) {
2562 ret
= relay_process_data(data_conn
);
2563 /* Connection closed */
2565 relay_thread_close_connection(&events
, pollfd
,
2568 * Every goto restart call sets the last seen fd where
2569 * here we don't really care since we gracefully
2570 * continue the loop after the connection is deleted.
2573 /* Keep last seen port. */
2574 last_seen_data_fd
= pollfd
;
2575 connection_put(data_conn
);
2578 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2579 relay_thread_close_connection(&events
, pollfd
,
2582 ERR("Unknown poll events %u for data sock %d",
2585 put_data_connection
:
2586 connection_put(data_conn
);
2588 last_seen_data_fd
= -1;
2591 /* Normal exit, no error */
2596 /* Cleanup reamaining connection object. */
2598 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2601 health_code_update();
2603 * No need to grab another ref, because we own
2606 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2611 lttng_poll_clean(&events
);
2613 lttng_ht_destroy(relay_connections_ht
);
2614 relay_connections_ht_error
:
2615 /* Close relay conn pipes */
2616 utils_close_pipe(relay_conn_pipe
);
2618 DBG("Thread exited with error");
2620 DBG("Worker thread cleanup complete");
2625 ERR("Health error occurred in %s", __func__
);
2627 health_unregister(health_relayd
);
2628 rcu_unregister_thread();
2629 lttng_relay_stop_threads();
2634 * Create the relay command pipe to wake thread_manage_apps.
2635 * Closed in cleanup().
2637 static int create_relay_conn_pipe(void)
2641 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2649 int main(int argc
, char **argv
)
2651 int ret
= 0, retval
= 0;
2654 /* Parse arguments */
2656 if (set_options(argc
, argv
)) {
2661 if (set_signal_handler()) {
2666 /* Try to create directory if -o, --output is specified. */
2667 if (opt_output_path
) {
2668 if (*opt_output_path
!= '/') {
2669 ERR("Please specify an absolute path for -o, --output PATH");
2674 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2677 ERR("Unable to create %s", opt_output_path
);
2684 if (opt_daemon
|| opt_background
) {
2687 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2695 * We are in the child. Make sure all other file
2696 * descriptors are closed, in case we are called with
2697 * more opened file descriptors than the standard ones.
2699 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2705 /* Initialize thread health monitoring */
2706 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2707 if (!health_relayd
) {
2708 PERROR("health_app_create error");
2710 goto exit_health_app_create
;
2713 /* Create thread quit pipe */
2714 if (init_thread_quit_pipe()) {
2716 goto exit_init_data
;
2719 /* Check if daemon is UID = 0 */
2721 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2722 ERR("Need to be root to use ports < 1024");
2724 goto exit_init_data
;
2728 /* Setup the thread apps communication pipe. */
2729 if (create_relay_conn_pipe()) {
2731 goto exit_init_data
;
2734 /* Init relay command queue. */
2735 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2737 /* Set up max poll set size */
2738 if (lttng_poll_set_max_size()) {
2740 goto exit_init_data
;
2743 /* Initialize communication library */
2745 lttcomm_inet_init();
2747 /* tables of sessions indexed by session ID */
2748 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2751 goto exit_init_data
;
2754 /* tables of streams indexed by stream ID */
2755 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2756 if (!relay_streams_ht
) {
2758 goto exit_init_data
;
2761 /* tables of streams indexed by stream ID */
2762 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2763 if (!viewer_streams_ht
) {
2765 goto exit_init_data
;
2768 ret
= utils_create_pipe(health_quit_pipe
);
2771 goto exit_health_quit_pipe
;
2774 /* Create thread to manage the client socket */
2775 ret
= pthread_create(&health_thread
, NULL
,
2776 thread_manage_health
, (void *) NULL
);
2779 PERROR("pthread_create health");
2781 goto exit_health_thread
;
2784 /* Setup the dispatcher thread */
2785 ret
= pthread_create(&dispatcher_thread
, NULL
,
2786 relay_thread_dispatcher
, (void *) NULL
);
2789 PERROR("pthread_create dispatcher");
2791 goto exit_dispatcher_thread
;
2794 /* Setup the worker thread */
2795 ret
= pthread_create(&worker_thread
, NULL
,
2796 relay_thread_worker
, NULL
);
2799 PERROR("pthread_create worker");
2801 goto exit_worker_thread
;
2804 /* Setup the listener thread */
2805 ret
= pthread_create(&listener_thread
, NULL
,
2806 relay_thread_listener
, (void *) NULL
);
2809 PERROR("pthread_create listener");
2811 goto exit_listener_thread
;
2814 ret
= relayd_live_create(live_uri
);
2816 ERR("Starting live viewer threads");
2822 * This is where we start awaiting program completion (e.g. through
2823 * signal that asks threads to teardown).
2826 ret
= relayd_live_join();
2832 ret
= pthread_join(listener_thread
, &status
);
2835 PERROR("pthread_join listener_thread");
2839 exit_listener_thread
:
2840 ret
= pthread_join(worker_thread
, &status
);
2843 PERROR("pthread_join worker_thread");
2848 ret
= pthread_join(dispatcher_thread
, &status
);
2851 PERROR("pthread_join dispatcher_thread");
2854 exit_dispatcher_thread
:
2856 ret
= pthread_join(health_thread
, &status
);
2859 PERROR("pthread_join health_thread");
2864 utils_close_pipe(health_quit_pipe
);
2865 exit_health_quit_pipe
:
2868 health_app_destroy(health_relayd
);
2869 exit_health_app_create
:
2873 /* Ensure all prior call_rcu are done. */