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.
32 #include <sys/mount.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
36 #include <sys/types.h>
39 #include <urcu/futex.h>
40 #include <urcu/uatomic.h>
45 #include <lttng/lttng.h>
46 #include <common/common.h>
47 #include <common/compat/poll.h>
48 #include <common/compat/socket.h>
49 #include <common/compat/endian.h>
50 #include <common/compat/getenv.h>
51 #include <common/defaults.h>
52 #include <common/daemonize.h>
53 #include <common/futex.h>
54 #include <common/sessiond-comm/sessiond-comm.h>
55 #include <common/sessiond-comm/inet.h>
56 #include <common/sessiond-comm/relayd.h>
57 #include <common/uri.h>
58 #include <common/utils.h>
59 #include <common/config/config.h>
60 #include <urcu/rculist.h>
63 #include "ctf-trace.h"
66 #include "lttng-relayd.h"
68 #include "health-relayd.h"
69 #include "testpoint.h"
70 #include "viewer-stream.h"
73 #include "connection.h"
75 /* command line options */
76 char *opt_output_path
;
77 static int opt_daemon
, opt_background
;
80 * We need to wait for listener and live listener threads, as well as
81 * health check thread, before being ready to signal readiness.
83 #define NR_LTTNG_RELAY_READY 3
84 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
85 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
86 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
88 static struct lttng_uri
*control_uri
;
89 static struct lttng_uri
*data_uri
;
90 static struct lttng_uri
*live_uri
;
94 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
95 static int tracing_group_name_override
;
97 const char * const config_section_name
= "relayd";
100 * Quit pipe for all threads. This permits a single cancellation point
101 * for all threads when receiving an event on the pipe.
103 int thread_quit_pipe
[2] = { -1, -1 };
106 * This pipe is used to inform the worker thread that a command is queued and
107 * ready to be processed.
109 static int relay_conn_pipe
[2] = { -1, -1 };
111 /* Shared between threads */
112 static int dispatch_thread_exit
;
114 static pthread_t listener_thread
;
115 static pthread_t dispatcher_thread
;
116 static pthread_t worker_thread
;
117 static pthread_t health_thread
;
120 * last_relay_stream_id_lock protects last_relay_stream_id increment
121 * atomicity on 32-bit architectures.
123 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
124 static uint64_t last_relay_stream_id
;
127 * Relay command queue.
129 * The relay_thread_listener and relay_thread_dispatcher communicate with this
132 static struct relay_conn_queue relay_conn_queue
;
134 /* buffer allocated at startup, used to store the trace data */
135 static char *data_buffer
;
136 static unsigned int data_buffer_size
;
138 /* Global relay stream hash table. */
139 struct lttng_ht
*relay_streams_ht
;
141 /* Global relay viewer stream hash table. */
142 struct lttng_ht
*viewer_streams_ht
;
144 /* Global relay sessions hash table. */
145 struct lttng_ht
*sessions_ht
;
147 /* Relayd health monitoring */
148 struct health_app
*health_relayd
;
150 static struct option long_options
[] = {
151 { "control-port", 1, 0, 'C', },
152 { "data-port", 1, 0, 'D', },
153 { "live-port", 1, 0, 'L', },
154 { "daemonize", 0, 0, 'd', },
155 { "background", 0, 0, 'b', },
156 { "group", 1, 0, 'g', },
157 { "help", 0, 0, 'h', },
158 { "output", 1, 0, 'o', },
159 { "verbose", 0, 0, 'v', },
160 { "config", 1, 0, 'f' },
164 static const char *config_ignore_options
[] = { "help", "config" };
167 * usage function on stderr
169 static void usage(void)
171 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
172 fprintf(stderr
, " -h, --help Display this usage.\n");
173 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
174 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
175 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
176 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
177 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
178 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
179 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
180 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
181 fprintf(stderr
, " -f --config Load daemon configuration file\n");
185 * Take an option from the getopt output and set it in the right variable to be
188 * Return 0 on success else a negative value.
190 static int set_option(int opt
, const char *arg
, const char *optname
)
196 fprintf(stderr
, "option %s", optname
);
198 fprintf(stderr
, " with arg %s\n", arg
);
202 if (lttng_is_setuid_setgid()) {
203 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
204 "-C, --control-port");
206 ret
= uri_parse(arg
, &control_uri
);
208 ERR("Invalid control URI specified");
211 if (control_uri
->port
== 0) {
212 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
217 if (lttng_is_setuid_setgid()) {
218 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
221 ret
= uri_parse(arg
, &data_uri
);
223 ERR("Invalid data URI specified");
226 if (data_uri
->port
== 0) {
227 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
232 if (lttng_is_setuid_setgid()) {
233 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
236 ret
= uri_parse(arg
, &live_uri
);
238 ERR("Invalid live URI specified");
241 if (live_uri
->port
== 0) {
242 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
253 if (lttng_is_setuid_setgid()) {
254 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
257 tracing_group_name
= strdup(arg
);
258 if (tracing_group_name
== NULL
) {
263 tracing_group_name_override
= 1;
270 if (lttng_is_setuid_setgid()) {
271 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
274 ret
= asprintf(&opt_output_path
, "%s", arg
);
277 PERROR("asprintf opt_output_path");
283 /* Verbose level can increase using multiple -v */
285 lttng_opt_verbose
= config_parse_value(arg
);
287 /* Only 3 level of verbosity (-vvv). */
288 if (lttng_opt_verbose
< 3) {
289 lttng_opt_verbose
+= 1;
294 /* Unknown option or other error.
295 * Error is printed by getopt, just return */
308 * config_entry_handler_cb used to handle options read from a config file.
309 * See config_entry_handler_cb comment in common/config/config.h for the
310 * return value conventions.
312 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
316 if (!entry
|| !entry
->name
|| !entry
->value
) {
321 /* Check if the option is to be ignored */
322 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
323 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
328 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
329 /* Ignore if entry name is not fully matched. */
330 if (strcmp(entry
->name
, long_options
[i
].name
)) {
335 * If the option takes no argument on the command line,
336 * we have to check if the value is "true". We support
337 * non-zero numeric values, true, on and yes.
339 if (!long_options
[i
].has_arg
) {
340 ret
= config_parse_value(entry
->value
);
343 WARN("Invalid configuration value \"%s\" for option %s",
344 entry
->value
, entry
->name
);
346 /* False, skip boolean config option. */
351 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
355 WARN("Unrecognized option \"%s\" in daemon configuration file.",
362 static int set_options(int argc
, char **argv
)
364 int c
, ret
= 0, option_index
= 0, retval
= 0;
365 int orig_optopt
= optopt
, orig_optind
= optind
;
366 char *default_address
, *optstring
;
367 const char *config_path
= NULL
;
369 optstring
= utils_generate_optstring(long_options
,
370 sizeof(long_options
) / sizeof(struct option
));
376 /* Check for the --config option */
378 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
379 &option_index
)) != -1) {
383 } else if (c
!= 'f') {
387 if (lttng_is_setuid_setgid()) {
388 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
391 config_path
= utils_expand_path(optarg
);
393 ERR("Failed to resolve path: %s", optarg
);
398 ret
= config_get_section_entries(config_path
, config_section_name
,
399 config_entry_handler
, NULL
);
402 ERR("Invalid configuration option at line %i", ret
);
408 /* Reset getopt's global state */
409 optopt
= orig_optopt
;
410 optind
= orig_optind
;
412 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
417 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
424 /* assign default values */
425 if (control_uri
== NULL
) {
426 ret
= asprintf(&default_address
,
427 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
428 DEFAULT_NETWORK_CONTROL_PORT
);
430 PERROR("asprintf default data address");
435 ret
= uri_parse(default_address
, &control_uri
);
436 free(default_address
);
438 ERR("Invalid control URI specified");
443 if (data_uri
== NULL
) {
444 ret
= asprintf(&default_address
,
445 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
446 DEFAULT_NETWORK_DATA_PORT
);
448 PERROR("asprintf default data address");
453 ret
= uri_parse(default_address
, &data_uri
);
454 free(default_address
);
456 ERR("Invalid data URI specified");
461 if (live_uri
== NULL
) {
462 ret
= asprintf(&default_address
,
463 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
464 DEFAULT_NETWORK_VIEWER_PORT
);
466 PERROR("asprintf default viewer control address");
471 ret
= uri_parse(default_address
, &live_uri
);
472 free(default_address
);
474 ERR("Invalid viewer control URI specified");
485 static void print_global_objects(void)
487 rcu_register_thread();
489 print_viewer_streams();
490 print_relay_streams();
493 rcu_unregister_thread();
499 static void relayd_cleanup(void)
501 print_global_objects();
505 if (viewer_streams_ht
)
506 lttng_ht_destroy(viewer_streams_ht
);
507 if (relay_streams_ht
)
508 lttng_ht_destroy(relay_streams_ht
);
510 lttng_ht_destroy(sessions_ht
);
512 /* free the dynamically allocated opt_output_path */
513 free(opt_output_path
);
515 /* Close thread quit pipes */
516 utils_close_pipe(thread_quit_pipe
);
518 uri_free(control_uri
);
520 /* Live URI is freed in the live thread. */
522 if (tracing_group_name_override
) {
523 free((void *) tracing_group_name
);
528 * Write to writable pipe used to notify a thread.
530 static int notify_thread_pipe(int wpipe
)
534 ret
= lttng_write(wpipe
, "!", 1);
536 PERROR("write poll pipe");
544 static int notify_health_quit_pipe(int *pipe
)
548 ret
= lttng_write(pipe
[1], "4", 1);
550 PERROR("write relay health quit");
559 * Stop all relayd and relayd-live threads.
561 int lttng_relay_stop_threads(void)
565 /* Stopping all threads */
566 DBG("Terminating all threads");
567 if (notify_thread_pipe(thread_quit_pipe
[1])) {
568 ERR("write error on thread quit pipe");
572 if (notify_health_quit_pipe(health_quit_pipe
)) {
573 ERR("write error on health quit pipe");
576 /* Dispatch thread */
577 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
578 futex_nto1_wake(&relay_conn_queue
.futex
);
580 if (relayd_live_stop()) {
581 ERR("Error stopping live threads");
588 * Signal handler for the daemon
590 * Simply stop all worker threads, leaving main() return gracefully after
591 * joining all threads and calling cleanup().
593 static void sighandler(int sig
)
597 DBG("SIGPIPE caught");
600 DBG("SIGINT caught");
601 if (lttng_relay_stop_threads()) {
602 ERR("Error stopping threads");
606 DBG("SIGTERM caught");
607 if (lttng_relay_stop_threads()) {
608 ERR("Error stopping threads");
612 CMM_STORE_SHARED(recv_child_signal
, 1);
620 * Setup signal handler for :
621 * SIGINT, SIGTERM, SIGPIPE
623 static int set_signal_handler(void)
629 if ((ret
= sigemptyset(&sigset
)) < 0) {
630 PERROR("sigemptyset");
634 sa
.sa_handler
= sighandler
;
637 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
642 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
647 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
652 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
657 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
662 void lttng_relay_notify_ready(void)
664 /* Notify the parent of the fork() process that we are ready. */
665 if (opt_daemon
|| opt_background
) {
666 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
667 kill(child_ppid
, SIGUSR1
);
673 * Init thread quit pipe.
675 * Return -1 on error or 0 if all pipes are created.
677 static int init_thread_quit_pipe(void)
681 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
687 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
689 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
693 if (events
== NULL
|| size
== 0) {
698 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
704 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
716 * Check if the thread quit pipe was triggered.
718 * Return 1 if it was triggered else 0;
720 static int check_thread_quit_pipe(int fd
, uint32_t events
)
722 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
730 * Create and init socket from uri.
732 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
735 struct lttcomm_sock
*sock
= NULL
;
737 sock
= lttcomm_alloc_sock_from_uri(uri
);
739 ERR("Allocating socket");
743 ret
= lttcomm_create_sock(sock
);
747 DBG("Listening on sock %d", sock
->fd
);
749 ret
= sock
->ops
->bind(sock
);
754 ret
= sock
->ops
->listen(sock
, -1);
764 lttcomm_destroy_sock(sock
);
770 * This thread manages the listening for new connections on the network
772 static void *relay_thread_listener(void *data
)
774 int i
, ret
, pollfd
, err
= -1;
775 uint32_t revents
, nb_fd
;
776 struct lttng_poll_event events
;
777 struct lttcomm_sock
*control_sock
, *data_sock
;
779 DBG("[thread] Relay listener started");
781 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
783 health_code_update();
785 control_sock
= relay_socket_create(control_uri
);
787 goto error_sock_control
;
790 data_sock
= relay_socket_create(data_uri
);
792 goto error_sock_relay
;
796 * Pass 3 as size here for the thread quit pipe, control and
799 ret
= create_thread_poll_set(&events
, 3);
801 goto error_create_poll
;
804 /* Add the control socket */
805 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
810 /* Add the data socket */
811 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
816 lttng_relay_notify_ready();
818 if (testpoint(relayd_thread_listener
)) {
819 goto error_testpoint
;
823 health_code_update();
825 DBG("Listener accepting connections");
829 ret
= lttng_poll_wait(&events
, -1);
833 * Restart interrupted system call.
835 if (errno
== EINTR
) {
843 DBG("Relay new connection received");
844 for (i
= 0; i
< nb_fd
; i
++) {
845 health_code_update();
847 /* Fetch once the poll data */
848 revents
= LTTNG_POLL_GETEV(&events
, i
);
849 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
853 * No activity for this FD (poll
859 /* Thread quit pipe has been closed. Killing thread. */
860 ret
= check_thread_quit_pipe(pollfd
, revents
);
866 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
867 ERR("socket poll error");
869 } else if (revents
& LPOLLIN
) {
871 * A new connection is requested, therefore a
872 * sessiond/consumerd connection is allocated in
873 * this thread, enqueued to a global queue and
874 * dequeued (and freed) in the worker thread.
877 struct relay_connection
*new_conn
;
878 struct lttcomm_sock
*newsock
;
879 enum connection_type type
;
881 if (pollfd
== data_sock
->fd
) {
883 newsock
= data_sock
->ops
->accept(data_sock
);
884 DBG("Relay data connection accepted, socket %d",
887 assert(pollfd
== control_sock
->fd
);
888 type
= RELAY_CONTROL
;
889 newsock
= control_sock
->ops
->accept(control_sock
);
890 DBG("Relay control connection accepted, socket %d",
894 PERROR("accepting sock");
898 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
901 PERROR("setsockopt inet");
902 lttcomm_destroy_sock(newsock
);
905 new_conn
= connection_create(newsock
, type
);
907 lttcomm_destroy_sock(newsock
);
911 /* Enqueue request for the dispatcher thread. */
912 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
916 * Wake the dispatch queue futex.
917 * Implicit memory barrier with the
918 * exchange in cds_wfcq_enqueue.
920 futex_nto1_wake(&relay_conn_queue
.futex
);
929 lttng_poll_clean(&events
);
931 if (data_sock
->fd
>= 0) {
932 ret
= data_sock
->ops
->close(data_sock
);
937 lttcomm_destroy_sock(data_sock
);
939 if (control_sock
->fd
>= 0) {
940 ret
= control_sock
->ops
->close(control_sock
);
945 lttcomm_destroy_sock(control_sock
);
949 ERR("Health error occurred in %s", __func__
);
951 health_unregister(health_relayd
);
952 DBG("Relay listener thread cleanup complete");
953 lttng_relay_stop_threads();
958 * This thread manages the dispatching of the requests to worker threads
960 static void *relay_thread_dispatcher(void *data
)
964 struct cds_wfcq_node
*node
;
965 struct relay_connection
*new_conn
= NULL
;
967 DBG("[thread] Relay dispatcher started");
969 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
971 if (testpoint(relayd_thread_dispatcher
)) {
972 goto error_testpoint
;
975 health_code_update();
977 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
978 health_code_update();
980 /* Atomically prepare the queue futex */
981 futex_nto1_prepare(&relay_conn_queue
.futex
);
984 health_code_update();
986 /* Dequeue commands */
987 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
988 &relay_conn_queue
.tail
);
990 DBG("Woken up but nothing in the relay command queue");
991 /* Continue thread execution */
994 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
996 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
999 * Inform worker thread of the new request. This
1000 * call is blocking so we can be assured that
1001 * the data will be read at some point in time
1002 * or wait to the end of the world :)
1004 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1006 PERROR("write connection pipe");
1007 connection_put(new_conn
);
1010 } while (node
!= NULL
);
1012 /* Futex wait on queue. Blocking call on futex() */
1013 health_poll_entry();
1014 futex_nto1_wait(&relay_conn_queue
.futex
);
1018 /* Normal exit, no error */
1025 ERR("Health error occurred in %s", __func__
);
1027 health_unregister(health_relayd
);
1028 DBG("Dispatch thread dying");
1029 lttng_relay_stop_threads();
1034 * Set index data from the control port to a given index object.
1036 static int set_index_control_data(struct relay_index
*index
,
1037 struct lttcomm_relayd_index
*data
)
1039 struct ctf_packet_index index_data
;
1042 * The index on disk is encoded in big endian, so we don't need
1043 * to convert the data received on the network. The data_offset
1044 * value is NEVER modified here and is updated by the data
1047 index_data
.packet_size
= data
->packet_size
;
1048 index_data
.content_size
= data
->content_size
;
1049 index_data
.timestamp_begin
= data
->timestamp_begin
;
1050 index_data
.timestamp_end
= data
->timestamp_end
;
1051 index_data
.events_discarded
= data
->events_discarded
;
1052 index_data
.stream_id
= data
->stream_id
;
1053 return relay_index_set_data(index
, &index_data
);
1057 * Handle the RELAYD_CREATE_SESSION command.
1059 * On success, send back the session id or else return a negative value.
1061 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1062 struct relay_connection
*conn
)
1064 int ret
= 0, send_ret
;
1065 struct relay_session
*session
;
1066 struct lttcomm_relayd_status_session reply
;
1067 char session_name
[NAME_MAX
];
1068 char hostname
[HOST_NAME_MAX
];
1069 uint32_t live_timer
= 0;
1070 bool snapshot
= false;
1072 memset(session_name
, 0, NAME_MAX
);
1073 memset(hostname
, 0, HOST_NAME_MAX
);
1075 memset(&reply
, 0, sizeof(reply
));
1077 switch (conn
->minor
) {
1082 case 4: /* LTTng sessiond 2.4 */
1084 ret
= cmd_create_session_2_4(conn
, session_name
,
1085 hostname
, &live_timer
, &snapshot
);
1091 session
= session_create(session_name
, hostname
, live_timer
,
1092 snapshot
, conn
->major
, conn
->minor
);
1097 assert(!conn
->session
);
1098 conn
->session
= session
;
1099 DBG("Created session %" PRIu64
, session
->id
);
1101 reply
.session_id
= htobe64(session
->id
);
1105 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1107 reply
.ret_code
= htobe32(LTTNG_OK
);
1110 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1112 ERR("Relayd sending session id");
1120 * When we have received all the streams and the metadata for a channel,
1121 * we make them visible to the viewer threads.
1123 static void publish_connection_local_streams(struct relay_connection
*conn
)
1125 struct relay_stream
*stream
;
1126 struct relay_session
*session
= conn
->session
;
1129 * We publish all streams belonging to a session atomically wrt
1132 pthread_mutex_lock(&session
->lock
);
1134 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1136 stream_publish(stream
);
1141 * Inform the viewer that there are new streams in the session.
1143 if (session
->viewer_attached
) {
1144 uatomic_set(&session
->new_streams
, 1);
1146 pthread_mutex_unlock(&session
->lock
);
1150 * relay_add_stream: allocate a new stream for a session
1152 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1153 struct relay_connection
*conn
)
1157 struct relay_session
*session
= conn
->session
;
1158 struct relay_stream
*stream
= NULL
;
1159 struct lttcomm_relayd_status_stream reply
;
1160 struct ctf_trace
*trace
= NULL
;
1161 uint64_t stream_handle
= -1ULL;
1162 char *path_name
= NULL
, *channel_name
= NULL
;
1163 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1165 if (!session
|| conn
->version_check_done
== 0) {
1166 ERR("Trying to add a stream before version check");
1168 goto end_no_session
;
1171 switch (session
->minor
) {
1172 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1173 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1176 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1178 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1179 &channel_name
, &tracefile_size
, &tracefile_count
);
1186 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1190 /* This stream here has one reference on the trace. */
1192 pthread_mutex_lock(&last_relay_stream_id_lock
);
1193 stream_handle
= ++last_relay_stream_id
;
1194 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1196 /* We pass ownership of path_name and channel_name. */
1197 stream
= stream_create(trace
, stream_handle
, path_name
,
1198 channel_name
, tracefile_size
, tracefile_count
);
1200 channel_name
= NULL
;
1203 * Streams are the owners of their trace. Reference to trace is
1204 * kept within stream_create().
1206 ctf_trace_put(trace
);
1209 memset(&reply
, 0, sizeof(reply
));
1210 reply
.handle
= htobe64(stream_handle
);
1212 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1214 reply
.ret_code
= htobe32(LTTNG_OK
);
1217 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1218 sizeof(struct lttcomm_relayd_status_stream
), 0);
1220 ERR("Relay sending stream id");
1221 ret
= (int) send_ret
;
1231 * relay_close_stream: close a specific stream
1233 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1234 struct relay_connection
*conn
)
1237 struct relay_session
*session
= conn
->session
;
1238 struct lttcomm_relayd_close_stream stream_info
;
1239 struct lttcomm_relayd_generic_reply reply
;
1240 struct relay_stream
*stream
;
1242 DBG("Close stream received");
1244 if (!session
|| conn
->version_check_done
== 0) {
1245 ERR("Trying to close a stream before version check");
1247 goto end_no_session
;
1250 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1251 sizeof(struct lttcomm_relayd_close_stream
), 0);
1252 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1254 /* Orderly shutdown. Not necessary to print an error. */
1255 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1257 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1260 goto end_no_session
;
1263 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1268 pthread_mutex_lock(&stream
->lock
);
1269 stream
->closed
= true;
1270 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1271 if (stream
->is_metadata
) {
1272 struct relay_viewer_stream
*vstream
;
1274 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1276 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1278 * Since all the metadata has been sent to the
1279 * viewer and that we have a request to close
1280 * its stream, we can safely teardown the
1281 * corresponding metadata viewer stream.
1283 viewer_stream_put(vstream
);
1285 /* Put local reference. */
1286 viewer_stream_put(vstream
);
1289 pthread_mutex_unlock(&stream
->lock
);
1293 memset(&reply
, 0, sizeof(reply
));
1295 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1297 reply
.ret_code
= htobe32(LTTNG_OK
);
1299 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1300 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1302 ERR("Relay sending stream id");
1311 * relay_unknown_command: send -1 if received unknown command
1313 static void relay_unknown_command(struct relay_connection
*conn
)
1315 struct lttcomm_relayd_generic_reply reply
;
1318 memset(&reply
, 0, sizeof(reply
));
1319 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1320 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1321 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1323 ERR("Relay sending unknown command");
1328 * relay_start: send an acknowledgment to the client to tell if we are
1329 * ready to receive data. We are ready if a session is established.
1331 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1332 struct relay_connection
*conn
)
1334 int ret
= htobe32(LTTNG_OK
);
1335 struct lttcomm_relayd_generic_reply reply
;
1336 struct relay_session
*session
= conn
->session
;
1339 DBG("Trying to start the streaming without a session established");
1340 ret
= htobe32(LTTNG_ERR_UNK
);
1343 memset(&reply
, 0, sizeof(reply
));
1344 reply
.ret_code
= ret
;
1345 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1346 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1348 ERR("Relay sending start ack");
1355 * Append padding to the file pointed by the file descriptor fd.
1357 static int write_padding_to_file(int fd
, uint32_t size
)
1366 zeros
= zmalloc(size
);
1367 if (zeros
== NULL
) {
1368 PERROR("zmalloc zeros for padding");
1373 ret
= lttng_write(fd
, zeros
, size
);
1375 PERROR("write padding to file");
1385 * relay_recv_metadata: receive the metadata for the session.
1387 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1388 struct relay_connection
*conn
)
1390 int ret
= htobe32(LTTNG_OK
);
1392 struct relay_session
*session
= conn
->session
;
1393 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1394 struct relay_stream
*metadata_stream
;
1395 uint64_t data_size
, payload_size
;
1398 ERR("Metadata sent before version check");
1403 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1404 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1405 ERR("Incorrect data size");
1409 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1411 if (data_buffer_size
< data_size
) {
1412 /* In case the realloc fails, we can free the memory */
1415 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1416 if (!tmp_data_ptr
) {
1417 ERR("Allocating data buffer");
1422 data_buffer
= tmp_data_ptr
;
1423 data_buffer_size
= data_size
;
1425 memset(data_buffer
, 0, data_size
);
1426 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1427 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1428 if (ret
< 0 || ret
!= data_size
) {
1430 /* Orderly shutdown. Not necessary to print an error. */
1431 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1433 ERR("Relay didn't receive the whole metadata");
1438 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1440 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1441 if (!metadata_stream
) {
1446 pthread_mutex_lock(&metadata_stream
->lock
);
1448 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1450 if (size_ret
< payload_size
) {
1451 ERR("Relay error writing metadata on file");
1456 ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1457 be32toh(metadata_struct
->padding_size
));
1462 metadata_stream
->metadata_received
+=
1463 payload_size
+ be32toh(metadata_struct
->padding_size
);
1464 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1465 metadata_stream
->metadata_received
);
1468 pthread_mutex_unlock(&metadata_stream
->lock
);
1469 stream_put(metadata_stream
);
1476 * relay_send_version: send relayd version number
1478 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1479 struct relay_connection
*conn
)
1482 struct lttcomm_relayd_version reply
, msg
;
1484 conn
->version_check_done
= 1;
1486 /* Get version from the other side. */
1487 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1488 if (ret
< 0 || ret
!= sizeof(msg
)) {
1490 /* Orderly shutdown. Not necessary to print an error. */
1491 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1493 ERR("Relay failed to receive the version values.");
1499 memset(&reply
, 0, sizeof(reply
));
1500 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1501 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1503 /* Major versions must be the same */
1504 if (reply
.major
!= be32toh(msg
.major
)) {
1505 DBG("Incompatible major versions (%u vs %u), deleting session",
1506 reply
.major
, be32toh(msg
.major
));
1507 connection_put(conn
);
1512 conn
->major
= reply
.major
;
1513 /* We adapt to the lowest compatible version */
1514 if (reply
.minor
<= be32toh(msg
.minor
)) {
1515 conn
->minor
= reply
.minor
;
1517 conn
->minor
= be32toh(msg
.minor
);
1520 reply
.major
= htobe32(reply
.major
);
1521 reply
.minor
= htobe32(reply
.minor
);
1522 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1523 sizeof(struct lttcomm_relayd_version
), 0);
1525 ERR("Relay sending version");
1528 DBG("Version check done using protocol %u.%u", conn
->major
,
1536 * Check for data pending for a given stream id from the session daemon.
1538 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1539 struct relay_connection
*conn
)
1541 struct relay_session
*session
= conn
->session
;
1542 struct lttcomm_relayd_data_pending msg
;
1543 struct lttcomm_relayd_generic_reply reply
;
1544 struct relay_stream
*stream
;
1546 uint64_t last_net_seq_num
, stream_id
;
1548 DBG("Data pending command received");
1550 if (!session
|| conn
->version_check_done
== 0) {
1551 ERR("Trying to check for data before version check");
1553 goto end_no_session
;
1556 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1557 if (ret
< sizeof(msg
)) {
1559 /* Orderly shutdown. Not necessary to print an error. */
1560 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1562 ERR("Relay didn't receive valid data_pending struct size : %d",
1566 goto end_no_session
;
1569 stream_id
= be64toh(msg
.stream_id
);
1570 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1572 stream
= stream_get_by_id(stream_id
);
1573 if (stream
== NULL
) {
1578 pthread_mutex_lock(&stream
->lock
);
1580 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1581 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1584 /* Avoid wrapping issue */
1585 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1586 /* Data has in fact been written and is NOT pending */
1589 /* Data still being streamed thus pending */
1593 stream
->data_pending_check_done
= true;
1594 pthread_mutex_unlock(&stream
->lock
);
1599 memset(&reply
, 0, sizeof(reply
));
1600 reply
.ret_code
= htobe32(ret
);
1601 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1603 ERR("Relay data pending ret code failed");
1611 * Wait for the control socket to reach a quiescent state.
1613 * Note that for now, when receiving this command from the session
1614 * daemon, this means that every subsequent commands or data received on
1615 * the control socket has been handled. So, this is why we simply return
1618 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1619 struct relay_connection
*conn
)
1623 struct relay_stream
*stream
;
1624 struct lttcomm_relayd_quiescent_control msg
;
1625 struct lttcomm_relayd_generic_reply reply
;
1627 DBG("Checking quiescent state on control socket");
1629 if (!conn
->session
|| conn
->version_check_done
== 0) {
1630 ERR("Trying to check for data before version check");
1632 goto end_no_session
;
1635 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1636 if (ret
< sizeof(msg
)) {
1638 /* Orderly shutdown. Not necessary to print an error. */
1639 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1641 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1645 goto end_no_session
;
1648 stream_id
= be64toh(msg
.stream_id
);
1649 stream
= stream_get_by_id(stream_id
);
1653 pthread_mutex_lock(&stream
->lock
);
1654 stream
->data_pending_check_done
= true;
1655 pthread_mutex_unlock(&stream
->lock
);
1656 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1659 memset(&reply
, 0, sizeof(reply
));
1660 reply
.ret_code
= htobe32(LTTNG_OK
);
1661 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1663 ERR("Relay data quiescent control ret code failed");
1671 * Initialize a data pending command. This means that a consumer is about
1672 * to ask for data pending for each stream it holds. Simply iterate over
1673 * all streams of a session and set the data_pending_check_done flag.
1675 * This command returns to the client a LTTNG_OK code.
1677 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1678 struct relay_connection
*conn
)
1681 struct lttng_ht_iter iter
;
1682 struct lttcomm_relayd_begin_data_pending msg
;
1683 struct lttcomm_relayd_generic_reply reply
;
1684 struct relay_stream
*stream
;
1685 uint64_t session_id
;
1690 DBG("Init streams for data pending");
1692 if (!conn
->session
|| conn
->version_check_done
== 0) {
1693 ERR("Trying to check for data before version check");
1695 goto end_no_session
;
1698 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1699 if (ret
< sizeof(msg
)) {
1701 /* Orderly shutdown. Not necessary to print an error. */
1702 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1704 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1708 goto end_no_session
;
1711 session_id
= be64toh(msg
.session_id
);
1714 * Iterate over all streams to set the begin data pending flag.
1715 * For now, the streams are indexed by stream handle so we have
1716 * to iterate over all streams to find the one associated with
1717 * the right session_id.
1720 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1722 if (!stream_get(stream
)) {
1725 if (stream
->trace
->session
->id
== session_id
) {
1726 pthread_mutex_lock(&stream
->lock
);
1727 stream
->data_pending_check_done
= false;
1728 pthread_mutex_unlock(&stream
->lock
);
1729 DBG("Set begin data pending flag to stream %" PRIu64
,
1730 stream
->stream_handle
);
1736 memset(&reply
, 0, sizeof(reply
));
1737 /* All good, send back reply. */
1738 reply
.ret_code
= htobe32(LTTNG_OK
);
1740 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1742 ERR("Relay begin data pending send reply failed");
1750 * End data pending command. This will check, for a given session id, if
1751 * each stream associated with it has its data_pending_check_done flag
1752 * set. If not, this means that the client lost track of the stream but
1753 * the data is still being streamed on our side. In this case, we inform
1754 * the client that data is in flight.
1756 * Return to the client if there is data in flight or not with a ret_code.
1758 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1759 struct relay_connection
*conn
)
1762 struct lttng_ht_iter iter
;
1763 struct lttcomm_relayd_end_data_pending msg
;
1764 struct lttcomm_relayd_generic_reply reply
;
1765 struct relay_stream
*stream
;
1766 uint64_t session_id
;
1767 uint32_t is_data_inflight
= 0;
1769 DBG("End data pending command");
1771 if (!conn
->session
|| conn
->version_check_done
== 0) {
1772 ERR("Trying to check for data before version check");
1774 goto end_no_session
;
1777 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1778 if (ret
< sizeof(msg
)) {
1780 /* Orderly shutdown. Not necessary to print an error. */
1781 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1783 ERR("Relay didn't receive valid end data_pending struct size: %d",
1787 goto end_no_session
;
1790 session_id
= be64toh(msg
.session_id
);
1793 * Iterate over all streams to see if the begin data pending
1797 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1799 if (!stream_get(stream
)) {
1802 if (stream
->trace
->session
->id
!= session_id
) {
1806 pthread_mutex_lock(&stream
->lock
);
1807 if (!stream
->data_pending_check_done
) {
1808 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1809 is_data_inflight
= 1;
1810 DBG("Data is still in flight for stream %" PRIu64
,
1811 stream
->stream_handle
);
1812 pthread_mutex_unlock(&stream
->lock
);
1817 pthread_mutex_unlock(&stream
->lock
);
1822 memset(&reply
, 0, sizeof(reply
));
1823 /* All good, send back reply. */
1824 reply
.ret_code
= htobe32(is_data_inflight
);
1826 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1828 ERR("Relay end data pending send reply failed");
1836 * Receive an index for a specific stream.
1838 * Return 0 on success else a negative value.
1840 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1841 struct relay_connection
*conn
)
1844 struct relay_session
*session
= conn
->session
;
1845 struct lttcomm_relayd_index index_info
;
1846 struct relay_index
*index
;
1847 struct lttcomm_relayd_generic_reply reply
;
1848 struct relay_stream
*stream
;
1849 uint64_t net_seq_num
;
1853 DBG("Relay receiving index");
1855 if (!session
|| conn
->version_check_done
== 0) {
1856 ERR("Trying to close a stream before version check");
1858 goto end_no_session
;
1861 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1862 sizeof(index_info
), 0);
1863 if (ret
< sizeof(index_info
)) {
1865 /* Orderly shutdown. Not necessary to print an error. */
1866 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1868 ERR("Relay didn't receive valid index struct size : %d", ret
);
1871 goto end_no_session
;
1874 net_seq_num
= be64toh(index_info
.net_seq_num
);
1876 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1878 ERR("stream_get_by_id not found");
1882 pthread_mutex_lock(&stream
->lock
);
1884 /* Live beacon handling */
1885 if (index_info
.packet_size
== 0) {
1886 DBG("Received live beacon for stream %" PRIu64
,
1887 stream
->stream_handle
);
1890 * Only flag a stream inactive when it has already
1891 * received data and no indexes are in flight.
1893 if (stream
->total_index_received
> 0
1894 && stream
->indexes_in_flight
== 0) {
1895 stream
->beacon_ts_end
=
1896 be64toh(index_info
.timestamp_end
);
1899 goto end_stream_put
;
1901 stream
->beacon_ts_end
= -1ULL;
1904 if (stream
->ctf_stream_id
== -1ULL) {
1905 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1907 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1910 ERR("relay_index_get_by_id_or_create index NULL");
1911 goto end_stream_put
;
1913 if (set_index_control_data(index
, &index_info
)) {
1914 ERR("set_index_control_data error");
1915 relay_index_put(index
);
1917 goto end_stream_put
;
1919 ret
= relay_index_try_flush(index
);
1921 stream
->total_index_received
++;
1922 } else if (ret
> 0) {
1926 ERR("relay_index_try_flush error %d", ret
);
1927 relay_index_put(index
);
1932 pthread_mutex_unlock(&stream
->lock
);
1937 memset(&reply
, 0, sizeof(reply
));
1939 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1941 reply
.ret_code
= htobe32(LTTNG_OK
);
1943 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1945 ERR("Relay sending close index id reply");
1954 * Receive the streams_sent message.
1956 * Return 0 on success else a negative value.
1958 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1959 struct relay_connection
*conn
)
1962 struct lttcomm_relayd_generic_reply reply
;
1966 DBG("Relay receiving streams_sent");
1968 if (!conn
->session
|| conn
->version_check_done
== 0) {
1969 ERR("Trying to close a stream before version check");
1971 goto end_no_session
;
1975 * Publish every pending stream in the connection recv list which are
1976 * now ready to be used by the viewer.
1978 publish_connection_local_streams(conn
);
1980 memset(&reply
, 0, sizeof(reply
));
1981 reply
.ret_code
= htobe32(LTTNG_OK
);
1982 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1984 ERR("Relay sending sent_stream reply");
1996 * Process the commands received on the control socket
1998 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1999 struct relay_connection
*conn
)
2003 switch (be32toh(recv_hdr
->cmd
)) {
2004 case RELAYD_CREATE_SESSION
:
2005 ret
= relay_create_session(recv_hdr
, conn
);
2007 case RELAYD_ADD_STREAM
:
2008 ret
= relay_add_stream(recv_hdr
, conn
);
2010 case RELAYD_START_DATA
:
2011 ret
= relay_start(recv_hdr
, conn
);
2013 case RELAYD_SEND_METADATA
:
2014 ret
= relay_recv_metadata(recv_hdr
, conn
);
2016 case RELAYD_VERSION
:
2017 ret
= relay_send_version(recv_hdr
, conn
);
2019 case RELAYD_CLOSE_STREAM
:
2020 ret
= relay_close_stream(recv_hdr
, conn
);
2022 case RELAYD_DATA_PENDING
:
2023 ret
= relay_data_pending(recv_hdr
, conn
);
2025 case RELAYD_QUIESCENT_CONTROL
:
2026 ret
= relay_quiescent_control(recv_hdr
, conn
);
2028 case RELAYD_BEGIN_DATA_PENDING
:
2029 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2031 case RELAYD_END_DATA_PENDING
:
2032 ret
= relay_end_data_pending(recv_hdr
, conn
);
2034 case RELAYD_SEND_INDEX
:
2035 ret
= relay_recv_index(recv_hdr
, conn
);
2037 case RELAYD_STREAMS_SENT
:
2038 ret
= relay_streams_sent(recv_hdr
, conn
);
2040 case RELAYD_UPDATE_SYNC_INFO
:
2042 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2043 relay_unknown_command(conn
);
2053 * Handle index for a data stream.
2055 * Called with the stream lock held.
2057 * Return 0 on success else a negative value.
2059 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2063 uint64_t data_offset
;
2064 struct relay_index
*index
;
2066 /* Get data offset because we are about to update the index. */
2067 data_offset
= htobe64(stream
->tracefile_size_current
);
2069 DBG("handle_index_data: stream %" PRIu64
" data offset %" PRIu64
,
2070 stream
->stream_handle
, stream
->tracefile_size_current
);
2073 * Lookup for an existing index for that stream id/sequence
2074 * number. If it exists, the control thread has already received the
2075 * data for it, thus we need to write it to disk.
2077 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2083 if (rotate_index
|| !stream
->index_fd
) {
2086 /* Put ref on previous index_fd. */
2087 if (stream
->index_fd
) {
2088 stream_fd_put(stream
->index_fd
);
2089 stream
->index_fd
= NULL
;
2092 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2093 -1, -1, stream
->tracefile_size
,
2094 stream
->current_tracefile_id
);
2097 /* Put self-ref for this index due to error. */
2098 relay_index_put(index
);
2101 stream
->index_fd
= stream_fd_create(fd
);
2102 if (!stream
->index_fd
) {
2105 PERROR("Error closing FD %d", fd
);
2107 /* Put self-ref for this index due to error. */
2108 relay_index_put(index
);
2109 /* Will put the local ref. */
2114 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2116 /* Put self-ref for this index due to error. */
2117 relay_index_put(index
);
2121 ret
= relay_index_try_flush(index
);
2123 stream
->total_index_received
++;
2124 } else if (ret
> 0) {
2128 /* Put self-ref for this index due to error. */
2129 relay_index_put(index
);
2137 * relay_process_data: Process the data received on the data socket
2139 static int relay_process_data(struct relay_connection
*conn
)
2141 int ret
= 0, rotate_index
= 0;
2143 struct relay_stream
*stream
;
2144 struct lttcomm_relayd_data_hdr data_hdr
;
2146 uint64_t net_seq_num
;
2148 struct relay_session
*session
;
2149 bool new_stream
= false;
2151 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2152 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2155 /* Orderly shutdown. Not necessary to print an error. */
2156 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2158 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2164 stream_id
= be64toh(data_hdr
.stream_id
);
2165 stream
= stream_get_by_id(stream_id
);
2170 session
= stream
->trace
->session
;
2171 data_size
= be32toh(data_hdr
.data_size
);
2172 if (data_buffer_size
< data_size
) {
2175 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2176 if (!tmp_data_ptr
) {
2177 ERR("Allocating data buffer");
2180 goto end_stream_put
;
2182 data_buffer
= tmp_data_ptr
;
2183 data_buffer_size
= data_size
;
2185 memset(data_buffer
, 0, data_size
);
2187 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2189 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2190 data_size
, stream_id
, net_seq_num
);
2191 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2194 /* Orderly shutdown. Not necessary to print an error. */
2195 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2198 goto end_stream_put
;
2201 pthread_mutex_lock(&stream
->lock
);
2203 /* Check if a rotation is needed. */
2204 if (stream
->tracefile_size
> 0 &&
2205 (stream
->tracefile_size_current
+ data_size
) >
2206 stream
->tracefile_size
) {
2209 new_id
= (stream
->current_tracefile_id
+ 1) %
2210 stream
->tracefile_count
;
2212 * Move viewer oldest available data position forward if
2213 * we are overwriting a tracefile.
2215 if (new_id
== stream
->oldest_tracefile_id
) {
2216 stream
->oldest_tracefile_id
=
2217 (stream
->oldest_tracefile_id
+ 1) %
2218 stream
->tracefile_count
;
2220 ret
= utils_rotate_stream_file(stream
->path_name
,
2221 stream
->channel_name
, stream
->tracefile_size
,
2222 stream
->tracefile_count
, -1,
2223 -1, stream
->stream_fd
->fd
,
2224 &stream
->current_tracefile_id
,
2225 &stream
->stream_fd
->fd
);
2227 ERR("Rotating stream output file");
2228 goto end_stream_unlock
;
2230 stream
->current_tracefile_seq
++;
2231 if (stream
->current_tracefile_seq
2232 - stream
->oldest_tracefile_seq
>=
2233 stream
->tracefile_count
) {
2234 stream
->oldest_tracefile_seq
++;
2237 * Reset current size because we just performed a stream
2240 stream
->tracefile_size_current
= 0;
2245 * Index are handled in protocol version 2.4 and above. Also,
2246 * snapshot and index are NOT supported.
2248 if (session
->minor
>= 4 && !session
->snapshot
) {
2249 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2251 goto end_stream_unlock
;
2255 /* Write data to stream output fd. */
2256 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2257 if (size_ret
< data_size
) {
2258 ERR("Relay error writing data to file");
2260 goto end_stream_unlock
;
2263 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2264 size_ret
, stream
->stream_handle
);
2266 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2267 be32toh(data_hdr
.padding_size
));
2269 goto end_stream_unlock
;
2271 stream
->tracefile_size_current
+=
2272 data_size
+ be32toh(data_hdr
.padding_size
);
2273 if (stream
->prev_seq
== -1ULL) {
2277 stream
->prev_seq
= net_seq_num
;
2280 pthread_mutex_unlock(&stream
->lock
);
2282 pthread_mutex_lock(&session
->lock
);
2283 uatomic_set(&session
->new_streams
, 1);
2284 pthread_mutex_unlock(&session
->lock
);
2292 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2296 (void) lttng_poll_del(events
, pollfd
);
2298 ret
= close(pollfd
);
2300 ERR("Closing pollfd %d", pollfd
);
2304 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2305 int pollfd
, struct relay_connection
*conn
)
2307 const char *type_str
;
2309 switch (conn
->type
) {
2314 type_str
= "Control";
2316 case RELAY_VIEWER_COMMAND
:
2317 type_str
= "Viewer Command";
2319 case RELAY_VIEWER_NOTIFICATION
:
2320 type_str
= "Viewer Notification";
2323 type_str
= "Unknown";
2325 cleanup_connection_pollfd(events
, pollfd
);
2326 connection_put(conn
);
2327 DBG("%s connection closed with %d", type_str
, pollfd
);
2331 * This thread does the actual work
2333 static void *relay_thread_worker(void *data
)
2335 int ret
, err
= -1, last_seen_data_fd
= -1;
2337 struct lttng_poll_event events
;
2338 struct lttng_ht
*relay_connections_ht
;
2339 struct lttng_ht_iter iter
;
2340 struct lttcomm_relayd_hdr recv_hdr
;
2341 struct relay_connection
*destroy_conn
= NULL
;
2343 DBG("[thread] Relay worker started");
2345 rcu_register_thread();
2347 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2349 if (testpoint(relayd_thread_worker
)) {
2350 goto error_testpoint
;
2353 health_code_update();
2355 /* table of connections indexed on socket */
2356 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2357 if (!relay_connections_ht
) {
2358 goto relay_connections_ht_error
;
2361 ret
= create_thread_poll_set(&events
, 2);
2363 goto error_poll_create
;
2366 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2373 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2375 health_code_update();
2377 /* Infinite blocking call, waiting for transmission */
2378 DBG3("Relayd worker thread polling...");
2379 health_poll_entry();
2380 ret
= lttng_poll_wait(&events
, -1);
2384 * Restart interrupted system call.
2386 if (errno
== EINTR
) {
2395 * Process control. The control connection is
2396 * prioritized so we don't starve it with high
2397 * throughput tracing data on the data connection.
2399 for (i
= 0; i
< nb_fd
; i
++) {
2400 /* Fetch once the poll data */
2401 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2402 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2404 health_code_update();
2408 * No activity for this FD (poll
2414 /* Thread quit pipe has been closed. Killing thread. */
2415 ret
= check_thread_quit_pipe(pollfd
, revents
);
2421 /* Inspect the relay conn pipe for new connection */
2422 if (pollfd
== relay_conn_pipe
[0]) {
2423 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2424 ERR("Relay connection pipe error");
2426 } else if (revents
& LPOLLIN
) {
2427 struct relay_connection
*conn
;
2429 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2433 lttng_poll_add(&events
, conn
->sock
->fd
,
2434 LPOLLIN
| LPOLLRDHUP
);
2435 connection_ht_add(relay_connections_ht
, conn
);
2436 DBG("Connection socket %d added", conn
->sock
->fd
);
2439 struct relay_connection
*ctrl_conn
;
2441 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2442 /* If not found, there is a synchronization issue. */
2445 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2446 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
2447 if (last_seen_data_fd
== pollfd
) {
2448 last_seen_data_fd
= last_notdel_data_fd
;
2450 } else if (revents
& LPOLLIN
) {
2451 if (ctrl_conn
->type
== RELAY_CONTROL
) {
2452 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
, &recv_hdr
,
2453 sizeof(recv_hdr
), 0);
2455 /* Connection closed */
2456 relay_thread_close_connection(&events
, pollfd
,
2459 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2461 /* Clear the session on error. */
2462 relay_thread_close_connection(&events
, pollfd
,
2469 * Flag the last seen data fd not deleted. It will be
2470 * used as the last seen fd if any fd gets deleted in
2473 last_notdel_data_fd
= pollfd
;
2476 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
2478 connection_put(ctrl_conn
);
2483 * The last loop handled a control request, go back to poll to make
2484 * sure we prioritise the control socket.
2490 if (last_seen_data_fd
>= 0) {
2491 for (i
= 0; i
< nb_fd
; i
++) {
2492 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2494 health_code_update();
2496 if (last_seen_data_fd
== pollfd
) {
2503 /* Process data connection. */
2504 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2505 /* Fetch the poll data. */
2506 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2507 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2508 struct relay_connection
*data_conn
;
2510 health_code_update();
2513 /* No activity for this FD (poll implementation). */
2517 /* Skip the command pipe. It's handled in the first loop. */
2518 if (pollfd
== relay_conn_pipe
[0]) {
2522 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2524 /* Skip it. Might be removed before. */
2528 if (revents
& LPOLLIN
) {
2529 if (data_conn
->type
!= RELAY_DATA
) {
2530 goto put_connection
;
2533 ret
= relay_process_data(data_conn
);
2534 /* Connection closed */
2536 relay_thread_close_connection(&events
, pollfd
,
2539 * Every goto restart call sets the last seen fd where
2540 * here we don't really care since we gracefully
2541 * continue the loop after the connection is deleted.
2544 /* Keep last seen port. */
2545 last_seen_data_fd
= pollfd
;
2546 connection_put(data_conn
);
2551 connection_put(data_conn
);
2553 last_seen_data_fd
= -1;
2556 /* Normal exit, no error */
2561 /* Cleanup reamaining connection object. */
2563 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2566 health_code_update();
2568 * No need to grab another ref, because we own
2571 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2576 lttng_poll_clean(&events
);
2578 lttng_ht_destroy(relay_connections_ht
);
2579 relay_connections_ht_error
:
2580 /* Close relay conn pipes */
2581 utils_close_pipe(relay_conn_pipe
);
2583 DBG("Thread exited with error");
2585 DBG("Worker thread cleanup complete");
2590 ERR("Health error occurred in %s", __func__
);
2592 health_unregister(health_relayd
);
2593 rcu_unregister_thread();
2594 lttng_relay_stop_threads();
2599 * Create the relay command pipe to wake thread_manage_apps.
2600 * Closed in cleanup().
2602 static int create_relay_conn_pipe(void)
2606 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2614 int main(int argc
, char **argv
)
2616 int ret
= 0, retval
= 0;
2619 /* Parse arguments */
2621 if (set_options(argc
, argv
)) {
2626 if (set_signal_handler()) {
2631 /* Try to create directory if -o, --output is specified. */
2632 if (opt_output_path
) {
2633 if (*opt_output_path
!= '/') {
2634 ERR("Please specify an absolute path for -o, --output PATH");
2639 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2642 ERR("Unable to create %s", opt_output_path
);
2649 if (opt_daemon
|| opt_background
) {
2652 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2660 * We are in the child. Make sure all other file
2661 * descriptors are closed, in case we are called with
2662 * more opened file descriptors than the standard ones.
2664 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2670 /* Initialize thread health monitoring */
2671 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2672 if (!health_relayd
) {
2673 PERROR("health_app_create error");
2675 goto exit_health_app_create
;
2678 /* Create thread quit pipe */
2679 if (init_thread_quit_pipe()) {
2681 goto exit_init_data
;
2684 /* Check if daemon is UID = 0 */
2686 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2687 ERR("Need to be root to use ports < 1024");
2689 goto exit_init_data
;
2693 /* Setup the thread apps communication pipe. */
2694 if (create_relay_conn_pipe()) {
2696 goto exit_init_data
;
2699 /* Init relay command queue. */
2700 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2702 /* Set up max poll set size */
2703 if (lttng_poll_set_max_size()) {
2705 goto exit_init_data
;
2708 /* Initialize communication library */
2710 lttcomm_inet_init();
2712 /* tables of sessions indexed by session ID */
2713 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2716 goto exit_init_data
;
2719 /* tables of streams indexed by stream ID */
2720 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2721 if (!relay_streams_ht
) {
2723 goto exit_init_data
;
2726 /* tables of streams indexed by stream ID */
2727 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2728 if (!viewer_streams_ht
) {
2730 goto exit_init_data
;
2733 ret
= utils_create_pipe(health_quit_pipe
);
2736 goto exit_health_quit_pipe
;
2739 /* Create thread to manage the client socket */
2740 ret
= pthread_create(&health_thread
, NULL
,
2741 thread_manage_health
, (void *) NULL
);
2744 PERROR("pthread_create health");
2746 goto exit_health_thread
;
2749 /* Setup the dispatcher thread */
2750 ret
= pthread_create(&dispatcher_thread
, NULL
,
2751 relay_thread_dispatcher
, (void *) NULL
);
2754 PERROR("pthread_create dispatcher");
2756 goto exit_dispatcher_thread
;
2759 /* Setup the worker thread */
2760 ret
= pthread_create(&worker_thread
, NULL
,
2761 relay_thread_worker
, NULL
);
2764 PERROR("pthread_create worker");
2766 goto exit_worker_thread
;
2769 /* Setup the listener thread */
2770 ret
= pthread_create(&listener_thread
, NULL
,
2771 relay_thread_listener
, (void *) NULL
);
2774 PERROR("pthread_create listener");
2776 goto exit_listener_thread
;
2779 ret
= relayd_live_create(live_uri
);
2781 ERR("Starting live viewer threads");
2787 * This is where we start awaiting program completion (e.g. through
2788 * signal that asks threads to teardown).
2791 ret
= relayd_live_join();
2797 ret
= pthread_join(listener_thread
, &status
);
2800 PERROR("pthread_join listener_thread");
2804 exit_listener_thread
:
2805 ret
= pthread_join(worker_thread
, &status
);
2808 PERROR("pthread_join worker_thread");
2813 ret
= pthread_join(dispatcher_thread
, &status
);
2816 PERROR("pthread_join dispatcher_thread");
2819 exit_dispatcher_thread
:
2821 ret
= pthread_join(health_thread
, &status
);
2824 PERROR("pthread_join health_thread");
2829 utils_close_pipe(health_quit_pipe
);
2830 exit_health_quit_pipe
:
2833 health_app_destroy(health_relayd
);
2834 exit_health_app_create
:
2838 /* Ensure all prior call_rcu are done. */