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