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("SIGINT caught");
603 if (lttng_relay_stop_threads()) {
604 ERR("Error stopping threads");
608 DBG("SIGTERM caught");
609 if (lttng_relay_stop_threads()) {
610 ERR("Error stopping threads");
614 CMM_STORE_SHARED(recv_child_signal
, 1);
622 * Setup signal handler for :
623 * SIGINT, SIGTERM, SIGPIPE
625 static int set_signal_handler(void)
631 if ((ret
= sigemptyset(&sigset
)) < 0) {
632 PERROR("sigemptyset");
639 sa
.sa_handler
= sighandler
;
640 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
645 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
650 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
655 sa
.sa_handler
= SIG_IGN
;
656 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
661 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
666 void lttng_relay_notify_ready(void)
668 /* Notify the parent of the fork() process that we are ready. */
669 if (opt_daemon
|| opt_background
) {
670 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
671 kill(child_ppid
, SIGUSR1
);
677 * Init thread quit pipe.
679 * Return -1 on error or 0 if all pipes are created.
681 static int init_thread_quit_pipe(void)
685 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
691 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
693 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
697 if (events
== NULL
|| size
== 0) {
702 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
708 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
720 * Check if the thread quit pipe was triggered.
722 * Return 1 if it was triggered else 0;
724 static int check_thread_quit_pipe(int fd
, uint32_t events
)
726 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
734 * Create and init socket from uri.
736 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
739 struct lttcomm_sock
*sock
= NULL
;
741 sock
= lttcomm_alloc_sock_from_uri(uri
);
743 ERR("Allocating socket");
747 ret
= lttcomm_create_sock(sock
);
751 DBG("Listening on sock %d", sock
->fd
);
753 ret
= sock
->ops
->bind(sock
);
758 ret
= sock
->ops
->listen(sock
, -1);
768 lttcomm_destroy_sock(sock
);
774 * This thread manages the listening for new connections on the network
776 static void *relay_thread_listener(void *data
)
778 int i
, ret
, pollfd
, err
= -1;
779 uint32_t revents
, nb_fd
;
780 struct lttng_poll_event events
;
781 struct lttcomm_sock
*control_sock
, *data_sock
;
783 DBG("[thread] Relay listener started");
785 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
787 health_code_update();
789 control_sock
= relay_socket_create(control_uri
);
791 goto error_sock_control
;
794 data_sock
= relay_socket_create(data_uri
);
796 goto error_sock_relay
;
800 * Pass 3 as size here for the thread quit pipe, control and
803 ret
= create_thread_poll_set(&events
, 3);
805 goto error_create_poll
;
808 /* Add the control socket */
809 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
814 /* Add the data socket */
815 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
820 lttng_relay_notify_ready();
822 if (testpoint(relayd_thread_listener
)) {
823 goto error_testpoint
;
827 health_code_update();
829 DBG("Listener accepting connections");
833 ret
= lttng_poll_wait(&events
, -1);
837 * Restart interrupted system call.
839 if (errno
== EINTR
) {
847 DBG("Relay new connection received");
848 for (i
= 0; i
< nb_fd
; i
++) {
849 health_code_update();
851 /* Fetch once the poll data */
852 revents
= LTTNG_POLL_GETEV(&events
, i
);
853 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
857 * No activity for this FD (poll
863 /* Thread quit pipe has been closed. Killing thread. */
864 ret
= check_thread_quit_pipe(pollfd
, revents
);
870 if (revents
& LPOLLIN
) {
872 * A new connection is requested, therefore a
873 * sessiond/consumerd connection is allocated in
874 * this thread, enqueued to a global queue and
875 * dequeued (and freed) in the worker thread.
878 struct relay_connection
*new_conn
;
879 struct lttcomm_sock
*newsock
;
880 enum connection_type type
;
882 if (pollfd
== data_sock
->fd
) {
884 newsock
= data_sock
->ops
->accept(data_sock
);
885 DBG("Relay data connection accepted, socket %d",
888 assert(pollfd
== control_sock
->fd
);
889 type
= RELAY_CONTROL
;
890 newsock
= control_sock
->ops
->accept(control_sock
);
891 DBG("Relay control connection accepted, socket %d",
895 PERROR("accepting sock");
899 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
902 PERROR("setsockopt inet");
903 lttcomm_destroy_sock(newsock
);
906 new_conn
= connection_create(newsock
, type
);
908 lttcomm_destroy_sock(newsock
);
912 /* Enqueue request for the dispatcher thread. */
913 cds_wfcq_enqueue(&relay_conn_queue
.head
, &relay_conn_queue
.tail
,
917 * Wake the dispatch queue futex.
918 * Implicit memory barrier with the
919 * exchange in cds_wfcq_enqueue.
921 futex_nto1_wake(&relay_conn_queue
.futex
);
922 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
923 ERR("socket poll error");
926 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
936 lttng_poll_clean(&events
);
938 if (data_sock
->fd
>= 0) {
939 ret
= data_sock
->ops
->close(data_sock
);
944 lttcomm_destroy_sock(data_sock
);
946 if (control_sock
->fd
>= 0) {
947 ret
= control_sock
->ops
->close(control_sock
);
952 lttcomm_destroy_sock(control_sock
);
956 ERR("Health error occurred in %s", __func__
);
958 health_unregister(health_relayd
);
959 DBG("Relay listener thread cleanup complete");
960 lttng_relay_stop_threads();
965 * This thread manages the dispatching of the requests to worker threads
967 static void *relay_thread_dispatcher(void *data
)
971 struct cds_wfcq_node
*node
;
972 struct relay_connection
*new_conn
= NULL
;
974 DBG("[thread] Relay dispatcher started");
976 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
978 if (testpoint(relayd_thread_dispatcher
)) {
979 goto error_testpoint
;
982 health_code_update();
984 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
985 health_code_update();
987 /* Atomically prepare the queue futex */
988 futex_nto1_prepare(&relay_conn_queue
.futex
);
991 health_code_update();
993 /* Dequeue commands */
994 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
995 &relay_conn_queue
.tail
);
997 DBG("Woken up but nothing in the relay command queue");
998 /* Continue thread execution */
1001 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
1003 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1006 * Inform worker thread of the new request. This
1007 * call is blocking so we can be assured that
1008 * the data will be read at some point in time
1009 * or wait to the end of the world :)
1011 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1013 PERROR("write connection pipe");
1014 connection_put(new_conn
);
1017 } while (node
!= NULL
);
1019 /* Futex wait on queue. Blocking call on futex() */
1020 health_poll_entry();
1021 futex_nto1_wait(&relay_conn_queue
.futex
);
1025 /* Normal exit, no error */
1032 ERR("Health error occurred in %s", __func__
);
1034 health_unregister(health_relayd
);
1035 DBG("Dispatch thread dying");
1036 lttng_relay_stop_threads();
1041 * Set index data from the control port to a given index object.
1043 static int set_index_control_data(struct relay_index
*index
,
1044 struct lttcomm_relayd_index
*data
)
1046 struct ctf_packet_index index_data
;
1049 * The index on disk is encoded in big endian, so we don't need
1050 * to convert the data received on the network. The data_offset
1051 * value is NEVER modified here and is updated by the data
1054 index_data
.packet_size
= data
->packet_size
;
1055 index_data
.content_size
= data
->content_size
;
1056 index_data
.timestamp_begin
= data
->timestamp_begin
;
1057 index_data
.timestamp_end
= data
->timestamp_end
;
1058 index_data
.events_discarded
= data
->events_discarded
;
1059 index_data
.stream_id
= data
->stream_id
;
1060 return relay_index_set_data(index
, &index_data
);
1064 * Handle the RELAYD_CREATE_SESSION command.
1066 * On success, send back the session id or else return a negative value.
1068 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1069 struct relay_connection
*conn
)
1071 int ret
= 0, send_ret
;
1072 struct relay_session
*session
;
1073 struct lttcomm_relayd_status_session reply
;
1074 char session_name
[NAME_MAX
];
1075 char hostname
[HOST_NAME_MAX
];
1076 uint32_t live_timer
= 0;
1077 bool snapshot
= false;
1079 memset(session_name
, 0, NAME_MAX
);
1080 memset(hostname
, 0, HOST_NAME_MAX
);
1082 memset(&reply
, 0, sizeof(reply
));
1084 switch (conn
->minor
) {
1089 case 4: /* LTTng sessiond 2.4 */
1091 ret
= cmd_create_session_2_4(conn
, session_name
,
1092 hostname
, &live_timer
, &snapshot
);
1098 session
= session_create(session_name
, hostname
, live_timer
,
1099 snapshot
, conn
->major
, conn
->minor
);
1104 assert(!conn
->session
);
1105 conn
->session
= session
;
1106 DBG("Created session %" PRIu64
, session
->id
);
1108 reply
.session_id
= htobe64(session
->id
);
1112 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1114 reply
.ret_code
= htobe32(LTTNG_OK
);
1117 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1119 ERR("Relayd sending session id");
1127 * When we have received all the streams and the metadata for a channel,
1128 * we make them visible to the viewer threads.
1130 static void publish_connection_local_streams(struct relay_connection
*conn
)
1132 struct relay_stream
*stream
;
1133 struct relay_session
*session
= conn
->session
;
1136 * We publish all streams belonging to a session atomically wrt
1139 pthread_mutex_lock(&session
->lock
);
1141 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1143 stream_publish(stream
);
1148 * Inform the viewer that there are new streams in the session.
1150 if (session
->viewer_attached
) {
1151 uatomic_set(&session
->new_streams
, 1);
1153 pthread_mutex_unlock(&session
->lock
);
1157 * relay_add_stream: allocate a new stream for a session
1159 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1160 struct relay_connection
*conn
)
1164 struct relay_session
*session
= conn
->session
;
1165 struct relay_stream
*stream
= NULL
;
1166 struct lttcomm_relayd_status_stream reply
;
1167 struct ctf_trace
*trace
= NULL
;
1168 uint64_t stream_handle
= -1ULL;
1169 char *path_name
= NULL
, *channel_name
= NULL
;
1170 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1172 if (!session
|| conn
->version_check_done
== 0) {
1173 ERR("Trying to add a stream before version check");
1175 goto end_no_session
;
1178 switch (session
->minor
) {
1179 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1180 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1183 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1185 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1186 &channel_name
, &tracefile_size
, &tracefile_count
);
1193 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1197 /* This stream here has one reference on the trace. */
1199 pthread_mutex_lock(&last_relay_stream_id_lock
);
1200 stream_handle
= ++last_relay_stream_id
;
1201 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1203 /* We pass ownership of path_name and channel_name. */
1204 stream
= stream_create(trace
, stream_handle
, path_name
,
1205 channel_name
, tracefile_size
, tracefile_count
);
1207 channel_name
= NULL
;
1210 * Streams are the owners of their trace. Reference to trace is
1211 * kept within stream_create().
1213 ctf_trace_put(trace
);
1216 memset(&reply
, 0, sizeof(reply
));
1217 reply
.handle
= htobe64(stream_handle
);
1219 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1221 reply
.ret_code
= htobe32(LTTNG_OK
);
1224 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1225 sizeof(struct lttcomm_relayd_status_stream
), 0);
1227 ERR("Relay sending stream id");
1228 ret
= (int) send_ret
;
1238 * relay_close_stream: close a specific stream
1240 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1241 struct relay_connection
*conn
)
1244 struct relay_session
*session
= conn
->session
;
1245 struct lttcomm_relayd_close_stream stream_info
;
1246 struct lttcomm_relayd_generic_reply reply
;
1247 struct relay_stream
*stream
;
1249 DBG("Close stream received");
1251 if (!session
|| conn
->version_check_done
== 0) {
1252 ERR("Trying to close a stream before version check");
1254 goto end_no_session
;
1257 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1258 sizeof(struct lttcomm_relayd_close_stream
), 0);
1259 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1261 /* Orderly shutdown. Not necessary to print an error. */
1262 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1264 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1267 goto end_no_session
;
1270 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1277 * Set last_net_seq_num before the close flag. Required by data
1280 pthread_mutex_lock(&stream
->lock
);
1281 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1282 pthread_mutex_unlock(&stream
->lock
);
1285 * This is one of the conditions which may trigger a stream close
1286 * with the others being:
1287 * 1) A close command is received for a stream
1288 * 2) The control connection owning the stream is closed
1289 * 3) We have received all of the stream's data _after_ a close
1292 try_stream_close(stream
);
1293 if (stream
->is_metadata
) {
1294 struct relay_viewer_stream
*vstream
;
1296 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1298 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1300 * Since all the metadata has been sent to the
1301 * viewer and that we have a request to close
1302 * its stream, we can safely teardown the
1303 * corresponding metadata viewer stream.
1305 viewer_stream_put(vstream
);
1307 /* Put local reference. */
1308 viewer_stream_put(vstream
);
1314 memset(&reply
, 0, sizeof(reply
));
1316 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1318 reply
.ret_code
= htobe32(LTTNG_OK
);
1320 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1321 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1323 ERR("Relay sending stream id");
1332 * relay_unknown_command: send -1 if received unknown command
1334 static void relay_unknown_command(struct relay_connection
*conn
)
1336 struct lttcomm_relayd_generic_reply reply
;
1339 memset(&reply
, 0, sizeof(reply
));
1340 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1341 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1342 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1344 ERR("Relay sending unknown command");
1349 * relay_start: send an acknowledgment to the client to tell if we are
1350 * ready to receive data. We are ready if a session is established.
1352 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1353 struct relay_connection
*conn
)
1355 int ret
= htobe32(LTTNG_OK
);
1356 struct lttcomm_relayd_generic_reply reply
;
1357 struct relay_session
*session
= conn
->session
;
1360 DBG("Trying to start the streaming without a session established");
1361 ret
= htobe32(LTTNG_ERR_UNK
);
1364 memset(&reply
, 0, sizeof(reply
));
1365 reply
.ret_code
= ret
;
1366 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1367 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1369 ERR("Relay sending start ack");
1376 * Append padding to the file pointed by the file descriptor fd.
1378 static int write_padding_to_file(int fd
, uint32_t size
)
1387 zeros
= zmalloc(size
);
1388 if (zeros
== NULL
) {
1389 PERROR("zmalloc zeros for padding");
1394 ret
= lttng_write(fd
, zeros
, size
);
1396 PERROR("write padding to file");
1406 * relay_recv_metadata: receive the metadata for the session.
1408 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1409 struct relay_connection
*conn
)
1413 struct relay_session
*session
= conn
->session
;
1414 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1415 struct relay_stream
*metadata_stream
;
1416 uint64_t data_size
, payload_size
;
1419 ERR("Metadata sent before version check");
1424 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1425 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1426 ERR("Incorrect data size");
1430 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1432 if (data_buffer_size
< data_size
) {
1433 /* In case the realloc fails, we can free the memory */
1436 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1437 if (!tmp_data_ptr
) {
1438 ERR("Allocating data buffer");
1443 data_buffer
= tmp_data_ptr
;
1444 data_buffer_size
= data_size
;
1446 memset(data_buffer
, 0, data_size
);
1447 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1448 size_ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1449 if (size_ret
< 0 || size_ret
!= data_size
) {
1450 if (size_ret
== 0) {
1451 /* Orderly shutdown. Not necessary to print an error. */
1452 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1454 ERR("Relay didn't receive the whole metadata");
1459 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1461 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1462 if (!metadata_stream
) {
1467 pthread_mutex_lock(&metadata_stream
->lock
);
1469 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1471 if (size_ret
< payload_size
) {
1472 ERR("Relay error writing metadata on file");
1477 size_ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1478 be32toh(metadata_struct
->padding_size
));
1483 metadata_stream
->metadata_received
+=
1484 payload_size
+ be32toh(metadata_struct
->padding_size
);
1485 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1486 metadata_stream
->metadata_received
);
1489 pthread_mutex_unlock(&metadata_stream
->lock
);
1490 stream_put(metadata_stream
);
1496 * relay_send_version: send relayd version number
1498 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1499 struct relay_connection
*conn
)
1502 struct lttcomm_relayd_version reply
, msg
;
1504 conn
->version_check_done
= 1;
1506 /* Get version from the other side. */
1507 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1508 if (ret
< 0 || ret
!= sizeof(msg
)) {
1510 /* Orderly shutdown. Not necessary to print an error. */
1511 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1513 ERR("Relay failed to receive the version values.");
1519 memset(&reply
, 0, sizeof(reply
));
1520 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1521 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1523 /* Major versions must be the same */
1524 if (reply
.major
!= be32toh(msg
.major
)) {
1525 DBG("Incompatible major versions (%u vs %u), deleting session",
1526 reply
.major
, be32toh(msg
.major
));
1527 connection_put(conn
);
1532 conn
->major
= reply
.major
;
1533 /* We adapt to the lowest compatible version */
1534 if (reply
.minor
<= be32toh(msg
.minor
)) {
1535 conn
->minor
= reply
.minor
;
1537 conn
->minor
= be32toh(msg
.minor
);
1540 reply
.major
= htobe32(reply
.major
);
1541 reply
.minor
= htobe32(reply
.minor
);
1542 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1543 sizeof(struct lttcomm_relayd_version
), 0);
1545 ERR("Relay sending version");
1548 DBG("Version check done using protocol %u.%u", conn
->major
,
1556 * Check for data pending for a given stream id from the session daemon.
1558 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1559 struct relay_connection
*conn
)
1561 struct relay_session
*session
= conn
->session
;
1562 struct lttcomm_relayd_data_pending msg
;
1563 struct lttcomm_relayd_generic_reply reply
;
1564 struct relay_stream
*stream
;
1566 uint64_t last_net_seq_num
, stream_id
;
1568 DBG("Data pending command received");
1570 if (!session
|| conn
->version_check_done
== 0) {
1571 ERR("Trying to check for data before version check");
1573 goto end_no_session
;
1576 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1577 if (ret
< sizeof(msg
)) {
1579 /* Orderly shutdown. Not necessary to print an error. */
1580 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1582 ERR("Relay didn't receive valid data_pending struct size : %d",
1586 goto end_no_session
;
1589 stream_id
= be64toh(msg
.stream_id
);
1590 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1592 stream
= stream_get_by_id(stream_id
);
1593 if (stream
== NULL
) {
1598 pthread_mutex_lock(&stream
->lock
);
1600 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1601 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1604 /* Avoid wrapping issue */
1605 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1606 /* Data has in fact been written and is NOT pending */
1609 /* Data still being streamed thus pending */
1613 stream
->data_pending_check_done
= true;
1614 pthread_mutex_unlock(&stream
->lock
);
1619 memset(&reply
, 0, sizeof(reply
));
1620 reply
.ret_code
= htobe32(ret
);
1621 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1623 ERR("Relay data pending ret code failed");
1631 * Wait for the control socket to reach a quiescent state.
1633 * Note that for now, when receiving this command from the session
1634 * daemon, this means that every subsequent commands or data received on
1635 * the control socket has been handled. So, this is why we simply return
1638 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1639 struct relay_connection
*conn
)
1643 struct relay_stream
*stream
;
1644 struct lttcomm_relayd_quiescent_control msg
;
1645 struct lttcomm_relayd_generic_reply reply
;
1647 DBG("Checking quiescent state on control socket");
1649 if (!conn
->session
|| conn
->version_check_done
== 0) {
1650 ERR("Trying to check for data before version check");
1652 goto end_no_session
;
1655 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1656 if (ret
< sizeof(msg
)) {
1658 /* Orderly shutdown. Not necessary to print an error. */
1659 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1661 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1665 goto end_no_session
;
1668 stream_id
= be64toh(msg
.stream_id
);
1669 stream
= stream_get_by_id(stream_id
);
1673 pthread_mutex_lock(&stream
->lock
);
1674 stream
->data_pending_check_done
= true;
1675 pthread_mutex_unlock(&stream
->lock
);
1676 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1679 memset(&reply
, 0, sizeof(reply
));
1680 reply
.ret_code
= htobe32(LTTNG_OK
);
1681 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1683 ERR("Relay data quiescent control ret code failed");
1691 * Initialize a data pending command. This means that a consumer is about
1692 * to ask for data pending for each stream it holds. Simply iterate over
1693 * all streams of a session and set the data_pending_check_done flag.
1695 * This command returns to the client a LTTNG_OK code.
1697 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1698 struct relay_connection
*conn
)
1701 struct lttng_ht_iter iter
;
1702 struct lttcomm_relayd_begin_data_pending msg
;
1703 struct lttcomm_relayd_generic_reply reply
;
1704 struct relay_stream
*stream
;
1705 uint64_t session_id
;
1710 DBG("Init streams for data pending");
1712 if (!conn
->session
|| conn
->version_check_done
== 0) {
1713 ERR("Trying to check for data before version check");
1715 goto end_no_session
;
1718 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1719 if (ret
< sizeof(msg
)) {
1721 /* Orderly shutdown. Not necessary to print an error. */
1722 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1724 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1728 goto end_no_session
;
1731 session_id
= be64toh(msg
.session_id
);
1734 * Iterate over all streams to set the begin data pending flag.
1735 * For now, the streams are indexed by stream handle so we have
1736 * to iterate over all streams to find the one associated with
1737 * the right session_id.
1740 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1742 if (!stream_get(stream
)) {
1745 if (stream
->trace
->session
->id
== session_id
) {
1746 pthread_mutex_lock(&stream
->lock
);
1747 stream
->data_pending_check_done
= false;
1748 pthread_mutex_unlock(&stream
->lock
);
1749 DBG("Set begin data pending flag to stream %" PRIu64
,
1750 stream
->stream_handle
);
1756 memset(&reply
, 0, sizeof(reply
));
1757 /* All good, send back reply. */
1758 reply
.ret_code
= htobe32(LTTNG_OK
);
1760 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1762 ERR("Relay begin data pending send reply failed");
1770 * End data pending command. This will check, for a given session id, if
1771 * each stream associated with it has its data_pending_check_done flag
1772 * set. If not, this means that the client lost track of the stream but
1773 * the data is still being streamed on our side. In this case, we inform
1774 * the client that data is in flight.
1776 * Return to the client if there is data in flight or not with a ret_code.
1778 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1779 struct relay_connection
*conn
)
1782 struct lttng_ht_iter iter
;
1783 struct lttcomm_relayd_end_data_pending msg
;
1784 struct lttcomm_relayd_generic_reply reply
;
1785 struct relay_stream
*stream
;
1786 uint64_t session_id
;
1787 uint32_t is_data_inflight
= 0;
1789 DBG("End data pending command");
1791 if (!conn
->session
|| conn
->version_check_done
== 0) {
1792 ERR("Trying to check for data before version check");
1794 goto end_no_session
;
1797 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1798 if (ret
< sizeof(msg
)) {
1800 /* Orderly shutdown. Not necessary to print an error. */
1801 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1803 ERR("Relay didn't receive valid end data_pending struct size: %d",
1807 goto end_no_session
;
1810 session_id
= be64toh(msg
.session_id
);
1813 * Iterate over all streams to see if the begin data pending
1817 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1819 if (!stream_get(stream
)) {
1822 if (stream
->trace
->session
->id
!= session_id
) {
1826 pthread_mutex_lock(&stream
->lock
);
1827 if (!stream
->data_pending_check_done
) {
1828 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1829 is_data_inflight
= 1;
1830 DBG("Data is still in flight for stream %" PRIu64
,
1831 stream
->stream_handle
);
1832 pthread_mutex_unlock(&stream
->lock
);
1837 pthread_mutex_unlock(&stream
->lock
);
1842 memset(&reply
, 0, sizeof(reply
));
1843 /* All good, send back reply. */
1844 reply
.ret_code
= htobe32(is_data_inflight
);
1846 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1848 ERR("Relay end data pending send reply failed");
1856 * Receive an index for a specific stream.
1858 * Return 0 on success else a negative value.
1860 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1861 struct relay_connection
*conn
)
1864 struct relay_session
*session
= conn
->session
;
1865 struct lttcomm_relayd_index index_info
;
1866 struct relay_index
*index
;
1867 struct lttcomm_relayd_generic_reply reply
;
1868 struct relay_stream
*stream
;
1869 uint64_t net_seq_num
;
1873 DBG("Relay receiving index");
1875 if (!session
|| conn
->version_check_done
== 0) {
1876 ERR("Trying to close a stream before version check");
1878 goto end_no_session
;
1881 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1882 sizeof(index_info
), 0);
1883 if (ret
< sizeof(index_info
)) {
1885 /* Orderly shutdown. Not necessary to print an error. */
1886 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1888 ERR("Relay didn't receive valid index struct size : %d", ret
);
1891 goto end_no_session
;
1894 net_seq_num
= be64toh(index_info
.net_seq_num
);
1896 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1898 ERR("stream_get_by_id not found");
1902 pthread_mutex_lock(&stream
->lock
);
1904 /* Live beacon handling */
1905 if (index_info
.packet_size
== 0) {
1906 DBG("Received live beacon for stream %" PRIu64
,
1907 stream
->stream_handle
);
1910 * Only flag a stream inactive when it has already
1911 * received data and no indexes are in flight.
1913 if (stream
->index_received_seqcount
> 0
1914 && stream
->indexes_in_flight
== 0) {
1915 stream
->beacon_ts_end
=
1916 be64toh(index_info
.timestamp_end
);
1919 goto end_stream_put
;
1921 stream
->beacon_ts_end
= -1ULL;
1924 if (stream
->ctf_stream_id
== -1ULL) {
1925 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1927 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1930 ERR("relay_index_get_by_id_or_create index NULL");
1931 goto end_stream_put
;
1933 if (set_index_control_data(index
, &index_info
)) {
1934 ERR("set_index_control_data error");
1935 relay_index_put(index
);
1937 goto end_stream_put
;
1939 ret
= relay_index_try_flush(index
);
1941 tracefile_array_commit_seq(stream
->tfa
);
1942 stream
->index_received_seqcount
++;
1943 } else if (ret
> 0) {
1947 ERR("relay_index_try_flush error %d", ret
);
1948 relay_index_put(index
);
1953 pthread_mutex_unlock(&stream
->lock
);
1958 memset(&reply
, 0, sizeof(reply
));
1960 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1962 reply
.ret_code
= htobe32(LTTNG_OK
);
1964 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1966 ERR("Relay sending close index id reply");
1975 * Receive the streams_sent message.
1977 * Return 0 on success else a negative value.
1979 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1980 struct relay_connection
*conn
)
1983 struct lttcomm_relayd_generic_reply reply
;
1987 DBG("Relay receiving streams_sent");
1989 if (!conn
->session
|| conn
->version_check_done
== 0) {
1990 ERR("Trying to close a stream before version check");
1992 goto end_no_session
;
1996 * Publish every pending stream in the connection recv list which are
1997 * now ready to be used by the viewer.
1999 publish_connection_local_streams(conn
);
2001 memset(&reply
, 0, sizeof(reply
));
2002 reply
.ret_code
= htobe32(LTTNG_OK
);
2003 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
2005 ERR("Relay sending sent_stream reply");
2017 * Process the commands received on the control socket
2019 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2020 struct relay_connection
*conn
)
2024 switch (be32toh(recv_hdr
->cmd
)) {
2025 case RELAYD_CREATE_SESSION
:
2026 ret
= relay_create_session(recv_hdr
, conn
);
2028 case RELAYD_ADD_STREAM
:
2029 ret
= relay_add_stream(recv_hdr
, conn
);
2031 case RELAYD_START_DATA
:
2032 ret
= relay_start(recv_hdr
, conn
);
2034 case RELAYD_SEND_METADATA
:
2035 ret
= relay_recv_metadata(recv_hdr
, conn
);
2037 case RELAYD_VERSION
:
2038 ret
= relay_send_version(recv_hdr
, conn
);
2040 case RELAYD_CLOSE_STREAM
:
2041 ret
= relay_close_stream(recv_hdr
, conn
);
2043 case RELAYD_DATA_PENDING
:
2044 ret
= relay_data_pending(recv_hdr
, conn
);
2046 case RELAYD_QUIESCENT_CONTROL
:
2047 ret
= relay_quiescent_control(recv_hdr
, conn
);
2049 case RELAYD_BEGIN_DATA_PENDING
:
2050 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2052 case RELAYD_END_DATA_PENDING
:
2053 ret
= relay_end_data_pending(recv_hdr
, conn
);
2055 case RELAYD_SEND_INDEX
:
2056 ret
= relay_recv_index(recv_hdr
, conn
);
2058 case RELAYD_STREAMS_SENT
:
2059 ret
= relay_streams_sent(recv_hdr
, conn
);
2061 case RELAYD_UPDATE_SYNC_INFO
:
2063 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2064 relay_unknown_command(conn
);
2074 * Handle index for a data stream.
2076 * Called with the stream lock held.
2078 * Return 0 on success else a negative value.
2080 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2084 uint64_t data_offset
;
2085 struct relay_index
*index
;
2087 /* Get data offset because we are about to update the index. */
2088 data_offset
= htobe64(stream
->tracefile_size_current
);
2090 DBG("handle_index_data: stream %" PRIu64
" net_seq_num %" PRIu64
" data offset %" PRIu64
,
2091 stream
->stream_handle
, net_seq_num
, stream
->tracefile_size_current
);
2094 * Lookup for an existing index for that stream id/sequence
2095 * number. If it exists, the control thread has already received the
2096 * data for it, thus we need to write it to disk.
2098 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2104 if (rotate_index
|| !stream
->index_fd
) {
2107 /* Put ref on previous index_fd. */
2108 if (stream
->index_fd
) {
2109 stream_fd_put(stream
->index_fd
);
2110 stream
->index_fd
= NULL
;
2113 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2114 -1, -1, stream
->tracefile_size
,
2115 tracefile_array_get_file_index_head(stream
->tfa
));
2118 /* Put self-ref for this index due to error. */
2119 relay_index_put(index
);
2122 stream
->index_fd
= stream_fd_create(fd
);
2123 if (!stream
->index_fd
) {
2126 PERROR("Error closing FD %d", fd
);
2128 /* Put self-ref for this index due to error. */
2129 relay_index_put(index
);
2130 /* Will put the local ref. */
2135 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2137 /* Put self-ref for this index due to error. */
2138 relay_index_put(index
);
2142 ret
= relay_index_try_flush(index
);
2144 tracefile_array_commit_seq(stream
->tfa
);
2145 stream
->index_received_seqcount
++;
2146 } else if (ret
> 0) {
2150 /* Put self-ref for this index due to error. */
2151 relay_index_put(index
);
2159 * relay_process_data: Process the data received on the data socket
2161 static int relay_process_data(struct relay_connection
*conn
)
2163 int ret
= 0, rotate_index
= 0;
2165 struct relay_stream
*stream
;
2166 struct lttcomm_relayd_data_hdr data_hdr
;
2168 uint64_t net_seq_num
;
2170 struct relay_session
*session
;
2171 bool new_stream
= false, close_requested
= false;
2172 size_t chunk_size
= RECV_DATA_BUFFER_SIZE
;
2173 size_t recv_off
= 0;
2174 char data_buffer
[chunk_size
];
2176 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2177 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2180 /* Orderly shutdown. Not necessary to print an error. */
2181 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2183 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2189 stream_id
= be64toh(data_hdr
.stream_id
);
2190 stream
= stream_get_by_id(stream_id
);
2192 ERR("relay_process_data: Cannot find stream %" PRIu64
, stream_id
);
2196 session
= stream
->trace
->session
;
2197 data_size
= be32toh(data_hdr
.data_size
);
2199 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2201 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2202 data_size
, stream_id
, net_seq_num
);
2204 pthread_mutex_lock(&stream
->lock
);
2206 /* Check if a rotation is needed. */
2207 if (stream
->tracefile_size
> 0 &&
2208 (stream
->tracefile_size_current
+ data_size
) >
2209 stream
->tracefile_size
) {
2210 uint64_t old_id
, new_id
;
2212 old_id
= tracefile_array_get_file_index_head(stream
->tfa
);
2213 tracefile_array_file_rotate(stream
->tfa
);
2215 /* new_id is updated by utils_rotate_stream_file. */
2218 ret
= utils_rotate_stream_file(stream
->path_name
,
2219 stream
->channel_name
, stream
->tracefile_size
,
2220 stream
->tracefile_count
, -1,
2221 -1, stream
->stream_fd
->fd
,
2222 &new_id
, &stream
->stream_fd
->fd
);
2224 ERR("Rotating stream output file");
2225 goto end_stream_unlock
;
2228 * Reset current size because we just performed a stream
2231 stream
->tracefile_size_current
= 0;
2236 * Index are handled in protocol version 2.4 and above. Also,
2237 * snapshot and index are NOT supported.
2239 if (session
->minor
>= 4 && !session
->snapshot
) {
2240 ret
= handle_index_data(stream
, net_seq_num
, rotate_index
);
2242 ERR("handle_index_data: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2243 stream
->stream_handle
, net_seq_num
, ret
);
2244 goto end_stream_unlock
;
2248 for (recv_off
= 0; recv_off
< data_size
; recv_off
+= chunk_size
) {
2249 size_t recv_size
= min(data_size
- recv_off
, chunk_size
);
2251 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, recv_size
, 0);
2254 /* Orderly shutdown. Not necessary to print an error. */
2255 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2257 ERR("Socket %d error %d", conn
->sock
->fd
, ret
);
2260 goto end_stream_unlock
;
2263 /* Write data to stream output fd. */
2264 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
,
2266 if (size_ret
< recv_size
) {
2267 ERR("Relay error writing data to file");
2269 goto end_stream_unlock
;
2272 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2273 size_ret
, stream
->stream_handle
);
2276 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2277 be32toh(data_hdr
.padding_size
));
2279 ERR("write_padding_to_file: fail stream %" PRIu64
" net_seq_num %" PRIu64
" ret %d",
2280 stream
->stream_handle
, net_seq_num
, ret
);
2281 goto end_stream_unlock
;
2283 stream
->tracefile_size_current
+=
2284 data_size
+ be32toh(data_hdr
.padding_size
);
2285 if (stream
->prev_seq
== -1ULL) {
2289 stream
->prev_seq
= net_seq_num
;
2292 close_requested
= stream
->close_requested
;
2293 pthread_mutex_unlock(&stream
->lock
);
2294 if (close_requested
) {
2295 try_stream_close(stream
);
2299 pthread_mutex_lock(&session
->lock
);
2300 uatomic_set(&session
->new_streams
, 1);
2301 pthread_mutex_unlock(&session
->lock
);
2308 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2312 (void) lttng_poll_del(events
, pollfd
);
2314 ret
= close(pollfd
);
2316 ERR("Closing pollfd %d", pollfd
);
2320 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2321 int pollfd
, struct relay_connection
*conn
)
2323 const char *type_str
;
2325 switch (conn
->type
) {
2330 type_str
= "Control";
2332 case RELAY_VIEWER_COMMAND
:
2333 type_str
= "Viewer Command";
2335 case RELAY_VIEWER_NOTIFICATION
:
2336 type_str
= "Viewer Notification";
2339 type_str
= "Unknown";
2341 cleanup_connection_pollfd(events
, pollfd
);
2342 connection_put(conn
);
2343 DBG("%s connection closed with %d", type_str
, pollfd
);
2347 * This thread does the actual work
2349 static void *relay_thread_worker(void *data
)
2351 int ret
, err
= -1, last_seen_data_fd
= -1;
2353 struct lttng_poll_event events
;
2354 struct lttng_ht
*relay_connections_ht
;
2355 struct lttng_ht_iter iter
;
2356 struct lttcomm_relayd_hdr recv_hdr
;
2357 struct relay_connection
*destroy_conn
= NULL
;
2359 DBG("[thread] Relay worker started");
2361 rcu_register_thread();
2363 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2365 if (testpoint(relayd_thread_worker
)) {
2366 goto error_testpoint
;
2369 health_code_update();
2371 /* table of connections indexed on socket */
2372 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2373 if (!relay_connections_ht
) {
2374 goto relay_connections_ht_error
;
2377 ret
= create_thread_poll_set(&events
, 2);
2379 goto error_poll_create
;
2382 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2389 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2391 health_code_update();
2393 /* Infinite blocking call, waiting for transmission */
2394 DBG3("Relayd worker thread polling...");
2395 health_poll_entry();
2396 ret
= lttng_poll_wait(&events
, -1);
2400 * Restart interrupted system call.
2402 if (errno
== EINTR
) {
2411 * Process control. The control connection is
2412 * prioritized so we don't starve it with high
2413 * throughput tracing data on the data connection.
2415 for (i
= 0; i
< nb_fd
; i
++) {
2416 /* Fetch once the poll data */
2417 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2418 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2420 health_code_update();
2424 * No activity for this FD (poll
2430 /* Thread quit pipe has been closed. Killing thread. */
2431 ret
= check_thread_quit_pipe(pollfd
, revents
);
2437 /* Inspect the relay conn pipe for new connection */
2438 if (pollfd
== relay_conn_pipe
[0]) {
2439 if (revents
& LPOLLIN
) {
2440 struct relay_connection
*conn
;
2442 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2446 lttng_poll_add(&events
, conn
->sock
->fd
,
2447 LPOLLIN
| LPOLLRDHUP
);
2448 connection_ht_add(relay_connections_ht
, conn
);
2449 DBG("Connection socket %d added", conn
->sock
->fd
);
2450 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2451 ERR("Relay connection pipe error");
2454 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2458 struct relay_connection
*ctrl_conn
;
2460 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2461 /* If not found, there is a synchronization issue. */
2464 if (ctrl_conn
->type
== RELAY_DATA
) {
2465 if (revents
& LPOLLIN
) {
2467 * Flag the last seen data fd not deleted. It will be
2468 * used as the last seen fd if any fd gets deleted in
2471 last_notdel_data_fd
= pollfd
;
2473 goto put_ctrl_connection
;
2475 assert(ctrl_conn
->type
== RELAY_CONTROL
);
2477 if (revents
& LPOLLIN
) {
2478 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
,
2479 &recv_hdr
, sizeof(recv_hdr
), 0);
2481 /* Connection closed */
2482 relay_thread_close_connection(&events
, pollfd
,
2485 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2487 /* Clear the session on error. */
2488 relay_thread_close_connection(&events
,
2493 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2494 relay_thread_close_connection(&events
,
2496 if (last_seen_data_fd
== pollfd
) {
2497 last_seen_data_fd
= last_notdel_data_fd
;
2500 ERR("Unexpected poll events %u for control sock %d",
2502 connection_put(ctrl_conn
);
2505 put_ctrl_connection
:
2506 connection_put(ctrl_conn
);
2511 * The last loop handled a control request, go back to poll to make
2512 * sure we prioritise the control socket.
2518 if (last_seen_data_fd
>= 0) {
2519 for (i
= 0; i
< nb_fd
; i
++) {
2520 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2522 health_code_update();
2524 if (last_seen_data_fd
== pollfd
) {
2531 /* Process data connection. */
2532 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2533 /* Fetch the poll data. */
2534 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2535 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2536 struct relay_connection
*data_conn
;
2538 health_code_update();
2541 /* No activity for this FD (poll implementation). */
2545 /* Skip the command pipe. It's handled in the first loop. */
2546 if (pollfd
== relay_conn_pipe
[0]) {
2550 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2552 /* Skip it. Might be removed before. */
2555 if (data_conn
->type
== RELAY_CONTROL
) {
2556 goto put_data_connection
;
2558 assert(data_conn
->type
== RELAY_DATA
);
2560 if (revents
& LPOLLIN
) {
2561 ret
= relay_process_data(data_conn
);
2562 /* Connection closed */
2564 relay_thread_close_connection(&events
, pollfd
,
2567 * Every goto restart call sets the last seen fd where
2568 * here we don't really care since we gracefully
2569 * continue the loop after the connection is deleted.
2572 /* Keep last seen port. */
2573 last_seen_data_fd
= pollfd
;
2574 connection_put(data_conn
);
2577 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2578 relay_thread_close_connection(&events
, pollfd
,
2581 ERR("Unknown poll events %u for data sock %d",
2584 put_data_connection
:
2585 connection_put(data_conn
);
2587 last_seen_data_fd
= -1;
2590 /* Normal exit, no error */
2595 /* Cleanup reamaining connection object. */
2597 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2600 health_code_update();
2602 * No need to grab another ref, because we own
2605 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2610 lttng_poll_clean(&events
);
2612 lttng_ht_destroy(relay_connections_ht
);
2613 relay_connections_ht_error
:
2614 /* Close relay conn pipes */
2615 utils_close_pipe(relay_conn_pipe
);
2617 DBG("Thread exited with error");
2619 DBG("Worker thread cleanup complete");
2623 ERR("Health error occurred in %s", __func__
);
2625 health_unregister(health_relayd
);
2626 rcu_unregister_thread();
2627 lttng_relay_stop_threads();
2632 * Create the relay command pipe to wake thread_manage_apps.
2633 * Closed in cleanup().
2635 static int create_relay_conn_pipe(void)
2639 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2647 int main(int argc
, char **argv
)
2649 int ret
= 0, retval
= 0;
2652 /* Parse arguments */
2654 if (set_options(argc
, argv
)) {
2659 if (set_signal_handler()) {
2664 /* Try to create directory if -o, --output is specified. */
2665 if (opt_output_path
) {
2666 if (*opt_output_path
!= '/') {
2667 ERR("Please specify an absolute path for -o, --output PATH");
2672 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2675 ERR("Unable to create %s", opt_output_path
);
2682 if (opt_daemon
|| opt_background
) {
2685 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2693 * We are in the child. Make sure all other file
2694 * descriptors are closed, in case we are called with
2695 * more opened file descriptors than the standard ones.
2697 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2703 /* Initialize thread health monitoring */
2704 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2705 if (!health_relayd
) {
2706 PERROR("health_app_create error");
2708 goto exit_health_app_create
;
2711 /* Create thread quit pipe */
2712 if (init_thread_quit_pipe()) {
2714 goto exit_init_data
;
2717 /* Setup the thread apps communication pipe. */
2718 if (create_relay_conn_pipe()) {
2720 goto exit_init_data
;
2723 /* Init relay command queue. */
2724 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2726 /* Set up max poll set size */
2727 if (lttng_poll_set_max_size()) {
2729 goto exit_init_data
;
2732 /* Initialize communication library */
2734 lttcomm_inet_init();
2736 /* tables of sessions indexed by session ID */
2737 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2740 goto exit_init_data
;
2743 /* tables of streams indexed by stream ID */
2744 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2745 if (!relay_streams_ht
) {
2747 goto exit_init_data
;
2750 /* tables of streams indexed by stream ID */
2751 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2752 if (!viewer_streams_ht
) {
2754 goto exit_init_data
;
2757 ret
= utils_create_pipe(health_quit_pipe
);
2760 goto exit_health_quit_pipe
;
2763 /* Create thread to manage the client socket */
2764 ret
= pthread_create(&health_thread
, NULL
,
2765 thread_manage_health
, (void *) NULL
);
2768 PERROR("pthread_create health");
2770 goto exit_health_thread
;
2773 /* Setup the dispatcher thread */
2774 ret
= pthread_create(&dispatcher_thread
, NULL
,
2775 relay_thread_dispatcher
, (void *) NULL
);
2778 PERROR("pthread_create dispatcher");
2780 goto exit_dispatcher_thread
;
2783 /* Setup the worker thread */
2784 ret
= pthread_create(&worker_thread
, NULL
,
2785 relay_thread_worker
, NULL
);
2788 PERROR("pthread_create worker");
2790 goto exit_worker_thread
;
2793 /* Setup the listener thread */
2794 ret
= pthread_create(&listener_thread
, NULL
,
2795 relay_thread_listener
, (void *) NULL
);
2798 PERROR("pthread_create listener");
2800 goto exit_listener_thread
;
2803 ret
= relayd_live_create(live_uri
);
2805 ERR("Starting live viewer threads");
2811 * This is where we start awaiting program completion (e.g. through
2812 * signal that asks threads to teardown).
2815 ret
= relayd_live_join();
2821 ret
= pthread_join(listener_thread
, &status
);
2824 PERROR("pthread_join listener_thread");
2828 exit_listener_thread
:
2829 ret
= pthread_join(worker_thread
, &status
);
2832 PERROR("pthread_join worker_thread");
2837 ret
= pthread_join(dispatcher_thread
, &status
);
2840 PERROR("pthread_join dispatcher_thread");
2843 exit_dispatcher_thread
:
2845 ret
= pthread_join(health_thread
, &status
);
2848 PERROR("pthread_join health_thread");
2853 utils_close_pipe(health_quit_pipe
);
2854 exit_health_quit_pipe
:
2857 health_app_destroy(health_relayd
);
2858 exit_health_app_create
:
2862 /* Ensure all prior call_rcu are done. */