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