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' },
166 { "version", 0, 0, 'V' },
170 static const char *config_ignore_options
[] = { "help", "config", "version" };
173 * usage function on stderr
175 static void usage(void)
177 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
178 fprintf(stderr
, " -h, --help Display this usage.\n");
179 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
180 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
181 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
182 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
183 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
184 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
185 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
186 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
187 fprintf(stderr
, " -f --config Load daemon configuration file\n");
191 * Take an option from the getopt output and set it in the right variable to be
194 * Return 0 on success else a negative value.
196 static int set_option(int opt
, const char *arg
, const char *optname
)
202 fprintf(stderr
, "option %s", optname
);
204 fprintf(stderr
, " with arg %s\n", arg
);
208 if (lttng_is_setuid_setgid()) {
209 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
210 "-C, --control-port");
212 ret
= uri_parse(arg
, &control_uri
);
214 ERR("Invalid control URI specified");
217 if (control_uri
->port
== 0) {
218 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
223 if (lttng_is_setuid_setgid()) {
224 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
227 ret
= uri_parse(arg
, &data_uri
);
229 ERR("Invalid data URI specified");
232 if (data_uri
->port
== 0) {
233 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
238 if (lttng_is_setuid_setgid()) {
239 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
242 ret
= uri_parse(arg
, &live_uri
);
244 ERR("Invalid live URI specified");
247 if (live_uri
->port
== 0) {
248 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
259 if (lttng_is_setuid_setgid()) {
260 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
263 tracing_group_name
= strdup(arg
);
264 if (tracing_group_name
== NULL
) {
269 tracing_group_name_override
= 1;
276 fprintf(stdout
, "%s\n", VERSION
);
279 if (lttng_is_setuid_setgid()) {
280 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
283 ret
= asprintf(&opt_output_path
, "%s", arg
);
286 PERROR("asprintf opt_output_path");
292 /* Verbose level can increase using multiple -v */
294 lttng_opt_verbose
= config_parse_value(arg
);
296 /* Only 3 level of verbosity (-vvv). */
297 if (lttng_opt_verbose
< 3) {
298 lttng_opt_verbose
+= 1;
303 /* Unknown option or other error.
304 * Error is printed by getopt, just return */
317 * config_entry_handler_cb used to handle options read from a config file.
318 * See config_entry_handler_cb comment in common/config/config.h for the
319 * return value conventions.
321 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
325 if (!entry
|| !entry
->name
|| !entry
->value
) {
330 /* Check if the option is to be ignored */
331 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
332 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
337 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
338 /* Ignore if entry name is not fully matched. */
339 if (strcmp(entry
->name
, long_options
[i
].name
)) {
344 * If the option takes no argument on the command line,
345 * we have to check if the value is "true". We support
346 * non-zero numeric values, true, on and yes.
348 if (!long_options
[i
].has_arg
) {
349 ret
= config_parse_value(entry
->value
);
352 WARN("Invalid configuration value \"%s\" for option %s",
353 entry
->value
, entry
->name
);
355 /* False, skip boolean config option. */
360 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
364 WARN("Unrecognized option \"%s\" in daemon configuration file.",
371 static int set_options(int argc
, char **argv
)
373 int c
, ret
= 0, option_index
= 0, retval
= 0;
374 int orig_optopt
= optopt
, orig_optind
= optind
;
375 char *default_address
, *optstring
;
376 const char *config_path
= NULL
;
378 optstring
= utils_generate_optstring(long_options
,
379 sizeof(long_options
) / sizeof(struct option
));
385 /* Check for the --config option */
387 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
388 &option_index
)) != -1) {
392 } else if (c
!= 'f') {
396 if (lttng_is_setuid_setgid()) {
397 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
400 config_path
= utils_expand_path(optarg
);
402 ERR("Failed to resolve path: %s", optarg
);
407 ret
= config_get_section_entries(config_path
, config_section_name
,
408 config_entry_handler
, NULL
);
411 ERR("Invalid configuration option at line %i", ret
);
417 /* Reset getopt's global state */
418 optopt
= orig_optopt
;
419 optind
= orig_optind
;
421 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
426 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
433 /* assign default values */
434 if (control_uri
== NULL
) {
435 ret
= asprintf(&default_address
,
436 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
437 DEFAULT_NETWORK_CONTROL_PORT
);
439 PERROR("asprintf default data address");
444 ret
= uri_parse(default_address
, &control_uri
);
445 free(default_address
);
447 ERR("Invalid control URI specified");
452 if (data_uri
== NULL
) {
453 ret
= asprintf(&default_address
,
454 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
455 DEFAULT_NETWORK_DATA_PORT
);
457 PERROR("asprintf default data address");
462 ret
= uri_parse(default_address
, &data_uri
);
463 free(default_address
);
465 ERR("Invalid data URI specified");
470 if (live_uri
== NULL
) {
471 ret
= asprintf(&default_address
,
472 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
473 DEFAULT_NETWORK_VIEWER_PORT
);
475 PERROR("asprintf default viewer control address");
480 ret
= uri_parse(default_address
, &live_uri
);
481 free(default_address
);
483 ERR("Invalid viewer control URI specified");
494 static void print_global_objects(void)
496 rcu_register_thread();
498 print_viewer_streams();
499 print_relay_streams();
502 rcu_unregister_thread();
508 static void relayd_cleanup(void)
510 print_global_objects();
514 if (viewer_streams_ht
)
515 lttng_ht_destroy(viewer_streams_ht
);
516 if (relay_streams_ht
)
517 lttng_ht_destroy(relay_streams_ht
);
519 lttng_ht_destroy(sessions_ht
);
521 /* free the dynamically allocated opt_output_path */
522 free(opt_output_path
);
524 /* Close thread quit pipes */
525 utils_close_pipe(thread_quit_pipe
);
527 uri_free(control_uri
);
529 /* Live URI is freed in the live thread. */
531 if (tracing_group_name_override
) {
532 free((void *) tracing_group_name
);
537 * Write to writable pipe used to notify a thread.
539 static int notify_thread_pipe(int wpipe
)
543 ret
= lttng_write(wpipe
, "!", 1);
545 PERROR("write poll pipe");
553 static int notify_health_quit_pipe(int *pipe
)
557 ret
= lttng_write(pipe
[1], "4", 1);
559 PERROR("write relay health quit");
568 * Stop all relayd and relayd-live threads.
570 int lttng_relay_stop_threads(void)
574 /* Stopping all threads */
575 DBG("Terminating all threads");
576 if (notify_thread_pipe(thread_quit_pipe
[1])) {
577 ERR("write error on thread quit pipe");
581 if (notify_health_quit_pipe(health_quit_pipe
)) {
582 ERR("write error on health quit pipe");
585 /* Dispatch thread */
586 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
587 futex_nto1_wake(&relay_conn_queue
.futex
);
589 if (relayd_live_stop()) {
590 ERR("Error stopping live threads");
597 * Signal handler for the daemon
599 * Simply stop all worker threads, leaving main() return gracefully after
600 * joining all threads and calling cleanup().
602 static void sighandler(int sig
)
606 DBG("SIGINT caught");
607 if (lttng_relay_stop_threads()) {
608 ERR("Error stopping threads");
612 DBG("SIGTERM caught");
613 if (lttng_relay_stop_threads()) {
614 ERR("Error stopping threads");
618 CMM_STORE_SHARED(recv_child_signal
, 1);
626 * Setup signal handler for :
627 * SIGINT, SIGTERM, SIGPIPE
629 static int set_signal_handler(void)
635 if ((ret
= sigemptyset(&sigset
)) < 0) {
636 PERROR("sigemptyset");
643 sa
.sa_handler
= sighandler
;
644 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
649 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
654 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
659 sa
.sa_handler
= SIG_IGN
;
660 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
665 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
670 void lttng_relay_notify_ready(void)
672 /* Notify the parent of the fork() process that we are ready. */
673 if (opt_daemon
|| opt_background
) {
674 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
675 kill(child_ppid
, SIGUSR1
);
681 * Init thread quit pipe.
683 * Return -1 on error or 0 if all pipes are created.
685 static int init_thread_quit_pipe(void)
689 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
695 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
697 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
701 if (events
== NULL
|| size
== 0) {
706 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
712 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
724 * Check if the thread quit pipe was triggered.
726 * Return 1 if it was triggered else 0;
728 static int check_thread_quit_pipe(int fd
, uint32_t events
)
730 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
738 * Create and init socket from uri.
740 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
743 struct lttcomm_sock
*sock
= NULL
;
745 sock
= lttcomm_alloc_sock_from_uri(uri
);
747 ERR("Allocating socket");
751 ret
= lttcomm_create_sock(sock
);
755 DBG("Listening on sock %d", sock
->fd
);
757 ret
= sock
->ops
->bind(sock
);
762 ret
= sock
->ops
->listen(sock
, -1);
772 lttcomm_destroy_sock(sock
);
778 * This thread manages the listening for new connections on the network
780 static void *relay_thread_listener(void *data
)
782 int i
, ret
, pollfd
, err
= -1;
783 uint32_t revents
, nb_fd
;
784 struct lttng_poll_event events
;
785 struct lttcomm_sock
*control_sock
, *data_sock
;
787 DBG("[thread] Relay listener started");
789 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
791 health_code_update();
793 control_sock
= relay_socket_create(control_uri
);
795 goto error_sock_control
;
798 data_sock
= relay_socket_create(data_uri
);
800 goto error_sock_relay
;
804 * Pass 3 as size here for the thread quit pipe, control and
807 ret
= create_thread_poll_set(&events
, 3);
809 goto error_create_poll
;
812 /* Add the control socket */
813 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
818 /* Add the data socket */
819 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
824 lttng_relay_notify_ready();
826 if (testpoint(relayd_thread_listener
)) {
827 goto error_testpoint
;
831 health_code_update();
833 DBG("Listener accepting connections");
837 ret
= lttng_poll_wait(&events
, -1);
841 * Restart interrupted system call.
843 if (errno
== EINTR
) {
851 DBG("Relay new connection received");
852 for (i
= 0; i
< nb_fd
; i
++) {
853 health_code_update();
855 /* Fetch once the poll data */
856 revents
= LTTNG_POLL_GETEV(&events
, i
);
857 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
861 * No activity for this FD (poll
867 /* Thread quit pipe has been closed. Killing thread. */
868 ret
= check_thread_quit_pipe(pollfd
, revents
);
874 if (revents
& LPOLLIN
) {
876 * A new connection is requested, therefore a
877 * sessiond/consumerd connection is allocated in
878 * this thread, enqueued to a global queue and
879 * dequeued (and freed) in the worker thread.
882 struct relay_connection
*new_conn
;
883 struct lttcomm_sock
*newsock
;
884 enum connection_type type
;
886 if (pollfd
== data_sock
->fd
) {
888 newsock
= data_sock
->ops
->accept(data_sock
);
889 DBG("Relay data connection accepted, socket %d",
892 assert(pollfd
== control_sock
->fd
);
893 type
= RELAY_CONTROL
;
894 newsock
= control_sock
->ops
->accept(control_sock
);
895 DBG("Relay control connection accepted, socket %d",
899 PERROR("accepting sock");
903 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
906 PERROR("setsockopt inet");
907 lttcomm_destroy_sock(newsock
);
910 new_conn
= connection_create(newsock
, type
);
912 lttcomm_destroy_sock(newsock
);
916 /* Enqueue request for the dispatcher thread. */
917 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
921 * Wake the dispatch queue futex.
922 * Implicit memory barrier with the
923 * exchange in cds_wfcq_enqueue.
925 futex_nto1_wake(&relay_conn_queue
.futex
);
926 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
927 ERR("socket poll error");
930 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
940 lttng_poll_clean(&events
);
942 if (data_sock
->fd
>= 0) {
943 ret
= data_sock
->ops
->close(data_sock
);
948 lttcomm_destroy_sock(data_sock
);
950 if (control_sock
->fd
>= 0) {
951 ret
= control_sock
->ops
->close(control_sock
);
956 lttcomm_destroy_sock(control_sock
);
960 ERR("Health error occurred in %s", __func__
);
962 health_unregister(health_relayd
);
963 DBG("Relay listener thread cleanup complete");
964 lttng_relay_stop_threads();
969 * This thread manages the dispatching of the requests to worker threads
971 static void *relay_thread_dispatcher(void *data
)
975 struct cds_wfcq_node
*node
;
976 struct relay_connection
*new_conn
= NULL
;
978 DBG("[thread] Relay dispatcher started");
980 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
982 if (testpoint(relayd_thread_dispatcher
)) {
983 goto error_testpoint
;
986 health_code_update();
988 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
989 health_code_update();
991 /* Atomically prepare the queue futex */
992 futex_nto1_prepare(&relay_conn_queue
.futex
);
995 health_code_update();
997 /* Dequeue commands */
998 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
999 &relay_conn_queue
.tail
);
1001 DBG("Woken up but nothing in the relay command queue");
1002 /* Continue thread execution */
1005 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1007 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1010 * Inform worker thread of the new request. This
1011 * call is blocking so we can be assured that
1012 * the data will be read at some point in time
1013 * or wait to the end of the world :)
1015 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1017 PERROR("write connection pipe");
1018 connection_put(new_conn
);
1021 } while (node
!= NULL
);
1023 /* Futex wait on queue. Blocking call on futex() */
1024 health_poll_entry();
1025 futex_nto1_wait(&relay_conn_queue
.futex
);
1029 /* Normal exit, no error */
1036 ERR("Health error occurred in %s", __func__
);
1038 health_unregister(health_relayd
);
1039 DBG("Dispatch thread dying");
1040 lttng_relay_stop_threads();
1045 * Set index data from the control port to a given index object.
1047 static int set_index_control_data(struct relay_index
*index
,
1048 struct lttcomm_relayd_index
*data
)
1050 struct ctf_packet_index index_data
;
1053 * The index on disk is encoded in big endian, so we don't need
1054 * to convert the data received on the network. The data_offset
1055 * value is NEVER modified here and is updated by the data
1058 index_data
.packet_size
= data
->packet_size
;
1059 index_data
.content_size
= data
->content_size
;
1060 index_data
.timestamp_begin
= data
->timestamp_begin
;
1061 index_data
.timestamp_end
= data
->timestamp_end
;
1062 index_data
.events_discarded
= data
->events_discarded
;
1063 index_data
.stream_id
= data
->stream_id
;
1064 return relay_index_set_data(index
, &index_data
);
1068 * Handle the RELAYD_CREATE_SESSION command.
1070 * On success, send back the session id or else return a negative value.
1072 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1073 struct relay_connection
*conn
)
1075 int ret
= 0, send_ret
;
1076 struct relay_session
*session
;
1077 struct lttcomm_relayd_status_session reply
;
1078 char session_name
[NAME_MAX
];
1079 char hostname
[HOST_NAME_MAX
];
1080 uint32_t live_timer
= 0;
1081 bool snapshot
= false;
1083 memset(session_name
, 0, NAME_MAX
);
1084 memset(hostname
, 0, HOST_NAME_MAX
);
1086 memset(&reply
, 0, sizeof(reply
));
1088 switch (conn
->minor
) {
1093 case 4: /* LTTng sessiond 2.4 */
1095 ret
= cmd_create_session_2_4(conn
, session_name
,
1096 hostname
, &live_timer
, &snapshot
);
1102 session
= session_create(session_name
, hostname
, live_timer
,
1103 snapshot
, conn
->major
, conn
->minor
);
1108 assert(!conn
->session
);
1109 conn
->session
= session
;
1110 DBG("Created session %" PRIu64
, session
->id
);
1112 reply
.session_id
= htobe64(session
->id
);
1116 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1118 reply
.ret_code
= htobe32(LTTNG_OK
);
1121 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1123 ERR("Relayd sending session id");
1131 * When we have received all the streams and the metadata for a channel,
1132 * we make them visible to the viewer threads.
1134 static void publish_connection_local_streams(struct relay_connection
*conn
)
1136 struct relay_stream
*stream
;
1137 struct relay_session
*session
= conn
->session
;
1140 * We publish all streams belonging to a session atomically wrt
1143 pthread_mutex_lock(&session
->lock
);
1145 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1147 stream_publish(stream
);
1152 * Inform the viewer that there are new streams in the session.
1154 if (session
->viewer_attached
) {
1155 uatomic_set(&session
->new_streams
, 1);
1157 pthread_mutex_unlock(&session
->lock
);
1161 * relay_add_stream: allocate a new stream for a session
1163 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1164 struct relay_connection
*conn
)
1168 struct relay_session
*session
= conn
->session
;
1169 struct relay_stream
*stream
= NULL
;
1170 struct lttcomm_relayd_status_stream reply
;
1171 struct ctf_trace
*trace
= NULL
;
1172 uint64_t stream_handle
= -1ULL;
1173 char *path_name
= NULL
, *channel_name
= NULL
;
1174 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1176 if (!session
|| conn
->version_check_done
== 0) {
1177 ERR("Trying to add a stream before version check");
1179 goto end_no_session
;
1182 switch (session
->minor
) {
1183 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1184 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1187 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1189 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1190 &channel_name
, &tracefile_size
, &tracefile_count
);
1197 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1201 /* This stream here has one reference on the trace. */
1203 pthread_mutex_lock(&last_relay_stream_id_lock
);
1204 stream_handle
= ++last_relay_stream_id
;
1205 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1207 /* We pass ownership of path_name and channel_name. */
1208 stream
= stream_create(trace
, stream_handle
, path_name
,
1209 channel_name
, tracefile_size
, tracefile_count
);
1211 channel_name
= NULL
;
1214 * Streams are the owners of their trace. Reference to trace is
1215 * kept within stream_create().
1217 ctf_trace_put(trace
);
1220 memset(&reply
, 0, sizeof(reply
));
1221 reply
.handle
= htobe64(stream_handle
);
1223 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1225 reply
.ret_code
= htobe32(LTTNG_OK
);
1228 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1229 sizeof(struct lttcomm_relayd_status_stream
), 0);
1231 ERR("Relay sending stream id");
1232 ret
= (int) send_ret
;
1242 * relay_close_stream: close a specific stream
1244 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1245 struct relay_connection
*conn
)
1248 struct relay_session
*session
= conn
->session
;
1249 struct lttcomm_relayd_close_stream stream_info
;
1250 struct lttcomm_relayd_generic_reply reply
;
1251 struct relay_stream
*stream
;
1253 DBG("Close stream received");
1255 if (!session
|| conn
->version_check_done
== 0) {
1256 ERR("Trying to close a stream before version check");
1258 goto end_no_session
;
1261 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1262 sizeof(struct lttcomm_relayd_close_stream
), 0);
1263 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1265 /* Orderly shutdown. Not necessary to print an error. */
1266 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1268 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1271 goto end_no_session
;
1274 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1281 * Set last_net_seq_num before the close flag. Required by data
1284 pthread_mutex_lock(&stream
->lock
);
1285 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1286 pthread_mutex_unlock(&stream
->lock
);
1289 * This is one of the conditions which may trigger a stream close
1290 * with the others being:
1291 * 1) A close command is received for a stream
1292 * 2) The control connection owning the stream is closed
1293 * 3) We have received all of the stream's data _after_ a close
1296 try_stream_close(stream
);
1297 if (stream
->is_metadata
) {
1298 struct relay_viewer_stream
*vstream
;
1300 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1302 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1304 * Since all the metadata has been sent to the
1305 * viewer and that we have a request to close
1306 * its stream, we can safely teardown the
1307 * corresponding metadata viewer stream.
1309 viewer_stream_put(vstream
);
1311 /* Put local reference. */
1312 viewer_stream_put(vstream
);
1318 memset(&reply
, 0, sizeof(reply
));
1320 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1322 reply
.ret_code
= htobe32(LTTNG_OK
);
1324 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1325 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1327 ERR("Relay sending stream id");
1336 * relay_unknown_command: send -1 if received unknown command
1338 static void relay_unknown_command(struct relay_connection
*conn
)
1340 struct lttcomm_relayd_generic_reply reply
;
1343 memset(&reply
, 0, sizeof(reply
));
1344 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1345 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1346 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1348 ERR("Relay sending unknown command");
1353 * relay_start: send an acknowledgment to the client to tell if we are
1354 * ready to receive data. We are ready if a session is established.
1356 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1357 struct relay_connection
*conn
)
1359 int ret
= htobe32(LTTNG_OK
);
1360 struct lttcomm_relayd_generic_reply reply
;
1361 struct relay_session
*session
= conn
->session
;
1364 DBG("Trying to start the streaming without a session established");
1365 ret
= htobe32(LTTNG_ERR_UNK
);
1368 memset(&reply
, 0, sizeof(reply
));
1369 reply
.ret_code
= ret
;
1370 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1371 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1373 ERR("Relay sending start ack");
1380 * Append padding to the file pointed by the file descriptor fd.
1382 static int write_padding_to_file(int fd
, uint32_t size
)
1391 zeros
= zmalloc(size
);
1392 if (zeros
== NULL
) {
1393 PERROR("zmalloc zeros for padding");
1398 ret
= lttng_write(fd
, zeros
, size
);
1400 PERROR("write padding to file");
1410 * relay_recv_metadata: receive the metadata for the session.
1412 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1413 struct relay_connection
*conn
)
1417 struct relay_session
*session
= conn
->session
;
1418 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1419 struct relay_stream
*metadata_stream
;
1420 uint64_t data_size
, payload_size
;
1423 ERR("Metadata sent before version check");
1428 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1429 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1430 ERR("Incorrect data size");
1434 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1436 if (data_buffer_size
< data_size
) {
1437 /* In case the realloc fails, we can free the memory */
1440 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1441 if (!tmp_data_ptr
) {
1442 ERR("Allocating data buffer");
1447 data_buffer
= tmp_data_ptr
;
1448 data_buffer_size
= data_size
;
1450 memset(data_buffer
, 0, data_size
);
1451 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1452 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1453 if (size_ret
< 0 || size_ret
!= data_size
) {
1454 if (size_ret
== 0) {
1455 /* Orderly shutdown. Not necessary to print an error. */
1456 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1458 ERR("Relay didn't receive the whole metadata");
1463 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1465 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1466 if (!metadata_stream
) {
1471 pthread_mutex_lock(&metadata_stream
->lock
);
1473 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1475 if (size_ret
< payload_size
) {
1476 ERR("Relay error writing metadata on file");
1481 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1482 be32toh(metadata_struct
->padding_size
));
1487 metadata_stream
->metadata_received
+=
1488 payload_size
+ be32toh(metadata_struct
->padding_size
);
1489 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1490 metadata_stream
->metadata_received
);
1493 pthread_mutex_unlock(&metadata_stream
->lock
);
1494 stream_put(metadata_stream
);
1500 * relay_send_version: send relayd version number
1502 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1503 struct relay_connection
*conn
)
1506 struct lttcomm_relayd_version reply
, msg
;
1508 conn
->version_check_done
= 1;
1510 /* Get version from the other side. */
1511 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1512 if (ret
< 0 || ret
!= sizeof(msg
)) {
1514 /* Orderly shutdown. Not necessary to print an error. */
1515 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1517 ERR("Relay failed to receive the version values.");
1523 memset(&reply
, 0, sizeof(reply
));
1524 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1525 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1527 /* Major versions must be the same */
1528 if (reply
.major
!= be32toh(msg
.major
)) {
1529 DBG("Incompatible major versions (%u vs %u), deleting session",
1530 reply
.major
, be32toh(msg
.major
));
1531 connection_put(conn
);
1536 conn
->major
= reply
.major
;
1537 /* We adapt to the lowest compatible version */
1538 if (reply
.minor
<= be32toh(msg
.minor
)) {
1539 conn
->minor
= reply
.minor
;
1541 conn
->minor
= be32toh(msg
.minor
);
1544 reply
.major
= htobe32(reply
.major
);
1545 reply
.minor
= htobe32(reply
.minor
);
1546 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1547 sizeof(struct lttcomm_relayd_version
), 0);
1549 ERR("Relay sending version");
1552 DBG("Version check done using protocol %u.%u", conn
->major
,
1560 * Check for data pending for a given stream id from the session daemon.
1562 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1563 struct relay_connection
*conn
)
1565 struct relay_session
*session
= conn
->session
;
1566 struct lttcomm_relayd_data_pending msg
;
1567 struct lttcomm_relayd_generic_reply reply
;
1568 struct relay_stream
*stream
;
1570 uint64_t last_net_seq_num
, stream_id
;
1572 DBG("Data pending command received");
1574 if (!session
|| conn
->version_check_done
== 0) {
1575 ERR("Trying to check for data before version check");
1577 goto end_no_session
;
1580 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1581 if (ret
< sizeof(msg
)) {
1583 /* Orderly shutdown. Not necessary to print an error. */
1584 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1586 ERR("Relay didn't receive valid data_pending struct size : %d",
1590 goto end_no_session
;
1593 stream_id
= be64toh(msg
.stream_id
);
1594 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1596 stream
= stream_get_by_id(stream_id
);
1597 if (stream
== NULL
) {
1602 pthread_mutex_lock(&stream
->lock
);
1604 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1605 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1608 /* Avoid wrapping issue */
1609 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1610 /* Data has in fact been written and is NOT pending */
1613 /* Data still being streamed thus pending */
1617 stream
->data_pending_check_done
= true;
1618 pthread_mutex_unlock(&stream
->lock
);
1623 memset(&reply
, 0, sizeof(reply
));
1624 reply
.ret_code
= htobe32(ret
);
1625 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1627 ERR("Relay data pending ret code failed");
1635 * Wait for the control socket to reach a quiescent state.
1637 * Note that for now, when receiving this command from the session
1638 * daemon, this means that every subsequent commands or data received on
1639 * the control socket has been handled. So, this is why we simply return
1642 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1643 struct relay_connection
*conn
)
1647 struct relay_stream
*stream
;
1648 struct lttcomm_relayd_quiescent_control msg
;
1649 struct lttcomm_relayd_generic_reply reply
;
1651 DBG("Checking quiescent state on control socket");
1653 if (!conn
->session
|| conn
->version_check_done
== 0) {
1654 ERR("Trying to check for data before version check");
1656 goto end_no_session
;
1659 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1660 if (ret
< sizeof(msg
)) {
1662 /* Orderly shutdown. Not necessary to print an error. */
1663 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1665 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1669 goto end_no_session
;
1672 stream_id
= be64toh(msg
.stream_id
);
1673 stream
= stream_get_by_id(stream_id
);
1677 pthread_mutex_lock(&stream
->lock
);
1678 stream
->data_pending_check_done
= true;
1679 pthread_mutex_unlock(&stream
->lock
);
1680 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1683 memset(&reply
, 0, sizeof(reply
));
1684 reply
.ret_code
= htobe32(LTTNG_OK
);
1685 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1687 ERR("Relay data quiescent control ret code failed");
1695 * Initialize a data pending command. This means that a consumer is about
1696 * to ask for data pending for each stream it holds. Simply iterate over
1697 * all streams of a session and set the data_pending_check_done flag.
1699 * This command returns to the client a LTTNG_OK code.
1701 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1702 struct relay_connection
*conn
)
1705 struct lttng_ht_iter iter
;
1706 struct lttcomm_relayd_begin_data_pending msg
;
1707 struct lttcomm_relayd_generic_reply reply
;
1708 struct relay_stream
*stream
;
1709 uint64_t session_id
;
1714 DBG("Init streams for data pending");
1716 if (!conn
->session
|| conn
->version_check_done
== 0) {
1717 ERR("Trying to check for data before version check");
1719 goto end_no_session
;
1722 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1723 if (ret
< sizeof(msg
)) {
1725 /* Orderly shutdown. Not necessary to print an error. */
1726 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1728 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1732 goto end_no_session
;
1735 session_id
= be64toh(msg
.session_id
);
1738 * Iterate over all streams to set the begin data pending flag.
1739 * For now, the streams are indexed by stream handle so we have
1740 * to iterate over all streams to find the one associated with
1741 * the right session_id.
1744 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1746 if (!stream_get(stream
)) {
1749 if (stream
->trace
->session
->id
== session_id
) {
1750 pthread_mutex_lock(&stream
->lock
);
1751 stream
->data_pending_check_done
= false;
1752 pthread_mutex_unlock(&stream
->lock
);
1753 DBG("Set begin data pending flag to stream %" PRIu64
,
1754 stream
->stream_handle
);
1760 memset(&reply
, 0, sizeof(reply
));
1761 /* All good, send back reply. */
1762 reply
.ret_code
= htobe32(LTTNG_OK
);
1764 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1766 ERR("Relay begin data pending send reply failed");
1774 * End data pending command. This will check, for a given session id, if
1775 * each stream associated with it has its data_pending_check_done flag
1776 * set. If not, this means that the client lost track of the stream but
1777 * the data is still being streamed on our side. In this case, we inform
1778 * the client that data is in flight.
1780 * Return to the client if there is data in flight or not with a ret_code.
1782 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1783 struct relay_connection
*conn
)
1786 struct lttng_ht_iter iter
;
1787 struct lttcomm_relayd_end_data_pending msg
;
1788 struct lttcomm_relayd_generic_reply reply
;
1789 struct relay_stream
*stream
;
1790 uint64_t session_id
;
1791 uint32_t is_data_inflight
= 0;
1793 DBG("End data pending command");
1795 if (!conn
->session
|| conn
->version_check_done
== 0) {
1796 ERR("Trying to check for data before version check");
1798 goto end_no_session
;
1801 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1802 if (ret
< sizeof(msg
)) {
1804 /* Orderly shutdown. Not necessary to print an error. */
1805 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1807 ERR("Relay didn't receive valid end data_pending struct size: %d",
1811 goto end_no_session
;
1814 session_id
= be64toh(msg
.session_id
);
1817 * Iterate over all streams to see if the begin data pending
1821 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1823 if (!stream_get(stream
)) {
1826 if (stream
->trace
->session
->id
!= session_id
) {
1830 pthread_mutex_lock(&stream
->lock
);
1831 if (!stream
->data_pending_check_done
) {
1832 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1833 is_data_inflight
= 1;
1834 DBG("Data is still in flight for stream %" PRIu64
,
1835 stream
->stream_handle
);
1836 pthread_mutex_unlock(&stream
->lock
);
1841 pthread_mutex_unlock(&stream
->lock
);
1846 memset(&reply
, 0, sizeof(reply
));
1847 /* All good, send back reply. */
1848 reply
.ret_code
= htobe32(is_data_inflight
);
1850 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1852 ERR("Relay end data pending send reply failed");
1860 * Receive an index for a specific stream.
1862 * Return 0 on success else a negative value.
1864 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1865 struct relay_connection
*conn
)
1868 struct relay_session
*session
= conn
->session
;
1869 struct lttcomm_relayd_index index_info
;
1870 struct relay_index
*index
;
1871 struct lttcomm_relayd_generic_reply reply
;
1872 struct relay_stream
*stream
;
1873 uint64_t net_seq_num
;
1877 DBG("Relay receiving index");
1879 if (!session
|| conn
->version_check_done
== 0) {
1880 ERR("Trying to close a stream before version check");
1882 goto end_no_session
;
1885 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1886 sizeof(index_info
), 0);
1887 if (ret
< sizeof(index_info
)) {
1889 /* Orderly shutdown. Not necessary to print an error. */
1890 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1892 ERR("Relay didn't receive valid index struct size : %d", ret
);
1895 goto end_no_session
;
1898 net_seq_num
= be64toh(index_info
.net_seq_num
);
1900 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1902 ERR("stream_get_by_id not found");
1906 pthread_mutex_lock(&stream
->lock
);
1908 /* Live beacon handling */
1909 if (index_info
.packet_size
== 0) {
1910 DBG("Received live beacon for stream %" PRIu64
,
1911 stream
->stream_handle
);
1914 * Only flag a stream inactive when it has already
1915 * received data and no indexes are in flight.
1917 if (stream
->index_received_seqcount
> 0
1918 && stream
->indexes_in_flight
== 0) {
1919 stream
->beacon_ts_end
=
1920 be64toh(index_info
.timestamp_end
);
1923 goto end_stream_put
;
1925 stream
->beacon_ts_end
= -1ULL;
1928 if (stream
->ctf_stream_id
== -1ULL) {
1929 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1931 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1934 ERR("relay_index_get_by_id_or_create index NULL");
1935 goto end_stream_put
;
1937 if (set_index_control_data(index
, &index_info
)) {
1938 ERR("set_index_control_data error");
1939 relay_index_put(index
);
1941 goto end_stream_put
;
1943 ret
= relay_index_try_flush(index
);
1945 tracefile_array_commit_seq(stream
->tfa
);
1946 stream
->index_received_seqcount
++;
1947 } else if (ret
> 0) {
1951 ERR("relay_index_try_flush error %d", ret
);
1952 relay_index_put(index
);
1957 pthread_mutex_unlock(&stream
->lock
);
1962 memset(&reply
, 0, sizeof(reply
));
1964 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1966 reply
.ret_code
= htobe32(LTTNG_OK
);
1968 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1970 ERR("Relay sending close index id reply");
1979 * Receive the streams_sent message.
1981 * Return 0 on success else a negative value.
1983 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1984 struct relay_connection
*conn
)
1987 struct lttcomm_relayd_generic_reply reply
;
1991 DBG("Relay receiving streams_sent");
1993 if (!conn
->session
|| conn
->version_check_done
== 0) {
1994 ERR("Trying to close a stream before version check");
1996 goto end_no_session
;
2000 * Publish every pending stream in the connection recv list which are
2001 * now ready to be used by the viewer.
2003 publish_connection_local_streams(conn
);
2005 memset(&reply
, 0, sizeof(reply
));
2006 reply
.ret_code
= htobe32(LTTNG_OK
);
2007 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2009 ERR("Relay sending sent_stream reply");
2021 * Process the commands received on the control socket
2023 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2024 struct relay_connection
*conn
)
2028 switch (be32toh(recv_hdr
->cmd
)) {
2029 case RELAYD_CREATE_SESSION
:
2030 ret
= relay_create_session(recv_hdr
, conn
);
2032 case RELAYD_ADD_STREAM
:
2033 ret
= relay_add_stream(recv_hdr
, conn
);
2035 case RELAYD_START_DATA
:
2036 ret
= relay_start(recv_hdr
, conn
);
2038 case RELAYD_SEND_METADATA
:
2039 ret
= relay_recv_metadata(recv_hdr
, conn
);
2041 case RELAYD_VERSION
:
2042 ret
= relay_send_version(recv_hdr
, conn
);
2044 case RELAYD_CLOSE_STREAM
:
2045 ret
= relay_close_stream(recv_hdr
, conn
);
2047 case RELAYD_DATA_PENDING
:
2048 ret
= relay_data_pending(recv_hdr
, conn
);
2050 case RELAYD_QUIESCENT_CONTROL
:
2051 ret
= relay_quiescent_control(recv_hdr
, conn
);
2053 case RELAYD_BEGIN_DATA_PENDING
:
2054 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2056 case RELAYD_END_DATA_PENDING
:
2057 ret
= relay_end_data_pending(recv_hdr
, conn
);
2059 case RELAYD_SEND_INDEX
:
2060 ret
= relay_recv_index(recv_hdr
, conn
);
2062 case RELAYD_STREAMS_SENT
:
2063 ret
= relay_streams_sent(recv_hdr
, conn
);
2065 case RELAYD_UPDATE_SYNC_INFO
:
2067 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2068 relay_unknown_command(conn
);
2078 * Handle index for a data stream.
2080 * Called with the stream lock held.
2082 * Return 0 on success else a negative value.
2084 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2088 uint64_t data_offset
;
2089 struct relay_index
*index
;
2091 /* Get data offset because we are about to update the index. */
2092 data_offset
= htobe64(stream
->tracefile_size_current
);
2094 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2095 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2098 * Lookup for an existing index for that stream id/sequence
2099 * number. If it exists, the control thread has already received the
2100 * data for it, thus we need to write it to disk.
2102 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2108 if (rotate_index
|| !stream
->index_fd
) {
2111 /* Put ref on previous index_fd. */
2112 if (stream
->index_fd
) {
2113 stream_fd_put(stream
->index_fd
);
2114 stream
->index_fd
= NULL
;
2117 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2118 -1, -1, stream
->tracefile_size
,
2119 tracefile_array_get_file_index_head(stream
->tfa
));
2122 /* Put self-ref for this index due to error. */
2123 relay_index_put(index
);
2126 stream
->index_fd
= stream_fd_create(fd
);
2127 if (!stream
->index_fd
) {
2130 PERROR("Error closing FD %d", fd
);
2132 /* Put self-ref for this index due to error. */
2133 relay_index_put(index
);
2134 /* Will put the local ref. */
2139 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2141 /* Put self-ref for this index due to error. */
2142 relay_index_put(index
);
2146 ret
= relay_index_try_flush(index
);
2148 tracefile_array_commit_seq(stream
->tfa
);
2149 stream
->index_received_seqcount
++;
2150 } else if (ret
> 0) {
2154 /* Put self-ref for this index due to error. */
2155 relay_index_put(index
);
2163 * relay_process_data: Process the data received on the data socket
2165 static int relay_process_data(struct relay_connection
*conn
)
2167 int ret
= 0, rotate_index
= 0;
2169 struct relay_stream
*stream
;
2170 struct lttcomm_relayd_data_hdr data_hdr
;
2172 uint64_t net_seq_num
;
2174 struct relay_session
*session
;
2175 bool new_stream
= false, close_requested
= false;
2176 size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2177 size_t recv_off
= 0;
2178 char data_buffer
[chunk_size
];
2180 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2181 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2184 /* Orderly shutdown. Not necessary to print an error. */
2185 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2187 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2193 stream_id
= be64toh(data_hdr
.stream_id
);
2194 stream
= stream_get_by_id(stream_id
);
2196 ERR("relay_process_data: Cannot find stream %" PRIu64
, stream_id
);
2200 session
= stream
->trace
->session
;
2201 data_size
= be32toh(data_hdr
.data_size
);
2203 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2205 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2206 data_size
, stream_id
, net_seq_num
);
2208 pthread_mutex_lock(&stream
->lock
);
2210 /* Check if a rotation is needed. */
2211 if (stream
->tracefile_size
> 0 &&
2212 (stream
->tracefile_size_current
+ data_size
) >
2213 stream
->tracefile_size
) {
2214 uint64_t old_id
, new_id
;
2216 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2217 tracefile_array_file_rotate(stream
->tfa
);
2219 /* new_id is updated by utils_rotate_stream_file. */
2222 ret
= utils_rotate_stream_file(stream
->path_name
,
2223 stream
->channel_name
, stream
->tracefile_size
,
2224 stream
->tracefile_count
, -1,
2225 -1, stream
->stream_fd
->fd
,
2226 &new_id
, &stream
->stream_fd
->fd
);
2228 ERR("Rotating stream output file");
2229 goto end_stream_unlock
;
2232 * Reset current size because we just performed a stream
2235 stream
->tracefile_size_current
= 0;
2240 * Index are handled in protocol version 2.4 and above. Also,
2241 * snapshot and index are NOT supported.
2243 if (session
->minor
>= 4 && !session
->snapshot
) {
2244 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2246 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2247 stream
->stream_handle
, net_seq_num
, ret
);
2248 goto end_stream_unlock
;
2252 for (recv_off
= 0; recv_off
< data_size
; recv_off
+= chunk_size
) {
2253 size_t recv_size
= min(data_size
- recv_off
, chunk_size
);
2255 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, 0);
2258 /* Orderly shutdown. Not necessary to print an error. */
2259 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2261 ERR("Socket %d error %d", conn
->sock
->fd
, ret
);
2264 goto end_stream_unlock
;
2267 /* Write data to stream output fd. */
2268 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2270 if (size_ret
< recv_size
) {
2271 ERR("Relay error writing data to file");
2273 goto end_stream_unlock
;
2276 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2277 size_ret
, stream
->stream_handle
);
2280 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2281 be32toh(data_hdr
.padding_size
));
2283 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2284 stream
->stream_handle
, net_seq_num
, ret
);
2285 goto end_stream_unlock
;
2287 stream
->tracefile_size_current
+=
2288 data_size
+ be32toh(data_hdr
.padding_size
);
2289 if (stream
->prev_seq
== -1ULL) {
2293 stream
->prev_seq
= net_seq_num
;
2296 close_requested
= stream
->close_requested
;
2297 pthread_mutex_unlock(&stream
->lock
);
2298 if (close_requested
) {
2299 try_stream_close(stream
);
2303 pthread_mutex_lock(&session
->lock
);
2304 uatomic_set(&session
->new_streams
, 1);
2305 pthread_mutex_unlock(&session
->lock
);
2312 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2316 (void) lttng_poll_del(events
, pollfd
);
2318 ret
= close(pollfd
);
2320 ERR("Closing pollfd %d", pollfd
);
2324 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2325 int pollfd
, struct relay_connection
*conn
)
2327 const char *type_str
;
2329 switch (conn
->type
) {
2334 type_str
= "Control";
2336 case RELAY_VIEWER_COMMAND
:
2337 type_str
= "Viewer Command";
2339 case RELAY_VIEWER_NOTIFICATION
:
2340 type_str
= "Viewer Notification";
2343 type_str
= "Unknown";
2345 cleanup_connection_pollfd(events
, pollfd
);
2346 connection_put(conn
);
2347 DBG("%s connection closed with %d", type_str
, pollfd
);
2351 * This thread does the actual work
2353 static void *relay_thread_worker(void *data
)
2355 int ret
, err
= -1, last_seen_data_fd
= -1;
2357 struct lttng_poll_event events
;
2358 struct lttng_ht
*relay_connections_ht
;
2359 struct lttng_ht_iter iter
;
2360 struct lttcomm_relayd_hdr recv_hdr
;
2361 struct relay_connection
*destroy_conn
= NULL
;
2363 DBG("[thread] Relay worker started");
2365 rcu_register_thread();
2367 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2369 if (testpoint(relayd_thread_worker
)) {
2370 goto error_testpoint
;
2373 health_code_update();
2375 /* table of connections indexed on socket */
2376 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2377 if (!relay_connections_ht
) {
2378 goto relay_connections_ht_error
;
2381 ret
= create_thread_poll_set(&events
, 2);
2383 goto error_poll_create
;
2386 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2393 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2395 health_code_update();
2397 /* Infinite blocking call, waiting for transmission */
2398 DBG3("Relayd worker thread polling...");
2399 health_poll_entry();
2400 ret
= lttng_poll_wait(&events
, -1);
2404 * Restart interrupted system call.
2406 if (errno
== EINTR
) {
2415 * Process control. The control connection is
2416 * prioritized so we don't starve it with high
2417 * throughput tracing data on the data connection.
2419 for (i
= 0; i
< nb_fd
; i
++) {
2420 /* Fetch once the poll data */
2421 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2422 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2424 health_code_update();
2428 * No activity for this FD (poll
2434 /* Thread quit pipe has been closed. Killing thread. */
2435 ret
= check_thread_quit_pipe(pollfd
, revents
);
2441 /* Inspect the relay conn pipe for new connection */
2442 if (pollfd
== relay_conn_pipe
[0]) {
2443 if (revents
& LPOLLIN
) {
2444 struct relay_connection
*conn
;
2446 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2450 lttng_poll_add(&events
, conn
->sock
->fd
,
2451 LPOLLIN
| LPOLLRDHUP
);
2452 connection_ht_add(relay_connections_ht
, conn
);
2453 DBG("Connection socket %d added", conn
->sock
->fd
);
2454 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2455 ERR("Relay connection pipe error");
2458 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2462 struct relay_connection
*ctrl_conn
;
2464 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2465 /* If not found, there is a synchronization issue. */
2468 if (ctrl_conn
->type
== RELAY_DATA
) {
2469 if (revents
& LPOLLIN
) {
2471 * Flag the last seen data fd not deleted. It will be
2472 * used as the last seen fd if any fd gets deleted in
2475 last_notdel_data_fd
= pollfd
;
2477 goto put_ctrl_connection
;
2479 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2481 if (revents
& LPOLLIN
) {
2482 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2483 &recv_hdr
, sizeof(recv_hdr
), 0);
2485 /* Connection closed */
2486 relay_thread_close_connection(&events
, pollfd
,
2489 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2491 /* Clear the session on error. */
2492 relay_thread_close_connection(&events
,
2497 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2498 relay_thread_close_connection(&events
,
2500 if (last_seen_data_fd
== pollfd
) {
2501 last_seen_data_fd
= last_notdel_data_fd
;
2504 ERR("Unexpected poll events %u for control sock %d",
2506 connection_put(ctrl_conn
);
2509 put_ctrl_connection
:
2510 connection_put(ctrl_conn
);
2515 * The last loop handled a control request, go back to poll to make
2516 * sure we prioritise the control socket.
2522 if (last_seen_data_fd
>= 0) {
2523 for (i
= 0; i
< nb_fd
; i
++) {
2524 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2526 health_code_update();
2528 if (last_seen_data_fd
== pollfd
) {
2535 /* Process data connection. */
2536 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2537 /* Fetch the poll data. */
2538 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2539 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2540 struct relay_connection
*data_conn
;
2542 health_code_update();
2545 /* No activity for this FD (poll implementation). */
2549 /* Skip the command pipe. It's handled in the first loop. */
2550 if (pollfd
== relay_conn_pipe
[0]) {
2554 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2556 /* Skip it. Might be removed before. */
2559 if (data_conn
->type
== RELAY_CONTROL
) {
2560 goto put_data_connection
;
2562 assert(data_conn
->type
== RELAY_DATA
);
2564 if (revents
& LPOLLIN
) {
2565 ret
= relay_process_data(data_conn
);
2566 /* Connection closed */
2568 relay_thread_close_connection(&events
, pollfd
,
2571 * Every goto restart call sets the last seen fd where
2572 * here we don't really care since we gracefully
2573 * continue the loop after the connection is deleted.
2576 /* Keep last seen port. */
2577 last_seen_data_fd
= pollfd
;
2578 connection_put(data_conn
);
2581 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2582 relay_thread_close_connection(&events
, pollfd
,
2585 ERR("Unknown poll events %u for data sock %d",
2588 put_data_connection
:
2589 connection_put(data_conn
);
2591 last_seen_data_fd
= -1;
2594 /* Normal exit, no error */
2599 /* Cleanup reamaining connection object. */
2601 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2604 health_code_update();
2606 * No need to grab another ref, because we own
2609 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2614 lttng_poll_clean(&events
);
2616 lttng_ht_destroy(relay_connections_ht
);
2617 relay_connections_ht_error
:
2618 /* Close relay conn pipes */
2619 utils_close_pipe(relay_conn_pipe
);
2621 DBG("Thread exited with error");
2623 DBG("Worker thread cleanup complete");
2627 ERR("Health error occurred in %s", __func__
);
2629 health_unregister(health_relayd
);
2630 rcu_unregister_thread();
2631 lttng_relay_stop_threads();
2636 * Create the relay command pipe to wake thread_manage_apps.
2637 * Closed in cleanup().
2639 static int create_relay_conn_pipe(void)
2643 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2651 int main(int argc
, char **argv
)
2653 int ret
= 0, retval
= 0;
2656 /* Parse arguments */
2658 if (set_options(argc
, argv
)) {
2663 if (set_signal_handler()) {
2668 /* Try to create directory if -o, --output is specified. */
2669 if (opt_output_path
) {
2670 if (*opt_output_path
!= '/') {
2671 ERR("Please specify an absolute path for -o, --output PATH");
2676 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2679 ERR("Unable to create %s", opt_output_path
);
2686 if (opt_daemon
|| opt_background
) {
2689 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2697 * We are in the child. Make sure all other file
2698 * descriptors are closed, in case we are called with
2699 * more opened file descriptors than the standard ones.
2701 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2707 /* Initialize thread health monitoring */
2708 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2709 if (!health_relayd
) {
2710 PERROR("health_app_create error");
2712 goto exit_health_app_create
;
2715 /* Create thread quit pipe */
2716 if (init_thread_quit_pipe()) {
2718 goto exit_init_data
;
2721 /* Setup the thread apps communication pipe. */
2722 if (create_relay_conn_pipe()) {
2724 goto exit_init_data
;
2727 /* Init relay command queue. */
2728 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2730 /* Set up max poll set size */
2731 if (lttng_poll_set_max_size()) {
2733 goto exit_init_data
;
2736 /* Initialize communication library */
2738 lttcomm_inet_init();
2740 /* tables of sessions indexed by session ID */
2741 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2744 goto exit_init_data
;
2747 /* tables of streams indexed by stream ID */
2748 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2749 if (!relay_streams_ht
) {
2751 goto exit_init_data
;
2754 /* tables of streams indexed by stream ID */
2755 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2756 if (!viewer_streams_ht
) {
2758 goto exit_init_data
;
2761 ret
= utils_create_pipe(health_quit_pipe
);
2764 goto exit_health_quit_pipe
;
2767 /* Create thread to manage the client socket */
2768 ret
= pthread_create(&health_thread
, NULL
,
2769 thread_manage_health
, (void *) NULL
);
2772 PERROR("pthread_create health");
2774 goto exit_health_thread
;
2777 /* Setup the dispatcher thread */
2778 ret
= pthread_create(&dispatcher_thread
, NULL
,
2779 relay_thread_dispatcher
, (void *) NULL
);
2782 PERROR("pthread_create dispatcher");
2784 goto exit_dispatcher_thread
;
2787 /* Setup the worker thread */
2788 ret
= pthread_create(&worker_thread
, NULL
,
2789 relay_thread_worker
, NULL
);
2792 PERROR("pthread_create worker");
2794 goto exit_worker_thread
;
2797 /* Setup the listener thread */
2798 ret
= pthread_create(&listener_thread
, NULL
,
2799 relay_thread_listener
, (void *) NULL
);
2802 PERROR("pthread_create listener");
2804 goto exit_listener_thread
;
2807 ret
= relayd_live_create(live_uri
);
2809 ERR("Starting live viewer threads");
2815 * This is where we start awaiting program completion (e.g. through
2816 * signal that asks threads to teardown).
2819 ret
= relayd_live_join();
2825 ret
= pthread_join(listener_thread
, &status
);
2828 PERROR("pthread_join listener_thread");
2832 exit_listener_thread
:
2833 ret
= pthread_join(worker_thread
, &status
);
2836 PERROR("pthread_join worker_thread");
2841 ret
= pthread_join(dispatcher_thread
, &status
);
2844 PERROR("pthread_join dispatcher_thread");
2847 exit_dispatcher_thread
:
2849 ret
= pthread_join(health_thread
, &status
);
2852 PERROR("pthread_join health_thread");
2857 utils_close_pipe(health_quit_pipe
);
2858 exit_health_quit_pipe
:
2861 health_app_destroy(health_relayd
);
2862 exit_health_app_create
:
2866 /* Ensure all prior call_rcu are done. */