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