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