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