2 * Copyright (C) 2013 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2013 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 * SPDX-License-Identifier: GPL-2.0-only
22 #include <sys/mount.h>
23 #include <sys/resource.h>
24 #include <sys/socket.h>
26 #include <sys/types.h>
29 #include <urcu/futex.h>
30 #include <urcu/rculist.h>
31 #include <urcu/uatomic.h>
33 #include <common/common.h>
34 #include <common/compat/endian.h>
35 #include <common/compat/poll.h>
36 #include <common/compat/socket.h>
37 #include <common/defaults.h>
38 #include <common/fd-tracker/utils.h>
39 #include <common/fs-handle.h>
40 #include <common/futex.h>
41 #include <common/index/index.h>
42 #include <common/sessiond-comm/inet.h>
43 #include <common/sessiond-comm/relayd.h>
44 #include <common/sessiond-comm/sessiond-comm.h>
45 #include <common/uri.h>
46 #include <common/utils.h>
47 #include <lttng/lttng.h>
50 #include "connection.h"
51 #include "ctf-trace.h"
52 #include "health-relayd.h"
54 #include "lttng-relayd.h"
57 #include "testpoint.h"
59 #include "viewer-session.h"
60 #include "viewer-stream.h"
62 #define SESSION_BUF_DEFAULT_COUNT 16
64 static struct lttng_uri
*live_uri
;
67 * This pipe is used to inform the worker thread that a command is queued and
68 * ready to be processed.
70 static int live_conn_pipe
[2] = { -1, -1 };
72 /* Shared between threads */
73 static int live_dispatch_thread_exit
;
75 static pthread_t live_listener_thread
;
76 static pthread_t live_dispatcher_thread
;
77 static pthread_t live_worker_thread
;
80 * Relay command queue.
82 * The live_thread_listener and live_thread_dispatcher communicate with this
85 static struct relay_conn_queue viewer_conn_queue
;
87 static uint64_t last_relay_viewer_session_id
;
88 static pthread_mutex_t last_relay_viewer_session_id_lock
=
89 PTHREAD_MUTEX_INITIALIZER
;
95 void cleanup_relayd_live(void)
103 * Receive a request buffer using a given socket, destination allocated buffer
106 * Return the size of the received message or else a negative value on error
107 * with errno being set by recvmsg() syscall.
110 ssize_t
recv_request(struct lttcomm_sock
*sock
, void *buf
, size_t size
)
114 ret
= sock
->ops
->recvmsg(sock
, buf
, size
, 0);
115 if (ret
< 0 || ret
!= size
) {
117 /* Orderly shutdown. Not necessary to print an error. */
118 DBG("Socket %d did an orderly shutdown", sock
->fd
);
120 ERR("Relay failed to receive request.");
129 * Send a response buffer using a given socket, source allocated buffer of
132 * Return the size of the sent message or else a negative value on error with
133 * errno being set by sendmsg() syscall.
136 ssize_t
send_response(struct lttcomm_sock
*sock
, void *buf
, size_t size
)
140 ret
= sock
->ops
->sendmsg(sock
, buf
, size
, 0);
142 ERR("Relayd failed to send response.");
149 * Atomically check if new streams got added in one of the sessions attached
150 * and reset the flag to 0.
152 * Returns 1 if new streams got added, 0 if nothing changed, a negative value
156 int check_new_streams(struct relay_connection
*conn
)
158 struct relay_session
*session
;
159 unsigned long current_val
;
162 if (!conn
->viewer_session
) {
166 cds_list_for_each_entry_rcu(session
,
167 &conn
->viewer_session
->session_list
,
168 viewer_session_node
) {
169 if (!session_get(session
)) {
172 current_val
= uatomic_cmpxchg(&session
->new_streams
, 1, 0);
174 session_put(session
);
185 * Send viewer streams to the given socket. The ignore_sent_flag indicates if
186 * this function should ignore the sent flag or not.
188 * Return 0 on success or else a negative value.
191 ssize_t
send_viewer_streams(struct lttcomm_sock
*sock
,
192 uint64_t session_id
, unsigned int ignore_sent_flag
)
195 struct lttng_ht_iter iter
;
196 struct relay_viewer_stream
*vstream
;
200 cds_lfht_for_each_entry(viewer_streams_ht
->ht
, &iter
.iter
, vstream
,
202 struct ctf_trace
*ctf_trace
;
203 struct lttng_viewer_stream send_stream
= {};
205 health_code_update();
207 if (!viewer_stream_get(vstream
)) {
211 pthread_mutex_lock(&vstream
->stream
->lock
);
212 /* Ignore if not the same session. */
213 if (vstream
->stream
->trace
->session
->id
!= session_id
||
214 (!ignore_sent_flag
&& vstream
->sent_flag
)) {
215 pthread_mutex_unlock(&vstream
->stream
->lock
);
216 viewer_stream_put(vstream
);
220 ctf_trace
= vstream
->stream
->trace
;
221 send_stream
.id
= htobe64(vstream
->stream
->stream_handle
);
222 send_stream
.ctf_trace_id
= htobe64(ctf_trace
->id
);
223 send_stream
.metadata_flag
= htobe32(
224 vstream
->stream
->is_metadata
);
225 if (lttng_strncpy(send_stream
.path_name
, vstream
->path_name
,
226 sizeof(send_stream
.path_name
))) {
227 pthread_mutex_unlock(&vstream
->stream
->lock
);
228 viewer_stream_put(vstream
);
229 ret
= -1; /* Error. */
232 if (lttng_strncpy(send_stream
.channel_name
,
233 vstream
->channel_name
,
234 sizeof(send_stream
.channel_name
))) {
235 pthread_mutex_unlock(&vstream
->stream
->lock
);
236 viewer_stream_put(vstream
);
237 ret
= -1; /* Error. */
241 DBG("Sending stream %" PRIu64
" to viewer",
242 vstream
->stream
->stream_handle
);
243 vstream
->sent_flag
= 1;
244 pthread_mutex_unlock(&vstream
->stream
->lock
);
246 ret
= send_response(sock
, &send_stream
, sizeof(send_stream
));
247 viewer_stream_put(vstream
);
261 * Create every viewer stream possible for the given session with the seek
262 * type. Three counters *can* be return which are in order the total amount of
263 * viewer stream of the session, the number of unsent stream and the number of
264 * stream created. Those counters can be NULL and thus will be ignored.
266 * session must be locked to ensure that we see either none or all initial
267 * streams for a session, but no intermediate state..
269 * Return 0 on success or else a negative value.
271 static int make_viewer_streams(struct relay_session
*relay_session
,
272 struct relay_viewer_session
*viewer_session
,
273 enum lttng_viewer_seek seek_t
,
276 uint32_t *nb_created
,
280 struct lttng_ht_iter iter
;
281 struct ctf_trace
*ctf_trace
;
282 struct relay_stream
*relay_stream
= NULL
;
284 assert(relay_session
);
285 ASSERT_LOCKED(relay_session
->lock
);
287 if (!viewer_session
->current_trace_chunk
) {
288 ERR("Internal error: viewer session associated with session \"%s\" has a NULL trace chunk",
289 relay_session
->session_name
);
294 if (relay_session
->connection_closed
) {
299 * Create viewer streams for relay streams that are ready to be
300 * used for a the given session id only.
303 cds_lfht_for_each_entry (relay_session
->ctf_traces_ht
->ht
, &iter
.iter
,
304 ctf_trace
, node
.node
) {
305 bool trace_has_metadata_stream
= false;
307 health_code_update();
309 if (!ctf_trace_get(ctf_trace
)) {
314 * Iterate over all the streams of the trace to see if we have a
317 cds_list_for_each_entry_rcu(relay_stream
,
318 &ctf_trace
->stream_list
, stream_node
)
320 bool is_metadata_stream
;
322 pthread_mutex_lock(&relay_stream
->lock
);
323 is_metadata_stream
= relay_stream
->is_metadata
;
324 pthread_mutex_unlock(&relay_stream
->lock
);
326 if (is_metadata_stream
) {
327 trace_has_metadata_stream
= true;
335 * If there is no metadata stream in this trace at the moment
336 * and we never sent one to the viewer, skip the trace. We
337 * accept that the viewer will not see this trace at all.
339 if (!trace_has_metadata_stream
&&
340 !ctf_trace
->metadata_stream_sent_to_viewer
) {
341 ctf_trace_put(ctf_trace
);
345 cds_list_for_each_entry_rcu(relay_stream
,
346 &ctf_trace
->stream_list
, stream_node
)
348 struct relay_viewer_stream
*viewer_stream
;
350 if (!stream_get(relay_stream
)) {
354 pthread_mutex_lock(&relay_stream
->lock
);
356 * stream published is protected by the session lock.
358 if (!relay_stream
->published
) {
361 viewer_stream
= viewer_stream_get_by_id(
362 relay_stream
->stream_handle
);
363 if (!viewer_stream
) {
364 struct lttng_trace_chunk
*viewer_stream_trace_chunk
;
367 * Save that we sent the metadata stream to the
368 * viewer. So that we know what trace the viewer
371 if (relay_stream
->is_metadata
) {
372 ctf_trace
->metadata_stream_sent_to_viewer
= true;
376 * If a rotation is ongoing, use a copy of the
377 * relay stream's chunk to ensure the stream
380 * Otherwise, the viewer session's current trace
381 * chunk can be used safely.
383 if ((relay_stream
->ongoing_rotation
.is_set
||
384 relay_session
->ongoing_rotation
) &&
385 relay_stream
->trace_chunk
) {
386 viewer_stream_trace_chunk
= lttng_trace_chunk_copy(
387 relay_stream
->trace_chunk
);
388 if (!viewer_stream_trace_chunk
) {
390 ctf_trace_put(ctf_trace
);
394 const bool reference_acquired
= lttng_trace_chunk_get(
395 viewer_session
->current_trace_chunk
);
397 assert(reference_acquired
);
398 viewer_stream_trace_chunk
=
399 viewer_session
->current_trace_chunk
;
402 viewer_stream
= viewer_stream_create(
404 viewer_stream_trace_chunk
,
406 lttng_trace_chunk_put(viewer_stream_trace_chunk
);
407 viewer_stream_trace_chunk
= NULL
;
408 if (!viewer_stream
) {
410 ctf_trace_put(ctf_trace
);
415 /* Update number of created stream counter. */
419 * Ensure a self-reference is preserved even
420 * after we have put our local reference.
422 if (!viewer_stream_get(viewer_stream
)) {
423 ERR("Unable to get self-reference on viewer stream, logic error.");
427 if (!viewer_stream
->sent_flag
&& nb_unsent
) {
428 /* Update number of unsent stream counter. */
432 /* Update number of total stream counter. */
434 if (relay_stream
->is_metadata
) {
435 if (!relay_stream
->closed
||
436 relay_stream
->metadata_received
>
437 viewer_stream
->metadata_sent
) {
441 if (!relay_stream
->closed
||
442 !(((int64_t)(relay_stream
->prev_data_seq
-
443 relay_stream
->last_net_seq_num
)) >=
449 /* Put local reference. */
450 viewer_stream_put(viewer_stream
);
452 pthread_mutex_unlock(&relay_stream
->lock
);
453 stream_put(relay_stream
);
456 ctf_trace_put(ctf_trace
);
465 pthread_mutex_unlock(&relay_stream
->lock
);
466 stream_put(relay_stream
);
472 int relayd_live_stop(void)
474 /* Stop dispatch thread */
475 CMM_STORE_SHARED(live_dispatch_thread_exit
, 1);
476 futex_nto1_wake(&viewer_conn_queue
.futex
);
481 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
484 int create_named_thread_poll_set(struct lttng_poll_event
*events
,
485 int size
, const char *name
)
489 if (events
== NULL
|| size
== 0) {
494 ret
= fd_tracker_util_poll_create(the_fd_tracker
,
495 name
, events
, 1, LTTNG_CLOEXEC
);
497 PERROR("Failed to create \"%s\" poll file descriptor", name
);
502 ret
= lttng_poll_add(events
, thread_quit_pipe
[0], LPOLLIN
| LPOLLERR
);
514 * Check if the thread quit pipe was triggered.
516 * Return 1 if it was triggered else 0;
519 int check_thread_quit_pipe(int fd
, uint32_t events
)
521 if (fd
== thread_quit_pipe
[0] && (events
& LPOLLIN
)) {
529 int create_sock(void *data
, int *out_fd
)
532 struct lttcomm_sock
*sock
= data
;
534 ret
= lttcomm_create_sock(sock
);
545 int close_sock(void *data
, int *in_fd
)
547 struct lttcomm_sock
*sock
= data
;
549 return sock
->ops
->close(sock
);
552 static int accept_sock(void *data
, int *out_fd
)
555 /* Socks is an array of in_sock, out_sock. */
556 struct lttcomm_sock
**socks
= data
;
557 struct lttcomm_sock
*in_sock
= socks
[0];
559 socks
[1] = in_sock
->ops
->accept(in_sock
);
564 *out_fd
= socks
[1]->fd
;
570 struct lttcomm_sock
*accept_live_sock(struct lttcomm_sock
*listening_sock
,
574 struct lttcomm_sock
*socks
[2] = { listening_sock
, NULL
};
575 struct lttcomm_sock
*new_sock
= NULL
;
577 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &out_fd
,
578 (const char **) &name
, 1, accept_sock
, &socks
);
583 DBG("%s accepted, socket %d", name
, new_sock
->fd
);
589 * Create and init socket from uri.
592 struct lttcomm_sock
*init_socket(struct lttng_uri
*uri
, const char *name
)
595 struct lttcomm_sock
*sock
= NULL
;
596 char uri_str
[LTTNG_PATH_MAX
];
597 char *formated_name
= NULL
;
599 sock
= lttcomm_alloc_sock_from_uri(uri
);
601 ERR("Allocating socket");
606 * Don't fail to create the socket if the name can't be built as it is
607 * only used for debugging purposes.
609 ret
= uri_to_str_url(uri
, uri_str
, sizeof(uri_str
));
610 uri_str
[sizeof(uri_str
) - 1] = '\0';
612 ret
= asprintf(&formated_name
, "%s socket @ %s", name
,
615 formated_name
= NULL
;
619 ret
= fd_tracker_open_unsuspendable_fd(the_fd_tracker
, &sock_fd
,
620 (const char **) (formated_name
? &formated_name
: NULL
),
621 1, create_sock
, sock
);
623 PERROR("Failed to create \"%s\" socket",
624 formated_name
?: "Unknown");
627 DBG("Listening on %s socket %d", name
, sock
->fd
);
629 ret
= sock
->ops
->bind(sock
);
631 PERROR("Failed to bind lttng-live socket");
635 ret
= sock
->ops
->listen(sock
, -1);
646 lttcomm_destroy_sock(sock
);
653 * This thread manages the listening for new connections on the network
656 void *thread_listener(void *data
)
658 int i
, ret
, pollfd
, err
= -1;
659 uint32_t revents
, nb_fd
;
660 struct lttng_poll_event events
;
661 struct lttcomm_sock
*live_control_sock
;
663 DBG("[thread] Relay live listener started");
665 rcu_register_thread();
666 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LIVE_LISTENER
);
668 health_code_update();
670 live_control_sock
= init_socket(live_uri
, "Live listener");
671 if (!live_control_sock
) {
672 goto error_sock_control
;
675 /* Pass 2 as size here for the thread quit pipe and control sockets. */
676 ret
= create_named_thread_poll_set(&events
, 2,
677 "Live listener thread epoll");
679 goto error_create_poll
;
682 /* Add the control socket */
683 ret
= lttng_poll_add(&events
, live_control_sock
->fd
, LPOLLIN
| LPOLLRDHUP
);
688 lttng_relay_notify_ready();
690 if (testpoint(relayd_thread_live_listener
)) {
691 goto error_testpoint
;
695 health_code_update();
697 DBG("Listener accepting live viewers connections");
701 ret
= lttng_poll_wait(&events
, -1);
705 * Restart interrupted system call.
707 if (errno
== EINTR
) {
714 DBG("Relay new viewer connection received");
715 for (i
= 0; i
< nb_fd
; i
++) {
716 health_code_update();
718 /* Fetch once the poll data */
719 revents
= LTTNG_POLL_GETEV(&events
, i
);
720 pollfd
= LTTNG_POLL_GETFD(&events
, i
);
722 /* Thread quit pipe has been closed. Killing thread. */
723 ret
= check_thread_quit_pipe(pollfd
, revents
);
729 if (revents
& LPOLLIN
) {
731 * A new connection is requested, therefore a
732 * viewer connection is allocated in this
733 * thread, enqueued to a global queue and
734 * dequeued (and freed) in the worker thread.
737 struct relay_connection
*new_conn
;
738 struct lttcomm_sock
*newsock
;
740 newsock
= accept_live_sock(live_control_sock
,
741 "Live socket to client");
743 PERROR("accepting control sock");
746 DBG("Relay viewer connection accepted socket %d", newsock
->fd
);
748 ret
= setsockopt(newsock
->fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
,
751 PERROR("setsockopt inet");
752 lttcomm_destroy_sock(newsock
);
755 new_conn
= connection_create(newsock
, RELAY_CONNECTION_UNKNOWN
);
757 lttcomm_destroy_sock(newsock
);
760 /* Ownership assumed by the connection. */
763 /* Enqueue request for the dispatcher thread. */
764 cds_wfcq_enqueue(&viewer_conn_queue
.head
, &viewer_conn_queue
.tail
,
768 * Wake the dispatch queue futex.
769 * Implicit memory barrier with the
770 * exchange in cds_wfcq_enqueue.
772 futex_nto1_wake(&viewer_conn_queue
.futex
);
773 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
774 ERR("socket poll error");
777 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
787 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
789 if (live_control_sock
->fd
>= 0) {
790 int sock_fd
= live_control_sock
->fd
;
792 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
,
793 &sock_fd
, 1, close_sock
,
798 live_control_sock
->fd
= -1;
800 lttcomm_destroy_sock(live_control_sock
);
804 DBG("Live viewer listener thread exited with error");
806 health_unregister(health_relayd
);
807 rcu_unregister_thread();
808 DBG("Live viewer listener thread cleanup complete");
809 if (lttng_relay_stop_threads()) {
810 ERR("Error stopping threads");
816 * This thread manages the dispatching of the requests to worker threads
819 void *thread_dispatcher(void *data
)
823 struct cds_wfcq_node
*node
;
824 struct relay_connection
*conn
= NULL
;
826 DBG("[thread] Live viewer relay dispatcher started");
828 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LIVE_DISPATCHER
);
830 if (testpoint(relayd_thread_live_dispatcher
)) {
831 goto error_testpoint
;
834 health_code_update();
837 health_code_update();
839 /* Atomically prepare the queue futex */
840 futex_nto1_prepare(&viewer_conn_queue
.futex
);
842 if (CMM_LOAD_SHARED(live_dispatch_thread_exit
)) {
847 health_code_update();
849 /* Dequeue commands */
850 node
= cds_wfcq_dequeue_blocking(&viewer_conn_queue
.head
,
851 &viewer_conn_queue
.tail
);
853 DBG("Woken up but nothing in the live-viewer "
854 "relay command queue");
855 /* Continue thread execution */
858 conn
= caa_container_of(node
, struct relay_connection
, qnode
);
859 DBG("Dispatching viewer request waiting on sock %d",
863 * Inform worker thread of the new request. This
864 * call is blocking so we can be assured that
865 * the data will be read at some point in time
866 * or wait to the end of the world :)
868 ret
= lttng_write(live_conn_pipe
[1], &conn
, sizeof(conn
));
870 PERROR("write conn pipe");
871 connection_put(conn
);
874 } while (node
!= NULL
);
876 /* Futex wait on queue. Blocking call on futex() */
878 futex_nto1_wait(&viewer_conn_queue
.futex
);
882 /* Normal exit, no error */
889 ERR("Health error occurred in %s", __func__
);
891 health_unregister(health_relayd
);
892 DBG("Live viewer dispatch thread dying");
893 if (lttng_relay_stop_threads()) {
894 ERR("Error stopping threads");
900 * Establish connection with the viewer and check the versions.
902 * Return 0 on success or else negative value.
905 int viewer_connect(struct relay_connection
*conn
)
908 struct lttng_viewer_connect reply
, msg
;
910 conn
->version_check_done
= 1;
912 health_code_update();
914 DBG("Viewer is establishing a connection to the relayd.");
916 ret
= recv_request(conn
->sock
, &msg
, sizeof(msg
));
921 health_code_update();
923 memset(&reply
, 0, sizeof(reply
));
924 reply
.major
= RELAYD_VERSION_COMM_MAJOR
;
925 reply
.minor
= RELAYD_VERSION_COMM_MINOR
;
927 /* Major versions must be the same */
928 if (reply
.major
!= be32toh(msg
.major
)) {
929 DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
930 reply
.major
, be32toh(msg
.major
));
935 conn
->major
= reply
.major
;
936 /* We adapt to the lowest compatible version */
937 if (reply
.minor
<= be32toh(msg
.minor
)) {
938 conn
->minor
= reply
.minor
;
940 conn
->minor
= be32toh(msg
.minor
);
943 if (be32toh(msg
.type
) == LTTNG_VIEWER_CLIENT_COMMAND
) {
944 conn
->type
= RELAY_VIEWER_COMMAND
;
945 } else if (be32toh(msg
.type
) == LTTNG_VIEWER_CLIENT_NOTIFICATION
) {
946 conn
->type
= RELAY_VIEWER_NOTIFICATION
;
948 ERR("Unknown connection type : %u", be32toh(msg
.type
));
953 reply
.major
= htobe32(reply
.major
);
954 reply
.minor
= htobe32(reply
.minor
);
955 if (conn
->type
== RELAY_VIEWER_COMMAND
) {
957 * Increment outside of htobe64 macro, because the argument can
958 * be used more than once within the macro, and thus the
959 * operation may be undefined.
961 pthread_mutex_lock(&last_relay_viewer_session_id_lock
);
962 last_relay_viewer_session_id
++;
963 pthread_mutex_unlock(&last_relay_viewer_session_id_lock
);
964 reply
.viewer_session_id
= htobe64(last_relay_viewer_session_id
);
967 health_code_update();
969 ret
= send_response(conn
->sock
, &reply
, sizeof(reply
));
974 health_code_update();
976 DBG("Version check done using protocol %u.%u", conn
->major
, conn
->minor
);
984 * Send the viewer the list of current sessions.
985 * We need to create a copy of the hash table content because otherwise
986 * we cannot assume the number of entries stays the same between getting
987 * the number of HT elements and iteration over the HT.
989 * Return 0 on success or else a negative value.
992 int viewer_list_sessions(struct relay_connection
*conn
)
995 struct lttng_viewer_list_sessions session_list
;
996 struct lttng_ht_iter iter
;
997 struct relay_session
*session
;
998 struct lttng_viewer_session
*send_session_buf
= NULL
;
999 uint32_t buf_count
= SESSION_BUF_DEFAULT_COUNT
;
1002 DBG("List sessions received");
1004 send_session_buf
= zmalloc(SESSION_BUF_DEFAULT_COUNT
* sizeof(*send_session_buf
));
1005 if (!send_session_buf
) {
1010 cds_lfht_for_each_entry(sessions_ht
->ht
, &iter
.iter
, session
,
1012 struct lttng_viewer_session
*send_session
;
1014 health_code_update();
1016 pthread_mutex_lock(&session
->lock
);
1017 if (session
->connection_closed
) {
1018 /* Skip closed session */
1021 if (!session
->current_trace_chunk
) {
1023 * Skip un-attachable session. It is either
1024 * being destroyed or has not had a trace
1025 * chunk created against it yet.
1030 if (count
>= buf_count
) {
1031 struct lttng_viewer_session
*newbuf
;
1032 uint32_t new_buf_count
= buf_count
<< 1;
1034 newbuf
= realloc(send_session_buf
,
1035 new_buf_count
* sizeof(*send_session_buf
));
1040 send_session_buf
= newbuf
;
1041 buf_count
= new_buf_count
;
1043 send_session
= &send_session_buf
[count
];
1044 if (lttng_strncpy(send_session
->session_name
,
1045 session
->session_name
,
1046 sizeof(send_session
->session_name
))) {
1050 if (lttng_strncpy(send_session
->hostname
, session
->hostname
,
1051 sizeof(send_session
->hostname
))) {
1055 send_session
->id
= htobe64(session
->id
);
1056 send_session
->live_timer
= htobe32(session
->live_timer
);
1057 if (session
->viewer_attached
) {
1058 send_session
->clients
= htobe32(1);
1060 send_session
->clients
= htobe32(0);
1062 send_session
->streams
= htobe32(session
->stream_count
);
1065 pthread_mutex_unlock(&session
->lock
);
1068 pthread_mutex_unlock(&session
->lock
);
1076 session_list
.sessions_count
= htobe32(count
);
1078 health_code_update();
1080 ret
= send_response(conn
->sock
, &session_list
, sizeof(session_list
));
1085 health_code_update();
1087 ret
= send_response(conn
->sock
, send_session_buf
,
1088 count
* sizeof(*send_session_buf
));
1092 health_code_update();
1096 free(send_session_buf
);
1101 * Send the viewer the list of current streams.
1104 int viewer_get_new_streams(struct relay_connection
*conn
)
1106 int ret
, send_streams
= 0;
1107 uint32_t nb_created
= 0, nb_unsent
= 0, nb_streams
= 0, nb_total
= 0;
1108 struct lttng_viewer_new_streams_request request
;
1109 struct lttng_viewer_new_streams_response response
;
1110 struct relay_session
*session
= NULL
;
1111 uint64_t session_id
;
1112 bool closed
= false;
1116 DBG("Get new streams received");
1118 health_code_update();
1120 /* Receive the request from the connected client. */
1121 ret
= recv_request(conn
->sock
, &request
, sizeof(request
));
1125 session_id
= be64toh(request
.session_id
);
1127 health_code_update();
1129 memset(&response
, 0, sizeof(response
));
1131 session
= session_get_by_id(session_id
);
1133 DBG("Relay session %" PRIu64
" not found", session_id
);
1134 response
.status
= htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR
);
1138 if (!viewer_session_is_attached(conn
->viewer_session
, session
)) {
1139 response
.status
= htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR
);
1144 * For any new stream, create it with LTTNG_VIEWER_SEEK_BEGINNING since
1145 * that at this point the client is already attached to the session.Aany
1146 * initial stream will have been created with the seek type at attach
1147 * time (for now most readers use the LTTNG_VIEWER_SEEK_LAST on attach).
1148 * Otherwise any event happening in a new stream between the attach and
1149 * a call to viewer_get_new_streams will be "lost" (never received) from
1150 * the viewer's point of view.
1152 pthread_mutex_lock(&session
->lock
);
1153 ret
= make_viewer_streams(session
,
1154 conn
->viewer_session
,
1155 LTTNG_VIEWER_SEEK_BEGINNING
, &nb_total
, &nb_unsent
,
1156 &nb_created
, &closed
);
1158 goto error_unlock_session
;
1161 response
.status
= htobe32(LTTNG_VIEWER_NEW_STREAMS_OK
);
1163 /* Only send back the newly created streams with the unsent ones. */
1164 nb_streams
= nb_created
+ nb_unsent
;
1165 response
.streams_count
= htobe32(nb_streams
);
1168 * If the session is closed, HUP when there are no more streams
1171 if (closed
&& nb_total
== 0) {
1173 response
.streams_count
= 0;
1174 response
.status
= htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP
);
1175 goto send_reply_unlock
;
1178 pthread_mutex_unlock(&session
->lock
);
1181 health_code_update();
1182 ret
= send_response(conn
->sock
, &response
, sizeof(response
));
1184 goto end_put_session
;
1186 health_code_update();
1189 * Unknown or empty session, just return gracefully, the viewer
1190 * knows what is happening.
1192 if (!send_streams
|| !nb_streams
) {
1194 goto end_put_session
;
1198 * Send stream and *DON'T* ignore the sent flag so every viewer
1199 * streams that were not sent from that point will be sent to
1202 ret
= send_viewer_streams(conn
->sock
, session_id
, 0);
1204 goto end_put_session
;
1209 session_put(session
);
1213 error_unlock_session
:
1214 pthread_mutex_unlock(&session
->lock
);
1215 session_put(session
);
1220 * Send the viewer the list of current sessions.
1223 int viewer_attach_session(struct relay_connection
*conn
)
1225 int send_streams
= 0;
1227 uint32_t nb_streams
= 0;
1228 enum lttng_viewer_seek seek_type
;
1229 struct lttng_viewer_attach_session_request request
;
1230 struct lttng_viewer_attach_session_response response
;
1231 struct relay_session
*session
= NULL
;
1232 enum lttng_viewer_attach_return_code viewer_attach_status
;
1233 bool closed
= false;
1234 uint64_t session_id
;
1238 health_code_update();
1240 /* Receive the request from the connected client. */
1241 ret
= recv_request(conn
->sock
, &request
, sizeof(request
));
1246 session_id
= be64toh(request
.session_id
);
1247 health_code_update();
1249 memset(&response
, 0, sizeof(response
));
1251 if (!conn
->viewer_session
) {
1252 DBG("Client trying to attach before creating a live viewer session");
1253 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION
);
1257 session
= session_get_by_id(session_id
);
1259 DBG("Relay session %" PRIu64
" not found", session_id
);
1260 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_UNK
);
1263 DBG("Attach session ID %" PRIu64
" received", session_id
);
1265 pthread_mutex_lock(&session
->lock
);
1266 if (!session
->current_trace_chunk
) {
1268 * Session is either being destroyed or it never had a trace
1269 * chunk created against it.
1271 DBG("Session requested by live client has no current trace chunk, returning unknown session");
1272 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_UNK
);
1275 if (session
->live_timer
== 0) {
1276 DBG("Not live session");
1277 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE
);
1282 viewer_attach_status
= viewer_session_attach(conn
->viewer_session
,
1284 if (viewer_attach_status
!= LTTNG_VIEWER_ATTACH_OK
) {
1285 response
.status
= htobe32(viewer_attach_status
);
1289 switch (be32toh(request
.seek
)) {
1290 case LTTNG_VIEWER_SEEK_BEGINNING
:
1291 case LTTNG_VIEWER_SEEK_LAST
:
1292 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_OK
);
1293 seek_type
= be32toh(request
.seek
);
1296 ERR("Wrong seek parameter");
1297 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR
);
1302 ret
= make_viewer_streams(session
,
1303 conn
->viewer_session
, seek_type
,
1304 &nb_streams
, NULL
, NULL
, &closed
);
1306 goto end_put_session
;
1308 pthread_mutex_unlock(&session
->lock
);
1309 session_put(session
);
1312 response
.streams_count
= htobe32(nb_streams
);
1314 * If the session is closed when the viewer is attaching, it
1315 * means some of the streams may have been concurrently removed,
1316 * so we don't allow the viewer to attach, even if there are
1317 * streams available.
1321 response
.streams_count
= 0;
1322 response
.status
= htobe32(LTTNG_VIEWER_ATTACH_UNK
);
1327 health_code_update();
1328 ret
= send_response(conn
->sock
, &response
, sizeof(response
));
1330 goto end_put_session
;
1332 health_code_update();
1335 * Unknown or empty session, just return gracefully, the viewer
1336 * knows what is happening.
1338 if (!send_streams
|| !nb_streams
) {
1340 goto end_put_session
;
1343 /* Send stream and ignore the sent flag. */
1344 ret
= send_viewer_streams(conn
->sock
, session_id
, 1);
1346 goto end_put_session
;
1351 pthread_mutex_unlock(&session
->lock
);
1352 session_put(session
);
1359 * Open the index file if needed for the given vstream.
1361 * If an index file is successfully opened, the vstream will set it as its
1362 * current index file.
1364 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
1366 * Called with rstream lock held.
1368 static int try_open_index(struct relay_viewer_stream
*vstream
,
1369 struct relay_stream
*rstream
)
1372 const uint32_t connection_major
= rstream
->trace
->session
->major
;
1373 const uint32_t connection_minor
= rstream
->trace
->session
->minor
;
1374 enum lttng_trace_chunk_status chunk_status
;
1376 if (vstream
->index_file
) {
1381 * First time, we open the index file and at least one index is ready.
1383 if (rstream
->index_received_seqcount
== 0) {
1387 chunk_status
= lttng_index_file_create_from_trace_chunk_read_only(
1388 vstream
->stream_file
.trace_chunk
, rstream
->path_name
,
1389 rstream
->channel_name
, rstream
->tracefile_size
,
1390 vstream
->current_tracefile_id
,
1391 lttng_to_index_major(connection_major
, connection_minor
),
1392 lttng_to_index_minor(connection_major
, connection_minor
),
1393 true, &vstream
->index_file
);
1394 if (chunk_status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
1395 if (chunk_status
== LTTNG_TRACE_CHUNK_STATUS_NO_FILE
) {
1407 * Check the status of the index for the given stream. This function
1408 * updates the index structure if needed and can put (close) the vstream
1409 * in the HUP situation.
1411 * Return 0 means that we can proceed with the index. A value of 1 means
1412 * that the index has been updated and is ready to be sent to the
1413 * client. A negative value indicates an error that can't be handled.
1415 * Called with rstream lock held.
1417 static int check_index_status(struct relay_viewer_stream
*vstream
,
1418 struct relay_stream
*rstream
, struct ctf_trace
*trace
,
1419 struct lttng_viewer_index
*index
)
1423 DBG("Check index status: index_received_seqcount %" PRIu64
" "
1424 "index_sent_seqcount %" PRIu64
" "
1425 "for stream %" PRIu64
,
1426 rstream
->index_received_seqcount
,
1427 vstream
->index_sent_seqcount
,
1428 vstream
->stream
->stream_handle
);
1429 if ((trace
->session
->connection_closed
|| rstream
->closed
)
1430 && rstream
->index_received_seqcount
1431 == vstream
->index_sent_seqcount
) {
1433 * Last index sent and session connection or relay
1434 * stream are closed.
1436 index
->status
= htobe32(LTTNG_VIEWER_INDEX_HUP
);
1438 } else if (rstream
->beacon_ts_end
!= -1ULL &&
1439 (rstream
->index_received_seqcount
== 0 ||
1440 (vstream
->index_sent_seqcount
!= 0 &&
1441 rstream
->index_received_seqcount
1442 <= vstream
->index_sent_seqcount
))) {
1444 * We've received a synchronization beacon and the last index
1445 * available has been sent, the index for now is inactive.
1447 * In this case, we have received a beacon which allows us to
1448 * inform the client of a time interval during which we can
1449 * guarantee that there are no events to read (and never will
1452 * The sent seqcount can grow higher than receive seqcount on
1453 * clear because the rotation performed by clear will push
1454 * the index_sent_seqcount ahead (see
1455 * viewer_stream_sync_tracefile_array_tail) and skip over
1456 * packet sequence numbers.
1458 index
->status
= htobe32(LTTNG_VIEWER_INDEX_INACTIVE
);
1459 index
->timestamp_end
= htobe64(rstream
->beacon_ts_end
);
1460 index
->stream_id
= htobe64(rstream
->ctf_stream_id
);
1461 DBG("Check index status: inactive with beacon, for stream %" PRIu64
,
1462 vstream
->stream
->stream_handle
);
1464 } else if (rstream
->index_received_seqcount
== 0 ||
1465 (vstream
->index_sent_seqcount
!= 0 &&
1466 rstream
->index_received_seqcount
1467 <= vstream
->index_sent_seqcount
)) {
1469 * This checks whether received <= sent seqcount. In
1470 * this case, we have not received a beacon. Therefore,
1471 * we can only ask the client to retry later.
1473 * The sent seqcount can grow higher than receive seqcount on
1474 * clear because the rotation performed by clear will push
1475 * the index_sent_seqcount ahead (see
1476 * viewer_stream_sync_tracefile_array_tail) and skip over
1477 * packet sequence numbers.
1479 index
->status
= htobe32(LTTNG_VIEWER_INDEX_RETRY
);
1480 DBG("Check index status: retry for stream %" PRIu64
,
1481 vstream
->stream
->stream_handle
);
1483 } else if (!tracefile_array_seq_in_file(rstream
->tfa
,
1484 vstream
->current_tracefile_id
,
1485 vstream
->index_sent_seqcount
)) {
1487 * The next index we want to send cannot be read either
1488 * because we need to perform a rotation, or due to
1489 * the producer having overwritten its trace file.
1491 DBG("Viewer stream %" PRIu64
" rotation",
1492 vstream
->stream
->stream_handle
);
1493 ret
= viewer_stream_rotate(vstream
);
1495 /* EOF across entire stream. */
1496 index
->status
= htobe32(LTTNG_VIEWER_INDEX_HUP
);
1500 * If we have been pushed due to overwrite, it
1501 * necessarily means there is data that can be read in
1502 * the stream. If we rotated because we reached the end
1503 * of a tracefile, it means the following tracefile
1504 * needs to contain at least one index, else we would
1505 * have already returned LTTNG_VIEWER_INDEX_RETRY to the
1506 * viewer. The updated index_sent_seqcount needs to
1507 * point to a readable index entry now.
1509 * In the case where we "rotate" on a single file, we
1510 * can end up in a case where the requested index is
1511 * still unavailable.
1513 if (rstream
->tracefile_count
== 1 &&
1514 !tracefile_array_seq_in_file(
1516 vstream
->current_tracefile_id
,
1517 vstream
->index_sent_seqcount
)) {
1518 index
->status
= htobe32(LTTNG_VIEWER_INDEX_RETRY
);
1519 DBG("Check index status: retry: "
1520 "tracefile array sequence number %" PRIu64
1521 " not in file for stream %" PRIu64
,
1522 vstream
->index_sent_seqcount
,
1523 vstream
->stream
->stream_handle
);
1526 assert(tracefile_array_seq_in_file(rstream
->tfa
,
1527 vstream
->current_tracefile_id
,
1528 vstream
->index_sent_seqcount
));
1530 /* ret == 0 means successful so we continue. */
1535 viewer_stream_put(vstream
);
1541 * Send the next index for a stream.
1543 * Return 0 on success or else a negative value.
1546 int viewer_get_next_index(struct relay_connection
*conn
)
1549 struct lttng_viewer_get_next_index request_index
;
1550 struct lttng_viewer_index viewer_index
;
1551 struct ctf_packet_index packet_index
;
1552 struct relay_viewer_stream
*vstream
= NULL
;
1553 struct relay_stream
*rstream
= NULL
;
1554 struct ctf_trace
*ctf_trace
= NULL
;
1555 struct relay_viewer_stream
*metadata_viewer_stream
= NULL
;
1559 DBG("Viewer get next index");
1561 memset(&viewer_index
, 0, sizeof(viewer_index
));
1562 health_code_update();
1564 ret
= recv_request(conn
->sock
, &request_index
, sizeof(request_index
));
1568 health_code_update();
1570 vstream
= viewer_stream_get_by_id(be64toh(request_index
.stream_id
));
1572 DBG("Client requested index of unknown stream id %" PRIu64
,
1573 (uint64_t) be64toh(request_index
.stream_id
));
1574 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_ERR
);
1578 /* Use back. ref. Protected by refcounts. */
1579 rstream
= vstream
->stream
;
1580 ctf_trace
= rstream
->trace
;
1582 /* metadata_viewer_stream may be NULL. */
1583 metadata_viewer_stream
=
1584 ctf_trace_get_viewer_metadata_stream(ctf_trace
);
1586 pthread_mutex_lock(&rstream
->lock
);
1589 * The viewer should not ask for index on metadata stream.
1591 if (rstream
->is_metadata
) {
1592 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_HUP
);
1596 if (rstream
->ongoing_rotation
.is_set
) {
1597 /* Rotation is ongoing, try again later. */
1598 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_RETRY
);
1602 if (rstream
->trace
->session
->ongoing_rotation
) {
1603 /* Rotation is ongoing, try again later. */
1604 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_RETRY
);
1608 if (rstream
->trace_chunk
&& !lttng_trace_chunk_ids_equal(
1609 conn
->viewer_session
->current_trace_chunk
,
1610 rstream
->trace_chunk
)) {
1611 DBG("Relay stream and viewer chunk ids differ");
1613 ret
= viewer_session_set_trace_chunk_copy(
1614 conn
->viewer_session
,
1615 rstream
->trace_chunk
);
1617 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_ERR
);
1621 if (conn
->viewer_session
->current_trace_chunk
!=
1622 vstream
->stream_file
.trace_chunk
) {
1623 bool acquired_reference
;
1625 DBG("Viewer session and viewer stream chunk differ: "
1626 "vsession chunk %p vstream chunk %p",
1627 conn
->viewer_session
->current_trace_chunk
,
1628 vstream
->stream_file
.trace_chunk
);
1629 lttng_trace_chunk_put(vstream
->stream_file
.trace_chunk
);
1630 acquired_reference
= lttng_trace_chunk_get(conn
->viewer_session
->current_trace_chunk
);
1631 assert(acquired_reference
);
1632 vstream
->stream_file
.trace_chunk
=
1633 conn
->viewer_session
->current_trace_chunk
;
1634 viewer_stream_sync_tracefile_array_tail(vstream
);
1635 viewer_stream_close_files(vstream
);
1638 ret
= check_index_status(vstream
, rstream
, ctf_trace
, &viewer_index
);
1641 } else if (ret
== 1) {
1643 * We have no index to send and check_index_status has populated
1644 * viewer_index's status.
1648 /* At this point, ret is 0 thus we will be able to read the index. */
1651 /* Try to open an index if one is needed for that stream. */
1652 ret
= try_open_index(vstream
, rstream
);
1653 if (ret
== -ENOENT
) {
1654 if (rstream
->closed
) {
1655 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_HUP
);
1658 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_RETRY
);
1663 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_ERR
);
1668 * vstream->stream_fd may be NULL if it has been closed by
1669 * tracefile rotation, or if we are at the beginning of the
1670 * stream. We open the data stream file here to protect against
1671 * overwrite caused by tracefile rotation (in association with
1672 * unlink performed before overwrite).
1674 if (!vstream
->stream_file
.handle
) {
1675 char file_path
[LTTNG_PATH_MAX
];
1676 enum lttng_trace_chunk_status status
;
1677 struct fs_handle
*fs_handle
;
1679 ret
= utils_stream_file_path(rstream
->path_name
,
1680 rstream
->channel_name
, rstream
->tracefile_size
,
1681 vstream
->current_tracefile_id
, NULL
, file_path
,
1688 * It is possible the the file we are trying to open is
1689 * missing if the stream has been closed (application exits with
1690 * per-pid buffers) and a clear command has been performed.
1692 status
= lttng_trace_chunk_open_fs_handle(
1693 vstream
->stream_file
.trace_chunk
,
1694 file_path
, O_RDONLY
, 0, &fs_handle
, true);
1695 if (status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
1696 if (status
== LTTNG_TRACE_CHUNK_STATUS_NO_FILE
&&
1698 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_HUP
);
1701 PERROR("Failed to open trace file for viewer stream");
1704 vstream
->stream_file
.handle
= fs_handle
;
1707 ret
= check_new_streams(conn
);
1709 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_ERR
);
1711 } else if (ret
== 1) {
1712 viewer_index
.flags
|= LTTNG_VIEWER_FLAG_NEW_STREAM
;
1715 ret
= lttng_index_file_read(vstream
->index_file
, &packet_index
);
1717 ERR("Relay error reading index file");
1718 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_ERR
);
1721 viewer_index
.status
= htobe32(LTTNG_VIEWER_INDEX_OK
);
1722 vstream
->index_sent_seqcount
++;
1726 * Indexes are stored in big endian, no need to switch before sending.
1728 DBG("Sending viewer index for stream %" PRIu64
" offset %" PRIu64
,
1729 rstream
->stream_handle
,
1730 (uint64_t) be64toh(packet_index
.offset
));
1731 viewer_index
.offset
= packet_index
.offset
;
1732 viewer_index
.packet_size
= packet_index
.packet_size
;
1733 viewer_index
.content_size
= packet_index
.content_size
;
1734 viewer_index
.timestamp_begin
= packet_index
.timestamp_begin
;
1735 viewer_index
.timestamp_end
= packet_index
.timestamp_end
;
1736 viewer_index
.events_discarded
= packet_index
.events_discarded
;
1737 viewer_index
.stream_id
= packet_index
.stream_id
;
1741 pthread_mutex_unlock(&rstream
->lock
);
1744 if (metadata_viewer_stream
) {
1745 pthread_mutex_lock(&metadata_viewer_stream
->stream
->lock
);
1746 DBG("get next index metadata check: recv %" PRIu64
1748 metadata_viewer_stream
->stream
->metadata_received
,
1749 metadata_viewer_stream
->metadata_sent
);
1750 if (!metadata_viewer_stream
->stream
->metadata_received
||
1751 metadata_viewer_stream
->stream
->metadata_received
>
1752 metadata_viewer_stream
->metadata_sent
) {
1753 viewer_index
.flags
|= LTTNG_VIEWER_FLAG_NEW_METADATA
;
1755 pthread_mutex_unlock(&metadata_viewer_stream
->stream
->lock
);
1758 viewer_index
.flags
= htobe32(viewer_index
.flags
);
1759 health_code_update();
1761 ret
= send_response(conn
->sock
, &viewer_index
, sizeof(viewer_index
));
1765 health_code_update();
1768 DBG("Index %" PRIu64
" for stream %" PRIu64
" sent",
1769 vstream
->index_sent_seqcount
,
1770 vstream
->stream
->stream_handle
);
1773 if (metadata_viewer_stream
) {
1774 viewer_stream_put(metadata_viewer_stream
);
1777 viewer_stream_put(vstream
);
1782 pthread_mutex_unlock(&rstream
->lock
);
1783 if (metadata_viewer_stream
) {
1784 viewer_stream_put(metadata_viewer_stream
);
1786 viewer_stream_put(vstream
);
1791 * Send the next index for a stream
1793 * Return 0 on success or else a negative value.
1796 int viewer_get_packet(struct relay_connection
*conn
)
1801 struct lttng_viewer_get_packet get_packet_info
;
1802 struct lttng_viewer_trace_packet reply_header
;
1803 struct relay_viewer_stream
*vstream
= NULL
;
1804 uint32_t reply_size
= sizeof(reply_header
);
1805 uint32_t packet_data_len
= 0;
1809 DBG2("Relay get data packet");
1811 health_code_update();
1813 ret
= recv_request(conn
->sock
, &get_packet_info
,
1814 sizeof(get_packet_info
));
1818 health_code_update();
1820 /* From this point on, the error label can be reached. */
1821 memset(&reply_header
, 0, sizeof(reply_header
));
1822 stream_id
= (uint64_t) be64toh(get_packet_info
.stream_id
);
1824 vstream
= viewer_stream_get_by_id(stream_id
);
1826 DBG("Client requested packet of unknown stream id %" PRIu64
,
1828 reply_header
.status
= htobe32(LTTNG_VIEWER_GET_PACKET_ERR
);
1829 goto send_reply_nolock
;
1831 packet_data_len
= be32toh(get_packet_info
.len
);
1832 reply_size
+= packet_data_len
;
1835 reply
= zmalloc(reply_size
);
1837 PERROR("packet reply zmalloc");
1838 reply_size
= sizeof(reply_header
);
1842 pthread_mutex_lock(&vstream
->stream
->lock
);
1843 lseek_ret
= fs_handle_seek(vstream
->stream_file
.handle
,
1844 be64toh(get_packet_info
.offset
), SEEK_SET
);
1845 if (lseek_ret
< 0) {
1846 PERROR("Failed to seek file system handle of viewer stream %" PRIu64
1847 " to offset %" PRIu64
,
1849 (uint64_t) be64toh(get_packet_info
.offset
));
1852 read_len
= fs_handle_read(vstream
->stream_file
.handle
,
1853 reply
+ sizeof(reply_header
), packet_data_len
);
1854 if (read_len
< packet_data_len
) {
1855 PERROR("Failed to read from file system handle of viewer stream id %" PRIu64
1856 ", offset: %" PRIu64
,
1858 (uint64_t) be64toh(get_packet_info
.offset
));
1861 reply_header
.status
= htobe32(LTTNG_VIEWER_GET_PACKET_OK
);
1862 reply_header
.len
= htobe32(packet_data_len
);
1866 reply_header
.status
= htobe32(LTTNG_VIEWER_GET_PACKET_ERR
);
1870 pthread_mutex_unlock(&vstream
->stream
->lock
);
1874 health_code_update();
1877 memcpy(reply
, &reply_header
, sizeof(reply_header
));
1878 ret
= send_response(conn
->sock
, reply
, reply_size
);
1880 /* No reply to send. */
1881 ret
= send_response(conn
->sock
, &reply_header
,
1885 health_code_update();
1887 PERROR("sendmsg of packet data failed");
1891 DBG("Sent %u bytes for stream %" PRIu64
, reply_size
, stream_id
);
1897 viewer_stream_put(vstream
);
1903 * Send the session's metadata
1905 * Return 0 on success else a negative value.
1908 int viewer_get_metadata(struct relay_connection
*conn
)
1915 struct lttng_viewer_get_metadata request
;
1916 struct lttng_viewer_metadata_packet reply
;
1917 struct relay_viewer_stream
*vstream
= NULL
;
1921 DBG("Relay get metadata");
1923 health_code_update();
1925 ret
= recv_request(conn
->sock
, &request
, sizeof(request
));
1929 health_code_update();
1931 memset(&reply
, 0, sizeof(reply
));
1933 vstream
= viewer_stream_get_by_id(be64toh(request
.stream_id
));
1936 * The metadata stream can be closed by a CLOSE command
1937 * just before we attach. It can also be closed by
1938 * per-pid tracing during tracing. Therefore, it is
1939 * possible that we cannot find this viewer stream.
1940 * Reply back to the client with an error if we cannot
1943 DBG("Client requested metadata of unknown stream id %" PRIu64
,
1944 (uint64_t) be64toh(request
.stream_id
));
1945 reply
.status
= htobe32(LTTNG_VIEWER_METADATA_ERR
);
1948 pthread_mutex_lock(&vstream
->stream
->lock
);
1949 if (!vstream
->stream
->is_metadata
) {
1950 ERR("Invalid metadata stream");
1954 if (vstream
->metadata_sent
>= vstream
->stream
->metadata_received
) {
1956 * The live viewers expect to receive a NO_NEW_METADATA
1957 * status before a stream disappears, otherwise they abort the
1958 * entire live connection when receiving an error status.
1960 * Clear feature resets the metadata_sent to 0 until the
1961 * same metadata is received again.
1963 reply
.status
= htobe32(LTTNG_VIEWER_NO_NEW_METADATA
);
1965 * The live viewer considers a closed 0 byte metadata stream as
1968 if (vstream
->metadata_sent
> 0) {
1969 vstream
->stream
->no_new_metadata_notified
= true;
1970 if (vstream
->stream
->closed
) {
1971 /* Release ownership for the viewer metadata stream. */
1972 viewer_stream_put(vstream
);
1978 if (vstream
->stream
->trace_chunk
&&
1979 !lttng_trace_chunk_ids_equal(
1980 conn
->viewer_session
->current_trace_chunk
,
1981 vstream
->stream
->trace_chunk
)) {
1982 /* A rotation has occurred on the relay stream. */
1983 DBG("Metadata relay stream and viewer chunk ids differ");
1985 ret
= viewer_session_set_trace_chunk_copy(
1986 conn
->viewer_session
,
1987 vstream
->stream
->trace_chunk
);
1989 reply
.status
= htobe32(LTTNG_VIEWER_METADATA_ERR
);
1994 if (conn
->viewer_session
->current_trace_chunk
!=
1995 vstream
->stream_file
.trace_chunk
) {
1996 bool acquired_reference
;
1998 DBG("Viewer session and viewer stream chunk differ: "
1999 "vsession chunk %p vstream chunk %p",
2000 conn
->viewer_session
->current_trace_chunk
,
2001 vstream
->stream_file
.trace_chunk
);
2002 lttng_trace_chunk_put(vstream
->stream_file
.trace_chunk
);
2003 acquired_reference
= lttng_trace_chunk_get(conn
->viewer_session
->current_trace_chunk
);
2004 assert(acquired_reference
);
2005 vstream
->stream_file
.trace_chunk
=
2006 conn
->viewer_session
->current_trace_chunk
;
2007 viewer_stream_close_files(vstream
);
2010 len
= vstream
->stream
->metadata_received
- vstream
->metadata_sent
;
2013 * Either this is the first time the metadata file is read, or a
2014 * rotation of the corresponding relay stream has occured.
2016 if (!vstream
->stream_file
.handle
&& len
> 0) {
2017 struct fs_handle
*fs_handle
;
2018 char file_path
[LTTNG_PATH_MAX
];
2019 enum lttng_trace_chunk_status status
;
2020 struct relay_stream
*rstream
= vstream
->stream
;
2022 ret
= utils_stream_file_path(rstream
->path_name
,
2023 rstream
->channel_name
, rstream
->tracefile_size
,
2024 vstream
->current_tracefile_id
, NULL
, file_path
,
2031 * It is possible the the metadata file we are trying to open is
2032 * missing if the stream has been closed (application exits with
2033 * per-pid buffers) and a clear command has been performed.
2035 status
= lttng_trace_chunk_open_fs_handle(
2036 vstream
->stream_file
.trace_chunk
,
2037 file_path
, O_RDONLY
, 0, &fs_handle
, true);
2038 if (status
!= LTTNG_TRACE_CHUNK_STATUS_OK
) {
2039 if (status
== LTTNG_TRACE_CHUNK_STATUS_NO_FILE
) {
2040 reply
.status
= htobe32(LTTNG_VIEWER_NO_NEW_METADATA
);
2042 if (vstream
->stream
->closed
) {
2043 viewer_stream_put(vstream
);
2047 PERROR("Failed to open metadata file for viewer stream");
2050 vstream
->stream_file
.handle
= fs_handle
;
2052 if (vstream
->metadata_sent
!= 0) {
2054 * The client does not expect to receive any metadata
2055 * it has received and metadata files in successive
2056 * chunks must be a strict superset of one another.
2058 * Skip the first `metadata_sent` bytes to ensure
2059 * they are not sent a second time to the client.
2061 * Baring a block layer error or an internal error,
2062 * this seek should not fail as
2063 * `vstream->stream->metadata_received` is reset when
2064 * a relay stream is rotated. If this is reached, it is
2065 * safe to assume that
2066 * `metadata_received` > `metadata_sent`.
2068 const off_t seek_ret
= fs_handle_seek(fs_handle
,
2069 vstream
->metadata_sent
, SEEK_SET
);
2072 PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64
,
2073 vstream
->metadata_sent
);
2074 reply
.status
= htobe32(LTTNG_VIEWER_METADATA_ERR
);
2080 reply
.len
= htobe64(len
);
2081 data
= zmalloc(len
);
2083 PERROR("viewer metadata zmalloc");
2087 fd
= fs_handle_get_fd(vstream
->stream_file
.handle
);
2089 ERR("Failed to restore viewer stream file system handle");
2092 read_len
= lttng_read(fd
, data
, len
);
2093 fs_handle_put_fd(vstream
->stream_file
.handle
);
2095 if (read_len
< len
) {
2097 PERROR("Failed to read metadata file");
2101 * A clear has been performed which prevents the relay
2102 * from sending `len` bytes of metadata.
2104 * It is important not to send any metadata if we
2105 * couldn't read all the available metadata in one shot:
2106 * sending partial metadata can cause the client to
2107 * attempt to parse an incomplete (incoherent) metadata
2108 * stream, which would result in an error.
2110 const off_t seek_ret
= fs_handle_seek(
2111 vstream
->stream_file
.handle
, -read_len
,
2114 DBG("Failed to read metadata: requested = %" PRIu64
", got = %zd",
2119 PERROR("Failed to restore metadata file position after partial read");
2125 vstream
->metadata_sent
+= read_len
;
2126 reply
.status
= htobe32(LTTNG_VIEWER_METADATA_OK
);
2131 reply
.status
= htobe32(LTTNG_VIEWER_METADATA_ERR
);
2134 health_code_update();
2136 pthread_mutex_unlock(&vstream
->stream
->lock
);
2138 ret
= send_response(conn
->sock
, &reply
, sizeof(reply
));
2142 health_code_update();
2145 ret
= send_response(conn
->sock
, data
, len
);
2151 DBG("Sent %" PRIu64
" bytes of metadata for stream %" PRIu64
, len
,
2152 (uint64_t) be64toh(request
.stream_id
));
2154 DBG("Metadata sent");
2160 viewer_stream_put(vstream
);
2166 * Create a viewer session.
2168 * Return 0 on success or else a negative value.
2171 int viewer_create_session(struct relay_connection
*conn
)
2174 struct lttng_viewer_create_session_response resp
;
2176 DBG("Viewer create session received");
2178 memset(&resp
, 0, sizeof(resp
));
2179 resp
.status
= htobe32(LTTNG_VIEWER_CREATE_SESSION_OK
);
2180 conn
->viewer_session
= viewer_session_create();
2181 if (!conn
->viewer_session
) {
2182 ERR("Allocation viewer session");
2183 resp
.status
= htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR
);
2188 health_code_update();
2189 ret
= send_response(conn
->sock
, &resp
, sizeof(resp
));
2193 health_code_update();
2201 * Detach a viewer session.
2203 * Return 0 on success or else a negative value.
2206 int viewer_detach_session(struct relay_connection
*conn
)
2209 struct lttng_viewer_detach_session_response response
;
2210 struct lttng_viewer_detach_session_request request
;
2211 struct relay_session
*session
= NULL
;
2212 uint64_t viewer_session_to_close
;
2214 DBG("Viewer detach session received");
2218 health_code_update();
2220 /* Receive the request from the connected client. */
2221 ret
= recv_request(conn
->sock
, &request
, sizeof(request
));
2225 viewer_session_to_close
= be64toh(request
.session_id
);
2227 if (!conn
->viewer_session
) {
2228 DBG("Client trying to detach before creating a live viewer session");
2229 response
.status
= htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR
);
2233 health_code_update();
2235 memset(&response
, 0, sizeof(response
));
2236 DBG("Detaching from session ID %" PRIu64
, viewer_session_to_close
);
2238 session
= session_get_by_id(be64toh(request
.session_id
));
2240 DBG("Relay session %" PRIu64
" not found",
2241 (uint64_t) be64toh(request
.session_id
));
2242 response
.status
= htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK
);
2246 ret
= viewer_session_is_attached(conn
->viewer_session
, session
);
2248 DBG("Not attached to this session");
2249 response
.status
= htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR
);
2250 goto send_reply_put
;
2253 viewer_session_close_one_session(conn
->viewer_session
, session
);
2254 response
.status
= htobe32(LTTNG_VIEWER_DETACH_SESSION_OK
);
2255 DBG("Session %" PRIu64
" detached.", viewer_session_to_close
);
2258 session_put(session
);
2261 health_code_update();
2262 ret
= send_response(conn
->sock
, &response
, sizeof(response
));
2266 health_code_update();
2274 * live_relay_unknown_command: send -1 if received unknown command
2277 void live_relay_unknown_command(struct relay_connection
*conn
)
2279 struct lttcomm_relayd_generic_reply reply
;
2281 memset(&reply
, 0, sizeof(reply
));
2282 reply
.ret_code
= htobe32(LTTNG_ERR_UNK
);
2283 (void) send_response(conn
->sock
, &reply
, sizeof(reply
));
2287 * Process the commands received on the control socket
2290 int process_control(struct lttng_viewer_cmd
*recv_hdr
,
2291 struct relay_connection
*conn
)
2296 msg_value
= be32toh(recv_hdr
->cmd
);
2299 * Make sure we've done the version check before any command other then a
2300 * new client connection.
2302 if (msg_value
!= LTTNG_VIEWER_CONNECT
&& !conn
->version_check_done
) {
2303 ERR("Viewer conn value %" PRIu32
" before version check", msg_value
);
2308 switch (msg_value
) {
2309 case LTTNG_VIEWER_CONNECT
:
2310 ret
= viewer_connect(conn
);
2312 case LTTNG_VIEWER_LIST_SESSIONS
:
2313 ret
= viewer_list_sessions(conn
);
2315 case LTTNG_VIEWER_ATTACH_SESSION
:
2316 ret
= viewer_attach_session(conn
);
2318 case LTTNG_VIEWER_GET_NEXT_INDEX
:
2319 ret
= viewer_get_next_index(conn
);
2321 case LTTNG_VIEWER_GET_PACKET
:
2322 ret
= viewer_get_packet(conn
);
2324 case LTTNG_VIEWER_GET_METADATA
:
2325 ret
= viewer_get_metadata(conn
);
2327 case LTTNG_VIEWER_GET_NEW_STREAMS
:
2328 ret
= viewer_get_new_streams(conn
);
2330 case LTTNG_VIEWER_CREATE_SESSION
:
2331 ret
= viewer_create_session(conn
);
2333 case LTTNG_VIEWER_DETACH_SESSION
:
2334 ret
= viewer_detach_session(conn
);
2337 ERR("Received unknown viewer command (%u)",
2338 be32toh(recv_hdr
->cmd
));
2339 live_relay_unknown_command(conn
);
2349 void cleanup_connection_pollfd(struct lttng_poll_event
*events
, int pollfd
)
2353 (void) lttng_poll_del(events
, pollfd
);
2355 ret
= fd_tracker_close_unsuspendable_fd(the_fd_tracker
, &pollfd
, 1,
2356 fd_tracker_util_close_fd
, NULL
);
2358 ERR("Closing pollfd %d", pollfd
);
2363 * This thread does the actual work
2366 void *thread_worker(void *data
)
2370 struct lttng_poll_event events
;
2371 struct lttng_ht
*viewer_connections_ht
;
2372 struct lttng_ht_iter iter
;
2373 struct lttng_viewer_cmd recv_hdr
;
2374 struct relay_connection
*destroy_conn
;
2376 DBG("[thread] Live viewer relay worker started");
2378 rcu_register_thread();
2380 health_register(health_relayd
, HEALTH_RELAYD_TYPE_LIVE_WORKER
);
2382 if (testpoint(relayd_thread_live_worker
)) {
2383 goto error_testpoint
;
2386 /* table of connections indexed on socket */
2387 viewer_connections_ht
= lttng_ht_new(0, LTTNG_HT_TYPE_ULONG
);
2388 if (!viewer_connections_ht
) {
2389 goto viewer_connections_ht_error
;
2392 ret
= create_named_thread_poll_set(&events
, 2,
2393 "Live viewer worker thread epoll");
2395 goto error_poll_create
;
2398 ret
= lttng_poll_add(&events
, live_conn_pipe
[0], LPOLLIN
| LPOLLRDHUP
);
2407 health_code_update();
2409 /* Infinite blocking call, waiting for transmission */
2410 DBG3("Relayd live viewer worker thread polling...");
2411 health_poll_entry();
2412 ret
= lttng_poll_wait(&events
, -1);
2416 * Restart interrupted system call.
2418 if (errno
== EINTR
) {
2427 * Process control. The control connection is prioritised so we don't
2428 * starve it with high throughput tracing data on the data
2431 for (i
= 0; i
< nb_fd
; i
++) {
2432 /* Fetch once the poll data */
2433 uint32_t revents
= LTTNG_POLL_GETEV(&events
, i
);
2434 int pollfd
= LTTNG_POLL_GETFD(&events
, i
);
2436 health_code_update();
2438 /* Thread quit pipe has been closed. Killing thread. */
2439 ret
= check_thread_quit_pipe(pollfd
, revents
);
2445 /* Inspect the relay conn pipe for new connection. */
2446 if (pollfd
== live_conn_pipe
[0]) {
2447 if (revents
& LPOLLIN
) {
2448 struct relay_connection
*conn
;
2450 ret
= lttng_read(live_conn_pipe
[0],
2451 &conn
, sizeof(conn
));
2455 ret
= lttng_poll_add(&events
,
2457 LPOLLIN
| LPOLLRDHUP
);
2459 ERR("Failed to add new live connection file descriptor to poll set");
2462 connection_ht_add(viewer_connections_ht
, conn
);
2463 DBG("Connection socket %d added to poll", conn
->sock
->fd
);
2464 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2465 ERR("Relay live pipe error");
2468 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2472 /* Connection activity. */
2473 struct relay_connection
*conn
;
2475 conn
= connection_get_by_sock(viewer_connections_ht
, pollfd
);
2480 if (revents
& LPOLLIN
) {
2481 ret
= conn
->sock
->ops
->recvmsg(conn
->sock
, &recv_hdr
,
2482 sizeof(recv_hdr
), 0);
2484 /* Connection closed. */
2485 cleanup_connection_pollfd(&events
, pollfd
);
2486 /* Put "create" ownership reference. */
2487 connection_put(conn
);
2488 DBG("Viewer control conn closed with %d", pollfd
);
2490 ret
= process_control(&recv_hdr
, conn
);
2492 /* Clear the session on error. */
2493 cleanup_connection_pollfd(&events
, pollfd
);
2494 /* Put "create" ownership reference. */
2495 connection_put(conn
);
2496 DBG("Viewer connection closed with %d", pollfd
);
2499 } else if (revents
& (LPOLLERR
| LPOLLHUP
| LPOLLRDHUP
)) {
2500 cleanup_connection_pollfd(&events
, pollfd
);
2501 /* Put "create" ownership reference. */
2502 connection_put(conn
);
2504 ERR("Unexpected poll events %u for sock %d", revents
, pollfd
);
2505 connection_put(conn
);
2508 /* Put local "get_by_sock" reference. */
2509 connection_put(conn
);
2516 (void) fd_tracker_util_poll_clean(the_fd_tracker
, &events
);
2518 /* Cleanup remaining connection object. */
2520 cds_lfht_for_each_entry(viewer_connections_ht
->ht
, &iter
.iter
,
2523 health_code_update();
2524 connection_put(destroy_conn
);
2528 lttng_ht_destroy(viewer_connections_ht
);
2529 viewer_connections_ht_error
:
2530 /* Close relay conn pipes */
2531 (void) fd_tracker_util_pipe_close(the_fd_tracker
, live_conn_pipe
);
2533 DBG("Viewer worker thread exited with error");
2535 DBG("Viewer worker thread cleanup complete");
2539 ERR("Health error occurred in %s", __func__
);
2541 health_unregister(health_relayd
);
2542 if (lttng_relay_stop_threads()) {
2543 ERR("Error stopping threads");
2545 rcu_unregister_thread();
2550 * Create the relay command pipe to wake thread_manage_apps.
2551 * Closed in cleanup().
2553 static int create_conn_pipe(void)
2555 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker
,
2556 "Live connection pipe", live_conn_pipe
);
2559 int relayd_live_join(void)
2561 int ret
, retval
= 0;
2564 ret
= pthread_join(live_listener_thread
, &status
);
2567 PERROR("pthread_join live listener");
2571 ret
= pthread_join(live_worker_thread
, &status
);
2574 PERROR("pthread_join live worker");
2578 ret
= pthread_join(live_dispatcher_thread
, &status
);
2581 PERROR("pthread_join live dispatcher");
2585 cleanup_relayd_live();
2593 int relayd_live_create(struct lttng_uri
*uri
)
2595 int ret
= 0, retval
= 0;
2601 goto exit_init_data
;
2605 /* Check if daemon is UID = 0 */
2606 is_root
= !getuid();
2609 if (live_uri
->port
< 1024) {
2610 ERR("Need to be root to use ports < 1024");
2612 goto exit_init_data
;
2616 /* Setup the thread apps communication pipe. */
2617 if (create_conn_pipe()) {
2619 goto exit_init_data
;
2622 /* Init relay command queue. */
2623 cds_wfcq_init(&viewer_conn_queue
.head
, &viewer_conn_queue
.tail
);
2625 /* Set up max poll set size */
2626 if (lttng_poll_set_max_size()) {
2628 goto exit_init_data
;
2631 /* Setup the dispatcher thread */
2632 ret
= pthread_create(&live_dispatcher_thread
, default_pthread_attr(),
2633 thread_dispatcher
, (void *) NULL
);
2636 PERROR("pthread_create viewer dispatcher");
2638 goto exit_dispatcher_thread
;
2641 /* Setup the worker thread */
2642 ret
= pthread_create(&live_worker_thread
, default_pthread_attr(),
2643 thread_worker
, NULL
);
2646 PERROR("pthread_create viewer worker");
2648 goto exit_worker_thread
;
2651 /* Setup the listener thread */
2652 ret
= pthread_create(&live_listener_thread
, default_pthread_attr(),
2653 thread_listener
, (void *) NULL
);
2656 PERROR("pthread_create viewer listener");
2658 goto exit_listener_thread
;
2662 * All OK, started all threads.
2667 * Join on the live_listener_thread should anything be added after
2668 * the live_listener thread's creation.
2671 exit_listener_thread
:
2673 ret
= pthread_join(live_worker_thread
, &status
);
2676 PERROR("pthread_join live worker");
2681 ret
= pthread_join(live_dispatcher_thread
, &status
);
2684 PERROR("pthread_join live dispatcher");
2687 exit_dispatcher_thread
:
2690 cleanup_relayd_live();