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