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