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"
74 #include "tracefile-array.h"
76 /* command line options */
77 char *opt_output_path
;
78 static int opt_daemon
, opt_background
;
81 * We need to wait for listener and live listener threads, as well as
82 * health check thread, before being ready to signal readiness.
84 #define NR_LTTNG_RELAY_READY 3
85 static int lttng_relay_ready
= NR_LTTNG_RELAY_READY
;
87 /* Size of receive buffer. */
88 #define RECV_DATA_BUFFER_SIZE 65536
90 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
91 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
93 static struct lttng_uri
*control_uri
;
94 static struct lttng_uri
*data_uri
;
95 static struct lttng_uri
*live_uri
;
99 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
100 static int tracing_group_name_override
;
102 const char * const config_section_name
= "relayd";
105 * Quit pipe for all threads. This permits a single cancellation point
106 * for all threads when receiving an event on the pipe.
108 int thread_quit_pipe
[2] = { -1, -1 };
111 * This pipe is used to inform the worker thread that a command is queued and
112 * ready to be processed.
114 static int relay_conn_pipe
[2] = { -1, -1 };
116 /* Shared between threads */
117 static int dispatch_thread_exit
;
119 static pthread_t listener_thread
;
120 static pthread_t dispatcher_thread
;
121 static pthread_t worker_thread
;
122 static pthread_t health_thread
;
125 * last_relay_stream_id_lock protects last_relay_stream_id increment
126 * atomicity on 32-bit architectures.
128 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
129 static uint64_t last_relay_stream_id
;
132 * Relay command queue.
134 * The relay_thread_listener and relay_thread_dispatcher communicate with this
137 static struct relay_conn_queue relay_conn_queue
;
139 /* buffer allocated at startup, used to store the trace data */
140 static char *data_buffer
;
141 static unsigned int data_buffer_size
;
143 /* Global relay stream hash table. */
144 struct lttng_ht
*relay_streams_ht
;
146 /* Global relay viewer stream hash table. */
147 struct lttng_ht
*viewer_streams_ht
;
149 /* Global relay sessions hash table. */
150 struct lttng_ht
*sessions_ht
;
152 /* Relayd health monitoring */
153 struct health_app
*health_relayd
;
155 static struct option long_options
[] = {
156 { "control-port", 1, 0, 'C', },
157 { "data-port", 1, 0, 'D', },
158 { "live-port", 1, 0, 'L', },
159 { "daemonize", 0, 0, 'd', },
160 { "background", 0, 0, 'b', },
161 { "group", 1, 0, 'g', },
162 { "help", 0, 0, 'h', },
163 { "output", 1, 0, 'o', },
164 { "verbose", 0, 0, 'v', },
165 { "config", 1, 0, 'f' },
169 static const char *config_ignore_options
[] = { "help", "config" };
172 * usage function on stderr
174 static void usage(void)
176 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
177 fprintf(stderr
, " -h, --help Display this usage.\n");
178 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
179 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
180 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
181 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
182 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
183 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
184 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
185 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
186 fprintf(stderr
, " -f --config Load daemon configuration file\n");
190 * Take an option from the getopt output and set it in the right variable to be
193 * Return 0 on success else a negative value.
195 static int set_option(int opt
, const char *arg
, const char *optname
)
201 fprintf(stderr
, "option %s", optname
);
203 fprintf(stderr
, " with arg %s\n", arg
);
207 if (lttng_is_setuid_setgid()) {
208 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
209 "-C, --control-port");
211 ret
= uri_parse(arg
, &control_uri
);
213 ERR("Invalid control URI specified");
216 if (control_uri
->port
== 0) {
217 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
222 if (lttng_is_setuid_setgid()) {
223 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
226 ret
= uri_parse(arg
, &data_uri
);
228 ERR("Invalid data URI specified");
231 if (data_uri
->port
== 0) {
232 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
237 if (lttng_is_setuid_setgid()) {
238 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
241 ret
= uri_parse(arg
, &live_uri
);
243 ERR("Invalid live URI specified");
246 if (live_uri
->port
== 0) {
247 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
258 if (lttng_is_setuid_setgid()) {
259 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
262 tracing_group_name
= strdup(arg
);
263 if (tracing_group_name
== NULL
) {
268 tracing_group_name_override
= 1;
275 if (lttng_is_setuid_setgid()) {
276 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
279 ret
= asprintf(&opt_output_path
, "%s", arg
);
282 PERROR("asprintf opt_output_path");
288 /* Verbose level can increase using multiple -v */
290 lttng_opt_verbose
= config_parse_value(arg
);
292 /* Only 3 level of verbosity (-vvv). */
293 if (lttng_opt_verbose
< 3) {
294 lttng_opt_verbose
+= 1;
299 /* Unknown option or other error.
300 * Error is printed by getopt, just return */
313 * config_entry_handler_cb used to handle options read from a config file.
314 * See config_entry_handler_cb comment in common/config/config.h for the
315 * return value conventions.
317 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
321 if (!entry
|| !entry
->name
|| !entry
->value
) {
326 /* Check if the option is to be ignored */
327 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
328 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
333 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
334 /* Ignore if entry name is not fully matched. */
335 if (strcmp(entry
->name
, long_options
[i
].name
)) {
340 * If the option takes no argument on the command line,
341 * we have to check if the value is "true". We support
342 * non-zero numeric values, true, on and yes.
344 if (!long_options
[i
].has_arg
) {
345 ret
= config_parse_value(entry
->value
);
348 WARN("Invalid configuration value \"%s\" for option %s",
349 entry
->value
, entry
->name
);
351 /* False, skip boolean config option. */
356 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
360 WARN("Unrecognized option \"%s\" in daemon configuration file.",
367 static int set_options(int argc
, char **argv
)
369 int c
, ret
= 0, option_index
= 0, retval
= 0;
370 int orig_optopt
= optopt
, orig_optind
= optind
;
371 char *default_address
, *optstring
;
372 const char *config_path
= NULL
;
374 optstring
= utils_generate_optstring(long_options
,
375 sizeof(long_options
) / sizeof(struct option
));
381 /* Check for the --config option */
383 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
384 &option_index
)) != -1) {
388 } else if (c
!= 'f') {
392 if (lttng_is_setuid_setgid()) {
393 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
396 config_path
= utils_expand_path(optarg
);
398 ERR("Failed to resolve path: %s", optarg
);
403 ret
= config_get_section_entries(config_path
, config_section_name
,
404 config_entry_handler
, NULL
);
407 ERR("Invalid configuration option at line %i", ret
);
413 /* Reset getopt's global state */
414 optopt
= orig_optopt
;
415 optind
= orig_optind
;
417 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
422 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
429 /* assign default values */
430 if (control_uri
== NULL
) {
431 ret
= asprintf(&default_address
,
432 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
433 DEFAULT_NETWORK_CONTROL_PORT
);
435 PERROR("asprintf default data address");
440 ret
= uri_parse(default_address
, &control_uri
);
441 free(default_address
);
443 ERR("Invalid control URI specified");
448 if (data_uri
== NULL
) {
449 ret
= asprintf(&default_address
,
450 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
451 DEFAULT_NETWORK_DATA_PORT
);
453 PERROR("asprintf default data address");
458 ret
= uri_parse(default_address
, &data_uri
);
459 free(default_address
);
461 ERR("Invalid data URI specified");
466 if (live_uri
== NULL
) {
467 ret
= asprintf(&default_address
,
468 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
469 DEFAULT_NETWORK_VIEWER_PORT
);
471 PERROR("asprintf default viewer control address");
476 ret
= uri_parse(default_address
, &live_uri
);
477 free(default_address
);
479 ERR("Invalid viewer control URI specified");
490 static void print_global_objects(void)
492 rcu_register_thread();
494 print_viewer_streams();
495 print_relay_streams();
498 rcu_unregister_thread();
504 static void relayd_cleanup(void)
506 print_global_objects();
510 if (viewer_streams_ht
)
511 lttng_ht_destroy(viewer_streams_ht
);
512 if (relay_streams_ht
)
513 lttng_ht_destroy(relay_streams_ht
);
515 lttng_ht_destroy(sessions_ht
);
517 /* free the dynamically allocated opt_output_path */
518 free(opt_output_path
);
520 /* Close thread quit pipes */
521 utils_close_pipe(thread_quit_pipe
);
523 uri_free(control_uri
);
525 /* Live URI is freed in the live thread. */
527 if (tracing_group_name_override
) {
528 free((void *) tracing_group_name
);
533 * Write to writable pipe used to notify a thread.
535 static int notify_thread_pipe(int wpipe
)
539 ret
= lttng_write(wpipe
, "!", 1);
541 PERROR("write poll pipe");
549 static int notify_health_quit_pipe(int *pipe
)
553 ret
= lttng_write(pipe
[1], "4", 1);
555 PERROR("write relay health quit");
564 * Stop all relayd and relayd-live threads.
566 int lttng_relay_stop_threads(void)
570 /* Stopping all threads */
571 DBG("Terminating all threads");
572 if (notify_thread_pipe(thread_quit_pipe
[1])) {
573 ERR("write error on thread quit pipe");
577 if (notify_health_quit_pipe(health_quit_pipe
)) {
578 ERR("write error on health quit pipe");
581 /* Dispatch thread */
582 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
583 futex_nto1_wake(&relay_conn_queue
.futex
);
585 if (relayd_live_stop()) {
586 ERR("Error stopping live threads");
593 * Signal handler for the daemon
595 * Simply stop all worker threads, leaving main() return gracefully after
596 * joining all threads and calling cleanup().
598 static void sighandler(int sig
)
602 DBG("SIGPIPE caught");
605 DBG("SIGINT caught");
606 if (lttng_relay_stop_threads()) {
607 ERR("Error stopping threads");
611 DBG("SIGTERM caught");
612 if (lttng_relay_stop_threads()) {
613 ERR("Error stopping threads");
617 CMM_STORE_SHARED(recv_child_signal
, 1);
625 * Setup signal handler for :
626 * SIGINT, SIGTERM, SIGPIPE
628 static int set_signal_handler(void)
634 if ((ret
= sigemptyset(&sigset
)) < 0) {
635 PERROR("sigemptyset");
639 sa
.sa_handler
= sighandler
;
642 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
647 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
652 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
657 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
662 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
667 void lttng_relay_notify_ready(void)
669 /* Notify the parent of the fork() process that we are ready. */
670 if (opt_daemon
|| opt_background
) {
671 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
672 kill(child_ppid
, SIGUSR1
);
678 * Init thread quit pipe.
680 * Return -1 on error or 0 if all pipes are created.
682 static int init_thread_quit_pipe(void)
686 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
692 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
694 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
698 if (events
== NULL
|| size
== 0) {
703 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
709 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
721 * Check if the thread quit pipe was triggered.
723 * Return 1 if it was triggered else 0;
725 static int check_thread_quit_pipe(int fd
, uint32_t events
)
727 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
735 * Create and init socket from uri.
737 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
740 struct lttcomm_sock
*sock
= NULL
;
742 sock
= lttcomm_alloc_sock_from_uri(uri
);
744 ERR("Allocating socket");
748 ret
= lttcomm_create_sock(sock
);
752 DBG("Listening on sock %d", sock
->fd
);
754 ret
= sock
->ops
->bind(sock
);
759 ret
= sock
->ops
->listen(sock
, -1);
769 lttcomm_destroy_sock(sock
);
775 * This thread manages the listening for new connections on the network
777 static void *relay_thread_listener(void *data
)
779 int i
, ret
, pollfd
, err
= -1;
780 uint32_t revents
, nb_fd
;
781 struct lttng_poll_event events
;
782 struct lttcomm_sock
*control_sock
, *data_sock
;
784 DBG("[thread] Relay listener started");
786 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
788 health_code_update();
790 control_sock
= relay_socket_create(control_uri
);
792 goto error_sock_control
;
795 data_sock
= relay_socket_create(data_uri
);
797 goto error_sock_relay
;
801 * Pass 3 as size here for the thread quit pipe, control and
804 ret
= create_thread_poll_set(&events
, 3);
806 goto error_create_poll
;
809 /* Add the control socket */
810 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
815 /* Add the data socket */
816 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
821 lttng_relay_notify_ready();
823 if (testpoint(relayd_thread_listener
)) {
824 goto error_testpoint
;
828 health_code_update();
830 DBG("Listener accepting connections");
834 ret
= lttng_poll_wait(&events
, -1);
838 * Restart interrupted system call.
840 if (errno
== EINTR
) {
848 DBG("Relay new connection received");
849 for (i
= 0; i
< nb_fd
; i
++) {
850 health_code_update();
852 /* Fetch once the poll data */
853 revents
= LTTNG_POLL_GETEV(&events
, i
);
854 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
858 * No activity for this FD (poll
864 /* Thread quit pipe has been closed. Killing thread. */
865 ret
= check_thread_quit_pipe(pollfd
, revents
);
871 if (revents
& LPOLLIN
) {
873 * A new connection is requested, therefore a
874 * sessiond/consumerd connection is allocated in
875 * this thread, enqueued to a global queue and
876 * dequeued (and freed) in the worker thread.
879 struct relay_connection
*new_conn
;
880 struct lttcomm_sock
*newsock
;
881 enum connection_type type
;
883 if (pollfd
== data_sock
->fd
) {
885 newsock
= data_sock
->ops
->accept(data_sock
);
886 DBG("Relay data connection accepted, socket %d",
889 assert(pollfd
== control_sock
->fd
);
890 type
= RELAY_CONTROL
;
891 newsock
= control_sock
->ops
->accept(control_sock
);
892 DBG("Relay control connection accepted, socket %d",
896 PERROR("accepting sock");
900 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
903 PERROR("setsockopt inet");
904 lttcomm_destroy_sock(newsock
);
907 new_conn
= connection_create(newsock
, type
);
909 lttcomm_destroy_sock(newsock
);
913 /* Enqueue request for the dispatcher thread. */
914 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
918 * Wake the dispatch queue futex.
919 * Implicit memory barrier with the
920 * exchange in cds_wfcq_enqueue.
922 futex_nto1_wake(&relay_conn_queue
.futex
);
923 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
924 ERR("socket poll error");
927 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
937 lttng_poll_clean(&events
);
939 if (data_sock
->fd
>= 0) {
940 ret
= data_sock
->ops
->close(data_sock
);
945 lttcomm_destroy_sock(data_sock
);
947 if (control_sock
->fd
>= 0) {
948 ret
= control_sock
->ops
->close(control_sock
);
953 lttcomm_destroy_sock(control_sock
);
957 ERR("Health error occurred in %s", __func__
);
959 health_unregister(health_relayd
);
960 DBG("Relay listener thread cleanup complete");
961 lttng_relay_stop_threads();
966 * This thread manages the dispatching of the requests to worker threads
968 static void *relay_thread_dispatcher(void *data
)
972 struct cds_wfcq_node
*node
;
973 struct relay_connection
*new_conn
= NULL
;
975 DBG("[thread] Relay dispatcher started");
977 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
979 if (testpoint(relayd_thread_dispatcher
)) {
980 goto error_testpoint
;
983 health_code_update();
985 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
986 health_code_update();
988 /* Atomically prepare the queue futex */
989 futex_nto1_prepare(&relay_conn_queue
.futex
);
992 health_code_update();
994 /* Dequeue commands */
995 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
996 &relay_conn_queue
.tail
);
998 DBG("Woken up but nothing in the relay command queue");
999 /* Continue thread execution */
1002 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1004 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1007 * Inform worker thread of the new request. This
1008 * call is blocking so we can be assured that
1009 * the data will be read at some point in time
1010 * or wait to the end of the world :)
1012 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1014 PERROR("write connection pipe");
1015 connection_put(new_conn
);
1018 } while (node
!= NULL
);
1020 /* Futex wait on queue. Blocking call on futex() */
1021 health_poll_entry();
1022 futex_nto1_wait(&relay_conn_queue
.futex
);
1026 /* Normal exit, no error */
1033 ERR("Health error occurred in %s", __func__
);
1035 health_unregister(health_relayd
);
1036 DBG("Dispatch thread dying");
1037 lttng_relay_stop_threads();
1042 * Set index data from the control port to a given index object.
1044 static int set_index_control_data(struct relay_index
*index
,
1045 struct lttcomm_relayd_index
*data
)
1047 struct ctf_packet_index index_data
;
1050 * The index on disk is encoded in big endian, so we don't need
1051 * to convert the data received on the network. The data_offset
1052 * value is NEVER modified here and is updated by the data
1055 index_data
.packet_size
= data
->packet_size
;
1056 index_data
.content_size
= data
->content_size
;
1057 index_data
.timestamp_begin
= data
->timestamp_begin
;
1058 index_data
.timestamp_end
= data
->timestamp_end
;
1059 index_data
.events_discarded
= data
->events_discarded
;
1060 index_data
.stream_id
= data
->stream_id
;
1061 return relay_index_set_data(index
, &index_data
);
1065 * Handle the RELAYD_CREATE_SESSION command.
1067 * On success, send back the session id or else return a negative value.
1069 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1070 struct relay_connection
*conn
)
1072 int ret
= 0, send_ret
;
1073 struct relay_session
*session
;
1074 struct lttcomm_relayd_status_session reply
;
1075 char session_name
[NAME_MAX
];
1076 char hostname
[HOST_NAME_MAX
];
1077 uint32_t live_timer
= 0;
1078 bool snapshot
= false;
1080 memset(session_name
, 0, NAME_MAX
);
1081 memset(hostname
, 0, HOST_NAME_MAX
);
1083 memset(&reply
, 0, sizeof(reply
));
1085 switch (conn
->minor
) {
1090 case 4: /* LTTng sessiond 2.4 */
1092 ret
= cmd_create_session_2_4(conn
, session_name
,
1093 hostname
, &live_timer
, &snapshot
);
1099 session
= session_create(session_name
, hostname
, live_timer
,
1100 snapshot
, conn
->major
, conn
->minor
);
1105 assert(!conn
->session
);
1106 conn
->session
= session
;
1107 DBG("Created session %" PRIu64
, session
->id
);
1109 reply
.session_id
= htobe64(session
->id
);
1113 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1115 reply
.ret_code
= htobe32(LTTNG_OK
);
1118 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1120 ERR("Relayd sending session id");
1128 * When we have received all the streams and the metadata for a channel,
1129 * we make them visible to the viewer threads.
1131 static void publish_connection_local_streams(struct relay_connection
*conn
)
1133 struct relay_stream
*stream
;
1134 struct relay_session
*session
= conn
->session
;
1137 * We publish all streams belonging to a session atomically wrt
1140 pthread_mutex_lock(&session
->lock
);
1142 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1144 stream_publish(stream
);
1149 * Inform the viewer that there are new streams in the session.
1151 if (session
->viewer_attached
) {
1152 uatomic_set(&session
->new_streams
, 1);
1154 pthread_mutex_unlock(&session
->lock
);
1158 * relay_add_stream: allocate a new stream for a session
1160 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1161 struct relay_connection
*conn
)
1165 struct relay_session
*session
= conn
->session
;
1166 struct relay_stream
*stream
= NULL
;
1167 struct lttcomm_relayd_status_stream reply
;
1168 struct ctf_trace
*trace
= NULL
;
1169 uint64_t stream_handle
= -1ULL;
1170 char *path_name
= NULL
, *channel_name
= NULL
;
1171 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1173 if (!session
|| conn
->version_check_done
== 0) {
1174 ERR("Trying to add a stream before version check");
1176 goto end_no_session
;
1179 switch (session
->minor
) {
1180 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1181 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1184 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1186 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1187 &channel_name
, &tracefile_size
, &tracefile_count
);
1194 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1198 /* This stream here has one reference on the trace. */
1200 pthread_mutex_lock(&last_relay_stream_id_lock
);
1201 stream_handle
= ++last_relay_stream_id
;
1202 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1204 /* We pass ownership of path_name and channel_name. */
1205 stream
= stream_create(trace
, stream_handle
, path_name
,
1206 channel_name
, tracefile_size
, tracefile_count
);
1208 channel_name
= NULL
;
1211 * Streams are the owners of their trace. Reference to trace is
1212 * kept within stream_create().
1214 ctf_trace_put(trace
);
1217 memset(&reply
, 0, sizeof(reply
));
1218 reply
.handle
= htobe64(stream_handle
);
1220 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1222 reply
.ret_code
= htobe32(LTTNG_OK
);
1225 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1226 sizeof(struct lttcomm_relayd_status_stream
), 0);
1228 ERR("Relay sending stream id");
1229 ret
= (int) send_ret
;
1239 * relay_close_stream: close a specific stream
1241 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1242 struct relay_connection
*conn
)
1245 struct relay_session
*session
= conn
->session
;
1246 struct lttcomm_relayd_close_stream stream_info
;
1247 struct lttcomm_relayd_generic_reply reply
;
1248 struct relay_stream
*stream
;
1250 DBG("Close stream received");
1252 if (!session
|| conn
->version_check_done
== 0) {
1253 ERR("Trying to close a stream before version check");
1255 goto end_no_session
;
1258 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1259 sizeof(struct lttcomm_relayd_close_stream
), 0);
1260 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1262 /* Orderly shutdown. Not necessary to print an error. */
1263 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1265 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1268 goto end_no_session
;
1271 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1278 * Set last_net_seq_num before the close flag. Required by data
1281 pthread_mutex_lock(&stream
->lock
);
1282 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1283 pthread_mutex_unlock(&stream
->lock
);
1286 * This is one of the conditions which may trigger a stream close
1287 * with the others being:
1288 * 1) A close command is received for a stream
1289 * 2) The control connection owning the stream is closed
1290 * 3) We have received all of the stream's data _after_ a close
1293 try_stream_close(stream
);
1294 if (stream
->is_metadata
) {
1295 struct relay_viewer_stream
*vstream
;
1297 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1299 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1301 * Since all the metadata has been sent to the
1302 * viewer and that we have a request to close
1303 * its stream, we can safely teardown the
1304 * corresponding metadata viewer stream.
1306 viewer_stream_put(vstream
);
1308 /* Put local reference. */
1309 viewer_stream_put(vstream
);
1315 memset(&reply
, 0, sizeof(reply
));
1317 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1319 reply
.ret_code
= htobe32(LTTNG_OK
);
1321 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1322 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1324 ERR("Relay sending stream id");
1333 * relay_unknown_command: send -1 if received unknown command
1335 static void relay_unknown_command(struct relay_connection
*conn
)
1337 struct lttcomm_relayd_generic_reply reply
;
1340 memset(&reply
, 0, sizeof(reply
));
1341 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1342 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1343 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1345 ERR("Relay sending unknown command");
1350 * relay_start: send an acknowledgment to the client to tell if we are
1351 * ready to receive data. We are ready if a session is established.
1353 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1354 struct relay_connection
*conn
)
1356 int ret
= htobe32(LTTNG_OK
);
1357 struct lttcomm_relayd_generic_reply reply
;
1358 struct relay_session
*session
= conn
->session
;
1361 DBG("Trying to start the streaming without a session established");
1362 ret
= htobe32(LTTNG_ERR_UNK
);
1365 memset(&reply
, 0, sizeof(reply
));
1366 reply
.ret_code
= ret
;
1367 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1368 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1370 ERR("Relay sending start ack");
1377 * Append padding to the file pointed by the file descriptor fd.
1379 static int write_padding_to_file(int fd
, uint32_t size
)
1388 zeros
= zmalloc(size
);
1389 if (zeros
== NULL
) {
1390 PERROR("zmalloc zeros for padding");
1395 ret
= lttng_write(fd
, zeros
, size
);
1397 PERROR("write padding to file");
1407 * relay_recv_metadata: receive the metadata for the session.
1409 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1410 struct relay_connection
*conn
)
1414 struct relay_session
*session
= conn
->session
;
1415 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1416 struct relay_stream
*metadata_stream
;
1417 uint64_t data_size
, payload_size
;
1420 ERR("Metadata sent before version check");
1425 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1426 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1427 ERR("Incorrect data size");
1431 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1433 if (data_buffer_size
< data_size
) {
1434 /* In case the realloc fails, we can free the memory */
1437 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1438 if (!tmp_data_ptr
) {
1439 ERR("Allocating data buffer");
1444 data_buffer
= tmp_data_ptr
;
1445 data_buffer_size
= data_size
;
1447 memset(data_buffer
, 0, data_size
);
1448 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1449 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1450 if (size_ret
< 0 || size_ret
!= data_size
) {
1451 if (size_ret
== 0) {
1452 /* Orderly shutdown. Not necessary to print an error. */
1453 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1455 ERR("Relay didn't receive the whole metadata");
1460 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1462 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1463 if (!metadata_stream
) {
1468 pthread_mutex_lock(&metadata_stream
->lock
);
1470 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1472 if (size_ret
< payload_size
) {
1473 ERR("Relay error writing metadata on file");
1478 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1479 be32toh(metadata_struct
->padding_size
));
1484 metadata_stream
->metadata_received
+=
1485 payload_size
+ be32toh(metadata_struct
->padding_size
);
1486 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1487 metadata_stream
->metadata_received
);
1490 pthread_mutex_unlock(&metadata_stream
->lock
);
1491 stream_put(metadata_stream
);
1497 * relay_send_version: send relayd version number
1499 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1500 struct relay_connection
*conn
)
1503 struct lttcomm_relayd_version reply
, msg
;
1505 conn
->version_check_done
= 1;
1507 /* Get version from the other side. */
1508 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1509 if (ret
< 0 || ret
!= sizeof(msg
)) {
1511 /* Orderly shutdown. Not necessary to print an error. */
1512 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1514 ERR("Relay failed to receive the version values.");
1520 memset(&reply
, 0, sizeof(reply
));
1521 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1522 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1524 /* Major versions must be the same */
1525 if (reply
.major
!= be32toh(msg
.major
)) {
1526 DBG("Incompatible major versions (%u vs %u), deleting session",
1527 reply
.major
, be32toh(msg
.major
));
1528 connection_put(conn
);
1533 conn
->major
= reply
.major
;
1534 /* We adapt to the lowest compatible version */
1535 if (reply
.minor
<= be32toh(msg
.minor
)) {
1536 conn
->minor
= reply
.minor
;
1538 conn
->minor
= be32toh(msg
.minor
);
1541 reply
.major
= htobe32(reply
.major
);
1542 reply
.minor
= htobe32(reply
.minor
);
1543 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1544 sizeof(struct lttcomm_relayd_version
), 0);
1546 ERR("Relay sending version");
1549 DBG("Version check done using protocol %u.%u", conn
->major
,
1557 * Check for data pending for a given stream id from the session daemon.
1559 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1560 struct relay_connection
*conn
)
1562 struct relay_session
*session
= conn
->session
;
1563 struct lttcomm_relayd_data_pending msg
;
1564 struct lttcomm_relayd_generic_reply reply
;
1565 struct relay_stream
*stream
;
1567 uint64_t last_net_seq_num
, stream_id
;
1569 DBG("Data pending command received");
1571 if (!session
|| conn
->version_check_done
== 0) {
1572 ERR("Trying to check for data before version check");
1574 goto end_no_session
;
1577 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1578 if (ret
< sizeof(msg
)) {
1580 /* Orderly shutdown. Not necessary to print an error. */
1581 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1583 ERR("Relay didn't receive valid data_pending struct size : %d",
1587 goto end_no_session
;
1590 stream_id
= be64toh(msg
.stream_id
);
1591 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1593 stream
= stream_get_by_id(stream_id
);
1594 if (stream
== NULL
) {
1599 pthread_mutex_lock(&stream
->lock
);
1601 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1602 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1605 /* Avoid wrapping issue */
1606 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1607 /* Data has in fact been written and is NOT pending */
1610 /* Data still being streamed thus pending */
1614 stream
->data_pending_check_done
= true;
1615 pthread_mutex_unlock(&stream
->lock
);
1620 memset(&reply
, 0, sizeof(reply
));
1621 reply
.ret_code
= htobe32(ret
);
1622 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1624 ERR("Relay data pending ret code failed");
1632 * Wait for the control socket to reach a quiescent state.
1634 * Note that for now, when receiving this command from the session
1635 * daemon, this means that every subsequent commands or data received on
1636 * the control socket has been handled. So, this is why we simply return
1639 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1640 struct relay_connection
*conn
)
1644 struct relay_stream
*stream
;
1645 struct lttcomm_relayd_quiescent_control msg
;
1646 struct lttcomm_relayd_generic_reply reply
;
1648 DBG("Checking quiescent state on control socket");
1650 if (!conn
->session
|| conn
->version_check_done
== 0) {
1651 ERR("Trying to check for data before version check");
1653 goto end_no_session
;
1656 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1657 if (ret
< sizeof(msg
)) {
1659 /* Orderly shutdown. Not necessary to print an error. */
1660 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1662 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1666 goto end_no_session
;
1669 stream_id
= be64toh(msg
.stream_id
);
1670 stream
= stream_get_by_id(stream_id
);
1674 pthread_mutex_lock(&stream
->lock
);
1675 stream
->data_pending_check_done
= true;
1676 pthread_mutex_unlock(&stream
->lock
);
1677 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1680 memset(&reply
, 0, sizeof(reply
));
1681 reply
.ret_code
= htobe32(LTTNG_OK
);
1682 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1684 ERR("Relay data quiescent control ret code failed");
1692 * Initialize a data pending command. This means that a consumer is about
1693 * to ask for data pending for each stream it holds. Simply iterate over
1694 * all streams of a session and set the data_pending_check_done flag.
1696 * This command returns to the client a LTTNG_OK code.
1698 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1699 struct relay_connection
*conn
)
1702 struct lttng_ht_iter iter
;
1703 struct lttcomm_relayd_begin_data_pending msg
;
1704 struct lttcomm_relayd_generic_reply reply
;
1705 struct relay_stream
*stream
;
1706 uint64_t session_id
;
1711 DBG("Init streams for data pending");
1713 if (!conn
->session
|| conn
->version_check_done
== 0) {
1714 ERR("Trying to check for data before version check");
1716 goto end_no_session
;
1719 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1720 if (ret
< sizeof(msg
)) {
1722 /* Orderly shutdown. Not necessary to print an error. */
1723 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1725 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1729 goto end_no_session
;
1732 session_id
= be64toh(msg
.session_id
);
1735 * Iterate over all streams to set the begin data pending flag.
1736 * For now, the streams are indexed by stream handle so we have
1737 * to iterate over all streams to find the one associated with
1738 * the right session_id.
1741 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1743 if (!stream_get(stream
)) {
1746 if (stream
->trace
->session
->id
== session_id
) {
1747 pthread_mutex_lock(&stream
->lock
);
1748 stream
->data_pending_check_done
= false;
1749 pthread_mutex_unlock(&stream
->lock
);
1750 DBG("Set begin data pending flag to stream %" PRIu64
,
1751 stream
->stream_handle
);
1757 memset(&reply
, 0, sizeof(reply
));
1758 /* All good, send back reply. */
1759 reply
.ret_code
= htobe32(LTTNG_OK
);
1761 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1763 ERR("Relay begin data pending send reply failed");
1771 * End data pending command. This will check, for a given session id, if
1772 * each stream associated with it has its data_pending_check_done flag
1773 * set. If not, this means that the client lost track of the stream but
1774 * the data is still being streamed on our side. In this case, we inform
1775 * the client that data is in flight.
1777 * Return to the client if there is data in flight or not with a ret_code.
1779 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1780 struct relay_connection
*conn
)
1783 struct lttng_ht_iter iter
;
1784 struct lttcomm_relayd_end_data_pending msg
;
1785 struct lttcomm_relayd_generic_reply reply
;
1786 struct relay_stream
*stream
;
1787 uint64_t session_id
;
1788 uint32_t is_data_inflight
= 0;
1790 DBG("End data pending command");
1792 if (!conn
->session
|| conn
->version_check_done
== 0) {
1793 ERR("Trying to check for data before version check");
1795 goto end_no_session
;
1798 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1799 if (ret
< sizeof(msg
)) {
1801 /* Orderly shutdown. Not necessary to print an error. */
1802 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1804 ERR("Relay didn't receive valid end data_pending struct size: %d",
1808 goto end_no_session
;
1811 session_id
= be64toh(msg
.session_id
);
1814 * Iterate over all streams to see if the begin data pending
1818 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1820 if (!stream_get(stream
)) {
1823 if (stream
->trace
->session
->id
!= session_id
) {
1827 pthread_mutex_lock(&stream
->lock
);
1828 if (!stream
->data_pending_check_done
) {
1829 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1830 is_data_inflight
= 1;
1831 DBG("Data is still in flight for stream %" PRIu64
,
1832 stream
->stream_handle
);
1833 pthread_mutex_unlock(&stream
->lock
);
1838 pthread_mutex_unlock(&stream
->lock
);
1843 memset(&reply
, 0, sizeof(reply
));
1844 /* All good, send back reply. */
1845 reply
.ret_code
= htobe32(is_data_inflight
);
1847 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1849 ERR("Relay end data pending send reply failed");
1857 * Receive an index for a specific stream.
1859 * Return 0 on success else a negative value.
1861 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1862 struct relay_connection
*conn
)
1865 struct relay_session
*session
= conn
->session
;
1866 struct lttcomm_relayd_index index_info
;
1867 struct relay_index
*index
;
1868 struct lttcomm_relayd_generic_reply reply
;
1869 struct relay_stream
*stream
;
1870 uint64_t net_seq_num
;
1874 DBG("Relay receiving index");
1876 if (!session
|| conn
->version_check_done
== 0) {
1877 ERR("Trying to close a stream before version check");
1879 goto end_no_session
;
1882 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1883 sizeof(index_info
), 0);
1884 if (ret
< sizeof(index_info
)) {
1886 /* Orderly shutdown. Not necessary to print an error. */
1887 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1889 ERR("Relay didn't receive valid index struct size : %d", ret
);
1892 goto end_no_session
;
1895 net_seq_num
= be64toh(index_info
.net_seq_num
);
1897 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1899 ERR("stream_get_by_id not found");
1903 pthread_mutex_lock(&stream
->lock
);
1905 /* Live beacon handling */
1906 if (index_info
.packet_size
== 0) {
1907 DBG("Received live beacon for stream %" PRIu64
,
1908 stream
->stream_handle
);
1911 * Only flag a stream inactive when it has already
1912 * received data and no indexes are in flight.
1914 if (stream
->index_received_seqcount
> 0
1915 && stream
->indexes_in_flight
== 0) {
1916 stream
->beacon_ts_end
=
1917 be64toh(index_info
.timestamp_end
);
1920 goto end_stream_put
;
1922 stream
->beacon_ts_end
= -1ULL;
1925 if (stream
->ctf_stream_id
== -1ULL) {
1926 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1928 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1931 ERR("relay_index_get_by_id_or_create index NULL");
1932 goto end_stream_put
;
1934 if (set_index_control_data(index
, &index_info
)) {
1935 ERR("set_index_control_data error");
1936 relay_index_put(index
);
1938 goto end_stream_put
;
1940 ret
= relay_index_try_flush(index
);
1942 tracefile_array_commit_seq(stream
->tfa
);
1943 stream
->index_received_seqcount
++;
1944 } else if (ret
> 0) {
1948 ERR("relay_index_try_flush error %d", ret
);
1949 relay_index_put(index
);
1954 pthread_mutex_unlock(&stream
->lock
);
1959 memset(&reply
, 0, sizeof(reply
));
1961 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1963 reply
.ret_code
= htobe32(LTTNG_OK
);
1965 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1967 ERR("Relay sending close index id reply");
1976 * Receive the streams_sent message.
1978 * Return 0 on success else a negative value.
1980 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1981 struct relay_connection
*conn
)
1984 struct lttcomm_relayd_generic_reply reply
;
1988 DBG("Relay receiving streams_sent");
1990 if (!conn
->session
|| conn
->version_check_done
== 0) {
1991 ERR("Trying to close a stream before version check");
1993 goto end_no_session
;
1997 * Publish every pending stream in the connection recv list which are
1998 * now ready to be used by the viewer.
2000 publish_connection_local_streams(conn
);
2002 memset(&reply
, 0, sizeof(reply
));
2003 reply
.ret_code
= htobe32(LTTNG_OK
);
2004 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2006 ERR("Relay sending sent_stream reply");
2018 * Process the commands received on the control socket
2020 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2021 struct relay_connection
*conn
)
2025 switch (be32toh(recv_hdr
->cmd
)) {
2026 case RELAYD_CREATE_SESSION
:
2027 ret
= relay_create_session(recv_hdr
, conn
);
2029 case RELAYD_ADD_STREAM
:
2030 ret
= relay_add_stream(recv_hdr
, conn
);
2032 case RELAYD_START_DATA
:
2033 ret
= relay_start(recv_hdr
, conn
);
2035 case RELAYD_SEND_METADATA
:
2036 ret
= relay_recv_metadata(recv_hdr
, conn
);
2038 case RELAYD_VERSION
:
2039 ret
= relay_send_version(recv_hdr
, conn
);
2041 case RELAYD_CLOSE_STREAM
:
2042 ret
= relay_close_stream(recv_hdr
, conn
);
2044 case RELAYD_DATA_PENDING
:
2045 ret
= relay_data_pending(recv_hdr
, conn
);
2047 case RELAYD_QUIESCENT_CONTROL
:
2048 ret
= relay_quiescent_control(recv_hdr
, conn
);
2050 case RELAYD_BEGIN_DATA_PENDING
:
2051 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2053 case RELAYD_END_DATA_PENDING
:
2054 ret
= relay_end_data_pending(recv_hdr
, conn
);
2056 case RELAYD_SEND_INDEX
:
2057 ret
= relay_recv_index(recv_hdr
, conn
);
2059 case RELAYD_STREAMS_SENT
:
2060 ret
= relay_streams_sent(recv_hdr
, conn
);
2062 case RELAYD_UPDATE_SYNC_INFO
:
2064 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2065 relay_unknown_command(conn
);
2075 * Handle index for a data stream.
2077 * Called with the stream lock held.
2079 * Return 0 on success else a negative value.
2081 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2085 uint64_t data_offset
;
2086 struct relay_index
*index
;
2088 /* Get data offset because we are about to update the index. */
2089 data_offset
= htobe64(stream
->tracefile_size_current
);
2091 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2092 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2095 * Lookup for an existing index for that stream id/sequence
2096 * number. If it exists, the control thread has already received the
2097 * data for it, thus we need to write it to disk.
2099 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2105 if (rotate_index
|| !stream
->index_fd
) {
2108 /* Put ref on previous index_fd. */
2109 if (stream
->index_fd
) {
2110 stream_fd_put(stream
->index_fd
);
2111 stream
->index_fd
= NULL
;
2114 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2115 -1, -1, stream
->tracefile_size
,
2116 tracefile_array_get_file_index_head(stream
->tfa
));
2119 /* Put self-ref for this index due to error. */
2120 relay_index_put(index
);
2123 stream
->index_fd
= stream_fd_create(fd
);
2124 if (!stream
->index_fd
) {
2127 PERROR("Error closing FD %d", fd
);
2129 /* Put self-ref for this index due to error. */
2130 relay_index_put(index
);
2131 /* Will put the local ref. */
2136 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2138 /* Put self-ref for this index due to error. */
2139 relay_index_put(index
);
2143 ret
= relay_index_try_flush(index
);
2145 tracefile_array_commit_seq(stream
->tfa
);
2146 stream
->index_received_seqcount
++;
2147 } else if (ret
> 0) {
2151 /* Put self-ref for this index due to error. */
2152 relay_index_put(index
);
2160 * relay_process_data: Process the data received on the data socket
2162 static int relay_process_data(struct relay_connection
*conn
)
2164 int ret
= 0, rotate_index
= 0;
2166 struct relay_stream
*stream
;
2167 struct lttcomm_relayd_data_hdr data_hdr
;
2169 uint64_t net_seq_num
;
2171 struct relay_session
*session
;
2172 bool new_stream
= false, close_requested
= false;
2173 size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2174 size_t recv_off
= 0;
2175 char data_buffer
[chunk_size
];
2177 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2178 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2181 /* Orderly shutdown. Not necessary to print an error. */
2182 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2184 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2190 stream_id
= be64toh(data_hdr
.stream_id
);
2191 stream
= stream_get_by_id(stream_id
);
2193 ERR("relay_process_data: Cannot find stream %" PRIu64
, stream_id
);
2197 session
= stream
->trace
->session
;
2198 data_size
= be32toh(data_hdr
.data_size
);
2200 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2202 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2203 data_size
, stream_id
, net_seq_num
);
2205 pthread_mutex_lock(&stream
->lock
);
2207 /* Check if a rotation is needed. */
2208 if (stream
->tracefile_size
> 0 &&
2209 (stream
->tracefile_size_current
+ data_size
) >
2210 stream
->tracefile_size
) {
2211 uint64_t old_id
, new_id
;
2213 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2214 tracefile_array_file_rotate(stream
->tfa
);
2216 /* new_id is updated by utils_rotate_stream_file. */
2219 ret
= utils_rotate_stream_file(stream
->path_name
,
2220 stream
->channel_name
, stream
->tracefile_size
,
2221 stream
->tracefile_count
, -1,
2222 -1, stream
->stream_fd
->fd
,
2223 &new_id
, &stream
->stream_fd
->fd
);
2225 ERR("Rotating stream output file");
2226 goto end_stream_unlock
;
2229 * Reset current size because we just performed a stream
2232 stream
->tracefile_size_current
= 0;
2237 * Index are handled in protocol version 2.4 and above. Also,
2238 * snapshot and index are NOT supported.
2240 if (session
->minor
>= 4 && !session
->snapshot
) {
2241 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2243 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2244 stream
->stream_handle
, net_seq_num
, ret
);
2245 goto end_stream_unlock
;
2249 for (recv_off
= 0; recv_off
< data_size
; recv_off
+= chunk_size
) {
2250 size_t recv_size
= min(data_size
- recv_off
, chunk_size
);
2252 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, 0);
2255 /* Orderly shutdown. Not necessary to print an error. */
2256 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2258 ERR("Socket %d error %d", conn
->sock
->fd
, ret
);
2261 goto end_stream_unlock
;
2264 /* Write data to stream output fd. */
2265 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2267 if (size_ret
< recv_size
) {
2268 ERR("Relay error writing data to file");
2270 goto end_stream_unlock
;
2273 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2274 size_ret
, stream
->stream_handle
);
2277 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2278 be32toh(data_hdr
.padding_size
));
2280 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2281 stream
->stream_handle
, net_seq_num
, ret
);
2282 goto end_stream_unlock
;
2284 stream
->tracefile_size_current
+=
2285 data_size
+ be32toh(data_hdr
.padding_size
);
2286 if (stream
->prev_seq
== -1ULL) {
2290 stream
->prev_seq
= net_seq_num
;
2293 close_requested
= stream
->close_requested
;
2294 pthread_mutex_unlock(&stream
->lock
);
2295 if (close_requested
) {
2296 try_stream_close(stream
);
2300 pthread_mutex_lock(&session
->lock
);
2301 uatomic_set(&session
->new_streams
, 1);
2302 pthread_mutex_unlock(&session
->lock
);
2309 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2313 (void) lttng_poll_del(events
, pollfd
);
2315 ret
= close(pollfd
);
2317 ERR("Closing pollfd %d", pollfd
);
2321 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2322 int pollfd
, struct relay_connection
*conn
)
2324 const char *type_str
;
2326 switch (conn
->type
) {
2331 type_str
= "Control";
2333 case RELAY_VIEWER_COMMAND
:
2334 type_str
= "Viewer Command";
2336 case RELAY_VIEWER_NOTIFICATION
:
2337 type_str
= "Viewer Notification";
2340 type_str
= "Unknown";
2342 cleanup_connection_pollfd(events
, pollfd
);
2343 connection_put(conn
);
2344 DBG("%s connection closed with %d", type_str
, pollfd
);
2348 * This thread does the actual work
2350 static void *relay_thread_worker(void *data
)
2352 int ret
, err
= -1, last_seen_data_fd
= -1;
2354 struct lttng_poll_event events
;
2355 struct lttng_ht
*relay_connections_ht
;
2356 struct lttng_ht_iter iter
;
2357 struct lttcomm_relayd_hdr recv_hdr
;
2358 struct relay_connection
*destroy_conn
= NULL
;
2360 DBG("[thread] Relay worker started");
2362 rcu_register_thread();
2364 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2366 if (testpoint(relayd_thread_worker
)) {
2367 goto error_testpoint
;
2370 health_code_update();
2372 /* table of connections indexed on socket */
2373 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2374 if (!relay_connections_ht
) {
2375 goto relay_connections_ht_error
;
2378 ret
= create_thread_poll_set(&events
, 2);
2380 goto error_poll_create
;
2383 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2390 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2392 health_code_update();
2394 /* Infinite blocking call, waiting for transmission */
2395 DBG3("Relayd worker thread polling...");
2396 health_poll_entry();
2397 ret
= lttng_poll_wait(&events
, -1);
2401 * Restart interrupted system call.
2403 if (errno
== EINTR
) {
2412 * Process control. The control connection is
2413 * prioritized so we don't starve it with high
2414 * throughput tracing data on the data connection.
2416 for (i
= 0; i
< nb_fd
; i
++) {
2417 /* Fetch once the poll data */
2418 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2419 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2421 health_code_update();
2425 * No activity for this FD (poll
2431 /* Thread quit pipe has been closed. Killing thread. */
2432 ret
= check_thread_quit_pipe(pollfd
, revents
);
2438 /* Inspect the relay conn pipe for new connection */
2439 if (pollfd
== relay_conn_pipe
[0]) {
2440 if (revents
& LPOLLIN
) {
2441 struct relay_connection
*conn
;
2443 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2447 lttng_poll_add(&events
, conn
->sock
->fd
,
2448 LPOLLIN
| LPOLLRDHUP
);
2449 connection_ht_add(relay_connections_ht
, conn
);
2450 DBG("Connection socket %d added", conn
->sock
->fd
);
2451 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2452 ERR("Relay connection pipe error");
2455 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2459 struct relay_connection
*ctrl_conn
;
2461 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2462 /* If not found, there is a synchronization issue. */
2465 if (ctrl_conn
->type
== RELAY_DATA
) {
2466 if (revents
& LPOLLIN
) {
2468 * Flag the last seen data fd not deleted. It will be
2469 * used as the last seen fd if any fd gets deleted in
2472 last_notdel_data_fd
= pollfd
;
2474 goto put_ctrl_connection
;
2476 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2478 if (revents
& LPOLLIN
) {
2479 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2480 &recv_hdr
, sizeof(recv_hdr
), 0);
2482 /* Connection closed */
2483 relay_thread_close_connection(&events
, pollfd
,
2486 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2488 /* Clear the session on error. */
2489 relay_thread_close_connection(&events
,
2494 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2495 relay_thread_close_connection(&events
,
2497 if (last_seen_data_fd
== pollfd
) {
2498 last_seen_data_fd
= last_notdel_data_fd
;
2501 ERR("Unexpected poll events %u for control sock %d",
2503 connection_put(ctrl_conn
);
2506 put_ctrl_connection
:
2507 connection_put(ctrl_conn
);
2512 * The last loop handled a control request, go back to poll to make
2513 * sure we prioritise the control socket.
2519 if (last_seen_data_fd
>= 0) {
2520 for (i
= 0; i
< nb_fd
; i
++) {
2521 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2523 health_code_update();
2525 if (last_seen_data_fd
== pollfd
) {
2532 /* Process data connection. */
2533 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2534 /* Fetch the poll data. */
2535 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2536 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2537 struct relay_connection
*data_conn
;
2539 health_code_update();
2542 /* No activity for this FD (poll implementation). */
2546 /* Skip the command pipe. It's handled in the first loop. */
2547 if (pollfd
== relay_conn_pipe
[0]) {
2551 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2553 /* Skip it. Might be removed before. */
2556 if (data_conn
->type
== RELAY_CONTROL
) {
2557 goto put_data_connection
;
2559 assert(data_conn
->type
== RELAY_DATA
);
2561 if (revents
& LPOLLIN
) {
2562 ret
= relay_process_data(data_conn
);
2563 /* Connection closed */
2565 relay_thread_close_connection(&events
, pollfd
,
2568 * Every goto restart call sets the last seen fd where
2569 * here we don't really care since we gracefully
2570 * continue the loop after the connection is deleted.
2573 /* Keep last seen port. */
2574 last_seen_data_fd
= pollfd
;
2575 connection_put(data_conn
);
2578 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2579 relay_thread_close_connection(&events
, pollfd
,
2582 ERR("Unknown poll events %u for data sock %d",
2585 put_data_connection
:
2586 connection_put(data_conn
);
2588 last_seen_data_fd
= -1;
2591 /* Normal exit, no error */
2596 /* Cleanup reamaining connection object. */
2598 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2601 health_code_update();
2603 * No need to grab another ref, because we own
2606 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2611 lttng_poll_clean(&events
);
2613 lttng_ht_destroy(relay_connections_ht
);
2614 relay_connections_ht_error
:
2615 /* Close relay conn pipes */
2616 utils_close_pipe(relay_conn_pipe
);
2618 DBG("Thread exited with error");
2620 DBG("Worker thread cleanup complete");
2624 ERR("Health error occurred in %s", __func__
);
2626 health_unregister(health_relayd
);
2627 rcu_unregister_thread();
2628 lttng_relay_stop_threads();
2633 * Create the relay command pipe to wake thread_manage_apps.
2634 * Closed in cleanup().
2636 static int create_relay_conn_pipe(void)
2640 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2648 int main(int argc
, char **argv
)
2650 int ret
= 0, retval
= 0;
2653 /* Parse arguments */
2655 if (set_options(argc
, argv
)) {
2660 if (set_signal_handler()) {
2665 /* Try to create directory if -o, --output is specified. */
2666 if (opt_output_path
) {
2667 if (*opt_output_path
!= '/') {
2668 ERR("Please specify an absolute path for -o, --output PATH");
2673 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2676 ERR("Unable to create %s", opt_output_path
);
2683 if (opt_daemon
|| opt_background
) {
2686 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2694 * We are in the child. Make sure all other file
2695 * descriptors are closed, in case we are called with
2696 * more opened file descriptors than the standard ones.
2698 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2704 /* Initialize thread health monitoring */
2705 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2706 if (!health_relayd
) {
2707 PERROR("health_app_create error");
2709 goto exit_health_app_create
;
2712 /* Create thread quit pipe */
2713 if (init_thread_quit_pipe()) {
2715 goto exit_init_data
;
2718 /* Setup the thread apps communication pipe. */
2719 if (create_relay_conn_pipe()) {
2721 goto exit_init_data
;
2724 /* Init relay command queue. */
2725 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2727 /* Set up max poll set size */
2728 if (lttng_poll_set_max_size()) {
2730 goto exit_init_data
;
2733 /* Initialize communication library */
2735 lttcomm_inet_init();
2737 /* tables of sessions indexed by session ID */
2738 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2741 goto exit_init_data
;
2744 /* tables of streams indexed by stream ID */
2745 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2746 if (!relay_streams_ht
) {
2748 goto exit_init_data
;
2751 /* tables of streams indexed by stream ID */
2752 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2753 if (!viewer_streams_ht
) {
2755 goto exit_init_data
;
2758 ret
= utils_create_pipe(health_quit_pipe
);
2761 goto exit_health_quit_pipe
;
2764 /* Create thread to manage the client socket */
2765 ret
= pthread_create(&health_thread
, NULL
,
2766 thread_manage_health
, (void *) NULL
);
2769 PERROR("pthread_create health");
2771 goto exit_health_thread
;
2774 /* Setup the dispatcher thread */
2775 ret
= pthread_create(&dispatcher_thread
, NULL
,
2776 relay_thread_dispatcher
, (void *) NULL
);
2779 PERROR("pthread_create dispatcher");
2781 goto exit_dispatcher_thread
;
2784 /* Setup the worker thread */
2785 ret
= pthread_create(&worker_thread
, NULL
,
2786 relay_thread_worker
, NULL
);
2789 PERROR("pthread_create worker");
2791 goto exit_worker_thread
;
2794 /* Setup the listener thread */
2795 ret
= pthread_create(&listener_thread
, NULL
,
2796 relay_thread_listener
, (void *) NULL
);
2799 PERROR("pthread_create listener");
2801 goto exit_listener_thread
;
2804 ret
= relayd_live_create(live_uri
);
2806 ERR("Starting live viewer threads");
2812 * This is where we start awaiting program completion (e.g. through
2813 * signal that asks threads to teardown).
2816 ret
= relayd_live_join();
2822 ret
= pthread_join(listener_thread
, &status
);
2825 PERROR("pthread_join listener_thread");
2829 exit_listener_thread
:
2830 ret
= pthread_join(worker_thread
, &status
);
2833 PERROR("pthread_join worker_thread");
2838 ret
= pthread_join(dispatcher_thread
, &status
);
2841 PERROR("pthread_join dispatcher_thread");
2844 exit_dispatcher_thread
:
2846 ret
= pthread_join(health_thread
, &status
);
2849 PERROR("pthread_join health_thread");
2854 utils_close_pipe(health_quit_pipe
);
2855 exit_health_quit_pipe
:
2858 health_app_destroy(health_relayd
);
2859 exit_health_app_create
:
2863 /* Ensure all prior call_rcu are done. */