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