7d6dc1bc20a03a5af6cafe1e5ef170be1b7f5cb8
[lttng-tools.git] / src / bin / lttng-relayd / live.c
1 /*
2 * Copyright (C) 2013 Julien Desfossez <jdesfossez@efficios.com>
3 * Copyright (C) 2013 David Goulet <dgoulet@efficios.com>
4 * Copyright (C) 2015 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 *
6 * SPDX-License-Identifier: GPL-2.0-only
7 *
8 */
9
10 #define _LGPL_SOURCE
11 #include <fcntl.h>
12 #include <getopt.h>
13 #include <grp.h>
14 #include <inttypes.h>
15 #include <limits.h>
16 #include <pthread.h>
17 #include <signal.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/mman.h>
22 #include <sys/mount.h>
23 #include <sys/resource.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 #include <urcu/futex.h>
30 #include <urcu/rculist.h>
31 #include <urcu/uatomic.h>
32
33 #include <common/common.h>
34 #include <common/compat/endian.h>
35 #include <common/compat/poll.h>
36 #include <common/compat/socket.h>
37 #include <common/defaults.h>
38 #include <common/fd-tracker/utils.h>
39 #include <common/fs-handle.h>
40 #include <common/futex.h>
41 #include <common/index/index.h>
42 #include <common/sessiond-comm/inet.h>
43 #include <common/sessiond-comm/relayd.h>
44 #include <common/sessiond-comm/sessiond-comm.h>
45 #include <common/uri.h>
46 #include <common/utils.h>
47 #include <lttng/lttng.h>
48
49 #include "cmd.h"
50 #include "connection.h"
51 #include "ctf-trace.h"
52 #include "health-relayd.h"
53 #include "live.h"
54 #include "lttng-relayd.h"
55 #include "session.h"
56 #include "stream.h"
57 #include "testpoint.h"
58 #include "utils.h"
59 #include "viewer-session.h"
60 #include "viewer-stream.h"
61
62 #define SESSION_BUF_DEFAULT_COUNT 16
63
64 static struct lttng_uri *live_uri;
65
66 /*
67 * This pipe is used to inform the worker thread that a command is queued and
68 * ready to be processed.
69 */
70 static int live_conn_pipe[2] = { -1, -1 };
71
72 /* Shared between threads */
73 static int live_dispatch_thread_exit;
74
75 static pthread_t live_listener_thread;
76 static pthread_t live_dispatcher_thread;
77 static pthread_t live_worker_thread;
78
79 /*
80 * Relay command queue.
81 *
82 * The live_thread_listener and live_thread_dispatcher communicate with this
83 * queue.
84 */
85 static struct relay_conn_queue viewer_conn_queue;
86
87 static uint64_t last_relay_viewer_session_id;
88 static pthread_mutex_t last_relay_viewer_session_id_lock =
89 PTHREAD_MUTEX_INITIALIZER;
90
91 /*
92 * Cleanup the daemon
93 */
94 static
95 void cleanup_relayd_live(void)
96 {
97 DBG("Cleaning up");
98
99 free(live_uri);
100 }
101
102 /*
103 * Receive a request buffer using a given socket, destination allocated buffer
104 * of length size.
105 *
106 * Return the size of the received message or else a negative value on error
107 * with errno being set by recvmsg() syscall.
108 */
109 static
110 ssize_t recv_request(struct lttcomm_sock *sock, void *buf, size_t size)
111 {
112 ssize_t ret;
113
114 ret = sock->ops->recvmsg(sock, buf, size, 0);
115 if (ret < 0 || ret != size) {
116 if (ret == 0) {
117 /* Orderly shutdown. Not necessary to print an error. */
118 DBG("Socket %d did an orderly shutdown", sock->fd);
119 } else {
120 ERR("Relay failed to receive request.");
121 }
122 ret = -1;
123 }
124
125 return ret;
126 }
127
128 /*
129 * Send a response buffer using a given socket, source allocated buffer of
130 * length size.
131 *
132 * Return the size of the sent message or else a negative value on error with
133 * errno being set by sendmsg() syscall.
134 */
135 static
136 ssize_t send_response(struct lttcomm_sock *sock, void *buf, size_t size)
137 {
138 ssize_t ret;
139
140 ret = sock->ops->sendmsg(sock, buf, size, 0);
141 if (ret < 0) {
142 ERR("Relayd failed to send response.");
143 }
144
145 return ret;
146 }
147
148 /*
149 * Atomically check if new streams got added in one of the sessions attached
150 * and reset the flag to 0.
151 *
152 * Returns 1 if new streams got added, 0 if nothing changed, a negative value
153 * on error.
154 */
155 static
156 int check_new_streams(struct relay_connection *conn)
157 {
158 struct relay_session *session;
159 unsigned long current_val;
160 int ret = 0;
161
162 if (!conn->viewer_session) {
163 goto end;
164 }
165 rcu_read_lock();
166 cds_list_for_each_entry_rcu(session,
167 &conn->viewer_session->session_list,
168 viewer_session_node) {
169 if (!session_get(session)) {
170 continue;
171 }
172 current_val = uatomic_cmpxchg(&session->new_streams, 1, 0);
173 ret = current_val;
174 session_put(session);
175 if (ret == 1) {
176 goto end;
177 }
178 }
179 end:
180 rcu_read_unlock();
181 return ret;
182 }
183
184 /*
185 * Send viewer streams to the given socket. The ignore_sent_flag indicates if
186 * this function should ignore the sent flag or not.
187 *
188 * Return 0 on success or else a negative value.
189 */
190 static
191 ssize_t send_viewer_streams(struct lttcomm_sock *sock,
192 uint64_t session_id, unsigned int ignore_sent_flag)
193 {
194 ssize_t ret;
195 struct lttng_ht_iter iter;
196 struct relay_viewer_stream *vstream;
197
198 rcu_read_lock();
199
200 cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
201 stream_n.node) {
202 struct ctf_trace *ctf_trace;
203 struct lttng_viewer_stream send_stream = {};
204
205 health_code_update();
206
207 if (!viewer_stream_get(vstream)) {
208 continue;
209 }
210
211 pthread_mutex_lock(&vstream->stream->lock);
212 /* Ignore if not the same session. */
213 if (vstream->stream->trace->session->id != session_id ||
214 (!ignore_sent_flag && vstream->sent_flag)) {
215 pthread_mutex_unlock(&vstream->stream->lock);
216 viewer_stream_put(vstream);
217 continue;
218 }
219
220 ctf_trace = vstream->stream->trace;
221 send_stream.id = htobe64(vstream->stream->stream_handle);
222 send_stream.ctf_trace_id = htobe64(ctf_trace->id);
223 send_stream.metadata_flag = htobe32(
224 vstream->stream->is_metadata);
225 if (lttng_strncpy(send_stream.path_name, vstream->path_name,
226 sizeof(send_stream.path_name))) {
227 pthread_mutex_unlock(&vstream->stream->lock);
228 viewer_stream_put(vstream);
229 ret = -1; /* Error. */
230 goto end_unlock;
231 }
232 if (lttng_strncpy(send_stream.channel_name,
233 vstream->channel_name,
234 sizeof(send_stream.channel_name))) {
235 pthread_mutex_unlock(&vstream->stream->lock);
236 viewer_stream_put(vstream);
237 ret = -1; /* Error. */
238 goto end_unlock;
239 }
240
241 DBG("Sending stream %" PRIu64 " to viewer",
242 vstream->stream->stream_handle);
243 vstream->sent_flag = 1;
244 pthread_mutex_unlock(&vstream->stream->lock);
245
246 ret = send_response(sock, &send_stream, sizeof(send_stream));
247 viewer_stream_put(vstream);
248 if (ret < 0) {
249 goto end_unlock;
250 }
251 }
252
253 ret = 0;
254
255 end_unlock:
256 rcu_read_unlock();
257 return ret;
258 }
259
260 /*
261 * Create every viewer stream possible for the given session with the seek
262 * type. Three counters *can* be return which are in order the total amount of
263 * viewer stream of the session, the number of unsent stream and the number of
264 * stream created. Those counters can be NULL and thus will be ignored.
265 *
266 * session must be locked to ensure that we see either none or all initial
267 * streams for a session, but no intermediate state..
268 *
269 * Return 0 on success or else a negative value.
270 */
271 static int make_viewer_streams(struct relay_session *relay_session,
272 struct relay_viewer_session *viewer_session,
273 enum lttng_viewer_seek seek_t,
274 uint32_t *nb_total,
275 uint32_t *nb_unsent,
276 uint32_t *nb_created,
277 bool *closed)
278 {
279 int ret;
280 struct lttng_ht_iter iter;
281 struct ctf_trace *ctf_trace;
282 struct relay_stream *relay_stream = NULL;
283
284 assert(relay_session);
285 ASSERT_LOCKED(relay_session->lock);
286
287 if (!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
461 error_unlock:
462 rcu_read_unlock();
463 error:
464 if (relay_stream) {
465 pthread_mutex_unlock(&relay_stream->lock);
466 stream_put(relay_stream);
467 }
468
469 return ret;
470 }
471
472 int 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 */
483 static
484 int 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
509 error:
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 */
518 static
519 int 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
528 static
529 int 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;
540 end:
541 return ret;
542 }
543
544 static
545 int close_sock(void *data, int *in_fd)
546 {
547 struct lttcomm_sock *sock = data;
548
549 return sock->ops->close(sock);
550 }
551
552 static 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;
565 end:
566 return ret;
567 }
568
569 static
570 struct 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);
584 end:
585 return new_sock;
586 }
587
588 /*
589 * Create and init socket from uri.
590 */
591 static
592 struct 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
644 error:
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 */
655 static
656 void *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
699 restart:
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
783 exit:
784 error:
785 error_poll_add:
786 error_testpoint:
787 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
788 error_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);
801 error_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 */
818 static
819 void *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
885 error:
886 error_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 */
904 static
905 int 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
979 end:
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 */
991 static
992 int 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;
1095 end_free:
1096 free(send_session_buf);
1097 return ret;
1098 }
1099
1100 /*
1101 * Send the viewer the list of current streams.
1102 */
1103 static
1104 int 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 }
1168 send_reply_unlock:
1169 pthread_mutex_unlock(&session->lock);
1170
1171 send_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
1198 end_put_session:
1199 if (session) {
1200 session_put(session);
1201 }
1202 error:
1203 return ret;
1204 error_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 */
1213 static
1214 int 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
1317 send_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
1340 end_put_session:
1341 if (session) {
1342 pthread_mutex_unlock(&session->lock);
1343 session_put(session);
1344 }
1345 error:
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 */
1359 static 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
1393 end:
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 */
1408 static 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
1525 hup:
1526 viewer_stream_put(vstream);
1527 index_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 */
1536 static
1537 int 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
1730 send_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 }
1763 end:
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
1772 error_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 */
1786 static
1787 int 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
1856 error:
1857 reply_header.status = htobe32(LTTNG_VIEWER_GET_PACKET_ERR);
1858
1859 send_reply:
1860 if (vstream) {
1861 pthread_mutex_unlock(&vstream->stream->lock);
1862 }
1863 send_reply_nolock:
1864
1865 health_code_update();
1866
1867 if (reply) {
1868 memcpy(reply, &reply_header, sizeof(reply_header));
1869 ret = send_response(conn->sock, reply, reply_size);
1870 } else {
1871 /* No reply to send. */
1872 ret = send_response(conn->sock, &reply_header,
1873 reply_size);
1874 }
1875
1876 health_code_update();
1877 if (ret < 0) {
1878 PERROR("sendmsg of packet data failed");
1879 goto end_free;
1880 }
1881
1882 DBG("Sent %u bytes for stream %" PRIu64, reply_size, stream_id);
1883
1884 end_free:
1885 free(reply);
1886 end:
1887 if (vstream) {
1888 viewer_stream_put(vstream);
1889 }
1890 return ret;
1891 }
1892
1893 /*
1894 * Send the session's metadata
1895 *
1896 * Return 0 on success else a negative value.
1897 */
1898 static
1899 int viewer_get_metadata(struct relay_connection *conn)
1900 {
1901 int ret = 0;
1902 int fd = -1;
1903 ssize_t read_len;
1904 uint64_t len = 0;
1905 char *data = NULL;
1906 struct lttng_viewer_get_metadata request;
1907 struct lttng_viewer_metadata_packet reply;
1908 struct relay_viewer_stream *vstream = NULL;
1909
1910 assert(conn);
1911
1912 DBG("Relay get metadata");
1913
1914 health_code_update();
1915
1916 ret = recv_request(conn->sock, &request, sizeof(request));
1917 if (ret < 0) {
1918 goto end;
1919 }
1920 health_code_update();
1921
1922 memset(&reply, 0, sizeof(reply));
1923
1924 vstream = viewer_stream_get_by_id(be64toh(request.stream_id));
1925 if (!vstream) {
1926 /*
1927 * The metadata stream can be closed by a CLOSE command
1928 * just before we attach. It can also be closed by
1929 * per-pid tracing during tracing. Therefore, it is
1930 * possible that we cannot find this viewer stream.
1931 * Reply back to the client with an error if we cannot
1932 * find it.
1933 */
1934 DBG("Client requested metadata of unknown stream id %" PRIu64,
1935 (uint64_t) be64toh(request.stream_id));
1936 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1937 goto send_reply;
1938 }
1939 pthread_mutex_lock(&vstream->stream->lock);
1940 if (!vstream->stream->is_metadata) {
1941 ERR("Invalid metadata stream");
1942 goto error;
1943 }
1944
1945 if (vstream->metadata_sent >= vstream->stream->metadata_received) {
1946 /*
1947 * The live viewers expect to receive a NO_NEW_METADATA
1948 * status before a stream disappears, otherwise they abort the
1949 * entire live connection when receiving an error status.
1950 *
1951 * Clear feature resets the metadata_sent to 0 until the
1952 * same metadata is received again.
1953 */
1954 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
1955 /*
1956 * The live viewer considers a closed 0 byte metadata stream as
1957 * an error.
1958 */
1959 if (vstream->metadata_sent > 0) {
1960 vstream->stream->no_new_metadata_notified = true;
1961 if (vstream->stream->closed) {
1962 /* Release ownership for the viewer metadata stream. */
1963 viewer_stream_put(vstream);
1964 }
1965 }
1966 goto send_reply;
1967 }
1968
1969 if (vstream->stream->trace_chunk &&
1970 !lttng_trace_chunk_ids_equal(
1971 conn->viewer_session->current_trace_chunk,
1972 vstream->stream->trace_chunk)) {
1973 /* A rotation has occurred on the relay stream. */
1974 DBG("Metadata relay stream and viewer chunk ids differ");
1975
1976 ret = viewer_session_set_trace_chunk_copy(
1977 conn->viewer_session,
1978 vstream->stream->trace_chunk);
1979 if (ret) {
1980 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
1981 goto send_reply;
1982 }
1983 }
1984
1985 if (conn->viewer_session->current_trace_chunk !=
1986 vstream->stream_file.trace_chunk) {
1987 bool acquired_reference;
1988
1989 DBG("Viewer session and viewer stream chunk differ: "
1990 "vsession chunk %p vstream chunk %p",
1991 conn->viewer_session->current_trace_chunk,
1992 vstream->stream_file.trace_chunk);
1993 lttng_trace_chunk_put(vstream->stream_file.trace_chunk);
1994 acquired_reference = lttng_trace_chunk_get(conn->viewer_session->current_trace_chunk);
1995 assert(acquired_reference);
1996 vstream->stream_file.trace_chunk =
1997 conn->viewer_session->current_trace_chunk;
1998 viewer_stream_close_files(vstream);
1999 }
2000
2001 len = vstream->stream->metadata_received - vstream->metadata_sent;
2002
2003 /*
2004 * Either this is the first time the metadata file is read, or a
2005 * rotation of the corresponding relay stream has occured.
2006 */
2007 if (!vstream->stream_file.handle && len > 0) {
2008 struct fs_handle *fs_handle;
2009 char file_path[LTTNG_PATH_MAX];
2010 enum lttng_trace_chunk_status status;
2011 struct relay_stream *rstream = vstream->stream;
2012
2013 ret = utils_stream_file_path(rstream->path_name,
2014 rstream->channel_name, rstream->tracefile_size,
2015 vstream->current_tracefile_id, NULL, file_path,
2016 sizeof(file_path));
2017 if (ret < 0) {
2018 goto error;
2019 }
2020
2021 /*
2022 * It is possible the the metadata file we are trying to open is
2023 * missing if the stream has been closed (application exits with
2024 * per-pid buffers) and a clear command has been performed.
2025 */
2026 status = lttng_trace_chunk_open_fs_handle(
2027 vstream->stream_file.trace_chunk,
2028 file_path, O_RDONLY, 0, &fs_handle, true);
2029 if (status != LTTNG_TRACE_CHUNK_STATUS_OK) {
2030 if (status == LTTNG_TRACE_CHUNK_STATUS_NO_FILE) {
2031 reply.status = htobe32(LTTNG_VIEWER_NO_NEW_METADATA);
2032 len = 0;
2033 if (vstream->stream->closed) {
2034 viewer_stream_put(vstream);
2035 }
2036 goto send_reply;
2037 }
2038 PERROR("Failed to open metadata file for viewer stream");
2039 goto error;
2040 }
2041 vstream->stream_file.handle = fs_handle;
2042
2043 if (vstream->metadata_sent != 0) {
2044 /*
2045 * The client does not expect to receive any metadata
2046 * it has received and metadata files in successive
2047 * chunks must be a strict superset of one another.
2048 *
2049 * Skip the first `metadata_sent` bytes to ensure
2050 * they are not sent a second time to the client.
2051 *
2052 * Baring a block layer error or an internal error,
2053 * this seek should not fail as
2054 * `vstream->stream->metadata_received` is reset when
2055 * a relay stream is rotated. If this is reached, it is
2056 * safe to assume that
2057 * `metadata_received` > `metadata_sent`.
2058 */
2059 const off_t seek_ret = fs_handle_seek(fs_handle,
2060 vstream->metadata_sent, SEEK_SET);
2061
2062 if (seek_ret < 0) {
2063 PERROR("Failed to seek metadata viewer stream file to `sent` position: pos = %" PRId64,
2064 vstream->metadata_sent);
2065 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2066 goto send_reply;
2067 }
2068 }
2069 }
2070
2071 reply.len = htobe64(len);
2072 data = zmalloc(len);
2073 if (!data) {
2074 PERROR("viewer metadata zmalloc");
2075 goto error;
2076 }
2077
2078 fd = fs_handle_get_fd(vstream->stream_file.handle);
2079 if (fd < 0) {
2080 ERR("Failed to restore viewer stream file system handle");
2081 goto error;
2082 }
2083 read_len = lttng_read(fd, data, len);
2084 fs_handle_put_fd(vstream->stream_file.handle);
2085 fd = -1;
2086 if (read_len < len) {
2087 if (read_len < 0) {
2088 PERROR("Failed to read metadata file");
2089 goto error;
2090 } else {
2091 /*
2092 * A clear has been performed which prevents the relay
2093 * from sending `len` bytes of metadata.
2094 *
2095 * It is important not to send any metadata if we
2096 * couldn't read all the available metadata in one shot:
2097 * sending partial metadata can cause the client to
2098 * attempt to parse an incomplete (incoherent) metadata
2099 * stream, which would result in an error.
2100 */
2101 const off_t seek_ret = fs_handle_seek(
2102 vstream->stream_file.handle, -read_len,
2103 SEEK_CUR);
2104
2105 DBG("Failed to read metadata: requested = %" PRIu64 ", got = %zd",
2106 len, read_len);
2107 read_len = 0;
2108 len = 0;
2109 if (seek_ret < 0) {
2110 PERROR("Failed to restore metadata file position after partial read");
2111 ret = -1;
2112 goto error;
2113 }
2114 }
2115 }
2116 vstream->metadata_sent += read_len;
2117 reply.status = htobe32(LTTNG_VIEWER_METADATA_OK);
2118
2119 goto send_reply;
2120
2121 error:
2122 reply.status = htobe32(LTTNG_VIEWER_METADATA_ERR);
2123
2124 send_reply:
2125 health_code_update();
2126 if (vstream) {
2127 pthread_mutex_unlock(&vstream->stream->lock);
2128 }
2129 ret = send_response(conn->sock, &reply, sizeof(reply));
2130 if (ret < 0) {
2131 goto end_free;
2132 }
2133 health_code_update();
2134
2135 if (len > 0) {
2136 ret = send_response(conn->sock, data, len);
2137 if (ret < 0) {
2138 goto end_free;
2139 }
2140 }
2141
2142 DBG("Sent %" PRIu64 " bytes of metadata for stream %" PRIu64, len,
2143 (uint64_t) be64toh(request.stream_id));
2144
2145 DBG("Metadata sent");
2146
2147 end_free:
2148 free(data);
2149 end:
2150 if (vstream) {
2151 viewer_stream_put(vstream);
2152 }
2153 return ret;
2154 }
2155
2156 /*
2157 * Create a viewer session.
2158 *
2159 * Return 0 on success or else a negative value.
2160 */
2161 static
2162 int viewer_create_session(struct relay_connection *conn)
2163 {
2164 int ret;
2165 struct lttng_viewer_create_session_response resp;
2166
2167 DBG("Viewer create session received");
2168
2169 memset(&resp, 0, sizeof(resp));
2170 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_OK);
2171 conn->viewer_session = viewer_session_create();
2172 if (!conn->viewer_session) {
2173 ERR("Allocation viewer session");
2174 resp.status = htobe32(LTTNG_VIEWER_CREATE_SESSION_ERR);
2175 goto send_reply;
2176 }
2177
2178 send_reply:
2179 health_code_update();
2180 ret = send_response(conn->sock, &resp, sizeof(resp));
2181 if (ret < 0) {
2182 goto end;
2183 }
2184 health_code_update();
2185 ret = 0;
2186
2187 end:
2188 return ret;
2189 }
2190
2191 /*
2192 * Detach a viewer session.
2193 *
2194 * Return 0 on success or else a negative value.
2195 */
2196 static
2197 int viewer_detach_session(struct relay_connection *conn)
2198 {
2199 int ret;
2200 struct lttng_viewer_detach_session_response response;
2201 struct lttng_viewer_detach_session_request request;
2202 struct relay_session *session = NULL;
2203 uint64_t viewer_session_to_close;
2204
2205 DBG("Viewer detach session received");
2206
2207 assert(conn);
2208
2209 health_code_update();
2210
2211 /* Receive the request from the connected client. */
2212 ret = recv_request(conn->sock, &request, sizeof(request));
2213 if (ret < 0) {
2214 goto end;
2215 }
2216 viewer_session_to_close = be64toh(request.session_id);
2217
2218 if (!conn->viewer_session) {
2219 DBG("Client trying to detach before creating a live viewer session");
2220 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2221 goto send_reply;
2222 }
2223
2224 health_code_update();
2225
2226 memset(&response, 0, sizeof(response));
2227 DBG("Detaching from session ID %" PRIu64, viewer_session_to_close);
2228
2229 session = session_get_by_id(be64toh(request.session_id));
2230 if (!session) {
2231 DBG("Relay session %" PRIu64 " not found",
2232 (uint64_t) be64toh(request.session_id));
2233 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_UNK);
2234 goto send_reply;
2235 }
2236
2237 ret = viewer_session_is_attached(conn->viewer_session, session);
2238 if (ret != 1) {
2239 DBG("Not attached to this session");
2240 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_ERR);
2241 goto send_reply_put;
2242 }
2243
2244 viewer_session_close_one_session(conn->viewer_session, session);
2245 response.status = htobe32(LTTNG_VIEWER_DETACH_SESSION_OK);
2246 DBG("Session %" PRIu64 " detached.", viewer_session_to_close);
2247
2248 send_reply_put:
2249 session_put(session);
2250
2251 send_reply:
2252 health_code_update();
2253 ret = send_response(conn->sock, &response, sizeof(response));
2254 if (ret < 0) {
2255 goto end;
2256 }
2257 health_code_update();
2258 ret = 0;
2259
2260 end:
2261 return ret;
2262 }
2263
2264 /*
2265 * live_relay_unknown_command: send -1 if received unknown command
2266 */
2267 static
2268 void live_relay_unknown_command(struct relay_connection *conn)
2269 {
2270 struct lttcomm_relayd_generic_reply reply;
2271
2272 memset(&reply, 0, sizeof(reply));
2273 reply.ret_code = htobe32(LTTNG_ERR_UNK);
2274 (void) send_response(conn->sock, &reply, sizeof(reply));
2275 }
2276
2277 /*
2278 * Process the commands received on the control socket
2279 */
2280 static
2281 int process_control(struct lttng_viewer_cmd *recv_hdr,
2282 struct relay_connection *conn)
2283 {
2284 int ret = 0;
2285 uint32_t msg_value;
2286
2287 msg_value = be32toh(recv_hdr->cmd);
2288
2289 /*
2290 * Make sure we've done the version check before any command other then a
2291 * new client connection.
2292 */
2293 if (msg_value != LTTNG_VIEWER_CONNECT && !conn->version_check_done) {
2294 ERR("Viewer conn value %" PRIu32 " before version check", msg_value);
2295 ret = -1;
2296 goto end;
2297 }
2298
2299 switch (msg_value) {
2300 case LTTNG_VIEWER_CONNECT:
2301 ret = viewer_connect(conn);
2302 break;
2303 case LTTNG_VIEWER_LIST_SESSIONS:
2304 ret = viewer_list_sessions(conn);
2305 break;
2306 case LTTNG_VIEWER_ATTACH_SESSION:
2307 ret = viewer_attach_session(conn);
2308 break;
2309 case LTTNG_VIEWER_GET_NEXT_INDEX:
2310 ret = viewer_get_next_index(conn);
2311 break;
2312 case LTTNG_VIEWER_GET_PACKET:
2313 ret = viewer_get_packet(conn);
2314 break;
2315 case LTTNG_VIEWER_GET_METADATA:
2316 ret = viewer_get_metadata(conn);
2317 break;
2318 case LTTNG_VIEWER_GET_NEW_STREAMS:
2319 ret = viewer_get_new_streams(conn);
2320 break;
2321 case LTTNG_VIEWER_CREATE_SESSION:
2322 ret = viewer_create_session(conn);
2323 break;
2324 case LTTNG_VIEWER_DETACH_SESSION:
2325 ret = viewer_detach_session(conn);
2326 break;
2327 default:
2328 ERR("Received unknown viewer command (%u)",
2329 be32toh(recv_hdr->cmd));
2330 live_relay_unknown_command(conn);
2331 ret = -1;
2332 goto end;
2333 }
2334
2335 end:
2336 return ret;
2337 }
2338
2339 static
2340 void cleanup_connection_pollfd(struct lttng_poll_event *events, int pollfd)
2341 {
2342 int ret;
2343
2344 (void) lttng_poll_del(events, pollfd);
2345
2346 ret = fd_tracker_close_unsuspendable_fd(the_fd_tracker, &pollfd, 1,
2347 fd_tracker_util_close_fd, NULL);
2348 if (ret < 0) {
2349 ERR("Closing pollfd %d", pollfd);
2350 }
2351 }
2352
2353 /*
2354 * This thread does the actual work
2355 */
2356 static
2357 void *thread_worker(void *data)
2358 {
2359 int ret, err = -1;
2360 uint32_t nb_fd;
2361 struct lttng_poll_event events;
2362 struct lttng_ht *viewer_connections_ht;
2363 struct lttng_ht_iter iter;
2364 struct lttng_viewer_cmd recv_hdr;
2365 struct relay_connection *destroy_conn;
2366
2367 DBG("[thread] Live viewer relay worker started");
2368
2369 rcu_register_thread();
2370
2371 health_register(health_relayd, HEALTH_RELAYD_TYPE_LIVE_WORKER);
2372
2373 if (testpoint(relayd_thread_live_worker)) {
2374 goto error_testpoint;
2375 }
2376
2377 /* table of connections indexed on socket */
2378 viewer_connections_ht = lttng_ht_new(0, LTTNG_HT_TYPE_ULONG);
2379 if (!viewer_connections_ht) {
2380 goto viewer_connections_ht_error;
2381 }
2382
2383 ret = create_named_thread_poll_set(&events, 2,
2384 "Live viewer worker thread epoll");
2385 if (ret < 0) {
2386 goto error_poll_create;
2387 }
2388
2389 ret = lttng_poll_add(&events, live_conn_pipe[0], LPOLLIN | LPOLLRDHUP);
2390 if (ret < 0) {
2391 goto error;
2392 }
2393
2394 restart:
2395 while (1) {
2396 int i;
2397
2398 health_code_update();
2399
2400 /* Infinite blocking call, waiting for transmission */
2401 DBG3("Relayd live viewer worker thread polling...");
2402 health_poll_entry();
2403 ret = lttng_poll_wait(&events, -1);
2404 health_poll_exit();
2405 if (ret < 0) {
2406 /*
2407 * Restart interrupted system call.
2408 */
2409 if (errno == EINTR) {
2410 goto restart;
2411 }
2412 goto error;
2413 }
2414
2415 nb_fd = ret;
2416
2417 /*
2418 * Process control. The control connection is prioritised so we don't
2419 * starve it with high throughput tracing data on the data
2420 * connection.
2421 */
2422 for (i = 0; i < nb_fd; i++) {
2423 /* Fetch once the poll data */
2424 uint32_t revents = LTTNG_POLL_GETEV(&events, i);
2425 int pollfd = LTTNG_POLL_GETFD(&events, i);
2426
2427 health_code_update();
2428
2429 /* Thread quit pipe has been closed. Killing thread. */
2430 ret = check_thread_quit_pipe(pollfd, revents);
2431 if (ret) {
2432 err = 0;
2433 goto exit;
2434 }
2435
2436 /* Inspect the relay conn pipe for new connection. */
2437 if (pollfd == live_conn_pipe[0]) {
2438 if (revents & LPOLLIN) {
2439 struct relay_connection *conn;
2440
2441 ret = lttng_read(live_conn_pipe[0],
2442 &conn, sizeof(conn));
2443 if (ret < 0) {
2444 goto error;
2445 }
2446 ret = lttng_poll_add(&events,
2447 conn->sock->fd,
2448 LPOLLIN | LPOLLRDHUP);
2449 if (ret) {
2450 ERR("Failed to add new live connection file descriptor to poll set");
2451 goto error;
2452 }
2453 connection_ht_add(viewer_connections_ht, conn);
2454 DBG("Connection socket %d added to poll", conn->sock->fd);
2455 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2456 ERR("Relay live pipe error");
2457 goto error;
2458 } else {
2459 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2460 goto error;
2461 }
2462 } else {
2463 /* Connection activity. */
2464 struct relay_connection *conn;
2465
2466 conn = connection_get_by_sock(viewer_connections_ht, pollfd);
2467 if (!conn) {
2468 continue;
2469 }
2470
2471 if (revents & LPOLLIN) {
2472 ret = conn->sock->ops->recvmsg(conn->sock, &recv_hdr,
2473 sizeof(recv_hdr), 0);
2474 if (ret <= 0) {
2475 /* Connection closed. */
2476 cleanup_connection_pollfd(&events, pollfd);
2477 /* Put "create" ownership reference. */
2478 connection_put(conn);
2479 DBG("Viewer control conn closed with %d", pollfd);
2480 } else {
2481 ret = process_control(&recv_hdr, conn);
2482 if (ret < 0) {
2483 /* Clear the session on error. */
2484 cleanup_connection_pollfd(&events, pollfd);
2485 /* Put "create" ownership reference. */
2486 connection_put(conn);
2487 DBG("Viewer connection closed with %d", pollfd);
2488 }
2489 }
2490 } else if (revents & (LPOLLERR | LPOLLHUP | LPOLLRDHUP)) {
2491 cleanup_connection_pollfd(&events, pollfd);
2492 /* Put "create" ownership reference. */
2493 connection_put(conn);
2494 } else {
2495 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2496 connection_put(conn);
2497 goto error;
2498 }
2499 /* Put local "get_by_sock" reference. */
2500 connection_put(conn);
2501 }
2502 }
2503 }
2504
2505 exit:
2506 error:
2507 (void) fd_tracker_util_poll_clean(the_fd_tracker, &events);
2508
2509 /* Cleanup remaining connection object. */
2510 rcu_read_lock();
2511 cds_lfht_for_each_entry(viewer_connections_ht->ht, &iter.iter,
2512 destroy_conn,
2513 sock_n.node) {
2514 health_code_update();
2515 connection_put(destroy_conn);
2516 }
2517 rcu_read_unlock();
2518 error_poll_create:
2519 lttng_ht_destroy(viewer_connections_ht);
2520 viewer_connections_ht_error:
2521 /* Close relay conn pipes */
2522 (void) fd_tracker_util_pipe_close(the_fd_tracker, live_conn_pipe);
2523 if (err) {
2524 DBG("Viewer worker thread exited with error");
2525 }
2526 DBG("Viewer worker thread cleanup complete");
2527 error_testpoint:
2528 if (err) {
2529 health_error();
2530 ERR("Health error occurred in %s", __func__);
2531 }
2532 health_unregister(health_relayd);
2533 if (lttng_relay_stop_threads()) {
2534 ERR("Error stopping threads");
2535 }
2536 rcu_unregister_thread();
2537 return NULL;
2538 }
2539
2540 /*
2541 * Create the relay command pipe to wake thread_manage_apps.
2542 * Closed in cleanup().
2543 */
2544 static int create_conn_pipe(void)
2545 {
2546 return fd_tracker_util_pipe_open_cloexec(the_fd_tracker,
2547 "Live connection pipe", live_conn_pipe);
2548 }
2549
2550 int relayd_live_join(void)
2551 {
2552 int ret, retval = 0;
2553 void *status;
2554
2555 ret = pthread_join(live_listener_thread, &status);
2556 if (ret) {
2557 errno = ret;
2558 PERROR("pthread_join live listener");
2559 retval = -1;
2560 }
2561
2562 ret = pthread_join(live_worker_thread, &status);
2563 if (ret) {
2564 errno = ret;
2565 PERROR("pthread_join live worker");
2566 retval = -1;
2567 }
2568
2569 ret = pthread_join(live_dispatcher_thread, &status);
2570 if (ret) {
2571 errno = ret;
2572 PERROR("pthread_join live dispatcher");
2573 retval = -1;
2574 }
2575
2576 cleanup_relayd_live();
2577
2578 return retval;
2579 }
2580
2581 /*
2582 * main
2583 */
2584 int relayd_live_create(struct lttng_uri *uri)
2585 {
2586 int ret = 0, retval = 0;
2587 void *status;
2588 int is_root;
2589
2590 if (!uri) {
2591 retval = -1;
2592 goto exit_init_data;
2593 }
2594 live_uri = uri;
2595
2596 /* Check if daemon is UID = 0 */
2597 is_root = !getuid();
2598
2599 if (!is_root) {
2600 if (live_uri->port < 1024) {
2601 ERR("Need to be root to use ports < 1024");
2602 retval = -1;
2603 goto exit_init_data;
2604 }
2605 }
2606
2607 /* Setup the thread apps communication pipe. */
2608 if (create_conn_pipe()) {
2609 retval = -1;
2610 goto exit_init_data;
2611 }
2612
2613 /* Init relay command queue. */
2614 cds_wfcq_init(&viewer_conn_queue.head, &viewer_conn_queue.tail);
2615
2616 /* Set up max poll set size */
2617 if (lttng_poll_set_max_size()) {
2618 retval = -1;
2619 goto exit_init_data;
2620 }
2621
2622 /* Setup the dispatcher thread */
2623 ret = pthread_create(&live_dispatcher_thread, default_pthread_attr(),
2624 thread_dispatcher, (void *) NULL);
2625 if (ret) {
2626 errno = ret;
2627 PERROR("pthread_create viewer dispatcher");
2628 retval = -1;
2629 goto exit_dispatcher_thread;
2630 }
2631
2632 /* Setup the worker thread */
2633 ret = pthread_create(&live_worker_thread, default_pthread_attr(),
2634 thread_worker, NULL);
2635 if (ret) {
2636 errno = ret;
2637 PERROR("pthread_create viewer worker");
2638 retval = -1;
2639 goto exit_worker_thread;
2640 }
2641
2642 /* Setup the listener thread */
2643 ret = pthread_create(&live_listener_thread, default_pthread_attr(),
2644 thread_listener, (void *) NULL);
2645 if (ret) {
2646 errno = ret;
2647 PERROR("pthread_create viewer listener");
2648 retval = -1;
2649 goto exit_listener_thread;
2650 }
2651
2652 /*
2653 * All OK, started all threads.
2654 */
2655 return retval;
2656
2657 /*
2658 * Join on the live_listener_thread should anything be added after
2659 * the live_listener thread's creation.
2660 */
2661
2662 exit_listener_thread:
2663
2664 ret = pthread_join(live_worker_thread, &status);
2665 if (ret) {
2666 errno = ret;
2667 PERROR("pthread_join live worker");
2668 retval = -1;
2669 }
2670 exit_worker_thread:
2671
2672 ret = pthread_join(live_dispatcher_thread, &status);
2673 if (ret) {
2674 errno = ret;
2675 PERROR("pthread_join live dispatcher");
2676 retval = -1;
2677 }
2678 exit_dispatcher_thread:
2679
2680 exit_init_data:
2681 cleanup_relayd_live();
2682
2683 return retval;
2684 }
This page took 0.162163 seconds and 3 git commands to generate.