Fix: relayd: live client not notified of inactive streams
[lttng-tools.git] / src / bin / lttng-relayd / live.c
1 /*
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>
5 *
6 * SPDX-License-Identifier: GPL-2.0-only
7 *
8 */
9
10 #define _LGPL_SOURCE
11 #include <fcntl.h>
12 #include <getopt.h>
13 #include <grp.h>
14 #include <inttypes.h>
15 #include <limits.h>
16 #include <pthread.h>
17 #include <signal.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/mman.h>
22 #include <sys/mount.h>
23 #include <sys/resource.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <urcu/futex.h>
30 #include <urcu/rculist.h>
31 #include <urcu/uatomic.h>
32
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>
48
49 #include "cmd.h"
50 #include "connection.h"
51 #include "ctf-trace.h"
52 #include "health-relayd.h"
53 #include "live.h"
54 #include "lttng-relayd.h"
55 #include "session.h"
56 #include "stream.h"
57 #include "testpoint.h"
58 #include "utils.h"
59 #include "viewer-session.h"
60 #include "viewer-stream.h"
61
62 #define SESSION_BUF_DEFAULT_COUNT 16
63
64 static struct lttng_uri *live_uri;
65
66 /*
67 * This pipe is used to inform the worker thread that a command is queued and
68 * ready to be processed.
69 */
70 static int live_conn_pipe[2] = { -1, -1 };
71
72 /* Shared between threads */
73 static int live_dispatch_thread_exit;
74
75 static pthread_t live_listener_thread;
76 static pthread_t live_dispatcher_thread;
77 static pthread_t live_worker_thread;
78
79 /*
80 * Relay command queue.
81 *
82 * The live_thread_listener and live_thread_dispatcher communicate with this
83 * queue.
84 */
85 static struct relay_conn_queue viewer_conn_queue;
86
87 static uint64_t last_relay_viewer_session_id;
88 static pthread_mutex_t last_relay_viewer_session_id_lock =
89 PTHREAD_MUTEX_INITIALIZER;
90
91 static const char *
92 lttng_viewer_next_index_return_code_str(enum lttng_viewer_next_index_return_code code)
93 {
94 switch (code) {
95 case LTTNG_VIEWER_INDEX_OK:
96 return "INDEX_OK";
97 case LTTNG_VIEWER_INDEX_RETRY:
98 return "INDEX_RETRY";
99 case LTTNG_VIEWER_INDEX_HUP:
100 return "INDEX_HUP";
101 case LTTNG_VIEWER_INDEX_ERR:
102 return "INDEX_ERR";
103 case LTTNG_VIEWER_INDEX_INACTIVE:
104 return "INDEX_INACTIVE";
105 case LTTNG_VIEWER_INDEX_EOF:
106 return "INDEX_EOF";
107 default:
108 abort();
109 }
110 }
111
112 /*
113 * Cleanup the daemon
114 */
115 static
116 void cleanup_relayd_live(void)
117 {
118 DBG("Cleaning up");
119
120 free(live_uri);
121 }
122
123 /*
124 * Receive a request buffer using a given socket, destination allocated buffer
125 * of length size.
126 *
127 * Return the size of the received message or else a negative value on error
128 * with errno being set by recvmsg() syscall.
129 */
130 static
131 ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
132 {
133 ssize_t ret;
134
135 ret = sock->ops->recvmsg(sock, buf, size, 0);
136 if (ret < 0 || ret != size) {
137 if (ret == 0) {
138 /* Orderly shutdown. Not necessary to print an error. */
139 DBG("Socket %d did an orderly shutdown", sock->fd);
140 } else {
141 ERR("Relay failed to receive request.");
142 }
143 ret = -1;
144 }
145
146 return ret;
147 }
148
149 /*
150 * Send a response buffer using a given socket, source allocated buffer of
151 * length size.
152 *
153 * Return the size of the sent message or else a negative value on error with
154 * errno being set by sendmsg() syscall.
155 */
156 static
157 ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
158 {
159 ssize_t ret;
160
161 ret = sock->ops->sendmsg(sock, buf, size, 0);
162 if (ret < 0) {
163 ERR("Relayd failed to send response.");
164 }
165
166 return ret;
167 }
168
169 /*
170 * Atomically check if new streams got added in one of the sessions attached
171 * and reset the flag to 0.
172 *
173 * Returns 1 if new streams got added, 0 if nothing changed, a negative value
174 * on error.
175 */
176 static
177 int check_new_streams(struct relay_connection *conn)
178 {
179 struct relay_session *session;
180 int ret = 0;
181
182 rcu_read_lock();
183 if (!conn->viewer_session) {
184 goto end;
185 }
186
187 cds_list_for_each_entry_rcu(
188 session, &conn->viewer_session->session_list, viewer_session_node)
189 {
190 if (!session_get(session)) {
191 continue;
192 }
193
194 ret = uatomic_read(&session->new_streams);
195 session_put(session);
196 if (ret == 1) {
197 goto end;
198 }
199 }
200
201 end:
202 rcu_read_unlock();
203 DBG("Viewer connection has%s new streams: socket_fd = %d", ret == 0 ? " no" : "", conn->sock->fd);
204 return ret;
205 }
206
207 /*
208 * Send viewer streams to the given socket. The ignore_sent_flag indicates if
209 * this function should ignore the sent flag or not.
210 *
211 * Return 0 on success or else a negative value.
212 */
213 static
214 ssize_t send_viewer_streams(struct lttcomm_sock *sock,
215 uint64_t session_id, unsigned int ignore_sent_flag)
216 {
217 ssize_t ret;
218 struct lttng_ht_iter iter;
219 struct relay_viewer_stream *vstream;
220
221 rcu_read_lock();
222
223 cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
224 stream_n.node) {
225 struct ctf_trace *ctf_trace;
226 struct lttng_viewer_stream send_stream = {};
227
228 health_code_update();
229
230 if (!viewer_stream_get(vstream)) {
231 continue;
232 }
233
234 pthread_mutex_lock(&vstream->stream->lock);
235 /* Ignore if not the same session. */
236 if (vstream->stream->trace->session->id != session_id ||
237 (!ignore_sent_flag && vstream->sent_flag)) {
238 pthread_mutex_unlock(&vstream->stream->lock);
239 viewer_stream_put(vstream);
240 continue;
241 }
242
243 ctf_trace = vstream->stream->trace;
244 send_stream.id = htobe64(vstream->stream->stream_handle);
245 send_stream.ctf_trace_id = htobe64(ctf_trace->id);
246 send_stream.metadata_flag = htobe32(
247 vstream->stream->is_metadata);
248 if (lttng_strncpy(send_stream.path_name, vstream->path_name,
249 sizeof(send_stream.path_name))) {
250 pthread_mutex_unlock(&vstream->stream->lock);
251 viewer_stream_put(vstream);
252 ret = -1; /* Error. */
253 goto end_unlock;
254 }
255 if (lttng_strncpy(send_stream.channel_name,
256 vstream->channel_name,
257 sizeof(send_stream.channel_name))) {
258 pthread_mutex_unlock(&vstream->stream->lock);
259 viewer_stream_put(vstream);
260 ret = -1; /* Error. */
261 goto end_unlock;
262 }
263
264 DBG("Sending stream %" PRIu64 " to viewer",
265 vstream->stream->stream_handle);
266 vstream->sent_flag = 1;
267 pthread_mutex_unlock(&vstream->stream->lock);
268
269 ret = send_response(sock, &send_stream, sizeof(send_stream));
270 viewer_stream_put(vstream);
271 if (ret < 0) {
272 goto end_unlock;
273 }
274 }
275
276 ret = 0;
277
278 end_unlock:
279 rcu_read_unlock();
280 return ret;
281 }
282
283 /*
284 * Create every viewer stream possible for the given session with the seek
285 * type. Three counters *can* be return which are in order the total amount of
286 * viewer stream of the session, the number of unsent stream and the number of
287 * stream created. Those counters can be NULL and thus will be ignored.
288 *
289 * session must be locked to ensure that we see either none or all initial
290 * streams for a session, but no intermediate state..
291 *
292 * Return 0 on success or else a negative value.
293 */
294 static int make_viewer_streams(struct relay_session *relay_session,
295 struct relay_viewer_session *viewer_session,
296 enum lttng_viewer_seek seek_t,
297 uint32_t *nb_total,
298 uint32_t *nb_unsent,
299 uint32_t *nb_created,
300 bool *closed)
301 {
302 int ret;
303 struct lttng_ht_iter iter;
304 struct ctf_trace *ctf_trace;
305 struct relay_stream *relay_stream = NULL;
306
307 assert(relay_session);
308 ASSERT_LOCKED(relay_session->lock);
309
310 if (relay_session->connection_closed) {
311 *closed = true;
312 }
313
314 /*
315 * Create viewer streams for relay streams that are ready to be
316 * used for a the given session id only.
317 */
318 rcu_read_lock();
319 cds_lfht_for_each_entry (relay_session->ctf_traces_ht->ht, &iter.iter,
320 ctf_trace, node.node) {
321 bool trace_has_metadata_stream = false;
322
323 health_code_update();
324
325 if (!ctf_trace_get(ctf_trace)) {
326 continue;
327 }
328
329 /*
330 * Iterate over all the streams of the trace to see if we have a
331 * metadata stream.
332 */
333 cds_list_for_each_entry_rcu(relay_stream,
334 &ctf_trace->stream_list, stream_node)
335 {
336 bool is_metadata_stream;
337
338 pthread_mutex_lock(&relay_stream->lock);
339 is_metadata_stream = relay_stream->is_metadata;
340 pthread_mutex_unlock(&relay_stream->lock);
341
342 if (is_metadata_stream) {
343 trace_has_metadata_stream = true;
344 break;
345 }
346 }
347
348 relay_stream = NULL;
349
350 /*
351 * If there is no metadata stream in this trace at the moment
352 * and we never sent one to the viewer, skip the trace. We
353 * accept that the viewer will not see this trace at all.
354 */
355 if (!trace_has_metadata_stream &&
356 !ctf_trace->metadata_stream_sent_to_viewer) {
357 ctf_trace_put(ctf_trace);
358 continue;
359 }
360
361 cds_list_for_each_entry_rcu(relay_stream,
362 &ctf_trace->stream_list, stream_node)
363 {
364 struct relay_viewer_stream *viewer_stream;
365
366 if (!stream_get(relay_stream)) {
367 continue;
368 }
369
370 pthread_mutex_lock(&relay_stream->lock);
371 /*
372 * stream published is protected by the session lock.
373 */
374 if (!relay_stream->published) {
375 goto next;
376 }
377 viewer_stream = viewer_stream_get_by_id(
378 relay_stream->stream_handle);
379 if (!viewer_stream) {
380 struct lttng_trace_chunk *viewer_stream_trace_chunk = NULL;
381
382 /*
383 * Save that we sent the metadata stream to the
384 * viewer. So that we know what trace the viewer
385 * is aware of.
386 */
387 if (relay_stream->is_metadata) {
388 ctf_trace->metadata_stream_sent_to_viewer = true;
389 }
390
391 /*
392 * If a rotation is ongoing, use a copy of the
393 * relay stream's chunk to ensure the stream
394 * files exist.
395 *
396 * Otherwise, the viewer session's current trace
397 * chunk can be used safely.
398 */
399 if ((relay_stream->ongoing_rotation.is_set ||
400 session_has_ongoing_rotation(relay_session)) &&
401 relay_stream->trace_chunk) {
402 viewer_stream_trace_chunk = lttng_trace_chunk_copy(
403 relay_stream->trace_chunk);
404 if (!viewer_stream_trace_chunk) {
405 ret = -1;
406 ctf_trace_put(ctf_trace);
407 goto error_unlock;
408 }
409 } else {
410 /*
411 * Transition the viewer session into the newest trace chunk available.
412 */
413 if (!lttng_trace_chunk_ids_equal(viewer_session->current_trace_chunk,
414 relay_stream->trace_chunk)) {
415
416 ret = viewer_session_set_trace_chunk_copy(
417 viewer_session,
418 relay_stream->trace_chunk);
419 if (ret) {
420 ret = -1;
421 ctf_trace_put(ctf_trace);
422 goto error_unlock;
423 }
424 }
425
426 if (relay_stream->trace_chunk) {
427 /*
428 * If the corresponding relay
429 * stream's trace chunk is set,
430 * the viewer stream will be
431 * created under it.
432 *
433 * Note that a relay stream can
434 * have a NULL output trace
435 * chunk (for instance, after a
436 * clear against a stopped
437 * session).
438 */
439 const bool reference_acquired = lttng_trace_chunk_get(
440 viewer_session->current_trace_chunk);
441
442 assert(reference_acquired);
443 viewer_stream_trace_chunk =
444 viewer_session->current_trace_chunk;
445 }
446 }
447
448 viewer_stream = viewer_stream_create(
449 relay_stream,
450 viewer_stream_trace_chunk,
451 seek_t);
452 lttng_trace_chunk_put(viewer_stream_trace_chunk);
453 viewer_stream_trace_chunk = NULL;
454 if (!viewer_stream) {
455 ret = -1;
456 ctf_trace_put(ctf_trace);
457 goto error_unlock;
458 }
459
460 if (nb_created) {
461 /* Update number of created stream counter. */
462 (*nb_created)++;
463 }
464 /*
465 * Ensure a self-reference is preserved even
466 * after we have put our local reference.
467 */
468 if (!viewer_stream_get(viewer_stream)) {
469 ERR("Unable to get self-reference on viewer stream, logic error.");
470 abort();
471 }
472 } else {
473 if (!viewer_stream->sent_flag && nb_unsent) {
474 /* Update number of unsent stream counter. */
475 (*nb_unsent)++;
476 }
477 }
478 /* Update number of total stream counter. */
479 if (nb_total) {
480 if (relay_stream->is_metadata) {
481 if (!relay_stream->closed ||
482 relay_stream->metadata_received >
483 viewer_stream->metadata_sent) {
484 (*nb_total)++;
485 }
486 } else {
487 if (!relay_stream->closed ||
488 !(((int64_t)(relay_stream->prev_data_seq -
489 relay_stream->last_net_seq_num)) >=
490 0)) {
491 (*nb_total)++;
492 }
493 }
494 }
495 /* Put local reference. */
496 viewer_stream_put(viewer_stream);
497 next:
498 pthread_mutex_unlock(&relay_stream->lock);
499 stream_put(relay_stream);
500 }
501 relay_stream = NULL;
502 ctf_trace_put(ctf_trace);
503 }
504
505 ret = 0;
506
507 error_unlock:
508 rcu_read_unlock();
509
510 if (relay_stream) {
511 pthread_mutex_unlock(&relay_stream->lock);
512 stream_put(relay_stream);
513 }
514
515 return ret;
516 }
517
518 int relayd_live_stop(void)
519 {
520 /* Stop dispatch thread */
521 CMM_STORE_SHARED(live_dispatch_thread_exit, 1);
522 futex_nto1_wake(&viewer_conn_queue.futex);
523 return 0;
524 }
525
526 /*
527 * Create a poll set with O_CLOEXEC and add the thread quit pipe to the set.
528 */
529 static
530 int create_named_thread_poll_set(struct lttng_poll_event *events,
531 int size, const char *name)
532 {
533 int ret;
534
535 if (events == NULL || size == 0) {
536 ret = -1;
537 goto error;
538 }
539
540 ret = fd_tracker_util_poll_create(the_fd_tracker,
541 name, events, 1, LTTNG_CLOEXEC);
542 if (ret) {
543 PERROR("Failed to create \"%s\" poll file descriptor", name);
544 goto error;
545 }
546
547 /* Add quit pipe */
548 ret = lttng_poll_add(events, thread_quit_pipe[0], LPOLLIN | LPOLLERR);
549 if (ret < 0) {
550 goto error;
551 }
552
553 return 0;
554
555 error:
556 return ret;
557 }
558
559 /*
560 * Check if the thread quit pipe was triggered.
561 *
562 * Return 1 if it was triggered else 0;
563 */
564 static
565 int check_thread_quit_pipe(int fd, uint32_t events)
566 {
567 if (fd == thread_quit_pipe[0] && (events & LPOLLIN)) {
568 return 1;
569 }
570
571 return 0;
572 }
573
574 static
575 int create_sock(void *data, int *out_fd)
576 {
577 int ret;
578 struct lttcomm_sock *sock = data;
579
580 ret = lttcomm_create_sock(sock);
581 if (ret < 0) {
582 goto end;
583 }
584
585 *out_fd = sock->fd;
586 end:
587 return ret;
588 }
589
590 static
591 int close_sock(void *data, int *in_fd)
592 {
593 struct lttcomm_sock *sock = data;
594
595 return sock->ops->close(sock);
596 }
597
598 static int accept_sock(void *data, int *out_fd)
599 {
600 int ret = 0;
601 /* Socks is an array of in_sock, out_sock. */
602 struct lttcomm_sock **socks = data;
603 struct lttcomm_sock *in_sock = socks[0];
604
605 socks[1] = in_sock->ops->accept(in_sock);
606 if (!socks[1]) {
607 ret = -1;
608 goto end;
609 }
610 *out_fd = socks[1]->fd;
611 end:
612 return ret;
613 }
614
615 static
616 struct lttcomm_sock *accept_live_sock(struct lttcomm_sock *listening_sock,
617 const char *name)
618 {
619 int out_fd, ret;
620 struct lttcomm_sock *socks[2] = { listening_sock, NULL };
621 struct lttcomm_sock *new_sock = NULL;
622
623 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &out_fd,
624 (const char **) &name, 1, accept_sock, &socks);
625 if (ret) {
626 goto end;
627 }
628 new_sock = socks[1];
629 DBG("%s accepted, socket %d", name, new_sock->fd);
630 end:
631 return new_sock;
632 }
633
634 /*
635 * Create and init socket from uri.
636 */
637 static
638 struct lttcomm_sock *init_socket(struct lttng_uri *uri, const char *name)
639 {
640 int ret, sock_fd;
641 struct lttcomm_sock *sock = NULL;
642 char uri_str[LTTNG_PATH_MAX];
643 char *formated_name = NULL;
644
645 sock = lttcomm_alloc_sock_from_uri(uri);
646 if (sock == NULL) {
647 ERR("Allocating socket");
648 goto error;
649 }
650
651 /*
652 * Don't fail to create the socket if the name can't be built as it is
653 * only used for debugging purposes.
654 */
655 ret = uri_to_str_url(uri, uri_str, sizeof(uri_str));
656 uri_str[sizeof(uri_str) - 1] = '\0';
657 if (ret >= 0) {
658 ret = asprintf(&formated_name, "%s socket @ %s", name,
659 uri_str);
660 if (ret < 0) {
661 formated_name = NULL;
662 }
663 }
664
665 ret = fd_tracker_open_unsuspendable_fd(the_fd_tracker, &sock_fd,
666 (const char **) (formated_name ? &formated_name : NULL),
667 1, create_sock, sock);
668 if (ret) {
669 PERROR("Failed to create \"%s\" socket",
670 formated_name ?: "Unknown");
671 goto error;
672 }
673 DBG("Listening on %s socket %d", name, sock->fd);
674
675 ret = sock->ops->bind(sock);
676 if (ret < 0) {
677 PERROR("Failed to bind lttng-live socket");
678 goto error;
679 }
680
681 ret = sock->ops->listen(sock, -1);
682 if (ret < 0) {
683 goto error;
684
685 }
686
687 free(formated_name);
688 return sock;
689
690 error:
691 if (sock) {
692 lttcomm_destroy_sock(sock);
693 }
694 free(formated_name);
695 return NULL;
696 }
697
698 /*
699 * This thread manages the listening for new connections on the network
700 */
701 static
702 void *thread_listener(void *data)
703 {
704 int i, ret, pollfd, err = -1;
705 uint32_t revents, nb_fd;
706 struct lttng_poll_event events;
707 struct lttcomm_sock *live_control_sock;
708
709 DBG("[thread] Relay live listener started");
710
711 rcu_register_thread();
712 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_LISTENER);
713
714 health_code_update();
715
716 live_control_sock = init_socket(live_uri, "Live listener");
717 if (!live_control_sock) {
718 goto error_sock_control;
719 }
720
721 /* Pass 2 as size here for the thread quit pipe and control sockets. */
722 ret = create_named_thread_poll_set(&events, 2,
723 "Live listener thread epoll");
724 if (ret < 0) {
725 goto error_create_poll;
726 }
727
728 /* Add the control socket */
729 ret = lttng_poll_add(&events, live_control_sock->fd, LPOLLIN | LPOLLRDHUP);
730 if (ret < 0) {
731 goto error_poll_add;
732 }
733
734 lttng_relay_notify_ready();
735
736 if (testpoint(relayd_thread_live_listener)) {
737 goto error_testpoint;
738 }
739
740 while (1) {
741 health_code_update();
742
743 DBG("Listener accepting live viewers connections");
744
745 restart:
746 health_poll_entry();
747 ret = lttng_poll_wait(&events, -1);
748 health_poll_exit();
749 if (ret < 0) {
750 /*
751 * Restart interrupted system call.
752 */
753 if (errno == EINTR) {
754 goto restart;
755 }
756 goto error;
757 }
758 nb_fd = ret;
759
760 DBG("Relay new viewer connection received");
761 for (i = 0; i < nb_fd; i++) {
762 health_code_update();
763
764 /* Fetch once the poll data */
765 revents = LTTNG_POLL_GETEV(&events, i);
766 pollfd = LTTNG_POLL_GETFD(&events, i);
767
768 /* Thread quit pipe has been closed. Killing thread. */
769 ret = check_thread_quit_pipe(pollfd, revents);
770 if (ret) {
771 err = 0;
772 goto exit;
773 }
774
775 if (revents & LPOLLIN) {
776 /*
777 * A new connection is requested, therefore a
778 * viewer connection is allocated in this
779 * thread, enqueued to a global queue and
780 * dequeued (and freed) in the worker thread.
781 */
782 int val = 1;
783 struct relay_connection *new_conn;
784 struct lttcomm_sock *newsock;
785
786 newsock = accept_live_sock(live_control_sock,
787 "Live socket to client");
788 if (!newsock) {
789 PERROR("accepting control sock");
790 goto error;
791 }
792 DBG("Relay viewer connection accepted socket %d", newsock->fd);
793
794 ret = setsockopt(newsock->fd, SOL_SOCKET, SO_REUSEADDR, &val,
795 sizeof(val));
796 if (ret < 0) {
797 PERROR("setsockopt inet");
798 lttcomm_destroy_sock(newsock);
799 goto error;
800 }
801 new_conn = connection_create(newsock, RELAY_CONNECTION_UNKNOWN);
802 if (!new_conn) {
803 lttcomm_destroy_sock(newsock);
804 goto error;
805 }
806 /* Ownership assumed by the connection. */
807 newsock = NULL;
808
809 /* Enqueue request for the dispatcher thread. */
810 cds_wfcq_enqueue(&viewer_conn_queue.head, &viewer_conn_queue.tail,
811 &new_conn->qnode);
812
813 /*
814 * Wake the dispatch queue futex.
815 * Implicit memory barrier with the
816 * exchange in cds_wfcq_enqueue.
817 */
818 futex_nto1_wake(&viewer_conn_queue.futex);
819 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
820 ERR("socket poll error");
821 goto error;
822 } else {
823 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
824 goto error;
825 }
826 }
827 }
828
829 exit:
830 error:
831 error_poll_add:
832 error_testpoint:
833 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
834 error_create_poll:
835 if (live_control_sock->fd >= 0) {
836 int sock_fd = live_control_sock->fd;
837
838 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
839 &sock_fd, 1, close_sock,
840 live_control_sock);
841 if (ret) {
842 PERROR("close");
843 }
844 live_control_sock->fd = -1;
845 }
846 lttcomm_destroy_sock(live_control_sock);
847 error_sock_control:
848 if (err) {
849 health_error();
850 DBG("Live viewer listener thread exited with error");
851 }
852 health_unregister(health_relayd);
853 rcu_unregister_thread();
854 DBG("Live viewer listener thread cleanup complete");
855 if (lttng_relay_stop_threads()) {
856 ERR("Error stopping threads");
857 }
858 return NULL;
859 }
860
861 /*
862 * This thread manages the dispatching of the requests to worker threads
863 */
864 static
865 void *thread_dispatcher(void *data)
866 {
867 int err = -1;
868 ssize_t ret;
869 struct cds_wfcq_node *node;
870 struct relay_connection *conn = NULL;
871
872 DBG("[thread] Live viewer relay dispatcher started");
873
874 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_DISPATCHER);
875
876 if (testpoint(relayd_thread_live_dispatcher)) {
877 goto error_testpoint;
878 }
879
880 health_code_update();
881
882 for (;;) {
883 health_code_update();
884
885 /* Atomically prepare the queue futex */
886 futex_nto1_prepare(&viewer_conn_queue.futex);
887
888 if (CMM_LOAD_SHARED(live_dispatch_thread_exit)) {
889 break;
890 }
891
892 do {
893 health_code_update();
894
895 /* Dequeue commands */
896 node = cds_wfcq_dequeue_blocking(&viewer_conn_queue.head,
897 &viewer_conn_queue.tail);
898 if (node == NULL) {
899 DBG("Woken up but nothing in the live-viewer "
900 "relay command queue");
901 /* Continue thread execution */
902 break;
903 }
904 conn = caa_container_of(node, struct relay_connection, qnode);
905 DBG("Dispatching viewer request waiting on sock %d",
906 conn->sock->fd);
907
908 /*
909 * Inform worker thread of the new request. This
910 * call is blocking so we can be assured that
911 * the data will be read at some point in time
912 * or wait to the end of the world :)
913 */
914 ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn));
915 if (ret < 0) {
916 PERROR("write conn pipe");
917 connection_put(conn);
918 goto error;
919 }
920 } while (node != NULL);
921
922 /* Futex wait on queue. Blocking call on futex() */
923 health_poll_entry();
924 futex_nto1_wait(&viewer_conn_queue.futex);
925 health_poll_exit();
926 }
927
928 /* Normal exit, no error */
929 err = 0;
930
931 error:
932 error_testpoint:
933 if (err) {
934 health_error();
935 ERR("Health error occurred in %s", __func__);
936 }
937 health_unregister(health_relayd);
938 DBG("Live viewer dispatch thread dying");
939 if (lttng_relay_stop_threads()) {
940 ERR("Error stopping threads");
941 }
942 return NULL;
943 }
944
945 /*
946 * Establish connection with the viewer and check the versions.
947 *
948 * Return 0 on success or else negative value.
949 */
950 static
951 int viewer_connect(struct relay_connection *conn)
952 {
953 int ret;
954 struct lttng_viewer_connect reply, msg;
955
956 conn->version_check_done = 1;
957
958 health_code_update();
959
960 DBG("Viewer is establishing a connection to the relayd.");
961
962 ret = recv_request(conn->sock, &msg, sizeof(msg));
963 if (ret < 0) {
964 goto end;
965 }
966
967 health_code_update();
968
969 memset(&reply, 0, sizeof(reply));
970 reply.major = RELAYD_VERSION_COMM_MAJOR;
971 reply.minor = RELAYD_VERSION_COMM_MINOR;
972
973 /* Major versions must be the same */
974 if (reply.major != be32toh(msg.major)) {
975 DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
976 reply.major, be32toh(msg.major));
977 ret = -1;
978 goto end;
979 }
980
981 conn->major = reply.major;
982 /* We adapt to the lowest compatible version */
983 if (reply.minor <= be32toh(msg.minor)) {
984 conn->minor = reply.minor;
985 } else {
986 conn->minor = be32toh(msg.minor);
987 }
988
989 if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_COMMAND) {
990 conn->type = RELAY_VIEWER_COMMAND;
991 } else if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_NOTIFICATION) {
992 conn->type = RELAY_VIEWER_NOTIFICATION;
993 } else {
994 ERR("Unknown connection type : %u", be32toh(msg.type));
995 ret = -1;
996 goto end;
997 }
998
999 reply.major = htobe32(reply.major);
1000 reply.minor = htobe32(reply.minor);
1001 if (conn->type == RELAY_VIEWER_COMMAND) {
1002 /*
1003 * Increment outside of htobe64 macro, because the argument can
1004 * be used more than once within the macro, and thus the
1005 * operation may be undefined.
1006 */
1007 pthread_mutex_lock(&last_relay_viewer_session_id_lock);
1008 last_relay_viewer_session_id++;
1009 pthread_mutex_unlock(&last_relay_viewer_session_id_lock);
1010 reply.viewer_session_id = htobe64(last_relay_viewer_session_id);
1011 }
1012
1013 health_code_update();
1014
1015 ret = send_response(conn->sock, &reply, sizeof(reply));
1016 if (ret < 0) {
1017 goto end;
1018 }
1019
1020 health_code_update();
1021
1022 DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
1023 ret = 0;
1024
1025 end:
1026 return ret;
1027 }
1028
1029 /*
1030 * Send the viewer the list of current sessions.
1031 * We need to create a copy of the hash table content because otherwise
1032 * we cannot assume the number of entries stays the same between getting
1033 * the number of HT elements and iteration over the HT.
1034 *
1035 * Return 0 on success or else a negative value.
1036 */
1037 static
1038 int viewer_list_sessions(struct relay_connection *conn)
1039 {
1040 int ret = 0;
1041 struct lttng_viewer_list_sessions session_list;
1042 struct lttng_ht_iter iter;
1043 struct relay_session *session;
1044 struct lttng_viewer_session *send_session_buf = NULL;
1045 uint32_t buf_count = SESSION_BUF_DEFAULT_COUNT;
1046 uint32_t count = 0;
1047
1048 DBG("List sessions received");
1049
1050 send_session_buf = zmalloc(SESSION_BUF_DEFAULT_COUNT * sizeof(*send_session_buf));
1051 if (!send_session_buf) {
1052 return -1;
1053 }
1054
1055 rcu_read_lock();
1056 cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
1057 session_n.node) {
1058 struct lttng_viewer_session *send_session;
1059
1060 health_code_update();
1061
1062 pthread_mutex_lock(&session->lock);
1063 if (session->connection_closed) {
1064 /* Skip closed session */
1065 goto next_session;
1066 }
1067
1068 if (count >= buf_count) {
1069 struct lttng_viewer_session *newbuf;
1070 uint32_t new_buf_count = buf_count << 1;
1071
1072 newbuf = realloc(send_session_buf,
1073 new_buf_count * sizeof(*send_session_buf));
1074 if (!newbuf) {
1075 ret = -1;
1076 goto break_loop;
1077 }
1078 send_session_buf = newbuf;
1079 buf_count = new_buf_count;
1080 }
1081 send_session = &send_session_buf[count];
1082 if (lttng_strncpy(send_session->session_name,
1083 session->session_name,
1084 sizeof(send_session->session_name))) {
1085 ret = -1;
1086 goto break_loop;
1087 }
1088 if (lttng_strncpy(send_session->hostname, session->hostname,
1089 sizeof(send_session->hostname))) {
1090 ret = -1;
1091 goto break_loop;
1092 }
1093 send_session->id = htobe64(session->id);
1094 send_session->live_timer = htobe32(session->live_timer);
1095 if (session->viewer_attached) {
1096 send_session->clients = htobe32(1);
1097 } else {
1098 send_session->clients = htobe32(0);
1099 }
1100 send_session->streams = htobe32(session->stream_count);
1101 count++;
1102 next_session:
1103 pthread_mutex_unlock(&session->lock);
1104 continue;
1105 break_loop:
1106 pthread_mutex_unlock(&session->lock);
1107 break;
1108 }
1109 rcu_read_unlock();
1110 if (ret < 0) {
1111 goto end_free;
1112 }
1113
1114 session_list.sessions_count = htobe32(count);
1115
1116 health_code_update();
1117
1118 ret = send_response(conn->sock, &session_list, sizeof(session_list));
1119 if (ret < 0) {
1120 goto end_free;
1121 }
1122
1123 health_code_update();
1124
1125 ret = send_response(conn->sock, send_session_buf,
1126 count * sizeof(*send_session_buf));
1127 if (ret < 0) {
1128 goto end_free;
1129 }
1130 health_code_update();
1131
1132 ret = 0;
1133 end_free:
1134 free(send_session_buf);
1135 return ret;
1136 }
1137
1138 /*
1139 * Send the viewer the list of current streams.
1140 */
1141 static
1142 int viewer_get_new_streams(struct relay_connection *conn)
1143 {
1144 int ret, send_streams = 0;
1145 uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0, nb_total = 0;
1146 struct lttng_viewer_new_streams_request request;
1147 struct lttng_viewer_new_streams_response response;
1148 struct relay_session *session = NULL;
1149 uint64_t session_id;
1150 bool closed = false;
1151
1152 assert(conn);
1153
1154 DBG("Get new streams received");
1155
1156 health_code_update();
1157
1158 /* Receive the request from the connected client. */
1159 ret = recv_request(conn->sock, &request, sizeof(request));
1160 if (ret < 0) {
1161 goto error;
1162 }
1163 session_id = be64toh(request.session_id);
1164
1165 health_code_update();
1166
1167 memset(&response, 0, sizeof(response));
1168
1169 session = session_get_by_id(session_id);
1170 if (!session) {
1171 DBG("Relay session %" PRIu64 " not found", session_id);
1172 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1173 goto send_reply;
1174 }
1175
1176 if (!viewer_session_is_attached(conn->viewer_session, session)) {
1177 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1178 goto send_reply;
1179 }
1180
1181 /*
1182 * For any new stream, create it with LTTNG_VIEWER_SEEK_BEGINNING since
1183 * that at this point the client is already attached to the session.Aany
1184 * initial stream will have been created with the seek type at attach
1185 * time (for now most readers use the LTTNG_VIEWER_SEEK_LAST on attach).
1186 * Otherwise any event happening in a new stream between the attach and
1187 * a call to viewer_get_new_streams will be "lost" (never received) from
1188 * the viewer's point of view.
1189 */
1190 pthread_mutex_lock(&session->lock);
1191 /*
1192 * If a session rotation is ongoing, do not attempt to open any
1193 * stream, because the chunk can be in an intermediate state
1194 * due to directory renaming.
1195 */
1196 if (session_has_ongoing_rotation(session)) {
1197 DBG("Relay session %" PRIu64 " rotation ongoing", session_id);
1198 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_NO_NEW);
1199 goto send_reply_unlock;
1200 }
1201 ret = make_viewer_streams(session,
1202 conn->viewer_session,
1203 LTTNG_VIEWER_SEEK_BEGINNING, &nb_total, &nb_unsent,
1204 &nb_created, &closed);
1205 if (ret < 0) {
1206 /*
1207 * This is caused by an internal error; propagate the negative
1208 * 'ret' to close the connection.
1209 */
1210 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1211 goto send_reply_unlock;
1212 }
1213
1214 uatomic_set(&session->new_streams, 0);
1215 send_streams = 1;
1216 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
1217
1218 /* Only send back the newly created streams with the unsent ones. */
1219 nb_streams = nb_created + nb_unsent;
1220 response.streams_count = htobe32(nb_streams);
1221
1222 /*
1223 * If the session is closed, HUP when there are no more streams
1224 * with data.
1225 */
1226 if (closed && nb_total == 0) {
1227 send_streams = 0;
1228 response.streams_count = 0;
1229 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP);
1230 goto send_reply_unlock;
1231 }
1232 send_reply_unlock:
1233 pthread_mutex_unlock(&session->lock);
1234
1235 send_reply:
1236 health_code_update();
1237 ret = send_response(conn->sock, &response, sizeof(response));
1238 if (ret < 0) {
1239 goto end_put_session;
1240 }
1241 health_code_update();
1242
1243 /*
1244 * Unknown or empty session, just return gracefully, the viewer
1245 * knows what is happening.
1246 */
1247 if (!send_streams || !nb_streams) {
1248 ret = 0;
1249 goto end_put_session;
1250 }
1251
1252 /*
1253 * Send stream and *DON'T* ignore the sent flag so every viewer
1254 * streams that were not sent from that point will be sent to
1255 * the viewer.
1256 */
1257 ret = send_viewer_streams(conn->sock, session_id, 0);
1258 if (ret < 0) {
1259 goto end_put_session;
1260 }
1261
1262 end_put_session:
1263 if (session) {
1264 session_put(session);
1265 }
1266 error:
1267 return ret;
1268 }
1269
1270 /*
1271 * Send the viewer the list of current sessions.
1272 */
1273 static
1274 int viewer_attach_session(struct relay_connection *conn)
1275 {
1276 int send_streams = 0;
1277 ssize_t ret;
1278 uint32_t nb_streams = 0;
1279 enum lttng_viewer_seek seek_type;
1280 struct lttng_viewer_attach_session_request request;
1281 struct lttng_viewer_attach_session_response response;
1282 struct relay_session *session = NULL;
1283 enum lttng_viewer_attach_return_code viewer_attach_status;
1284 bool closed = false;
1285 uint64_t session_id;
1286
1287 assert(conn);
1288
1289 health_code_update();
1290
1291 /* Receive the request from the connected client. */
1292 ret = recv_request(conn->sock, &request, sizeof(request));
1293 if (ret < 0) {
1294 goto error;
1295 }
1296
1297 session_id = be64toh(request.session_id);
1298 health_code_update();
1299
1300 memset(&response, 0, sizeof(response));
1301
1302 if (!conn->viewer_session) {
1303 DBG("Client trying to attach before creating a live viewer session");
1304 response.status = htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION);
1305 goto send_reply;
1306 }
1307
1308 session = session_get_by_id(session_id);
1309 if (!session) {
1310 DBG("Relay session %" PRIu64 " not found", session_id);
1311 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1312 goto send_reply;
1313 }
1314 DBG("Attach session ID %" PRIu64 " received", session_id);
1315
1316 pthread_mutex_lock(&session->lock);
1317 if (session->live_timer == 0) {
1318 DBG("Not live session");
1319 response.status = htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE);
1320 goto send_reply;
1321 }
1322
1323 send_streams = 1;
1324 viewer_attach_status = viewer_session_attach(conn->viewer_session,
1325 session);
1326 if (viewer_attach_status != LTTNG_VIEWER_ATTACH_OK) {
1327 response.status = htobe32(viewer_attach_status);
1328 goto send_reply;
1329 }
1330
1331 switch (be32toh(request.seek)) {
1332 case LTTNG_VIEWER_SEEK_BEGINNING:
1333 case LTTNG_VIEWER_SEEK_LAST:
1334 response.status = htobe32(LTTNG_VIEWER_ATTACH_OK);
1335 seek_type = be32toh(request.seek);
1336 break;
1337 default:
1338 ERR("Wrong seek parameter");
1339 response.status = htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR);
1340 send_streams = 0;
1341 goto send_reply;
1342 }
1343
1344 /*
1345 * If a session rotation is ongoing, do not attempt to open any
1346 * stream, because the chunk can be in an intermediate state
1347 * due to directory renaming.
1348 */
1349 if (session_has_ongoing_rotation(session)) {
1350 DBG("Relay session %" PRIu64 " rotation ongoing", session_id);
1351 send_streams = 0;
1352 goto send_reply;
1353 }
1354
1355 ret = make_viewer_streams(session,
1356 conn->viewer_session, seek_type,
1357 &nb_streams, NULL, NULL, &closed);
1358 if (ret < 0) {
1359 goto end_put_session;
1360 }
1361 pthread_mutex_unlock(&session->lock);
1362 session_put(session);
1363 session = NULL;
1364
1365 response.streams_count = htobe32(nb_streams);
1366 /*
1367 * If the session is closed when the viewer is attaching, it
1368 * means some of the streams may have been concurrently removed,
1369 * so we don't allow the viewer to attach, even if there are
1370 * streams available.
1371 */
1372 if (closed) {
1373 send_streams = 0;
1374 response.streams_count = 0;
1375 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1376 goto send_reply;
1377 }
1378
1379 send_reply:
1380 health_code_update();
1381 ret = send_response(conn->sock, &response, sizeof(response));
1382 if (ret < 0) {
1383 goto end_put_session;
1384 }
1385 health_code_update();
1386
1387 /*
1388 * Unknown or empty session, just return gracefully, the viewer
1389 * knows what is happening.
1390 */
1391 if (!send_streams || !nb_streams) {
1392 ret = 0;
1393 goto end_put_session;
1394 }
1395
1396 /* Send stream and ignore the sent flag. */
1397 ret = send_viewer_streams(conn->sock, session_id, 1);
1398 if (ret < 0) {
1399 goto end_put_session;
1400 }
1401
1402 end_put_session:
1403 if (session) {
1404 pthread_mutex_unlock(&session->lock);
1405 session_put(session);
1406 }
1407 error:
1408 return ret;
1409 }
1410
1411 /*
1412 * Open the index file if needed for the given vstream.
1413 *
1414 * If an index file is successfully opened, the vstream will set it as its
1415 * current index file.
1416 *
1417 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
1418 *
1419 * Called with rstream lock held.
1420 */
1421 static int try_open_index(struct relay_viewer_stream *vstream,
1422 struct relay_stream *rstream)
1423 {
1424 int ret = 0;
1425 const uint32_t connection_major = rstream->trace->session->major;
1426 const uint32_t connection_minor = rstream->trace->session->minor;
1427 enum lttng_trace_chunk_status chunk_status;
1428
1429 if (vstream->index_file) {
1430 goto end;
1431 }
1432
1433 /*
1434 * First time, we open the index file and at least one index is ready.
1435 */
1436 if (rstream->index_received_seqcount == 0 ||
1437 !vstream->stream_file.trace_chunk) {
1438 ret = -ENOENT;
1439 goto end;
1440 }
1441
1442 chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
1443 vstream->stream_file.trace_chunk, rstream->path_name,
1444 rstream->channel_name, rstream->tracefile_size,
1445 vstream->current_tracefile_id,
1446 lttng_to_index_major(connection_major, connection_minor),
1447 lttng_to_index_minor(connection_major, connection_minor),
1448 true, &vstream->index_file);
1449 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1450 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
1451 ret = -ENOENT;
1452 } else {
1453 ret = -1;
1454 }
1455 }
1456
1457 end:
1458 return ret;
1459 }
1460
1461 /*
1462 * Check the status of the index for the given stream. This function
1463 * updates the index structure if needed and can put (close) the vstream
1464 * in the HUP situation.
1465 *
1466 * Return 0 means that we can proceed with the index. A value of 1 means
1467 * that the index has been updated and is ready to be sent to the
1468 * client. A negative value indicates an error that can't be handled.
1469 *
1470 * Called with rstream lock held.
1471 */
1472 static int check_index_status(struct relay_viewer_stream *vstream,
1473 struct relay_stream *rstream, struct ctf_trace *trace,
1474 struct lttng_viewer_index *index)
1475 {
1476 int ret;
1477
1478 DBG("Check index status: index_received_seqcount %" PRIu64 " "
1479 "index_sent_seqcount %" PRIu64 " "
1480 "for stream %" PRIu64,
1481 rstream->index_received_seqcount,
1482 vstream->index_sent_seqcount,
1483 vstream->stream->stream_handle);
1484 if ((trace->session->connection_closed || rstream->closed)
1485 && rstream->index_received_seqcount
1486 == vstream->index_sent_seqcount) {
1487 /*
1488 * Last index sent and session connection or relay
1489 * stream are closed.
1490 */
1491 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1492 goto hup;
1493 } else if (rstream->beacon_ts_end != -1ULL &&
1494 (rstream->index_received_seqcount == 0 ||
1495 (vstream->index_sent_seqcount != 0 &&
1496 rstream->index_received_seqcount
1497 <= vstream->index_sent_seqcount))) {
1498 /*
1499 * We've received a synchronization beacon and the last index
1500 * available has been sent, the index for now is inactive.
1501 *
1502 * In this case, we have received a beacon which allows us to
1503 * inform the client of a time interval during which we can
1504 * guarantee that there are no events to read (and never will
1505 * be).
1506 *
1507 * The sent seqcount can grow higher than receive seqcount on
1508 * clear because the rotation performed by clear will push
1509 * the index_sent_seqcount ahead (see
1510 * viewer_stream_sync_tracefile_array_tail) and skip over
1511 * packet sequence numbers.
1512 */
1513 index->status = htobe32(LTTNG_VIEWER_INDEX_INACTIVE);
1514 index->timestamp_end = htobe64(rstream->beacon_ts_end);
1515 index->stream_id = htobe64(rstream->ctf_stream_id);
1516 DBG("Check index status: inactive with beacon, for stream %" PRIu64,
1517 vstream->stream->stream_handle);
1518 goto index_ready;
1519 } else if (rstream->index_received_seqcount == 0 ||
1520 (vstream->index_sent_seqcount != 0 &&
1521 rstream->index_received_seqcount
1522 <= vstream->index_sent_seqcount)) {
1523 /*
1524 * This checks whether received <= sent seqcount. In
1525 * this case, we have not received a beacon. Therefore,
1526 * we can only ask the client to retry later.
1527 *
1528 * The sent seqcount can grow higher than receive seqcount on
1529 * clear because the rotation performed by clear will push
1530 * the index_sent_seqcount ahead (see
1531 * viewer_stream_sync_tracefile_array_tail) and skip over
1532 * packet sequence numbers.
1533 */
1534 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1535 DBG("Check index status: retry for stream %" PRIu64,
1536 vstream->stream->stream_handle);
1537 goto index_ready;
1538 } else if (!tracefile_array_seq_in_file(rstream->tfa,
1539 vstream->current_tracefile_id,
1540 vstream->index_sent_seqcount)) {
1541 /*
1542 * The next index we want to send cannot be read either
1543 * because we need to perform a rotation, or due to
1544 * the producer having overwritten its trace file.
1545 */
1546 DBG("Viewer stream %" PRIu64 " rotation",
1547 vstream->stream->stream_handle);
1548 ret = viewer_stream_rotate(vstream);
1549 if (ret == 1) {
1550 /* EOF across entire stream. */
1551 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1552 goto hup;
1553 }
1554 /*
1555 * If we have been pushed due to overwrite, it
1556 * necessarily means there is data that can be read in
1557 * the stream. If we rotated because we reached the end
1558 * of a tracefile, it means the following tracefile
1559 * needs to contain at least one index, else we would
1560 * have already returned LTTNG_VIEWER_INDEX_RETRY to the
1561 * viewer. The updated index_sent_seqcount needs to
1562 * point to a readable index entry now.
1563 *
1564 * In the case where we "rotate" on a single file, we
1565 * can end up in a case where the requested index is
1566 * still unavailable.
1567 */
1568 if (rstream->tracefile_count == 1 &&
1569 !tracefile_array_seq_in_file(
1570 rstream->tfa,
1571 vstream->current_tracefile_id,
1572 vstream->index_sent_seqcount)) {
1573 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1574 DBG("Check index status: retry: "
1575 "tracefile array sequence number %" PRIu64
1576 " not in file for stream %" PRIu64,
1577 vstream->index_sent_seqcount,
1578 vstream->stream->stream_handle);
1579 goto index_ready;
1580 }
1581 assert(tracefile_array_seq_in_file(rstream->tfa,
1582 vstream->current_tracefile_id,
1583 vstream->index_sent_seqcount));
1584 }
1585 /* ret == 0 means successful so we continue. */
1586 ret = 0;
1587 return ret;
1588
1589 hup:
1590 viewer_stream_put(vstream);
1591 index_ready:
1592 return 1;
1593 }
1594
1595 static
1596 void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
1597 struct lttng_trace_chunk *new_trace_chunk)
1598 {
1599 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
1600
1601 if (new_trace_chunk) {
1602 const bool acquired_reference = lttng_trace_chunk_get(
1603 new_trace_chunk);
1604
1605 assert(acquired_reference);
1606 }
1607
1608 vstream->stream_file.trace_chunk = new_trace_chunk;
1609 viewer_stream_sync_tracefile_array_tail(vstream);
1610 viewer_stream_close_files(vstream);
1611 }
1612
1613 /*
1614 * Send the next index for a stream.
1615 *
1616 * Return 0 on success or else a negative value.
1617 */
1618 static
1619 int viewer_get_next_index(struct relay_connection *conn)
1620 {
1621 int ret;
1622 struct lttng_viewer_get_next_index request_index;
1623 struct lttng_viewer_index viewer_index;
1624 struct ctf_packet_index packet_index;
1625 struct relay_viewer_stream *vstream = NULL;
1626 struct relay_stream *rstream = NULL;
1627 struct ctf_trace *ctf_trace = NULL;
1628 struct relay_viewer_stream *metadata_viewer_stream = NULL;
1629 bool attached_sessions_have_new_streams = false;
1630
1631 assert(conn);
1632
1633 DBG("Viewer get next index");
1634
1635 memset(&viewer_index, 0, sizeof(viewer_index));
1636 health_code_update();
1637
1638 ret = recv_request(conn->sock, &request_index, sizeof(request_index));
1639 if (ret < 0) {
1640 goto end;
1641 }
1642 health_code_update();
1643
1644 vstream = viewer_stream_get_by_id(be64toh(request_index.stream_id));
1645 if (!vstream) {
1646 DBG("Client requested index of unknown stream id %" PRIu64,
1647 (uint64_t) be64toh(request_index.stream_id));
1648 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1649 goto send_reply;
1650 }
1651
1652 /* Use back. ref. Protected by refcounts. */
1653 rstream = vstream->stream;
1654 ctf_trace = rstream->trace;
1655
1656 /* metadata_viewer_stream may be NULL. */
1657 metadata_viewer_stream =
1658 ctf_trace_get_viewer_metadata_stream(ctf_trace);
1659
1660 /*
1661 * Hold the session lock to protect against concurrent changes
1662 * to the chunk files (e.g. rename done by clear), which are
1663 * protected by the session ongoing rotation state. Those are
1664 * synchronized with the session lock.
1665 */
1666 pthread_mutex_lock(&rstream->trace->session->lock);
1667 pthread_mutex_lock(&rstream->lock);
1668
1669 /*
1670 * The viewer should not ask for index on metadata stream.
1671 */
1672 if (rstream->is_metadata) {
1673 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1674 goto send_reply;
1675 }
1676
1677 ret = check_new_streams(conn);
1678 if (ret < 0) {
1679 viewer_index.status = LTTNG_VIEWER_INDEX_ERR;
1680 ERR("Error checking for new streams in the attached sessions, returning status=%s",
1681 lttng_viewer_next_index_return_code_str(
1682 (enum lttng_viewer_next_index_return_code) viewer_index.status));
1683 goto send_reply;
1684 } else if (ret == 1) {
1685 attached_sessions_have_new_streams = true;
1686 }
1687
1688 if (rstream->ongoing_rotation.is_set) {
1689 /* Rotation is ongoing, try again later. */
1690 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1691 goto send_reply;
1692 }
1693
1694 if (session_has_ongoing_rotation(rstream->trace->session)) {
1695 /* Rotation is ongoing, try again later. */
1696 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1697 goto send_reply;
1698 }
1699
1700 /*
1701 * Transition the viewer session into the newest trace chunk available.
1702 */
1703 if (!lttng_trace_chunk_ids_equal(
1704 conn->viewer_session->current_trace_chunk,
1705 rstream->trace_chunk)) {
1706 DBG("Relay stream and viewer chunk ids differ");
1707
1708 ret = viewer_session_set_trace_chunk_copy(
1709 conn->viewer_session,
1710 rstream->trace_chunk);
1711 if (ret) {
1712 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1713 goto send_reply;
1714 }
1715 }
1716
1717 /*
1718 * Transition the viewer stream into the latest trace chunk available.
1719 *
1720 * Note that the stream must _not_ rotate in one precise condition:
1721 * the relay stream has rotated to a NULL trace chunk and the viewer
1722 * stream is consuming the trace chunk that was active just before
1723 * that rotation to NULL.
1724 *
1725 * This allows clients to consume all the packets of a trace chunk
1726 * after a session's destruction.
1727 */
1728 if (!lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk, vstream->stream_file.trace_chunk) &&
1729 !(rstream->completed_rotation_count == vstream->last_seen_rotation_count + 1 && !rstream->trace_chunk)) {
1730 DBG("Viewer session and viewer stream chunk IDs differ: "
1731 "vsession chunk %p vstream chunk %p",
1732 conn->viewer_session->current_trace_chunk,
1733 vstream->stream_file.trace_chunk);
1734 viewer_stream_rotate_to_trace_chunk(vstream,
1735 conn->viewer_session->current_trace_chunk);
1736 vstream->last_seen_rotation_count =
1737 rstream->completed_rotation_count;
1738 }
1739
1740 ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
1741 if (ret < 0) {
1742 goto error_put;
1743 } else if (ret == 1) {
1744 /*
1745 * We have no index to send and check_index_status has populated
1746 * viewer_index's status.
1747 */
1748 goto send_reply;
1749 }
1750
1751 /* At this point, ret is 0 thus we will be able to read the index. */
1752 assert(!ret);
1753
1754 /* Try to open an index if one is needed for that stream. */
1755 ret = try_open_index(vstream, rstream);
1756 if (ret == -ENOENT) {
1757 if (rstream->closed) {
1758 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1759 goto send_reply;
1760 } else {
1761 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1762 goto send_reply;
1763 }
1764 }
1765 if (ret < 0) {
1766 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1767 goto send_reply;
1768 }
1769
1770 /*
1771 * vstream->stream_fd may be NULL if it has been closed by
1772 * tracefile rotation, or if we are at the beginning of the
1773 * stream. We open the data stream file here to protect against
1774 * overwrite caused by tracefile rotation (in association with
1775 * unlink performed before overwrite).
1776 */
1777 if (!vstream->stream_file.handle) {
1778 char file_path[LTTNG_PATH_MAX];
1779 enum lttng_trace_chunk_status status;
1780 struct fs_handle *fs_handle;
1781
1782 ret = utils_stream_file_path(rstream->path_name,
1783 rstream->channel_name, rstream->tracefile_size,
1784 vstream->current_tracefile_id, NULL, file_path,
1785 sizeof(file_path));
1786 if (ret < 0) {
1787 goto error_put;
1788 }
1789
1790 /*
1791 * It is possible the the file we are trying to open is
1792 * missing if the stream has been closed (application exits with
1793 * per-pid buffers) and a clear command has been performed.
1794 */
1795 status = lttng_trace_chunk_open_fs_handle(
1796 vstream->stream_file.trace_chunk,
1797 file_path, O_RDONLY, 0, &fs_handle, true);
1798 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1799 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE &&
1800 rstream->closed) {
1801 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1802 goto send_reply;
1803 }
1804 PERROR("Failed to open trace file for viewer stream");
1805 goto error_put;
1806 }
1807 vstream->stream_file.handle = fs_handle;
1808 }
1809
1810 ret = lttng_index_file_read(vstream->index_file, &packet_index);
1811 if (ret) {
1812 ERR("Relay error reading index file");
1813 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1814 goto send_reply;
1815 } else {
1816 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_OK);
1817 vstream->index_sent_seqcount++;
1818 }
1819
1820 /*
1821 * Indexes are stored in big endian, no need to switch before sending.
1822 */
1823 DBG("Sending viewer index for stream %" PRIu64 " offset %" PRIu64,
1824 rstream->stream_handle,
1825 (uint64_t) be64toh(packet_index.offset));
1826 viewer_index.offset = packet_index.offset;
1827 viewer_index.packet_size = packet_index.packet_size;
1828 viewer_index.content_size = packet_index.content_size;
1829 viewer_index.timestamp_begin = packet_index.timestamp_begin;
1830 viewer_index.timestamp_end = packet_index.timestamp_end;
1831 viewer_index.events_discarded = packet_index.events_discarded;
1832 viewer_index.stream_id = packet_index.stream_id;
1833
1834 send_reply:
1835 if (rstream) {
1836 pthread_mutex_unlock(&rstream->lock);
1837 pthread_mutex_unlock(&rstream->trace->session->lock);
1838 }
1839
1840 if (metadata_viewer_stream) {
1841 pthread_mutex_lock(&metadata_viewer_stream->stream->lock);
1842 DBG("get next index metadata check: recv %" PRIu64
1843 " sent %" PRIu64,
1844 metadata_viewer_stream->stream->metadata_received,
1845 metadata_viewer_stream->metadata_sent);
1846 if (!metadata_viewer_stream->stream->metadata_received ||
1847 metadata_viewer_stream->stream->metadata_received >
1848 metadata_viewer_stream->metadata_sent) {
1849 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1850 }
1851 pthread_mutex_unlock(&metadata_viewer_stream->stream->lock);
1852 }
1853
1854 if (attached_sessions_have_new_streams) {
1855 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1856 }
1857
1858 viewer_index.flags = htobe32(viewer_index.flags);
1859 health_code_update();
1860
1861 ret = send_response(conn->sock, &viewer_index, sizeof(viewer_index));
1862 if (ret < 0) {
1863 goto end;
1864 }
1865 health_code_update();
1866
1867 if (vstream) {
1868 DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
1869 vstream->index_sent_seqcount,
1870 vstream->stream->stream_handle);
1871 }
1872 end:
1873 if (metadata_viewer_stream) {
1874 viewer_stream_put(metadata_viewer_stream);
1875 }
1876 if (vstream) {
1877 viewer_stream_put(vstream);
1878 }
1879 return ret;
1880
1881 error_put:
1882 pthread_mutex_unlock(&rstream->lock);
1883 pthread_mutex_unlock(&rstream->trace->session->lock);
1884 if (metadata_viewer_stream) {
1885 viewer_stream_put(metadata_viewer_stream);
1886 }
1887 viewer_stream_put(vstream);
1888 return ret;
1889 }
1890
1891 /*
1892 * Send the next index for a stream
1893 *
1894 * Return 0 on success or else a negative value.
1895 */
1896 static
1897 int viewer_get_packet(struct relay_connection *conn)
1898 {
1899 int ret;
1900 off_t lseek_ret;
1901 char *reply = NULL;
1902 struct lttng_viewer_get_packet get_packet_info;
1903 struct lttng_viewer_trace_packet reply_header;
1904 struct relay_viewer_stream *vstream = NULL;
1905 uint32_t reply_size = sizeof(reply_header);
1906 uint32_t packet_data_len = 0;
1907 ssize_t read_len;
1908 uint64_t stream_id;
1909
1910 DBG2("Relay get data packet");
1911
1912 health_code_update();
1913
1914 ret = recv_request(conn->sock, &get_packet_info,
1915 sizeof(get_packet_info));
1916 if (ret < 0) {
1917 goto end;
1918 }
1919 health_code_update();
1920
1921 /* From this point on, the error label can be reached. */
1922 memset(&reply_header, 0, sizeof(reply_header));
1923 stream_id = (uint64_t) be64toh(get_packet_info.stream_id);
1924
1925 vstream = viewer_stream_get_by_id(stream_id);
1926 if (!vstream) {
1927 DBG("Client requested packet of unknown stream id %" PRIu64,
1928 stream_id);
1929 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1930 goto send_reply_nolock;
1931 } else {
1932 packet_data_len = be32toh(get_packet_info.len);
1933 reply_size += packet_data_len;
1934 }
1935
1936 reply = zmalloc(reply_size);
1937 if (!reply) {
1938 PERROR("packet reply zmalloc");
1939 reply_size = sizeof(reply_header);
1940 goto error;
1941 }
1942
1943 pthread_mutex_lock(&vstream->stream->lock);
1944 lseek_ret = fs_handle_seek(vstream->stream_file.handle,
1945 be64toh(get_packet_info.offset), SEEK_SET);
1946 if (lseek_ret < 0) {
1947 PERROR("Failed to seek file system handle of viewer stream %" PRIu64
1948 " to offset %" PRIu64,
1949 stream_id,
1950 (uint64_t) be64toh(get_packet_info.offset));
1951 goto error;
1952 }
1953 read_len = fs_handle_read(vstream->stream_file.handle,
1954 reply + sizeof(reply_header), packet_data_len);
1955 if (read_len < packet_data_len) {
1956 PERROR("Failed to read from file system handle of viewer stream id %" PRIu64
1957 ", offset: %" PRIu64,
1958 stream_id,
1959 (uint64_t) be64toh(get_packet_info.offset));
1960 goto error;
1961 }
1962 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1963 reply_header.len = htobe32(packet_data_len);
1964 goto send_reply;
1965
1966 error:
1967 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1968
1969 send_reply:
1970 if (vstream) {
1971 pthread_mutex_unlock(&vstream->stream->lock);
1972 }
1973 send_reply_nolock:
1974
1975 health_code_update();
1976
1977 if (reply) {
1978 memcpy(reply, &reply_header, sizeof(reply_header));
1979 ret = send_response(conn->sock, reply, reply_size);
1980 } else {
1981 /* No reply to send. */
1982 ret = send_response(conn->sock, &reply_header,
1983 reply_size);
1984 }
1985
1986 health_code_update();
1987 if (ret < 0) {
1988 PERROR("sendmsg of packet data failed");
1989 goto end_free;
1990 }
1991
1992 DBG("Sent %u bytes for stream %" PRIu64, reply_size, stream_id);
1993
1994 end_free:
1995 free(reply);
1996 end:
1997 if (vstream) {
1998 viewer_stream_put(vstream);
1999 }
2000 return ret;
2001 }
2002
2003 /*
2004 * Send the session's metadata
2005 *
2006 * Return 0 on success else a negative value.
2007 */
2008 static
2009 int viewer_get_metadata(struct relay_connection *conn)
2010 {
2011 int ret = 0;
2012 int fd = -1;
2013 ssize_t read_len;
2014 uint64_t len = 0;
2015 char *data = NULL;
2016 struct lttng_viewer_get_metadata request;
2017 struct lttng_viewer_metadata_packet reply;
2018 struct relay_viewer_stream *vstream = NULL;
2019 bool dispose_of_stream = false;
2020
2021 assert(conn);
2022
2023 DBG("Relay get metadata");
2024
2025 health_code_update();
2026
2027 ret = recv_request(conn->sock, &request, sizeof(request));
2028 if (ret < 0) {
2029 goto end;
2030 }
2031 health_code_update();
2032
2033 memset(&reply, 0, sizeof(reply));
2034
2035 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
2036 if (!vstream) {
2037 /*
2038 * The metadata stream can be closed by a CLOSE command
2039 * just before we attach. It can also be closed by
2040 * per-pid tracing during tracing. Therefore, it is
2041 * possible that we cannot find this viewer stream.
2042 * Reply back to the client with an error if we cannot
2043 * find it.
2044 */
2045 DBG("Client requested metadata of unknown stream id %" PRIu64,
2046 (uint64_t) be64toh(request.stream_id));
2047 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2048 goto send_reply;
2049 }
2050
2051 pthread_mutex_lock(&vstream->stream->trace->session->lock);
2052 pthread_mutex_lock(&vstream->stream->trace->lock);
2053 pthread_mutex_lock(&vstream->stream->lock);
2054 if (!vstream->stream->is_metadata) {
2055 ERR("Invalid metadata stream");
2056 goto error;
2057 }
2058
2059 if (vstream->metadata_sent >= vstream->stream->metadata_received) {
2060 /*
2061 * Clear feature resets the metadata_received to 0 until the
2062 * same metadata is received again.
2063 */
2064 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2065 /*
2066 * The live viewer considers a closed 0 byte metadata stream as
2067 * an error.
2068 */
2069 dispose_of_stream = vstream->metadata_sent > 0 && vstream->stream->closed;
2070 goto send_reply;
2071 }
2072
2073 if (vstream->stream->trace_chunk &&
2074 !lttng_trace_chunk_ids_equal(
2075 conn->viewer_session->current_trace_chunk,
2076 vstream->stream->trace_chunk)) {
2077 /* A rotation has occurred on the relay stream. */
2078 DBG("Metadata relay stream and viewer chunk ids differ");
2079
2080 ret = viewer_session_set_trace_chunk_copy(
2081 conn->viewer_session,
2082 vstream->stream->trace_chunk);
2083 if (ret) {
2084 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2085 goto send_reply;
2086 }
2087 }
2088
2089 if (conn->viewer_session->current_trace_chunk &&
2090 !lttng_trace_chunk_ids_equal(conn->viewer_session->current_trace_chunk,
2091 vstream->stream_file.trace_chunk)) {
2092 bool acquired_reference;
2093
2094 DBG("Viewer session and viewer stream chunk differ: "
2095 "vsession chunk %p vstream chunk %p",
2096 conn->viewer_session->current_trace_chunk,
2097 vstream->stream_file.trace_chunk);
2098 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
2099 acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
2100 assert(acquired_reference);
2101 vstream->stream_file.trace_chunk =
2102 conn->viewer_session->current_trace_chunk;
2103 viewer_stream_close_files(vstream);
2104 }
2105
2106 len = vstream->stream->metadata_received - vstream->metadata_sent;
2107
2108 if (!vstream->stream_file.trace_chunk) {
2109 if (vstream->stream->trace->session->connection_closed) {
2110 /*
2111 * If the connection is closed, there is no way for the metadata stream
2112 * to ever transition back to an active chunk. As such, signal to the viewer
2113 * that there is no new metadata available.
2114 *
2115 * The stream can be disposed-of. On the next execution of this command,
2116 * the relay daemon will reply with an error status since the stream can't
2117 * be found.
2118 */
2119 dispose_of_stream = true;
2120 }
2121
2122 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2123 len = 0;
2124 goto send_reply;
2125 } else if (vstream->stream_file.trace_chunk &&
2126 !vstream->stream_file.handle && len > 0) {
2127 /*
2128 * Either this is the first time the metadata file is read, or a
2129 * rotation of the corresponding relay stream has occurred.
2130 */
2131 struct fs_handle *fs_handle;
2132 char file_path[LTTNG_PATH_MAX];
2133 enum lttng_trace_chunk_status status;
2134 struct relay_stream *rstream = vstream->stream;
2135
2136 ret = utils_stream_file_path(rstream->path_name,
2137 rstream->channel_name, rstream->tracefile_size,
2138 vstream->current_tracefile_id, NULL, file_path,
2139 sizeof(file_path));
2140 if (ret < 0) {
2141 goto error;
2142 }
2143
2144 /*
2145 * It is possible the the metadata file we are trying to open is
2146 * missing if the stream has been closed (application exits with
2147 * per-pid buffers) and a clear command has been performed.
2148 */
2149 status = lttng_trace_chunk_open_fs_handle(
2150 vstream->stream_file.trace_chunk,
2151 file_path, O_RDONLY, 0, &fs_handle, true);
2152 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2153 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
2154 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2155 len = 0;
2156 if (vstream->stream->closed) {
2157 viewer_stream_put(vstream);
2158 }
2159 goto send_reply;
2160 }
2161 PERROR("Failed to open metadata file for viewer stream");
2162 goto error;
2163 }
2164 vstream->stream_file.handle = fs_handle;
2165
2166 if (vstream->metadata_sent != 0) {
2167 /*
2168 * The client does not expect to receive any metadata
2169 * it has received and metadata files in successive
2170 * chunks must be a strict superset of one another.
2171 *
2172 * Skip the first `metadata_sent` bytes to ensure
2173 * they are not sent a second time to the client.
2174 *
2175 * Baring a block layer error or an internal error,
2176 * this seek should not fail as
2177 * `vstream->stream->metadata_received` is reset when
2178 * a relay stream is rotated. If this is reached, it is
2179 * safe to assume that
2180 * `metadata_received` > `metadata_sent`.
2181 */
2182 const off_t seek_ret = fs_handle_seek(fs_handle,
2183 vstream->metadata_sent, SEEK_SET);
2184
2185 if (seek_ret < 0) {
2186 PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64,
2187 vstream->metadata_sent);
2188 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2189 goto send_reply;
2190 }
2191 }
2192 }
2193
2194 reply.len = htobe64(len);
2195 data = zmalloc(len);
2196 if (!data) {
2197 PERROR("viewer metadata zmalloc");
2198 goto error;
2199 }
2200
2201 fd = fs_handle_get_fd(vstream->stream_file.handle);
2202 if (fd < 0) {
2203 ERR("Failed to restore viewer stream file system handle");
2204 goto error;
2205 }
2206 read_len = lttng_read(fd, data, len);
2207 fs_handle_put_fd(vstream->stream_file.handle);
2208 fd = -1;
2209 if (read_len < len) {
2210 if (read_len < 0) {
2211 PERROR("Failed to read metadata file");
2212 goto error;
2213 } else {
2214 /*
2215 * A clear has been performed which prevents the relay
2216 * from sending `len` bytes of metadata.
2217 *
2218 * It is important not to send any metadata if we
2219 * couldn't read all the available metadata in one shot:
2220 * sending partial metadata can cause the client to
2221 * attempt to parse an incomplete (incoherent) metadata
2222 * stream, which would result in an error.
2223 */
2224 const off_t seek_ret = fs_handle_seek(
2225 vstream->stream_file.handle, -read_len,
2226 SEEK_CUR);
2227
2228 DBG("Failed to read metadata: requested = %" PRIu64 ", got = %zd",
2229 len, read_len);
2230 read_len = 0;
2231 len = 0;
2232 if (seek_ret < 0) {
2233 PERROR("Failed to restore metadata file position after partial read");
2234 ret = -1;
2235 goto error;
2236 }
2237 }
2238 }
2239 vstream->metadata_sent += read_len;
2240 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
2241
2242 goto send_reply;
2243
2244 error:
2245 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2246
2247 send_reply:
2248 health_code_update();
2249 if (vstream) {
2250 pthread_mutex_unlock(&vstream->stream->lock);
2251 pthread_mutex_unlock(&vstream->stream->trace->lock);
2252 pthread_mutex_unlock(&vstream->stream->trace->session->lock);
2253 }
2254 ret = send_response(conn->sock, &reply, sizeof(reply));
2255 if (ret < 0) {
2256 goto end_free;
2257 }
2258 health_code_update();
2259
2260 if (len > 0) {
2261 ret = send_response(conn->sock, data, len);
2262 if (ret < 0) {
2263 goto end_free;
2264 }
2265 }
2266
2267 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
2268 (uint64_t) be64toh(request.stream_id));
2269
2270 DBG("Metadata sent");
2271
2272 end_free:
2273 free(data);
2274 end:
2275 if (vstream) {
2276 viewer_stream_put(vstream);
2277 if (dispose_of_stream) {
2278 /*
2279 * Trigger the destruction of the viewer stream
2280 * by releasing its global reference.
2281 *
2282 * The live viewers expect to receive a NO_NEW_METADATA
2283 * status before a stream disappears, otherwise they abort the
2284 * entire live connection when receiving an error status.
2285 *
2286 * On the next query for this stream, an error will be reported to the
2287 * client.
2288 */
2289 viewer_stream_put(vstream);
2290 }
2291 }
2292
2293 return ret;
2294 }
2295
2296 /*
2297 * Create a viewer session.
2298 *
2299 * Return 0 on success or else a negative value.
2300 */
2301 static
2302 int viewer_create_session(struct relay_connection *conn)
2303 {
2304 int ret;
2305 struct lttng_viewer_create_session_response resp;
2306
2307 DBG("Viewer create session received");
2308
2309 memset(&resp, 0, sizeof(resp));
2310 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
2311 conn->viewer_session = viewer_session_create();
2312 if (!conn->viewer_session) {
2313 ERR("Allocation viewer session");
2314 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
2315 goto send_reply;
2316 }
2317
2318 send_reply:
2319 health_code_update();
2320 ret = send_response(conn->sock, &resp, sizeof(resp));
2321 if (ret < 0) {
2322 goto end;
2323 }
2324 health_code_update();
2325 ret = 0;
2326
2327 end:
2328 return ret;
2329 }
2330
2331 /*
2332 * Detach a viewer session.
2333 *
2334 * Return 0 on success or else a negative value.
2335 */
2336 static
2337 int viewer_detach_session(struct relay_connection *conn)
2338 {
2339 int ret;
2340 struct lttng_viewer_detach_session_response response;
2341 struct lttng_viewer_detach_session_request request;
2342 struct relay_session *session = NULL;
2343 uint64_t viewer_session_to_close;
2344
2345 DBG("Viewer detach session received");
2346
2347 assert(conn);
2348
2349 health_code_update();
2350
2351 /* Receive the request from the connected client. */
2352 ret = recv_request(conn->sock, &request, sizeof(request));
2353 if (ret < 0) {
2354 goto end;
2355 }
2356 viewer_session_to_close = be64toh(request.session_id);
2357
2358 if (!conn->viewer_session) {
2359 DBG("Client trying to detach before creating a live viewer session");
2360 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2361 goto send_reply;
2362 }
2363
2364 health_code_update();
2365
2366 memset(&response, 0, sizeof(response));
2367 DBG("Detaching from session ID %" PRIu64, viewer_session_to_close);
2368
2369 session = session_get_by_id(be64toh(request.session_id));
2370 if (!session) {
2371 DBG("Relay session %" PRIu64 " not found",
2372 (uint64_t) be64toh(request.session_id));
2373 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
2374 goto send_reply;
2375 }
2376
2377 ret = viewer_session_is_attached(conn->viewer_session, session);
2378 if (ret != 1) {
2379 DBG("Not attached to this session");
2380 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2381 goto send_reply_put;
2382 }
2383
2384 viewer_session_close_one_session(conn->viewer_session, session);
2385 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_OK);
2386 DBG("Session %" PRIu64 " detached.", viewer_session_to_close);
2387
2388 send_reply_put:
2389 session_put(session);
2390
2391 send_reply:
2392 health_code_update();
2393 ret = send_response(conn->sock, &response, sizeof(response));
2394 if (ret < 0) {
2395 goto end;
2396 }
2397 health_code_update();
2398 ret = 0;
2399
2400 end:
2401 return ret;
2402 }
2403
2404 /*
2405 * live_relay_unknown_command: send -1 if received unknown command
2406 */
2407 static
2408 void live_relay_unknown_command(struct relay_connection *conn)
2409 {
2410 struct lttcomm_relayd_generic_reply reply;
2411
2412 memset(&reply, 0, sizeof(reply));
2413 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2414 (void) send_response(conn->sock, &reply, sizeof(reply));
2415 }
2416
2417 /*
2418 * Process the commands received on the control socket
2419 */
2420 static
2421 int process_control(struct lttng_viewer_cmd *recv_hdr,
2422 struct relay_connection *conn)
2423 {
2424 int ret = 0;
2425 uint32_t msg_value;
2426
2427 msg_value = be32toh(recv_hdr->cmd);
2428
2429 /*
2430 * Make sure we've done the version check before any command other then a
2431 * new client connection.
2432 */
2433 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
2434 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
2435 ret = -1;
2436 goto end;
2437 }
2438
2439 switch (msg_value) {
2440 case LTTNG_VIEWER_CONNECT:
2441 ret = viewer_connect(conn);
2442 break;
2443 case LTTNG_VIEWER_LIST_SESSIONS:
2444 ret = viewer_list_sessions(conn);
2445 break;
2446 case LTTNG_VIEWER_ATTACH_SESSION:
2447 ret = viewer_attach_session(conn);
2448 break;
2449 case LTTNG_VIEWER_GET_NEXT_INDEX:
2450 ret = viewer_get_next_index(conn);
2451 break;
2452 case LTTNG_VIEWER_GET_PACKET:
2453 ret = viewer_get_packet(conn);
2454 break;
2455 case LTTNG_VIEWER_GET_METADATA:
2456 ret = viewer_get_metadata(conn);
2457 break;
2458 case LTTNG_VIEWER_GET_NEW_STREAMS:
2459 ret = viewer_get_new_streams(conn);
2460 break;
2461 case LTTNG_VIEWER_CREATE_SESSION:
2462 ret = viewer_create_session(conn);
2463 break;
2464 case LTTNG_VIEWER_DETACH_SESSION:
2465 ret = viewer_detach_session(conn);
2466 break;
2467 default:
2468 ERR("Received unknown viewer command (%u)",
2469 be32toh(recv_hdr->cmd));
2470 live_relay_unknown_command(conn);
2471 ret = -1;
2472 goto end;
2473 }
2474
2475 end:
2476 return ret;
2477 }
2478
2479 static
2480 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2481 {
2482 int ret;
2483
2484 (void) lttng_poll_del(events, pollfd);
2485
2486 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
2487 fd_tracker_util_close_fd, NULL);
2488 if (ret < 0) {
2489 ERR("Closing pollfd %d", pollfd);
2490 }
2491 }
2492
2493 /*
2494 * This thread does the actual work
2495 */
2496 static
2497 void *thread_worker(void *data)
2498 {
2499 int ret, err = -1;
2500 uint32_t nb_fd;
2501 struct lttng_poll_event events;
2502 struct lttng_ht *viewer_connections_ht;
2503 struct lttng_ht_iter iter;
2504 struct lttng_viewer_cmd recv_hdr;
2505 struct relay_connection *destroy_conn;
2506
2507 DBG("[thread] Live viewer relay worker started");
2508
2509 rcu_register_thread();
2510
2511 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
2512
2513 if (testpoint(relayd_thread_live_worker)) {
2514 goto error_testpoint;
2515 }
2516
2517 /* table of connections indexed on socket */
2518 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2519 if (!viewer_connections_ht) {
2520 goto viewer_connections_ht_error;
2521 }
2522
2523 ret = create_named_thread_poll_set(&events, 2,
2524 "Live viewer worker thread epoll");
2525 if (ret < 0) {
2526 goto error_poll_create;
2527 }
2528
2529 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2530 if (ret < 0) {
2531 goto error;
2532 }
2533
2534 restart:
2535 while (1) {
2536 int i;
2537
2538 health_code_update();
2539
2540 /* Infinite blocking call, waiting for transmission */
2541 DBG3("Relayd live viewer worker thread polling...");
2542 health_poll_entry();
2543 ret = lttng_poll_wait(&events, -1);
2544 health_poll_exit();
2545 if (ret < 0) {
2546 /*
2547 * Restart interrupted system call.
2548 */
2549 if (errno == EINTR) {
2550 goto restart;
2551 }
2552 goto error;
2553 }
2554
2555 nb_fd = ret;
2556
2557 /*
2558 * Process control. The control connection is prioritised so we don't
2559 * starve it with high throughput tracing data on the data
2560 * connection.
2561 */
2562 for (i = 0; i < nb_fd; i++) {
2563 /* Fetch once the poll data */
2564 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2565 int pollfd = LTTNG_POLL_GETFD(&events, i);
2566
2567 health_code_update();
2568
2569 /* Thread quit pipe has been closed. Killing thread. */
2570 ret = check_thread_quit_pipe(pollfd, revents);
2571 if (ret) {
2572 err = 0;
2573 goto exit;
2574 }
2575
2576 /* Inspect the relay conn pipe for new connection. */
2577 if (pollfd == live_conn_pipe[0]) {
2578 if (revents & LPOLLIN) {
2579 struct relay_connection *conn;
2580
2581 ret = lttng_read(live_conn_pipe[0],
2582 &conn, sizeof(conn));
2583 if (ret < 0) {
2584 goto error;
2585 }
2586 ret = lttng_poll_add(&events,
2587 conn->sock->fd,
2588 LPOLLIN | LPOLLRDHUP);
2589 if (ret) {
2590 ERR("Failed to add new live connection file descriptor to poll set");
2591 goto error;
2592 }
2593 connection_ht_add(viewer_connections_ht, conn);
2594 DBG("Connection socket %d added to poll", conn->sock->fd);
2595 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2596 ERR("Relay live pipe error");
2597 goto error;
2598 } else {
2599 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2600 goto error;
2601 }
2602 } else {
2603 /* Connection activity. */
2604 struct relay_connection *conn;
2605
2606 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
2607 if (!conn) {
2608 continue;
2609 }
2610
2611 if (revents & LPOLLIN) {
2612 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2613 sizeof(recv_hdr), 0);
2614 if (ret <= 0) {
2615 /* Connection closed. */
2616 cleanup_connection_pollfd(&events, pollfd);
2617 /* Put "create" ownership reference. */
2618 connection_put(conn);
2619 DBG("Viewer control conn closed with %d", pollfd);
2620 } else {
2621 ret = process_control(&recv_hdr, conn);
2622 if (ret < 0) {
2623 /* Clear the session on error. */
2624 cleanup_connection_pollfd(&events, pollfd);
2625 /* Put "create" ownership reference. */
2626 connection_put(conn);
2627 DBG("Viewer connection closed with %d", pollfd);
2628 }
2629 }
2630 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2631 cleanup_connection_pollfd(&events, pollfd);
2632 /* Put "create" ownership reference. */
2633 connection_put(conn);
2634 } else {
2635 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2636 connection_put(conn);
2637 goto error;
2638 }
2639 /* Put local "get_by_sock" reference. */
2640 connection_put(conn);
2641 }
2642 }
2643 }
2644
2645 exit:
2646 error:
2647 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
2648
2649 /* Cleanup remaining connection object. */
2650 rcu_read_lock();
2651 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
2652 destroy_conn,
2653 sock_n.node) {
2654 health_code_update();
2655 connection_put(destroy_conn);
2656 }
2657 rcu_read_unlock();
2658 error_poll_create:
2659 lttng_ht_destroy(viewer_connections_ht);
2660 viewer_connections_ht_error:
2661 /* Close relay conn pipes */
2662 (void) fd_tracker_util_pipe_close(the_fd_tracker, live_conn_pipe);
2663 if (err) {
2664 DBG("Viewer worker thread exited with error");
2665 }
2666 DBG("Viewer worker thread cleanup complete");
2667 error_testpoint:
2668 if (err) {
2669 health_error();
2670 ERR("Health error occurred in %s", __func__);
2671 }
2672 health_unregister(health_relayd);
2673 if (lttng_relay_stop_threads()) {
2674 ERR("Error stopping threads");
2675 }
2676 rcu_unregister_thread();
2677 return NULL;
2678 }
2679
2680 /*
2681 * Create the relay command pipe to wake thread_manage_apps.
2682 * Closed in cleanup().
2683 */
2684 static int create_conn_pipe(void)
2685 {
2686 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
2687 "Live connection pipe", live_conn_pipe);
2688 }
2689
2690 int relayd_live_join(void)
2691 {
2692 int ret, retval = 0;
2693 void *status;
2694
2695 ret = pthread_join(live_listener_thread, &status);
2696 if (ret) {
2697 errno = ret;
2698 PERROR("pthread_join live listener");
2699 retval = -1;
2700 }
2701
2702 ret = pthread_join(live_worker_thread, &status);
2703 if (ret) {
2704 errno = ret;
2705 PERROR("pthread_join live worker");
2706 retval = -1;
2707 }
2708
2709 ret = pthread_join(live_dispatcher_thread, &status);
2710 if (ret) {
2711 errno = ret;
2712 PERROR("pthread_join live dispatcher");
2713 retval = -1;
2714 }
2715
2716 cleanup_relayd_live();
2717
2718 return retval;
2719 }
2720
2721 /*
2722 * main
2723 */
2724 int relayd_live_create(struct lttng_uri *uri)
2725 {
2726 int ret = 0, retval = 0;
2727 void *status;
2728 int is_root;
2729
2730 if (!uri) {
2731 retval = -1;
2732 goto exit_init_data;
2733 }
2734 live_uri = uri;
2735
2736 /* Check if daemon is UID = 0 */
2737 is_root = !getuid();
2738
2739 if (!is_root) {
2740 if (live_uri->port < 1024) {
2741 ERR("Need to be root to use ports < 1024");
2742 retval = -1;
2743 goto exit_init_data;
2744 }
2745 }
2746
2747 /* Setup the thread apps communication pipe. */
2748 if (create_conn_pipe()) {
2749 retval = -1;
2750 goto exit_init_data;
2751 }
2752
2753 /* Init relay command queue. */
2754 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2755
2756 /* Set up max poll set size */
2757 if (lttng_poll_set_max_size()) {
2758 retval = -1;
2759 goto exit_init_data;
2760 }
2761
2762 /* Setup the dispatcher thread */
2763 ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
2764 thread_dispatcher, (void *) NULL);
2765 if (ret) {
2766 errno = ret;
2767 PERROR("pthread_create viewer dispatcher");
2768 retval = -1;
2769 goto exit_dispatcher_thread;
2770 }
2771
2772 /* Setup the worker thread */
2773 ret = pthread_create(&live_worker_thread, default_pthread_attr(),
2774 thread_worker, NULL);
2775 if (ret) {
2776 errno = ret;
2777 PERROR("pthread_create viewer worker");
2778 retval = -1;
2779 goto exit_worker_thread;
2780 }
2781
2782 /* Setup the listener thread */
2783 ret = pthread_create(&live_listener_thread, default_pthread_attr(),
2784 thread_listener, (void *) NULL);
2785 if (ret) {
2786 errno = ret;
2787 PERROR("pthread_create viewer listener");
2788 retval = -1;
2789 goto exit_listener_thread;
2790 }
2791
2792 /*
2793 * All OK, started all threads.
2794 */
2795 return retval;
2796
2797 /*
2798 * Join on the live_listener_thread should anything be added after
2799 * the live_listener thread's creation.
2800 */
2801
2802 exit_listener_thread:
2803
2804 ret = pthread_join(live_worker_thread, &status);
2805 if (ret) {
2806 errno = ret;
2807 PERROR("pthread_join live worker");
2808 retval = -1;
2809 }
2810 exit_worker_thread:
2811
2812 ret = pthread_join(live_dispatcher_thread, &status);
2813 if (ret) {
2814 errno = ret;
2815 PERROR("pthread_join live dispatcher");
2816 retval = -1;
2817 }
2818 exit_dispatcher_thread:
2819
2820 exit_init_data:
2821 cleanup_relayd_live();
2822
2823 return retval;
2824 }
This page took 0.094822 seconds and 4 git commands to generate.