Tests: Add test to check shared-memory FD leaks after relayd dies
[lttng-tools.git] / src / bin / lttng-relayd / live.cpp
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 LTTNG_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 relay_session->ongoing_rotation) &&
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 LTTNG_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 = (lttcomm_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 = (lttcomm_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 = (lttcomm_sock **) 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_head_ptr_t head;
788 head.h = &viewer_conn_queue.head;
789 cds_wfcq_enqueue(head, &viewer_conn_queue.tail,
790 &new_conn->qnode);
791
792 /*
793 * Wake the dispatch queue futex.
794 * Implicit memory barrier with the
795 * exchange in cds_wfcq_enqueue.
796 */
797 futex_nto1_wake(&viewer_conn_queue.futex);
798 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
799 ERR("socket poll error");
800 goto error;
801 } else {
802 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
803 goto error;
804 }
805 }
806 }
807
808 exit:
809 error:
810 error_poll_add:
811 error_testpoint:
812 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
813 error_create_poll:
814 if (live_control_sock->fd >= 0) {
815 int sock_fd = live_control_sock->fd;
816
817 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker,
818 &sock_fd, 1, close_sock,
819 live_control_sock);
820 if (ret) {
821 PERROR("close");
822 }
823 live_control_sock->fd = -1;
824 }
825 lttcomm_destroy_sock(live_control_sock);
826 error_sock_control:
827 if (err) {
828 health_error();
829 DBG("Live viewer listener thread exited with error");
830 }
831 health_unregister(health_relayd);
832 rcu_unregister_thread();
833 DBG("Live viewer listener thread cleanup complete");
834 if (lttng_relay_stop_threads()) {
835 ERR("Error stopping threads");
836 }
837 return NULL;
838 }
839
840 /*
841 * This thread manages the dispatching of the requests to worker threads
842 */
843 static
844 void *thread_dispatcher(void *data)
845 {
846 int err = -1;
847 ssize_t ret;
848 struct cds_wfcq_node *node;
849 struct relay_connection *conn = NULL;
850
851 DBG("[thread] Live viewer relay dispatcher started");
852
853 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_DISPATCHER);
854
855 if (testpoint(relayd_thread_live_dispatcher)) {
856 goto error_testpoint;
857 }
858
859 health_code_update();
860
861 for (;;) {
862 health_code_update();
863
864 /* Atomically prepare the queue futex */
865 futex_nto1_prepare(&viewer_conn_queue.futex);
866
867 if (CMM_LOAD_SHARED(live_dispatch_thread_exit)) {
868 break;
869 }
870
871 do {
872 health_code_update();
873
874 /* Dequeue commands */
875 node = cds_wfcq_dequeue_blocking(&viewer_conn_queue.head,
876 &viewer_conn_queue.tail);
877 if (node == NULL) {
878 DBG("Woken up but nothing in the live-viewer "
879 "relay command queue");
880 /* Continue thread execution */
881 break;
882 }
883 conn = caa_container_of(node, struct relay_connection, qnode);
884 DBG("Dispatching viewer request waiting on sock %d",
885 conn->sock->fd);
886
887 /*
888 * Inform worker thread of the new request. This
889 * call is blocking so we can be assured that
890 * the data will be read at some point in time
891 * or wait to the end of the world :)
892 */
893 ret = lttng_write(live_conn_pipe[1], &conn, sizeof(conn));
894 if (ret < 0) {
895 PERROR("write conn pipe");
896 connection_put(conn);
897 goto error;
898 }
899 } while (node != NULL);
900
901 /* Futex wait on queue. Blocking call on futex() */
902 health_poll_entry();
903 futex_nto1_wait(&viewer_conn_queue.futex);
904 health_poll_exit();
905 }
906
907 /* Normal exit, no error */
908 err = 0;
909
910 error:
911 error_testpoint:
912 if (err) {
913 health_error();
914 ERR("Health error occurred in %s", __func__);
915 }
916 health_unregister(health_relayd);
917 DBG("Live viewer dispatch thread dying");
918 if (lttng_relay_stop_threads()) {
919 ERR("Error stopping threads");
920 }
921 return NULL;
922 }
923
924 /*
925 * Establish connection with the viewer and check the versions.
926 *
927 * Return 0 on success or else negative value.
928 */
929 static
930 int viewer_connect(struct relay_connection *conn)
931 {
932 int ret;
933 struct lttng_viewer_connect reply, msg;
934
935 conn->version_check_done = 1;
936
937 health_code_update();
938
939 DBG("Viewer is establishing a connection to the relayd.");
940
941 ret = recv_request(conn->sock, &msg, sizeof(msg));
942 if (ret < 0) {
943 goto end;
944 }
945
946 health_code_update();
947
948 memset(&reply, 0, sizeof(reply));
949 reply.major = RELAYD_VERSION_COMM_MAJOR;
950 reply.minor = RELAYD_VERSION_COMM_MINOR;
951
952 /* Major versions must be the same */
953 if (reply.major != be32toh(msg.major)) {
954 DBG("Incompatible major versions ([relayd] %u vs [client] %u)",
955 reply.major, be32toh(msg.major));
956 ret = -1;
957 goto end;
958 }
959
960 conn->major = reply.major;
961 /* We adapt to the lowest compatible version */
962 if (reply.minor <= be32toh(msg.minor)) {
963 conn->minor = reply.minor;
964 } else {
965 conn->minor = be32toh(msg.minor);
966 }
967
968 if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_COMMAND) {
969 conn->type = RELAY_VIEWER_COMMAND;
970 } else if (be32toh(msg.type) == LTTNG_VIEWER_CLIENT_NOTIFICATION) {
971 conn->type = RELAY_VIEWER_NOTIFICATION;
972 } else {
973 ERR("Unknown connection type : %u", be32toh(msg.type));
974 ret = -1;
975 goto end;
976 }
977
978 reply.major = htobe32(reply.major);
979 reply.minor = htobe32(reply.minor);
980 if (conn->type == RELAY_VIEWER_COMMAND) {
981 /*
982 * Increment outside of htobe64 macro, because the argument can
983 * be used more than once within the macro, and thus the
984 * operation may be undefined.
985 */
986 pthread_mutex_lock(&last_relay_viewer_session_id_lock);
987 last_relay_viewer_session_id++;
988 pthread_mutex_unlock(&last_relay_viewer_session_id_lock);
989 reply.viewer_session_id = htobe64(last_relay_viewer_session_id);
990 }
991
992 health_code_update();
993
994 ret = send_response(conn->sock, &reply, sizeof(reply));
995 if (ret < 0) {
996 goto end;
997 }
998
999 health_code_update();
1000
1001 DBG("Version check done using protocol %u.%u", conn->major, conn->minor);
1002 ret = 0;
1003
1004 end:
1005 return ret;
1006 }
1007
1008 /*
1009 * Send the viewer the list of current sessions.
1010 * We need to create a copy of the hash table content because otherwise
1011 * we cannot assume the number of entries stays the same between getting
1012 * the number of HT elements and iteration over the HT.
1013 *
1014 * Return 0 on success or else a negative value.
1015 */
1016 static
1017 int viewer_list_sessions(struct relay_connection *conn)
1018 {
1019 int ret = 0;
1020 struct lttng_viewer_list_sessions session_list;
1021 struct lttng_ht_iter iter;
1022 struct relay_session *session;
1023 struct lttng_viewer_session *send_session_buf = NULL;
1024 uint32_t buf_count = SESSION_BUF_DEFAULT_COUNT;
1025 uint32_t count = 0;
1026
1027 DBG("List sessions received");
1028
1029 send_session_buf = (lttng_viewer_session *) zmalloc(SESSION_BUF_DEFAULT_COUNT * sizeof(*send_session_buf));
1030 if (!send_session_buf) {
1031 return -1;
1032 }
1033
1034 rcu_read_lock();
1035 cds_lfht_for_each_entry(sessions_ht->ht, &iter.iter, session,
1036 session_n.node) {
1037 struct lttng_viewer_session *send_session;
1038
1039 health_code_update();
1040
1041 pthread_mutex_lock(&session->lock);
1042 if (session->connection_closed) {
1043 /* Skip closed session */
1044 goto next_session;
1045 }
1046
1047 if (count >= buf_count) {
1048 struct lttng_viewer_session *newbuf;
1049 uint32_t new_buf_count = buf_count << 1;
1050
1051 newbuf = (lttng_viewer_session *) realloc(send_session_buf,
1052 new_buf_count * sizeof(*send_session_buf));
1053 if (!newbuf) {
1054 ret = -1;
1055 goto break_loop;
1056 }
1057 send_session_buf = newbuf;
1058 buf_count = new_buf_count;
1059 }
1060 send_session = &send_session_buf[count];
1061 if (lttng_strncpy(send_session->session_name,
1062 session->session_name,
1063 sizeof(send_session->session_name))) {
1064 ret = -1;
1065 goto break_loop;
1066 }
1067 if (lttng_strncpy(send_session->hostname, session->hostname,
1068 sizeof(send_session->hostname))) {
1069 ret = -1;
1070 goto break_loop;
1071 }
1072 send_session->id = htobe64(session->id);
1073 send_session->live_timer = htobe32(session->live_timer);
1074 if (session->viewer_attached) {
1075 send_session->clients = htobe32(1);
1076 } else {
1077 send_session->clients = htobe32(0);
1078 }
1079 send_session->streams = htobe32(session->stream_count);
1080 count++;
1081 next_session:
1082 pthread_mutex_unlock(&session->lock);
1083 continue;
1084 break_loop:
1085 pthread_mutex_unlock(&session->lock);
1086 break;
1087 }
1088 rcu_read_unlock();
1089 if (ret < 0) {
1090 goto end_free;
1091 }
1092
1093 session_list.sessions_count = htobe32(count);
1094
1095 health_code_update();
1096
1097 ret = send_response(conn->sock, &session_list, sizeof(session_list));
1098 if (ret < 0) {
1099 goto end_free;
1100 }
1101
1102 health_code_update();
1103
1104 ret = send_response(conn->sock, send_session_buf,
1105 count * sizeof(*send_session_buf));
1106 if (ret < 0) {
1107 goto end_free;
1108 }
1109 health_code_update();
1110
1111 ret = 0;
1112 end_free:
1113 free(send_session_buf);
1114 return ret;
1115 }
1116
1117 /*
1118 * Send the viewer the list of current streams.
1119 */
1120 static
1121 int viewer_get_new_streams(struct relay_connection *conn)
1122 {
1123 int ret, send_streams = 0;
1124 uint32_t nb_created = 0, nb_unsent = 0, nb_streams = 0, nb_total = 0;
1125 struct lttng_viewer_new_streams_request request;
1126 struct lttng_viewer_new_streams_response response;
1127 struct relay_session *session = NULL;
1128 uint64_t session_id;
1129 bool closed = false;
1130
1131 LTTNG_ASSERT(conn);
1132
1133 DBG("Get new streams received");
1134
1135 health_code_update();
1136
1137 /* Receive the request from the connected client. */
1138 ret = recv_request(conn->sock, &request, sizeof(request));
1139 if (ret < 0) {
1140 goto error;
1141 }
1142 session_id = be64toh(request.session_id);
1143
1144 health_code_update();
1145
1146 memset(&response, 0, sizeof(response));
1147
1148 session = session_get_by_id(session_id);
1149 if (!session) {
1150 DBG("Relay session %" PRIu64 " not found", session_id);
1151 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1152 goto send_reply;
1153 }
1154
1155 if (!viewer_session_is_attached(conn->viewer_session, session)) {
1156 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_ERR);
1157 goto send_reply;
1158 }
1159
1160 /*
1161 * For any new stream, create it with LTTNG_VIEWER_SEEK_BEGINNING since
1162 * that at this point the client is already attached to the session.Aany
1163 * initial stream will have been created with the seek type at attach
1164 * time (for now most readers use the LTTNG_VIEWER_SEEK_LAST on attach).
1165 * Otherwise any event happening in a new stream between the attach and
1166 * a call to viewer_get_new_streams will be "lost" (never received) from
1167 * the viewer's point of view.
1168 */
1169 pthread_mutex_lock(&session->lock);
1170 ret = make_viewer_streams(session,
1171 conn->viewer_session,
1172 LTTNG_VIEWER_SEEK_BEGINNING, &nb_total, &nb_unsent,
1173 &nb_created, &closed);
1174 if (ret < 0) {
1175 goto error_unlock_session;
1176 }
1177 send_streams = 1;
1178 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_OK);
1179
1180 /* Only send back the newly created streams with the unsent ones. */
1181 nb_streams = nb_created + nb_unsent;
1182 response.streams_count = htobe32(nb_streams);
1183
1184 /*
1185 * If the session is closed, HUP when there are no more streams
1186 * with data.
1187 */
1188 if (closed && nb_total == 0) {
1189 send_streams = 0;
1190 response.streams_count = 0;
1191 response.status = htobe32(LTTNG_VIEWER_NEW_STREAMS_HUP);
1192 goto send_reply_unlock;
1193 }
1194 send_reply_unlock:
1195 pthread_mutex_unlock(&session->lock);
1196
1197 send_reply:
1198 health_code_update();
1199 ret = send_response(conn->sock, &response, sizeof(response));
1200 if (ret < 0) {
1201 goto end_put_session;
1202 }
1203 health_code_update();
1204
1205 /*
1206 * Unknown or empty session, just return gracefully, the viewer
1207 * knows what is happening.
1208 */
1209 if (!send_streams || !nb_streams) {
1210 ret = 0;
1211 goto end_put_session;
1212 }
1213
1214 /*
1215 * Send stream and *DON'T* ignore the sent flag so every viewer
1216 * streams that were not sent from that point will be sent to
1217 * the viewer.
1218 */
1219 ret = send_viewer_streams(conn->sock, session_id, 0);
1220 if (ret < 0) {
1221 goto end_put_session;
1222 }
1223
1224 end_put_session:
1225 if (session) {
1226 session_put(session);
1227 }
1228 error:
1229 return ret;
1230 error_unlock_session:
1231 pthread_mutex_unlock(&session->lock);
1232 session_put(session);
1233 return ret;
1234 }
1235
1236 /*
1237 * Send the viewer the list of current sessions.
1238 */
1239 static
1240 int viewer_attach_session(struct relay_connection *conn)
1241 {
1242 int send_streams = 0;
1243 ssize_t ret;
1244 uint32_t nb_streams = 0;
1245 enum lttng_viewer_seek seek_type;
1246 struct lttng_viewer_attach_session_request request;
1247 struct lttng_viewer_attach_session_response response;
1248 struct relay_session *session = NULL;
1249 enum lttng_viewer_attach_return_code viewer_attach_status;
1250 bool closed = false;
1251 uint64_t session_id;
1252
1253 LTTNG_ASSERT(conn);
1254
1255 health_code_update();
1256
1257 /* Receive the request from the connected client. */
1258 ret = recv_request(conn->sock, &request, sizeof(request));
1259 if (ret < 0) {
1260 goto error;
1261 }
1262
1263 session_id = be64toh(request.session_id);
1264 health_code_update();
1265
1266 memset(&response, 0, sizeof(response));
1267
1268 if (!conn->viewer_session) {
1269 DBG("Client trying to attach before creating a live viewer session");
1270 response.status = htobe32(LTTNG_VIEWER_ATTACH_NO_SESSION);
1271 goto send_reply;
1272 }
1273
1274 session = session_get_by_id(session_id);
1275 if (!session) {
1276 DBG("Relay session %" PRIu64 " not found", session_id);
1277 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1278 goto send_reply;
1279 }
1280 DBG("Attach session ID %" PRIu64 " received", session_id);
1281
1282 pthread_mutex_lock(&session->lock);
1283 if (session->live_timer == 0) {
1284 DBG("Not live session");
1285 response.status = htobe32(LTTNG_VIEWER_ATTACH_NOT_LIVE);
1286 goto send_reply;
1287 }
1288
1289 send_streams = 1;
1290 viewer_attach_status = viewer_session_attach(conn->viewer_session,
1291 session);
1292 if (viewer_attach_status != LTTNG_VIEWER_ATTACH_OK) {
1293 response.status = htobe32(viewer_attach_status);
1294 goto send_reply;
1295 }
1296
1297 switch (be32toh(request.seek)) {
1298 case LTTNG_VIEWER_SEEK_BEGINNING:
1299 case LTTNG_VIEWER_SEEK_LAST:
1300 response.status = htobe32(LTTNG_VIEWER_ATTACH_OK);
1301 seek_type = (lttng_viewer_seek) be32toh(request.seek);
1302 break;
1303 default:
1304 ERR("Wrong seek parameter");
1305 response.status = htobe32(LTTNG_VIEWER_ATTACH_SEEK_ERR);
1306 send_streams = 0;
1307 goto send_reply;
1308 }
1309
1310 ret = make_viewer_streams(session,
1311 conn->viewer_session, seek_type,
1312 &nb_streams, NULL, NULL, &closed);
1313 if (ret < 0) {
1314 goto end_put_session;
1315 }
1316 pthread_mutex_unlock(&session->lock);
1317 session_put(session);
1318 session = NULL;
1319
1320 response.streams_count = htobe32(nb_streams);
1321 /*
1322 * If the session is closed when the viewer is attaching, it
1323 * means some of the streams may have been concurrently removed,
1324 * so we don't allow the viewer to attach, even if there are
1325 * streams available.
1326 */
1327 if (closed) {
1328 send_streams = 0;
1329 response.streams_count = 0;
1330 response.status = htobe32(LTTNG_VIEWER_ATTACH_UNK);
1331 goto send_reply;
1332 }
1333
1334 send_reply:
1335 health_code_update();
1336 ret = send_response(conn->sock, &response, sizeof(response));
1337 if (ret < 0) {
1338 goto end_put_session;
1339 }
1340 health_code_update();
1341
1342 /*
1343 * Unknown or empty session, just return gracefully, the viewer
1344 * knows what is happening.
1345 */
1346 if (!send_streams || !nb_streams) {
1347 ret = 0;
1348 goto end_put_session;
1349 }
1350
1351 /* Send stream and ignore the sent flag. */
1352 ret = send_viewer_streams(conn->sock, session_id, 1);
1353 if (ret < 0) {
1354 goto end_put_session;
1355 }
1356
1357 end_put_session:
1358 if (session) {
1359 pthread_mutex_unlock(&session->lock);
1360 session_put(session);
1361 }
1362 error:
1363 return ret;
1364 }
1365
1366 /*
1367 * Open the index file if needed for the given vstream.
1368 *
1369 * If an index file is successfully opened, the vstream will set it as its
1370 * current index file.
1371 *
1372 * Return 0 on success, a negative value on error (-ENOENT if not ready yet).
1373 *
1374 * Called with rstream lock held.
1375 */
1376 static int try_open_index(struct relay_viewer_stream *vstream,
1377 struct relay_stream *rstream)
1378 {
1379 int ret = 0;
1380 const uint32_t connection_major = rstream->trace->session->major;
1381 const uint32_t connection_minor = rstream->trace->session->minor;
1382 enum lttng_trace_chunk_status chunk_status;
1383
1384 if (vstream->index_file) {
1385 goto end;
1386 }
1387
1388 /*
1389 * First time, we open the index file and at least one index is ready.
1390 */
1391 if (rstream->index_received_seqcount == 0 ||
1392 !vstream->stream_file.trace_chunk) {
1393 ret = -ENOENT;
1394 goto end;
1395 }
1396
1397 chunk_status = lttng_index_file_create_from_trace_chunk_read_only(
1398 vstream->stream_file.trace_chunk, rstream->path_name,
1399 rstream->channel_name, rstream->tracefile_size,
1400 vstream->current_tracefile_id,
1401 lttng_to_index_major(connection_major, connection_minor),
1402 lttng_to_index_minor(connection_major, connection_minor),
1403 true, &vstream->index_file);
1404 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1405 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
1406 ret = -ENOENT;
1407 } else {
1408 ret = -1;
1409 }
1410 }
1411
1412 end:
1413 return ret;
1414 }
1415
1416 /*
1417 * Check the status of the index for the given stream. This function
1418 * updates the index structure if needed and can put (close) the vstream
1419 * in the HUP situation.
1420 *
1421 * Return 0 means that we can proceed with the index. A value of 1 means
1422 * that the index has been updated and is ready to be sent to the
1423 * client. A negative value indicates an error that can't be handled.
1424 *
1425 * Called with rstream lock held.
1426 */
1427 static int check_index_status(struct relay_viewer_stream *vstream,
1428 struct relay_stream *rstream, struct ctf_trace *trace,
1429 struct lttng_viewer_index *index)
1430 {
1431 int ret;
1432
1433 DBG("Check index status: index_received_seqcount %" PRIu64 " "
1434 "index_sent_seqcount %" PRIu64 " "
1435 "for stream %" PRIu64,
1436 rstream->index_received_seqcount,
1437 vstream->index_sent_seqcount,
1438 vstream->stream->stream_handle);
1439 if ((trace->session->connection_closed || rstream->closed)
1440 && rstream->index_received_seqcount
1441 == vstream->index_sent_seqcount) {
1442 /*
1443 * Last index sent and session connection or relay
1444 * stream are closed.
1445 */
1446 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1447 goto hup;
1448 } else if (rstream->beacon_ts_end != -1ULL &&
1449 (rstream->index_received_seqcount == 0 ||
1450 (vstream->index_sent_seqcount != 0 &&
1451 rstream->index_received_seqcount
1452 <= vstream->index_sent_seqcount))) {
1453 /*
1454 * We've received a synchronization beacon and the last index
1455 * available has been sent, the index for now is inactive.
1456 *
1457 * In this case, we have received a beacon which allows us to
1458 * inform the client of a time interval during which we can
1459 * guarantee that there are no events to read (and never will
1460 * be).
1461 *
1462 * The sent seqcount can grow higher than receive seqcount on
1463 * clear because the rotation performed by clear will push
1464 * the index_sent_seqcount ahead (see
1465 * viewer_stream_sync_tracefile_array_tail) and skip over
1466 * packet sequence numbers.
1467 */
1468 index->status = htobe32(LTTNG_VIEWER_INDEX_INACTIVE);
1469 index->timestamp_end = htobe64(rstream->beacon_ts_end);
1470 index->stream_id = htobe64(rstream->ctf_stream_id);
1471 DBG("Check index status: inactive with beacon, for stream %" PRIu64,
1472 vstream->stream->stream_handle);
1473 goto index_ready;
1474 } else if (rstream->index_received_seqcount == 0 ||
1475 (vstream->index_sent_seqcount != 0 &&
1476 rstream->index_received_seqcount
1477 <= vstream->index_sent_seqcount)) {
1478 /*
1479 * This checks whether received <= sent seqcount. In
1480 * this case, we have not received a beacon. Therefore,
1481 * we can only ask the client to retry later.
1482 *
1483 * The sent seqcount can grow higher than receive seqcount on
1484 * clear because the rotation performed by clear will push
1485 * the index_sent_seqcount ahead (see
1486 * viewer_stream_sync_tracefile_array_tail) and skip over
1487 * packet sequence numbers.
1488 */
1489 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1490 DBG("Check index status: retry for stream %" PRIu64,
1491 vstream->stream->stream_handle);
1492 goto index_ready;
1493 } else if (!tracefile_array_seq_in_file(rstream->tfa,
1494 vstream->current_tracefile_id,
1495 vstream->index_sent_seqcount)) {
1496 /*
1497 * The next index we want to send cannot be read either
1498 * because we need to perform a rotation, or due to
1499 * the producer having overwritten its trace file.
1500 */
1501 DBG("Viewer stream %" PRIu64 " rotation",
1502 vstream->stream->stream_handle);
1503 ret = viewer_stream_rotate(vstream);
1504 if (ret == 1) {
1505 /* EOF across entire stream. */
1506 index->status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1507 goto hup;
1508 }
1509 /*
1510 * If we have been pushed due to overwrite, it
1511 * necessarily means there is data that can be read in
1512 * the stream. If we rotated because we reached the end
1513 * of a tracefile, it means the following tracefile
1514 * needs to contain at least one index, else we would
1515 * have already returned LTTNG_VIEWER_INDEX_RETRY to the
1516 * viewer. The updated index_sent_seqcount needs to
1517 * point to a readable index entry now.
1518 *
1519 * In the case where we "rotate" on a single file, we
1520 * can end up in a case where the requested index is
1521 * still unavailable.
1522 */
1523 if (rstream->tracefile_count == 1 &&
1524 !tracefile_array_seq_in_file(
1525 rstream->tfa,
1526 vstream->current_tracefile_id,
1527 vstream->index_sent_seqcount)) {
1528 index->status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1529 DBG("Check index status: retry: "
1530 "tracefile array sequence number %" PRIu64
1531 " not in file for stream %" PRIu64,
1532 vstream->index_sent_seqcount,
1533 vstream->stream->stream_handle);
1534 goto index_ready;
1535 }
1536 LTTNG_ASSERT(tracefile_array_seq_in_file(rstream->tfa,
1537 vstream->current_tracefile_id,
1538 vstream->index_sent_seqcount));
1539 }
1540 /* ret == 0 means successful so we continue. */
1541 ret = 0;
1542 return ret;
1543
1544 hup:
1545 viewer_stream_put(vstream);
1546 index_ready:
1547 return 1;
1548 }
1549
1550 static
1551 void viewer_stream_rotate_to_trace_chunk(struct relay_viewer_stream *vstream,
1552 struct lttng_trace_chunk *new_trace_chunk)
1553 {
1554 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
1555
1556 if (new_trace_chunk) {
1557 const bool acquired_reference = lttng_trace_chunk_get(
1558 new_trace_chunk);
1559
1560 LTTNG_ASSERT(acquired_reference);
1561 }
1562
1563 vstream->stream_file.trace_chunk = new_trace_chunk;
1564 viewer_stream_sync_tracefile_array_tail(vstream);
1565 viewer_stream_close_files(vstream);
1566 }
1567
1568 /*
1569 * Send the next index for a stream.
1570 *
1571 * Return 0 on success or else a negative value.
1572 */
1573 static
1574 int viewer_get_next_index(struct relay_connection *conn)
1575 {
1576 int ret;
1577 struct lttng_viewer_get_next_index request_index;
1578 struct lttng_viewer_index viewer_index;
1579 struct ctf_packet_index packet_index;
1580 struct relay_viewer_stream *vstream = NULL;
1581 struct relay_stream *rstream = NULL;
1582 struct ctf_trace *ctf_trace = NULL;
1583 struct relay_viewer_stream *metadata_viewer_stream = NULL;
1584
1585 LTTNG_ASSERT(conn);
1586
1587 DBG("Viewer get next index");
1588
1589 memset(&viewer_index, 0, sizeof(viewer_index));
1590 health_code_update();
1591
1592 ret = recv_request(conn->sock, &request_index, sizeof(request_index));
1593 if (ret < 0) {
1594 goto end;
1595 }
1596 health_code_update();
1597
1598 vstream = viewer_stream_get_by_id(be64toh(request_index.stream_id));
1599 if (!vstream) {
1600 DBG("Client requested index of unknown stream id %" PRIu64,
1601 (uint64_t) be64toh(request_index.stream_id));
1602 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1603 goto send_reply;
1604 }
1605
1606 /* Use back. ref. Protected by refcounts. */
1607 rstream = vstream->stream;
1608 ctf_trace = rstream->trace;
1609
1610 /* metadata_viewer_stream may be NULL. */
1611 metadata_viewer_stream =
1612 ctf_trace_get_viewer_metadata_stream(ctf_trace);
1613
1614 pthread_mutex_lock(&rstream->lock);
1615
1616 /*
1617 * The viewer should not ask for index on metadata stream.
1618 */
1619 if (rstream->is_metadata) {
1620 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1621 goto send_reply;
1622 }
1623
1624 if (rstream->ongoing_rotation.is_set) {
1625 /* Rotation is ongoing, try again later. */
1626 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1627 goto send_reply;
1628 }
1629
1630 if (rstream->trace->session->ongoing_rotation) {
1631 /* Rotation is ongoing, try again later. */
1632 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1633 goto send_reply;
1634 }
1635
1636 /*
1637 * Transition the viewer session into the newest trace chunk available.
1638 */
1639 if (!lttng_trace_chunk_ids_equal(
1640 conn->viewer_session->current_trace_chunk,
1641 rstream->trace_chunk)) {
1642 DBG("Relay stream and viewer chunk ids differ");
1643
1644 ret = viewer_session_set_trace_chunk_copy(
1645 conn->viewer_session,
1646 rstream->trace_chunk);
1647 if (ret) {
1648 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1649 goto send_reply;
1650 }
1651 }
1652
1653 /*
1654 * Transition the viewer stream into the latest trace chunk available.
1655 *
1656 * Note that the stream must _not_ rotate in one precise condition:
1657 * the relay stream has rotated to a NULL trace chunk and the viewer
1658 * stream is consuming the trace chunk that was active just before
1659 * that rotation to NULL.
1660 *
1661 * This allows clients to consume all the packets of a trace chunk
1662 * after a session's destruction.
1663 */
1664 if (conn->viewer_session->current_trace_chunk != vstream->stream_file.trace_chunk &&
1665 !(rstream->completed_rotation_count == vstream->last_seen_rotation_count + 1 && !rstream->trace_chunk)) {
1666 DBG("Viewer session and viewer stream chunk differ: "
1667 "vsession chunk %p vstream chunk %p",
1668 conn->viewer_session->current_trace_chunk,
1669 vstream->stream_file.trace_chunk);
1670 viewer_stream_rotate_to_trace_chunk(vstream,
1671 conn->viewer_session->current_trace_chunk);
1672 vstream->last_seen_rotation_count =
1673 rstream->completed_rotation_count;
1674 }
1675
1676 ret = check_index_status(vstream, rstream, ctf_trace, &viewer_index);
1677 if (ret < 0) {
1678 goto error_put;
1679 } else if (ret == 1) {
1680 /*
1681 * We have no index to send and check_index_status has populated
1682 * viewer_index's status.
1683 */
1684 goto send_reply;
1685 }
1686 /* At this point, ret is 0 thus we will be able to read the index. */
1687 LTTNG_ASSERT(!ret);
1688
1689 /* Try to open an index if one is needed for that stream. */
1690 ret = try_open_index(vstream, rstream);
1691 if (ret == -ENOENT) {
1692 if (rstream->closed) {
1693 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1694 goto send_reply;
1695 } else {
1696 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_RETRY);
1697 goto send_reply;
1698 }
1699 }
1700 if (ret < 0) {
1701 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1702 goto send_reply;
1703 }
1704
1705 /*
1706 * vstream->stream_fd may be NULL if it has been closed by
1707 * tracefile rotation, or if we are at the beginning of the
1708 * stream. We open the data stream file here to protect against
1709 * overwrite caused by tracefile rotation (in association with
1710 * unlink performed before overwrite).
1711 */
1712 if (!vstream->stream_file.handle) {
1713 char file_path[LTTNG_PATH_MAX];
1714 enum lttng_trace_chunk_status status;
1715 struct fs_handle *fs_handle;
1716
1717 ret = utils_stream_file_path(rstream->path_name,
1718 rstream->channel_name, rstream->tracefile_size,
1719 vstream->current_tracefile_id, NULL, file_path,
1720 sizeof(file_path));
1721 if (ret < 0) {
1722 goto error_put;
1723 }
1724
1725 /*
1726 * It is possible the the file we are trying to open is
1727 * missing if the stream has been closed (application exits with
1728 * per-pid buffers) and a clear command has been performed.
1729 */
1730 status = lttng_trace_chunk_open_fs_handle(
1731 vstream->stream_file.trace_chunk,
1732 file_path, O_RDONLY, 0, &fs_handle, true);
1733 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
1734 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE &&
1735 rstream->closed) {
1736 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_HUP);
1737 goto send_reply;
1738 }
1739 PERROR("Failed to open trace file for viewer stream");
1740 goto error_put;
1741 }
1742 vstream->stream_file.handle = fs_handle;
1743 }
1744
1745 ret = check_new_streams(conn);
1746 if (ret < 0) {
1747 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1748 goto send_reply;
1749 } else if (ret == 1) {
1750 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_STREAM;
1751 }
1752
1753 ret = lttng_index_file_read(vstream->index_file, &packet_index);
1754 if (ret) {
1755 ERR("Relay error reading index file");
1756 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_ERR);
1757 goto send_reply;
1758 } else {
1759 viewer_index.status = htobe32(LTTNG_VIEWER_INDEX_OK);
1760 vstream->index_sent_seqcount++;
1761 }
1762
1763 /*
1764 * Indexes are stored in big endian, no need to switch before sending.
1765 */
1766 DBG("Sending viewer index for stream %" PRIu64 " offset %" PRIu64,
1767 rstream->stream_handle,
1768 (uint64_t) be64toh(packet_index.offset));
1769 viewer_index.offset = packet_index.offset;
1770 viewer_index.packet_size = packet_index.packet_size;
1771 viewer_index.content_size = packet_index.content_size;
1772 viewer_index.timestamp_begin = packet_index.timestamp_begin;
1773 viewer_index.timestamp_end = packet_index.timestamp_end;
1774 viewer_index.events_discarded = packet_index.events_discarded;
1775 viewer_index.stream_id = packet_index.stream_id;
1776
1777 send_reply:
1778 if (rstream) {
1779 pthread_mutex_unlock(&rstream->lock);
1780 }
1781
1782 if (metadata_viewer_stream) {
1783 pthread_mutex_lock(&metadata_viewer_stream->stream->lock);
1784 DBG("get next index metadata check: recv %" PRIu64
1785 " sent %" PRIu64,
1786 metadata_viewer_stream->stream->metadata_received,
1787 metadata_viewer_stream->metadata_sent);
1788 if (!metadata_viewer_stream->stream->metadata_received ||
1789 metadata_viewer_stream->stream->metadata_received >
1790 metadata_viewer_stream->metadata_sent) {
1791 viewer_index.flags |= LTTNG_VIEWER_FLAG_NEW_METADATA;
1792 }
1793 pthread_mutex_unlock(&metadata_viewer_stream->stream->lock);
1794 }
1795
1796 viewer_index.flags = htobe32(viewer_index.flags);
1797 health_code_update();
1798
1799 ret = send_response(conn->sock, &viewer_index, sizeof(viewer_index));
1800 if (ret < 0) {
1801 goto end;
1802 }
1803 health_code_update();
1804
1805 if (vstream) {
1806 DBG("Index %" PRIu64 " for stream %" PRIu64 " sent",
1807 vstream->index_sent_seqcount,
1808 vstream->stream->stream_handle);
1809 }
1810 end:
1811 if (metadata_viewer_stream) {
1812 viewer_stream_put(metadata_viewer_stream);
1813 }
1814 if (vstream) {
1815 viewer_stream_put(vstream);
1816 }
1817 return ret;
1818
1819 error_put:
1820 pthread_mutex_unlock(&rstream->lock);
1821 if (metadata_viewer_stream) {
1822 viewer_stream_put(metadata_viewer_stream);
1823 }
1824 viewer_stream_put(vstream);
1825 return ret;
1826 }
1827
1828 /*
1829 * Send the next index for a stream
1830 *
1831 * Return 0 on success or else a negative value.
1832 */
1833 static
1834 int viewer_get_packet(struct relay_connection *conn)
1835 {
1836 int ret;
1837 off_t lseek_ret;
1838 char *reply = NULL;
1839 struct lttng_viewer_get_packet get_packet_info;
1840 struct lttng_viewer_trace_packet reply_header;
1841 struct relay_viewer_stream *vstream = NULL;
1842 uint32_t reply_size = sizeof(reply_header);
1843 uint32_t packet_data_len = 0;
1844 ssize_t read_len;
1845 uint64_t stream_id;
1846
1847 DBG2("Relay get data packet");
1848
1849 health_code_update();
1850
1851 ret = recv_request(conn->sock, &get_packet_info,
1852 sizeof(get_packet_info));
1853 if (ret < 0) {
1854 goto end;
1855 }
1856 health_code_update();
1857
1858 /* From this point on, the error label can be reached. */
1859 memset(&reply_header, 0, sizeof(reply_header));
1860 stream_id = (uint64_t) be64toh(get_packet_info.stream_id);
1861
1862 vstream = viewer_stream_get_by_id(stream_id);
1863 if (!vstream) {
1864 DBG("Client requested packet of unknown stream id %" PRIu64,
1865 stream_id);
1866 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1867 goto send_reply_nolock;
1868 } else {
1869 packet_data_len = be32toh(get_packet_info.len);
1870 reply_size += packet_data_len;
1871 }
1872
1873 reply = (char *) zmalloc(reply_size);
1874 if (!reply) {
1875 PERROR("packet reply zmalloc");
1876 reply_size = sizeof(reply_header);
1877 goto error;
1878 }
1879
1880 pthread_mutex_lock(&vstream->stream->lock);
1881 lseek_ret = fs_handle_seek(vstream->stream_file.handle,
1882 be64toh(get_packet_info.offset), SEEK_SET);
1883 if (lseek_ret < 0) {
1884 PERROR("Failed to seek file system handle of viewer stream %" PRIu64
1885 " to offset %" PRIu64,
1886 stream_id,
1887 (uint64_t) be64toh(get_packet_info.offset));
1888 goto error;
1889 }
1890 read_len = fs_handle_read(vstream->stream_file.handle,
1891 reply + sizeof(reply_header), packet_data_len);
1892 if (read_len < packet_data_len) {
1893 PERROR("Failed to read from file system handle of viewer stream id %" PRIu64
1894 ", offset: %" PRIu64,
1895 stream_id,
1896 (uint64_t) be64toh(get_packet_info.offset));
1897 goto error;
1898 }
1899 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_OK);
1900 reply_header.len = htobe32(packet_data_len);
1901 goto send_reply;
1902
1903 error:
1904 /* No payload to send on error. */
1905 reply_size = sizeof(reply_header);
1906 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1907
1908 send_reply:
1909 if (vstream) {
1910 pthread_mutex_unlock(&vstream->stream->lock);
1911 }
1912 send_reply_nolock:
1913
1914 health_code_update();
1915
1916 if (reply) {
1917 memcpy(reply, &reply_header, sizeof(reply_header));
1918 ret = send_response(conn->sock, reply, reply_size);
1919 } else {
1920 /* No reply to send. */
1921 ret = send_response(conn->sock, &reply_header,
1922 reply_size);
1923 }
1924
1925 health_code_update();
1926 if (ret < 0) {
1927 PERROR("sendmsg of packet data failed");
1928 goto end_free;
1929 }
1930
1931 DBG("Sent %u bytes for stream %" PRIu64, reply_size, stream_id);
1932
1933 end_free:
1934 free(reply);
1935 end:
1936 if (vstream) {
1937 viewer_stream_put(vstream);
1938 }
1939 return ret;
1940 }
1941
1942 /*
1943 * Send the session's metadata
1944 *
1945 * Return 0 on success else a negative value.
1946 */
1947 static
1948 int viewer_get_metadata(struct relay_connection *conn)
1949 {
1950 int ret = 0;
1951 int fd = -1;
1952 ssize_t read_len;
1953 uint64_t len = 0;
1954 char *data = NULL;
1955 struct lttng_viewer_get_metadata request;
1956 struct lttng_viewer_metadata_packet reply;
1957 struct relay_viewer_stream *vstream = NULL;
1958
1959 LTTNG_ASSERT(conn);
1960
1961 DBG("Relay get metadata");
1962
1963 health_code_update();
1964
1965 ret = recv_request(conn->sock, &request, sizeof(request));
1966 if (ret < 0) {
1967 goto end;
1968 }
1969 health_code_update();
1970
1971 memset(&reply, 0, sizeof(reply));
1972
1973 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
1974 if (!vstream) {
1975 /*
1976 * The metadata stream can be closed by a CLOSE command
1977 * just before we attach. It can also be closed by
1978 * per-pid tracing during tracing. Therefore, it is
1979 * possible that we cannot find this viewer stream.
1980 * Reply back to the client with an error if we cannot
1981 * find it.
1982 */
1983 DBG("Client requested metadata of unknown stream id %" PRIu64,
1984 (uint64_t) be64toh(request.stream_id));
1985 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1986 goto send_reply;
1987 }
1988 pthread_mutex_lock(&vstream->stream->lock);
1989 if (!vstream->stream->is_metadata) {
1990 ERR("Invalid metadata stream");
1991 goto error;
1992 }
1993
1994 if (vstream->metadata_sent >= vstream->stream->metadata_received) {
1995 /*
1996 * The live viewers expect to receive a NO_NEW_METADATA
1997 * status before a stream disappears, otherwise they abort the
1998 * entire live connection when receiving an error status.
1999 *
2000 * Clear feature resets the metadata_sent to 0 until the
2001 * same metadata is received again.
2002 */
2003 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2004 /*
2005 * The live viewer considers a closed 0 byte metadata stream as
2006 * an error.
2007 */
2008 if (vstream->metadata_sent > 0) {
2009 vstream->stream->no_new_metadata_notified = true;
2010 if (vstream->stream->closed) {
2011 /* Release ownership for the viewer metadata stream. */
2012 viewer_stream_put(vstream);
2013 }
2014 }
2015 goto send_reply;
2016 }
2017
2018 if (vstream->stream->trace_chunk &&
2019 !lttng_trace_chunk_ids_equal(
2020 conn->viewer_session->current_trace_chunk,
2021 vstream->stream->trace_chunk)) {
2022 /* A rotation has occurred on the relay stream. */
2023 DBG("Metadata relay stream and viewer chunk ids differ");
2024
2025 ret = viewer_session_set_trace_chunk_copy(
2026 conn->viewer_session,
2027 vstream->stream->trace_chunk);
2028 if (ret) {
2029 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2030 goto send_reply;
2031 }
2032 }
2033
2034 if (conn->viewer_session->current_trace_chunk &&
2035 conn->viewer_session->current_trace_chunk !=
2036 vstream->stream_file.trace_chunk) {
2037 bool acquired_reference;
2038
2039 DBG("Viewer session and viewer stream chunk differ: "
2040 "vsession chunk %p vstream chunk %p",
2041 conn->viewer_session->current_trace_chunk,
2042 vstream->stream_file.trace_chunk);
2043 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
2044 acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
2045 LTTNG_ASSERT(acquired_reference);
2046 vstream->stream_file.trace_chunk =
2047 conn->viewer_session->current_trace_chunk;
2048 viewer_stream_close_files(vstream);
2049 }
2050
2051 len = vstream->stream->metadata_received - vstream->metadata_sent;
2052
2053 if (!vstream->stream_file.trace_chunk) {
2054 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2055 len = 0;
2056 goto send_reply;
2057 } else if (vstream->stream_file.trace_chunk &&
2058 !vstream->stream_file.handle && len > 0) {
2059 /*
2060 * Either this is the first time the metadata file is read, or a
2061 * rotation of the corresponding relay stream has occurred.
2062 */
2063 struct fs_handle *fs_handle;
2064 char file_path[LTTNG_PATH_MAX];
2065 enum lttng_trace_chunk_status status;
2066 struct relay_stream *rstream = vstream->stream;
2067
2068 ret = utils_stream_file_path(rstream->path_name,
2069 rstream->channel_name, rstream->tracefile_size,
2070 vstream->current_tracefile_id, NULL, file_path,
2071 sizeof(file_path));
2072 if (ret < 0) {
2073 goto error;
2074 }
2075
2076 /*
2077 * It is possible the the metadata file we are trying to open is
2078 * missing if the stream has been closed (application exits with
2079 * per-pid buffers) and a clear command has been performed.
2080 */
2081 status = lttng_trace_chunk_open_fs_handle(
2082 vstream->stream_file.trace_chunk,
2083 file_path, O_RDONLY, 0, &fs_handle, true);
2084 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2085 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
2086 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2087 len = 0;
2088 if (vstream->stream->closed) {
2089 viewer_stream_put(vstream);
2090 }
2091 goto send_reply;
2092 }
2093 PERROR("Failed to open metadata file for viewer stream");
2094 goto error;
2095 }
2096 vstream->stream_file.handle = fs_handle;
2097
2098 if (vstream->metadata_sent != 0) {
2099 /*
2100 * The client does not expect to receive any metadata
2101 * it has received and metadata files in successive
2102 * chunks must be a strict superset of one another.
2103 *
2104 * Skip the first `metadata_sent` bytes to ensure
2105 * they are not sent a second time to the client.
2106 *
2107 * Baring a block layer error or an internal error,
2108 * this seek should not fail as
2109 * `vstream->stream->metadata_received` is reset when
2110 * a relay stream is rotated. If this is reached, it is
2111 * safe to assume that
2112 * `metadata_received` > `metadata_sent`.
2113 */
2114 const off_t seek_ret = fs_handle_seek(fs_handle,
2115 vstream->metadata_sent, SEEK_SET);
2116
2117 if (seek_ret < 0) {
2118 PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64,
2119 vstream->metadata_sent);
2120 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2121 goto send_reply;
2122 }
2123 }
2124 }
2125
2126 reply.len = htobe64(len);
2127 data = (char *) zmalloc(len);
2128 if (!data) {
2129 PERROR("viewer metadata zmalloc");
2130 goto error;
2131 }
2132
2133 fd = fs_handle_get_fd(vstream->stream_file.handle);
2134 if (fd < 0) {
2135 ERR("Failed to restore viewer stream file system handle");
2136 goto error;
2137 }
2138 read_len = lttng_read(fd, data, len);
2139 fs_handle_put_fd(vstream->stream_file.handle);
2140 fd = -1;
2141 if (read_len < len) {
2142 if (read_len < 0) {
2143 PERROR("Failed to read metadata file");
2144 goto error;
2145 } else {
2146 /*
2147 * A clear has been performed which prevents the relay
2148 * from sending `len` bytes of metadata.
2149 *
2150 * It is important not to send any metadata if we
2151 * couldn't read all the available metadata in one shot:
2152 * sending partial metadata can cause the client to
2153 * attempt to parse an incomplete (incoherent) metadata
2154 * stream, which would result in an error.
2155 */
2156 const off_t seek_ret = fs_handle_seek(
2157 vstream->stream_file.handle, -read_len,
2158 SEEK_CUR);
2159
2160 DBG("Failed to read metadata: requested = %" PRIu64 ", got = %zd",
2161 len, read_len);
2162 read_len = 0;
2163 len = 0;
2164 if (seek_ret < 0) {
2165 PERROR("Failed to restore metadata file position after partial read");
2166 ret = -1;
2167 goto error;
2168 }
2169 }
2170 }
2171 vstream->metadata_sent += read_len;
2172 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
2173
2174 goto send_reply;
2175
2176 error:
2177 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2178
2179 send_reply:
2180 health_code_update();
2181 if (vstream) {
2182 pthread_mutex_unlock(&vstream->stream->lock);
2183 }
2184 ret = send_response(conn->sock, &reply, sizeof(reply));
2185 if (ret < 0) {
2186 goto end_free;
2187 }
2188 health_code_update();
2189
2190 if (len > 0) {
2191 ret = send_response(conn->sock, data, len);
2192 if (ret < 0) {
2193 goto end_free;
2194 }
2195 }
2196
2197 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
2198 (uint64_t) be64toh(request.stream_id));
2199
2200 DBG("Metadata sent");
2201
2202 end_free:
2203 free(data);
2204 end:
2205 if (vstream) {
2206 viewer_stream_put(vstream);
2207 }
2208 return ret;
2209 }
2210
2211 /*
2212 * Create a viewer session.
2213 *
2214 * Return 0 on success or else a negative value.
2215 */
2216 static
2217 int viewer_create_session(struct relay_connection *conn)
2218 {
2219 int ret;
2220 struct lttng_viewer_create_session_response resp;
2221
2222 DBG("Viewer create session received");
2223
2224 memset(&resp, 0, sizeof(resp));
2225 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
2226 conn->viewer_session = viewer_session_create();
2227 if (!conn->viewer_session) {
2228 ERR("Allocation viewer session");
2229 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
2230 goto send_reply;
2231 }
2232
2233 send_reply:
2234 health_code_update();
2235 ret = send_response(conn->sock, &resp, sizeof(resp));
2236 if (ret < 0) {
2237 goto end;
2238 }
2239 health_code_update();
2240 ret = 0;
2241
2242 end:
2243 return ret;
2244 }
2245
2246 /*
2247 * Detach a viewer session.
2248 *
2249 * Return 0 on success or else a negative value.
2250 */
2251 static
2252 int viewer_detach_session(struct relay_connection *conn)
2253 {
2254 int ret;
2255 struct lttng_viewer_detach_session_response response;
2256 struct lttng_viewer_detach_session_request request;
2257 struct relay_session *session = NULL;
2258 uint64_t viewer_session_to_close;
2259
2260 DBG("Viewer detach session received");
2261
2262 LTTNG_ASSERT(conn);
2263
2264 health_code_update();
2265
2266 /* Receive the request from the connected client. */
2267 ret = recv_request(conn->sock, &request, sizeof(request));
2268 if (ret < 0) {
2269 goto end;
2270 }
2271 viewer_session_to_close = be64toh(request.session_id);
2272
2273 if (!conn->viewer_session) {
2274 DBG("Client trying to detach before creating a live viewer session");
2275 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2276 goto send_reply;
2277 }
2278
2279 health_code_update();
2280
2281 memset(&response, 0, sizeof(response));
2282 DBG("Detaching from session ID %" PRIu64, viewer_session_to_close);
2283
2284 session = session_get_by_id(be64toh(request.session_id));
2285 if (!session) {
2286 DBG("Relay session %" PRIu64 " not found",
2287 (uint64_t) be64toh(request.session_id));
2288 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
2289 goto send_reply;
2290 }
2291
2292 ret = viewer_session_is_attached(conn->viewer_session, session);
2293 if (ret != 1) {
2294 DBG("Not attached to this session");
2295 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2296 goto send_reply_put;
2297 }
2298
2299 viewer_session_close_one_session(conn->viewer_session, session);
2300 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_OK);
2301 DBG("Session %" PRIu64 " detached.", viewer_session_to_close);
2302
2303 send_reply_put:
2304 session_put(session);
2305
2306 send_reply:
2307 health_code_update();
2308 ret = send_response(conn->sock, &response, sizeof(response));
2309 if (ret < 0) {
2310 goto end;
2311 }
2312 health_code_update();
2313 ret = 0;
2314
2315 end:
2316 return ret;
2317 }
2318
2319 /*
2320 * live_relay_unknown_command: send -1 if received unknown command
2321 */
2322 static
2323 void live_relay_unknown_command(struct relay_connection *conn)
2324 {
2325 struct lttcomm_relayd_generic_reply reply;
2326
2327 memset(&reply, 0, sizeof(reply));
2328 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2329 (void) send_response(conn->sock, &reply, sizeof(reply));
2330 }
2331
2332 /*
2333 * Process the commands received on the control socket
2334 */
2335 static
2336 int process_control(struct lttng_viewer_cmd *recv_hdr,
2337 struct relay_connection *conn)
2338 {
2339 int ret = 0;
2340 uint32_t msg_value;
2341
2342 msg_value = be32toh(recv_hdr->cmd);
2343
2344 /*
2345 * Make sure we've done the version check before any command other then a
2346 * new client connection.
2347 */
2348 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
2349 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
2350 ret = -1;
2351 goto end;
2352 }
2353
2354 switch (msg_value) {
2355 case LTTNG_VIEWER_CONNECT:
2356 ret = viewer_connect(conn);
2357 break;
2358 case LTTNG_VIEWER_LIST_SESSIONS:
2359 ret = viewer_list_sessions(conn);
2360 break;
2361 case LTTNG_VIEWER_ATTACH_SESSION:
2362 ret = viewer_attach_session(conn);
2363 break;
2364 case LTTNG_VIEWER_GET_NEXT_INDEX:
2365 ret = viewer_get_next_index(conn);
2366 break;
2367 case LTTNG_VIEWER_GET_PACKET:
2368 ret = viewer_get_packet(conn);
2369 break;
2370 case LTTNG_VIEWER_GET_METADATA:
2371 ret = viewer_get_metadata(conn);
2372 break;
2373 case LTTNG_VIEWER_GET_NEW_STREAMS:
2374 ret = viewer_get_new_streams(conn);
2375 break;
2376 case LTTNG_VIEWER_CREATE_SESSION:
2377 ret = viewer_create_session(conn);
2378 break;
2379 case LTTNG_VIEWER_DETACH_SESSION:
2380 ret = viewer_detach_session(conn);
2381 break;
2382 default:
2383 ERR("Received unknown viewer command (%u)",
2384 be32toh(recv_hdr->cmd));
2385 live_relay_unknown_command(conn);
2386 ret = -1;
2387 goto end;
2388 }
2389
2390 end:
2391 return ret;
2392 }
2393
2394 static
2395 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2396 {
2397 int ret;
2398
2399 (void) lttng_poll_del(events, pollfd);
2400
2401 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
2402 fd_tracker_util_close_fd, NULL);
2403 if (ret < 0) {
2404 ERR("Closing pollfd %d", pollfd);
2405 }
2406 }
2407
2408 /*
2409 * This thread does the actual work
2410 */
2411 static
2412 void *thread_worker(void *data)
2413 {
2414 int ret, err = -1;
2415 uint32_t nb_fd;
2416 struct lttng_poll_event events;
2417 struct lttng_ht *viewer_connections_ht;
2418 struct lttng_ht_iter iter;
2419 struct lttng_viewer_cmd recv_hdr;
2420 struct relay_connection *destroy_conn;
2421
2422 DBG("[thread] Live viewer relay worker started");
2423
2424 rcu_register_thread();
2425
2426 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
2427
2428 if (testpoint(relayd_thread_live_worker)) {
2429 goto error_testpoint;
2430 }
2431
2432 /* table of connections indexed on socket */
2433 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2434 if (!viewer_connections_ht) {
2435 goto viewer_connections_ht_error;
2436 }
2437
2438 ret = create_named_thread_poll_set(&events, 2,
2439 "Live viewer worker thread epoll");
2440 if (ret < 0) {
2441 goto error_poll_create;
2442 }
2443
2444 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2445 if (ret < 0) {
2446 goto error;
2447 }
2448
2449 restart:
2450 while (1) {
2451 int i;
2452
2453 health_code_update();
2454
2455 /* Infinite blocking call, waiting for transmission */
2456 DBG3("Relayd live viewer worker thread polling...");
2457 health_poll_entry();
2458 ret = lttng_poll_wait(&events, -1);
2459 health_poll_exit();
2460 if (ret < 0) {
2461 /*
2462 * Restart interrupted system call.
2463 */
2464 if (errno == EINTR) {
2465 goto restart;
2466 }
2467 goto error;
2468 }
2469
2470 nb_fd = ret;
2471
2472 /*
2473 * Process control. The control connection is prioritised so we don't
2474 * starve it with high throughput tracing data on the data
2475 * connection.
2476 */
2477 for (i = 0; i < nb_fd; i++) {
2478 /* Fetch once the poll data */
2479 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2480 int pollfd = LTTNG_POLL_GETFD(&events, i);
2481
2482 health_code_update();
2483
2484 /* Thread quit pipe has been closed. Killing thread. */
2485 ret = check_thread_quit_pipe(pollfd, revents);
2486 if (ret) {
2487 err = 0;
2488 goto exit;
2489 }
2490
2491 /* Inspect the relay conn pipe for new connection. */
2492 if (pollfd == live_conn_pipe[0]) {
2493 if (revents & LPOLLIN) {
2494 struct relay_connection *conn;
2495
2496 ret = lttng_read(live_conn_pipe[0],
2497 &conn, sizeof(conn));
2498 if (ret < 0) {
2499 goto error;
2500 }
2501 ret = lttng_poll_add(&events,
2502 conn->sock->fd,
2503 LPOLLIN | LPOLLRDHUP);
2504 if (ret) {
2505 ERR("Failed to add new live connection file descriptor to poll set");
2506 goto error;
2507 }
2508 connection_ht_add(viewer_connections_ht, conn);
2509 DBG("Connection socket %d added to poll", conn->sock->fd);
2510 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2511 ERR("Relay live pipe error");
2512 goto error;
2513 } else {
2514 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2515 goto error;
2516 }
2517 } else {
2518 /* Connection activity. */
2519 struct relay_connection *conn;
2520
2521 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
2522 if (!conn) {
2523 continue;
2524 }
2525
2526 if (revents & LPOLLIN) {
2527 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2528 sizeof(recv_hdr), 0);
2529 if (ret <= 0) {
2530 /* Connection closed. */
2531 cleanup_connection_pollfd(&events, pollfd);
2532 /* Put "create" ownership reference. */
2533 connection_put(conn);
2534 DBG("Viewer control conn closed with %d", pollfd);
2535 } else {
2536 ret = process_control(&recv_hdr, conn);
2537 if (ret < 0) {
2538 /* Clear the session on error. */
2539 cleanup_connection_pollfd(&events, pollfd);
2540 /* Put "create" ownership reference. */
2541 connection_put(conn);
2542 DBG("Viewer connection closed with %d", pollfd);
2543 }
2544 }
2545 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2546 cleanup_connection_pollfd(&events, pollfd);
2547 /* Put "create" ownership reference. */
2548 connection_put(conn);
2549 } else {
2550 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2551 connection_put(conn);
2552 goto error;
2553 }
2554 /* Put local "get_by_sock" reference. */
2555 connection_put(conn);
2556 }
2557 }
2558 }
2559
2560 exit:
2561 error:
2562 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
2563
2564 /* Cleanup remaining connection object. */
2565 rcu_read_lock();
2566 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
2567 destroy_conn,
2568 sock_n.node) {
2569 health_code_update();
2570 connection_put(destroy_conn);
2571 }
2572 rcu_read_unlock();
2573 error_poll_create:
2574 lttng_ht_destroy(viewer_connections_ht);
2575 viewer_connections_ht_error:
2576 /* Close relay conn pipes */
2577 (void) fd_tracker_util_pipe_close(the_fd_tracker, live_conn_pipe);
2578 if (err) {
2579 DBG("Viewer worker thread exited with error");
2580 }
2581 DBG("Viewer worker thread cleanup complete");
2582 error_testpoint:
2583 if (err) {
2584 health_error();
2585 ERR("Health error occurred in %s", __func__);
2586 }
2587 health_unregister(health_relayd);
2588 if (lttng_relay_stop_threads()) {
2589 ERR("Error stopping threads");
2590 }
2591 rcu_unregister_thread();
2592 return NULL;
2593 }
2594
2595 /*
2596 * Create the relay command pipe to wake thread_manage_apps.
2597 * Closed in cleanup().
2598 */
2599 static int create_conn_pipe(void)
2600 {
2601 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
2602 "Live connection pipe", live_conn_pipe);
2603 }
2604
2605 int relayd_live_join(void)
2606 {
2607 int ret, retval = 0;
2608 void *status;
2609
2610 ret = pthread_join(live_listener_thread, &status);
2611 if (ret) {
2612 errno = ret;
2613 PERROR("pthread_join live listener");
2614 retval = -1;
2615 }
2616
2617 ret = pthread_join(live_worker_thread, &status);
2618 if (ret) {
2619 errno = ret;
2620 PERROR("pthread_join live worker");
2621 retval = -1;
2622 }
2623
2624 ret = pthread_join(live_dispatcher_thread, &status);
2625 if (ret) {
2626 errno = ret;
2627 PERROR("pthread_join live dispatcher");
2628 retval = -1;
2629 }
2630
2631 cleanup_relayd_live();
2632
2633 return retval;
2634 }
2635
2636 /*
2637 * main
2638 */
2639 int relayd_live_create(struct lttng_uri *uri)
2640 {
2641 int ret = 0, retval = 0;
2642 void *status;
2643 int is_root;
2644
2645 if (!uri) {
2646 retval = -1;
2647 goto exit_init_data;
2648 }
2649 live_uri = uri;
2650
2651 /* Check if daemon is UID = 0 */
2652 is_root = !getuid();
2653
2654 if (!is_root) {
2655 if (live_uri->port < 1024) {
2656 ERR("Need to be root to use ports < 1024");
2657 retval = -1;
2658 goto exit_init_data;
2659 }
2660 }
2661
2662 /* Setup the thread apps communication pipe. */
2663 if (create_conn_pipe()) {
2664 retval = -1;
2665 goto exit_init_data;
2666 }
2667
2668 /* Init relay command queue. */
2669 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2670
2671 /* Set up max poll set size */
2672 if (lttng_poll_set_max_size()) {
2673 retval = -1;
2674 goto exit_init_data;
2675 }
2676
2677 /* Setup the dispatcher thread */
2678 ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
2679 thread_dispatcher, (void *) NULL);
2680 if (ret) {
2681 errno = ret;
2682 PERROR("pthread_create viewer dispatcher");
2683 retval = -1;
2684 goto exit_dispatcher_thread;
2685 }
2686
2687 /* Setup the worker thread */
2688 ret = pthread_create(&live_worker_thread, default_pthread_attr(),
2689 thread_worker, NULL);
2690 if (ret) {
2691 errno = ret;
2692 PERROR("pthread_create viewer worker");
2693 retval = -1;
2694 goto exit_worker_thread;
2695 }
2696
2697 /* Setup the listener thread */
2698 ret = pthread_create(&live_listener_thread, default_pthread_attr(),
2699 thread_listener, (void *) NULL);
2700 if (ret) {
2701 errno = ret;
2702 PERROR("pthread_create viewer listener");
2703 retval = -1;
2704 goto exit_listener_thread;
2705 }
2706
2707 /*
2708 * All OK, started all threads.
2709 */
2710 return retval;
2711
2712 /*
2713 * Join on the live_listener_thread should anything be added after
2714 * the live_listener thread's creation.
2715 */
2716
2717 exit_listener_thread:
2718
2719 ret = pthread_join(live_worker_thread, &status);
2720 if (ret) {
2721 errno = ret;
2722 PERROR("pthread_join live worker");
2723 retval = -1;
2724 }
2725 exit_worker_thread:
2726
2727 ret = pthread_join(live_dispatcher_thread, &status);
2728 if (ret) {
2729 errno = ret;
2730 PERROR("pthread_join live dispatcher");
2731 retval = -1;
2732 }
2733 exit_dispatcher_thread:
2734
2735 exit_init_data:
2736 cleanup_relayd_live();
2737
2738 return retval;
2739 }
This page took 0.123223 seconds and 4 git commands to generate.