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
;
86 static int recv_child_signal
; /* Set to 1 when a SIGUSR1 signal is received. */
87 static pid_t child_ppid
; /* Internal parent PID use with daemonize. */
89 static struct lttng_uri
*control_uri
;
90 static struct lttng_uri
*data_uri
;
91 static struct lttng_uri
*live_uri
;
95 const char *tracing_group_name
= DEFAULT_TRACING_GROUP
;
96 static int tracing_group_name_override
;
98 const char * const config_section_name
= "relayd";
101 * Quit pipe for all threads. This permits a single cancellation point
102 * for all threads when receiving an event on the pipe.
104 int thread_quit_pipe
[2] = { -1, -1 };
107 * This pipe is used to inform the worker thread that a command is queued and
108 * ready to be processed.
110 static int relay_conn_pipe
[2] = { -1, -1 };
112 /* Shared between threads */
113 static int dispatch_thread_exit
;
115 static pthread_t listener_thread
;
116 static pthread_t dispatcher_thread
;
117 static pthread_t worker_thread
;
118 static pthread_t health_thread
;
121 * last_relay_stream_id_lock protects last_relay_stream_id increment
122 * atomicity on 32-bit architectures.
124 static pthread_mutex_t last_relay_stream_id_lock
= PTHREAD_MUTEX_INITIALIZER
;
125 static uint64_t last_relay_stream_id
;
128 * Relay command queue.
130 * The relay_thread_listener and relay_thread_dispatcher communicate with this
133 static struct relay_conn_queue relay_conn_queue
;
135 /* buffer allocated at startup, used to store the trace data */
136 static char *data_buffer
;
137 static unsigned int data_buffer_size
;
139 /* Global relay stream hash table. */
140 struct lttng_ht
*relay_streams_ht
;
142 /* Global relay viewer stream hash table. */
143 struct lttng_ht
*viewer_streams_ht
;
145 /* Global relay sessions hash table. */
146 struct lttng_ht
*sessions_ht
;
148 /* Relayd health monitoring */
149 struct health_app
*health_relayd
;
151 static struct option long_options
[] = {
152 { "control-port", 1, 0, 'C', },
153 { "data-port", 1, 0, 'D', },
154 { "live-port", 1, 0, 'L', },
155 { "daemonize", 0, 0, 'd', },
156 { "background", 0, 0, 'b', },
157 { "group", 1, 0, 'g', },
158 { "help", 0, 0, 'h', },
159 { "output", 1, 0, 'o', },
160 { "verbose", 0, 0, 'v', },
161 { "config", 1, 0, 'f' },
165 static const char *config_ignore_options
[] = { "help", "config" };
168 * usage function on stderr
170 static void usage(void)
172 fprintf(stderr
, "Usage: %s OPTIONS\n\nOptions:\n", progname
);
173 fprintf(stderr
, " -h, --help Display this usage.\n");
174 fprintf(stderr
, " -d, --daemonize Start as a daemon.\n");
175 fprintf(stderr
, " -b, --background Start as a daemon, keeping console open.\n");
176 fprintf(stderr
, " -C, --control-port URL Control port listening.\n");
177 fprintf(stderr
, " -D, --data-port URL Data port listening.\n");
178 fprintf(stderr
, " -L, --live-port URL Live view port listening.\n");
179 fprintf(stderr
, " -o, --output PATH Output path for traces. Must use an absolute path.\n");
180 fprintf(stderr
, " -v, --verbose Verbose mode. Activate DBG() macro.\n");
181 fprintf(stderr
, " -g, --group NAME Specify the tracing group name. (default: tracing)\n");
182 fprintf(stderr
, " -f --config Load daemon configuration file\n");
186 * Take an option from the getopt output and set it in the right variable to be
189 * Return 0 on success else a negative value.
191 static int set_option(int opt
, const char *arg
, const char *optname
)
197 fprintf(stderr
, "option %s", optname
);
199 fprintf(stderr
, " with arg %s\n", arg
);
203 if (lttng_is_setuid_setgid()) {
204 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
205 "-C, --control-port");
207 ret
= uri_parse(arg
, &control_uri
);
209 ERR("Invalid control URI specified");
212 if (control_uri
->port
== 0) {
213 control_uri
->port
= DEFAULT_NETWORK_CONTROL_PORT
;
218 if (lttng_is_setuid_setgid()) {
219 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
222 ret
= uri_parse(arg
, &data_uri
);
224 ERR("Invalid data URI specified");
227 if (data_uri
->port
== 0) {
228 data_uri
->port
= DEFAULT_NETWORK_DATA_PORT
;
233 if (lttng_is_setuid_setgid()) {
234 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
237 ret
= uri_parse(arg
, &live_uri
);
239 ERR("Invalid live URI specified");
242 if (live_uri
->port
== 0) {
243 live_uri
->port
= DEFAULT_NETWORK_VIEWER_PORT
;
254 if (lttng_is_setuid_setgid()) {
255 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
258 tracing_group_name
= strdup(arg
);
259 if (tracing_group_name
== NULL
) {
264 tracing_group_name_override
= 1;
271 if (lttng_is_setuid_setgid()) {
272 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
275 ret
= asprintf(&opt_output_path
, "%s", arg
);
278 PERROR("asprintf opt_output_path");
284 /* Verbose level can increase using multiple -v */
286 lttng_opt_verbose
= config_parse_value(arg
);
288 /* Only 3 level of verbosity (-vvv). */
289 if (lttng_opt_verbose
< 3) {
290 lttng_opt_verbose
+= 1;
295 /* Unknown option or other error.
296 * Error is printed by getopt, just return */
309 * config_entry_handler_cb used to handle options read from a config file.
310 * See config_entry_handler_cb comment in common/config/config.h for the
311 * return value conventions.
313 static int config_entry_handler(const struct config_entry
*entry
, void *unused
)
317 if (!entry
|| !entry
->name
|| !entry
->value
) {
322 /* Check if the option is to be ignored */
323 for (i
= 0; i
< sizeof(config_ignore_options
) / sizeof(char *); i
++) {
324 if (!strcmp(entry
->name
, config_ignore_options
[i
])) {
329 for (i
= 0; i
< (sizeof(long_options
) / sizeof(struct option
)) - 1; i
++) {
330 /* Ignore if entry name is not fully matched. */
331 if (strcmp(entry
->name
, long_options
[i
].name
)) {
336 * If the option takes no argument on the command line,
337 * we have to check if the value is "true". We support
338 * non-zero numeric values, true, on and yes.
340 if (!long_options
[i
].has_arg
) {
341 ret
= config_parse_value(entry
->value
);
344 WARN("Invalid configuration value \"%s\" for option %s",
345 entry
->value
, entry
->name
);
347 /* False, skip boolean config option. */
352 ret
= set_option(long_options
[i
].val
, entry
->value
, entry
->name
);
356 WARN("Unrecognized option \"%s\" in daemon configuration file.",
363 static int set_options(int argc
, char **argv
)
365 int c
, ret
= 0, option_index
= 0, retval
= 0;
366 int orig_optopt
= optopt
, orig_optind
= optind
;
367 char *default_address
, *optstring
;
368 const char *config_path
= NULL
;
370 optstring
= utils_generate_optstring(long_options
,
371 sizeof(long_options
) / sizeof(struct option
));
377 /* Check for the --config option */
379 while ((c
= getopt_long(argc
, argv
, optstring
, long_options
,
380 &option_index
)) != -1) {
384 } else if (c
!= 'f') {
388 if (lttng_is_setuid_setgid()) {
389 WARN("Getting '%s' argument from setuid/setgid binary refused for security reasons.",
392 config_path
= utils_expand_path(optarg
);
394 ERR("Failed to resolve path: %s", optarg
);
399 ret
= config_get_section_entries(config_path
, config_section_name
,
400 config_entry_handler
, NULL
);
403 ERR("Invalid configuration option at line %i", ret
);
409 /* Reset getopt's global state */
410 optopt
= orig_optopt
;
411 optind
= orig_optind
;
413 c
= getopt_long(argc
, argv
, optstring
, long_options
, &option_index
);
418 ret
= set_option(c
, optarg
, long_options
[option_index
].name
);
425 /* assign default values */
426 if (control_uri
== NULL
) {
427 ret
= asprintf(&default_address
,
428 "tcp://" DEFAULT_NETWORK_CONTROL_BIND_ADDRESS
":%d",
429 DEFAULT_NETWORK_CONTROL_PORT
);
431 PERROR("asprintf default data address");
436 ret
= uri_parse(default_address
, &control_uri
);
437 free(default_address
);
439 ERR("Invalid control URI specified");
444 if (data_uri
== NULL
) {
445 ret
= asprintf(&default_address
,
446 "tcp://" DEFAULT_NETWORK_DATA_BIND_ADDRESS
":%d",
447 DEFAULT_NETWORK_DATA_PORT
);
449 PERROR("asprintf default data address");
454 ret
= uri_parse(default_address
, &data_uri
);
455 free(default_address
);
457 ERR("Invalid data URI specified");
462 if (live_uri
== NULL
) {
463 ret
= asprintf(&default_address
,
464 "tcp://" DEFAULT_NETWORK_VIEWER_BIND_ADDRESS
":%d",
465 DEFAULT_NETWORK_VIEWER_PORT
);
467 PERROR("asprintf default viewer control address");
472 ret
= uri_parse(default_address
, &live_uri
);
473 free(default_address
);
475 ERR("Invalid viewer control URI specified");
486 static void print_global_objects(void)
488 rcu_register_thread();
490 print_viewer_streams();
491 print_relay_streams();
494 rcu_unregister_thread();
500 static void relayd_cleanup(void)
502 print_global_objects();
506 if (viewer_streams_ht
)
507 lttng_ht_destroy(viewer_streams_ht
);
508 if (relay_streams_ht
)
509 lttng_ht_destroy(relay_streams_ht
);
511 lttng_ht_destroy(sessions_ht
);
513 /* free the dynamically allocated opt_output_path */
514 free(opt_output_path
);
516 /* Close thread quit pipes */
517 utils_close_pipe(thread_quit_pipe
);
519 uri_free(control_uri
);
521 /* Live URI is freed in the live thread. */
523 if (tracing_group_name_override
) {
524 free((void *) tracing_group_name
);
529 * Write to writable pipe used to notify a thread.
531 static int notify_thread_pipe(int wpipe
)
535 ret
= lttng_write(wpipe
, "!", 1);
537 PERROR("write poll pipe");
545 static int notify_health_quit_pipe(int *pipe
)
549 ret
= lttng_write(pipe
[1], "4", 1);
551 PERROR("write relay health quit");
560 * Stop all relayd and relayd-live threads.
562 int lttng_relay_stop_threads(void)
566 /* Stopping all threads */
567 DBG("Terminating all threads");
568 if (notify_thread_pipe(thread_quit_pipe
[1])) {
569 ERR("write error on thread quit pipe");
573 if (notify_health_quit_pipe(health_quit_pipe
)) {
574 ERR("write error on health quit pipe");
577 /* Dispatch thread */
578 CMM_STORE_SHARED(dispatch_thread_exit
, 1);
579 futex_nto1_wake(&relay_conn_queue
.futex
);
581 if (relayd_live_stop()) {
582 ERR("Error stopping live threads");
589 * Signal handler for the daemon
591 * Simply stop all worker threads, leaving main() return gracefully after
592 * joining all threads and calling cleanup().
594 static void sighandler(int sig
)
598 DBG("SIGPIPE caught");
601 DBG("SIGINT caught");
602 if (lttng_relay_stop_threads()) {
603 ERR("Error stopping threads");
607 DBG("SIGTERM caught");
608 if (lttng_relay_stop_threads()) {
609 ERR("Error stopping threads");
613 CMM_STORE_SHARED(recv_child_signal
, 1);
621 * Setup signal handler for :
622 * SIGINT, SIGTERM, SIGPIPE
624 static int set_signal_handler(void)
630 if ((ret
= sigemptyset(&sigset
)) < 0) {
631 PERROR("sigemptyset");
635 sa
.sa_handler
= sighandler
;
638 if ((ret
= sigaction(SIGTERM
, &sa
, NULL
)) < 0) {
643 if ((ret
= sigaction(SIGINT
, &sa
, NULL
)) < 0) {
648 if ((ret
= sigaction(SIGPIPE
, &sa
, NULL
)) < 0) {
653 if ((ret
= sigaction(SIGUSR1
, &sa
, NULL
)) < 0) {
658 DBG("Signal handler set for SIGTERM, SIGUSR1, SIGPIPE and SIGINT");
663 void lttng_relay_notify_ready(void)
665 /* Notify the parent of the fork() process that we are ready. */
666 if (opt_daemon
|| opt_background
) {
667 if (uatomic_sub_return(<tng_relay_ready
, 1) == 0) {
668 kill(child_ppid
, SIGUSR1
);
674 * Init thread quit pipe.
676 * Return -1 on error or 0 if all pipes are created.
678 static int init_thread_quit_pipe(void)
682 ret
= utils_create_pipe_cloexec(thread_quit_pipe
);
688 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
690 static int create_thread_poll_set(struct lttng_poll_event
*events
, int size
)
694 if (events
== NULL
|| size
== 0) {
699 ret
= lttng_poll_create(events
, size
, LTTNG_CLOEXEC
);
705 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
717 * Check if the thread quit pipe was triggered.
719 * Return 1 if it was triggered else 0;
721 static int check_thread_quit_pipe(int fd
, uint32_t events
)
723 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
731 * Create and init socket from uri.
733 static struct lttcomm_sock
*relay_socket_create(struct lttng_uri
*uri
)
736 struct lttcomm_sock
*sock
= NULL
;
738 sock
= lttcomm_alloc_sock_from_uri(uri
);
740 ERR("Allocating socket");
744 ret
= lttcomm_create_sock(sock
);
748 DBG("Listening on sock %d", sock
->fd
);
750 ret
= sock
->ops
->bind(sock
);
755 ret
= sock
->ops
->listen(sock
, -1);
765 lttcomm_destroy_sock(sock
);
771 * This thread manages the listening for new connections on the network
773 static void *relay_thread_listener(void *data
)
775 int i
, ret
, pollfd
, err
= -1;
776 uint32_t revents
, nb_fd
;
777 struct lttng_poll_event events
;
778 struct lttcomm_sock
*control_sock
, *data_sock
;
780 DBG("[thread] Relay listener started");
782 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LISTENER
);
784 health_code_update();
786 control_sock
= relay_socket_create(control_uri
);
788 goto error_sock_control
;
791 data_sock
= relay_socket_create(data_uri
);
793 goto error_sock_relay
;
797 * Pass 3 as size here for the thread quit pipe, control and
800 ret
= create_thread_poll_set(&events
, 3);
802 goto error_create_poll
;
805 /* Add the control socket */
806 ret
= lttng_poll_add(&events
, control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
811 /* Add the data socket */
812 ret
= lttng_poll_add(&events
, data_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
817 lttng_relay_notify_ready();
819 if (testpoint(relayd_thread_listener
)) {
820 goto error_testpoint
;
824 health_code_update();
826 DBG("Listener accepting connections");
830 ret
= lttng_poll_wait(&events
, -1);
834 * Restart interrupted system call.
836 if (errno
== EINTR
) {
844 DBG("Relay new connection received");
845 for (i
= 0; i
< nb_fd
; i
++) {
846 health_code_update();
848 /* Fetch once the poll data */
849 revents
= LTTNG_POLL_GETEV(&events
, i
);
850 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
854 * No activity for this FD (poll
860 /* Thread quit pipe has been closed. Killing thread. */
861 ret
= check_thread_quit_pipe(pollfd
, revents
);
867 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
868 ERR("socket poll error");
870 } else 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
);
930 lttng_poll_clean(&events
);
932 if (data_sock
->fd
>= 0) {
933 ret
= data_sock
->ops
->close(data_sock
);
938 lttcomm_destroy_sock(data_sock
);
940 if (control_sock
->fd
>= 0) {
941 ret
= control_sock
->ops
->close(control_sock
);
946 lttcomm_destroy_sock(control_sock
);
950 ERR("Health error occurred in %s", __func__
);
952 health_unregister(health_relayd
);
953 DBG("Relay listener thread cleanup complete");
954 lttng_relay_stop_threads();
959 * This thread manages the dispatching of the requests to worker threads
961 static void *relay_thread_dispatcher(void *data
)
965 struct cds_wfcq_node
*node
;
966 struct relay_connection
*new_conn
= NULL
;
968 DBG("[thread] Relay dispatcher started");
970 health_register(health_relayd
, HEALTH_RELAYD_TYPE_DISPATCHER
);
972 if (testpoint(relayd_thread_dispatcher
)) {
973 goto error_testpoint
;
976 health_code_update();
978 while (!CMM_LOAD_SHARED(dispatch_thread_exit
)) {
979 health_code_update();
981 /* Atomically prepare the queue futex */
982 futex_nto1_prepare(&relay_conn_queue
.futex
);
985 health_code_update();
987 /* Dequeue commands */
988 node
= cds_wfcq_dequeue_blocking(&relay_conn_queue
.head
,
989 &relay_conn_queue
.tail
);
991 DBG("Woken up but nothing in the relay command queue");
992 /* Continue thread execution */
995 new_conn
= caa_container_of(node
, struct relay_connection
, qnode
);
997 DBG("Dispatching request waiting on sock %d", new_conn
->sock
->fd
);
1000 * Inform worker thread of the new request. This
1001 * call is blocking so we can be assured that
1002 * the data will be read at some point in time
1003 * or wait to the end of the world :)
1005 ret
= lttng_write(relay_conn_pipe
[1], &new_conn
, sizeof(new_conn
));
1007 PERROR("write connection pipe");
1008 connection_put(new_conn
);
1011 } while (node
!= NULL
);
1013 /* Futex wait on queue. Blocking call on futex() */
1014 health_poll_entry();
1015 futex_nto1_wait(&relay_conn_queue
.futex
);
1019 /* Normal exit, no error */
1026 ERR("Health error occurred in %s", __func__
);
1028 health_unregister(health_relayd
);
1029 DBG("Dispatch thread dying");
1030 lttng_relay_stop_threads();
1035 * Set index data from the control port to a given index object.
1037 static int set_index_control_data(struct relay_index
*index
,
1038 struct lttcomm_relayd_index
*data
)
1040 struct ctf_packet_index index_data
;
1043 * The index on disk is encoded in big endian, so we don't need
1044 * to convert the data received on the network. The data_offset
1045 * value is NEVER modified here and is updated by the data
1048 index_data
.packet_size
= data
->packet_size
;
1049 index_data
.content_size
= data
->content_size
;
1050 index_data
.timestamp_begin
= data
->timestamp_begin
;
1051 index_data
.timestamp_end
= data
->timestamp_end
;
1052 index_data
.events_discarded
= data
->events_discarded
;
1053 index_data
.stream_id
= data
->stream_id
;
1054 return relay_index_set_data(index
, &index_data
);
1058 * Handle the RELAYD_CREATE_SESSION command.
1060 * On success, send back the session id or else return a negative value.
1062 static int relay_create_session(struct lttcomm_relayd_hdr
*recv_hdr
,
1063 struct relay_connection
*conn
)
1065 int ret
= 0, send_ret
;
1066 struct relay_session
*session
;
1067 struct lttcomm_relayd_status_session reply
;
1068 char session_name
[NAME_MAX
];
1069 char hostname
[HOST_NAME_MAX
];
1070 uint32_t live_timer
= 0;
1071 bool snapshot
= false;
1073 memset(session_name
, 0, NAME_MAX
);
1074 memset(hostname
, 0, HOST_NAME_MAX
);
1076 memset(&reply
, 0, sizeof(reply
));
1078 switch (conn
->minor
) {
1083 case 4: /* LTTng sessiond 2.4 */
1085 ret
= cmd_create_session_2_4(conn
, session_name
,
1086 hostname
, &live_timer
, &snapshot
);
1092 session
= session_create(session_name
, hostname
, live_timer
,
1093 snapshot
, conn
->major
, conn
->minor
);
1098 assert(!conn
->session
);
1099 conn
->session
= session
;
1100 DBG("Created session %" PRIu64
, session
->id
);
1102 reply
.session_id
= htobe64(session
->id
);
1106 reply
.ret_code
= htobe32(LTTNG_ERR_FATAL
);
1108 reply
.ret_code
= htobe32(LTTNG_OK
);
1111 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1113 ERR("Relayd sending session id");
1121 * When we have received all the streams and the metadata for a channel,
1122 * we make them visible to the viewer threads.
1124 static void publish_connection_local_streams(struct relay_connection
*conn
)
1126 struct relay_stream
*stream
;
1127 struct relay_session
*session
= conn
->session
;
1130 * We publish all streams belonging to a session atomically wrt
1133 pthread_mutex_lock(&session
->lock
);
1135 cds_list_for_each_entry_rcu(stream
, &session
->recv_list
,
1137 stream_publish(stream
);
1142 * Inform the viewer that there are new streams in the session.
1144 if (session
->viewer_attached
) {
1145 uatomic_set(&session
->new_streams
, 1);
1147 pthread_mutex_unlock(&session
->lock
);
1151 * relay_add_stream: allocate a new stream for a session
1153 static int relay_add_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1154 struct relay_connection
*conn
)
1158 struct relay_session
*session
= conn
->session
;
1159 struct relay_stream
*stream
= NULL
;
1160 struct lttcomm_relayd_status_stream reply
;
1161 struct ctf_trace
*trace
= NULL
;
1162 uint64_t stream_handle
= -1ULL;
1163 char *path_name
= NULL
, *channel_name
= NULL
;
1164 uint64_t tracefile_size
= 0, tracefile_count
= 0;
1166 if (!session
|| conn
->version_check_done
== 0) {
1167 ERR("Trying to add a stream before version check");
1169 goto end_no_session
;
1172 switch (session
->minor
) {
1173 case 1: /* LTTng sessiond 2.1. Allocates path_name and channel_name. */
1174 ret
= cmd_recv_stream_2_1(conn
, &path_name
,
1177 case 2: /* LTTng sessiond 2.2. Allocates path_name and channel_name. */
1179 ret
= cmd_recv_stream_2_2(conn
, &path_name
,
1180 &channel_name
, &tracefile_size
, &tracefile_count
);
1187 trace
= ctf_trace_get_by_path_or_create(session
, path_name
);
1191 /* This stream here has one reference on the trace. */
1193 pthread_mutex_lock(&last_relay_stream_id_lock
);
1194 stream_handle
= ++last_relay_stream_id
;
1195 pthread_mutex_unlock(&last_relay_stream_id_lock
);
1197 /* We pass ownership of path_name and channel_name. */
1198 stream
= stream_create(trace
, stream_handle
, path_name
,
1199 channel_name
, tracefile_size
, tracefile_count
);
1201 channel_name
= NULL
;
1204 * Streams are the owners of their trace. Reference to trace is
1205 * kept within stream_create().
1207 ctf_trace_put(trace
);
1210 memset(&reply
, 0, sizeof(reply
));
1211 reply
.handle
= htobe64(stream_handle
);
1213 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1215 reply
.ret_code
= htobe32(LTTNG_OK
);
1218 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1219 sizeof(struct lttcomm_relayd_status_stream
), 0);
1221 ERR("Relay sending stream id");
1222 ret
= (int) send_ret
;
1232 * relay_close_stream: close a specific stream
1234 static int relay_close_stream(struct lttcomm_relayd_hdr
*recv_hdr
,
1235 struct relay_connection
*conn
)
1238 struct relay_session
*session
= conn
->session
;
1239 struct lttcomm_relayd_close_stream stream_info
;
1240 struct lttcomm_relayd_generic_reply reply
;
1241 struct relay_stream
*stream
;
1243 DBG("Close stream received");
1245 if (!session
|| conn
->version_check_done
== 0) {
1246 ERR("Trying to close a stream before version check");
1248 goto end_no_session
;
1251 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &stream_info
,
1252 sizeof(struct lttcomm_relayd_close_stream
), 0);
1253 if (ret
< sizeof(struct lttcomm_relayd_close_stream
)) {
1255 /* Orderly shutdown. Not necessary to print an error. */
1256 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1258 ERR("Relay didn't receive valid add_stream struct size : %d", ret
);
1261 goto end_no_session
;
1264 stream
= stream_get_by_id(be64toh(stream_info
.stream_id
));
1269 pthread_mutex_lock(&stream
->lock
);
1270 stream
->closed
= true;
1271 stream
->last_net_seq_num
= be64toh(stream_info
.last_net_seq_num
);
1272 if (stream
->is_metadata
) {
1273 struct relay_viewer_stream
*vstream
;
1275 vstream
= viewer_stream_get_by_id(stream
->stream_handle
);
1277 if (vstream
->metadata_sent
== stream
->metadata_received
) {
1279 * Since all the metadata has been sent to the
1280 * viewer and that we have a request to close
1281 * its stream, we can safely teardown the
1282 * corresponding metadata viewer stream.
1284 viewer_stream_put(vstream
);
1286 /* Put local reference. */
1287 viewer_stream_put(vstream
);
1290 pthread_mutex_unlock(&stream
->lock
);
1294 memset(&reply
, 0, sizeof(reply
));
1296 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1298 reply
.ret_code
= htobe32(LTTNG_OK
);
1300 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1301 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1303 ERR("Relay sending stream id");
1312 * relay_unknown_command: send -1 if received unknown command
1314 static void relay_unknown_command(struct relay_connection
*conn
)
1316 struct lttcomm_relayd_generic_reply reply
;
1319 memset(&reply
, 0, sizeof(reply
));
1320 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1321 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1322 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1324 ERR("Relay sending unknown command");
1329 * relay_start: send an acknowledgment to the client to tell if we are
1330 * ready to receive data. We are ready if a session is established.
1332 static int relay_start(struct lttcomm_relayd_hdr
*recv_hdr
,
1333 struct relay_connection
*conn
)
1335 int ret
= htobe32(LTTNG_OK
);
1336 struct lttcomm_relayd_generic_reply reply
;
1337 struct relay_session
*session
= conn
->session
;
1340 DBG("Trying to start the streaming without a session established");
1341 ret
= htobe32(LTTNG_ERR_UNK
);
1344 memset(&reply
, 0, sizeof(reply
));
1345 reply
.ret_code
= ret
;
1346 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1347 sizeof(struct lttcomm_relayd_generic_reply
), 0);
1349 ERR("Relay sending start ack");
1356 * Append padding to the file pointed by the file descriptor fd.
1358 static int write_padding_to_file(int fd
, uint32_t size
)
1367 zeros
= zmalloc(size
);
1368 if (zeros
== NULL
) {
1369 PERROR("zmalloc zeros for padding");
1374 ret
= lttng_write(fd
, zeros
, size
);
1376 PERROR("write padding to file");
1386 * relay_recv_metadata: receive the metadata for the session.
1388 static int relay_recv_metadata(struct lttcomm_relayd_hdr
*recv_hdr
,
1389 struct relay_connection
*conn
)
1391 int ret
= htobe32(LTTNG_OK
);
1393 struct relay_session
*session
= conn
->session
;
1394 struct lttcomm_relayd_metadata_payload
*metadata_struct
;
1395 struct relay_stream
*metadata_stream
;
1396 uint64_t data_size
, payload_size
;
1399 ERR("Metadata sent before version check");
1404 data_size
= payload_size
= be64toh(recv_hdr
->data_size
);
1405 if (data_size
< sizeof(struct lttcomm_relayd_metadata_payload
)) {
1406 ERR("Incorrect data size");
1410 payload_size
-= sizeof(struct lttcomm_relayd_metadata_payload
);
1412 if (data_buffer_size
< data_size
) {
1413 /* In case the realloc fails, we can free the memory */
1416 tmp_data_ptr
= realloc(data_buffer
, data_size
);
1417 if (!tmp_data_ptr
) {
1418 ERR("Allocating data buffer");
1423 data_buffer
= tmp_data_ptr
;
1424 data_buffer_size
= data_size
;
1426 memset(data_buffer
, 0, data_size
);
1427 DBG2("Relay receiving metadata, waiting for %" PRIu64
" bytes", data_size
);
1428 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
1429 if (ret
< 0 || ret
!= data_size
) {
1431 /* Orderly shutdown. Not necessary to print an error. */
1432 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1434 ERR("Relay didn't receive the whole metadata");
1439 metadata_struct
= (struct lttcomm_relayd_metadata_payload
*) data_buffer
;
1441 metadata_stream
= stream_get_by_id(be64toh(metadata_struct
->stream_id
));
1442 if (!metadata_stream
) {
1447 pthread_mutex_lock(&metadata_stream
->lock
);
1449 size_ret
= lttng_write(metadata_stream
->stream_fd
->fd
, metadata_struct
->payload
,
1451 if (size_ret
< payload_size
) {
1452 ERR("Relay error writing metadata on file");
1457 ret
= write_padding_to_file(metadata_stream
->stream_fd
->fd
,
1458 be32toh(metadata_struct
->padding_size
));
1463 metadata_stream
->metadata_received
+=
1464 payload_size
+ be32toh(metadata_struct
->padding_size
);
1465 DBG2("Relay metadata written. Updated metadata_received %" PRIu64
,
1466 metadata_stream
->metadata_received
);
1469 pthread_mutex_unlock(&metadata_stream
->lock
);
1470 stream_put(metadata_stream
);
1477 * relay_send_version: send relayd version number
1479 static int relay_send_version(struct lttcomm_relayd_hdr
*recv_hdr
,
1480 struct relay_connection
*conn
)
1483 struct lttcomm_relayd_version reply
, msg
;
1485 conn
->version_check_done
= 1;
1487 /* Get version from the other side. */
1488 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1489 if (ret
< 0 || ret
!= sizeof(msg
)) {
1491 /* Orderly shutdown. Not necessary to print an error. */
1492 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1494 ERR("Relay failed to receive the version values.");
1500 memset(&reply
, 0, sizeof(reply
));
1501 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
1502 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
1504 /* Major versions must be the same */
1505 if (reply
.major
!= be32toh(msg
.major
)) {
1506 DBG("Incompatible major versions (%u vs %u), deleting session",
1507 reply
.major
, be32toh(msg
.major
));
1508 connection_put(conn
);
1513 conn
->major
= reply
.major
;
1514 /* We adapt to the lowest compatible version */
1515 if (reply
.minor
<= be32toh(msg
.minor
)) {
1516 conn
->minor
= reply
.minor
;
1518 conn
->minor
= be32toh(msg
.minor
);
1521 reply
.major
= htobe32(reply
.major
);
1522 reply
.minor
= htobe32(reply
.minor
);
1523 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
,
1524 sizeof(struct lttcomm_relayd_version
), 0);
1526 ERR("Relay sending version");
1529 DBG("Version check done using protocol %u.%u", conn
->major
,
1537 * Check for data pending for a given stream id from the session daemon.
1539 static int relay_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1540 struct relay_connection
*conn
)
1542 struct relay_session
*session
= conn
->session
;
1543 struct lttcomm_relayd_data_pending msg
;
1544 struct lttcomm_relayd_generic_reply reply
;
1545 struct relay_stream
*stream
;
1547 uint64_t last_net_seq_num
, stream_id
;
1549 DBG("Data pending command received");
1551 if (!session
|| conn
->version_check_done
== 0) {
1552 ERR("Trying to check for data before version check");
1554 goto end_no_session
;
1557 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1558 if (ret
< sizeof(msg
)) {
1560 /* Orderly shutdown. Not necessary to print an error. */
1561 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1563 ERR("Relay didn't receive valid data_pending struct size : %d",
1567 goto end_no_session
;
1570 stream_id
= be64toh(msg
.stream_id
);
1571 last_net_seq_num
= be64toh(msg
.last_net_seq_num
);
1573 stream
= stream_get_by_id(stream_id
);
1574 if (stream
== NULL
) {
1579 pthread_mutex_lock(&stream
->lock
);
1581 DBG("Data pending for stream id %" PRIu64
" prev_seq %" PRIu64
1582 " and last_seq %" PRIu64
, stream_id
, stream
->prev_seq
,
1585 /* Avoid wrapping issue */
1586 if (((int64_t) (stream
->prev_seq
- last_net_seq_num
)) >= 0) {
1587 /* Data has in fact been written and is NOT pending */
1590 /* Data still being streamed thus pending */
1594 stream
->data_pending_check_done
= true;
1595 pthread_mutex_unlock(&stream
->lock
);
1600 memset(&reply
, 0, sizeof(reply
));
1601 reply
.ret_code
= htobe32(ret
);
1602 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1604 ERR("Relay data pending ret code failed");
1612 * Wait for the control socket to reach a quiescent state.
1614 * Note that for now, when receiving this command from the session
1615 * daemon, this means that every subsequent commands or data received on
1616 * the control socket has been handled. So, this is why we simply return
1619 static int relay_quiescent_control(struct lttcomm_relayd_hdr
*recv_hdr
,
1620 struct relay_connection
*conn
)
1624 struct relay_stream
*stream
;
1625 struct lttcomm_relayd_quiescent_control msg
;
1626 struct lttcomm_relayd_generic_reply reply
;
1628 DBG("Checking quiescent state on control socket");
1630 if (!conn
->session
|| conn
->version_check_done
== 0) {
1631 ERR("Trying to check for data before version check");
1633 goto end_no_session
;
1636 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1637 if (ret
< sizeof(msg
)) {
1639 /* Orderly shutdown. Not necessary to print an error. */
1640 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1642 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1646 goto end_no_session
;
1649 stream_id
= be64toh(msg
.stream_id
);
1650 stream
= stream_get_by_id(stream_id
);
1654 pthread_mutex_lock(&stream
->lock
);
1655 stream
->data_pending_check_done
= true;
1656 pthread_mutex_unlock(&stream
->lock
);
1657 DBG("Relay quiescent control pending flag set to %" PRIu64
, stream_id
);
1660 memset(&reply
, 0, sizeof(reply
));
1661 reply
.ret_code
= htobe32(LTTNG_OK
);
1662 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1664 ERR("Relay data quiescent control ret code failed");
1672 * Initialize a data pending command. This means that a consumer is about
1673 * to ask for data pending for each stream it holds. Simply iterate over
1674 * all streams of a session and set the data_pending_check_done flag.
1676 * This command returns to the client a LTTNG_OK code.
1678 static int relay_begin_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1679 struct relay_connection
*conn
)
1682 struct lttng_ht_iter iter
;
1683 struct lttcomm_relayd_begin_data_pending msg
;
1684 struct lttcomm_relayd_generic_reply reply
;
1685 struct relay_stream
*stream
;
1686 uint64_t session_id
;
1691 DBG("Init streams for data pending");
1693 if (!conn
->session
|| conn
->version_check_done
== 0) {
1694 ERR("Trying to check for data before version check");
1696 goto end_no_session
;
1699 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1700 if (ret
< sizeof(msg
)) {
1702 /* Orderly shutdown. Not necessary to print an error. */
1703 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1705 ERR("Relay didn't receive valid begin data_pending struct size: %d",
1709 goto end_no_session
;
1712 session_id
= be64toh(msg
.session_id
);
1715 * Iterate over all streams to set the begin data pending flag.
1716 * For now, the streams are indexed by stream handle so we have
1717 * to iterate over all streams to find the one associated with
1718 * the right session_id.
1721 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1723 if (!stream_get(stream
)) {
1726 if (stream
->trace
->session
->id
== session_id
) {
1727 pthread_mutex_lock(&stream
->lock
);
1728 stream
->data_pending_check_done
= false;
1729 pthread_mutex_unlock(&stream
->lock
);
1730 DBG("Set begin data pending flag to stream %" PRIu64
,
1731 stream
->stream_handle
);
1737 memset(&reply
, 0, sizeof(reply
));
1738 /* All good, send back reply. */
1739 reply
.ret_code
= htobe32(LTTNG_OK
);
1741 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1743 ERR("Relay begin data pending send reply failed");
1751 * End data pending command. This will check, for a given session id, if
1752 * each stream associated with it has its data_pending_check_done flag
1753 * set. If not, this means that the client lost track of the stream but
1754 * the data is still being streamed on our side. In this case, we inform
1755 * the client that data is in flight.
1757 * Return to the client if there is data in flight or not with a ret_code.
1759 static int relay_end_data_pending(struct lttcomm_relayd_hdr
*recv_hdr
,
1760 struct relay_connection
*conn
)
1763 struct lttng_ht_iter iter
;
1764 struct lttcomm_relayd_end_data_pending msg
;
1765 struct lttcomm_relayd_generic_reply reply
;
1766 struct relay_stream
*stream
;
1767 uint64_t session_id
;
1768 uint32_t is_data_inflight
= 0;
1770 DBG("End data pending command");
1772 if (!conn
->session
|| conn
->version_check_done
== 0) {
1773 ERR("Trying to check for data before version check");
1775 goto end_no_session
;
1778 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &msg
, sizeof(msg
), 0);
1779 if (ret
< sizeof(msg
)) {
1781 /* Orderly shutdown. Not necessary to print an error. */
1782 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1784 ERR("Relay didn't receive valid end data_pending struct size: %d",
1788 goto end_no_session
;
1791 session_id
= be64toh(msg
.session_id
);
1794 * Iterate over all streams to see if the begin data pending
1798 cds_lfht_for_each_entry(relay_streams_ht
->ht
, &iter
.iter
, stream
,
1800 if (!stream_get(stream
)) {
1803 if (stream
->trace
->session
->id
!= session_id
) {
1807 pthread_mutex_lock(&stream
->lock
);
1808 if (!stream
->data_pending_check_done
) {
1809 if (!stream
->closed
|| !(((int64_t) (stream
->prev_seq
- stream
->last_net_seq_num
)) >= 0)) {
1810 is_data_inflight
= 1;
1811 DBG("Data is still in flight for stream %" PRIu64
,
1812 stream
->stream_handle
);
1813 pthread_mutex_unlock(&stream
->lock
);
1818 pthread_mutex_unlock(&stream
->lock
);
1823 memset(&reply
, 0, sizeof(reply
));
1824 /* All good, send back reply. */
1825 reply
.ret_code
= htobe32(is_data_inflight
);
1827 ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1829 ERR("Relay end data pending send reply failed");
1837 * Receive an index for a specific stream.
1839 * Return 0 on success else a negative value.
1841 static int relay_recv_index(struct lttcomm_relayd_hdr
*recv_hdr
,
1842 struct relay_connection
*conn
)
1845 struct relay_session
*session
= conn
->session
;
1846 struct lttcomm_relayd_index index_info
;
1847 struct relay_index
*index
;
1848 struct lttcomm_relayd_generic_reply reply
;
1849 struct relay_stream
*stream
;
1850 uint64_t net_seq_num
;
1854 DBG("Relay receiving index");
1856 if (!session
|| conn
->version_check_done
== 0) {
1857 ERR("Trying to close a stream before version check");
1859 goto end_no_session
;
1862 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &index_info
,
1863 sizeof(index_info
), 0);
1864 if (ret
< sizeof(index_info
)) {
1866 /* Orderly shutdown. Not necessary to print an error. */
1867 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
1869 ERR("Relay didn't receive valid index struct size : %d", ret
);
1872 goto end_no_session
;
1875 net_seq_num
= be64toh(index_info
.net_seq_num
);
1877 stream
= stream_get_by_id(be64toh(index_info
.relay_stream_id
));
1879 ERR("stream_get_by_id not found");
1883 pthread_mutex_lock(&stream
->lock
);
1885 /* Live beacon handling */
1886 if (index_info
.packet_size
== 0) {
1887 DBG("Received live beacon for stream %" PRIu64
,
1888 stream
->stream_handle
);
1891 * Only flag a stream inactive when it has already
1892 * received data and no indexes are in flight.
1894 if (stream
->index_received_seqcount
> 0
1895 && stream
->indexes_in_flight
== 0) {
1896 stream
->beacon_ts_end
=
1897 be64toh(index_info
.timestamp_end
);
1900 goto end_stream_put
;
1902 stream
->beacon_ts_end
= -1ULL;
1905 if (stream
->ctf_stream_id
== -1ULL) {
1906 stream
->ctf_stream_id
= be64toh(index_info
.stream_id
);
1908 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
1911 ERR("relay_index_get_by_id_or_create index NULL");
1912 goto end_stream_put
;
1914 if (set_index_control_data(index
, &index_info
)) {
1915 ERR("set_index_control_data error");
1916 relay_index_put(index
);
1918 goto end_stream_put
;
1920 ret
= relay_index_try_flush(index
);
1922 tracefile_array_commit_seq(stream
->tfa
);
1923 stream
->index_received_seqcount
++;
1924 } else if (ret
> 0) {
1928 ERR("relay_index_try_flush error %d", ret
);
1929 relay_index_put(index
);
1934 pthread_mutex_unlock(&stream
->lock
);
1939 memset(&reply
, 0, sizeof(reply
));
1941 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
1943 reply
.ret_code
= htobe32(LTTNG_OK
);
1945 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1947 ERR("Relay sending close index id reply");
1956 * Receive the streams_sent message.
1958 * Return 0 on success else a negative value.
1960 static int relay_streams_sent(struct lttcomm_relayd_hdr
*recv_hdr
,
1961 struct relay_connection
*conn
)
1964 struct lttcomm_relayd_generic_reply reply
;
1968 DBG("Relay receiving streams_sent");
1970 if (!conn
->session
|| conn
->version_check_done
== 0) {
1971 ERR("Trying to close a stream before version check");
1973 goto end_no_session
;
1977 * Publish every pending stream in the connection recv list which are
1978 * now ready to be used by the viewer.
1980 publish_connection_local_streams(conn
);
1982 memset(&reply
, 0, sizeof(reply
));
1983 reply
.ret_code
= htobe32(LTTNG_OK
);
1984 send_ret
= conn
->sock
->ops
->sendmsg(conn
->sock
, &reply
, sizeof(reply
), 0);
1986 ERR("Relay sending sent_stream reply");
1998 * Process the commands received on the control socket
2000 static int relay_process_control(struct lttcomm_relayd_hdr
*recv_hdr
,
2001 struct relay_connection
*conn
)
2005 switch (be32toh(recv_hdr
->cmd
)) {
2006 case RELAYD_CREATE_SESSION
:
2007 ret
= relay_create_session(recv_hdr
, conn
);
2009 case RELAYD_ADD_STREAM
:
2010 ret
= relay_add_stream(recv_hdr
, conn
);
2012 case RELAYD_START_DATA
:
2013 ret
= relay_start(recv_hdr
, conn
);
2015 case RELAYD_SEND_METADATA
:
2016 ret
= relay_recv_metadata(recv_hdr
, conn
);
2018 case RELAYD_VERSION
:
2019 ret
= relay_send_version(recv_hdr
, conn
);
2021 case RELAYD_CLOSE_STREAM
:
2022 ret
= relay_close_stream(recv_hdr
, conn
);
2024 case RELAYD_DATA_PENDING
:
2025 ret
= relay_data_pending(recv_hdr
, conn
);
2027 case RELAYD_QUIESCENT_CONTROL
:
2028 ret
= relay_quiescent_control(recv_hdr
, conn
);
2030 case RELAYD_BEGIN_DATA_PENDING
:
2031 ret
= relay_begin_data_pending(recv_hdr
, conn
);
2033 case RELAYD_END_DATA_PENDING
:
2034 ret
= relay_end_data_pending(recv_hdr
, conn
);
2036 case RELAYD_SEND_INDEX
:
2037 ret
= relay_recv_index(recv_hdr
, conn
);
2039 case RELAYD_STREAMS_SENT
:
2040 ret
= relay_streams_sent(recv_hdr
, conn
);
2042 case RELAYD_UPDATE_SYNC_INFO
:
2044 ERR("Received unknown command (%u)", be32toh(recv_hdr
->cmd
));
2045 relay_unknown_command(conn
);
2055 * Handle index for a data stream.
2057 * Called with the stream lock held.
2059 * Return 0 on success else a negative value.
2061 static int handle_index_data(struct relay_stream
*stream
, uint64_t net_seq_num
,
2065 uint64_t data_offset
;
2066 struct relay_index
*index
;
2068 /* Get data offset because we are about to update the index. */
2069 data_offset
= htobe64(stream
->tracefile_size_current
);
2071 DBG("handle_index_data: stream %" PRIu64
" data offset %" PRIu64
,
2072 stream
->stream_handle
, stream
->tracefile_size_current
);
2075 * Lookup for an existing index for that stream id/sequence
2076 * number. If it exists, the control thread has already received the
2077 * data for it, thus we need to write it to disk.
2079 index
= relay_index_get_by_id_or_create(stream
, net_seq_num
);
2085 if (rotate_index
|| !stream
->index_fd
) {
2088 /* Put ref on previous index_fd. */
2089 if (stream
->index_fd
) {
2090 stream_fd_put(stream
->index_fd
);
2091 stream
->index_fd
= NULL
;
2094 fd
= index_create_file(stream
->path_name
, stream
->channel_name
,
2095 -1, -1, stream
->tracefile_size
,
2096 tracefile_array_get_file_index_head(stream
->tfa
));
2099 /* Put self-ref for this index due to error. */
2100 relay_index_put(index
);
2103 stream
->index_fd
= stream_fd_create(fd
);
2104 if (!stream
->index_fd
) {
2107 PERROR("Error closing FD %d", fd
);
2109 /* Put self-ref for this index due to error. */
2110 relay_index_put(index
);
2111 /* Will put the local ref. */
2116 if (relay_index_set_fd(index
, stream
->index_fd
, data_offset
)) {
2118 /* Put self-ref for this index due to error. */
2119 relay_index_put(index
);
2123 ret
= relay_index_try_flush(index
);
2125 tracefile_array_commit_seq(stream
->tfa
);
2126 stream
->index_received_seqcount
++;
2127 } else if (ret
> 0) {
2131 /* Put self-ref for this index due to error. */
2132 relay_index_put(index
);
2140 * relay_process_data: Process the data received on the data socket
2142 static int relay_process_data(struct relay_connection
*conn
)
2144 int ret
= 0, rotate_index
= 0;
2146 struct relay_stream
*stream
;
2147 struct lttcomm_relayd_data_hdr data_hdr
;
2149 uint64_t net_seq_num
;
2151 struct relay_session
*session
;
2152 bool new_stream
= false;
2154 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &data_hdr
,
2155 sizeof(struct lttcomm_relayd_data_hdr
), 0);
2158 /* Orderly shutdown. Not necessary to print an error. */
2159 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2161 ERR("Unable to receive data header on sock %d", conn
->sock
->fd
);
2167 stream_id
= be64toh(data_hdr
.stream_id
);
2168 stream
= stream_get_by_id(stream_id
);
2173 session
= stream
->trace
->session
;
2174 data_size
= be32toh(data_hdr
.data_size
);
2175 if (data_buffer_size
< data_size
) {
2178 tmp_data_ptr
= realloc(data_buffer
, data_size
);
2179 if (!tmp_data_ptr
) {
2180 ERR("Allocating data buffer");
2183 goto end_stream_put
;
2185 data_buffer
= tmp_data_ptr
;
2186 data_buffer_size
= data_size
;
2188 memset(data_buffer
, 0, data_size
);
2190 net_seq_num
= be64toh(data_hdr
.net_seq_num
);
2192 DBG3("Receiving data of size %u for stream id %" PRIu64
" seqnum %" PRIu64
,
2193 data_size
, stream_id
, net_seq_num
);
2194 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, data_buffer
, data_size
, 0);
2197 /* Orderly shutdown. Not necessary to print an error. */
2198 DBG("Socket %d did an orderly shutdown", conn
->sock
->fd
);
2201 goto end_stream_put
;
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 goto end_stream_unlock
;
2246 /* Write data to stream output fd. */
2247 size_ret
= lttng_write(stream
->stream_fd
->fd
, data_buffer
, data_size
);
2248 if (size_ret
< data_size
) {
2249 ERR("Relay error writing data to file");
2251 goto end_stream_unlock
;
2254 DBG2("Relay wrote %zd bytes to tracefile for stream id %" PRIu64
,
2255 size_ret
, stream
->stream_handle
);
2257 ret
= write_padding_to_file(stream
->stream_fd
->fd
,
2258 be32toh(data_hdr
.padding_size
));
2260 goto end_stream_unlock
;
2262 stream
->tracefile_size_current
+=
2263 data_size
+ be32toh(data_hdr
.padding_size
);
2264 if (stream
->prev_seq
== -1ULL) {
2268 stream
->prev_seq
= net_seq_num
;
2271 pthread_mutex_unlock(&stream
->lock
);
2273 pthread_mutex_lock(&session
->lock
);
2274 uatomic_set(&session
->new_streams
, 1);
2275 pthread_mutex_unlock(&session
->lock
);
2283 static void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2287 (void) lttng_poll_del(events
, pollfd
);
2289 ret
= close(pollfd
);
2291 ERR("Closing pollfd %d", pollfd
);
2295 static void relay_thread_close_connection(struct lttng_poll_event
*events
,
2296 int pollfd
, struct relay_connection
*conn
)
2298 const char *type_str
;
2300 switch (conn
->type
) {
2305 type_str
= "Control";
2307 case RELAY_VIEWER_COMMAND
:
2308 type_str
= "Viewer Command";
2310 case RELAY_VIEWER_NOTIFICATION
:
2311 type_str
= "Viewer Notification";
2314 type_str
= "Unknown";
2316 cleanup_connection_pollfd(events
, pollfd
);
2317 connection_put(conn
);
2318 DBG("%s connection closed with %d", type_str
, pollfd
);
2322 * This thread does the actual work
2324 static void *relay_thread_worker(void *data
)
2326 int ret
, err
= -1, last_seen_data_fd
= -1;
2328 struct lttng_poll_event events
;
2329 struct lttng_ht
*relay_connections_ht
;
2330 struct lttng_ht_iter iter
;
2331 struct lttcomm_relayd_hdr recv_hdr
;
2332 struct relay_connection
*destroy_conn
= NULL
;
2334 DBG("[thread] Relay worker started");
2336 rcu_register_thread();
2338 health_register(health_relayd
, HEALTH_RELAYD_TYPE_WORKER
);
2340 if (testpoint(relayd_thread_worker
)) {
2341 goto error_testpoint
;
2344 health_code_update();
2346 /* table of connections indexed on socket */
2347 relay_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2348 if (!relay_connections_ht
) {
2349 goto relay_connections_ht_error
;
2352 ret
= create_thread_poll_set(&events
, 2);
2354 goto error_poll_create
;
2357 ret
= lttng_poll_add(&events
, relay_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2364 int idx
= -1, i
, seen_control
= 0, last_notdel_data_fd
= -1;
2366 health_code_update();
2368 /* Infinite blocking call, waiting for transmission */
2369 DBG3("Relayd worker thread polling...");
2370 health_poll_entry();
2371 ret
= lttng_poll_wait(&events
, -1);
2375 * Restart interrupted system call.
2377 if (errno
== EINTR
) {
2386 * Process control. The control connection is
2387 * prioritized so we don't starve it with high
2388 * throughput tracing data on the data connection.
2390 for (i
= 0; i
< nb_fd
; i
++) {
2391 /* Fetch once the poll data */
2392 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2393 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2395 health_code_update();
2399 * No activity for this FD (poll
2405 /* Thread quit pipe has been closed. Killing thread. */
2406 ret
= check_thread_quit_pipe(pollfd
, revents
);
2412 /* Inspect the relay conn pipe for new connection */
2413 if (pollfd
== relay_conn_pipe
[0]) {
2414 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2415 ERR("Relay connection pipe error");
2417 } else if (revents
& LPOLLIN
) {
2418 struct relay_connection
*conn
;
2420 ret
= lttng_read(relay_conn_pipe
[0], &conn
, sizeof(conn
));
2424 lttng_poll_add(&events
, conn
->sock
->fd
,
2425 LPOLLIN
| LPOLLRDHUP
);
2426 connection_ht_add(relay_connections_ht
, conn
);
2427 DBG("Connection socket %d added", conn
->sock
->fd
);
2430 struct relay_connection
*ctrl_conn
;
2432 ctrl_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2433 /* If not found, there is a synchronization issue. */
2436 if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2437 relay_thread_close_connection(&events
, pollfd
, ctrl_conn
);
2438 if (last_seen_data_fd
== pollfd
) {
2439 last_seen_data_fd
= last_notdel_data_fd
;
2441 } else if (revents
& LPOLLIN
) {
2442 if (ctrl_conn
->type
== RELAY_CONTROL
) {
2443 ret
= ctrl_conn
->sock
->ops
->recvmsg(ctrl_conn
->sock
, &recv_hdr
,
2444 sizeof(recv_hdr
), 0);
2446 /* Connection closed */
2447 relay_thread_close_connection(&events
, pollfd
,
2450 ret
= relay_process_control(&recv_hdr
, ctrl_conn
);
2452 /* Clear the session on error. */
2453 relay_thread_close_connection(&events
, pollfd
,
2460 * Flag the last seen data fd not deleted. It will be
2461 * used as the last seen fd if any fd gets deleted in
2464 last_notdel_data_fd
= pollfd
;
2467 ERR("Unknown poll events %u for sock %d", revents
, pollfd
);
2469 connection_put(ctrl_conn
);
2474 * The last loop handled a control request, go back to poll to make
2475 * sure we prioritise the control socket.
2481 if (last_seen_data_fd
>= 0) {
2482 for (i
= 0; i
< nb_fd
; i
++) {
2483 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2485 health_code_update();
2487 if (last_seen_data_fd
== pollfd
) {
2494 /* Process data connection. */
2495 for (i
= idx
+ 1; i
< nb_fd
; i
++) {
2496 /* Fetch the poll data. */
2497 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2498 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2499 struct relay_connection
*data_conn
;
2501 health_code_update();
2504 /* No activity for this FD (poll implementation). */
2508 /* Skip the command pipe. It's handled in the first loop. */
2509 if (pollfd
== relay_conn_pipe
[0]) {
2513 data_conn
= connection_get_by_sock(relay_connections_ht
, pollfd
);
2515 /* Skip it. Might be removed before. */
2519 if (revents
& LPOLLIN
) {
2520 if (data_conn
->type
!= RELAY_DATA
) {
2521 goto put_connection
;
2524 ret
= relay_process_data(data_conn
);
2525 /* Connection closed */
2527 relay_thread_close_connection(&events
, pollfd
,
2530 * Every goto restart call sets the last seen fd where
2531 * here we don't really care since we gracefully
2532 * continue the loop after the connection is deleted.
2535 /* Keep last seen port. */
2536 last_seen_data_fd
= pollfd
;
2537 connection_put(data_conn
);
2542 connection_put(data_conn
);
2544 last_seen_data_fd
= -1;
2547 /* Normal exit, no error */
2552 /* Cleanup reamaining connection object. */
2554 cds_lfht_for_each_entry(relay_connections_ht
->ht
, &iter
.iter
,
2557 health_code_update();
2559 * No need to grab another ref, because we own
2562 relay_thread_close_connection(&events
, destroy_conn
->sock
->fd
,
2567 lttng_poll_clean(&events
);
2569 lttng_ht_destroy(relay_connections_ht
);
2570 relay_connections_ht_error
:
2571 /* Close relay conn pipes */
2572 utils_close_pipe(relay_conn_pipe
);
2574 DBG("Thread exited with error");
2576 DBG("Worker thread cleanup complete");
2581 ERR("Health error occurred in %s", __func__
);
2583 health_unregister(health_relayd
);
2584 rcu_unregister_thread();
2585 lttng_relay_stop_threads();
2590 * Create the relay command pipe to wake thread_manage_apps.
2591 * Closed in cleanup().
2593 static int create_relay_conn_pipe(void)
2597 ret
= utils_create_pipe_cloexec(relay_conn_pipe
);
2605 int main(int argc
, char **argv
)
2607 int ret
= 0, retval
= 0;
2610 /* Parse arguments */
2612 if (set_options(argc
, argv
)) {
2617 if (set_signal_handler()) {
2622 /* Try to create directory if -o, --output is specified. */
2623 if (opt_output_path
) {
2624 if (*opt_output_path
!= '/') {
2625 ERR("Please specify an absolute path for -o, --output PATH");
2630 ret
= utils_mkdir_recursive(opt_output_path
, S_IRWXU
| S_IRWXG
,
2633 ERR("Unable to create %s", opt_output_path
);
2640 if (opt_daemon
|| opt_background
) {
2643 ret
= lttng_daemonize(&child_ppid
, &recv_child_signal
,
2651 * We are in the child. Make sure all other file
2652 * descriptors are closed, in case we are called with
2653 * more opened file descriptors than the standard ones.
2655 for (i
= 3; i
< sysconf(_SC_OPEN_MAX
); i
++) {
2661 /* Initialize thread health monitoring */
2662 health_relayd
= health_app_create(NR_HEALTH_RELAYD_TYPES
);
2663 if (!health_relayd
) {
2664 PERROR("health_app_create error");
2666 goto exit_health_app_create
;
2669 /* Create thread quit pipe */
2670 if (init_thread_quit_pipe()) {
2672 goto exit_init_data
;
2675 /* Check if daemon is UID = 0 */
2677 if (control_uri
->port
< 1024 || data_uri
->port
< 1024 || live_uri
->port
< 1024) {
2678 ERR("Need to be root to use ports < 1024");
2680 goto exit_init_data
;
2684 /* Setup the thread apps communication pipe. */
2685 if (create_relay_conn_pipe()) {
2687 goto exit_init_data
;
2690 /* Init relay command queue. */
2691 cds_wfcq_init(&relay_conn_queue
.head
, &relay_conn_queue
.tail
);
2693 /* Set up max poll set size */
2694 if (lttng_poll_set_max_size()) {
2696 goto exit_init_data
;
2699 /* Initialize communication library */
2701 lttcomm_inet_init();
2703 /* tables of sessions indexed by session ID */
2704 sessions_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2707 goto exit_init_data
;
2710 /* tables of streams indexed by stream ID */
2711 relay_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2712 if (!relay_streams_ht
) {
2714 goto exit_init_data
;
2717 /* tables of streams indexed by stream ID */
2718 viewer_streams_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_U64
);
2719 if (!viewer_streams_ht
) {
2721 goto exit_init_data
;
2724 ret
= utils_create_pipe(health_quit_pipe
);
2727 goto exit_health_quit_pipe
;
2730 /* Create thread to manage the client socket */
2731 ret
= pthread_create(&health_thread
, NULL
,
2732 thread_manage_health
, (void *) NULL
);
2735 PERROR("pthread_create health");
2737 goto exit_health_thread
;
2740 /* Setup the dispatcher thread */
2741 ret
= pthread_create(&dispatcher_thread
, NULL
,
2742 relay_thread_dispatcher
, (void *) NULL
);
2745 PERROR("pthread_create dispatcher");
2747 goto exit_dispatcher_thread
;
2750 /* Setup the worker thread */
2751 ret
= pthread_create(&worker_thread
, NULL
,
2752 relay_thread_worker
, NULL
);
2755 PERROR("pthread_create worker");
2757 goto exit_worker_thread
;
2760 /* Setup the listener thread */
2761 ret
= pthread_create(&listener_thread
, NULL
,
2762 relay_thread_listener
, (void *) NULL
);
2765 PERROR("pthread_create listener");
2767 goto exit_listener_thread
;
2770 ret
= relayd_live_create(live_uri
);
2772 ERR("Starting live viewer threads");
2778 * This is where we start awaiting program completion (e.g. through
2779 * signal that asks threads to teardown).
2782 ret
= relayd_live_join();
2788 ret
= pthread_join(listener_thread
, &status
);
2791 PERROR("pthread_join listener_thread");
2795 exit_listener_thread
:
2796 ret
= pthread_join(worker_thread
, &status
);
2799 PERROR("pthread_join worker_thread");
2804 ret
= pthread_join(dispatcher_thread
, &status
);
2807 PERROR("pthread_join dispatcher_thread");
2810 exit_dispatcher_thread
:
2812 ret
= pthread_join(health_thread
, &status
);
2815 PERROR("pthread_join health_thread");
2820 utils_close_pipe(health_quit_pipe
);
2821 exit_health_quit_pipe
:
2824 health_app_destroy(health_relayd
);
2825 exit_health_app_create
:
2829 /* Ensure all prior call_rcu are done. */