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>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 #include <sys/mount.h>
31 #include <sys/resource.h>
32 #include <sys/socket.h>
34 #include <sys/types.h>
37 #include <urcu/futex.h>
38 #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/defaults.h>
48 #include <common/daemonize.h>
49 #include <common/futex.h>
50 #include <common/sessiond-comm/sessiond-comm.h>
51 #include <common/sessiond-comm/inet.h>
52 #include <common/sessiond-comm/relayd.h>
53 #include <common/uri.h>
54 #include <common/utils.h>
55 #include <common/config/config.h>
58 #include "ctf-trace.h"
61 #include "lttng-relayd.h"
63 #include "health-relayd.h"
64 #include "testpoint.h"
65 #include "viewer-stream.h"
68 #include "connection.h"
70 /* command line options */
71 char *opt_output_path
;
72 static int opt_daemon
, opt_background
;
75 * We need to wait for listener and live listener threads, as well as
76 * health check thread, before being ready to signal readiness.
78 #define NR_LTTNG_RELAY_READY 3
79 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
80 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
81 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
83 static struct lttng_uri
*control_uri
;
84 static struct lttng_uri
*data_uri
;
85 static struct lttng_uri
*live_uri
;
89 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
90 static int tracing_group_name_override
;
92 const char * const config_section_name
= "relayd";
95 * Quit pipe for all threads. This permits a single cancellation point
96 * for all threads when receiving an event on the pipe.
98 int thread_quit_pipe
[2] = { -1, -1 };
101 * This pipe is used to inform the worker thread that a command is queued and
102 * ready to be processed.
104 static int relay_conn_pipe
[2] = { -1, -1 };
106 /* Shared between threads */
107 static int dispatch_thread_exit
;
109 static pthread_t listener_thread
;
110 static pthread_t dispatcher_thread
;
111 static pthread_t worker_thread
;
112 static pthread_t health_thread
;
114 static uint64_t last_relay_stream_id
;
117 * Relay command queue.
119 * The relay_thread_listener and relay_thread_dispatcher communicate with this
122 static struct relay_conn_queue relay_conn_queue
;
124 /* buffer allocated at startup, used to store the trace data */
125 static char *data_buffer
;
126 static unsigned int data_buffer_size
;
128 /* We need those values for the file/dir creation. */
129 static uid_t relayd_uid
;
130 static gid_t relayd_gid
;
132 /* Global relay stream hash table. */
133 struct lttng_ht
*relay_streams_ht
;
135 /* Global relay viewer stream hash table. */
136 struct lttng_ht
*viewer_streams_ht
;
138 /* Global hash table that stores relay index object. */
139 struct lttng_ht
*indexes_ht
;
141 /* Relayd health monitoring */
142 struct health_app
*health_relayd
;
144 static struct option long_options
[] = {
145 { "control-port", 1, 0, 'C', },
146 { "data-port", 1, 0, 'D', },
147 { "live-port", 1, 0, 'L', },
148 { "daemonize", 0, 0, 'd', },
149 { "background", 0, 0, 'b', },
150 { "group", 1, 0, 'g', },
151 { "help", 0, 0, 'h', },
152 { "output", 1, 0, 'o', },
153 { "verbose", 0, 0, 'v', },
154 { "config", 1, 0, 'f' },
158 static const char *config_ignore_options
[] = { "help", "config" };
161 * usage function on stderr
166 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
167 fprintf(stderr
, " -h, --help Display this usage.\n");
168 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
169 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
170 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
171 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
172 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
173 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
174 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
175 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
176 fprintf(stderr
, " -f --config Load daemon configuration file\n");
180 * Take an option from the getopt output and set it in the right variable to be
183 * Return 0 on success else a negative value.
186 int set_option(int opt
, const char *arg
, const char *optname
)
192 fprintf(stderr
, "option %s", optname
);
194 fprintf(stderr
, " with arg %s\n", arg
);
198 ret
= uri_parse(arg
, &control_uri
);
200 ERR("Invalid control URI specified");
203 if (control_uri
->port
== 0) {
204 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
208 ret
= uri_parse(arg
, &data_uri
);
210 ERR("Invalid data URI specified");
213 if (data_uri
->port
== 0) {
214 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
218 ret
= uri_parse(arg
, &live_uri
);
220 ERR("Invalid live URI specified");
223 if (live_uri
->port
== 0) {
224 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
234 tracing_group_name
= strdup(arg
);
235 tracing_group_name_override
= 1;
241 ret
= asprintf(&opt_output_path
, "%s", arg
);
244 PERROR("asprintf opt_output_path");
249 /* Verbose level can increase using multiple -v */
251 lttng_opt_verbose
= config_parse_value(arg
);
253 lttng_opt_verbose
+= 1;
257 /* Unknown option or other error.
258 * Error is printed by getopt, just return */
271 * config_entry_handler_cb used to handle options read from a config file.
272 * See config_entry_handler_cb comment in common/config/config.h for the
273 * return value conventions.
276 int config_entry_handler(const struct config_entry
*entry
, void *unused
)
280 if (!entry
|| !entry
->name
|| !entry
->value
) {
285 /* Check if the option is to be ignored */
286 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
287 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
292 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
293 /* Ignore if entry name is not fully matched. */
294 if (strcmp(entry
->name
, long_options
[i
].name
)) {
299 * If the option takes no argument on the command line, we have to
300 * check if the value is "true". We support non-zero numeric values,
303 if (!long_options
[i
].has_arg
) {
304 ret
= config_parse_value(entry
->value
);
307 WARN("Invalid configuration value \"%s\" for option %s",
308 entry
->value
, entry
->name
);
310 /* False, skip boolean config option. */
315 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
319 WARN("Unrecognized option \"%s\" in daemon configuration file.",
327 int set_options(int argc
, char **argv
)
329 int c
, ret
= 0, option_index
= 0;
330 int orig_optopt
= optopt
, orig_optind
= optind
;
331 char *default_address
, *optstring
;
332 const char *config_path
= NULL
;
334 optstring
= utils_generate_optstring(long_options
,
335 sizeof(long_options
) / sizeof(struct option
));
341 /* Check for the --config option */
343 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
344 &option_index
)) != -1) {
348 } else if (c
!= 'f') {
352 config_path
= utils_expand_path(optarg
);
354 ERR("Failed to resolve path: %s", optarg
);
358 ret
= config_get_section_entries(config_path
, config_section_name
,
359 config_entry_handler
, NULL
);
362 ERR("Invalid configuration option at line %i", ret
);
368 /* Reset getopt's global state */
369 optopt
= orig_optopt
;
370 optind
= orig_optind
;
372 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
377 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
383 /* assign default values */
384 if (control_uri
== NULL
) {
385 ret
= asprintf(&default_address
, "tcp://0.0.0.0:%d",
386 DEFAULT_NETWORK_CONTROL_PORT
);
388 PERROR("asprintf default data address");
392 ret
= uri_parse(default_address
, &control_uri
);
393 free(default_address
);
395 ERR("Invalid control URI specified");
399 if (data_uri
== NULL
) {
400 ret
= asprintf(&default_address
, "tcp://0.0.0.0:%d",
401 DEFAULT_NETWORK_DATA_PORT
);
403 PERROR("asprintf default data address");
407 ret
= uri_parse(default_address
, &data_uri
);
408 free(default_address
);
410 ERR("Invalid data URI specified");
414 if (live_uri
== NULL
) {
415 ret
= asprintf(&default_address
, "tcp://0.0.0.0:%d",
416 DEFAULT_NETWORK_VIEWER_PORT
);
418 PERROR("asprintf default viewer control address");
422 ret
= uri_parse(default_address
, &live_uri
);
423 free(default_address
);
425 ERR("Invalid viewer control URI specified");
443 /* free the dynamically allocated opt_output_path */
444 free(opt_output_path
);
446 /* Close thread quit pipes */
447 utils_close_pipe(thread_quit_pipe
);
449 uri_free(control_uri
);
451 /* Live URI is freed in the live thread. */
453 if (tracing_group_name_override
) {
454 free((void *) tracing_group_name
);
459 * Write to writable pipe used to notify a thread.
462 int notify_thread_pipe(int wpipe
)
466 ret
= lttng_write(wpipe
, "!", 1);
468 PERROR("write poll pipe");
474 static void notify_health_quit_pipe(int *pipe
)
478 ret
= lttng_write(pipe
[1], "4", 1);
480 PERROR("write relay health quit");
485 * Stop all threads by closing the thread quit pipe.
488 void stop_threads(void)
492 /* Stopping all threads */
493 DBG("Terminating all threads");
494 ret
= notify_thread_pipe(thread_quit_pipe
[1]);
496 ERR("write error on thread quit pipe");
499 notify_health_quit_pipe(health_quit_pipe
);
501 /* Dispatch thread */
502 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
503 futex_nto1_wake(&relay_conn_queue
.futex
);
507 * Signal handler for the daemon
509 * Simply stop all worker threads, leaving main() return gracefully after
510 * joining all threads and calling cleanup().
513 void sighandler(int sig
)
517 DBG("SIGPIPE caught");
520 DBG("SIGINT caught");
524 DBG("SIGTERM caught");
528 CMM_STORE_SHARED(recv_child_signal
, 1);
536 * Setup signal handler for :
537 * SIGINT, SIGTERM, SIGPIPE
540 int set_signal_handler(void)
546 if ((ret
= sigemptyset(&sigset
)) < 0) {
547 PERROR("sigemptyset");
551 sa
.sa_handler
= sighandler
;
554 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
559 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
564 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
569 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
574 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
579 void lttng_relay_notify_ready(void)
581 /* Notify the parent of the fork() process that we are ready. */
582 if (opt_daemon
|| opt_background
) {
583 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
584 kill(child_ppid
, SIGUSR1
);
590 * Init thread quit pipe.
592 * Return -1 on error or 0 if all pipes are created.
595 int init_thread_quit_pipe(void)
599 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
605 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
608 int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
612 if (events
== NULL
|| size
== 0) {
617 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
623 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
635 * Check if the thread quit pipe was triggered.
637 * Return 1 if it was triggered else 0;
640 int check_thread_quit_pipe(int fd
, uint32_t events
)
642 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
650 * Create and init socket from uri.
653 struct lttcomm_sock
*relay_init_sock(struct lttng_uri
*uri
)
656 struct lttcomm_sock
*sock
= NULL
;
658 sock
= lttcomm_alloc_sock_from_uri(uri
);
660 ERR("Allocating socket");
664 ret
= lttcomm_create_sock(sock
);
668 DBG("Listening on sock %d", sock
->fd
);
670 ret
= sock
->ops
->bind(sock
);
675 ret
= sock
->ops
->listen(sock
, -1);
685 lttcomm_destroy_sock(sock
);
691 * Return nonzero if stream needs to be closed.
694 int close_stream_check(struct relay_stream
*stream
)
696 if (stream
->close_flag
&& stream
->prev_seq
== stream
->last_net_seq_num
) {
698 * We are about to close the stream so set the data pending flag to 1
699 * which will make the end data pending command skip the stream which
700 * is now closed and ready. Note that after proceeding to a file close,
701 * the written file is ready for reading.
703 stream
->data_pending_check_done
= 1;
709 static void try_close_stream(struct relay_session
*session
,
710 struct relay_stream
*stream
)
713 struct ctf_trace
*ctf_trace
;
718 if (!close_stream_check(stream
)) {
719 /* Can't close it, not ready for that. */
723 ctf_trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
,
727 pthread_mutex_lock(&session
->viewer_ready_lock
);
728 ctf_trace
->invalid_flag
= 1;
729 pthread_mutex_unlock(&session
->viewer_ready_lock
);
731 ret
= stream_close(session
, stream
);
733 /* Already close thus the ctf trace is being or has been destroyed. */
737 ctf_trace_try_destroy(session
, ctf_trace
);
744 * This thread manages the listening for new connections on the network
747 void *relay_thread_listener(void *data
)
749 int i
, ret
, pollfd
, err
= -1;
750 uint32_t revents
, nb_fd
;
751 struct lttng_poll_event events
;
752 struct lttcomm_sock
*control_sock
, *data_sock
;
754 DBG("[thread] Relay listener started");
756 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
758 health_code_update();
760 control_sock
= relay_init_sock(control_uri
);
762 goto error_sock_control
;
765 data_sock
= relay_init_sock(data_uri
);
767 goto error_sock_relay
;
771 * Pass 3 as size here for the thread quit pipe, control and data socket.
773 ret
= create_thread_poll_set(&events
, 3);
775 goto error_create_poll
;
778 /* Add the control socket */
779 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
784 /* Add the data socket */
785 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
790 lttng_relay_notify_ready();
792 if (testpoint(relayd_thread_listener
)) {
793 goto error_testpoint
;
797 health_code_update();
799 DBG("Listener accepting connections");
803 ret
= lttng_poll_wait(&events
, -1);
807 * Restart interrupted system call.
809 if (errno
== EINTR
) {
817 DBG("Relay new connection received");
818 for (i
= 0; i
< nb_fd
; i
++) {
819 health_code_update();
821 /* Fetch once the poll data */
822 revents
= LTTNG_POLL_GETEV(&events
, i
);
823 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
825 /* Thread quit pipe has been closed. Killing thread. */
826 ret
= check_thread_quit_pipe(pollfd
, revents
);
832 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
833 ERR("socket poll error");
835 } else if (revents
& LPOLLIN
) {
837 * Get allocated in this thread, enqueued to a global queue,
838 * dequeued and freed in the worker thread.
841 struct relay_connection
*new_conn
;
842 struct lttcomm_sock
*newsock
;
844 new_conn
= connection_create();
849 if (pollfd
== data_sock
->fd
) {
850 new_conn
->type
= RELAY_DATA
;
851 newsock
= data_sock
->ops
->accept(data_sock
);
852 DBG("Relay data connection accepted, socket %d",
855 assert(pollfd
== control_sock
->fd
);
856 new_conn
->type
= RELAY_CONTROL
;
857 newsock
= control_sock
->ops
->accept(control_sock
);
858 DBG("Relay control connection accepted, socket %d",
862 PERROR("accepting sock");
863 connection_free(new_conn
);
867 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
870 PERROR("setsockopt inet");
871 lttcomm_destroy_sock(newsock
);
872 connection_free(new_conn
);
875 new_conn
->sock
= newsock
;
877 /* Enqueue request for the dispatcher thread. */
878 cds_wfq_enqueue(&relay_conn_queue
.queue
, &new_conn
->qnode
);
881 * Wake the dispatch queue futex. Implicit memory barrier with
882 * the exchange in cds_wfq_enqueue.
884 futex_nto1_wake(&relay_conn_queue
.futex
);
893 lttng_poll_clean(&events
);
895 if (data_sock
->fd
>= 0) {
896 ret
= data_sock
->ops
->close(data_sock
);
901 lttcomm_destroy_sock(data_sock
);
903 if (control_sock
->fd
>= 0) {
904 ret
= control_sock
->ops
->close(control_sock
);
909 lttcomm_destroy_sock(control_sock
);
913 ERR("Health error occurred in %s", __func__
);
915 health_unregister(health_relayd
);
916 DBG("Relay listener thread cleanup complete");
922 * This thread manages the dispatching of the requests to worker threads
925 void *relay_thread_dispatcher(void *data
)
929 struct cds_wfq_node
*node
;
930 struct relay_connection
*new_conn
= NULL
;
932 DBG("[thread] Relay dispatcher started");
934 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
936 if (testpoint(relayd_thread_dispatcher
)) {
937 goto error_testpoint
;
940 health_code_update();
942 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
943 health_code_update();
945 /* Atomically prepare the queue futex */
946 futex_nto1_prepare(&relay_conn_queue
.futex
);
949 health_code_update();
951 /* Dequeue commands */
952 node
= cds_wfq_dequeue_blocking(&relay_conn_queue
.queue
);
954 DBG("Woken up but nothing in the relay command queue");
955 /* Continue thread execution */
958 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
960 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
963 * Inform worker thread of the new request. This call is blocking
964 * so we can be assured that the data will be read at some point in
965 * time or wait to the end of the world :)
967 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
969 PERROR("write connection pipe");
970 connection_destroy(new_conn
);
973 } while (node
!= NULL
);
975 /* Futex wait on queue. Blocking call on futex() */
977 futex_nto1_wait(&relay_conn_queue
.futex
);
981 /* Normal exit, no error */
988 ERR("Health error occurred in %s", __func__
);
990 health_unregister(health_relayd
);
991 DBG("Dispatch thread dying");
996 static void try_close_streams(struct relay_session
*session
)
998 struct ctf_trace
*ctf_trace
;
999 struct lttng_ht_iter iter
;
1003 pthread_mutex_lock(&session
->viewer_ready_lock
);
1005 cds_lfht_for_each_entry(session
->ctf_traces_ht
->ht
, &iter
.iter
, ctf_trace
,
1007 struct relay_stream
*stream
;
1009 /* Close streams. */
1010 cds_list_for_each_entry(stream
, &ctf_trace
->stream_list
, trace_list
) {
1011 stream_close(session
, stream
);
1014 ctf_trace
->invalid_flag
= 1;
1015 ctf_trace_try_destroy(session
, ctf_trace
);
1018 pthread_mutex_unlock(&session
->viewer_ready_lock
);
1022 * Try to destroy a session within a connection.
1024 static void destroy_session(struct relay_session
*session
,
1025 struct lttng_ht
*sessions_ht
)
1028 assert(sessions_ht
);
1030 /* Indicate that this session can be destroyed from now on. */
1031 session
->close_flag
= 1;
1033 try_close_streams(session
);
1036 * This will try to delete and destroy the session if no viewer is attached
1037 * to it meaning the refcount is down to zero.
1039 session_try_destroy(sessions_ht
, session
);
1043 * Copy index data from the control port to a given index object.
1045 static void copy_index_control_data(struct relay_index
*index
,
1046 struct lttcomm_relayd_index
*data
)
1052 * The index on disk is encoded in big endian, so we don't need to convert
1053 * the data received on the network. The data_offset value is NEVER
1054 * modified here and is updated by the data thread.
1056 index
->index_data
.packet_size
= data
->packet_size
;
1057 index
->index_data
.content_size
= data
->content_size
;
1058 index
->index_data
.timestamp_begin
= data
->timestamp_begin
;
1059 index
->index_data
.timestamp_end
= data
->timestamp_end
;
1060 index
->index_data
.events_discarded
= data
->events_discarded
;
1061 index
->index_data
.stream_id
= data
->stream_id
;
1065 * Handle the RELAYD_CREATE_SESSION command.
1067 * On success, send back the session id or else return a negative value.
1070 int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1071 struct relay_connection
*conn
)
1073 int ret
= 0, send_ret
;
1074 struct relay_session
*session
;
1075 struct lttcomm_relayd_status_session reply
;
1080 memset(&reply
, 0, sizeof(reply
));
1082 session
= session_create();
1087 session
->minor
= conn
->minor
;
1088 session
->major
= conn
->major
;
1089 conn
->session_id
= session
->id
;
1090 conn
->session
= session
;
1092 reply
.session_id
= htobe64(session
->id
);
1094 switch (conn
->minor
) {
1099 case 4: /* LTTng sessiond 2.4 */
1101 ret
= cmd_create_session_2_4(conn
, session
);
1104 lttng_ht_add_unique_u64(conn
->sessions_ht
, &session
->session_n
);
1105 DBG("Created session %" PRIu64
, session
->id
);
1109 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1111 reply
.ret_code
= htobe32(LTTNG_OK
);
1114 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1116 ERR("Relayd sending session id");
1124 * When we have received all the streams and the metadata for a channel,
1125 * we make them visible to the viewer threads.
1128 void set_viewer_ready_flag(struct relay_connection
*conn
)
1130 struct relay_stream
*stream
, *tmp_stream
;
1132 pthread_mutex_lock(&conn
->session
->viewer_ready_lock
);
1133 cds_list_for_each_entry_safe(stream
, tmp_stream
, &conn
->recv_head
,
1135 stream
->viewer_ready
= 1;
1136 cds_list_del(&stream
->recv_list
);
1138 pthread_mutex_unlock(&conn
->session
->viewer_ready_lock
);
1143 * Add a recv handle node to the connection recv list with the given stream
1144 * handle. A new node is allocated thus must be freed when the node is deleted
1147 static void queue_stream(struct relay_stream
*stream
,
1148 struct relay_connection
*conn
)
1153 cds_list_add(&stream
->recv_list
, &conn
->recv_head
);
1157 * relay_add_stream: allocate a new stream for a session
1160 int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1161 struct relay_connection
*conn
)
1164 struct relay_session
*session
= conn
->session
;
1165 struct relay_stream
*stream
= NULL
;
1166 struct lttcomm_relayd_status_stream reply
;
1167 struct ctf_trace
*trace
;
1169 if (!session
|| conn
->version_check_done
== 0) {
1170 ERR("Trying to add a stream before version check");
1172 goto end_no_session
;
1175 stream
= zmalloc(sizeof(struct relay_stream
));
1176 if (stream
== NULL
) {
1177 PERROR("relay stream zmalloc");
1179 goto end_no_session
;
1182 switch (conn
->minor
) {
1183 case 1: /* LTTng sessiond 2.1 */
1184 ret
= cmd_recv_stream_2_1(conn
, stream
);
1186 case 2: /* LTTng sessiond 2.2 */
1188 ret
= cmd_recv_stream_2_2(conn
, stream
);
1192 goto err_free_stream
;
1196 stream
->stream_handle
= ++last_relay_stream_id
;
1197 stream
->prev_seq
= -1ULL;
1198 stream
->session_id
= session
->id
;
1199 stream
->index_fd
= -1;
1200 stream
->read_index_fd
= -1;
1201 lttng_ht_node_init_u64(&stream
->node
, stream
->stream_handle
);
1202 pthread_mutex_init(&stream
->lock
, NULL
);
1204 ret
= utils_mkdir_recursive(stream
->path_name
, S_IRWXU
| S_IRWXG
);
1206 ERR("relay creating output directory");
1211 * No need to use run_as API here because whatever we receives, the relayd
1212 * uses its own credentials for the stream files.
1214 ret
= utils_create_stream_file(stream
->path_name
, stream
->channel_name
,
1215 stream
->tracefile_size
, 0, relayd_uid
, relayd_gid
, NULL
);
1217 ERR("Create output file");
1221 if (stream
->tracefile_size
) {
1222 DBG("Tracefile %s/%s_0 created", stream
->path_name
, stream
->channel_name
);
1224 DBG("Tracefile %s/%s created", stream
->path_name
, stream
->channel_name
);
1227 trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
, stream
->path_name
);
1229 trace
= ctf_trace_create(stream
->path_name
);
1234 ctf_trace_add(session
->ctf_traces_ht
, trace
);
1236 ctf_trace_get_ref(trace
);
1238 if (!strncmp(stream
->channel_name
, DEFAULT_METADATA_NAME
, NAME_MAX
)) {
1239 stream
->metadata_flag
= 1;
1240 /* Assign quick reference to the metadata stream in the trace. */
1241 trace
->metadata_stream
= stream
;
1245 * Add the stream in the recv list of the connection. Once the end stream
1246 * message is received, this list is emptied and streams are set with the
1247 * viewer ready flag.
1249 queue_stream(stream
, conn
);
1252 * Both in the ctf_trace object and the global stream ht since the data
1253 * side of the relayd does not have the concept of session.
1255 lttng_ht_add_unique_u64(relay_streams_ht
, &stream
->node
);
1256 cds_list_add_tail(&stream
->trace_list
, &trace
->stream_list
);
1258 session
->stream_count
++;
1260 DBG("Relay new stream added %s with ID %" PRIu64
, stream
->channel_name
,
1261 stream
->stream_handle
);
1264 reply
.handle
= htobe64(stream
->stream_handle
);
1265 /* send the session id to the client or a negative return code on error */
1267 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1268 /* stream was not properly added to the ht, so free it */
1271 reply
.ret_code
= htobe32(LTTNG_OK
);
1274 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1275 sizeof(struct lttcomm_relayd_status_stream
), 0);
1277 ERR("Relay sending stream id");
1286 free(stream
->path_name
);
1287 free(stream
->channel_name
);
1293 * relay_close_stream: close a specific stream
1296 int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1297 struct relay_connection
*conn
)
1300 struct relay_session
*session
= conn
->session
;
1301 struct lttcomm_relayd_close_stream stream_info
;
1302 struct lttcomm_relayd_generic_reply reply
;
1303 struct relay_stream
*stream
;
1305 DBG("Close stream received");
1307 if (!session
|| conn
->version_check_done
== 0) {
1308 ERR("Trying to close a stream before version check");
1310 goto end_no_session
;
1313 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1314 sizeof(struct lttcomm_relayd_close_stream
), 0);
1315 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1317 /* Orderly shutdown. Not necessary to print an error. */
1318 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1320 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1323 goto end_no_session
;
1327 stream
= stream_find_by_id(relay_streams_ht
,
1328 be64toh(stream_info
.stream_id
));
1334 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1335 stream
->close_flag
= 1;
1336 session
->stream_count
--;
1337 assert(session
->stream_count
>= 0);
1339 /* Check if we can close it or else the data will do it. */
1340 try_close_stream(session
, stream
);
1346 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1348 reply
.ret_code
= htobe32(LTTNG_OK
);
1350 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1351 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1353 ERR("Relay sending stream id");
1362 * relay_unknown_command: send -1 if received unknown command
1365 void relay_unknown_command(struct relay_connection
*conn
)
1367 struct lttcomm_relayd_generic_reply reply
;
1370 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1371 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1372 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1374 ERR("Relay sending unknown command");
1379 * relay_start: send an acknowledgment to the client to tell if we are
1380 * ready to receive data. We are ready if a session is established.
1383 int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1384 struct relay_connection
*conn
)
1386 int ret
= htobe32(LTTNG_OK
);
1387 struct lttcomm_relayd_generic_reply reply
;
1388 struct relay_session
*session
= conn
->session
;
1391 DBG("Trying to start the streaming without a session established");
1392 ret
= htobe32(LTTNG_ERR_UNK
);
1395 reply
.ret_code
= ret
;
1396 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1397 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1399 ERR("Relay sending start ack");
1406 * Append padding to the file pointed by the file descriptor fd.
1408 static int write_padding_to_file(int fd
, uint32_t size
)
1417 zeros
= zmalloc(size
);
1418 if (zeros
== NULL
) {
1419 PERROR("zmalloc zeros for padding");
1424 ret
= lttng_write(fd
, zeros
, size
);
1426 PERROR("write padding to file");
1436 * relay_recv_metadata: receive the metada for the session.
1439 int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1440 struct relay_connection
*conn
)
1442 int ret
= htobe32(LTTNG_OK
);
1444 struct relay_session
*session
= conn
->session
;
1445 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1446 struct relay_stream
*metadata_stream
;
1447 uint64_t data_size
, payload_size
;
1448 struct ctf_trace
*ctf_trace
;
1451 ERR("Metadata sent before version check");
1456 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1457 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1458 ERR("Incorrect data size");
1462 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1464 if (data_buffer_size
< data_size
) {
1465 /* In case the realloc fails, we can free the memory */
1468 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1469 if (!tmp_data_ptr
) {
1470 ERR("Allocating data buffer");
1475 data_buffer
= tmp_data_ptr
;
1476 data_buffer_size
= data_size
;
1478 memset(data_buffer
, 0, data_size
);
1479 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1480 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1481 if (ret
< 0 || ret
!= data_size
) {
1483 /* Orderly shutdown. Not necessary to print an error. */
1484 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1486 ERR("Relay didn't receive the whole metadata");
1491 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1494 metadata_stream
= stream_find_by_id(relay_streams_ht
,
1495 be64toh(metadata_struct
->stream_id
));
1496 if (!metadata_stream
) {
1501 size_ret
= lttng_write(metadata_stream
->fd
, metadata_struct
->payload
,
1503 if (size_ret
< payload_size
) {
1504 ERR("Relay error writing metadata on file");
1509 ret
= write_padding_to_file(metadata_stream
->fd
,
1510 be32toh(metadata_struct
->padding_size
));
1515 ctf_trace
= ctf_trace_find_by_path(session
->ctf_traces_ht
,
1516 metadata_stream
->path_name
);
1518 ctf_trace
->metadata_received
+=
1519 payload_size
+ be32toh(metadata_struct
->padding_size
);
1521 DBG2("Relay metadata written");
1530 * relay_send_version: send relayd version number
1533 int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1534 struct relay_connection
*conn
)
1537 struct lttcomm_relayd_version reply
, msg
;
1541 conn
->version_check_done
= 1;
1543 /* Get version from the other side. */
1544 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1545 if (ret
< 0 || ret
!= sizeof(msg
)) {
1547 /* Orderly shutdown. Not necessary to print an error. */
1548 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1550 ERR("Relay failed to receive the version values.");
1556 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1557 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1559 /* Major versions must be the same */
1560 if (reply
.major
!= be32toh(msg
.major
)) {
1561 DBG("Incompatible major versions (%u vs %u), deleting session",
1562 reply
.major
, be32toh(msg
.major
));
1563 destroy_session(conn
->session
, conn
->sessions_ht
);
1568 conn
->major
= reply
.major
;
1569 /* We adapt to the lowest compatible version */
1570 if (reply
.minor
<= be32toh(msg
.minor
)) {
1571 conn
->minor
= reply
.minor
;
1573 conn
->minor
= be32toh(msg
.minor
);
1576 reply
.major
= htobe32(reply
.major
);
1577 reply
.minor
= htobe32(reply
.minor
);
1578 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1579 sizeof(struct lttcomm_relayd_version
), 0);
1581 ERR("Relay sending version");
1584 DBG("Version check done using protocol %u.%u", conn
->major
,
1592 * Check for data pending for a given stream id from the session daemon.
1595 int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1596 struct relay_connection
*conn
)
1598 struct relay_session
*session
= conn
->session
;
1599 struct lttcomm_relayd_data_pending msg
;
1600 struct lttcomm_relayd_generic_reply reply
;
1601 struct relay_stream
*stream
;
1603 uint64_t last_net_seq_num
, stream_id
;
1605 DBG("Data pending command received");
1607 if (!session
|| conn
->version_check_done
== 0) {
1608 ERR("Trying to check for data before version check");
1610 goto end_no_session
;
1613 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1614 if (ret
< sizeof(msg
)) {
1616 /* Orderly shutdown. Not necessary to print an error. */
1617 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1619 ERR("Relay didn't receive valid data_pending struct size : %d",
1623 goto end_no_session
;
1626 stream_id
= be64toh(msg
.stream_id
);
1627 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1630 stream
= stream_find_by_id(relay_streams_ht
, stream_id
);
1631 if (stream
== NULL
) {
1636 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1637 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1640 /* Avoid wrapping issue */
1641 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1642 /* Data has in fact been written and is NOT pending */
1645 /* Data still being streamed thus pending */
1649 /* Pending check is now done. */
1650 stream
->data_pending_check_done
= 1;
1655 reply
.ret_code
= htobe32(ret
);
1656 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1658 ERR("Relay data pending ret code failed");
1666 * Wait for the control socket to reach a quiescent state.
1668 * Note that for now, when receiving this command from the session daemon, this
1669 * means that every subsequent commands or data received on the control socket
1670 * has been handled. So, this is why we simply return OK here.
1673 int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1674 struct relay_connection
*conn
)
1678 struct relay_stream
*stream
;
1679 struct lttng_ht_iter iter
;
1680 struct lttcomm_relayd_quiescent_control msg
;
1681 struct lttcomm_relayd_generic_reply reply
;
1683 DBG("Checking quiescent state on control socket");
1685 if (!conn
->session
|| conn
->version_check_done
== 0) {
1686 ERR("Trying to check for data before version check");
1688 goto end_no_session
;
1691 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1692 if (ret
< sizeof(msg
)) {
1694 /* Orderly shutdown. Not necessary to print an error. */
1695 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1697 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1701 goto end_no_session
;
1704 stream_id
= be64toh(msg
.stream_id
);
1707 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1709 if (stream
->stream_handle
== stream_id
) {
1710 stream
->data_pending_check_done
= 1;
1711 DBG("Relay quiescent control pending flag set to %" PRIu64
,
1718 reply
.ret_code
= htobe32(LTTNG_OK
);
1719 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1721 ERR("Relay data quiescent control ret code failed");
1729 * Initialize a data pending command. This means that a client is about to ask
1730 * for data pending for each stream he/she holds. Simply iterate over all
1731 * streams of a session and set the data_pending_check_done flag.
1733 * This command returns to the client a LTTNG_OK code.
1736 int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1737 struct relay_connection
*conn
)
1740 struct lttng_ht_iter iter
;
1741 struct lttcomm_relayd_begin_data_pending msg
;
1742 struct lttcomm_relayd_generic_reply reply
;
1743 struct relay_stream
*stream
;
1744 uint64_t session_id
;
1749 DBG("Init streams for data pending");
1751 if (!conn
->session
|| conn
->version_check_done
== 0) {
1752 ERR("Trying to check for data before version check");
1754 goto end_no_session
;
1757 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1758 if (ret
< sizeof(msg
)) {
1760 /* Orderly shutdown. Not necessary to print an error. */
1761 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1763 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1767 goto end_no_session
;
1770 session_id
= be64toh(msg
.session_id
);
1773 * Iterate over all streams to set the begin data pending flag. For now, the
1774 * streams are indexed by stream handle so we have to iterate over all
1775 * streams to find the one associated with the right session_id.
1778 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1780 if (stream
->session_id
== session_id
) {
1781 stream
->data_pending_check_done
= 0;
1782 DBG("Set begin data pending flag to stream %" PRIu64
,
1783 stream
->stream_handle
);
1788 /* All good, send back reply. */
1789 reply
.ret_code
= htobe32(LTTNG_OK
);
1791 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1793 ERR("Relay begin data pending send reply failed");
1801 * End data pending command. This will check, for a given session id, if each
1802 * stream associated with it has its data_pending_check_done flag set. If not,
1803 * this means that the client lost track of the stream but the data is still
1804 * being streamed on our side. In this case, we inform the client that data is
1807 * Return to the client if there is data in flight or not with a ret_code.
1810 int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1811 struct relay_connection
*conn
)
1814 struct lttng_ht_iter iter
;
1815 struct lttcomm_relayd_end_data_pending msg
;
1816 struct lttcomm_relayd_generic_reply reply
;
1817 struct relay_stream
*stream
;
1818 uint64_t session_id
;
1819 uint32_t is_data_inflight
= 0;
1824 DBG("End data pending command");
1826 if (!conn
->session
|| conn
->version_check_done
== 0) {
1827 ERR("Trying to check for data before version check");
1829 goto end_no_session
;
1832 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1833 if (ret
< sizeof(msg
)) {
1835 /* Orderly shutdown. Not necessary to print an error. */
1836 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1838 ERR("Relay didn't receive valid end data_pending struct size: %d",
1842 goto end_no_session
;
1845 session_id
= be64toh(msg
.session_id
);
1847 /* Iterate over all streams to see if the begin data pending flag is set. */
1849 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1851 if (stream
->session_id
== session_id
&&
1852 !stream
->data_pending_check_done
) {
1853 is_data_inflight
= 1;
1854 DBG("Data is still in flight for stream %" PRIu64
,
1855 stream
->stream_handle
);
1861 /* All good, send back reply. */
1862 reply
.ret_code
= htobe32(is_data_inflight
);
1864 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1866 ERR("Relay end data pending send reply failed");
1874 * Receive an index for a specific stream.
1876 * Return 0 on success else a negative value.
1879 int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1880 struct relay_connection
*conn
)
1882 int ret
, send_ret
, index_created
= 0;
1883 struct relay_session
*session
= conn
->session
;
1884 struct lttcomm_relayd_index index_info
;
1885 struct relay_index
*index
, *wr_index
= NULL
;
1886 struct lttcomm_relayd_generic_reply reply
;
1887 struct relay_stream
*stream
;
1888 uint64_t net_seq_num
;
1892 DBG("Relay receiving index");
1894 if (!session
|| conn
->version_check_done
== 0) {
1895 ERR("Trying to close a stream before version check");
1897 goto end_no_session
;
1900 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1901 sizeof(index_info
), 0);
1902 if (ret
< sizeof(index_info
)) {
1904 /* Orderly shutdown. Not necessary to print an error. */
1905 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1907 ERR("Relay didn't receive valid index struct size : %d", ret
);
1910 goto end_no_session
;
1913 net_seq_num
= be64toh(index_info
.net_seq_num
);
1916 stream
= stream_find_by_id(relay_streams_ht
,
1917 be64toh(index_info
.relay_stream_id
));
1920 goto end_rcu_unlock
;
1923 /* Live beacon handling */
1924 if (index_info
.packet_size
== 0) {
1925 DBG("Received live beacon for stream %" PRIu64
, stream
->stream_handle
);
1928 * Only flag a stream inactive when it has already received data.
1930 if (stream
->total_index_received
> 0) {
1931 stream
->beacon_ts_end
= be64toh(index_info
.timestamp_end
);
1934 goto end_rcu_unlock
;
1936 stream
->beacon_ts_end
= -1ULL;
1939 index
= relay_index_find(stream
->stream_handle
, net_seq_num
);
1941 /* A successful creation will add the object to the HT. */
1942 index
= relay_index_create(stream
->stream_handle
, net_seq_num
);
1944 goto end_rcu_unlock
;
1949 copy_index_control_data(index
, &index_info
);
1951 if (index_created
) {
1953 * Try to add the relay index object to the hash table. If an object
1954 * already exist, destroy back the index created, set the data in this
1955 * object and write it on disk.
1957 relay_index_add(index
, &wr_index
);
1959 copy_index_control_data(wr_index
, &index_info
);
1963 /* The index already exists so write it on disk. */
1967 /* Do we have a writable ready index to write on disk. */
1969 /* Starting at 2.4, create the index file if none available. */
1970 if (conn
->minor
>= 4 && stream
->index_fd
< 0) {
1971 ret
= index_create_file(stream
->path_name
, stream
->channel_name
,
1972 relayd_uid
, relayd_gid
, stream
->tracefile_size
,
1973 stream
->tracefile_count_current
);
1975 goto end_rcu_unlock
;
1977 stream
->index_fd
= ret
;
1980 ret
= relay_index_write(wr_index
->fd
, wr_index
);
1982 goto end_rcu_unlock
;
1984 stream
->total_index_received
++;
1991 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1993 reply
.ret_code
= htobe32(LTTNG_OK
);
1995 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1997 ERR("Relay sending close index id reply");
2006 * Receive the streams_sent message.
2008 * Return 0 on success else a negative value.
2011 int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
2012 struct relay_connection
*conn
)
2015 struct lttcomm_relayd_generic_reply reply
;
2019 DBG("Relay receiving streams_sent");
2021 if (!conn
->session
|| conn
->version_check_done
== 0) {
2022 ERR("Trying to close a stream before version check");
2024 goto end_no_session
;
2028 * Flag every pending stream in the connection recv list that they are
2029 * ready to be used by the viewer.
2031 set_viewer_ready_flag(conn
);
2034 * Inform the viewer that there are new streams in the session.
2036 uatomic_set(&conn
->session
->new_streams
, 1);
2038 reply
.ret_code
= htobe32(LTTNG_OK
);
2039 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2041 ERR("Relay sending sent_stream reply");
2053 * Process the commands received on the control socket
2056 int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2057 struct relay_connection
*conn
)
2061 switch (be32toh(recv_hdr
->cmd
)) {
2062 case RELAYD_CREATE_SESSION
:
2063 ret
= relay_create_session(recv_hdr
, conn
);
2065 case RELAYD_ADD_STREAM
:
2066 ret
= relay_add_stream(recv_hdr
, conn
);
2068 case RELAYD_START_DATA
:
2069 ret
= relay_start(recv_hdr
, conn
);
2071 case RELAYD_SEND_METADATA
:
2072 ret
= relay_recv_metadata(recv_hdr
, conn
);
2074 case RELAYD_VERSION
:
2075 ret
= relay_send_version(recv_hdr
, conn
);
2077 case RELAYD_CLOSE_STREAM
:
2078 ret
= relay_close_stream(recv_hdr
, conn
);
2080 case RELAYD_DATA_PENDING
:
2081 ret
= relay_data_pending(recv_hdr
, conn
);
2083 case RELAYD_QUIESCENT_CONTROL
:
2084 ret
= relay_quiescent_control(recv_hdr
, conn
);
2086 case RELAYD_BEGIN_DATA_PENDING
:
2087 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2089 case RELAYD_END_DATA_PENDING
:
2090 ret
= relay_end_data_pending(recv_hdr
, conn
);
2092 case RELAYD_SEND_INDEX
:
2093 ret
= relay_recv_index(recv_hdr
, conn
);
2095 case RELAYD_STREAMS_SENT
:
2096 ret
= relay_streams_sent(recv_hdr
, conn
);
2098 case RELAYD_UPDATE_SYNC_INFO
:
2100 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2101 relay_unknown_command(conn
);
2111 * Handle index for a data stream.
2113 * RCU read side lock MUST be acquired.
2115 * Return 0 on success else a negative value.
2117 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2120 int ret
= 0, index_created
= 0;
2121 uint64_t stream_id
, data_offset
;
2122 struct relay_index
*index
, *wr_index
= NULL
;
2126 stream_id
= stream
->stream_handle
;
2127 /* Get data offset because we are about to update the index. */
2128 data_offset
= htobe64(stream
->tracefile_size_current
);
2131 * Lookup for an existing index for that stream id/sequence number. If on
2132 * exists, the control thread already received the data for it thus we need
2133 * to write it on disk.
2135 index
= relay_index_find(stream_id
, net_seq_num
);
2137 /* A successful creation will add the object to the HT. */
2138 index
= relay_index_create(stream_id
, net_seq_num
);
2146 if (rotate_index
|| stream
->index_fd
< 0) {
2147 index
->to_close_fd
= stream
->index_fd
;
2148 ret
= index_create_file(stream
->path_name
, stream
->channel_name
,
2149 relayd_uid
, relayd_gid
, stream
->tracefile_size
,
2150 stream
->tracefile_count_current
);
2152 /* This will close the stream's index fd if one. */
2153 relay_index_free_safe(index
);
2156 stream
->index_fd
= ret
;
2158 index
->fd
= stream
->index_fd
;
2159 index
->index_data
.offset
= data_offset
;
2161 if (index_created
) {
2163 * Try to add the relay index object to the hash table. If an object
2164 * already exist, destroy back the index created and set the data.
2166 relay_index_add(index
, &wr_index
);
2168 /* Copy back data from the created index. */
2169 wr_index
->fd
= index
->fd
;
2170 wr_index
->to_close_fd
= index
->to_close_fd
;
2171 wr_index
->index_data
.offset
= data_offset
;
2175 /* The index already exists so write it on disk. */
2179 /* Do we have a writable ready index to write on disk. */
2181 ret
= relay_index_write(wr_index
->fd
, wr_index
);
2185 stream
->total_index_received
++;
2193 * relay_process_data: Process the data received on the data socket
2196 int relay_process_data(struct relay_connection
*conn
)
2198 int ret
= 0, rotate_index
= 0;
2200 struct relay_stream
*stream
;
2201 struct lttcomm_relayd_data_hdr data_hdr
;
2203 uint64_t net_seq_num
;
2205 struct relay_session
*session
;
2209 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2210 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2213 /* Orderly shutdown. Not necessary to print an error. */
2214 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2216 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2222 stream_id
= be64toh(data_hdr
.stream_id
);
2225 stream
= stream_find_by_id(relay_streams_ht
, stream_id
);
2228 goto end_rcu_unlock
;
2231 session
= session_find_by_id(conn
->sessions_ht
, stream
->session_id
);
2234 data_size
= be32toh(data_hdr
.data_size
);
2235 if (data_buffer_size
< data_size
) {
2238 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2239 if (!tmp_data_ptr
) {
2240 ERR("Allocating data buffer");
2243 goto end_rcu_unlock
;
2245 data_buffer
= tmp_data_ptr
;
2246 data_buffer_size
= data_size
;
2248 memset(data_buffer
, 0, data_size
);
2250 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2252 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2253 data_size
, stream_id
, net_seq_num
);
2254 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2257 /* Orderly shutdown. Not necessary to print an error. */
2258 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2261 goto end_rcu_unlock
;
2264 /* Check if a rotation is needed. */
2265 if (stream
->tracefile_size
> 0 &&
2266 (stream
->tracefile_size_current
+ data_size
) >
2267 stream
->tracefile_size
) {
2268 struct relay_viewer_stream
*vstream
;
2271 new_id
= (stream
->tracefile_count_current
+ 1) %
2272 stream
->tracefile_count
;
2274 * When we wrap-around back to 0, we start overwriting old
2277 if (!stream
->tracefile_overwrite
&& new_id
== 0) {
2278 stream
->tracefile_overwrite
= 1;
2280 pthread_mutex_lock(&stream
->viewer_stream_rotation_lock
);
2281 if (stream
->tracefile_overwrite
) {
2282 stream
->oldest_tracefile_id
=
2283 (stream
->oldest_tracefile_id
+ 1) %
2284 stream
->tracefile_count
;
2286 vstream
= viewer_stream_find_by_id(stream
->stream_handle
);
2289 * The viewer is reading a file about to be
2290 * overwritten. Close the FDs it is
2291 * currently using and let it handle the fault.
2293 if (vstream
->tracefile_count_current
== new_id
) {
2294 pthread_mutex_lock(&vstream
->overwrite_lock
);
2295 vstream
->abort_flag
= 1;
2296 pthread_mutex_unlock(&vstream
->overwrite_lock
);
2297 DBG("Streaming side setting abort_flag on stream %s_%lu\n",
2298 stream
->channel_name
, new_id
);
2299 } else if (vstream
->tracefile_count_current
==
2300 stream
->tracefile_count_current
) {
2302 * The reader and writer were in the
2303 * same trace file, inform the viewer
2304 * that no new index will ever be added
2307 vstream
->close_write_flag
= 1;
2310 ret
= utils_rotate_stream_file(stream
->path_name
, stream
->channel_name
,
2311 stream
->tracefile_size
, stream
->tracefile_count
,
2312 relayd_uid
, relayd_gid
, stream
->fd
,
2313 &(stream
->tracefile_count_current
), &stream
->fd
);
2314 stream
->total_index_received
= 0;
2315 pthread_mutex_unlock(&stream
->viewer_stream_rotation_lock
);
2317 ERR("Rotating stream output file");
2318 goto end_rcu_unlock
;
2320 /* Reset current size because we just perform a stream rotation. */
2321 stream
->tracefile_size_current
= 0;
2326 * Index are handled in protocol version 2.4 and above. Also, snapshot and
2327 * index are NOT supported.
2329 if (session
->minor
>= 4 && !session
->snapshot
) {
2330 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2332 goto end_rcu_unlock
;
2336 /* Write data to stream output fd. */
2337 size_ret
= lttng_write(stream
->fd
, data_buffer
, data_size
);
2338 if (size_ret
< data_size
) {
2339 ERR("Relay error writing data to file");
2341 goto end_rcu_unlock
;
2344 DBG2("Relay wrote %d bytes to tracefile for stream id %" PRIu64
,
2345 ret
, stream
->stream_handle
);
2347 ret
= write_padding_to_file(stream
->fd
, be32toh(data_hdr
.padding_size
));
2349 goto end_rcu_unlock
;
2351 stream
->tracefile_size_current
+= data_size
+ be32toh(data_hdr
.padding_size
);
2353 stream
->prev_seq
= net_seq_num
;
2355 try_close_stream(session
, stream
);
2364 void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2370 (void) lttng_poll_del(events
, pollfd
);
2372 ret
= close(pollfd
);
2374 ERR("Closing pollfd %d", pollfd
);
2378 static void destroy_connection(struct lttng_ht
*relay_connections_ht
,
2379 struct relay_connection
*conn
)
2381 assert(relay_connections_ht
);
2384 connection_delete(relay_connections_ht
, conn
);
2386 /* For the control socket, we try to destroy the session. */
2387 if (conn
->type
== RELAY_CONTROL
) {
2388 destroy_session(conn
->session
, conn
->sessions_ht
);
2391 connection_destroy(conn
);
2395 * This thread does the actual work
2398 void *relay_thread_worker(void *data
)
2400 int ret
, err
= -1, last_seen_data_fd
= -1;
2402 struct relay_connection
*conn
;
2403 struct lttng_poll_event events
;
2404 struct lttng_ht
*relay_connections_ht
;
2405 struct lttng_ht_iter iter
;
2406 struct lttcomm_relayd_hdr recv_hdr
;
2407 struct relay_local_data
*relay_ctx
= (struct relay_local_data
*) data
;
2408 struct lttng_ht
*sessions_ht
= relay_ctx
->sessions_ht
;
2410 DBG("[thread] Relay worker started");
2412 rcu_register_thread();
2414 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2416 if (testpoint(relayd_thread_worker
)) {
2417 goto error_testpoint
;
2420 health_code_update();
2422 /* table of connections indexed on socket */
2423 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2424 if (!relay_connections_ht
) {
2425 goto relay_connections_ht_error
;
2428 /* Tables of received indexes indexed by index handle and net_seq_num. */
2429 indexes_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_TWO_U64
);
2431 goto indexes_ht_error
;
2434 ret
= create_thread_poll_set(&events
, 2);
2436 goto error_poll_create
;
2439 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2446 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2448 health_code_update();
2450 /* Infinite blocking call, waiting for transmission */
2451 DBG3("Relayd worker thread polling...");
2452 health_poll_entry();
2453 ret
= lttng_poll_wait(&events
, -1);
2457 * Restart interrupted system call.
2459 if (errno
== EINTR
) {
2468 * Process control. The control connection is prioritised so we don't
2469 * starve it with high throughout put tracing data on the data
2472 for (i
= 0; i
< nb_fd
; i
++) {
2473 /* Fetch once the poll data */
2474 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2475 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2477 health_code_update();
2479 /* Thread quit pipe has been closed. Killing thread. */
2480 ret
= check_thread_quit_pipe(pollfd
, revents
);
2486 /* Inspect the relay conn pipe for new connection */
2487 if (pollfd
== relay_conn_pipe
[0]) {
2488 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2489 ERR("Relay connection pipe error");
2491 } else if (revents
& LPOLLIN
) {
2492 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2496 conn
->sessions_ht
= sessions_ht
;
2497 connection_init(conn
);
2498 lttng_poll_add(&events
, conn
->sock
->fd
,
2499 LPOLLIN
| LPOLLRDHUP
);
2501 lttng_ht_add_unique_ulong(relay_connections_ht
,
2504 DBG("Connection socket %d added", conn
->sock
->fd
);
2508 conn
= connection_find_by_sock(relay_connections_ht
, pollfd
);
2509 /* If not found, there is a synchronization issue. */
2512 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2513 cleanup_connection_pollfd(&events
, pollfd
);
2514 destroy_connection(relay_connections_ht
, conn
);
2515 if (last_seen_data_fd
== pollfd
) {
2516 last_seen_data_fd
= last_notdel_data_fd
;
2518 } else if (revents
& LPOLLIN
) {
2519 if (conn
->type
== RELAY_CONTROL
) {
2520 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &recv_hdr
,
2521 sizeof(recv_hdr
), 0);
2523 /* Connection closed */
2524 cleanup_connection_pollfd(&events
, pollfd
);
2525 destroy_connection(relay_connections_ht
, conn
);
2526 DBG("Control connection closed with %d", pollfd
);
2528 ret
= relay_process_control(&recv_hdr
, conn
);
2530 /* Clear the session on error. */
2531 cleanup_connection_pollfd(&events
, pollfd
);
2532 destroy_connection(relay_connections_ht
, conn
);
2533 DBG("Connection closed with %d", pollfd
);
2539 * Flag the last seen data fd not deleted. It will be
2540 * used as the last seen fd if any fd gets deleted in
2543 last_notdel_data_fd
= pollfd
;
2546 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
2553 * The last loop handled a control request, go back to poll to make
2554 * sure we prioritise the control socket.
2560 if (last_seen_data_fd
>= 0) {
2561 for (i
= 0; i
< nb_fd
; i
++) {
2562 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2564 health_code_update();
2566 if (last_seen_data_fd
== pollfd
) {
2573 /* Process data connection. */
2574 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2575 /* Fetch the poll data. */
2576 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2577 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2579 health_code_update();
2581 /* Skip the command pipe. It's handled in the first loop. */
2582 if (pollfd
== relay_conn_pipe
[0]) {
2588 conn
= connection_find_by_sock(relay_connections_ht
, pollfd
);
2590 /* Skip it. Might be removed before. */
2595 if (revents
& LPOLLIN
) {
2596 if (conn
->type
!= RELAY_DATA
) {
2600 ret
= relay_process_data(conn
);
2601 /* Connection closed */
2603 cleanup_connection_pollfd(&events
, pollfd
);
2604 destroy_connection(relay_connections_ht
, conn
);
2605 DBG("Data connection closed with %d", pollfd
);
2607 * Every goto restart call sets the last seen fd where
2608 * here we don't really care since we gracefully
2609 * continue the loop after the connection is deleted.
2612 /* Keep last seen port. */
2613 last_seen_data_fd
= pollfd
;
2621 last_seen_data_fd
= -1;
2624 /* Normal exit, no error */
2629 lttng_poll_clean(&events
);
2631 /* Cleanup reamaining connection object. */
2633 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
, conn
,
2635 health_code_update();
2636 destroy_connection(relay_connections_ht
, conn
);
2640 lttng_ht_destroy(indexes_ht
);
2642 lttng_ht_destroy(relay_connections_ht
);
2643 relay_connections_ht_error
:
2644 /* Close relay conn pipes */
2645 utils_close_pipe(relay_conn_pipe
);
2647 DBG("Thread exited with error");
2649 DBG("Worker thread cleanup complete");
2654 ERR("Health error occurred in %s", __func__
);
2656 health_unregister(health_relayd
);
2657 rcu_unregister_thread();
2663 * Create the relay command pipe to wake thread_manage_apps.
2664 * Closed in cleanup().
2666 static int create_relay_conn_pipe(void)
2670 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2678 int main(int argc
, char **argv
)
2682 struct relay_local_data
*relay_ctx
;
2684 /* Parse arguments */
2686 if ((ret
= set_options(argc
, argv
)) < 0) {
2690 if ((ret
= set_signal_handler()) < 0) {
2694 /* Try to create directory if -o, --output is specified. */
2695 if (opt_output_path
) {
2696 if (*opt_output_path
!= '/') {
2697 ERR("Please specify an absolute path for -o, --output PATH");
2701 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
);
2703 ERR("Unable to create %s", opt_output_path
);
2709 if (opt_daemon
|| opt_background
) {
2712 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2719 * We are in the child. Make sure all other file
2720 * descriptors are closed, in case we are called with
2721 * more opened file descriptors than the standard ones.
2723 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2728 /* Create thread quit pipe */
2729 if ((ret
= init_thread_quit_pipe()) < 0) {
2733 /* We need those values for the file/dir creation. */
2734 relayd_uid
= getuid();
2735 relayd_gid
= getgid();
2737 /* Check if daemon is UID = 0 */
2738 if (relayd_uid
== 0) {
2739 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2740 ERR("Need to be root to use ports < 1024");
2746 /* Setup the thread apps communication pipe. */
2747 if ((ret
= create_relay_conn_pipe()) < 0) {
2751 /* Init relay command queue. */
2752 cds_wfq_init(&relay_conn_queue
.queue
);
2754 /* Set up max poll set size */
2755 lttng_poll_set_max_size();
2757 /* Initialize communication library */
2759 lttcomm_inet_init();
2761 relay_ctx
= zmalloc(sizeof(struct relay_local_data
));
2763 PERROR("relay_ctx");
2767 /* tables of sessions indexed by session ID */
2768 relay_ctx
->sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2769 if (!relay_ctx
->sessions_ht
) {
2770 goto exit_relay_ctx_sessions
;
2773 /* tables of streams indexed by stream ID */
2774 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2775 if (!relay_streams_ht
) {
2776 goto exit_relay_ctx_streams
;
2779 /* tables of streams indexed by stream ID */
2780 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2781 if (!viewer_streams_ht
) {
2782 goto exit_relay_ctx_viewer_streams
;
2785 /* Initialize thread health monitoring */
2786 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2787 if (!health_relayd
) {
2788 PERROR("health_app_create error");
2789 goto exit_health_app_create
;
2792 ret
= utils_create_pipe(health_quit_pipe
);
2794 goto error_health_pipe
;
2797 /* Create thread to manage the client socket */
2798 ret
= pthread_create(&health_thread
, NULL
,
2799 thread_manage_health
, (void *) NULL
);
2801 PERROR("pthread_create health");
2805 /* Setup the dispatcher thread */
2806 ret
= pthread_create(&dispatcher_thread
, NULL
,
2807 relay_thread_dispatcher
, (void *) NULL
);
2809 PERROR("pthread_create dispatcher");
2810 goto exit_dispatcher
;
2813 /* Setup the worker thread */
2814 ret
= pthread_create(&worker_thread
, NULL
,
2815 relay_thread_worker
, (void *) relay_ctx
);
2817 PERROR("pthread_create worker");
2821 /* Setup the listener thread */
2822 ret
= pthread_create(&listener_thread
, NULL
,
2823 relay_thread_listener
, (void *) NULL
);
2825 PERROR("pthread_create listener");
2829 ret
= live_start_threads(live_uri
, relay_ctx
);
2831 ERR("Starting live viewer threads");
2836 ret
= pthread_join(listener_thread
, &status
);
2838 PERROR("pthread_join");
2839 goto error
; /* join error, exit without cleanup */
2843 ret
= pthread_join(worker_thread
, &status
);
2845 PERROR("pthread_join");
2846 goto error
; /* join error, exit without cleanup */
2850 ret
= pthread_join(dispatcher_thread
, &status
);
2852 PERROR("pthread_join");
2853 goto error
; /* join error, exit without cleanup */
2857 ret
= pthread_join(health_thread
, &status
);
2859 PERROR("pthread_join health thread");
2860 goto error
; /* join error, exit without cleanup */
2864 * Stop live threads only after joining other threads.
2866 live_stop_threads();
2869 utils_close_pipe(health_quit_pipe
);
2872 health_app_destroy(health_relayd
);
2874 exit_health_app_create
:
2875 lttng_ht_destroy(viewer_streams_ht
);
2877 exit_relay_ctx_viewer_streams
:
2878 lttng_ht_destroy(relay_streams_ht
);
2880 exit_relay_ctx_streams
:
2881 lttng_ht_destroy(relay_ctx
->sessions_ht
);
2883 exit_relay_ctx_sessions
: